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
b751186e072b41eaa4a4d57ebaa6fe20be4b4161
[ "obj = self.objects[0]\nurl = reverse(self.delete_url, args=(obj.id,))\nresponse = self.client.delete(url)\nself.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\nself.assertIn('detail', response.data)\nself.assertEqual(response.data['detail'], STR_401_MESSAGE)", "user = self.template_users['staff_...
<|body_start_0|> obj = self.objects[0] url = reverse(self.delete_url, args=(obj.id,)) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertIn('detail', response.data) self.assertEqual(response.data['detail'], S...
BasicDeleteApiTestCaseRunMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicDeleteApiTestCaseRunMixin: def test_delete_anonymous(self): """Anonymous user should NOT be able to delete""" <|body_0|> def test_delete_staff_user(self): """Staff user should be able to delete EVERY object""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_028900
9,174
permissive
[ { "docstring": "Anonymous user should NOT be able to delete", "name": "test_delete_anonymous", "signature": "def test_delete_anonymous(self)" }, { "docstring": "Staff user should be able to delete EVERY object", "name": "test_delete_staff_user", "signature": "def test_delete_staff_user(s...
2
null
Implement the Python class `BasicDeleteApiTestCaseRunMixin` described below. Class description: Implement the BasicDeleteApiTestCaseRunMixin class. Method signatures and docstrings: - def test_delete_anonymous(self): Anonymous user should NOT be able to delete - def test_delete_staff_user(self): Staff user should be ...
Implement the Python class `BasicDeleteApiTestCaseRunMixin` described below. Class description: Implement the BasicDeleteApiTestCaseRunMixin class. Method signatures and docstrings: - def test_delete_anonymous(self): Anonymous user should NOT be able to delete - def test_delete_staff_user(self): Staff user should be ...
9baa530f2f3405322f74ccc145641148f253341b
<|skeleton|> class BasicDeleteApiTestCaseRunMixin: def test_delete_anonymous(self): """Anonymous user should NOT be able to delete""" <|body_0|> def test_delete_staff_user(self): """Staff user should be able to delete EVERY object""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasicDeleteApiTestCaseRunMixin: def test_delete_anonymous(self): """Anonymous user should NOT be able to delete""" obj = self.objects[0] url = reverse(self.delete_url, args=(obj.id,)) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_...
the_stack_v2_python_sparse
palvelutori/test_mixins.py
City-of-Turku/munpalvelut_backend
train
0
44c9cb6d316399125028abf41b5208fe96cc1066
[ "dire = os.listdir('E:\\\\PythonProject\\\\doctor\\\\problem')\nfor d in dire:\n name = d.split('.')[0]\n print(name)\n file = os.path.join('E:/PythonProject/doctor/problem/', d)\n fr = open(file, 'r', encoding='utf-8')\n fr_iter = iter(fr)\n for data in fr_iter:\n res = mongodb_tool.DB('pr...
<|body_start_0|> dire = os.listdir('E:\\PythonProject\\doctor\\problem') for d in dire: name = d.split('.')[0] print(name) file = os.path.join('E:/PythonProject/doctor/problem/', d) fr = open(file, 'r', encoding='utf-8') fr_iter = iter(fr) ...
DBOperation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBOperation: def save_problems(self): """将获取到的问题url相关信息保存到数据库 :return:""" <|body_0|> def save_dialog(self): """将获取到的问题url相关信息保存到数据库 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> dire = os.listdir('E:\\PythonProject\\doctor\\problem') ...
stack_v2_sparse_classes_36k_train_028901
2,704
permissive
[ { "docstring": "将获取到的问题url相关信息保存到数据库 :return:", "name": "save_problems", "signature": "def save_problems(self)" }, { "docstring": "将获取到的问题url相关信息保存到数据库 :return:", "name": "save_dialog", "signature": "def save_dialog(self)" } ]
2
stack_v2_sparse_classes_30k_train_008251
Implement the Python class `DBOperation` described below. Class description: Implement the DBOperation class. Method signatures and docstrings: - def save_problems(self): 将获取到的问题url相关信息保存到数据库 :return: - def save_dialog(self): 将获取到的问题url相关信息保存到数据库 :return:
Implement the Python class `DBOperation` described below. Class description: Implement the DBOperation class. Method signatures and docstrings: - def save_problems(self): 将获取到的问题url相关信息保存到数据库 :return: - def save_dialog(self): 将获取到的问题url相关信息保存到数据库 :return: <|skeleton|> class DBOperation: def save_problems(self):...
8b80bae35598d932f795f354cf11bd401831e008
<|skeleton|> class DBOperation: def save_problems(self): """将获取到的问题url相关信息保存到数据库 :return:""" <|body_0|> def save_dialog(self): """将获取到的问题url相关信息保存到数据库 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DBOperation: def save_problems(self): """将获取到的问题url相关信息保存到数据库 :return:""" dire = os.listdir('E:\\PythonProject\\doctor\\problem') for d in dire: name = d.split('.')[0] print(name) file = os.path.join('E:/PythonProject/doctor/problem/', d) ...
the_stack_v2_python_sparse
src/db_operation.py
anlinew/doctor
train
0
4829de30ea0dc00650aac0d42f868ebdf300f416
[ "self._parameters = parameters\nself._mapper = OCPGCPProviderMap(provider=self.provider, report_type=parameters.report_type)\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabled': True})\nsuper().__init__(parameters)", "filter_map = deepcopy(TagQueryHandler.FILTER_MAP)\nif self._pa...
<|body_start_0|> self._parameters = parameters self._mapper = OCPGCPProviderMap(provider=self.provider, report_type=parameters.report_type) if parameters.get_filter('enabled') is None: parameters.set_filter(**{'enabled': True}) super().__init__(parameters) <|end_body_0|> <|b...
Handles tag queries and responses for OCP-on-GCP.
OCPGCPTagQueryHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" <|body_0|> def filter_map(self): """Establish w...
stack_v2_sparse_classes_36k_train_028902
3,966
permissive
[ { "docstring": "Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query", "name": "__init__", "signature": "def __init__(self, parameters)" }, { "docstring": "Establish which filter map to use based on tag API.", "name": "filter_map", "signature...
2
null
Implement the Python class `OCPGCPTagQueryHandler` described below. Class description: Handles tag queries and responses for OCP-on-GCP. Method signatures and docstrings: - def __init__(self, parameters): Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query - def filter_m...
Implement the Python class `OCPGCPTagQueryHandler` described below. Class description: Handles tag queries and responses for OCP-on-GCP. Method signatures and docstrings: - def __init__(self, parameters): Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query - def filter_m...
0416e5216eb1ec4b41c8dd4999adde218b1ab2e1
<|skeleton|> class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" <|body_0|> def filter_map(self): """Establish w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" self._parameters = parameters self._mapper = OCPGCPProviderMap(pr...
the_stack_v2_python_sparse
koku/api/tags/gcp/openshift/queries.py
project-koku/koku
train
225
1a46db908b47d7c6395d88b40c228d52ec521b2d
[ "kw = super(ProjectEventView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw", "context = super(ProjectEventView, self).get_context_data(**kwargs)\nproject = get_object_or_404(Project, id=self.kwargs['pk'])\nevents = project.event_set.all()\nreporting_ct = project....
<|body_start_0|> kw = super(ProjectEventView, self).get_form_kwargs() kw.update({'organization': self.request.user.organization}) return kw <|end_body_0|> <|body_start_1|> context = super(ProjectEventView, self).get_context_data(**kwargs) project = get_object_or_404(Project, id=...
Display all the events associated with a project.
ProjectEventView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" <|body_0|> def get_context_data(self, **kwargs): """Return events belonging to the project.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k_train_028903
12,378
permissive
[ { "docstring": "Pass organization to form.", "name": "get_form_kwargs", "signature": "def get_form_kwargs(self)" }, { "docstring": "Return events belonging to the project.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ]
2
null
Implement the Python class `ProjectEventView` described below. Class description: Display all the events associated with a project. Method signatures and docstrings: - def get_form_kwargs(self): Pass organization to form. - def get_context_data(self, **kwargs): Return events belonging to the project.
Implement the Python class `ProjectEventView` described below. Class description: Display all the events associated with a project. Method signatures and docstrings: - def get_form_kwargs(self): Pass organization to form. - def get_context_data(self, **kwargs): Return events belonging to the project. <|skeleton|> cl...
dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9
<|skeleton|> class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" <|body_0|> def get_context_data(self, **kwargs): """Return events belonging to the project.""" <|body_1|> <|end_skeleton...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectEventView: """Display all the events associated with a project.""" def get_form_kwargs(self): """Pass organization to form.""" kw = super(ProjectEventView, self).get_form_kwargs() kw.update({'organization': self.request.user.organization}) return kw def get_con...
the_stack_v2_python_sparse
project/editorial/views/events.py
ProjectFacet/facet
train
25
5d9f5c27ef0f9d544442a5badcfeb063303af604
[ "mins = total_data() / 60\nhours = mins / 60\nnum_sources = len(amounts_recorded_by_device())\naverage_mins = mins / num_sources\naverage_hours = hours / num_sources\nreport = f'{hours:0.1f} hours total across {num_sources} sources - {average_hours:0.1f} hours (or {average_mins:0.0f}) mins per source on average.'\n...
<|body_start_0|> mins = total_data() / 60 hours = mins / 60 num_sources = len(amounts_recorded_by_device()) average_mins = mins / num_sources average_hours = hours / num_sources report = f'{hours:0.1f} hours total across {num_sources} sources - {average_hours:0.1f} hours ...
NoiseActions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NoiseActions: def report_noise_recorded() -> None: """Pop a notification showing the total amount of noise recorded.""" <|body_0|> def delete_last_noise_recording() -> None: """Delete the previous recording session (across all devices).""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k_train_028904
20,408
permissive
[ { "docstring": "Pop a notification showing the total amount of noise recorded.", "name": "report_noise_recorded", "signature": "def report_noise_recorded() -> None" }, { "docstring": "Delete the previous recording session (across all devices).", "name": "delete_last_noise_recording", "si...
2
null
Implement the Python class `NoiseActions` described below. Class description: Implement the NoiseActions class. Method signatures and docstrings: - def report_noise_recorded() -> None: Pop a notification showing the total amount of noise recorded. - def delete_last_noise_recording() -> None: Delete the previous recor...
Implement the Python class `NoiseActions` described below. Class description: Implement the NoiseActions class. Method signatures and docstrings: - def report_noise_recorded() -> None: Pop a notification showing the total amount of noise recorded. - def delete_last_noise_recording() -> None: Delete the previous recor...
b5c1ec10207a66a04226abe865d694e3786dc30d
<|skeleton|> class NoiseActions: def report_noise_recorded() -> None: """Pop a notification showing the total amount of noise recorded.""" <|body_0|> def delete_last_noise_recording() -> None: """Delete the previous recording session (across all devices).""" <|body_1|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NoiseActions: def report_noise_recorded() -> None: """Pop a notification showing the total amount of noise recorded.""" mins = total_data() / 60 hours = mins / 60 num_sources = len(amounts_recorded_by_device()) average_mins = mins / num_sources average_hours = h...
the_stack_v2_python_sparse
plugins/noise_recorder/noise_recorder.py
jcaw/talon_config
train
12
c7a23fe578d6324487fb8acf5987f047011d93d5
[ "from collections import defaultdict\nself.prefix_tr = defaultdict(set)\nself.suffix_tr = defaultdict(set)\nself.weights = {}\nfor weight, word in enumerate(words):\n pref = ''\n suff = ''\n for ch in [''] + list(word):\n pref += ch\n self.prefix_tr[pref].add(word)\n for ch in [''] + list(...
<|body_start_0|> from collections import defaultdict self.prefix_tr = defaultdict(set) self.suffix_tr = defaultdict(set) self.weights = {} for weight, word in enumerate(words): pref = '' suff = '' for ch in [''] + list(word): pr...
WordFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> from collections import defaultdict ...
stack_v2_sparse_classes_36k_train_028905
2,506
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type prefix: str :type suffix: str :rtype: int", "name": "f", "signature": "def f(self, prefix, suffix)" } ]
2
null
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
Implement the Python class `WordFilter` described below. Class description: Implement the WordFilter class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int <|skeleton|> class WordFilter: def __in...
df2ce669049ca040631dc6cc05cf5b5e8d2cc376
<|skeleton|> class WordFilter: def __init__(self, words): """:type words: List[str]""" <|body_0|> def f(self, prefix, suffix): """:type prefix: str :type suffix: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordFilter: def __init__(self, words): """:type words: List[str]""" from collections import defaultdict self.prefix_tr = defaultdict(set) self.suffix_tr = defaultdict(set) self.weights = {} for weight, word in enumerate(words): pref = '' ...
the_stack_v2_python_sparse
leetcode_2018/745_prefix_suffix_search.py
changediyasunny/Challenges
train
0
3fc57d7f38e15f2167074d376a1994f891df3d72
[ "self.term = TerminalController()\nif not hasattr(self, 'message_prefix'):\n self.message_prefix = 'Suitcase Error:'\nself.message = '%s %s' % (self.message_prefix, value)", "try:\n return self.term.render('${RED}%s${NORMAL}' % self.message)\nexcept ValueError:\n return self.message" ]
<|body_start_0|> self.term = TerminalController() if not hasattr(self, 'message_prefix'): self.message_prefix = 'Suitcase Error:' self.message = '%s %s' % (self.message_prefix, value) <|end_body_0|> <|body_start_1|> try: return self.term.render('${RED}%s${NORMAL}...
The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor!
SuitcaseException
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuitcaseException: """The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor!""" def __init__(self, value=''): """Set's the message on instantiation""" <|body_0|> def __str__(self): """Return...
stack_v2_sparse_classes_36k_train_028906
2,701
permissive
[ { "docstring": "Set's the message on instantiation", "name": "__init__", "signature": "def __init__(self, value='')" }, { "docstring": "Returns the error message", "name": "__str__", "signature": "def __str__(self)" } ]
2
stack_v2_sparse_classes_30k_val_000076
Implement the Python class `SuitcaseException` described below. Class description: The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor! Method signatures and docstrings: - def __init__(self, value=''): Set's the message on instantiation - def ...
Implement the Python class `SuitcaseException` described below. Class description: The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor! Method signatures and docstrings: - def __init__(self, value=''): Set's the message on instantiation - def ...
2a0eb274ffccd3692ba4659cbb0010d0725f2b20
<|skeleton|> class SuitcaseException: """The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor!""" def __init__(self, value=''): """Set's the message on instantiation""" <|body_0|> def __str__(self): """Return...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SuitcaseException: """The generic suitcase exception class This exception is raised when your suitcase falls open and spills everything on the floor!""" def __init__(self, value=''): """Set's the message on instantiation""" self.term = TerminalController() if not hasattr(self, 'me...
the_stack_v2_python_sparse
suitcase/exceptions.py
brosner/suitcaseproject
train
0
afcf4094b8bc6cc883ff27e95c3d60484828c11a
[ "if self.game_id[0:2] == NBA_GAME_ID_PREFIX:\n return NBA_STRING\nelif self.game_id[0:2] == G_LEAGUE_GAME_ID_PREFIX:\n return D_LEAGUE_STRING\nelif self.game_id[0:2] == WNBA_GAME_ID_PREFIX:\n return WNBA_STRING", "if self.game_id[3] == '9':\n return '19' + self.game_id[3] + self.game_id[4]\nelse:\n ...
<|body_start_0|> if self.game_id[0:2] == NBA_GAME_ID_PREFIX: return NBA_STRING elif self.game_id[0:2] == G_LEAGUE_GAME_ID_PREFIX: return D_LEAGUE_STRING elif self.game_id[0:2] == WNBA_GAME_ID_PREFIX: return WNBA_STRING <|end_body_0|> <|body_start_1|> ...
Base Class for all data.nba.com data loaders This class should not be instantiated directly
DataNbaLoaderBase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" <|body_0|> def season(s...
stack_v2_sparse_classes_36k_train_028907
1,242
permissive
[ { "docstring": "Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league", "name": "league", "signature": "def league(self)" }, { "docstring": "Returns year in which season starts for game id 4th and 5th characters in game id represent season yea...
2
stack_v2_sparse_classes_30k_train_017103
Implement the Python class `DataNbaLoaderBase` described below. Class description: Base Class for all data.nba.com data loaders This class should not be instantiated directly Method signatures and docstrings: - def league(self): Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba...
Implement the Python class `DataNbaLoaderBase` described below. Class description: Base Class for all data.nba.com data loaders This class should not be instantiated directly Method signatures and docstrings: - def league(self): Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba...
38d5d75be50a478dbe718700c880e48020ffa123
<|skeleton|> class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" <|body_0|> def season(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" if self.game_id[0:2] == NBA_GAME_ID_PREFI...
the_stack_v2_python_sparse
pbpstats/data_loader/data_nba/base.py
dblackrun/pbpstats
train
73
21b87cce745175b9186c1543337c506e8a41fbf4
[ "self.method = method\nself.options = options\nself.keep_value_history = self.options.pop('keep_value_history', False)", "history = []\nif self.method == 'SPSA':\n optimizer = SPSA(**self.options)\nelif self.method == 'ADAM' or self.method == 'AMSGRAD':\n if self.method == 'AMSGRAD':\n self.options['...
<|body_start_0|> self.method = method self.options = options self.keep_value_history = self.options.pop('keep_value_history', False) <|end_body_0|> <|body_start_1|> history = [] if self.method == 'SPSA': optimizer = SPSA(**self.options) elif self.method == 'A...
QiskitOptimizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QiskitOptimizer: def __init__(self, method, options={}): """Args: method(str): specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". options(dict): dictionary with additional options for the optimizer. Supported values for the options dictionary: Options: keep_...
stack_v2_sparse_classes_36k_train_028908
3,055
permissive
[ { "docstring": "Args: method(str): specifies optimizer to be used. Currently supports \"ADAM\", \"AMSGRAD\" and \"SPSA\". options(dict): dictionary with additional options for the optimizer. Supported values for the options dictionary: Options: keep_value_history(bool): boolean flag indicating whether the histo...
2
stack_v2_sparse_classes_30k_train_003953
Implement the Python class `QiskitOptimizer` described below. Class description: Implement the QiskitOptimizer class. Method signatures and docstrings: - def __init__(self, method, options={}): Args: method(str): specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". options(dict): dictionar...
Implement the Python class `QiskitOptimizer` described below. Class description: Implement the QiskitOptimizer class. Method signatures and docstrings: - def __init__(self, method, options={}): Args: method(str): specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". options(dict): dictionar...
35e0ee6b151edb1ec910605f25b2f3f81551f145
<|skeleton|> class QiskitOptimizer: def __init__(self, method, options={}): """Args: method(str): specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". options(dict): dictionary with additional options for the optimizer. Supported values for the options dictionary: Options: keep_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QiskitOptimizer: def __init__(self, method, options={}): """Args: method(str): specifies optimizer to be used. Currently supports "ADAM", "AMSGRAD" and "SPSA". options(dict): dictionary with additional options for the optimizer. Supported values for the options dictionary: Options: keep_value_history(...
the_stack_v2_python_sparse
src/python/qeqiskit/optimizer/optimizer.py
00mjk/qe-qiskit
train
0
73de1e00994d2d2bc453b2ff99df3e3320abdd7d
[ "csv = pd.read_csv(StringIO(conda_output), sep='\\\\s+', engine='python', header=None, comment='#', names=[NAME_COLUMN_NAME, VERSION_COLUMN_NAME, BUILD_COLUMN_NAME, CHANNEL_COLUMN_NAME])\nlogging.debug(csv)\npackage_list: List[PackageEntry] = []\nfor index, row in csv.iterrows():\n package = PackageEntry(name=ro...
<|body_start_0|> csv = pd.read_csv(StringIO(conda_output), sep='\\s+', engine='python', header=None, comment='#', names=[NAME_COLUMN_NAME, VERSION_COLUMN_NAME, BUILD_COLUMN_NAME, CHANNEL_COLUMN_NAME]) logging.debug(csv) package_list: List[PackageEntry] = [] for index, row in csv.iterrows...
Helper class for parsing conda output
CondaParser
[ "CC-BY-4.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CondaParser: """Helper class for parsing conda output""" def _parse_package_list(conda_output: str=None) -> List[PackageEntry]: """parses the conda output into a list""" <|body_0|> def get_package_list_from_conda() -> List[PackageEntry]: """calls conda and obtain...
stack_v2_sparse_classes_36k_train_028909
13,859
permissive
[ { "docstring": "parses the conda output into a list", "name": "_parse_package_list", "signature": "def _parse_package_list(conda_output: str=None) -> List[PackageEntry]" }, { "docstring": "calls conda and obtains a list of packages", "name": "get_package_list_from_conda", "signature": "d...
2
stack_v2_sparse_classes_30k_train_016392
Implement the Python class `CondaParser` described below. Class description: Helper class for parsing conda output Method signatures and docstrings: - def _parse_package_list(conda_output: str=None) -> List[PackageEntry]: parses the conda output into a list - def get_package_list_from_conda() -> List[PackageEntry]: c...
Implement the Python class `CondaParser` described below. Class description: Helper class for parsing conda output Method signatures and docstrings: - def _parse_package_list(conda_output: str=None) -> List[PackageEntry]: parses the conda output into a list - def get_package_list_from_conda() -> List[PackageEntry]: c...
9eb6d1c44e63e43e62bbf6983b2e618fb6ad02cc
<|skeleton|> class CondaParser: """Helper class for parsing conda output""" def _parse_package_list(conda_output: str=None) -> List[PackageEntry]: """parses the conda output into a list""" <|body_0|> def get_package_list_from_conda() -> List[PackageEntry]: """calls conda and obtain...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CondaParser: """Helper class for parsing conda output""" def _parse_package_list(conda_output: str=None) -> List[PackageEntry]: """parses the conda output into a list""" csv = pd.read_csv(StringIO(conda_output), sep='\\s+', engine='python', header=None, comment='#', names=[NAME_COLUMN_NAM...
the_stack_v2_python_sparse
tools/utils/generate_license_list.py
foxBMS/foxbms-2
train
151
9a68a1ca0ec2f5b2835308b491c99e9c0ef11cbb
[ "self.dataset = dataset\noptions_dict = options_dict or {}\nregions = [str(r) for r in regions] if regions else []\nsubcommand = 'view'\nsubproc_args = self.build_command_list(subcommand, options_string, options_dict, regions)\nsubproc_provider = external.SubprocessDataProvider(*subproc_args)\nsuper(SamtoolsDataPro...
<|body_start_0|> self.dataset = dataset options_dict = options_dict or {} regions = [str(r) for r in regions] if regions else [] subcommand = 'view' subproc_args = self.build_command_list(subcommand, options_string, options_dict, regions) subproc_provider = external.Subpr...
Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented.
SamtoolsDataProvider
[ "CC-BY-2.5", "AFL-2.1", "AFL-3.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SamtoolsDataProvider: """Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented.""" def __init__(self, dataset, options_string=...
stack_v2_sparse_classes_36k_train_028910
31,152
permissive
[ { "docstring": ":param options_string: samtools options in string form (flags separated by spaces) Optional: defaults to '' :type options_string: str :param options_dict: dictionary of samtools options Optional: defaults to None :type options_dict: dict or None :param regions: list of samtools regions strings O...
4
stack_v2_sparse_classes_30k_test_001173
Implement the Python class `SamtoolsDataProvider` described below. Class description: Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented. Method sign...
Implement the Python class `SamtoolsDataProvider` described below. Class description: Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented. Method sign...
d194520fdfe08e48c0b3d0d2299cd2adcb8f5952
<|skeleton|> class SamtoolsDataProvider: """Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented.""" def __init__(self, dataset, options_string=...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SamtoolsDataProvider: """Data provider that uses samtools on a Sam or Bam file as its source. This can be piped through other providers (column, map, genome region, etc.). .. note:: that only the samtools 'view' command is currently implemented.""" def __init__(self, dataset, options_string='', options_d...
the_stack_v2_python_sparse
lib/galaxy/datatypes/dataproviders/dataset.py
bwlang/galaxy
train
0
d67773b3bfa7605466627e7d5a95768a75963df9
[ "mock_test_file = 'scale_mock_test'\n_GenerateTestFlags(NUM_FLAGS, FLAG_RANGES, mock_test_file)\nreturn flags.ReadConf(mock_test_file)", "Task.InitLogCommand(None, None, 'output')\nspecs = self._GenerateFlagSpecifications()\ngeneration_tasks = _GenerateAllFlagsTasks(specs)\ngenerations = [HillClimbingBestBranch(g...
<|body_start_0|> mock_test_file = 'scale_mock_test' _GenerateTestFlags(NUM_FLAGS, FLAG_RANGES, mock_test_file) return flags.ReadConf(mock_test_file) <|end_body_0|> <|body_start_1|> Task.InitLogCommand(None, None, 'output') specs = self._GenerateFlagSpecifications() gener...
This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the computation of the fitness function from the build and test phases by letting the user defi...
MockAlgorithmsTest
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MockAlgorithmsTest: """This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the computation of the fitness function from the ...
stack_v2_sparse_classes_36k_train_028911
14,584
permissive
[ { "docstring": "Generate the testing specifications.", "name": "_GenerateFlagSpecifications", "signature": "def _GenerateFlagSpecifications(self)" }, { "docstring": "Test the best hill climb algorithm. Test whether it finds the best results as expected.", "name": "testBestHillClimb", "si...
4
null
Implement the Python class `MockAlgorithmsTest` described below. Class description: This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the comput...
Implement the Python class `MockAlgorithmsTest` described below. Class description: This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the comput...
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
<|skeleton|> class MockAlgorithmsTest: """This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the computation of the fitness function from the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MockAlgorithmsTest: """This class mock tests different steering algorithms. The steering algorithms are responsible for generating the next set of tasks to run in each iteration. This class does a functional testing on the algorithms. It mocks out the computation of the fitness function from the build and tes...
the_stack_v2_python_sparse
app/src/main/java/com/syd/source/aosp/external/toolchain-utils/bestflags/testing_batch.py
lz-purple/Source
train
4
1b78c7d9d8a926db4786577ea8ebd650eecd1d3c
[ "super(LandmarkGeneratorMask, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)\nself.output_size_np = list(reversed(self.output_size))\nself.ones_if_every_point_is_invalid = ones_if_every_point_is_invalid", "flip = self.is_flipped(transf...
<|body_start_0|> super(LandmarkGeneratorMask, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation) self.output_size_np = list(reversed(self.output_size)) self.ones_if_every_point_is_invalid = ones_if_every_point_is_invalid ...
Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks
LandmarkGeneratorMask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LandmarkGeneratorMask: """Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks""" def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post...
stack_v2_sparse_classes_36k_train_028912
16,690
no_license
[ { "docstring": "Initializer :param output_size: output image size :param ones_if_every_point_is_invalid: if True, create ones mask, if every point is invalid otherwise, create zeros mask, if every point is invalid :param landmark_indizes: list of landmark indizes that will be used for generating the output :par...
2
stack_v2_sparse_classes_30k_train_003667
Implement the Python class `LandmarkGeneratorMask` described below. Class description: Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks Method signatures and docstrings: - def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pai...
Implement the Python class `LandmarkGeneratorMask` described below. Class description: Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks Method signatures and docstrings: - def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pai...
ef6cee91264ba1fe6b40d9823a07647b95bcc2c4
<|skeleton|> class LandmarkGeneratorMask: """Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks""" def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LandmarkGeneratorMask: """Generates images filled with 1 for valid landmarks, and 0 for invalid landmarks""" def __init__(self, dim, output_size, ones_if_every_point_is_invalid=False, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformati...
the_stack_v2_python_sparse
generators/landmark_generator.py
XiaoweiXu/MedicalDataAugmentationTool
train
1
bfb8d903741c1349101d5ec64be90dba1dc21b61
[ "self.user = user\nself.server = server\nself.pub_key = pub_key_path\nself.kernel_id = kernel_info_path\nself.kernel_data = None\nself.kernel_name = None\ntry:\n self.connection = sh.ssh.bake('%s@%s' % (self.user, self.server))\nexcept:\n raise", "self.kernel_data = json.loads(str(self.connection('cat %s' %...
<|body_start_0|> self.user = user self.server = server self.pub_key = pub_key_path self.kernel_id = kernel_info_path self.kernel_data = None self.kernel_name = None try: self.connection = sh.ssh.bake('%s@%s' % (self.user, self.server)) except: ...
Manages doing stuff on the remote machine through ssh.
RemoteMachine
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoteMachine: """Manages doing stuff on the remote machine through ssh.""" def __init__(self, user, server, kernel_info_path, pub_key_path=None): """:param user: :param server: :param pub_key_path: :return:""" <|body_0|> def get_kernel_info(self): """Retrieves r...
stack_v2_sparse_classes_36k_train_028913
3,519
permissive
[ { "docstring": ":param user: :param server: :param pub_key_path: :return:", "name": "__init__", "signature": "def __init__(self, user, server, kernel_info_path, pub_key_path=None)" }, { "docstring": "Retrieves remote kernel info. :return:", "name": "get_kernel_info", "signature": "def ge...
4
stack_v2_sparse_classes_30k_train_007734
Implement the Python class `RemoteMachine` described below. Class description: Manages doing stuff on the remote machine through ssh. Method signatures and docstrings: - def __init__(self, user, server, kernel_info_path, pub_key_path=None): :param user: :param server: :param pub_key_path: :return: - def get_kernel_in...
Implement the Python class `RemoteMachine` described below. Class description: Manages doing stuff on the remote machine through ssh. Method signatures and docstrings: - def __init__(self, user, server, kernel_info_path, pub_key_path=None): :param user: :param server: :param pub_key_path: :return: - def get_kernel_in...
cb0cc345aaf66602752f57e48e93bb92d69e7dc5
<|skeleton|> class RemoteMachine: """Manages doing stuff on the remote machine through ssh.""" def __init__(self, user, server, kernel_info_path, pub_key_path=None): """:param user: :param server: :param pub_key_path: :return:""" <|body_0|> def get_kernel_info(self): """Retrieves r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RemoteMachine: """Manages doing stuff on the remote machine through ssh.""" def __init__(self, user, server, kernel_info_path, pub_key_path=None): """:param user: :param server: :param pub_key_path: :return:""" self.user = user self.server = server self.pub_key = pub_key_p...
the_stack_v2_python_sparse
src/spartan/scripts/connect_to_ipy_kernel.py
xguse/spartan
train
1
4ac5df82d902d026ff4d7c73eb49f1d6d4d51d99
[ "referral = self.context['referral']\nif referral.status != CompanyReferral.Status.OUTSTANDING:\n raise serializers.ValidationError(self.error_messages['invalid_status'])\nreturn super().validate(data)", "referral = self.context['referral']\nuser = self.context['user']\ninteraction = super().save(created_by=us...
<|body_start_0|> referral = self.context['referral'] if referral.status != CompanyReferral.Status.OUTSTANDING: raise serializers.ValidationError(self.error_messages['invalid_status']) return super().validate(data) <|end_body_0|> <|body_start_1|> referral = self.context['refe...
Serialiser for the complete a referral view.
CompleteCompanyReferralSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompleteCompanyReferralSerializer: """Serialiser for the complete a referral view.""" def validate(self, data): """Validate provided data. Checks that the referral has the expected status.""" <|body_0|> def save(self): """Create an interaction and update the refe...
stack_v2_sparse_classes_36k_train_028914
2,478
permissive
[ { "docstring": "Validate provided data. Checks that the referral has the expected status.", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Create an interaction and update the referral object.", "name": "save", "signature": "def save(self)" } ]
2
stack_v2_sparse_classes_30k_train_004605
Implement the Python class `CompleteCompanyReferralSerializer` described below. Class description: Serialiser for the complete a referral view. Method signatures and docstrings: - def validate(self, data): Validate provided data. Checks that the referral has the expected status. - def save(self): Create an interactio...
Implement the Python class `CompleteCompanyReferralSerializer` described below. Class description: Serialiser for the complete a referral view. Method signatures and docstrings: - def validate(self, data): Validate provided data. Checks that the referral has the expected status. - def save(self): Create an interactio...
a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e
<|skeleton|> class CompleteCompanyReferralSerializer: """Serialiser for the complete a referral view.""" def validate(self, data): """Validate provided data. Checks that the referral has the expected status.""" <|body_0|> def save(self): """Create an interaction and update the refe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompleteCompanyReferralSerializer: """Serialiser for the complete a referral view.""" def validate(self, data): """Validate provided data. Checks that the referral has the expected status.""" referral = self.context['referral'] if referral.status != CompanyReferral.Status.OUTSTAND...
the_stack_v2_python_sparse
datahub/company_referral/serializers.py
cgsunkel/data-hub-api
train
0
b178ab9e7b6f06b0b0226e6d8068ad093f9c3f89
[ "left, right = (0, len(nums) - 1)\nwhile left < right:\n mid = left + (right - left) // 2\n if mid % 2 == 0:\n if nums[mid] == nums[mid + 1]:\n left = mid + 1\n else:\n right = mid\n elif nums[mid - 1] == nums[mid]:\n left = mid + 1\n else:\n right = mid...
<|body_start_0|> left, right = (0, len(nums) - 1) while left < right: mid = left + (right - left) // 2 if mid % 2 == 0: if nums[mid] == nums[mid + 1]: left = mid + 1 else: right = mid elif nums[mi...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNonDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNonDuplicateDetail(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> left, right = (0, len(num...
stack_v2_sparse_classes_36k_train_028915
1,908
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNonDuplicate", "signature": "def singleNonDuplicate(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNonDuplicateDetail", "signature": "def singleNonDuplicateDetail(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNonDuplicate(self, nums): :type nums: List[int] :rtype: int - def singleNonDuplicateDetail(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNonDuplicate(self, nums): :type nums: List[int] :rtype: int - def singleNonDuplicateDetail(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: ...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def singleNonDuplicate(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNonDuplicateDetail(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def singleNonDuplicate(self, nums): """:type nums: List[int] :rtype: int""" left, right = (0, len(nums) - 1) while left < right: mid = left + (right - left) // 2 if mid % 2 == 0: if nums[mid] == nums[mid + 1]: left =...
the_stack_v2_python_sparse
cs_notes/binary_search/single_element_in_a_sorted_array.py
hwc1824/LeetCodeSolution
train
0
dbbf5d183f25689802b0dad86796eca5b1bca4bd
[ "self.count = count\nself.environment = environment\nself.size = size", "if dictionary is None:\n return None\ncount = dictionary.get('count')\nenvironment = dictionary.get('environment')\nsize = dictionary.get('size')\nreturn cls(count, environment, size)" ]
<|body_start_0|> self.count = count self.environment = environment self.size = size <|end_body_0|> <|body_start_1|> if dictionary is None: return None count = dictionary.get('count') environment = dictionary.get('environment') size = dictionary.get('s...
Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProviderStatsByEnvEnum): Specifies the environment type. size (long|int): Specifies the size of th...
VaultProviderStatsByEnv
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VaultProviderStatsByEnv: """Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProviderStatsByEnvEnum): Specifies the environm...
stack_v2_sparse_classes_36k_train_028916
1,885
permissive
[ { "docstring": "Constructor for the VaultProviderStatsByEnv class", "name": "__init__", "signature": "def __init__(self, count=None, environment=None, size=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of ...
2
stack_v2_sparse_classes_30k_test_000837
Implement the Python class `VaultProviderStatsByEnv` described below. Class description: Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProvider...
Implement the Python class `VaultProviderStatsByEnv` described below. Class description: Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProvider...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class VaultProviderStatsByEnv: """Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProviderStatsByEnvEnum): Specifies the environm...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VaultProviderStatsByEnv: """Implementation of the 'VaultProviderStatsByEnv' model. Specifies the Vault stats by environments. Attributes: count (long|int): Specifies the count of the objects of the specified environment. environment (EnvironmentVaultProviderStatsByEnvEnum): Specifies the environment type. siz...
the_stack_v2_python_sparse
cohesity_management_sdk/models/vault_provider_stats_by_env.py
cohesity/management-sdk-python
train
24
5c01df7e6b158b83336506331aef99d75b953b55
[ "super().__init__()\nself._name = 'Single-Qubit Pauli Preparation Basis'\nself._basis = {'0': np.array([[1, 0], [0, 0]]).astype(complex), '1': np.array([[0, 0], [0, 1]]).astype(complex), 'A': np.array([[1, 1], [1, 1]]).astype(complex) / 2, 'L': np.array([[1, -1j], [1j, 1]]).astype(complex) / 2}", "if qubits is No...
<|body_start_0|> super().__init__() self._name = 'Single-Qubit Pauli Preparation Basis' self._basis = {'0': np.array([[1, 0], [0, 0]]).astype(complex), '1': np.array([[0, 0], [0, 1]]).astype(complex), 'A': np.array([[1, 1], [1, 1]]).astype(complex) / 2, 'L': np.array([[1, -1j], [1j, 1]]).astype(...
The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\\ 0 & 0 \\end{bmatrix}`, "1": :math:`\\begin{bmatrix} 0 & 0 \\\\ 0 & 1 \\end{bmat...
PauliPrepBasis
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PauliPrepBasis: """The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\\ 0 & 0 \\end{bmatrix}`, "1": :math:`\\...
stack_v2_sparse_classes_36k_train_028917
43,941
permissive
[ { "docstring": "Initializes the Pauli preparation basis class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "For each preparation operator in the overcomplete preparation basis, decorate the given quantum program by adding the preparation quantum circuit to the begin...
2
null
Implement the Python class `PauliPrepBasis` described below. Class description: The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\...
Implement the Python class `PauliPrepBasis` described below. Class description: The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\...
8bc3c7238b5b6825eb63ded8d65afb08b389941f
<|skeleton|> class PauliPrepBasis: """The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\\ 0 & 0 \\end{bmatrix}`, "1": :math:`\\...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PauliPrepBasis: """The Pauli preparation basis class. The two properties: `name` and `basis` must be initialized. Here, `basis` is the preparation basis from the qubit Pauli operators, which is theoretically defined as {"0": :math:`\\begin{bmatrix} 1 & 0 \\\\ 0 & 0 \\end{bmatrix}`, "1": :math:`\\begin{bmatrix...
the_stack_v2_python_sparse
Extensions/QuantumErrorProcessing/qcompute_qep/tomography/basis.py
baidu/QCompute
train
86
e058866aab8b0d075db8236bb6da253417dfcecc
[ "with self.assertRaisesRegex(TypeError, 'simulator must inherit cirq.SimulatesFinalState.'):\n cirq_ops._get_cirq_simulate_state('junk')\ncirq_ops._get_cirq_simulate_state()\ncirq_ops._get_cirq_simulate_state(cirq.Simulator())\ncirq_ops._get_cirq_simulate_state(cirq.DensityMatrixSimulator())", "test_op = cirq_...
<|body_start_0|> with self.assertRaisesRegex(TypeError, 'simulator must inherit cirq.SimulatesFinalState.'): cirq_ops._get_cirq_simulate_state('junk') cirq_ops._get_cirq_simulate_state() cirq_ops._get_cirq_simulate_state(cirq.Simulator()) cirq_ops._get_cirq_simulate_state(cir...
Tests get_cirq_simulate_state.
CirqSimulateStateTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CirqSimulateStateTest: """Tests get_cirq_simulate_state.""" def test_get_cirq_state_op(self): """Input check the wrapper for the cirq state op.""" <|body_0|> def test_cirq_state_op_inputs(self): """test input checking in the state sim op.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_028918
23,553
permissive
[ { "docstring": "Input check the wrapper for the cirq state op.", "name": "test_get_cirq_state_op", "signature": "def test_get_cirq_state_op(self)" }, { "docstring": "test input checking in the state sim op.", "name": "test_cirq_state_op_inputs", "signature": "def test_cirq_state_op_input...
5
stack_v2_sparse_classes_30k_train_013005
Implement the Python class `CirqSimulateStateTest` described below. Class description: Tests get_cirq_simulate_state. Method signatures and docstrings: - def test_get_cirq_state_op(self): Input check the wrapper for the cirq state op. - def test_cirq_state_op_inputs(self): test input checking in the state sim op. - d...
Implement the Python class `CirqSimulateStateTest` described below. Class description: Tests get_cirq_simulate_state. Method signatures and docstrings: - def test_get_cirq_state_op(self): Input check the wrapper for the cirq state op. - def test_cirq_state_op_inputs(self): test input checking in the state sim op. - d...
f56257bceb988b743790e1e480eac76fd036d4ff
<|skeleton|> class CirqSimulateStateTest: """Tests get_cirq_simulate_state.""" def test_get_cirq_state_op(self): """Input check the wrapper for the cirq state op.""" <|body_0|> def test_cirq_state_op_inputs(self): """test input checking in the state sim op.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CirqSimulateStateTest: """Tests get_cirq_simulate_state.""" def test_get_cirq_state_op(self): """Input check the wrapper for the cirq state op.""" with self.assertRaisesRegex(TypeError, 'simulator must inherit cirq.SimulatesFinalState.'): cirq_ops._get_cirq_simulate_state('jun...
the_stack_v2_python_sparse
tensorflow_quantum/core/ops/cirq_ops_test.py
tensorflow/quantum
train
1,799
3b61ecf69e828c16665c06cecfa3d6188181f030
[ "if filename.endswith('.TIF') or filename.endswith('.tif') or filename.endswith('.tiff') or filename.endswith('.TIFF'):\n file_path = os.path.join(out_path, filename)\nelse:\n file_path = os.path.join(out_path, '{}_{}.TIF'.format(filename, type_bands_name))\nreturn file_path", "type_bands_name = 'r{0}g{1}b{...
<|body_start_0|> if filename.endswith('.TIF') or filename.endswith('.tif') or filename.endswith('.tiff') or filename.endswith('.TIFF'): file_path = os.path.join(out_path, filename) else: file_path = os.path.join(out_path, '{}_{}.TIF'.format(filename, type_bands_name)) ret...
Class with method that process and create composition from a Landsat list of files.
Composer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Composer: """Class with method that process and create composition from a Landsat list of files.""" def __set_full_output_filepath(self, filename, out_path, type_bands_name): """Returns complete filepath tif for rgb composition""" <|body_0|> def create_composition(filena...
stack_v2_sparse_classes_36k_train_028919
2,574
permissive
[ { "docstring": "Returns complete filepath tif for rgb composition", "name": "__set_full_output_filepath", "signature": "def __set_full_output_filepath(self, filename, out_path, type_bands_name)" }, { "docstring": "Creates a composition using gdal_merge.py with ordered filelist Args: filename: ou...
2
stack_v2_sparse_classes_30k_train_002959
Implement the Python class `Composer` described below. Class description: Class with method that process and create composition from a Landsat list of files. Method signatures and docstrings: - def __set_full_output_filepath(self, filename, out_path, type_bands_name): Returns complete filepath tif for rgb composition...
Implement the Python class `Composer` described below. Class description: Class with method that process and create composition from a Landsat list of files. Method signatures and docstrings: - def __set_full_output_filepath(self, filename, out_path, type_bands_name): Returns complete filepath tif for rgb composition...
310566df81483d9d7e5535832375091af2117c2d
<|skeleton|> class Composer: """Class with method that process and create composition from a Landsat list of files.""" def __set_full_output_filepath(self, filename, out_path, type_bands_name): """Returns complete filepath tif for rgb composition""" <|body_0|> def create_composition(filena...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Composer: """Class with method that process and create composition from a Landsat list of files.""" def __set_full_output_filepath(self, filename, out_path, type_bands_name): """Returns complete filepath tif for rgb composition""" if filename.endswith('.TIF') or filename.endswith('.tif') ...
the_stack_v2_python_sparse
landsat_processor/composer.py
igor-rodrigues01/landast_processor
train
0
46a57fd7deeb2e147dedeaba00120e4bbf971a25
[ "self.args = args\nif any((not isinstance(x, Arg) for x in args)):\n raise TypeError('Arguments to Args object should all be Arg objects')\nself.args_by_name = {x.name: x for x in args}", "attributes = {}\nerrors = []\nfor arg in self.args:\n if arg.name not in dargs and (not arg.IsOptional()):\n err...
<|body_start_0|> self.args = args if any((not isinstance(x, Arg) for x in args)): raise TypeError('Arguments to Args object should all be Arg objects') self.args_by_name = {x.name: x for x in args} <|end_body_0|> <|body_start_1|> attributes = {} errors = [] f...
A class to hold a list of argument specs for an argument parser.
Args
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Args: """A class to hold a list of argument specs for an argument parser.""" def __init__(self, *args): """Constructs an argument parser. Args: args: A list of Arg objects.""" <|body_0|> def Parse(self, dargs, unresolvable_type=None): """Parses a dargs object fro...
stack_v2_sparse_classes_36k_train_028920
8,140
permissive
[ { "docstring": "Constructs an argument parser. Args: args: A list of Arg objects.", "name": "__init__", "signature": "def __init__(self, *args)" }, { "docstring": "Parses a dargs object from the test list. Args: dargs: A name/value map of arguments from the test list. unresolvable_type: A type i...
2
stack_v2_sparse_classes_30k_train_021542
Implement the Python class `Args` described below. Class description: A class to hold a list of argument specs for an argument parser. Method signatures and docstrings: - def __init__(self, *args): Constructs an argument parser. Args: args: A list of Arg objects. - def Parse(self, dargs, unresolvable_type=None): Pars...
Implement the Python class `Args` described below. Class description: A class to hold a list of argument specs for an argument parser. Method signatures and docstrings: - def __init__(self, *args): Constructs an argument parser. Args: args: A list of Arg objects. - def Parse(self, dargs, unresolvable_type=None): Pars...
a1b0fccd68987d8cd9c89710adc3c04b868347ec
<|skeleton|> class Args: """A class to hold a list of argument specs for an argument parser.""" def __init__(self, *args): """Constructs an argument parser. Args: args: A list of Arg objects.""" <|body_0|> def Parse(self, dargs, unresolvable_type=None): """Parses a dargs object fro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Args: """A class to hold a list of argument specs for an argument parser.""" def __init__(self, *args): """Constructs an argument parser. Args: args: A list of Arg objects.""" self.args = args if any((not isinstance(x, Arg) for x in args)): raise TypeError('Arguments t...
the_stack_v2_python_sparse
py/utils/arg_utils.py
bridder/factory
train
0
fc1afc8cc7f200e96cf5b9232ae85947582d3153
[ "self.one_hot_values = one_hot_values\nself.found_values = []\nself.add_others = add_others", "encoded_list = [1 if x == value else 0 for x in self.one_hot_values]\nif self.add_others:\n if value not in self.one_hot_values:\n encoded_list += [1]\n else:\n encoded_list += [0]\nif value not in s...
<|body_start_0|> self.one_hot_values = one_hot_values self.found_values = [] self.add_others = add_others <|end_body_0|> <|body_start_1|> encoded_list = [1 if x == value else 0 for x in self.one_hot_values] if self.add_others: if value not in self.one_hot_values: ...
Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a basic encoder example for ``MolecularGraphRDKit``.
OneHotEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OneHotEncoder: """Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a basic encoder example for ``MolecularGrap...
stack_v2_sparse_classes_36k_train_028921
16,929
permissive
[ { "docstring": "Initialize the encoder beforehand with a set of all possible values to encounter. Args: one_hot_values (list): List of possible values, matching the one-hot encoding. add_others (bool): Whether to add a unknown bit. Default is True.", "name": "__init__", "signature": "def __init__(self, ...
2
stack_v2_sparse_classes_30k_val_000320
Implement the Python class `OneHotEncoder` described below. Class description: Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a ba...
Implement the Python class `OneHotEncoder` described below. Class description: Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a ba...
6e1ac91037da72a843b00eaa57b65405ae58c63e
<|skeleton|> class OneHotEncoder: """Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a basic encoder example for ``MolecularGrap...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OneHotEncoder: """Simple One-Hot-Encoding for python lists. Uses a list of possible values for a one-hot encoding of a single value. The translated values must support ``__eq__()`` operator. The list of possible values must be set beforehand. Is used as a basic encoder example for ``MolecularGraphRDKit``.""" ...
the_stack_v2_python_sparse
kgcnn/mol/molgraph.py
beoy/gcnn_keras
train
0
953d40e4e56208188a6ecfe86be81d89c96e31f9
[ "data = self.get_json()\ncatalog_name = data.get('catalog_name')\ncatalog_data = data.get('catalog_data')\nif catalog_name is None:\n return self.error('catalog_name is a required parameter.')\nif catalog_data is None:\n return self.error('catalog_data is a required parameter.')\nif type(catalog_name) is not ...
<|body_start_0|> data = self.get_json() catalog_name = data.get('catalog_name') catalog_data = data.get('catalog_data') if catalog_name is None: return self.error('catalog_name is a required parameter.') if catalog_data is None: return self.error('catalog_...
SpatialCatalogHandler
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpatialCatalogHandler: def post(self): """--- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object p...
stack_v2_sparse_classes_36k_train_028922
13,231
permissive
[ { "docstring": "--- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object properties: data: type: object properties: id: type...
3
null
Implement the Python class `SpatialCatalogHandler` described below. Class description: Implement the SpatialCatalogHandler class. Method signatures and docstrings: - def post(self): --- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost res...
Implement the Python class `SpatialCatalogHandler` described below. Class description: Implement the SpatialCatalogHandler class. Method signatures and docstrings: - def post(self): --- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost res...
161d3532ba3ba059446addcdac58ca96f39e9636
<|skeleton|> class SpatialCatalogHandler: def post(self): """--- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpatialCatalogHandler: def post(self): """--- description: Ingest a Spatial Catalog tags: - galaxies requestBody: content: application/json: schema: SpatialCatalogHandlerPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object properties: dat...
the_stack_v2_python_sparse
skyportal/handlers/api/spatial_catalog.py
skyportal/skyportal
train
80
f4210211733ca76f0073c5bab388ee7ee88ab38a
[ "self._op_state_model = op_state_model\nsuper().__init__(target, obs_state_model, action_slug, *args, logger=logger, **kwargs)\nself._action_slug = action_slug\nself._invoked_action = f'{action_slug}_invoked'", "if self._op_state_model.op_state != DevState.ON:\n if raise_if_disallowed:\n raise CommandEr...
<|body_start_0|> self._op_state_model = op_state_model super().__init__(target, obs_state_model, action_slug, *args, logger=logger, **kwargs) self._action_slug = action_slug self._invoked_action = f'{action_slug}_invoked' <|end_body_0|> <|body_start_1|> if self._op_state_model.o...
ObservationCommand
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObservationCommand: def __init__(self, target, obs_state_model, action_slug, op_state_model, *args, logger=None, **kwargs): """A base class for commands that drive the device's observing state. This is a special case of a ``StateModelCommand`` because although it only drives the observat...
stack_v2_sparse_classes_36k_train_028923
14,989
permissive
[ { "docstring": "A base class for commands that drive the device's observing state. This is a special case of a ``StateModelCommand`` because although it only drives the observation state model, it has to check also the operational state model to determine whether it is allowed to run. :param target: the object ...
2
stack_v2_sparse_classes_30k_train_013336
Implement the Python class `ObservationCommand` described below. Class description: Implement the ObservationCommand class. Method signatures and docstrings: - def __init__(self, target, obs_state_model, action_slug, op_state_model, *args, logger=None, **kwargs): A base class for commands that drive the device's obse...
Implement the Python class `ObservationCommand` described below. Class description: Implement the ObservationCommand class. Method signatures and docstrings: - def __init__(self, target, obs_state_model, action_slug, op_state_model, *args, logger=None, **kwargs): A base class for commands that drive the device's obse...
32b740065bd856a7155c068e82cede094207ec71
<|skeleton|> class ObservationCommand: def __init__(self, target, obs_state_model, action_slug, op_state_model, *args, logger=None, **kwargs): """A base class for commands that drive the device's observing state. This is a special case of a ``StateModelCommand`` because although it only drives the observat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObservationCommand: def __init__(self, target, obs_state_model, action_slug, op_state_model, *args, logger=None, **kwargs): """A base class for commands that drive the device's observing state. This is a special case of a ``StateModelCommand`` because although it only drives the observation state mode...
the_stack_v2_python_sparse
src/ska_tango_base/commands.py
Umadevi-amin/lmc-base-classes
train
0
98cf14d01fcfcd86ef1b11b3208fe037e9922432
[ "self.map = dict()\nself.head = DLNode()\nself.tail = DLNode()\nself.head.next = self.tail\nself.tail.prev = self.head", "if key in self.map:\n cur = self.map[key]\n cur.data[1].remove(key)\n val = cur.data[0] + 1\n r = cur.next\n if len(cur.data[1]) == 0:\n r.prev = cur.prev\n cur.pr...
<|body_start_0|> self.map = dict() self.head = DLNode() self.tail = DLNode() self.head.next = self.tail self.tail.prev = self.head <|end_body_0|> <|body_start_1|> if key in self.map: cur = self.map[key] cur.data[1].remove(key) val = cu...
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_36k_train_028924
3,736
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void", "name": "inc", "signature": "def inc(self, key)" }, ...
5
stack_v2_sparse_classes_30k_train_002083
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
9190d3d178f1733aa226973757ee7e045b7bab00
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllOne: def __init__(self): """Initialize your data structure here.""" self.map = dict() self.head = DLNode() self.tail = DLNode() self.head.next = self.tail self.tail.prev = self.head def inc(self, key): """Inserts a new key <Key> with value 1. Or ...
the_stack_v2_python_sparse
AllOoneDataStructure.py
ellinx/LC-python
train
1
8372bc500c8e3fb6115f577a6a583c784e294534
[ "if not check_for_language(language_id):\n raise serializers.ValidationError(_('Language is not supported by Kolibri'))\nreturn language_id", "with transaction.atomic():\n facility = Facility.objects.create(**validated_data.pop('facility'))\n preset = validated_data.pop('preset')\n dataset_data = mapp...
<|body_start_0|> if not check_for_language(language_id): raise serializers.ValidationError(_('Language is not supported by Kolibri')) return language_id <|end_body_0|> <|body_start_1|> with transaction.atomic(): facility = Facility.objects.create(**validated_data.pop('fa...
DeviceProvisionSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceProvisionSerializer: def validate_language_id(self, language_id): """Check that the language_id is supported by Kolibri""" <|body_0|> def create(self, validated_data): """Endpoint for initial setup of a device. Expects a value for: default language - the defaul...
stack_v2_sparse_classes_36k_train_028925
3,915
permissive
[ { "docstring": "Check that the language_id is supported by Kolibri", "name": "validate_language_id", "signature": "def validate_language_id(self, language_id)" }, { "docstring": "Endpoint for initial setup of a device. Expects a value for: default language - the default language of this Kolibri ...
2
null
Implement the Python class `DeviceProvisionSerializer` described below. Class description: Implement the DeviceProvisionSerializer class. Method signatures and docstrings: - def validate_language_id(self, language_id): Check that the language_id is supported by Kolibri - def create(self, validated_data): Endpoint for...
Implement the Python class `DeviceProvisionSerializer` described below. Class description: Implement the DeviceProvisionSerializer class. Method signatures and docstrings: - def validate_language_id(self, language_id): Check that the language_id is supported by Kolibri - def create(self, validated_data): Endpoint for...
11e0d01e2bc43850a6dfd4238e6408004449c3dc
<|skeleton|> class DeviceProvisionSerializer: def validate_language_id(self, language_id): """Check that the language_id is supported by Kolibri""" <|body_0|> def create(self, validated_data): """Endpoint for initial setup of a device. Expects a value for: default language - the defaul...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeviceProvisionSerializer: def validate_language_id(self, language_id): """Check that the language_id is supported by Kolibri""" if not check_for_language(language_id): raise serializers.ValidationError(_('Language is not supported by Kolibri')) return language_id def ...
the_stack_v2_python_sparse
kolibri/core/device/serializers.py
lyw07/kolibri
train
1
d14b410c05a62264ee66d2ddb54074530f11b68c
[ "with h5py.File(self.reference_fname, 'r') as reference_fid, h5py.File(self.test_fname, 'r') as test_fid:\n ref_dset = reference_fid['self-shadow']\n test_dset = test_fid['self-shadow']\n self.assertTrue(numpy.array_equal(ref_dset, test_dset))", "with h5py.File(self.reference_fname, 'r') as reference_fid...
<|body_start_0|> with h5py.File(self.reference_fname, 'r') as reference_fid, h5py.File(self.test_fname, 'r') as test_fid: ref_dset = reference_fid['self-shadow'] test_dset = test_fid['self-shadow'] self.assertTrue(numpy.array_equal(ref_dset, test_dset)) <|end_body_0|> <|body...
Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-sun * cast-shadow-satellite * combined-shadow We're not explicitly testing the func...
TestShadowMasks
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestShadowMasks: """Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-sun * cast-shadow-satellite * combined-s...
stack_v2_sparse_classes_36k_train_028926
3,914
permissive
[ { "docstring": "Test the self shadow mask.", "name": "test_self_shadow", "signature": "def test_self_shadow(self)" }, { "docstring": "Test the cast shadow mask (sun direction).", "name": "test_cast_shadow_sun", "signature": "def test_cast_shadow_sun(self)" }, { "docstring": "Test...
4
null
Implement the Python class `TestShadowMasks` described below. Class description: Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-s...
Implement the Python class `TestShadowMasks` described below. Class description: Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-s...
4ae3670681b872530f59c57ab537a45d1b09c009
<|skeleton|> class TestShadowMasks: """Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-sun * cast-shadow-satellite * combined-s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestShadowMasks: """Unittesting for the self shadow, cast shadow (from both the sun and satellite directions), and the combined shadow masks, found in `wagl.terrain_shadow_masks`. Unittests will occur for the following datasets: * self-shadow * cast-shadow-sun * cast-shadow-satellite * combined-shadow We're n...
the_stack_v2_python_sparse
wagl/scripts/test_terrain_shadow_masks.py
GeoscienceAustralia/wagl
train
25
b9bfbba7b86c4b0ef0f0d373321d685d16348be2
[ "del update_time\nerr = 'Error in GQL query - resolve_thread_messages.'\nwith ax_model.try_catch(info.context['session'], err) as db_session:\n current_user = info.context['user']\n if not thread_guid:\n return None\n thread = db_session.query(AxMessageThread).filter(AxMessageThread.guid == uuid.UUI...
<|body_start_0|> del update_time err = 'Error in GQL query - resolve_thread_messages.' with ax_model.try_catch(info.context['session'], err) as db_session: current_user = info.context['user'] if not thread_guid: return None thread = db_session....
AxFields queryes
FieldsQuery
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FieldsQuery: """AxFields queryes""" async def resolve_thread_messages(self, info, thread_guid, update_time=None): """Get all AxMessages for specific thread.""" <|body_0|> async def resolve_to1_fields(self, info, child_form_guid, field_guid, update_time=None): """...
stack_v2_sparse_classes_36k_train_028927
9,623
no_license
[ { "docstring": "Get all AxMessages for specific thread.", "name": "resolve_thread_messages", "signature": "async def resolve_thread_messages(self, info, thread_guid, update_time=None)" }, { "docstring": "Get all AxMessages for specific thread.", "name": "resolve_to1_fields", "signature":...
3
stack_v2_sparse_classes_30k_train_019713
Implement the Python class `FieldsQuery` described below. Class description: AxFields queryes Method signatures and docstrings: - async def resolve_thread_messages(self, info, thread_guid, update_time=None): Get all AxMessages for specific thread. - async def resolve_to1_fields(self, info, child_form_guid, field_guid...
Implement the Python class `FieldsQuery` described below. Class description: AxFields queryes Method signatures and docstrings: - async def resolve_thread_messages(self, info, thread_guid, update_time=None): Get all AxMessages for specific thread. - async def resolve_to1_fields(self, info, child_form_guid, field_guid...
3540979e680732d38e25a6b39f09338985de6743
<|skeleton|> class FieldsQuery: """AxFields queryes""" async def resolve_thread_messages(self, info, thread_guid, update_time=None): """Get all AxMessages for specific thread.""" <|body_0|> async def resolve_to1_fields(self, info, child_form_guid, field_guid, update_time=None): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FieldsQuery: """AxFields queryes""" async def resolve_thread_messages(self, info, thread_guid, update_time=None): """Get all AxMessages for specific thread.""" del update_time err = 'Error in GQL query - resolve_thread_messages.' with ax_model.try_catch(info.context['sessi...
the_stack_v2_python_sparse
Calculation methods/CalcMethods_Lab_3_V15_Task_3_15/venv/Lib/site-packages/ax/backend/schemas/fields_schema.py
areyykarthik/Zhukouski_Pavel_BSU_Projects
train
0
2d6d1211751bdaa27439e9d456f0e05c68c56a1e
[ "super(Discriminator, self).__init__()\nself.num_gpu = num_gpu\nself.layer = nn.Sequential(nn.Conv2d(num_channels, conv_dim, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(conv_dim, conv_dim * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(conv_dim * 2), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(conv_di...
<|body_start_0|> super(Discriminator, self).__init__() self.num_gpu = num_gpu self.layer = nn.Sequential(nn.Conv2d(num_channels, conv_dim, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(conv_dim, conv_dim * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(conv_dim * 2), nn.LeakyReLU(0.2...
Model for Discriminator.
Discriminator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Discriminator: """Model for Discriminator.""" def __init__(self, num_channels, conv_dim, num_gpu): """Init for Discriminator model.""" <|body_0|> def forward(self, input): """Forward step for Discriminator model.""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_028928
4,479
permissive
[ { "docstring": "Init for Discriminator model.", "name": "__init__", "signature": "def __init__(self, num_channels, conv_dim, num_gpu)" }, { "docstring": "Forward step for Discriminator model.", "name": "forward", "signature": "def forward(self, input)" } ]
2
stack_v2_sparse_classes_30k_train_010286
Implement the Python class `Discriminator` described below. Class description: Model for Discriminator. Method signatures and docstrings: - def __init__(self, num_channels, conv_dim, num_gpu): Init for Discriminator model. - def forward(self, input): Forward step for Discriminator model.
Implement the Python class `Discriminator` described below. Class description: Model for Discriminator. Method signatures and docstrings: - def __init__(self, num_channels, conv_dim, num_gpu): Init for Discriminator model. - def forward(self, input): Forward step for Discriminator model. <|skeleton|> class Discrimin...
fd4498da35ace5a3d1696ff4fbec3568eddbe6a1
<|skeleton|> class Discriminator: """Model for Discriminator.""" def __init__(self, num_channels, conv_dim, num_gpu): """Init for Discriminator model.""" <|body_0|> def forward(self, input): """Forward step for Discriminator model.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Discriminator: """Model for Discriminator.""" def __init__(self, num_channels, conv_dim, num_gpu): """Init for Discriminator model.""" super(Discriminator, self).__init__() self.num_gpu = num_gpu self.layer = nn.Sequential(nn.Conv2d(num_channels, conv_dim, 4, 2, 1, bias=Fa...
the_stack_v2_python_sparse
DCGAN/models.py
corenel/GAN-Zoo
train
10
0a0d4b60f88a63ca1931c59aab01e5066a2d4d4f
[ "self.name = 'OVA Classifier'\nif 'init_from_binary' in data_args.keys():\n self.init_model = data_args['init_from_binary']\nelse:\n self.init_model = None\nsuper(OvAModel, self).__init__(**data_args)", "if self.init_model is not None:\n print('Using Binary Model results.')\n self.class_labels = self....
<|body_start_0|> self.name = 'OVA Classifier' if 'init_from_binary' in data_args.keys(): self.init_model = data_args['init_from_binary'] else: self.init_model = None super(OvAModel, self).__init__(**data_args) <|end_body_0|> <|body_start_1|> if self.init_...
OvAModel
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OvAModel: def __init__(self, **data_args): """Initialize Independent Model - call init method of parent class""" <|body_0|> def run_cfv(self, start_time): """Overwrite MainModel function to see if results from BinaryModel were passed in""" <|body_1|> def...
stack_v2_sparse_classes_36k_train_028929
5,949
permissive
[ { "docstring": "Initialize Independent Model - call init method of parent class", "name": "__init__", "signature": "def __init__(self, **data_args)" }, { "docstring": "Overwrite MainModel function to see if results from BinaryModel were passed in", "name": "run_cfv", "signature": "def ru...
6
stack_v2_sparse_classes_30k_train_002750
Implement the Python class `OvAModel` described below. Class description: Implement the OvAModel class. Method signatures and docstrings: - def __init__(self, **data_args): Initialize Independent Model - call init method of parent class - def run_cfv(self, start_time): Overwrite MainModel function to see if results f...
Implement the Python class `OvAModel` described below. Class description: Implement the OvAModel class. Method signatures and docstrings: - def __init__(self, **data_args): Initialize Independent Model - call init method of parent class - def run_cfv(self, start_time): Overwrite MainModel function to see if results f...
9d498b697b7c4b03e1db31cae4d7a469311229f7
<|skeleton|> class OvAModel: def __init__(self, **data_args): """Initialize Independent Model - call init method of parent class""" <|body_0|> def run_cfv(self, start_time): """Overwrite MainModel function to see if results from BinaryModel were passed in""" <|body_1|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OvAModel: def __init__(self, **data_args): """Initialize Independent Model - call init method of parent class""" self.name = 'OVA Classifier' if 'init_from_binary' in data_args.keys(): self.init_model = data_args['init_from_binary'] else: self.init_model...
the_stack_v2_python_sparse
models/ind_model/ind_model.py
marinakiseleva/thex_model
train
4
a06712124f13364c70a2f77fd9a6a2f2f77fa0cf
[ "length = np.prod(self.nd_shape)\ntile = 1\nbiases = []\nfor i, l in enumerate(self.nd_shape):\n if l > 1:\n new_bias = self.relative_attn_bias(l, self.num_heads, f'bias_{i}')\n repeat = length // (tile * l)\n if repeat > 1:\n new_bias = new_bias[:, :, jnp.newaxis, :, jnp.newaxis]...
<|body_start_0|> length = np.prod(self.nd_shape) tile = 1 biases = [] for i, l in enumerate(self.nd_shape): if l > 1: new_bias = self.relative_attn_bias(l, self.num_heads, f'bias_{i}') repeat = length // (tile * l) if repeat > 1...
Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would provide a 2D shape. Note that batch and feature dimensions should be excluded here. initiali...
RelativeAttentionBias
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelativeAttentionBias: """Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would provide a 2D shape. Note that batch and fea...
stack_v2_sparse_classes_36k_train_028930
25,060
permissive
[ { "docstring": "Creates relative attention bias that factorizes over dimensions. length = prod(nd_shape) Returns: Bias of shape `[num_heads, length, length]`.", "name": "__call__", "signature": "def __call__(self) -> jnp.ndarray" }, { "docstring": "Computes attention bias based on relative posit...
2
null
Implement the Python class `RelativeAttentionBias` described below. Class description: Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would prov...
Implement the Python class `RelativeAttentionBias` described below. Class description: Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would prov...
c3ae6d7b5dc829fafe204a92522a5983959561a0
<|skeleton|> class RelativeAttentionBias: """Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would provide a 2D shape. Note that batch and fea...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelativeAttentionBias: """Provides learnable NxN relative attention bias. Attributes: num_heads: Number of heads for which to provide relative attention. nd_shape: Shape for which to provided relative attention bias. For instance, for images we we would provide a 2D shape. Note that batch and feature dimensio...
the_stack_v2_python_sparse
scenic/model_lib/layers/attention_layers.py
shreyasarora/scenic
train
0
1ad7a1072c7e9ed818719cd1433bbfc32b2a2bf2
[ "save_dir = tempfile.mkdtemp()\nresults, file_name = multiprocessing_tools.managed_multiprocessing_loop_to_numpy(DEFAULT_ARGUMENTS, save_dir=save_dir, function_to_execute=adder_function, save_every=3)\nself.assertEqual(file_name, os.path.join(save_dir, 'interpolation_result.npy'))\nself.assertTrue(all([i * 2 == res...
<|body_start_0|> save_dir = tempfile.mkdtemp() results, file_name = multiprocessing_tools.managed_multiprocessing_loop_to_numpy(DEFAULT_ARGUMENTS, save_dir=save_dir, function_to_execute=adder_function, save_every=3) self.assertEqual(file_name, os.path.join(save_dir, 'interpolation_result.npy')) ...
MultiprocessingToolsTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiprocessingToolsTest: def test_managed_multiprocessing_loop_to_numpy(self): """Test if multiprocessing loops work.""" <|body_0|> def test_managed_multiprocessing_loop_to_ndjson(self): """Test if multiprocessing loops work.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_028931
3,134
permissive
[ { "docstring": "Test if multiprocessing loops work.", "name": "test_managed_multiprocessing_loop_to_numpy", "signature": "def test_managed_multiprocessing_loop_to_numpy(self)" }, { "docstring": "Test if multiprocessing loops work.", "name": "test_managed_multiprocessing_loop_to_ndjson", ...
2
stack_v2_sparse_classes_30k_train_001812
Implement the Python class `MultiprocessingToolsTest` described below. Class description: Implement the MultiprocessingToolsTest class. Method signatures and docstrings: - def test_managed_multiprocessing_loop_to_numpy(self): Test if multiprocessing loops work. - def test_managed_multiprocessing_loop_to_ndjson(self):...
Implement the Python class `MultiprocessingToolsTest` described below. Class description: Implement the MultiprocessingToolsTest class. Method signatures and docstrings: - def test_managed_multiprocessing_loop_to_numpy(self): Test if multiprocessing loops work. - def test_managed_multiprocessing_loop_to_ndjson(self):...
96c99bc67ce40559c61bdb6110f625671fc96055
<|skeleton|> class MultiprocessingToolsTest: def test_managed_multiprocessing_loop_to_numpy(self): """Test if multiprocessing loops work.""" <|body_0|> def test_managed_multiprocessing_loop_to_ndjson(self): """Test if multiprocessing loops work.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiprocessingToolsTest: def test_managed_multiprocessing_loop_to_numpy(self): """Test if multiprocessing loops work.""" save_dir = tempfile.mkdtemp() results, file_name = multiprocessing_tools.managed_multiprocessing_loop_to_numpy(DEFAULT_ARGUMENTS, save_dir=save_dir, function_to_exe...
the_stack_v2_python_sparse
interpolation_experiments/multiprocessing_tools_test.py
muskanmahajan37/policy-learning-landscape
train
0
6de0436abd47ba94fac9bb05fdbe77550bf7c91f
[ "self.column_names: List = kargs.pop('column_names')\nsuper().__init__(*args, **kargs)\nself.set_fields_from_dict(['item_column', 'confirm_items'])\nitem_column = self.fields['item_column'].initial\nif item_column is None:\n item_column = ('', '---')\nelse:\n item_column = (item_column, item_column)\nself.fie...
<|body_start_0|> self.column_names: List = kargs.pop('column_names') super().__init__(*args, **kargs) self.set_fields_from_dict(['item_column', 'confirm_items']) item_column = self.fields['item_column'].initial if item_column is None: item_column = ('', '---') ...
Form to process Basic JSON information.
JSONKeyForm
[ "MIT", "LGPL-2.0-or-later", "Python-2.0", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONKeyForm: """Form to process Basic JSON information.""" def __init__(self, *args, **kargs): """Store column names, payload and modify item_column and confirm.""" <|body_0|> def clean(self): """Verify email values.""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_028932
20,237
permissive
[ { "docstring": "Store column names, payload and modify item_column and confirm.", "name": "__init__", "signature": "def __init__(self, *args, **kargs)" }, { "docstring": "Verify email values.", "name": "clean", "signature": "def clean(self)" } ]
2
stack_v2_sparse_classes_30k_train_000652
Implement the Python class `JSONKeyForm` described below. Class description: Form to process Basic JSON information. Method signatures and docstrings: - def __init__(self, *args, **kargs): Store column names, payload and modify item_column and confirm. - def clean(self): Verify email values.
Implement the Python class `JSONKeyForm` described below. Class description: Form to process Basic JSON information. Method signatures and docstrings: - def __init__(self, *args, **kargs): Store column names, payload and modify item_column and confirm. - def clean(self): Verify email values. <|skeleton|> class JSONK...
5473e9faa24c71a2a1102d47ebc2cbf27608e42a
<|skeleton|> class JSONKeyForm: """Form to process Basic JSON information.""" def __init__(self, *args, **kargs): """Store column names, payload and modify item_column and confirm.""" <|body_0|> def clean(self): """Verify email values.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JSONKeyForm: """Form to process Basic JSON information.""" def __init__(self, *args, **kargs): """Store column names, payload and modify item_column and confirm.""" self.column_names: List = kargs.pop('column_names') super().__init__(*args, **kargs) self.set_fields_from_di...
the_stack_v2_python_sparse
ontask/action/forms/run.py
LucasFranciscoCorreia/ontask_b
train
0
63206345b46bee6668424f7896d261e2dbcff51c
[ "avglumi = 0.0\nif c1 and nBXs > 0:\n avglumi = c1 * luminonorm / nBXs\nAfterglow = 1.0\nif len(afterglow) != 0:\n afterglowmap = ast.literal_eval(afterglow)\n for bxthreshold, correction in afterglowmap:\n if nBXs >= bxthreshold:\n Afterglow = correction\ndriftterm = 1.0\nif drift and in...
<|body_start_0|> avglumi = 0.0 if c1 and nBXs > 0: avglumi = c1 * luminonorm / nBXs Afterglow = 1.0 if len(afterglow) != 0: afterglowmap = ast.literal_eval(afterglow) for bxthreshold, correction in afterglowmap: if nBXs >= bxthreshold: ...
luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params
normFunctionFactory
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class normFunctionFactory: """luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params""" def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drif...
stack_v2_sparse_classes_36k_train_028933
3,290
permissive
[ { "docstring": "input: luminonorm unit Hz/ub output: correction factor to be applied on lumi in Hz/ub", "name": "fPoly", "signature": "def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drift=0.0, c1=0.0, afterglow='')" }, { "docstring": "input: luminonorm unit H...
2
null
Implement the Python class `normFunctionFactory` described below. Class description: luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params Method signatures and docstrings: - def fPoly(self, lumi...
Implement the Python class `normFunctionFactory` described below. Class description: luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params Method signatures and docstrings: - def fPoly(self, lumi...
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
<|skeleton|> class normFunctionFactory: """luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params""" def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drif...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class normFunctionFactory: """luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params""" def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drift=0.0, c1=0.0...
the_stack_v2_python_sparse
RecoLuminosity/LumiDB/python/normFunctors.py
CMS-TMTT/cmssw
train
3
2723ffd6b932b9db413778020657721ede5807be
[ "if len(args) < 1:\n raise CommandError('Please specify an action. See --help.')\naction = args[0]\nemail = None\nif action not in self.valid_actions:\n message = 'Invalid action: %s' % action\n raise CommandError(message)\nif action in ['verify', 'delete']:\n if len(args) < 2:\n message = 'Pleas...
<|body_start_0|> if len(args) < 1: raise CommandError('Please specify an action. See --help.') action = args[0] email = None if action not in self.valid_actions: message = 'Invalid action: %s' % action raise CommandError(message) if action in [...
This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available.
Command
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available.""" def handle(self, *args, **options): """Parses/validates, and breaks off into actions.""" <|body_0...
stack_v2_sparse_classes_36k_train_028934
4,013
permissive
[ { "docstring": "Parses/validates, and breaks off into actions.", "name": "handle", "signature": "def handle(self, *args, **options)" }, { "docstring": "Given an action and an email (can be None), figure out what to do with the validated inputs. :param str action: The action. Must be one of self....
4
stack_v2_sparse_classes_30k_train_015920
Implement the Python class `Command` described below. Class description: This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available. Method signatures and docstrings: - def handle(self, *args, **options): Parses/va...
Implement the Python class `Command` described below. Class description: This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available. Method signatures and docstrings: - def handle(self, *args, **options): Parses/va...
cef29f01658c845564a5044b48b4cf19efcaa4d6
<|skeleton|> class Command: """This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available.""" def handle(self, *args, **options): """Parses/validates, and breaks off into actions.""" <|body_0...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: """This is a completely optional command used to manage the user's SES email addresses. Make sure to have 'seacucumber' in INSTALLED_APPS, or this won't be available.""" def handle(self, *args, **options): """Parses/validates, and breaks off into actions.""" if len(args) < 1: ...
the_stack_v2_python_sparse
vendor/seacucumber/management/commands/ses_address.py
quanganhdo/NewsBlur
train
1
3d7f56be7306c0264ab4a27f638a5b194de34ba2
[ "if etcd is None:\n raise ImportError('Missing python-etcd library')\nsuper().__init__(*args, **kwargs)", "port = connection.client.port or self.default_port\nhost = connection.client.hostname or DEFAULT_HOST\nlogger.debug('Verify Etcd connection to %s:%s', host, port)\ntry:\n etcd.Client(host=host, port=in...
<|body_start_0|> if etcd is None: raise ImportError('Missing python-etcd library') super().__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> port = connection.client.port or self.default_port host = connection.client.hostname or DEFAULT_HOST logger.debug('Ver...
Etcd storage Transport for Kombu.
Transport
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transport: """Etcd storage Transport for Kombu.""" def __init__(self, *args, **kwargs): """Create a new instance of etcd.Transport.""" <|body_0|> def verify_connection(self, connection): """Verify the connection works.""" <|body_1|> def driver_versio...
stack_v2_sparse_classes_36k_train_028935
8,644
permissive
[ { "docstring": "Create a new instance of etcd.Transport.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Verify the connection works.", "name": "verify_connection", "signature": "def verify_connection(self, connection)" }, { "docstring"...
3
null
Implement the Python class `Transport` described below. Class description: Etcd storage Transport for Kombu. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Create a new instance of etcd.Transport. - def verify_connection(self, connection): Verify the connection works. - def driver_version(se...
Implement the Python class `Transport` described below. Class description: Etcd storage Transport for Kombu. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Create a new instance of etcd.Transport. - def verify_connection(self, connection): Verify the connection works. - def driver_version(se...
c18e9626e1dec56fa58cfe384403b25f34fe4473
<|skeleton|> class Transport: """Etcd storage Transport for Kombu.""" def __init__(self, *args, **kwargs): """Create a new instance of etcd.Transport.""" <|body_0|> def verify_connection(self, connection): """Verify the connection works.""" <|body_1|> def driver_versio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Transport: """Etcd storage Transport for Kombu.""" def __init__(self, *args, **kwargs): """Create a new instance of etcd.Transport.""" if etcd is None: raise ImportError('Missing python-etcd library') super().__init__(*args, **kwargs) def verify_connection(self, c...
the_stack_v2_python_sparse
kombu/transport/etcd.py
celery/kombu
train
2,232
af3ab7f71d7b332746ac10170e534a54954bd0d9
[ "has_page = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True).count() > 0\npages = []\nif request.user.is_manager:\n pages = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True)\n active_page = None\nelse:\n active_page = webapp_models.Project.objects.filter...
<|body_start_0|> has_page = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True).count() > 0 pages = [] if request.user.is_manager: pages = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True) active_page = None else: ...
Pages
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pages: def get(request): """微页面列表页""" <|body_0|> def api_get(request): """微页面列表页""" <|body_1|> <|end_skeleton|> <|body_start_0|> has_page = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True).count() > 0 pages = [] ...
stack_v2_sparse_classes_36k_train_028936
2,795
no_license
[ { "docstring": "微页面列表页", "name": "get", "signature": "def get(request)" }, { "docstring": "微页面列表页", "name": "api_get", "signature": "def api_get(request)" } ]
2
null
Implement the Python class `Pages` described below. Class description: Implement the Pages class. Method signatures and docstrings: - def get(request): 微页面列表页 - def api_get(request): 微页面列表页
Implement the Python class `Pages` described below. Class description: Implement the Pages class. Method signatures and docstrings: - def get(request): 微页面列表页 - def api_get(request): 微页面列表页 <|skeleton|> class Pages: def get(request): """微页面列表页""" <|body_0|> def api_get(request): """...
8b2f7befe92841bcc35e0e60cac5958ef3f3af54
<|skeleton|> class Pages: def get(request): """微页面列表页""" <|body_0|> def api_get(request): """微页面列表页""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Pages: def get(request): """微页面列表页""" has_page = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True).count() > 0 pages = [] if request.user.is_manager: pages = webapp_models.Project.objects.filter(owner=request.manager, is_enable=True) ...
the_stack_v2_python_sparse
weapp/termite2/pages.py
chengdg/weizoom
train
1
1c6315bf1ee497701ab03a0319aa9cf1024b13f0
[ "url = '/dashboard/bookings'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)", "url = '/dashboard/bookings'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.s...
<|body_start_0|> url = '/dashboard/bookings' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302) <|end_body_0|> <|body_start_1|> url = '/dashboard/bookings' self.client.login(username=self.adminUN, password='pass') resp...
DashboardBookingsTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DashboardBookingsTestCase: def test_not_logged_in(self): """Test that the dashboard bookings view will redirect whilst not logged in.""" <|body_0|> def test_logged_in_admin(self): """Test that the dashboard bookings view will load whilst logged in as admin.""" ...
stack_v2_sparse_classes_36k_train_028937
26,818
permissive
[ { "docstring": "Test that the dashboard bookings view will redirect whilst not logged in.", "name": "test_not_logged_in", "signature": "def test_not_logged_in(self)" }, { "docstring": "Test that the dashboard bookings view will load whilst logged in as admin.", "name": "test_logged_in_admin"...
3
null
Implement the Python class `DashboardBookingsTestCase` described below. Class description: Implement the DashboardBookingsTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the dashboard bookings view will redirect whilst not logged in. - def test_logged_in_admin(self): Test t...
Implement the Python class `DashboardBookingsTestCase` described below. Class description: Implement the DashboardBookingsTestCase class. Method signatures and docstrings: - def test_not_logged_in(self): Test that the dashboard bookings view will redirect whilst not logged in. - def test_logged_in_admin(self): Test t...
37d2942efcbdaad072f7a06ac876a40e0f69f702
<|skeleton|> class DashboardBookingsTestCase: def test_not_logged_in(self): """Test that the dashboard bookings view will redirect whilst not logged in.""" <|body_0|> def test_logged_in_admin(self): """Test that the dashboard bookings view will load whilst logged in as admin.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DashboardBookingsTestCase: def test_not_logged_in(self): """Test that the dashboard bookings view will redirect whilst not logged in.""" url = '/dashboard/bookings' response = self.client.get(url, HTTP_HOST='website.domain') self.assertEqual(response.status_code, 302) def ...
the_stack_v2_python_sparse
mooring/test_views.py
dbca-wa/moorings
train
0
b7f1b6210a1383eb3c61c312eacef2c002b80fab
[ "\"\"\"\n 先计算两个单链表长度,利用两个指针,先让长度更长的单链表前进两者长度差的步数,然后两个指针同步前进,比较是否相等即可\n \"\"\"\nif not headA or not headB:\n return None\nlenA = lenB = 1\npointA, pointB = (headA, headB)\nwhile headA.next:\n headA = headA.next\n lenA += 1\nwhile headB.next:\n lenB += 1\n headB = headB.next\nif lenA > le...
<|body_start_0|> """ 先计算两个单链表长度,利用两个指针,先让长度更长的单链表前进两者长度差的步数,然后两个指针同步前进,比较是否相等即可 """ if not headA or not headB: return None lenA = lenB = 1 pointA, pointB = (headA, headB) while headA.next: headA = headA.next lenA...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode1(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_028938
1,686
no_license
[ { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode", "signature": "def getIntersectionNode(self, headA, headB)" }, { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode1", "signature": "def getIntersectionNo...
2
stack_v2_sparse_classes_30k_train_021112
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode1(self, headA, headB): :type head1, head1: ListNode :rtype: Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode1(self, headA, headB): :type head1, head1: ListNode :rtype: Li...
e8eae749e77be21716ada6019db4c39d3f00989c
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode1(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" """ 先计算两个单链表长度,利用两个指针,先让长度更长的单链表前进两者长度差的步数,然后两个指针同步前进,比较是否相等即可 """ if not headA or not headB: return None lenA = lenB = 1 ...
the_stack_v2_python_sparse
linked list/160. Intersection of Two Linked Lists.py
zazaliu/leetcode-python
train
1
57c6cdc3b58dd5f69d7f8dd535e31f72e5bbe01f
[ "if self.template_name is None:\n flow_task = self.activation.flow_task\n opts = self.activation.flow_task.flow_class._meta\n return ('{}/{}/{}_detail.html'.format(opts.app_label, opts.flow_label, flow_task.name), '{}/{}/task_detail.html'.format(opts.app_label, opts.flow_label), 'viewflow/flow/task_detail....
<|body_start_0|> if self.template_name is None: flow_task = self.activation.flow_task opts = self.activation.flow_task.flow_class._meta return ('{}/{}/{}_detail.html'.format(opts.app_label, opts.flow_label, flow_task.name), '{}/{}/task_detail.html'.format(opts.app_label, opts...
Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages.
DetailTaskView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DetailTaskView: """Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages.""" def get_template_names(self): """List of template names to be used for a process detail page. If `template_name` is None, default value is:: [<app_label>...
stack_v2_sparse_classes_36k_train_028939
3,254
permissive
[ { "docstring": "List of template names to be used for a process detail page. If `template_name` is None, default value is:: [<app_label>/<flow_label>/<task_name>_detail.html, <app_label>/<flow_label>/task_detail.html, 'viewflow/flow/task_detail.html']", "name": "get_template_names", "signature": "def ge...
3
stack_v2_sparse_classes_30k_train_005766
Implement the Python class `DetailTaskView` described below. Class description: Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages. Method signatures and docstrings: - def get_template_names(self): List of template names to be used for a process detail page. If...
Implement the Python class `DetailTaskView` described below. Class description: Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages. Method signatures and docstrings: - def get_template_names(self): List of template names to be used for a process detail page. If...
0267168bb90e8e9c85aecdd715972b9622b82384
<|skeleton|> class DetailTaskView: """Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages.""" def get_template_names(self): """List of template names to be used for a process detail page. If `template_name` is None, default value is:: [<app_label>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DetailTaskView: """Default detail view for the flow task. Get confirmation from user, assigns task and redirects to task pages.""" def get_template_names(self): """List of template names to be used for a process detail page. If `template_name` is None, default value is:: [<app_label>/<flow_label>...
the_stack_v2_python_sparse
Scripts/ict/viewflow/flow/views/detail.py
mspgeek/Client_Portal
train
6
3bd7ba2537b10a6df92bdededc43139c76861a0d
[ "if request.args.get('pass_id'):\n data = db.session.query(Tenant).filter(Tenant.pass_id == request.args.get('pass_id')).first()\n return marshal(data, ten_struct) if data else 'No such tenant!'\nelif not request.args:\n data = db.session.query(Tenant).all()\n return marshal(data, ten_struct)\nelse:\n ...
<|body_start_0|> if request.args.get('pass_id'): data = db.session.query(Tenant).filter(Tenant.pass_id == request.args.get('pass_id')).first() return marshal(data, ten_struct) if data else 'No such tenant!' elif not request.args: data = db.session.query(Tenant).all() ...
TenantsRes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TenantsRes: def get(self): """Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return:""" <|body_0|> def post(self): """Add new tenant to DB (without address) :return:""" <|body_1|> def delete(self): """Delete...
stack_v2_sparse_classes_36k_train_028940
2,554
no_license
[ { "docstring": "Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "Add new tenant to DB (without address) :return:", "name": "post", "signature": "def post(self)" }, { "doc...
4
stack_v2_sparse_classes_30k_train_018045
Implement the Python class `TenantsRes` described below. Class description: Implement the TenantsRes class. Method signatures and docstrings: - def get(self): Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return: - def post(self): Add new tenant to DB (without address) :return:...
Implement the Python class `TenantsRes` described below. Class description: Implement the TenantsRes class. Method signatures and docstrings: - def get(self): Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return: - def post(self): Add new tenant to DB (without address) :return:...
d3759f773f9abc0e917e75c174c28feb7d4a0692
<|skeleton|> class TenantsRes: def get(self): """Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return:""" <|body_0|> def post(self): """Add new tenant to DB (without address) :return:""" <|body_1|> def delete(self): """Delete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TenantsRes: def get(self): """Get particular tenant by pass_id if '?pass_id=' specified or get all tenants if not. :return:""" if request.args.get('pass_id'): data = db.session.query(Tenant).filter(Tenant.pass_id == request.args.get('pass_id')).first() return marshal(da...
the_stack_v2_python_sparse
rest_alchemy/tenants/routes.py
serhiihoriaiev/common
train
0
4053fdb2d58aa73ed020015a2ce7d02cb4dd9a7f
[ "self.head = head\nself.current = head\nself.length = 1", "iter = self.head\noutput = []\nin_loop = False\nwhile iter is not None:\n if in_loop and iter == self.head:\n break\n if iter == self.current:\n output.append('(%s)' % iter.data)\n else:\n output.append(str(iter.data))\n i...
<|body_start_0|> self.head = head self.current = head self.length = 1 <|end_body_0|> <|body_start_1|> iter = self.head output = [] in_loop = False while iter is not None: if in_loop and iter == self.head: break if iter == s...
Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The list has a "head" pointer to the first item in the list (arbitrarily chosen in the c...
DoubleLinkedList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DoubleLinkedList: """Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The list has a "head" pointer to the first i...
stack_v2_sparse_classes_36k_train_028941
8,037
no_license
[ { "docstring": "Initialization function for a double linked list. :param head: Reference to the first node in the list. :type head: DoubleLinkedListNode", "name": "__init__", "signature": "def __init__(self, head)" }, { "docstring": "Util function to display the double linked list, starting from...
5
stack_v2_sparse_classes_30k_train_021583
Implement the Python class `DoubleLinkedList` described below. Class description: Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The l...
Implement the Python class `DoubleLinkedList` described below. Class description: Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The l...
87011a22d5f1ebd1e7064c043678c3cdb02414e8
<|skeleton|> class DoubleLinkedList: """Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The list has a "head" pointer to the first i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DoubleLinkedList: """Util class to implement a double linked list, i.e. a linked list where items both have a connection to the previous and the next node. The list is circular, meaning that the successor of the last node is the first node in the list. The list has a "head" pointer to the first item in the li...
the_stack_v2_python_sparse
2018/Python/day9.py
MinaPecheux/Advent-Of-Code
train
0
392e13a14c9614d39a6ae478afd18406c5ce23eb
[ "print('Received PUT on resource /books/<book_id>/notes/<note_title>')\nif book_id.isdigit():\n note = NoteChecker.update_note(book_id, note_title, request.get_json())\n return (note, 200)\nelse:\n abort(400, 'Invalid input for book_id')", "print('Received DELETE on resource /books/<book_id>/notes/<note_...
<|body_start_0|> print('Received PUT on resource /books/<book_id>/notes/<note_title>') if book_id.isdigit(): note = NoteChecker.update_note(book_id, note_title, request.get_json()) return (note, 200) else: abort(400, 'Invalid input for book_id') <|end_body_0|>...
BookNotes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BookNotes: def put(self, book_id, note_title): """Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :param note_title: Record for a note. :return: JSON of note according to return_note_marshaller.""" ...
stack_v2_sparse_classes_36k_train_028942
14,158
no_license
[ { "docstring": "Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :param note_title: Record for a note. :return: JSON of note according to return_note_marshaller.", "name": "put", "signature": "def put(self, book_id, n...
2
stack_v2_sparse_classes_30k_train_009102
Implement the Python class `BookNotes` described below. Class description: Implement the BookNotes class. Method signatures and docstrings: - def put(self, book_id, note_title): Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :par...
Implement the Python class `BookNotes` described below. Class description: Implement the BookNotes class. Method signatures and docstrings: - def put(self, book_id, note_title): Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :par...
4c3fdf41a43a56c253faecacac5f9d977d9c99be
<|skeleton|> class BookNotes: def put(self, book_id, note_title): """Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :param note_title: Record for a note. :return: JSON of note according to return_note_marshaller.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BookNotes: def put(self, book_id, note_title): """Edit a specific note for a book. Valid input for JSON are fields in the amend_note_marshaller model. :param book_id: Record for a book. :param note_title: Record for a note. :return: JSON of note according to return_note_marshaller.""" print('R...
the_stack_v2_python_sparse
apis/books_api.py
neu-seattle-cs5500-fall18/book-library-web-service-scrumptious
train
0
38f0fbfc732b09b18ad15d1f196edffac1108e05
[ "s_left, s_last, s_len, p_left, p_last, p_len = (0, -1, len(s), 0, -1, len(p))\nwhile s_left < s_len:\n if p_left < p_len and (s[s_left] == p[p_left] or p[p_left] == '?'):\n s_left += 1\n p_left += 1\n elif p_left < p_len and p[p_left] == '*':\n p_left += 1\n s_last = s_left\n ...
<|body_start_0|> s_left, s_last, s_len, p_left, p_last, p_len = (0, -1, len(s), 0, -1, len(p)) while s_left < s_len: if p_left < p_len and (s[s_left] == p[p_left] or p[p_left] == '?'): s_left += 1 p_left += 1 elif p_left < p_len and p[p_left] == '*...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_0|> def isMatch_failed(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> s_left, s_last, s_len, p_left, p_las...
stack_v2_sparse_classes_36k_train_028943
3,116
no_license
[ { "docstring": ":type s: str :type p: str :rtype: bool", "name": "isMatch", "signature": "def isMatch(self, s, p)" }, { "docstring": ":type s: str :type p: str :rtype: bool", "name": "isMatch_failed", "signature": "def isMatch_failed(self, s, p)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch_failed(self, s, p): :type s: str :type p: str :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isMatch(self, s, p): :type s: str :type p: str :rtype: bool - def isMatch_failed(self, s, p): :type s: str :type p: str :rtype: bool <|skeleton|> class Solution: def is...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_0|> def isMatch_failed(self, s, p): """:type s: str :type p: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isMatch(self, s, p): """:type s: str :type p: str :rtype: bool""" s_left, s_last, s_len, p_left, p_last, p_len = (0, -1, len(s), 0, -1, len(p)) while s_left < s_len: if p_left < p_len and (s[s_left] == p[p_left] or p[p_left] == '?'): s_left += ...
the_stack_v2_python_sparse
src/lt_44.py
oxhead/CodingYourWay
train
0
5cabbc61e0059b94a9ce16b69cbf8a1a3ff01bde
[ "nvars = 3\nsuper().__init__(init=(nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', 'Vs', 'Rs', 'C1', 'Rpi', 'Lpi', 'C2', 'Rl', localVars=locals(), readOnly=True)\nself.A = np.zeros((3, 3))\nself.A[0, 0] = -1 / (self.Rs * self.C1)\nself.A[0, 2] = -1 / self.C1\nself.A[1, 1] = -1 / (self.Rl...
<|body_start_0|> nvars = 3 super().__init__(init=(nvars, None, np.dtype('float64'))) self._makeAttributeAndRegister('nvars', 'Vs', 'Rs', 'C1', 'Rpi', 'Lpi', 'C2', 'Rl', localVars=locals(), readOnly=True) self.A = np.zeros((3, 3)) self.A[0, 0] = -1 / (self.Rs * self.C1) se...
Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t)}{dt} = -\\frac{1}{R_s C_1}v_{C_1} (t) - \\frac{1}{C_1} i_{L_\\pi} (t) +...
piline
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class piline: """Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t)}{dt} = -\\frac{1}{R_s C_1}v_{C_1} (t)...
stack_v2_sparse_classes_36k_train_028944
5,014
permissive
[ { "docstring": "Initialization routine", "name": "__init__", "signature": "def __init__(self, Vs=100.0, Rs=1.0, C1=1.0, Rpi=0.2, Lpi=1.0, C2=1.0, Rl=5.0)" }, { "docstring": "Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical ...
4
null
Implement the Python class `piline` described below. Class description: Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t...
Implement the Python class `piline` described below. Class description: Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class piline: """Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t)}{dt} = -\\frac{1}{R_s C_1}v_{C_1} (t)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class piline: """Example implementing the model of the piline. It serves as a transmission line in an energy grid. The problem of simulating the piline consists of three ordinary differential equations (ODEs) with nonhomogeneous part: .. math:: \\frac{d v_{C_1} (t)}{dt} = -\\frac{1}{R_s C_1}v_{C_1} (t) - \\frac{1}{...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/Piline.py
Parallel-in-Time/pySDC
train
30
26785751065b87146ccd135f98b0c68a1ef80a91
[ "res = GraphConnection().get_graph_connect()\ngraph_id = res[1]['data']['records'][0]['id']\nreturn graph_id", "res = GraphConnection().get_graph_connect()\ngraph_id = res[1]['data']['records'][0]['id']\nres = Load.query_load_job(graph_id)\njob_id = res[1]['data']['records'][0]['id']\nreturn (graph_id, job_id)", ...
<|body_start_0|> res = GraphConnection().get_graph_connect() graph_id = res[1]['data']['records'][0]['id'] return graph_id <|end_body_0|> <|body_start_1|> res = GraphConnection().get_graph_connect() graph_id = res[1]['data']['records'][0]['id'] res = Load.query_load_job(...
提供case需要的ID
ID
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ID: """提供case需要的ID""" def get_graph_id(): """获取图ID""" <|body_0|> def get_job_id(): """获取图ID,和任务ID""" <|body_1|> def get_file_id(): """获取ID,任务ID和文件ID""" <|body_2|> def get_task_id(): """获取图ID,任务ID,文件ID和任务ID""" <|bo...
stack_v2_sparse_classes_36k_train_028945
26,078
no_license
[ { "docstring": "获取图ID", "name": "get_graph_id", "signature": "def get_graph_id()" }, { "docstring": "获取图ID,和任务ID", "name": "get_job_id", "signature": "def get_job_id()" }, { "docstring": "获取ID,任务ID和文件ID", "name": "get_file_id", "signature": "def get_file_id()" }, { ...
6
stack_v2_sparse_classes_30k_train_008467
Implement the Python class `ID` described below. Class description: 提供case需要的ID Method signatures and docstrings: - def get_graph_id(): 获取图ID - def get_job_id(): 获取图ID,和任务ID - def get_file_id(): 获取ID,任务ID和文件ID - def get_task_id(): 获取图ID,任务ID,文件ID和任务ID - def get_vertexMapping_id(): 获取图ID,任务ID,文件ID和顶点映射ID - def get_edg...
Implement the Python class `ID` described below. Class description: 提供case需要的ID Method signatures and docstrings: - def get_graph_id(): 获取图ID - def get_job_id(): 获取图ID,和任务ID - def get_file_id(): 获取ID,任务ID和文件ID - def get_task_id(): 获取图ID,任务ID,文件ID和任务ID - def get_vertexMapping_id(): 获取图ID,任务ID,文件ID和顶点映射ID - def get_edg...
89e5b34ab925bcc0bbc4ad63302e96c62a420399
<|skeleton|> class ID: """提供case需要的ID""" def get_graph_id(): """获取图ID""" <|body_0|> def get_job_id(): """获取图ID,和任务ID""" <|body_1|> def get_file_id(): """获取ID,任务ID和文件ID""" <|body_2|> def get_task_id(): """获取图ID,任务ID,文件ID和任务ID""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ID: """提供case需要的ID""" def get_graph_id(): """获取图ID""" res = GraphConnection().get_graph_connect() graph_id = res[1]['data']['records'][0]['id'] return graph_id def get_job_id(): """获取图ID,和任务ID""" res = GraphConnection().get_graph_connect() grap...
the_stack_v2_python_sparse
src/common/hubble_api.py
hugegraph/hugegraph-test
train
1
855e5f2046b49958a008826354dcbad7d7df412c
[ "serial = []\nif not root:\n return serial\nQ = [root]\nwhile Q:\n u = Q.pop(0)\n if u:\n serial.append(u.val)\n Q.append(u.left)\n Q.append(u.right)\n else:\n serial.append(None)\nreturn serial", "n = len(data)\nif not n:\n return None\nroot = TreeNode(data[0])\nQ = [ro...
<|body_start_0|> serial = [] if not root: return serial Q = [root] while Q: u = Q.pop(0) if u: serial.append(u.val) Q.append(u.left) Q.append(u.right) else: serial.append(None)...
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_028946
1,858
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
418172cee1bf48bb2aed3b84fe8b4defd9ef4fdf
<|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""" serial = [] if not root: return serial Q = [root] while Q: u = Q.pop(0) if u: serial.append(u.val) ...
the_stack_v2_python_sparse
Serialize and Deserialize Binary Tree.py
TianyaoHua/LeetCodeSolutions
train
0
5e7b52ecb441c4972fd4855ac4edcc1747d8f79f
[ "super(UpNet, self).__init__()\nself.layer_1 = UpNetLayer_ParticularEncoder_2(in_channels, 64, 2)\nself.layer_2 = UpNetLayer_Encoder(64, 128, 2)\nself.layer_3 = UpNetLayer_Encoder(128, 256, 3)\nself.layer_4 = UpNetLayer_Encoder(256, 512, 3)\nself.layer_6 = UpNetLayer_ParticularEncoder(512, 1024, 3)\nself.layer_inte...
<|body_start_0|> super(UpNet, self).__init__() self.layer_1 = UpNetLayer_ParticularEncoder_2(in_channels, 64, 2) self.layer_2 = UpNetLayer_Encoder(64, 128, 2) self.layer_3 = UpNetLayer_Encoder(128, 256, 3) self.layer_4 = UpNetLayer_Encoder(256, 512, 3) self.layer_6 = UpNe...
Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Gabriel L. Oliveira, Wolfram Burgard and Thomas Brox
UpNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpNet: """Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Gabriel L. Oliveira, Wolfram Burgard and ...
stack_v2_sparse_classes_36k_train_028947
20,094
no_license
[ { "docstring": "Sequential Instanciation of the different Layers", "name": "__init__", "signature": "def __init__(self, in_channels=3, n_classes=21)" }, { "docstring": "Sequential Computation, see nn.Module.forward methods PyTorch", "name": "forward", "signature": "def forward(self, inpu...
2
stack_v2_sparse_classes_30k_train_004470
Implement the Python class `UpNet` described below. Class description: Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Ga...
Implement the Python class `UpNet` described below. Class description: Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Ga...
3b63f360e67013d5962082e57fb36ebfb37d8920
<|skeleton|> class UpNet: """Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Gabriel L. Oliveira, Wolfram Burgard and ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpNet: """Derived Class to define a UpNet Architecture of NN Attributes ---------- in_channels : int The input size of the network. n_classes : int The output size of the network. References ---------- Efficient Deep Models for Monocular Road Segmentation Gabriel L. Oliveira, Wolfram Burgard and Thomas Brox""...
the_stack_v2_python_sparse
segmentation/models/nn.py
Kivo0/vibotorch
train
0
7f88013ee78a015c7b76312bf6d6339e007671cd
[ "all_positions = set(itertools.product(set(range(self.grid_size)), list(range(self.grid_size))))\navailable_positions = all_positions - self._occupied_positions\nrelative_positions = set(DIR_TO_DIR_VEC.keys())\nif exclude_locations is not None:\n relative_positions = relative_positions - set(exclude_locations)\n...
<|body_start_0|> all_positions = set(itertools.product(set(range(self.grid_size)), list(range(self.grid_size)))) available_positions = all_positions - self._occupied_positions relative_positions = set(DIR_TO_DIR_VEC.keys()) if exclude_locations is not None: relative_positions...
The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py for more details.
RelationWorld
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelationWorld: """The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py for more details.""" def get_nearb...
stack_v2_sparse_classes_36k_train_028948
3,796
permissive
[ { "docstring": "Return a list of available positions that are next to the given position.", "name": "get_nearby_positions", "signature": "def get_nearby_positions(self, position, exclude_locations=None)" }, { "docstring": "Sample an available position that is next to the given position.", "n...
4
stack_v2_sparse_classes_30k_train_008936
Implement the Python class `RelationWorld` described below. Class description: The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py ...
Implement the Python class `RelationWorld` described below. Class description: The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py ...
ac9447064195e06de48cc91ff642f7fffa28ffe8
<|skeleton|> class RelationWorld: """The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py for more details.""" def get_nearb...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelationWorld: """The world class that considers object spatial relations. Similar to the original gSCAN world state but allows sampling positions basaed on specific conditions. See https://github.com/LauraRuis/groundedSCAN/blob/master/GroundedScan/world.py for more details.""" def get_nearby_positions(s...
the_stack_v2_python_sparse
language/gscan/data/world.py
google-research/language
train
1,567
7139f30dd8dca193b6982574c28e271f75294db1
[ "self.pid_type = pid_type\nself.object_type = object_type\nself.object_getter = getter", "pid = PersistentIdentifier.get(self.pid_type, pid_value)\nif pid.is_new() or pid.is_reserved():\n raise PIDUnregistered(pid)\nif pid.is_deleted():\n obj_id = pid.get_assigned_object(object_type=self.object_type)\n t...
<|body_start_0|> self.pid_type = pid_type self.object_type = object_type self.object_getter = getter <|end_body_0|> <|body_start_1|> pid = PersistentIdentifier.get(self.pid_type, pid_value) if pid.is_new() or pid.is_reserved(): raise PIDUnregistered(pid) if p...
Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.
Resolver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resolver: """Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.""" def __init__(self, pid_type=None, object_type=None, getter=None): """Initialize resolver. :param pid_type: Persistent identifier type. :param object_type:...
stack_v2_sparse_classes_36k_train_028949
2,856
no_license
[ { "docstring": "Initialize resolver. :param pid_type: Persistent identifier type. :param object_type: Object type. :param getter: Callable that will take an object id for the given object type and retrieve the internal object.", "name": "__init__", "signature": "def __init__(self, pid_type=None, object_...
2
stack_v2_sparse_classes_30k_train_005221
Implement the Python class `Resolver` described below. Class description: Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier. Method signatures and docstrings: - def __init__(self, pid_type=None, object_type=None, getter=None): Initialize resolver. :param ...
Implement the Python class `Resolver` described below. Class description: Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier. Method signatures and docstrings: - def __init__(self, pid_type=None, object_type=None, getter=None): Initialize resolver. :param ...
54eb34c7e1594cc50a5347ba93e12a991ba8b7f3
<|skeleton|> class Resolver: """Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.""" def __init__(self, pid_type=None, object_type=None, getter=None): """Initialize resolver. :param pid_type: Persistent identifier type. :param object_type:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Resolver: """Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.""" def __init__(self, pid_type=None, object_type=None, getter=None): """Initialize resolver. :param pid_type: Persistent identifier type. :param object_type: Object type....
the_stack_v2_python_sparse
.virtualenvs/invenio/lib/python2.7/site-packages/invenio_pidstore/resolver.py
N03/invenio
train
0
fc536323fa700c2846fddf9a6c7a899bca4580c4
[ "length = len(nums)\nif length == 0:\n return 0\nif length <= 3:\n return max(nums)\nres1 = self.single_rob(nums[:-1])\nres2 = self.single_rob(nums[1:])\nres = max(res1, res2)\nreturn res", "length = len(nums)\nif length == 0:\n return 0\nif length <= 2:\n return max(nums)\ndp = [0] * length\ndp[0] = ...
<|body_start_0|> length = len(nums) if length == 0: return 0 if length <= 3: return max(nums) res1 = self.single_rob(nums[:-1]) res2 = self.single_rob(nums[1:]) res = max(res1, res2) return res <|end_body_0|> <|body_start_1|> lengt...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def single_rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> length = len(nums) if length == 0: ...
stack_v2_sparse_classes_36k_train_028950
1,127
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "single_rob", "signature": "def single_rob(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def single_rob(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): :type nums: List[int] :rtype: int - def single_rob(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def rob(self, nums): ...
1d1ffe25d8b49832acc1791261c959ce436a6362
<|skeleton|> class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def single_rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rob(self, nums): """:type nums: List[int] :rtype: int""" length = len(nums) if length == 0: return 0 if length <= 3: return max(nums) res1 = self.single_rob(nums[:-1]) res2 = self.single_rob(nums[1:]) res = max(res1,...
the_stack_v2_python_sparse
00-每日一题/20200324_213.py
qiaozhi827/leetcode-1
train
0
03f4bb5fb6a696e9a67e4ab80650ea1333a856c3
[ "super(BoundedRandomDisplacement, self).__init__(stepsize)\nif bounds is None:\n self.bounds_min = -np.infty\n self.bounds_max = np.infty\nelse:\n bounds_np = np.array(bounds)\n self.bounds_min = bounds_np[:, 0]\n self.bounds_max = bounds_np[:, 1]\nreturn", "new_x = super(BoundedRandomDisplacement,...
<|body_start_0|> super(BoundedRandomDisplacement, self).__init__(stepsize) if bounds is None: self.bounds_min = -np.infty self.bounds_max = np.infty else: bounds_np = np.array(bounds) self.bounds_min = bounds_np[:, 0] self.bounds_max = ...
Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping.
BoundedRandomDisplacement
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BoundedRandomDisplacement: """Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping.""" def __init__(self, stepsize: float=1.0, bounds: list=None): """Constructor. :param stepsize: maximum length of step; :param bounds: bounds ...
stack_v2_sparse_classes_36k_train_028951
12,561
permissive
[ { "docstring": "Constructor. :param stepsize: maximum length of step; :param bounds: bounds for the search of the optimum x.", "name": "__init__", "signature": "def __init__(self, stepsize: float=1.0, bounds: list=None)" }, { "docstring": "Compute the new x and clips it to the bounds. :param x: ...
2
stack_v2_sparse_classes_30k_train_001212
Implement the Python class `BoundedRandomDisplacement` described below. Class description: Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping. Method signatures and docstrings: - def __init__(self, stepsize: float=1.0, bounds: list=None): Constructor. :param...
Implement the Python class `BoundedRandomDisplacement` described below. Class description: Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping. Method signatures and docstrings: - def __init__(self, stepsize: float=1.0, bounds: list=None): Constructor. :param...
02dd3eca8574899fd3f0e287b1a050e76e5ba0de
<|skeleton|> class BoundedRandomDisplacement: """Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping.""" def __init__(self, stepsize: float=1.0, bounds: list=None): """Constructor. :param stepsize: maximum length of step; :param bounds: bounds ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BoundedRandomDisplacement: """Class that overwrites the RandomDisplacement one, default for scipy basinhopping, and adds the bounds clipping.""" def __init__(self, stepsize: float=1.0, bounds: list=None): """Constructor. :param stepsize: maximum length of step; :param bounds: bounds for the searc...
the_stack_v2_python_sparse
odin/utils/tensorflow_optimizer.py
sdi1100041/SLEIPNIR
train
3
5500cd86914e48c0f808bc3c35ac9dd28d730ce3
[ "if not self.enabled:\n comm = getattr(communicator, self.__class__.__name__)(self._PyTravisCI['com']['requester'])\n self.__dict__ = comm.update(beta_feature_id=self.id, data={'beta_feature.enabled': False}, **self._PyTravisCI['shared']).__dict__\nreturn self.enabled", "if self.enabled:\n comm = getattr...
<|body_start_0|> if not self.enabled: comm = getattr(communicator, self.__class__.__name__)(self._PyTravisCI['com']['requester']) self.__dict__ = comm.update(beta_feature_id=self.id, data={'beta_feature.enabled': False}, **self._PyTravisCI['shared']).__dict__ return self.enabled ...
Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description of the feature. :ivar bool enabled: Indi...
BetaFeature
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BetaFeature: """Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description o...
stack_v2_sparse_classes_36k_train_028952
3,908
permissive
[ { "docstring": "Enables the current beta feature.", "name": "enable", "signature": "def enable(self) -> bool" }, { "docstring": "Disables the current beta feature.", "name": "disable", "signature": "def disable(self) -> bool" }, { "docstring": "Deletes the current beta feature. :...
3
stack_v2_sparse_classes_30k_train_021198
Implement the Python class `BetaFeature` described below. Class description: Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :iva...
Implement the Python class `BetaFeature` described below. Class description: Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :iva...
20a4bad3b05908b7371744b367ba7a33c289b83e
<|skeleton|> class BetaFeature: """Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BetaFeature: """Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description of the feature...
the_stack_v2_python_sparse
PyTravisCI/resource_types/beta_feature.py
funilrys/PyTravisCI
train
4
e484535231d77f3b6d743eddd8c9a7547fe78274
[ "super(Reranker, self).__init__(auto_prefix=False)\nself.encoder = Albert(batch_size)\nparam_dict = load_checkpoint(encoder_ck_file)\nnot_load_params_1, _ = load_param_into_net(self.encoder, param_dict)\nprint(f're-ranker albert not loaded params: {not_load_params_1}')\nself.no_answer_mlp = Rerank_Downstream()\npar...
<|body_start_0|> super(Reranker, self).__init__(auto_prefix=False) self.encoder = Albert(batch_size) param_dict = load_checkpoint(encoder_ck_file) not_load_params_1, _ = load_param_into_net(self.encoder, param_dict) print(f're-ranker albert not loaded params: {not_load_params_1}'...
Reranker model
Reranker
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Reranker: """Reranker model""" def __init__(self, batch_size, encoder_ck_file, downstream_ck_file): """init function""" <|body_0|> def construct(self, input_ids, attn_mask, token_type_ids): """construct function""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_028953
1,850
permissive
[ { "docstring": "init function", "name": "__init__", "signature": "def __init__(self, batch_size, encoder_ck_file, downstream_ck_file)" }, { "docstring": "construct function", "name": "construct", "signature": "def construct(self, input_ids, attn_mask, token_type_ids)" } ]
2
stack_v2_sparse_classes_30k_train_013828
Implement the Python class `Reranker` described below. Class description: Reranker model Method signatures and docstrings: - def __init__(self, batch_size, encoder_ck_file, downstream_ck_file): init function - def construct(self, input_ids, attn_mask, token_type_ids): construct function
Implement the Python class `Reranker` described below. Class description: Reranker model Method signatures and docstrings: - def __init__(self, batch_size, encoder_ck_file, downstream_ck_file): init function - def construct(self, input_ids, attn_mask, token_type_ids): construct function <|skeleton|> class Reranker: ...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class Reranker: """Reranker model""" def __init__(self, batch_size, encoder_ck_file, downstream_ck_file): """init function""" <|body_0|> def construct(self, input_ids, attn_mask, token_type_ids): """construct function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Reranker: """Reranker model""" def __init__(self, batch_size, encoder_ck_file, downstream_ck_file): """init function""" super(Reranker, self).__init__(auto_prefix=False) self.encoder = Albert(batch_size) param_dict = load_checkpoint(encoder_ck_file) not_load_params...
the_stack_v2_python_sparse
research/nlp/tprr/src/reranker.py
mindspore-ai/models
train
301
1c43649d6b4289a21dd0ea87d266f9b83ae7fe16
[ "url = 'os-hypervisors'\nschema = self.get_schema(self.schema_versions_info)\n_schema = schema.list_search_hypervisors\nif detail:\n url += '/detail'\n _schema = schema.list_hypervisors_detail\nif kwargs:\n url += '?%s' % urllib.urlencode(kwargs)\nresp, body = self.get(url)\nbody = json.loads(body)\nself.v...
<|body_start_0|> url = 'os-hypervisors' schema = self.get_schema(self.schema_versions_info) _schema = schema.list_search_hypervisors if detail: url += '/detail' _schema = schema.list_hypervisors_detail if kwargs: url += '?%s' % urllib.urlencode...
HypervisorClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HypervisorClient: def list_hypervisors(self, detail=False, **kwargs): """List hypervisors information.""" <|body_0|> def show_hypervisor(self, hypervisor_id, **kwargs): """Display the details of the specified hypervisor.""" <|body_1|> def list_servers_on...
stack_v2_sparse_classes_36k_train_028954
4,358
permissive
[ { "docstring": "List hypervisors information.", "name": "list_hypervisors", "signature": "def list_hypervisors(self, detail=False, **kwargs)" }, { "docstring": "Display the details of the specified hypervisor.", "name": "show_hypervisor", "signature": "def show_hypervisor(self, hyperviso...
6
stack_v2_sparse_classes_30k_train_014291
Implement the Python class `HypervisorClient` described below. Class description: Implement the HypervisorClient class. Method signatures and docstrings: - def list_hypervisors(self, detail=False, **kwargs): List hypervisors information. - def show_hypervisor(self, hypervisor_id, **kwargs): Display the details of the...
Implement the Python class `HypervisorClient` described below. Class description: Implement the HypervisorClient class. Method signatures and docstrings: - def list_hypervisors(self, detail=False, **kwargs): List hypervisors information. - def show_hypervisor(self, hypervisor_id, **kwargs): Display the details of the...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class HypervisorClient: def list_hypervisors(self, detail=False, **kwargs): """List hypervisors information.""" <|body_0|> def show_hypervisor(self, hypervisor_id, **kwargs): """Display the details of the specified hypervisor.""" <|body_1|> def list_servers_on...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HypervisorClient: def list_hypervisors(self, detail=False, **kwargs): """List hypervisors information.""" url = 'os-hypervisors' schema = self.get_schema(self.schema_versions_info) _schema = schema.list_search_hypervisors if detail: url += '/detail' ...
the_stack_v2_python_sparse
tempest/lib/services/compute/hypervisor_client.py
openstack/tempest
train
270
49424f28451f9046cae9f98a1b8c11a6feeef880
[ "it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\nself.s = uinput()\nself.cnt = {}\nfor c in self.s:\n self.cnt[c] = self.cnt.get(c, 0) + 1\nself.pcnt = dict(self.cnt)\nfor i in reversed(sorted(self.pcnt)):\n if self.p...
<|body_start_0|> it = iter(test_inputs.split('\n')) if test_inputs else None def uinput(): return next(it) if it else sys.stdin.readline().rstrip() self.s = uinput() self.cnt = {} for c in self.s: self.cnt[c] = self.cnt.get(c, 0) + 1 self.pcnt = d...
Palindrom representation
Palindrom
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Palindrom: """Palindrom representation""" def __init__(self, test_inputs=None): """Default constructor""" <|body_0|> def calculate(self): """Main calcualtion function of the class""" <|body_1|> <|end_skeleton|> <|body_start_0|> it = iter(test_in...
stack_v2_sparse_classes_36k_train_028955
3,524
permissive
[ { "docstring": "Default constructor", "name": "__init__", "signature": "def __init__(self, test_inputs=None)" }, { "docstring": "Main calcualtion function of the class", "name": "calculate", "signature": "def calculate(self)" } ]
2
stack_v2_sparse_classes_30k_train_018344
Implement the Python class `Palindrom` described below. Class description: Palindrom representation Method signatures and docstrings: - def __init__(self, test_inputs=None): Default constructor - def calculate(self): Main calcualtion function of the class
Implement the Python class `Palindrom` described below. Class description: Palindrom representation Method signatures and docstrings: - def __init__(self, test_inputs=None): Default constructor - def calculate(self): Main calcualtion function of the class <|skeleton|> class Palindrom: """Palindrom representation...
ae02ea872ca91ef98630cc172a844b82cc56f621
<|skeleton|> class Palindrom: """Palindrom representation""" def __init__(self, test_inputs=None): """Default constructor""" <|body_0|> def calculate(self): """Main calcualtion function of the class""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Palindrom: """Palindrom representation""" def __init__(self, test_inputs=None): """Default constructor""" it = iter(test_inputs.split('\n')) if test_inputs else None def uinput(): return next(it) if it else sys.stdin.readline().rstrip() self.s = uinput() ...
the_stack_v2_python_sparse
codeforces/600C_palindrom.py
snsokolov/contests
train
1
218f09cbd1ac47f44bb675b5098e316f72177bc9
[ "system_resource_type_dict = iam.list_resource_type(system_ids)\nsystem_resource_types = {}\nfor system_id, resource_types in system_resource_type_dict.items():\n system_resource_types[system_id] = [ResourceType(**i) for i in resource_types]\nreturn system_resource_types", "if not system_ids:\n return Resou...
<|body_start_0|> system_resource_type_dict = iam.list_resource_type(system_ids) system_resource_types = {} for system_id, resource_types in system_resource_type_dict.items(): system_resource_types[system_id] = [ResourceType(**i) for i in resource_types] return system_resource...
ResourceTypeService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceTypeService: def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]: """批量获取多个系统的资源类别""" <|body_0|> def get_resource_type_dict(self, system_ids: List[str]) -> ResourceTypeDict: """获取resource type name provider""" ...
stack_v2_sparse_classes_36k_train_028956
1,982
permissive
[ { "docstring": "批量获取多个系统的资源类别", "name": "list_resource_type_by_systems", "signature": "def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]" }, { "docstring": "获取resource type name provider", "name": "get_resource_type_dict", "signature": "def g...
2
stack_v2_sparse_classes_30k_train_015905
Implement the Python class `ResourceTypeService` described below. Class description: Implement the ResourceTypeService class. Method signatures and docstrings: - def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]: 批量获取多个系统的资源类别 - def get_resource_type_dict(self, system_ids...
Implement the Python class `ResourceTypeService` described below. Class description: Implement the ResourceTypeService class. Method signatures and docstrings: - def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]: 批量获取多个系统的资源类别 - def get_resource_type_dict(self, system_ids...
33c8f4ffe8697081abcfc5771b98a88c0578059f
<|skeleton|> class ResourceTypeService: def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]: """批量获取多个系统的资源类别""" <|body_0|> def get_resource_type_dict(self, system_ids: List[str]) -> ResourceTypeDict: """获取resource type name provider""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResourceTypeService: def list_resource_type_by_systems(self, system_ids: List[str]) -> Dict[str, List[ResourceType]]: """批量获取多个系统的资源类别""" system_resource_type_dict = iam.list_resource_type(system_ids) system_resource_types = {} for system_id, resource_types in system_resource_t...
the_stack_v2_python_sparse
saas/backend/service/resource_type.py
robert871126/bk-iam-saas
train
0
b3a8afe6d1659b3bfdd80b86d00701856ce6e712
[ "from random import choice\nif name == 'ip':\n result = choice(['127.0.0.1', '192.168.0.1'])\nelif name == 'user':\n result = choice(['jim', 'fred2', 'sheila'])\nelse:\n result = self.__dict__.get(name, '?')\nreturn result", "keys = ['ip', 'user']\nkeys.extend(self.__dict__.keys())\nreturn keys.__iter__(...
<|body_start_0|> from random import choice if name == 'ip': result = choice(['127.0.0.1', '192.168.0.1']) elif name == 'user': result = choice(['jim', 'fred2', 'sheila']) else: result = self.__dict__.get(name, '?') return result <|end_body_0|> ...
An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.
ConnInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConnInfo: """An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.""" def __getitem__(self, name): """To allow this instance to look like a dict.""" <|body_0|> def __iter__(self): ...
stack_v2_sparse_classes_36k_train_028957
1,615
no_license
[ { "docstring": "To allow this instance to look like a dict.", "name": "__getitem__", "signature": "def __getitem__(self, name)" }, { "docstring": "To allow iteration over keys, which will be merged into the LogRecord dict before formatting and output.", "name": "__iter__", "signature": "...
2
stack_v2_sparse_classes_30k_train_015209
Implement the Python class `ConnInfo` described below. Class description: An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter. Method signatures and docstrings: - def __getitem__(self, name): To allow this instance to look like a dict...
Implement the Python class `ConnInfo` described below. Class description: An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter. Method signatures and docstrings: - def __getitem__(self, name): To allow this instance to look like a dict...
bbb64dcfd581c30eddb210c647db5b5864b59166
<|skeleton|> class ConnInfo: """An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.""" def __getitem__(self, name): """To allow this instance to look like a dict.""" <|body_0|> def __iter__(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConnInfo: """An example class which shows how an arbitrary class can be used as the ‘extra’ context information repository passed to a LoggerAdapter.""" def __getitem__(self, name): """To allow this instance to look like a dict.""" from random import choice if name == 'ip': ...
the_stack_v2_python_sparse
configurations/i09-config/scripts/utils/ContextualInfo.py
openGDA/gda-diamond
train
4
309f707d68839a49ee448e3f956a85bb6deac1b9
[ "self._parent = parent\nself._device = dev\nmatcher = re.search('(\\\\d+)', dev)\nif matcher != None:\n no = matcher.group(1)\n dev.replace(no, '{:3s}'.format(no))\nself._sortName = dev\nself._label = label\nself._partType = ptype\nself._partInfo = pinfo\nself._filesystem = fs\nself._info = info\nself._mibyte...
<|body_start_0|> self._parent = parent self._device = dev matcher = re.search('(\\d+)', dev) if matcher != None: no = matcher.group(1) dev.replace(no, '{:3s}'.format(no)) self._sortName = dev self._label = label self._partType = ptype ...
the info of one partition
PartitionInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PartitionInfo: """the info of one partition""" def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info): """Constructor. @param parent: an instance of VirtualDisk""" <|body_0|> def canBeRoot(self, minSize): """Tests whether the partition can be...
stack_v2_sparse_classes_36k_train_028958
32,293
no_license
[ { "docstring": "Constructor. @param parent: an instance of VirtualDisk", "name": "__init__", "signature": "def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info)" }, { "docstring": "Tests whether the partition can be used as root partition @param minSize: minimum size of the...
2
stack_v2_sparse_classes_30k_train_010175
Implement the Python class `PartitionInfo` described below. Class description: the info of one partition Method signatures and docstrings: - def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info): Constructor. @param parent: an instance of VirtualDisk - def canBeRoot(self, minSize): Tests whether...
Implement the Python class `PartitionInfo` described below. Class description: the info of one partition Method signatures and docstrings: - def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info): Constructor. @param parent: an instance of VirtualDisk - def canBeRoot(self, minSize): Tests whether...
32e3eb74409741307d52a04173f0e5f0d4186352
<|skeleton|> class PartitionInfo: """the info of one partition""" def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info): """Constructor. @param parent: an instance of VirtualDisk""" <|body_0|> def canBeRoot(self, minSize): """Tests whether the partition can be...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PartitionInfo: """the info of one partition""" def __init__(self, parent, dev, label, size, size2, ptype, pinfo, fs, info): """Constructor. @param parent: an instance of VirtualDisk""" self._parent = parent self._device = dev matcher = re.search('(\\d+)', dev) if m...
the_stack_v2_python_sparse
isource/diskinfopage.py
siduction/sidu-installer
train
0
0e92fc0cc31387f1ae59ac44028ba37d9a2d664e
[ "assert isinstance(members, list)\nassert len(members) == 2\nuids = sorted(members)\nuidstr = ':'.join([str(uid) for uid in uids])\nconvid = idshift.generate_name_uuid(uidstr)\nreturn convid", "attrs = dict(creator=creator)\nconvid = self.check_convid(members)\ninst, _ = self.get_or_create(convid=convid, defaults...
<|body_start_0|> assert isinstance(members, list) assert len(members) == 2 uids = sorted(members) uidstr = ':'.join([str(uid) for uid in uids]) convid = idshift.generate_name_uuid(uidstr) return convid <|end_body_0|> <|body_start_1|> attrs = dict(creator=creator)...
ConversationManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConversationManager: def check_convid(members): """会话ID生成,用户ID排序,UUID""" <|body_0|> def conversation_init(self, members, creator, symbol=''): """会话初始化""" <|body_1|> <|end_skeleton|> <|body_start_0|> assert isinstance(members, list) assert le...
stack_v2_sparse_classes_36k_train_028959
25,386
no_license
[ { "docstring": "会话ID生成,用户ID排序,UUID", "name": "check_convid", "signature": "def check_convid(members)" }, { "docstring": "会话初始化", "name": "conversation_init", "signature": "def conversation_init(self, members, creator, symbol='')" } ]
2
null
Implement the Python class `ConversationManager` described below. Class description: Implement the ConversationManager class. Method signatures and docstrings: - def check_convid(members): 会话ID生成,用户ID排序,UUID - def conversation_init(self, members, creator, symbol=''): 会话初始化
Implement the Python class `ConversationManager` described below. Class description: Implement the ConversationManager class. Method signatures and docstrings: - def check_convid(members): 会话ID生成,用户ID排序,UUID - def conversation_init(self, members, creator, symbol=''): 会话初始化 <|skeleton|> class ConversationManager: ...
b7ed6588e13d2916a4162d56509d2794742a1eb1
<|skeleton|> class ConversationManager: def check_convid(members): """会话ID生成,用户ID排序,UUID""" <|body_0|> def conversation_init(self, members, creator, symbol=''): """会话初始化""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConversationManager: def check_convid(members): """会话ID生成,用户ID排序,UUID""" assert isinstance(members, list) assert len(members) == 2 uids = sorted(members) uidstr = ':'.join([str(uid) for uid in uids]) convid = idshift.generate_name_uuid(uidstr) return con...
the_stack_v2_python_sparse
server/applibs/convert/models/contact.py
fanshuai/kubrick
train
0
318579e84cc76ae717212d024125dc8fbe0406bf
[ "def review_summary_as_dict(review_summary):\n return {'review': review_summary.review, 'summary': review_summary.review.summary, 'latest_change': review_summary.latest_change, 'progress': review_summary.review.total_progress, 'issues': len(review_summary.review.open_issues)}\nreturn parameters.filtered('review ...
<|body_start_0|> def review_summary_as_dict(review_summary): return {'review': review_summary.review, 'summary': review_summary.review.summary, 'latest_change': review_summary.latest_change, 'progress': review_summary.review.total_progress, 'issues': len(review_summary.review.open_issues)} r...
Review summaries
ReviewSummaries
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReviewSummaries: """Review summaries""" def json(value, parameters): """ReviewSummaries { "reviews": ReviewSummary[], "more": bool // true if there are more reviews than the ones retrieved } ReviewSummary { "review": integer, "summary": string, // the review's summary (text) "latest_...
stack_v2_sparse_classes_36k_train_028960
3,409
permissive
[ { "docstring": "ReviewSummaries { \"reviews\": ReviewSummary[], \"more\": bool // true if there are more reviews than the ones retrieved } ReviewSummary { \"review\": integer, \"summary\": string, // the review's summary (text) \"latest_change\": integer, // the timestamp of the latest commit or comment \"progr...
2
null
Implement the Python class `ReviewSummaries` described below. Class description: Review summaries Method signatures and docstrings: - def json(value, parameters): ReviewSummaries { "reviews": ReviewSummary[], "more": bool // true if there are more reviews than the ones retrieved } ReviewSummary { "review": integer, "...
Implement the Python class `ReviewSummaries` described below. Class description: Review summaries Method signatures and docstrings: - def json(value, parameters): ReviewSummaries { "reviews": ReviewSummary[], "more": bool // true if there are more reviews than the ones retrieved } ReviewSummary { "review": integer, "...
c2d962b909ff7ef2f09bccbeb636333920b3659e
<|skeleton|> class ReviewSummaries: """Review summaries""" def json(value, parameters): """ReviewSummaries { "reviews": ReviewSummary[], "more": bool // true if there are more reviews than the ones retrieved } ReviewSummary { "review": integer, "summary": string, // the review's summary (text) "latest_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReviewSummaries: """Review summaries""" def json(value, parameters): """ReviewSummaries { "reviews": ReviewSummary[], "more": bool // true if there are more reviews than the ones retrieved } ReviewSummary { "review": integer, "summary": string, // the review's summary (text) "latest_change": inte...
the_stack_v2_python_sparse
src/jsonapi/v1/reviewsummaries.py
jensl/critic
train
224
862980c746946faf69f81e043c15a90cc130fa88
[ "from Akamai_SIEM import fetch_incidents_command\nrequests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT)\ntested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={})\nexpected_incidents = load_params_f...
<|body_start_0|> from Akamai_SIEM import fetch_incidents_command requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT) tested_incidents, tested_last_run = fetch_incidents_command(client=client, fetch_time='12 hours', fetch_limit=5, config_ids='50170', last_run={}) ...
TestCommandsFunctions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCommandsFunctions: def test_fetch_incidents_command_1(self, client, datadir, requests_mock): """Test - No last time exsits and event available""" <|body_0|> def test_fetch_incidents_command_2(self, client, datadir, requests_mock): """Test - Last time exsits and e...
stack_v2_sparse_classes_36k_train_028961
7,487
permissive
[ { "docstring": "Test - No last time exsits and event available", "name": "test_fetch_incidents_command_1", "signature": "def test_fetch_incidents_command_1(self, client, datadir, requests_mock)" }, { "docstring": "Test - Last time exsits and events available", "name": "test_fetch_incidents_c...
6
stack_v2_sparse_classes_30k_train_008047
Implement the Python class `TestCommandsFunctions` described below. Class description: Implement the TestCommandsFunctions class. Method signatures and docstrings: - def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available - def test_fetch_incidents_comm...
Implement the Python class `TestCommandsFunctions` described below. Class description: Implement the TestCommandsFunctions class. Method signatures and docstrings: - def test_fetch_incidents_command_1(self, client, datadir, requests_mock): Test - No last time exsits and event available - def test_fetch_incidents_comm...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestCommandsFunctions: def test_fetch_incidents_command_1(self, client, datadir, requests_mock): """Test - No last time exsits and event available""" <|body_0|> def test_fetch_incidents_command_2(self, client, datadir, requests_mock): """Test - Last time exsits and e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCommandsFunctions: def test_fetch_incidents_command_1(self, client, datadir, requests_mock): """Test - No last time exsits and event available""" from Akamai_SIEM import fetch_incidents_command requests_mock.get(f'{BASE_URL}/50170?limit=5&from=1575966002', text=SEC_EVENTS_TXT) ...
the_stack_v2_python_sparse
Packs/Akamai_SIEM/Integrations/Akamai_SIEM/Akamai_SIEM_test.py
demisto/content
train
1,023
f1bc5d4ef04b3d8fe6586318dd82771223b57d40
[ "self.capacity = capacity\nself.key_to_node = {}\nself.double_list = DoubleLinkedList()\nself.size = 0", "if key in self.key_to_node:\n node = self.key_to_node[key]\n self.double_list.unlink(node)\n self.double_list.add_to_front(node)\n return node.value\nreturn None", "if key in self.key_to_node:\n...
<|body_start_0|> self.capacity = capacity self.key_to_node = {} self.double_list = DoubleLinkedList() self.size = 0 <|end_body_0|> <|body_start_1|> if key in self.key_to_node: node = self.key_to_node[key] self.double_list.unlink(node) self.dou...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_028962
2,469
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_train_000907
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
e41d8ac70ef385618e6eb6dbe3e5bf42925f38ef
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.key_to_node = {} self.double_list = DoubleLinkedList() self.size = 0 def get(self, key): """:type key: int :rtype: int""" if key in self.key_to_node: ...
the_stack_v2_python_sparse
lru.py
sraisty/code_challenges
train
0
94fa417ef07cfdb365f037ac596949847cd8001f
[ "left, right, result = (0, 1, 0)\nnums.sort()\nn = len(nums)\nwhile left < n and right < n:\n if left == right or nums[right] - nums[left] < k:\n right += 1\n elif nums[right] - nums[left] > k:\n left += 1\n else:\n left += 1\n result += 1\n while left < n and nums[left] ...
<|body_start_0|> left, right, result = (0, 1, 0) nums.sort() n = len(nums) while left < n and right < n: if left == right or nums[right] - nums[left] < k: right += 1 elif nums[right] - nums[left] > k: left += 1 else: ...
Array
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Array: def k_diff_pairs(self, nums: List[int], k: int) -> int: """Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return:""" <|body_0|> def k_diff_pairs_(self, nums: List[int], k: int) -> int: """Approach: Hash Map Ti...
stack_v2_sparse_classes_36k_train_028963
1,604
no_license
[ { "docstring": "Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return:", "name": "k_diff_pairs", "signature": "def k_diff_pairs(self, nums: List[int], k: int) -> int" }, { "docstring": "Approach: Hash Map Time Complexity: O(N) Space Complexity: ...
2
null
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def k_diff_pairs(self, nums: List[int], k: int) -> int: Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return: - def k_diff_pairs_(se...
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def k_diff_pairs(self, nums: List[int], k: int) -> int: Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return: - def k_diff_pairs_(se...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Array: def k_diff_pairs(self, nums: List[int], k: int) -> int: """Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return:""" <|body_0|> def k_diff_pairs_(self, nums: List[int], k: int) -> int: """Approach: Hash Map Ti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Array: def k_diff_pairs(self, nums: List[int], k: int) -> int: """Approach: Two Pointers Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :param k: :return:""" left, right, result = (0, 1, 0) nums.sort() n = len(nums) while left < n and right < n: ...
the_stack_v2_python_sparse
revisited_2021/arrays/k_diff_pairs_in_array.py
Shiv2157k/leet_code
train
1
7a062e386db7c9c878217eb5b8d7435c0ff28982
[ "merged = None\nmerged_current = merged\ncurrent1 = pHead1\ncurrent2 = pHead2\nwhile current1 or current2:\n if self.less(current1, current2):\n less = current1\n current1 = current1.next\n else:\n less = current2\n current2 = current2.next\n if not merged_current:\n merg...
<|body_start_0|> merged = None merged_current = merged current1 = pHead1 current2 = pHead2 while current1 or current2: if self.less(current1, current2): less = current1 current1 = current1.next else: less = c...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def Merge(self, pHead1, pHead2): """输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表...
stack_v2_sparse_classes_36k_train_028964
2,931
permissive
[ { "docstring": "输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表看做了整体,而没有拆分成一个一个元素看待。 算法2: 比较两个链表的当前节点,然后选择更小的节点添加到新的链...
2
stack_v2_sparse_classes_30k_train_004913
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def Merge(self, pHead1, pHead2): 输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def Merge(self, pHead1, pHead2): 输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所...
5fdd3a607ee3828e9b229cac8104fcccf1a2770d
<|skeleton|> class Solution: def Merge(self, pHead1, pHead2): """输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def Merge(self, pHead1, pHead2): """输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表看做了整体,而没有拆分成一个...
the_stack_v2_python_sparse
017-合并两个排序的链表/merge.py
Jay54520/Learn-Algorithms-With-Python
train
0
0d23fdab33291cd88c86b0acf3989b422799967e
[ "def preorder(root):\n if not root:\n return []\n left = preorder(root.left)\n right = preorder(root.right)\n return [root.val] + left + right\nreturn ' '.join(map(str, preorder(root)))", "def helper(lower=float('-inf'), upper=float('inf')):\n if not data or data[0] < lower or data[0] > uppe...
<|body_start_0|> def preorder(root): if not root: return [] left = preorder(root.left) right = preorder(root.right) return [root.val] + left + right return ' '.join(map(str, preorder(root))) <|end_body_0|> <|body_start_1|> def help...
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_028965
3,030
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
feab001b9291f6e57c44eeb0b625fdaa145d19b4
<|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""" def preorder(root): if not root: return [] left = preorder(root.left) right = preorder(root.right) return [root.val] + lef...
the_stack_v2_python_sparse
449_Serialize_and_Deserialize_BST.py
luchang59/leetcode
train
0
5b15b05d38362eb07872a09272dc89206024e9c6
[ "if not isinstance(act1, MLAction):\n raise TypeError('act1 must be MLAction.')\nif not isinstance(act2, MLAction):\n raise TypeError('act2 must be MLAction.')\nn1 = 1 if isinstance(act1.output, (MLNumTypeFloat32, MLNumTypeFloat64)) else act1.output.dim[0]\nn2 = 1 if isinstance(act2.output, (MLNumTypeFloat32,...
<|body_start_0|> if not isinstance(act1, MLAction): raise TypeError('act1 must be MLAction.') if not isinstance(act2, MLAction): raise TypeError('act2 must be MLAction.') n1 = 1 if isinstance(act1.output, (MLNumTypeFloat32, MLNumTypeFloat64)) else act1.output.dim[0] ...
Concatenate number of arrays into an array.
MLActionConcat
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MLActionConcat: """Concatenate number of arrays into an array.""" def __init__(self, act1, act2): """@param act1 first element @param act2 second element""" <|body_0|> def execute(self, **kwargs): """Concatenation""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_028966
19,020
permissive
[ { "docstring": "@param act1 first element @param act2 second element", "name": "__init__", "signature": "def __init__(self, act1, act2)" }, { "docstring": "Concatenation", "name": "execute", "signature": "def execute(self, **kwargs)" } ]
2
null
Implement the Python class `MLActionConcat` described below. Class description: Concatenate number of arrays into an array. Method signatures and docstrings: - def __init__(self, act1, act2): @param act1 first element @param act2 second element - def execute(self, **kwargs): Concatenation
Implement the Python class `MLActionConcat` described below. Class description: Concatenate number of arrays into an array. Method signatures and docstrings: - def __init__(self, act1, act2): @param act1 first element @param act2 second element - def execute(self, **kwargs): Concatenation <|skeleton|> class MLAction...
27d6da4ecdd76e18292f265fde61d19b66937a5c
<|skeleton|> class MLActionConcat: """Concatenate number of arrays into an array.""" def __init__(self, act1, act2): """@param act1 first element @param act2 second element""" <|body_0|> def execute(self, **kwargs): """Concatenation""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MLActionConcat: """Concatenate number of arrays into an array.""" def __init__(self, act1, act2): """@param act1 first element @param act2 second element""" if not isinstance(act1, MLAction): raise TypeError('act1 must be MLAction.') if not isinstance(act2, MLAction): ...
the_stack_v2_python_sparse
mlprodict/grammar/grammar_sklearn/grammar/gactions.py
sdpython/mlprodict
train
60
d8e358028697cf503d7cafee7b67a629990a9e66
[ "self.username = username\nself.first_name = first_name\nself.last_name = last_name\nself.application_id = application_id\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nusername = dictionary.get('username')\nfirst_name = dictionary.get('firstName')\nlast_name = dic...
<|body_start_0|> self.username = username self.first_name = first_name self.last_name = last_name self.application_id = application_id self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximum 255 characters any mix of upper...
AddCustomerRequest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddCustomerRequest: """Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char...
stack_v2_sparse_classes_36k_train_028967
3,413
permissive
[ { "docstring": "Constructor for the AddCustomerRequest class", "name": "__init__", "signature": "def __init__(self, username=None, first_name=None, last_name=None, application_id=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: diction...
2
stack_v2_sparse_classes_30k_train_013299
Implement the Python class `AddCustomerRequest` described below. Class description: Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)...
Implement the Python class `AddCustomerRequest` described below. Class description: Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class AddCustomerRequest: """Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddCustomerRequest: """Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximu...
the_stack_v2_python_sparse
finicityapi/models/add_customer_request.py
monarchmoney/finicity-python
train
0
d3179f6608465ee67ea41c6f5cd149eb8f50a1e3
[ "create_and_login()\nresponse = self.client.put(USER_URL, json.dumps({'first_name': 'Dirk'}), content_type='application/json', HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % BAD_TOKEN)\nself.assertContains(response, CONTENT_BAD_TOKEN, status_code=HTTP_401_UNAUTHORIZED)", "token = create_and_login()\nresponse = self.c...
<|body_start_0|> create_and_login() response = self.client.put(USER_URL, json.dumps({'first_name': 'Dirk'}), content_type='application/json', HTTP_AUTHORIZATION=AUTHORIZATION_PAYLOAD % BAD_TOKEN) self.assertContains(response, CONTENT_BAD_TOKEN, status_code=HTTP_401_UNAUTHORIZED) <|end_body_0|> ...
Bad PUT requests to change account attributes.
BadPut
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BadPut: """Bad PUT requests to change account attributes.""" def test_put_badtoken(self): """Putting (trying to change user attributes) while logged in, but using a bad token.""" <|body_0|> def test_no_username(self): """Try changing account attributes with a goo...
stack_v2_sparse_classes_36k_train_028968
19,841
permissive
[ { "docstring": "Putting (trying to change user attributes) while logged in, but using a bad token.", "name": "test_put_badtoken", "signature": "def test_put_badtoken(self)" }, { "docstring": "Try changing account attributes with a good token, but a bad username.", "name": "test_no_username",...
2
stack_v2_sparse_classes_30k_train_007737
Implement the Python class `BadPut` described below. Class description: Bad PUT requests to change account attributes. Method signatures and docstrings: - def test_put_badtoken(self): Putting (trying to change user attributes) while logged in, but using a bad token. - def test_no_username(self): Try changing account ...
Implement the Python class `BadPut` described below. Class description: Bad PUT requests to change account attributes. Method signatures and docstrings: - def test_put_badtoken(self): Putting (trying to change user attributes) while logged in, but using a bad token. - def test_no_username(self): Try changing account ...
d7f1f1f1ff926148d2aa541d0bd4758173aa76d5
<|skeleton|> class BadPut: """Bad PUT requests to change account attributes.""" def test_put_badtoken(self): """Putting (trying to change user attributes) while logged in, but using a bad token.""" <|body_0|> def test_no_username(self): """Try changing account attributes with a goo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BadPut: """Bad PUT requests to change account attributes.""" def test_put_badtoken(self): """Putting (trying to change user attributes) while logged in, but using a bad token.""" create_and_login() response = self.client.put(USER_URL, json.dumps({'first_name': 'Dirk'}), content_ty...
the_stack_v2_python_sparse
goldstone/user/tests.py
leftees/goldstone-server
train
0
4eb5ed949f32b4c3950f62125948fc484466660c
[ "username = self.cleaned_data.get('username')\nif not checkutils.username_correct(username):\n raise forms.ValidationError(_(u'Username may only contain alphanumeric characters or dashes and cannot begin with a dash'))\ntry:\n User.objects.get(username=username)\nexcept ObjectDoesNotExist:\n return usernam...
<|body_start_0|> username = self.cleaned_data.get('username') if not checkutils.username_correct(username): raise forms.ValidationError(_(u'Username may only contain alphanumeric characters or dashes and cannot begin with a dash')) try: User.objects.get(username=username)...
SignupForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" <|body_0|> def clean_password2(self): """Checks if the length is correct and both passwords are the same""" <|body_1|> def clean_email(self): ...
stack_v2_sparse_classes_36k_train_028969
3,700
no_license
[ { "docstring": "Checks if the user exists and that the username is only -a-zA-Z", "name": "clean_username", "signature": "def clean_username(self)" }, { "docstring": "Checks if the length is correct and both passwords are the same", "name": "clean_password2", "signature": "def clean_pass...
3
stack_v2_sparse_classes_30k_train_019701
Implement the Python class `SignupForm` described below. Class description: Implement the SignupForm class. Method signatures and docstrings: - def clean_username(self): Checks if the user exists and that the username is only -a-zA-Z - def clean_password2(self): Checks if the length is correct and both passwords are ...
Implement the Python class `SignupForm` described below. Class description: Implement the SignupForm class. Method signatures and docstrings: - def clean_username(self): Checks if the user exists and that the username is only -a-zA-Z - def clean_password2(self): Checks if the length is correct and both passwords are ...
bee916136a67f2203a7ca6078220553ae1ce9c3c
<|skeleton|> class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" <|body_0|> def clean_password2(self): """Checks if the length is correct and both passwords are the same""" <|body_1|> def clean_email(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" username = self.cleaned_data.get('username') if not checkutils.username_correct(username): raise forms.ValidationError(_(u'Username may only contain alphanumeric char...
the_stack_v2_python_sparse
dwarf/userprofile/forms.py
slok/dwarf
train
1
144e8bc464940711e49ac8ebb9f2c70f375f85c3
[ "n = len(nums)\nk = k % n\nnums[:] = nums[n - k:] + nums[:n - k]\nreturn nums", "if len(nums) <= k:\n nums.reverse()\n return nums\nnums.reverse()\nnumk, nume = (nums[:k], nums[k:])\nnumk.reverse()\nnume.reverse()\nnums[:k] = numk\nnums[k:] = nume\nreturn nums" ]
<|body_start_0|> n = len(nums) k = k % n nums[:] = nums[n - k:] + nums[:n - k] return nums <|end_body_0|> <|body_start_1|> if len(nums) <= k: nums.reverse() return nums nums.reverse() numk, nume = (nums[:k], nums[k:]) numk.reverse(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, nums, k): """国外大神 几行代码解决,果然是大神,但是没看懂""" <|body_0|> def rotate1(self, nums, k): """反转更好理解一点点,但是代码有问题,执行不成功""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) k = k % n nums[:] = nums[n - k:] + num...
stack_v2_sparse_classes_36k_train_028970
2,277
no_license
[ { "docstring": "国外大神 几行代码解决,果然是大神,但是没看懂", "name": "rotate", "signature": "def rotate(self, nums, k)" }, { "docstring": "反转更好理解一点点,但是代码有问题,执行不成功", "name": "rotate1", "signature": "def rotate1(self, nums, k)" } ]
2
stack_v2_sparse_classes_30k_val_000817
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): 国外大神 几行代码解决,果然是大神,但是没看懂 - def rotate1(self, nums, k): 反转更好理解一点点,但是代码有问题,执行不成功
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): 国外大神 几行代码解决,果然是大神,但是没看懂 - def rotate1(self, nums, k): 反转更好理解一点点,但是代码有问题,执行不成功 <|skeleton|> class Solution: def rotate(self, nums, k): """...
069bb0b751ef7f469036b9897436eb5d138ffa24
<|skeleton|> class Solution: def rotate(self, nums, k): """国外大神 几行代码解决,果然是大神,但是没看懂""" <|body_0|> def rotate1(self, nums, k): """反转更好理解一点点,但是代码有问题,执行不成功""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, nums, k): """国外大神 几行代码解决,果然是大神,但是没看懂""" n = len(nums) k = k % n nums[:] = nums[n - k:] + nums[:n - k] return nums def rotate1(self, nums, k): """反转更好理解一点点,但是代码有问题,执行不成功""" if len(nums) <= k: nums.reverse() ...
the_stack_v2_python_sparse
算法/Week_01/189. 旋转数组.py
RichieSong/algorithm
train
0
913ea239d7661fce8c90160a40c5b908bf6fe273
[ "super(CreateBackupTests, cls).setUpClass()\nkey_resp = cls.keypairs_client.create_keypair(rand_name('key'))\nassert key_resp.status_code is 200, 'Create keypair failed with response code {0}'.format(key_resp.status_code)\ncls.key = key_resp.entity\ncls.resources.add(cls.key.name, cls.keypairs_client.delete_keypair...
<|body_start_0|> super(CreateBackupTests, cls).setUpClass() key_resp = cls.keypairs_client.create_keypair(rand_name('key')) assert key_resp.status_code is 200, 'Create keypair failed with response code {0}'.format(key_resp.status_code) cls.key = key_resp.entity cls.resources.add(...
CreateBackupTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateBackupTests: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defaults defined in server behaviors.""" <|body_0|> def test_create_backup_for_server(self): ...
stack_v2_sparse_classes_36k_train_028971
2,408
permissive
[ { "docstring": "Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defaults defined in server behaviors.", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "Verify that a backup can be c...
2
stack_v2_sparse_classes_30k_train_008403
Implement the Python class `CreateBackupTests` described below. Class description: Implement the CreateBackupTests class. Method signatures and docstrings: - def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defa...
Implement the Python class `CreateBackupTests` described below. Class description: Implement the CreateBackupTests class. Method signatures and docstrings: - def setUpClass(cls): Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defa...
30f0e64672676c3f90b4a582fe90fac6621475b3
<|skeleton|> class CreateBackupTests: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defaults defined in server behaviors.""" <|body_0|> def test_create_backup_for_server(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateBackupTests: def setUpClass(cls): """Perform actions that setup the necessary resources for testing. The following resources are created during this setup: - A server with defaults defined in server behaviors.""" super(CreateBackupTests, cls).setUpClass() key_resp = cls.keypairs_...
the_stack_v2_python_sparse
cloudroast/compute/instance_actions/admin_api/test_create_backup.py
RULCSoft/cloudroast
train
1
25ec0cf7049a3a19f55c79eb486332345a751ca7
[ "page = self.client.get('/search/')\nself.assertEqual(page.status_code, 302)\nself.client.post(reverse('index'))", "test_user = User.objects.create(username='TestUser', password='TestPassword')\nmembership = Membership.objects.create(user_id='1')\nself.client.force_login(test_user)\ntest_event = Event.objects.cre...
<|body_start_0|> page = self.client.get('/search/') self.assertEqual(page.status_code, 302) self.client.post(reverse('index')) <|end_body_0|> <|body_start_1|> test_user = User.objects.create(username='TestUser', password='TestPassword') membership = Membership.objects.create(use...
TestSearchViews
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSearchViews: def test_get_all_events_page_redirect(self): """Test search redirects to index with an empty result(or database)""" <|body_0|> def test_get_all_events_page(self): """Test search renders correct template with events in db""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_028972
1,705
no_license
[ { "docstring": "Test search redirects to index with an empty result(or database)", "name": "test_get_all_events_page_redirect", "signature": "def test_get_all_events_page_redirect(self)" }, { "docstring": "Test search renders correct template with events in db", "name": "test_get_all_events_...
2
stack_v2_sparse_classes_30k_train_005262
Implement the Python class `TestSearchViews` described below. Class description: Implement the TestSearchViews class. Method signatures and docstrings: - def test_get_all_events_page_redirect(self): Test search redirects to index with an empty result(or database) - def test_get_all_events_page(self): Test search rend...
Implement the Python class `TestSearchViews` described below. Class description: Implement the TestSearchViews class. Method signatures and docstrings: - def test_get_all_events_page_redirect(self): Test search redirects to index with an empty result(or database) - def test_get_all_events_page(self): Test search rend...
52795e9217d2786b457ca4f0b925c7d36c2dbfd4
<|skeleton|> class TestSearchViews: def test_get_all_events_page_redirect(self): """Test search redirects to index with an empty result(or database)""" <|body_0|> def test_get_all_events_page(self): """Test search renders correct template with events in db""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSearchViews: def test_get_all_events_page_redirect(self): """Test search redirects to index with an empty result(or database)""" page = self.client.get('/search/') self.assertEqual(page.status_code, 302) self.client.post(reverse('index')) def test_get_all_events_page(s...
the_stack_v2_python_sparse
search/tests.py
paperclippete/FinalMilestone
train
1
c9beeca6e4553388f17074b1ac382178ed627721
[ "self._state = state\nself._action_dispatcher = action_dispatcher\nself._plugins: List[AbstractPlugin] = []", "plugin._configure(state=self._state, action_dispatcher=self._action_dispatcher)\nself._plugins.append(plugin)\nself._action_dispatcher.add_handler(plugin)\nplugin.setup()", "for p in self._plugins:\n ...
<|body_start_0|> self._state = state self._action_dispatcher = action_dispatcher self._plugins: List[AbstractPlugin] = [] <|end_body_0|> <|body_start_1|> plugin._configure(state=self._state, action_dispatcher=self._action_dispatcher) self._plugins.append(plugin) self._ac...
Configure, setup, and tear down engine plugins.
PluginStarter
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PluginStarter: """Configure, setup, and tear down engine plugins.""" def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: """Create a PluginStarter interface with access to its dependencies.""" <|body_0|> def start(self, plugin: AbstractPlug...
stack_v2_sparse_classes_36k_train_028973
3,443
permissive
[ { "docstring": "Create a PluginStarter interface with access to its dependencies.", "name": "__init__", "signature": "def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None" }, { "docstring": "Configure a given plugin and add it to the dispatch pipeline.", "name": ...
3
null
Implement the Python class `PluginStarter` described below. Class description: Configure, setup, and tear down engine plugins. Method signatures and docstrings: - def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: Create a PluginStarter interface with access to its dependencies. - def ...
Implement the Python class `PluginStarter` described below. Class description: Configure, setup, and tear down engine plugins. Method signatures and docstrings: - def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: Create a PluginStarter interface with access to its dependencies. - def ...
026b523c8c9e5d45910c490efb89194d72595be9
<|skeleton|> class PluginStarter: """Configure, setup, and tear down engine plugins.""" def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: """Create a PluginStarter interface with access to its dependencies.""" <|body_0|> def start(self, plugin: AbstractPlug...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PluginStarter: """Configure, setup, and tear down engine plugins.""" def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: """Create a PluginStarter interface with access to its dependencies.""" self._state = state self._action_dispatcher = action_disp...
the_stack_v2_python_sparse
api/src/opentrons/protocol_engine/plugins.py
Opentrons/opentrons
train
326
b176edb56f363151fee8af905018296bd7e5f998
[ "url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id)\nr = requests.get(url)\nreturn BeautifulSoup(r.text, 'html.parser')", "form = self.soup(remote_id).find('form', {'name': 'frm_daily'})\ntable = form.findChild('table')\nchildren = table.findChildren('tr')[5].findChildren('td')\ndt = arrow.get(children[0]....
<|body_start_0|> url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id) r = requests.get(url) return BeautifulSoup(r.text, 'html.parser') <|end_body_0|> <|body_start_1|> form = self.soup(remote_id).find('form', {'name': 'frm_daily'}) table = form.findChild('table') ch...
Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil
Corps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Corps: """Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil""" def soup(self, remote_id): """Return a beautiful soup object from rivergages.mvr.usace.army.mil""" <|body_0|> def dt_value(self, remote_id): """Return the most recent datetime and v...
stack_v2_sparse_classes_36k_train_028974
1,525
no_license
[ { "docstring": "Return a beautiful soup object from rivergages.mvr.usace.army.mil", "name": "soup", "signature": "def soup(self, remote_id)" }, { "docstring": "Return the most recent datetime and value", "name": "dt_value", "signature": "def dt_value(self, remote_id)" }, { "docst...
3
stack_v2_sparse_classes_30k_train_009405
Implement the Python class `Corps` described below. Class description: Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil Method signatures and docstrings: - def soup(self, remote_id): Return a beautiful soup object from rivergages.mvr.usace.army.mil - def dt_value(self, remote_id): Return the most ...
Implement the Python class `Corps` described below. Class description: Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil Method signatures and docstrings: - def soup(self, remote_id): Return a beautiful soup object from rivergages.mvr.usace.army.mil - def dt_value(self, remote_id): Return the most ...
21dfc83758b689410578faef697398afab92fded
<|skeleton|> class Corps: """Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil""" def soup(self, remote_id): """Return a beautiful soup object from rivergages.mvr.usace.army.mil""" <|body_0|> def dt_value(self, remote_id): """Return the most recent datetime and v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Corps: """Get flows from Army Corps of Engineers rivergages.mvr.usace.army.mil""" def soup(self, remote_id): """Return a beautiful soup object from rivergages.mvr.usace.army.mil""" url = self.URLBASE + '?sid={}&d=1&dt=S'.format(remote_id) r = requests.get(url) return Beaut...
the_stack_v2_python_sparse
web/app/remote/corps.py
abkfenris/gage-web
train
1
4c820500f5efd22cf7ae7db44bebb4b20671f43b
[ "html = hio.from_file(src_file)\nsoup = bs4.BeautifulSoup(html, 'html.parser')\ntable = soup.findAll('table')[-1]\ndf = pd.read_html(str(table))[0]\ndf.columns = ['dataset', 'link']\ncols = [np.where(dataset.has_attr('href'), dataset.get('href'), 'no link') for dataset in table.find_all('a')]\ndf.link = [str(c) for...
<|body_start_0|> html = hio.from_file(src_file) soup = bs4.BeautifulSoup(html, 'html.parser') table = soup.findAll('table')[-1] df = pd.read_html(str(table))[0] df.columns = ['dataset', 'link'] cols = [np.where(dataset.has_attr('href'), dataset.get('href'), 'no link') for...
Extract the list of available datasets from Kibot.
DatasetListExtractor
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetListExtractor: """Extract the list of available datasets from Kibot.""" def extract_dataset_links(cls, src_file: str) -> pd.DataFrame: """Retrieve a table with datasets and corresponding page links. :param src_file: html file with the account page :return: DataFrame with datas...
stack_v2_sparse_classes_36k_train_028975
21,114
permissive
[ { "docstring": "Retrieve a table with datasets and corresponding page links. :param src_file: html file with the account page :return: DataFrame with dataset names and corresponding page links", "name": "extract_dataset_links", "signature": "def extract_dataset_links(cls, src_file: str) -> pd.DataFrame"...
2
null
Implement the Python class `DatasetListExtractor` described below. Class description: Extract the list of available datasets from Kibot. Method signatures and docstrings: - def extract_dataset_links(cls, src_file: str) -> pd.DataFrame: Retrieve a table with datasets and corresponding page links. :param src_file: html...
Implement the Python class `DatasetListExtractor` described below. Class description: Extract the list of available datasets from Kibot. Method signatures and docstrings: - def extract_dataset_links(cls, src_file: str) -> pd.DataFrame: Retrieve a table with datasets and corresponding page links. :param src_file: html...
363c59fa29df2ba2719cbad2f8a19ae12cc54a92
<|skeleton|> class DatasetListExtractor: """Extract the list of available datasets from Kibot.""" def extract_dataset_links(cls, src_file: str) -> pd.DataFrame: """Retrieve a table with datasets and corresponding page links. :param src_file: html file with the account page :return: DataFrame with datas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatasetListExtractor: """Extract the list of available datasets from Kibot.""" def extract_dataset_links(cls, src_file: str) -> pd.DataFrame: """Retrieve a table with datasets and corresponding page links. :param src_file: html file with the account page :return: DataFrame with dataset names and ...
the_stack_v2_python_sparse
im/kibot/data/extract/download.py
srlindemann/amp
train
0
286ec5fbbed7a877cc04dff967dff3bc804d7a71
[ "super(self.__class__, self).__init__()\nself.hash = hash_f\nself.key_len = key_len\nself.key = ''\nself.key_gen = key_gen", "if self.key_gen is None:\n self.key = random_string(self.key_len)\nelse:\n self.key = self.key_gen()\nreturn self.key", "x1, x2 = x\nif x1 == x2 or self.hash(self.key, x1) == None:...
<|body_start_0|> super(self.__class__, self).__init__() self.hash = hash_f self.key_len = key_len self.key = '' self.key_gen = key_gen <|end_body_0|> <|body_start_1|> if self.key_gen is None: self.key = random_string(self.key_len) else: se...
This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function.
GameCR
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameCR: """This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function.""" def __init__(self, hash_f, key_len, key_gen=None): """:param hash_f: T...
stack_v2_sparse_classes_36k_train_028976
1,745
no_license
[ { "docstring": ":param hash_f: This is the hash function that the adversary is playing against. It must take two parameters, a key of length key_len and a message. :param key_len: Length of key used by hash function.", "name": "__init__", "signature": "def __init__(self, hash_f, key_len, key_gen=None)" ...
3
stack_v2_sparse_classes_30k_train_008746
Implement the Python class `GameCR` described below. Class description: This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function. Method signatures and docstrings: - def __init...
Implement the Python class `GameCR` described below. Class description: This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function. Method signatures and docstrings: - def __init...
9014f5a9bf7021bef9f5cc4aa5b16424ca83dee9
<|skeleton|> class GameCR: """This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function.""" def __init__(self, hash_f, key_len, key_gen=None): """:param hash_f: T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameCR: """This game is used to test the collision resistance of hash functions. Adversaries playing this game do not have access to any oracles however they do have access to the key used by the hash function.""" def __init__(self, hash_f, key_len, key_gen=None): """:param hash_f: This is the ha...
the_stack_v2_python_sparse
src/playcrypt/games/game_cr.py
UCSDCSE107/playcrypt
train
2
b7319277b64f495c1075ac6ac812363e660cd91f
[ "dummy_node = ListNode()\npre_node = dummy_node\nwhile l1 or l2:\n if l1 and l2:\n if l1.val < l2.val:\n pre_node.next = l1\n l1 = l1.next\n else:\n pre_node.next = l2\n l2 = l2.next\n elif l1:\n pre_node.next = l1\n l1 = l1.next\n els...
<|body_start_0|> dummy_node = ListNode() pre_node = dummy_node while l1 or l2: if l1 and l2: if l1.val < l2.val: pre_node.next = l1 l1 = l1.next else: pre_node.next = l2 l2...
MergeTwoLists
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MergeTwoLists: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """使用遍历方式就行 :param l1: :param l2: :return:""" <|body_0|> def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode: """迭代方式 :param l1: :param l2: :return:""" <|body_1|> <|...
stack_v2_sparse_classes_36k_train_028977
2,134
no_license
[ { "docstring": "使用遍历方式就行 :param l1: :param l2: :return:", "name": "mergeTwoLists", "signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode" }, { "docstring": "迭代方式 :param l1: :param l2: :return:", "name": "mergeTwoLists1", "signature": "def mergeTwoLists1(self, l1: ...
2
stack_v2_sparse_classes_30k_train_013514
Implement the Python class `MergeTwoLists` described below. Class description: Implement the MergeTwoLists class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 使用遍历方式就行 :param l1: :param l2: :return: - def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListN...
Implement the Python class `MergeTwoLists` described below. Class description: Implement the MergeTwoLists class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 使用遍历方式就行 :param l1: :param l2: :return: - def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListN...
9acba92695c06406f12f997a720bfe1deb9464a8
<|skeleton|> class MergeTwoLists: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """使用遍历方式就行 :param l1: :param l2: :return:""" <|body_0|> def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode: """迭代方式 :param l1: :param l2: :return:""" <|body_1|> <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MergeTwoLists: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """使用遍历方式就行 :param l1: :param l2: :return:""" dummy_node = ListNode() pre_node = dummy_node while l1 or l2: if l1 and l2: if l1.val < l2.val: pre_node...
the_stack_v2_python_sparse
datastructure/linked_list/MergeTwoLists.py
yinhuax/leet_code
train
0
5ea38f8c5545030eb39ae0fca0e37d889f916bef
[ "form = super().get_form(request, obj, **kwargs)\nis_superuser = request.user.is_superuser\ndisabled_fields: Set[str] = set()\nif not is_superuser:\n disabled_fields |= {'username', 'is_staff', 'is_superuser', 'user_permissions', 'groups'}\nfor f in disabled_fields:\n if f in form.base_fields:\n form.b...
<|body_start_0|> form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser disabled_fields: Set[str] = set() if not is_superuser: disabled_fields |= {'username', 'is_staff', 'is_superuser', 'user_permissions', 'groups'} for f in disabled...
A custom admin interface for User instances.
CustomUserAdmin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserAdmin: """A custom admin interface for User instances.""" def get_form(self, request, obj=None, **kwargs): """Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/manage-users-in-django-admin/""" <|body_0|> d...
stack_v2_sparse_classes_36k_train_028978
2,326
permissive
[ { "docstring": "Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/manage-users-in-django-admin/", "name": "get_form", "signature": "def get_form(self, request, obj=None, **kwargs)" }, { "docstring": "Ensure that staff, and only staff, are m...
2
null
Implement the Python class `CustomUserAdmin` described below. Class description: A custom admin interface for User instances. Method signatures and docstrings: - def get_form(self, request, obj=None, **kwargs): Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/m...
Implement the Python class `CustomUserAdmin` described below. Class description: A custom admin interface for User instances. Method signatures and docstrings: - def get_form(self, request, obj=None, **kwargs): Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/m...
47c6377ccbfe8576b35854053d726537e533e78c
<|skeleton|> class CustomUserAdmin: """A custom admin interface for User instances.""" def get_form(self, request, obj=None, **kwargs): """Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/manage-users-in-django-admin/""" <|body_0|> d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomUserAdmin: """A custom admin interface for User instances.""" def get_form(self, request, obj=None, **kwargs): """Restrict the fields that staff can change. For more on the why and how of this see https://realpython.com/manage-users-in-django-admin/""" form = super().get_form(reques...
the_stack_v2_python_sparse
director/users/admin.py
gxf1986/hub
train
0
f336cd96cf813ec8daa9f4ea73b96fa49779c260
[ "self.file_path = source_file\nself.public = IdentifierSet()\nself.doxygen_groupings = []\nself.interfaces = IdentifierDict()\nself.subroutines = IdentifierDict()\nself.constants = IdentifierDict()\nself.types = IdentifierDict()\nself.parse_file(params_only)", "source_lines = _join_lines(open(self.file_path, 'r')...
<|body_start_0|> self.file_path = source_file self.public = IdentifierSet() self.doxygen_groupings = [] self.interfaces = IdentifierDict() self.subroutines = IdentifierDict() self.constants = IdentifierDict() self.types = IdentifierDict() self.parse_file(p...
Info for an individual source file
SourceFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceFile: """Info for an individual source file""" def __init__(self, source_file, params_only=False): """Initialise SourceFile object Arguments: source_file -- Path to the source file""" <|body_0|> def parse_file(self, params_only=False): """Run through file o...
stack_v2_sparse_classes_36k_train_028979
28,119
no_license
[ { "docstring": "Initialise SourceFile object Arguments: source_file -- Path to the source file", "name": "__init__", "signature": "def __init__(self, source_file, params_only=False)" }, { "docstring": "Run through file once, getting everything we'll need", "name": "parse_file", "signatur...
2
stack_v2_sparse_classes_30k_train_006670
Implement the Python class `SourceFile` described below. Class description: Info for an individual source file Method signatures and docstrings: - def __init__(self, source_file, params_only=False): Initialise SourceFile object Arguments: source_file -- Path to the source file - def parse_file(self, params_only=False...
Implement the Python class `SourceFile` described below. Class description: Info for an individual source file Method signatures and docstrings: - def __init__(self, source_file, params_only=False): Initialise SourceFile object Arguments: source_file -- Path to the source file - def parse_file(self, params_only=False...
38c0755396efea44feb87a4c01b5e956d6736691
<|skeleton|> class SourceFile: """Info for an individual source file""" def __init__(self, source_file, params_only=False): """Initialise SourceFile object Arguments: source_file -- Path to the source file""" <|body_0|> def parse_file(self, params_only=False): """Run through file o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SourceFile: """Info for an individual source file""" def __init__(self, source_file, params_only=False): """Initialise SourceFile object Arguments: source_file -- Path to the source file""" self.file_path = source_file self.public = IdentifierSet() self.doxygen_groupings =...
the_stack_v2_python_sparse
bindings/generate_bindings/parse.py
OpenCMISS/iron
train
10
54c6c231c648e443008bc18d68c301b635f4b6e6
[ "self.training_path = kwargs.get('train_data_path')\nself.predict_path = kwargs.get('predict_data_path')\nself.output_path = kwargs.get('output_path')", "training_dataset = load_fn(self.training_path)\nprediction_dataset = load_fn(self.predict_path)\nmodel = train_fn(training_dataset, **options)\npredictions = so...
<|body_start_0|> self.training_path = kwargs.get('train_data_path') self.predict_path = kwargs.get('predict_data_path') self.output_path = kwargs.get('output_path') <|end_body_0|> <|body_start_1|> training_dataset = load_fn(self.training_path) prediction_dataset = load_fn(self.p...
Generic model class for fitting a recommendation model.
Model
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" <|body_0|> def train(self, load_fn, train_fn, predict_fn, store_fn, **options): """Given the functions indicated below, load the tr...
stack_v2_sparse_classes_36k_train_028980
8,553
permissive
[ { "docstring": "Initialize a Model object.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Given the functions indicated below, load the training and prediction datasets, train with the training dataset and predict the values for the prediction dataset. Write...
2
stack_v2_sparse_classes_30k_train_020772
Implement the Python class `Model` described below. Class description: Generic model class for fitting a recommendation model. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize a Model object. - def train(self, load_fn, train_fn, predict_fn, store_fn, **options): Given the functions indicat...
Implement the Python class `Model` described below. Class description: Generic model class for fitting a recommendation model. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize a Model object. - def train(self, load_fn, train_fn, predict_fn, store_fn, **options): Given the functions indicat...
5e0c9efe3405245119bf5aa9bd81a4ca5159eab1
<|skeleton|> class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" <|body_0|> def train(self, load_fn, train_fn, predict_fn, store_fn, **options): """Given the functions indicated below, load the tr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Model: """Generic model class for fitting a recommendation model.""" def __init__(self, **kwargs): """Initialize a Model object.""" self.training_path = kwargs.get('train_data_path') self.predict_path = kwargs.get('predict_data_path') self.output_path = kwargs.get('output_...
the_stack_v2_python_sparse
project2/src/train.py
errikos/ml-makarona
train
0
c3d4b0139cba0453fde7f8e5a03a998c1b172de7
[ "super().__init__()\nself.fc = torch.nn.Linear(latent_dim, num_channels * img_size ** 2)\nself.l1 = torch.nn.Sequential(torch.nn.Conv2d(num_channels * 2, 64, 3, 1, 1), torch.nn.ReLU(inplace=True))\nresblocks = []\nfor _ in range(n_residual_blocks):\n resblocks.append(ResidualBlock(num_filts))\nself.resblocks = t...
<|body_start_0|> super().__init__() self.fc = torch.nn.Linear(latent_dim, num_channels * img_size ** 2) self.l1 = torch.nn.Sequential(torch.nn.Conv2d(num_channels * 2, 64, 3, 1, 1), torch.nn.ReLU(inplace=True)) resblocks = [] for _ in range(n_residual_blocks): resbloc...
The generator topology
Generator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: """The generator topology""" def __init__(self, latent_dim, num_channels, img_size, n_residual_blocks, num_filts=64): """Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number of image channels to generate img_size : int number of pix...
stack_v2_sparse_classes_36k_train_028981
5,861
permissive
[ { "docstring": "Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number of image channels to generate img_size : int number of pixels per side of the image n_residual_blocks : int number of residual blocks inside the generator num_filts : int number of filters inside each o...
2
null
Implement the Python class `Generator` described below. Class description: The generator topology Method signatures and docstrings: - def __init__(self, latent_dim, num_channels, img_size, n_residual_blocks, num_filts=64): Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number o...
Implement the Python class `Generator` described below. Class description: The generator topology Method signatures and docstrings: - def __init__(self, latent_dim, num_channels, img_size, n_residual_blocks, num_filts=64): Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number o...
1078f5030b8aac2bf022daf5fa14d66f74c3c893
<|skeleton|> class Generator: """The generator topology""" def __init__(self, latent_dim, num_channels, img_size, n_residual_blocks, num_filts=64): """Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number of image channels to generate img_size : int number of pix...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: """The generator topology""" def __init__(self, latent_dim, num_channels, img_size, n_residual_blocks, num_filts=64): """Parameters ---------- latent_dim : int size of the latent dimension num_channels : int number of image channels to generate img_size : int number of pixels per side ...
the_stack_v2_python_sparse
dlutils/models/gans/pixel_da/models.py
justusschock/dl-utils
train
15
8f71499291f0f9a084fddc33c479e83367e52ca0
[ "if not PolicyCapabilitiesType._is_valid(type):\n raise OnepIllegalArgumentException('invalid policy type')\nself.policy_type = type\nself.network_element = element\nself.session_id = element.session_handle._id\nself.client = Client(element.api_protocol)\nself.table = {'type': None, 'actions': [], 'matches': []}...
<|body_start_0|> if not PolicyCapabilitiesType._is_valid(type): raise OnepIllegalArgumentException('invalid policy type') self.policy_type = type self.network_element = element self.session_id = element.session_handle._id self.client = Client(element.api_protocol) ...
Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() ****************
PolicyCapabilities
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PolicyCapabilities: """Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() ****************""" def __init__(self, type, element): """Class ...
stack_v2_sparse_classes_36k_train_028982
15,793
no_license
[ { "docstring": "Class PolicyCapabilities. @param type: PolicyCapabilitiesType for type of policy @type type: {PolicyCapabilitiesType<onep.policyservice.caps.PolicyCapabilitiesType>} @param element: NetworkElement instance. @type element: {NetworkElement<onep.element.NetworkElement>} @raise OnepIllegalArgumentEx...
3
null
Implement the Python class `PolicyCapabilities` described below. Class description: Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() **************** Method signatures an...
Implement the Python class `PolicyCapabilities` described below. Class description: Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() **************** Method signatures an...
54bc49eaed14f7832aca45c4f52311a00282d862
<|skeleton|> class PolicyCapabilities: """Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() ****************""" def __init__(self, type, element): """Class ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PolicyCapabilities: """Internal PolicyCapabilities class stores the capabilities of the Network Element. ***DEPRECATED*** classmethods get_capabilities and get_table_capabilities Please use caps.get_table_capabilities() ****************""" def __init__(self, type, element): """Class PolicyCapabil...
the_stack_v2_python_sparse
onepk_without_pyc/onep/policyservice/caps.py
neoyogi/onepk
train
0
683859b8ebbb5d83222e3e406b7333fa266a277e
[ "if not shape:\n pytest.skip('Cannot expand the dimensions of a Python scalar!')\nt1 = np.empty(shape).tolist()\nt2 = fn.expand_dims(t1, axis=axis)\nassert t2.shape == new_shape", "t1 = np.empty(shape)\nt2 = fn.expand_dims(t1, axis=axis)\nassert t2.shape == new_shape\nassert isinstance(t2, np.ndarray)", "t1 ...
<|body_start_0|> if not shape: pytest.skip('Cannot expand the dimensions of a Python scalar!') t1 = np.empty(shape).tolist() t2 = fn.expand_dims(t1, axis=axis) assert t2.shape == new_shape <|end_body_0|> <|body_start_1|> t1 = np.empty(shape) t2 = fn.expand_di...
Tests for the expand_dims function
TestExpandDims
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestExpandDims: """Tests for the expand_dims function""" def test_expand_dims_sequence(self, shape, axis, new_shape): """Test that expand_dimensions works correctly when given a sequence""" <|body_0|> def test_expand_dims_array(self, shape, axis, new_shape): """T...
stack_v2_sparse_classes_36k_train_028983
47,600
permissive
[ { "docstring": "Test that expand_dimensions works correctly when given a sequence", "name": "test_expand_dims_sequence", "signature": "def test_expand_dims_sequence(self, shape, axis, new_shape)" }, { "docstring": "Test that expand_dimensions works correctly when given an array", "name": "te...
4
null
Implement the Python class `TestExpandDims` described below. Class description: Tests for the expand_dims function Method signatures and docstrings: - def test_expand_dims_sequence(self, shape, axis, new_shape): Test that expand_dimensions works correctly when given a sequence - def test_expand_dims_array(self, shape...
Implement the Python class `TestExpandDims` described below. Class description: Tests for the expand_dims function Method signatures and docstrings: - def test_expand_dims_sequence(self, shape, axis, new_shape): Test that expand_dimensions works correctly when given a sequence - def test_expand_dims_array(self, shape...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class TestExpandDims: """Tests for the expand_dims function""" def test_expand_dims_sequence(self, shape, axis, new_shape): """Test that expand_dimensions works correctly when given a sequence""" <|body_0|> def test_expand_dims_array(self, shape, axis, new_shape): """T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestExpandDims: """Tests for the expand_dims function""" def test_expand_dims_sequence(self, shape, axis, new_shape): """Test that expand_dimensions works correctly when given a sequence""" if not shape: pytest.skip('Cannot expand the dimensions of a Python scalar!') t...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
eeb1c03ca48b80c113cd4dd2626fe042363f071b
[ "preprocessor = BinaryChecker(num_variables, phenome_preprocessor)\nTestProblem.__init__(self, one_max, num_objectives=1, phenome_preprocessor=preprocessor, **kwargs)\nself.num_variables = num_variables\nself.is_deterministic = True\nself.do_maximize = True", "assert max_number is None or max_number > 0\nopt = In...
<|body_start_0|> preprocessor = BinaryChecker(num_variables, phenome_preprocessor) TestProblem.__init__(self, one_max, num_objectives=1, phenome_preprocessor=preprocessor, **kwargs) self.num_variables = num_variables self.is_deterministic = True self.do_maximize = True <|end_body...
The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized.
OneMax
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OneMax: """The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized.""" def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs): """Constructor. Parameters ---------- num_variables : in...
stack_v2_sparse_classes_36k_train_028984
7,172
permissive
[ { "docstring": "Constructor. Parameters ---------- num_variables : int, optional The search space dimension. phenome_preprocessor : callable, optional A callable potentially applying transformations or checks to the phenome. Modifications should only be applied to a copy of the input. The (modified) phenome mus...
2
stack_v2_sparse_classes_30k_train_010441
Implement the Python class `OneMax` described below. Class description: The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized. Method signatures and docstrings: - def __init__(self, num_variables=30, phenome_preprocessor=None, **kwarg...
Implement the Python class `OneMax` described below. Class description: The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized. Method signatures and docstrings: - def __init__(self, num_variables=30, phenome_preprocessor=None, **kwarg...
df14bf0cc263d8fa0ad0a539e94327ac35e33d1c
<|skeleton|> class OneMax: """The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized.""" def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs): """Constructor. Parameters ---------- num_variables : in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OneMax: """The most simple binary optimization problem. .. note:: In contrast to most other problems in this package, this problem must be maximized.""" def __init__(self, num_variables=30, phenome_preprocessor=None, **kwargs): """Constructor. Parameters ---------- num_variables : int, optional T...
the_stack_v2_python_sparse
pybandit/optproblems/binary.py
chunjenpeng/pyBandit
train
0
5163a39a3ba3038af6cae509580ddedbda2cbc1a
[ "params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))\nparams['image_id'] = image_id\nform = MultiGetForm(params)\nif not form.is_valid():\n raise BadRequestException()\nreturn Response(form.submit(request))", "params = dict(((key, val) for key, val in request.DATA.iteritems()))\nparams...
<|body_start_0|> params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems())) params['image_id'] = image_id form = MultiGetForm(params) if not form.is_valid(): raise BadRequestException() return Response(form.submit(request)) <|end_body_0|> <|body_sta...
Class for rendering the view for creating TagGroups and searching through the TagGroups.
TagGroupList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagGroupList: """Class for rendering the view for creating TagGroups and searching through the TagGroups.""" def get(self, request, image_id): """Method for getting multiple TagGroups either through search or general listing.""" <|body_0|> def post(self, request, image_i...
stack_v2_sparse_classes_36k_train_028985
2,816
no_license
[ { "docstring": "Method for getting multiple TagGroups either through search or general listing.", "name": "get", "signature": "def get(self, request, image_id)" }, { "docstring": "Method for creating a new TagGroup.", "name": "post", "signature": "def post(self, request, image_id)" } ]
2
stack_v2_sparse_classes_30k_train_013443
Implement the Python class `TagGroupList` described below. Class description: Class for rendering the view for creating TagGroups and searching through the TagGroups. Method signatures and docstrings: - def get(self, request, image_id): Method for getting multiple TagGroups either through search or general listing. -...
Implement the Python class `TagGroupList` described below. Class description: Class for rendering the view for creating TagGroups and searching through the TagGroups. Method signatures and docstrings: - def get(self, request, image_id): Method for getting multiple TagGroups either through search or general listing. -...
22c1ce3c5a8e4ed99c2f014672d60ad3c5a4003c
<|skeleton|> class TagGroupList: """Class for rendering the view for creating TagGroups and searching through the TagGroups.""" def get(self, request, image_id): """Method for getting multiple TagGroups either through search or general listing.""" <|body_0|> def post(self, request, image_i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TagGroupList: """Class for rendering the view for creating TagGroups and searching through the TagGroups.""" def get(self, request, image_id): """Method for getting multiple TagGroups either through search or general listing.""" params = dict(((key, val) for key, val in request.QUERY_PARA...
the_stack_v2_python_sparse
biodig/rest/v2/TagGroups/views.py
asmariyaz23/BioDIG
train
0
b8ada245e20ca67d18c0332cf4d854bb7cca1d89
[ "SYMBOL_SEPARATOR = ' '\nSYMBOL_NONE = 'X'\nif root == None:\n return ''\nqueue = Queue()\nqueue.put(root)\nans_str = ''\nwhile not queue.empty():\n cur_node = queue.get()\n ans_str += SYMBOL_SEPARATOR + (str(cur_node.val) if cur_node else SYMBOL_NONE)\n if cur_node:\n queue.put(cur_node.left)\n ...
<|body_start_0|> SYMBOL_SEPARATOR = ' ' SYMBOL_NONE = 'X' if root == None: return '' queue = Queue() queue.put(root) ans_str = '' while not queue.empty(): cur_node = queue.get() ans_str += SYMBOL_SEPARATOR + (str(cur_node.val) i...
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_028986
3,349
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_014266
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:...
e31ec989daf70bb4cba69e35e351fc970e93dc34
<|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""" SYMBOL_SEPARATOR = ' ' SYMBOL_NONE = 'X' if root == None: return '' queue = Queue() queue.put(root) ans_str = '' while not que...
the_stack_v2_python_sparse
Hard/#297_Serialize_and_Deserialize_Binary_Tree.py
AlphaGarden/LeetCodeProblems
train
0
e1a5d220b5cd9e086b6acf1e824790feda584e0d
[ "temp = matrix[x1][y1]\nmatrix[x1][y1] = matrix[x2][y2]\nmatrix[x2][y2] = temp", "if matrix == None or len(matrix) < 1:\n return matrix\nfor i in range(len(matrix) - 1):\n j = i\n while j < len(matrix[0]):\n self.swap(matrix, i, j, j, i)\n j += 1\nfor i in range(len(matrix)):\n for j in ...
<|body_start_0|> temp = matrix[x1][y1] matrix[x1][y1] = matrix[x2][y2] matrix[x2][y2] = temp <|end_body_0|> <|body_start_1|> if matrix == None or len(matrix) < 1: return matrix for i in range(len(matrix) - 1): j = i while j < len(matrix[0]): ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int): """交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2""" <|body_0|> def rotate(self, matrix: List[List[int]]) -> List[List[int]]: """旋转数组 Args: matrix:二维数组 Returns: 旋转后数组"...
stack_v2_sparse_classes_36k_train_028987
2,452
permissive
[ { "docstring": "交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2", "name": "swap", "signature": "def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int)" }, { "docstring": "旋转数组 Args: matrix:二维数组 Returns: 旋转后数组", "name": "rotate", "signature": "def rotate(s...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int): 交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2 - def rotate(self, matrix: List[List[int]...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int): 交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2 - def rotate(self, matrix: List[List[int]...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int): """交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2""" <|body_0|> def rotate(self, matrix: List[List[int]]) -> List[List[int]]: """旋转数组 Args: matrix:二维数组 Returns: 旋转后数组"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def swap(self, matrix: List[List[int]], x1: int, y1: int, x2: int, y2: int): """交换位置 Args: matrix: 二维数组 x1: 位置x1 y1: 位置y2 x2: 位置x2 y2: 位置y2""" temp = matrix[x1][y1] matrix[x1][y1] = matrix[x2][y2] matrix[x2][y2] = temp def rotate(self, matrix: List[List[int]]) ->...
the_stack_v2_python_sparse
src/leetcodepython/array/rotate_image_48.py
zhangyu345293721/leetcode
train
101
8134be26b083bea97f14a1f9d00d6aa12556a004
[ "super(MultiHeadedAttention, self).__init__()\nassert n_feat % n_head == 0\nself.d_k = n_feat // n_head\nself.h = n_head\nself.linear_q = nn.Linear(n_feat, n_feat)\nself.linear_k = nn.Linear(n_feat, n_feat)\nself.linear_v = nn.Linear(n_feat, n_feat)\nself.linear_out = nn.Linear(n_feat, n_feat)\nself.attn = None\nse...
<|body_start_0|> super(MultiHeadedAttention, self).__init__() assert n_feat % n_head == 0 self.d_k = n_feat // n_head self.h = n_head self.linear_q = nn.Linear(n_feat, n_feat) self.linear_k = nn.Linear(n_feat, n_feat) self.linear_v = nn.Linear(n_feat, n_feat) ...
Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
MultiHeadedAttention
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadedAttention: """Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.""" def __init__(self, n_head, n_feat, dropout_rate): """Construct an MultiHeadedAttention object.""" <|body_...
stack_v2_sparse_classes_36k_train_028988
37,737
permissive
[ { "docstring": "Construct an MultiHeadedAttention object.", "name": "__init__", "signature": "def __init__(self, n_head, n_feat, dropout_rate)" }, { "docstring": "Transform query, key and value. Args: query (torch.Tensor): Query tensor (#batch, time1, size). key (torch.Tensor): Key tensor (#batc...
4
null
Implement the Python class `MultiHeadedAttention` described below. Class description: Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. Method signatures and docstrings: - def __init__(self, n_head, n_feat, dropout_rate): Con...
Implement the Python class `MultiHeadedAttention` described below. Class description: Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. Method signatures and docstrings: - def __init__(self, n_head, n_feat, dropout_rate): Con...
31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39
<|skeleton|> class MultiHeadedAttention: """Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.""" def __init__(self, n_head, n_feat, dropout_rate): """Construct an MultiHeadedAttention object.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadedAttention: """Multi-Head Attention layer. Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.""" def __init__(self, n_head, n_feat, dropout_rate): """Construct an MultiHeadedAttention object.""" super(MultiHeadedAtt...
the_stack_v2_python_sparse
SVS/model/layers/conformer_related.py
SJTMusicTeam/SVS_system
train
85
7776fca1408bc2170bef0554f52b54f584dd285b
[ "def encode(word):\n cnt = [0] * 26\n for c in word:\n cnt[ord(c) - ord('a')] += 1\n return tuple(cnt)\n\ndef decode(cnt):\n ret = ''\n for i, c in enumerate(cnt):\n ret += chr(ord('a') + i) * c\n return ret\nchars = set(target)\nencoded = [encode(word) for word in stickers if set(wo...
<|body_start_0|> def encode(word): cnt = [0] * 26 for c in word: cnt[ord(c) - ord('a')] += 1 return tuple(cnt) def decode(cnt): ret = '' for i, c in enumerate(cnt): ret += chr(ord('a') + i) * c retur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minStickers(self, stickers: List[str], target: str) -> int: """11/28/2022 15:49 TLE""" <|body_0|> def minStickers(self, stickers: List[str], target: str) -> int: """11/28/2022 16:12""" <|body_1|> <|end_skeleton|> <|body_start_0|> def e...
stack_v2_sparse_classes_36k_train_028989
5,124
no_license
[ { "docstring": "11/28/2022 15:49 TLE", "name": "minStickers", "signature": "def minStickers(self, stickers: List[str], target: str) -> int" }, { "docstring": "11/28/2022 16:12", "name": "minStickers", "signature": "def minStickers(self, stickers: List[str], target: str) -> int" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minStickers(self, stickers: List[str], target: str) -> int: 11/28/2022 15:49 TLE - def minStickers(self, stickers: List[str], target: str) -> int: 11/28/2022 16:12
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minStickers(self, stickers: List[str], target: str) -> int: 11/28/2022 15:49 TLE - def minStickers(self, stickers: List[str], target: str) -> int: 11/28/2022 16:12 <|skeleto...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def minStickers(self, stickers: List[str], target: str) -> int: """11/28/2022 15:49 TLE""" <|body_0|> def minStickers(self, stickers: List[str], target: str) -> int: """11/28/2022 16:12""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: """11/28/2022 15:49 TLE""" def encode(word): cnt = [0] * 26 for c in word: cnt[ord(c) - ord('a')] += 1 return tuple(cnt) def decode(cnt): ret = '' ...
the_stack_v2_python_sparse
leetcode/solved/691_Stickers_to_Spell_Word/solution.py
sungminoh/algorithms
train
0
8608529dd0f3264f6a197bc52250d2a6181bb4bc
[ "Utility.set_attributes(self, task)\nself._operands = task.get('operands', [])\nif not self._operands:\n raise ValueError('`Operator` must have at least one operand.')\nself._result = task.get('result', 'result')\nself._op = self.ops.get(task.get('operator', '+'), np.add)", "ops = ['dense_' + x if self._wants_...
<|body_start_0|> Utility.set_attributes(self, task) self._operands = task.get('operands', []) if not self._operands: raise ValueError('`Operator` must have at least one operand.') self._result = task.get('result', 'result') self._op = self.ops.get(task.get('operator',...
Template class for photosphere Modules.
Operator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Operator: """Template class for photosphere Modules.""" def set_attributes(self, task): """Set key replacement dictionary.""" <|body_0|> def process(self, **kwargs): """Process module.""" <|body_1|> <|end_skeleton|> <|body_start_0|> Utility.set_...
stack_v2_sparse_classes_36k_train_028990
1,131
permissive
[ { "docstring": "Set key replacement dictionary.", "name": "set_attributes", "signature": "def set_attributes(self, task)" }, { "docstring": "Process module.", "name": "process", "signature": "def process(self, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_val_000767
Implement the Python class `Operator` described below. Class description: Template class for photosphere Modules. Method signatures and docstrings: - def set_attributes(self, task): Set key replacement dictionary. - def process(self, **kwargs): Process module.
Implement the Python class `Operator` described below. Class description: Template class for photosphere Modules. Method signatures and docstrings: - def set_attributes(self, task): Set key replacement dictionary. - def process(self, **kwargs): Process module. <|skeleton|> class Operator: """Template class for p...
7e7779b6932955eb3875ebab5fe3fd28745eeb17
<|skeleton|> class Operator: """Template class for photosphere Modules.""" def set_attributes(self, task): """Set key replacement dictionary.""" <|body_0|> def process(self, **kwargs): """Process module.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Operator: """Template class for photosphere Modules.""" def set_attributes(self, task): """Set key replacement dictionary.""" Utility.set_attributes(self, task) self._operands = task.get('operands', []) if not self._operands: raise ValueError('`Operator` must h...
the_stack_v2_python_sparse
mosfit/modules/utilities/operator.py
guillochon/MOSFiT
train
36
7ae19a18b4c5fb7d095a1bca020a7ca7d3230f86
[ "with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device:\n CrOS_AU = auto_updater.ChromiumOSUpdater(device, 'fake/image', self.payload_dir)\n auto_updater.DELAY_SEC_FOR_RETRY = 10\n auto_updater.MAX_RETRY = 1\n transfer_devserver = self.PatchObject(auto_updater.ChromiumOSFlashUpdater, 'Transfer...
<|body_start_0|> with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device: CrOS_AU = auto_updater.ChromiumOSUpdater(device, 'fake/image', self.payload_dir) auto_updater.DELAY_SEC_FOR_RETRY = 10 auto_updater.MAX_RETRY = 1 transfer_devserver = self.PatchObjec...
Test whether ChromiumOSUpdater's transfer functions are retried.
ChromiumOSUpdaterRetryTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" <|body_0|> def testErrorTriggerRetryTransferStateful(self): """Te...
stack_v2_sparse_classes_36k_train_028991
20,190
permissive
[ { "docstring": "Test ChromiumOSUpdate is retried properly.", "name": "testErrorTriggerRetryTransferDevServer", "signature": "def testErrorTriggerRetryTransferDevServer(self)" }, { "docstring": "Test ChromiumOSUpdate is retried properly.", "name": "testErrorTriggerRetryTransferStateful", ...
3
null
Implement the Python class `ChromiumOSUpdaterRetryTest` described below. Class description: Test whether ChromiumOSUpdater's transfer functions are retried. Method signatures and docstrings: - def testErrorTriggerRetryTransferDevServer(self): Test ChromiumOSUpdate is retried properly. - def testErrorTriggerRetryTrans...
Implement the Python class `ChromiumOSUpdaterRetryTest` described below. Class description: Test whether ChromiumOSUpdater's transfer functions are retried. Method signatures and docstrings: - def testErrorTriggerRetryTransferDevServer(self): Test ChromiumOSUpdate is retried properly. - def testErrorTriggerRetryTrans...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" <|body_0|> def testErrorTriggerRetryTransferStateful(self): """Te...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChromiumOSUpdaterRetryTest: """Test whether ChromiumOSUpdater's transfer functions are retried.""" def testErrorTriggerRetryTransferDevServer(self): """Test ChromiumOSUpdate is retried properly.""" with remote_access.ChromiumOSDeviceHandler('1.1.1.1') as device: CrOS_AU = auto...
the_stack_v2_python_sparse
third_party/chromite/lib/auto_updater_unittest.py
metux/chromium-suckless
train
5
7ba258f58991cac4ff68f21670e74127361cda2f
[ "self.offset = offset\nself.p = p\nself.down_scale = 1", "num_examples = len(data[0])\nfor i in range(num_examples):\n if np.random.uniform(0, 1) > self.p:\n continue\n offset = [self.down_scale * np.random.randint(-self.offset, self.offset + 1) for l in range(2)]\n data[0][i] = self.embed_image(d...
<|body_start_0|> self.offset = offset self.p = p self.down_scale = 1 <|end_body_0|> <|body_start_1|> num_examples = len(data[0]) for i in range(num_examples): if np.random.uniform(0, 1) > self.p: continue offset = [self.down_scale * np.ran...
Augments the images by translating the content and applying reflection padding.
TranslationAugmentor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TranslationAugmentor: """Augments the images by translating the content and applying reflection padding.""" def __init__(self, offset=40, p=1): """Initializes a new instance of the TranslationAugmentor class. :param offset: The offset by which the image is randomly translated. :param...
stack_v2_sparse_classes_36k_train_028992
5,227
no_license
[ { "docstring": "Initializes a new instance of the TranslationAugmentor class. :param offset: The offset by which the image is randomly translated. :param p: The probability that this will be applied.", "name": "__init__", "signature": "def __init__(self, offset=40, p=1)" }, { "docstring": "Augme...
4
stack_v2_sparse_classes_30k_train_004930
Implement the Python class `TranslationAugmentor` described below. Class description: Augments the images by translating the content and applying reflection padding. Method signatures and docstrings: - def __init__(self, offset=40, p=1): Initializes a new instance of the TranslationAugmentor class. :param offset: The...
Implement the Python class `TranslationAugmentor` described below. Class description: Augments the images by translating the content and applying reflection padding. Method signatures and docstrings: - def __init__(self, offset=40, p=1): Initializes a new instance of the TranslationAugmentor class. :param offset: The...
d494b3041069d377d6a7a9c296a14334f2fa5acc
<|skeleton|> class TranslationAugmentor: """Augments the images by translating the content and applying reflection padding.""" def __init__(self, offset=40, p=1): """Initializes a new instance of the TranslationAugmentor class. :param offset: The offset by which the image is randomly translated. :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TranslationAugmentor: """Augments the images by translating the content and applying reflection padding.""" def __init__(self, offset=40, p=1): """Initializes a new instance of the TranslationAugmentor class. :param offset: The offset by which the image is randomly translated. :param p: The proba...
the_stack_v2_python_sparse
python/TobyPDE_FRRN/FRRN-master/dltools/augmentation.py
LiuFang816/SALSTM_py_data
train
10
b2c8849b114ffbfe4722b43a1884203fb935c767
[ "self._num_classes = num_classes\nself._num_convs = num_convs\nself._num_filters = num_filters\nif use_separable_conv:\n self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initializer=tf.zeros_initializer())\nelse:\n self._conv2d_op = functools.partial(tf.layers.conv2d, k...
<|body_start_0|> self._num_classes = num_classes self._num_convs = num_convs self._num_filters = num_filters if use_separable_conv: self._conv2d_op = functools.partial(tf.layers.separable_conv2d, depth_multiplier=1, bias_initializer=tf.zeros_initializer()) else: ...
Fast R-CNN box head.
FastrcnnHead
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FastrcnnHead: """Fast R-CNN box head.""" def __init__(self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_bbox_pred=Fals...
stack_v2_sparse_classes_36k_train_028993
46,218
permissive
[ { "docstring": "Initialize params to build Fast R-CNN box head. Args: num_classes: an integer for the number of classes. num_convs: `int` number that represents the number of the intermediate conv layers before the FC layers. num_filters: `int` number that represents the number of filters of the intermediate co...
2
null
Implement the Python class `FastrcnnHead` described below. Class description: Fast R-CNN box head. Method signatures and docstrings: - def __init__(self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.B...
Implement the Python class `FastrcnnHead` described below. Class description: Fast R-CNN box head. Method signatures and docstrings: - def __init__(self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.B...
0f7adb97a93ec3e3485c261d030c507eb16b33e4
<|skeleton|> class FastrcnnHead: """Fast R-CNN box head.""" def __init__(self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_bbox_pred=Fals...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FastrcnnHead: """Fast R-CNN box head.""" def __init__(self, num_classes, num_convs=0, num_filters=256, use_separable_conv=False, num_fcs=2, fc_dims=1024, activation='relu', use_batch_norm=True, batch_norm_activation=nn_ops.BatchNormActivation(activation='relu'), class_agnostic_bbox_pred=False): "...
the_stack_v2_python_sparse
models/official/detection/modeling/architecture/heads.py
tensorflow/tpu
train
5,627
dafb2f0a33749f4fb47c1515e43f573e0de39a0c
[ "super().__init__(self)\nself.drink = other_order.drink\nself.addons = addons\nself.size = other_order.size", "total = Order.Sizecost[self.size]\ntotal += Order.Drinks[self.drink]\nfirst = True\nfor addon in self.addons:\n if first:\n first = False\n continue\n total += Order.Extras[addon]\nre...
<|body_start_0|> super().__init__(self) self.drink = other_order.drink self.addons = addons self.size = other_order.size <|end_body_0|> <|body_start_1|> total = Order.Sizecost[self.size] total += Order.Drinks[self.drink] first = True for addon in self.add...
Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found in the Extras dictionary are valid
Extra
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Extra: """Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found in the Extras dictionary are valid""" ...
stack_v2_sparse_classes_36k_train_028994
5,948
no_license
[ { "docstring": "Initializes an Extra object, an Order object with a list of addons Parameters ---------- other_order: Order Order object from which the base drink string is inherited addons : list List with strings for extras added, as found in Extras", "name": "__init__", "signature": "def __init__(sel...
3
stack_v2_sparse_classes_30k_train_004841
Implement the Python class `Extra` described below. Class description: Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found...
Implement the Python class `Extra` described below. Class description: Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found...
411a9e07898277af84cd7cc1fdae89545d5b893a
<|skeleton|> class Extra: """Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found in the Extras dictionary are valid""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Extra: """Class that extends order to store a list of extras Attributes ---------- drink : str String representing the base drink, taken from a base order object addons : list List containing any extras as strings added to the Order object, only extras found in the Extras dictionary are valid""" def __in...
the_stack_v2_python_sparse
T02/T02-2.py
NRL-Plasma-Physics-Division/turbopy-training-public
train
3
21150f240eca3a16f11dcb8503c350d619b6eae3
[ "self.cutoff = cutoff\nif contact_bins is None:\n self.contact_bins = SPLIF_CONTACT_BINS\nelse:\n self.contact_bins = contact_bins\nself.size = size\nself.radius = radius\nself.box_width = box_width\nself.voxel_width = voxel_width\nself.voxels_per_edge = int(self.box_width / self.voxel_width)", "if 'complex...
<|body_start_0|> self.cutoff = cutoff if contact_bins is None: self.contact_bins = SPLIF_CONTACT_BINS else: self.contact_bins = contact_bins self.size = size self.radius = radius self.box_width = box_width self.voxel_width = voxel_width ...
Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel in which they originated. This technique may be useful for downstream learning me...
SplifVoxelizer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplifVoxelizer: """Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel in which they originated. This techniqu...
stack_v2_sparse_classes_36k_train_028995
11,465
permissive
[ { "docstring": "Parameters ---------- cutoff: float (default 4.5) Distance cutoff in angstroms for molecules in complex. contact_bins: list[tuple] List of contact bins. If not specified is set to default `[(0, 2.0), (2.0, 3.0), (3.0, 4.5)]`. radius : int, optional (default 2) Fingerprint radius used for circula...
2
null
Implement the Python class `SplifVoxelizer` described below. Class description: Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel ...
Implement the Python class `SplifVoxelizer` described below. Class description: Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel ...
ee6e67ebcf7bf04259cf13aff6388e2b791fea3d
<|skeleton|> class SplifVoxelizer: """Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel in which they originated. This techniqu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SplifVoxelizer: """Computes SPLIF voxel grid for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper [1]_. The SPLIF voxelizer localizes local SPLIF descriptors in space, by assigning features to the voxel in which they originated. This technique may be usef...
the_stack_v2_python_sparse
deepchem/feat/complex_featurizers/splif_fingerprints.py
deepchem/deepchem
train
4,876
84930f7e60a31d5b3956f149d5335bb3fed48465
[ "verify_client_object(client)\nself.client = client\nself.loggit = logging.getLogger('curator.actions.cluster_routing')\nself.wfc = wait_for_completion\nself.wait_interval = wait_interval\nself.max_wait = max_wait\nif setting != 'enable':\n raise ValueError(f'Invalid value for \"setting\": {setting}.')\nif routi...
<|body_start_0|> verify_client_object(client) self.client = client self.loggit = logging.getLogger('curator.actions.cluster_routing') self.wfc = wait_for_completion self.wait_interval = wait_interval self.max_wait = max_wait if setting != 'enable': rai...
ClusterRouting Action Class
ClusterRouting
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClusterRouting: """ClusterRouting Action Class""" def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=-1): """For now, the cluster routing settings are hardcoded to be ``transient`` :param client: A client conne...
stack_v2_sparse_classes_36k_train_028996
4,374
permissive
[ { "docstring": "For now, the cluster routing settings are hardcoded to be ``transient`` :param client: A client connection object :param routing_type: Type of routing to apply. Either ``allocation`` or ``rebalance`` :param setting: Currently, the only acceptable value for ``setting`` is ``enable``. This is here...
3
stack_v2_sparse_classes_30k_train_011936
Implement the Python class `ClusterRouting` described below. Class description: ClusterRouting Action Class Method signatures and docstrings: - def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=-1): For now, the cluster routing settings are ha...
Implement the Python class `ClusterRouting` described below. Class description: ClusterRouting Action Class Method signatures and docstrings: - def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=-1): For now, the cluster routing settings are ha...
b41743a061ad790820affe7acee5f71abe819357
<|skeleton|> class ClusterRouting: """ClusterRouting Action Class""" def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=-1): """For now, the cluster routing settings are hardcoded to be ``transient`` :param client: A client conne...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClusterRouting: """ClusterRouting Action Class""" def __init__(self, client, routing_type=None, setting=None, value=None, wait_for_completion=False, wait_interval=9, max_wait=-1): """For now, the cluster routing settings are hardcoded to be ``transient`` :param client: A client connection object ...
the_stack_v2_python_sparse
curator/actions/cluster_routing.py
volatilemolotov/curator
train
0
6f2301e3e6bd43e8a82926349a880ca4b23fdc3b
[ "ts = int(datetime.now(timezone.utc).timestamp() * 1000)\nurl_suffix, _json = prepare_get_changes(ts)\nassert url_suffix == 'get_changes', f'prepare_get_changes\\n\\treturns url_suffix: {url_suffix}\\n\\tinstead url_suffix: get_changes'\nassert _json == {'last_update_ts': ts}", "url_suffix, iocs = prepare_enable_...
<|body_start_0|> ts = int(datetime.now(timezone.utc).timestamp() * 1000) url_suffix, _json = prepare_get_changes(ts) assert url_suffix == 'get_changes', f'prepare_get_changes\n\treturns url_suffix: {url_suffix}\n\tinstead url_suffix: get_changes' assert _json == {'last_update_ts': ts} <|...
TestPrepareCommands
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPrepareCommands: def test_prepare_get_changes(self): """Given: - get changes command Then: - Verify url and json format.""" <|body_0|> def test_prepare_enable_iocs(self): """Given: - enable iocs command Then: - Verify url and json format.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_028997
41,271
permissive
[ { "docstring": "Given: - get changes command Then: - Verify url and json format.", "name": "test_prepare_get_changes", "signature": "def test_prepare_get_changes(self)" }, { "docstring": "Given: - enable iocs command Then: - Verify url and json format.", "name": "test_prepare_enable_iocs", ...
3
stack_v2_sparse_classes_30k_train_006574
Implement the Python class `TestPrepareCommands` described below. Class description: Implement the TestPrepareCommands class. Method signatures and docstrings: - def test_prepare_get_changes(self): Given: - get changes command Then: - Verify url and json format. - def test_prepare_enable_iocs(self): Given: - enable i...
Implement the Python class `TestPrepareCommands` described below. Class description: Implement the TestPrepareCommands class. Method signatures and docstrings: - def test_prepare_get_changes(self): Given: - get changes command Then: - Verify url and json format. - def test_prepare_enable_iocs(self): Given: - enable i...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestPrepareCommands: def test_prepare_get_changes(self): """Given: - get changes command Then: - Verify url and json format.""" <|body_0|> def test_prepare_enable_iocs(self): """Given: - enable iocs command Then: - Verify url and json format.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPrepareCommands: def test_prepare_get_changes(self): """Given: - get changes command Then: - Verify url and json format.""" ts = int(datetime.now(timezone.utc).timestamp() * 1000) url_suffix, _json = prepare_get_changes(ts) assert url_suffix == 'get_changes', f'prepare_get_...
the_stack_v2_python_sparse
Packs/CortexXDR/Integrations/XDR_iocs/XDR_iocs_test.py
demisto/content
train
1,023
fc5e6fda819be04c471b8b857ae069ee6a74b348
[ "self.bot = bot\nself.query = query\nself.user = user\nself.data = self.query.data.split(':')\nself.callback_type = CallbackType(int(self.data[0]))\nself.payload = self.data[1]\ntry:\n self.action = int(self.data[2])\nexcept ValueError:\n self.action = self.data[2]\nself.poll = session.query(Poll).get(self.pa...
<|body_start_0|> self.bot = bot self.query = query self.user = user self.data = self.query.data.split(':') self.callback_type = CallbackType(int(self.data[0])) self.payload = self.data[1] try: self.action = int(self.data[2]) except ValueError: ...
Contains all important information for handling with callbacks.
CallbackContext
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CallbackContext: """Contains all important information for handling with callbacks.""" def __init__(self, session: scoped_session, bot, query, user): """Create a new CallbackContext from a query.""" <|body_0|> def __repr__(self): """Print as string.""" <|...
stack_v2_sparse_classes_36k_train_028998
2,066
permissive
[ { "docstring": "Create a new CallbackContext from a query.", "name": "__init__", "signature": "def __init__(self, session: scoped_session, bot, query, user)" }, { "docstring": "Print as string.", "name": "__repr__", "signature": "def __repr__(self)" } ]
2
null
Implement the Python class `CallbackContext` described below. Class description: Contains all important information for handling with callbacks. Method signatures and docstrings: - def __init__(self, session: scoped_session, bot, query, user): Create a new CallbackContext from a query. - def __repr__(self): Print as ...
Implement the Python class `CallbackContext` described below. Class description: Contains all important information for handling with callbacks. Method signatures and docstrings: - def __init__(self, session: scoped_session, bot, query, user): Create a new CallbackContext from a query. - def __repr__(self): Print as ...
4e1beae329326296b8ee6b55bef62cfce1aa0e55
<|skeleton|> class CallbackContext: """Contains all important information for handling with callbacks.""" def __init__(self, session: scoped_session, bot, query, user): """Create a new CallbackContext from a query.""" <|body_0|> def __repr__(self): """Print as string.""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CallbackContext: """Contains all important information for handling with callbacks.""" def __init__(self, session: scoped_session, bot, query, user): """Create a new CallbackContext from a query.""" self.bot = bot self.query = query self.user = user self.data = sel...
the_stack_v2_python_sparse
pollbot/telegram/callback_handler/context.py
Nukesor/ultimate-poll-bot
train
147
180af0e2f8459b3b0b6b121af00fb575b9d8f0f0
[ "if not nums:\n return 0\nm = -float('inf')\ni = 0\nwhile i < len(nums) and nums[i] == 0:\n i += 1\nif i > 0:\n m = 0\nwhile i < len(nums):\n p = 1\n for j in range(i, len(nums)):\n if nums[j] == 0:\n for k in range(i, j - 1):\n p //= nums[k]\n m = max(...
<|body_start_0|> if not nums: return 0 m = -float('inf') i = 0 while i < len(nums) and nums[i] == 0: i += 1 if i > 0: m = 0 while i < len(nums): p = 1 for j in range(i, len(nums)): if nums[j] == 0...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct(self, nums): """07/27/2018 22:42""" <|body_0|> def maxProduct(self, nums: List[int]) -> int: """Time complexity: O(n) Space complexity: O(1)""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not nums: return 0 ...
stack_v2_sparse_classes_36k_train_028999
3,384
no_license
[ { "docstring": "07/27/2018 22:42", "name": "maxProduct", "signature": "def maxProduct(self, nums)" }, { "docstring": "Time complexity: O(n) Space complexity: O(1)", "name": "maxProduct", "signature": "def maxProduct(self, nums: List[int]) -> int" } ]
2
stack_v2_sparse_classes_30k_train_001962
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): 07/27/2018 22:42 - def maxProduct(self, nums: List[int]) -> int: Time complexity: O(n) Space complexity: O(1)
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): 07/27/2018 22:42 - def maxProduct(self, nums: List[int]) -> int: Time complexity: O(n) Space complexity: O(1) <|skeleton|> class Solution: def m...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def maxProduct(self, nums): """07/27/2018 22:42""" <|body_0|> def maxProduct(self, nums: List[int]) -> int: """Time complexity: O(n) Space complexity: O(1)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProduct(self, nums): """07/27/2018 22:42""" if not nums: return 0 m = -float('inf') i = 0 while i < len(nums) and nums[i] == 0: i += 1 if i > 0: m = 0 while i < len(nums): p = 1 ...
the_stack_v2_python_sparse
leetcode/solved/152_Maximum_Product_Subarray/solution.py
sungminoh/algorithms
train
0