blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
679483262ef9e854746428f03c0310c0aae11700 | [
"if update_info.get('data_truncate', {}).get('enable', False):\n instalog_config['buffer']['args']['truncate_interval'] = 86400\nthreshold = update_info.get('input_http', {}).get('log_level_threshold', logging.NOTSET)\ninstalog_config['input']['http_in']['args']['log_level_threshold'] = threshold\nif update_info... | <|body_start_0|>
if update_info.get('data_truncate', {}).get('enable', False):
instalog_config['buffer']['args']['truncate_interval'] = 86400
threshold = update_info.get('input_http', {}).get('log_level_threshold', logging.NOTSET)
instalog_config['input']['http_in']['args']['log_leve... | Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs) | InstalogService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Arg... | stack_v2_sparse_classes_75kplus_train_002100 | 6,051 | permissive | [
{
"docstring": "Updates Instalog plugin config based on Umpire config. Args: instalog_config: Original Instalog configuration. update_info: The Umpire configuration used to update instalog_config. env: UmpireEnv object.",
"name": "UpdateConfig",
"signature": "def UpdateConfig(self, instalog_config, upda... | 3 | stack_v2_sparse_classes_30k_train_001482 | Implement the Python class `InstalogService` described below.
Class description:
Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)
Method signatures and docstrings:
- def UpdateConfig(self, instalog_config, update_info, env): U... | Implement the Python class `InstalogService` described below.
Class description:
Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)
Method signatures and docstrings:
- def UpdateConfig(self, instalog_config, update_info, env): U... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Args: instalog_c... | the_stack_v2_python_sparse | py/umpire/server/service/instalog.py | bridder/factory | train | 0 |
52b5409d1de9037589ed98029b8fe8a18d11407b | [
"if not isinstance(memory_location, MemoryLocation):\n raise ValueError('Given memory location must be an instance of MemoryLocation')\nif not isinstance(data, bytes):\n raise ValueError('data must be a bytes object')\nrequest = Request(service=cls)\nrequest.data = bytes()\nrequest.data += memory_location.alf... | <|body_start_0|>
if not isinstance(memory_location, MemoryLocation):
raise ValueError('Given memory location must be an instance of MemoryLocation')
if not isinstance(data, bytes):
raise ValueError('data must be a bytes object')
request = Request(service=cls)
requ... | WriteMemoryByAddress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteMemoryByAddress:
def make_request(cls, memory_location: MemoryLocation, data: bytes) -> Request:
"""Generates a request for ReadMemoryByAddress :param memory_location: The address and the size of the memory block to write. :type memory_location: :ref:`MemoryLocation <MemoryLocation>... | stack_v2_sparse_classes_75kplus_train_002101 | 4,804 | permissive | [
{
"docstring": "Generates a request for ReadMemoryByAddress :param memory_location: The address and the size of the memory block to write. :type memory_location: :ref:`MemoryLocation <MemoryLocation>` :param data: The data to write into memory. :type data: bytes :raises ValueError: If parameters are out of rang... | 2 | stack_v2_sparse_classes_30k_train_008219 | Implement the Python class `WriteMemoryByAddress` described below.
Class description:
Implement the WriteMemoryByAddress class.
Method signatures and docstrings:
- def make_request(cls, memory_location: MemoryLocation, data: bytes) -> Request: Generates a request for ReadMemoryByAddress :param memory_location: The ad... | Implement the Python class `WriteMemoryByAddress` described below.
Class description:
Implement the WriteMemoryByAddress class.
Method signatures and docstrings:
- def make_request(cls, memory_location: MemoryLocation, data: bytes) -> Request: Generates a request for ReadMemoryByAddress :param memory_location: The ad... | 1b93cc3cd0e09a21d48881ba53aed257f841bb89 | <|skeleton|>
class WriteMemoryByAddress:
def make_request(cls, memory_location: MemoryLocation, data: bytes) -> Request:
"""Generates a request for ReadMemoryByAddress :param memory_location: The address and the size of the memory block to write. :type memory_location: :ref:`MemoryLocation <MemoryLocation>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriteMemoryByAddress:
def make_request(cls, memory_location: MemoryLocation, data: bytes) -> Request:
"""Generates a request for ReadMemoryByAddress :param memory_location: The address and the size of the memory block to write. :type memory_location: :ref:`MemoryLocation <MemoryLocation>` :param data:... | the_stack_v2_python_sparse | udsoncan/services/WriteMemoryByAddress.py | pylessard/python-udsoncan | train | 477 | |
733e80053a2f9ad1ac8f646cd19b633d29004723 | [
"ids = dict(self.request.data).get('ids', [])\nqueryset = self.request.user.notes.filter(id__in=ids)\nreturn queryset",
"notes = self.get_queryset()\nif notes.exists():\n self.perform_action(notes)\n return Response(status=self.success_status)\nelse:\n return Response(status=status.HTTP_400_BAD_REQUEST)"... | <|body_start_0|>
ids = dict(self.request.data).get('ids', [])
queryset = self.request.user.notes.filter(id__in=ids)
return queryset
<|end_body_0|>
<|body_start_1|>
notes = self.get_queryset()
if notes.exists():
self.perform_action(notes)
return Response(s... | Mixin to be used a base class by API views that deal with multiple ids at once. | MutlipleNoteIdsMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MutlipleNoteIdsMixin:
"""Mixin to be used a base class by API views that deal with multiple ids at once."""
def get_queryset(self):
"""Return a queryset of Notes matching the ids given."""
<|body_0|>
def post(self, request):
"""Given a non-empty queryset, perform... | stack_v2_sparse_classes_75kplus_train_002102 | 3,894 | no_license | [
{
"docstring": "Return a queryset of Notes matching the ids given.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Given a non-empty queryset, perform the action. `perform_action` defined in child class.",
"name": "post",
"signature": "def post(self, re... | 2 | null | Implement the Python class `MutlipleNoteIdsMixin` described below.
Class description:
Mixin to be used a base class by API views that deal with multiple ids at once.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of Notes matching the ids given.
- def post(self, request): Given a non-em... | Implement the Python class `MutlipleNoteIdsMixin` described below.
Class description:
Mixin to be used a base class by API views that deal with multiple ids at once.
Method signatures and docstrings:
- def get_queryset(self): Return a queryset of Notes matching the ids given.
- def post(self, request): Given a non-em... | 8476643e12548ac797c6e18e23b9654c43cebe77 | <|skeleton|>
class MutlipleNoteIdsMixin:
"""Mixin to be used a base class by API views that deal with multiple ids at once."""
def get_queryset(self):
"""Return a queryset of Notes matching the ids given."""
<|body_0|>
def post(self, request):
"""Given a non-empty queryset, perform... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MutlipleNoteIdsMixin:
"""Mixin to be used a base class by API views that deal with multiple ids at once."""
def get_queryset(self):
"""Return a queryset of Notes matching the ids given."""
ids = dict(self.request.data).get('ids', [])
queryset = self.request.user.notes.filter(id__i... | the_stack_v2_python_sparse | notes/mixins.py | gurupratap-matharu/code-atlas | train | 0 |
03afe29e16b9302b0d6cc6f65ff195993467f874 | [
"n = len(nums)\ndp = [1] * n\nfor i in range(n):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n if dp[i] == 3:\n return True\nreturn False",
"smallest = second_smallest = float('inf')\nfor num in nums:\n if num < smallest:\n ... | <|body_start_0|>
n = len(nums)
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
if dp[i] == 3:
return True
return False
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
dp = [1] ... | stack_v2_sparse_classes_75kplus_train_002103 | 873 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002548 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
d... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
n = len(nums)
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
if dp[i... | the_stack_v2_python_sparse | 0334_Increasing_Triplet_Subsequence.py | bingli8802/leetcode | train | 0 | |
12033b48fdd9011707e972f6aedc5bc3fbcdb7d2 | [
"user = get_object_or_404(DashUser, uuid=request.data['userID'])\nscenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])\nuser_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario)\nif user_scenario:\n msg = scenario.name + ' scenario is already subscribed'\n return Respons... | <|body_start_0|>
user = get_object_or_404(DashUser, uuid=request.data['userID'])
scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])
user_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario)
if user_scenario:
msg = scenario.name + ' sce... | SubscribeScenario | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
<|body_0|>
def delete(self, request):
"""To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO... | stack_v2_sparse_classes_75kplus_train_002104 | 16,902 | no_license | [
{
"docstring": "To subscribe a new scenario # Format { \"userID\": \"<USER UUID>\", \"scenarioID\": \"<SCENARIO UUID>\" }",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "To unsubscribe existing scenario of the user # Format { \"uuid\": \"<USERSCENARIO UUID>\" }",
... | 2 | stack_v2_sparse_classes_30k_train_053170 | Implement the Python class `SubscribeScenario` described below.
Class description:
Implement the SubscribeScenario class.
Method signatures and docstrings:
- def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }
- def delete(self, request): To unsub... | Implement the Python class `SubscribeScenario` described below.
Class description:
Implement the SubscribeScenario class.
Method signatures and docstrings:
- def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }
- def delete(self, request): To unsub... | 9cb5303df8c54f1d26e72557680c35aa4d0b74d0 | <|skeleton|>
class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
<|body_0|>
def delete(self, request):
"""To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
user = get_object_or_404(DashUser, uuid=request.data['userID'])
scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])
... | the_stack_v2_python_sparse | apps/apis/views.py | guyandtheworld/news-serve-api | train | 2 | |
fee5f8d5e9ff9869a052ad751910ef74e1323aa6 | [
"super(PktEncoder, self).__init__(dest, config)\nself.len_obj = self.config.get_type('msg_len')\nself.desc_obj = self.config.get_type('msg_desc')\nself.id_obj = self.config.get_type('pkt_id')",
"pkt_temp = data.get_template()\nself.desc_obj.val = DataDescType['FW_PACKET_PACKETIZED_TLM'].value\ndesc_bin = self.des... | <|body_start_0|>
super(PktEncoder, self).__init__(dest, config)
self.len_obj = self.config.get_type('msg_len')
self.desc_obj = self.config.get_type('msg_desc')
self.id_obj = self.config.get_type('pkt_id')
<|end_body_0|>
<|body_start_1|>
pkt_temp = data.get_template()
sel... | Encoder class for packet data | PktEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PktEncoder:
"""Encoder class for packet data"""
def __init__(self, dest='GUI', config=None):
"""Constructor Args: dest (string, "FSW" or "GUI", default="GUI"): Destination for binary data produced by encoder. config (ConfigManager, default=None): Object with configuration data for th... | stack_v2_sparse_classes_75kplus_train_002105 | 5,627 | permissive | [
{
"docstring": "Constructor Args: dest (string, \"FSW\" or \"GUI\", default=\"GUI\"): Destination for binary data produced by encoder. config (ConfigManager, default=None): Object with configuration data for the sizes of fields in the binary data. If None passed, defaults are used. Returns: An initialized PktEn... | 2 | null | Implement the Python class `PktEncoder` described below.
Class description:
Encoder class for packet data
Method signatures and docstrings:
- def __init__(self, dest='GUI', config=None): Constructor Args: dest (string, "FSW" or "GUI", default="GUI"): Destination for binary data produced by encoder. config (ConfigMana... | Implement the Python class `PktEncoder` described below.
Class description:
Encoder class for packet data
Method signatures and docstrings:
- def __init__(self, dest='GUI', config=None): Constructor Args: dest (string, "FSW" or "GUI", default="GUI"): Destination for binary data produced by encoder. config (ConfigMana... | b63a84933f6da4c2f8c52a84ad05d0883837130d | <|skeleton|>
class PktEncoder:
"""Encoder class for packet data"""
def __init__(self, dest='GUI', config=None):
"""Constructor Args: dest (string, "FSW" or "GUI", default="GUI"): Destination for binary data produced by encoder. config (ConfigManager, default=None): Object with configuration data for th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PktEncoder:
"""Encoder class for packet data"""
def __init__(self, dest='GUI', config=None):
"""Constructor Args: dest (string, "FSW" or "GUI", default="GUI"): Destination for binary data produced by encoder. config (ConfigManager, default=None): Object with configuration data for the sizes of fi... | the_stack_v2_python_sparse | Gds/src/fprime_gds/common/encoders/pkt_encoder.py | SterlingPeet/fprime-GT1-Payload | train | 2 |
3b253a2f0f5f655ae894004fa63584142257cf7e | [
"params = PicksForm(data=request.GET)\nparams.is_valid(raise_exception=True)\nresults = picks_service.get_list(**params.validated_data)\npick_ids = ','.join((str(pick.pick_id) for pick in results['picks']))\nrequest_ads('GP0007', pick_ids)\nresults['paging'] = dict()\nnext_offset = results.get('next_offset')\nif ne... | <|body_start_0|>
params = PicksForm(data=request.GET)
params.is_valid(raise_exception=True)
results = picks_service.get_list(**params.validated_data)
pick_ids = ','.join((str(pick.pick_id) for pick in results['picks']))
request_ads('GP0007', pick_ids)
results['paging'] = ... | PickView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickView:
def list(self, request):
"""픽 (캐스트) 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""픽 (캐스트) 조회"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = PicksForm(data=request.GET)
params.is_valid(raise_exception=True)
... | stack_v2_sparse_classes_75kplus_train_002106 | 16,333 | no_license | [
{
"docstring": "픽 (캐스트) 리스트",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "픽 (캐스트) 조회",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052884 | Implement the Python class `PickView` described below.
Class description:
Implement the PickView class.
Method signatures and docstrings:
- def list(self, request): 픽 (캐스트) 리스트
- def retrieve(self, request, pk=None): 픽 (캐스트) 조회 | Implement the Python class `PickView` described below.
Class description:
Implement the PickView class.
Method signatures and docstrings:
- def list(self, request): 픽 (캐스트) 리스트
- def retrieve(self, request, pk=None): 픽 (캐스트) 조회
<|skeleton|>
class PickView:
def list(self, request):
"""픽 (캐스트) 리스트"""
... | 0edc046f57a1c171c10be5dfa4b4e26f440847be | <|skeleton|>
class PickView:
def list(self, request):
"""픽 (캐스트) 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""픽 (캐스트) 조회"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickView:
def list(self, request):
"""픽 (캐스트) 리스트"""
params = PicksForm(data=request.GET)
params.is_valid(raise_exception=True)
results = picks_service.get_list(**params.validated_data)
pick_ids = ','.join((str(pick.pick_id) for pick in results['picks']))
reques... | the_stack_v2_python_sparse | backends/api/v2/picks.py | jmp7786/coins | train | 0 | |
f50eb6a7798f814239a85228d8b9e9d3e2ec7974 | [
"identity = flask_jwt.get_jwt_identity() or {}\ntry:\n app = identity.get('app')\n return session.Session(save=False, profile=session.SessionProfile(**identity['profile']), groups=[groups.Group(**g) for g in identity['groups'] or []], app=app if app is None else session.SessionApp(**app), default_object_perms... | <|body_start_0|>
identity = flask_jwt.get_jwt_identity() or {}
try:
app = identity.get('app')
return session.Session(save=False, profile=session.SessionProfile(**identity['profile']), groups=[groups.Group(**g) for g in identity['groups'] or []], app=app if app is None else sessio... | Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server | JWTSessionInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWTSessionInterface:
"""Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server"""
def open_session(self, app, request):
"""P... | stack_v2_sparse_classes_75kplus_train_002107 | 4,373 | no_license | [
{
"docstring": "Populate the session from the JWT cookies at the start of a request",
"name": "open_session",
"signature": "def open_session(self, app, request)"
},
{
"docstring": "Save the session at the end of a request if it's new and we are the auth server",
"name": "save_session",
"... | 2 | stack_v2_sparse_classes_30k_train_030896 | Implement the Python class `JWTSessionInterface` described below.
Class description:
Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server
Method signatures ... | Implement the Python class `JWTSessionInterface` described below.
Class description:
Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server
Method signatures ... | dbba9f3b292ffef6ea924608fa54237171f0aaeb | <|skeleton|>
class JWTSessionInterface:
"""Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server"""
def open_session(self, app, request):
"""P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JWTSessionInterface:
"""Hooks up our JWT tokens to the session interface so we can use flask the way it was intended but also get the benefit of JWTs. Sessions in this system are immutable, and may only be written by an application server"""
def open_session(self, app, request):
"""Populate the s... | the_stack_v2_python_sparse | lib/python/core/directorofme/flask/jwt.py | DirectorOfMe/directorof.me | train | 0 |
0452d1562eef449846b36fbb6efa1f53ec893b81 | [
"self.uid = uid\nself._attrs = {'steps': {}}\nsuper(Step, self).__init__(uid)",
"if step not in self.steps:\n self.steps[step] = int(time.time())\n self.save()"
] | <|body_start_0|>
self.uid = uid
self._attrs = {'steps': {}}
super(Step, self).__init__(uid)
<|end_body_0|>
<|body_start_1|>
if step not in self.steps:
self.steps[step] = int(time.time())
self.save()
<|end_body_1|>
| 详细的用户行为记录 用来记录用户所到的每一个阶段 | Step | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Step:
"""详细的用户行为记录 用来记录用户所到的每一个阶段"""
def __init__(self, uid=None):
"""logs: {step: timestamp, step1: timestamp}"""
<|body_0|>
def add_step(self, step):
"""记录步骤 :param step: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.uid = uid
... | stack_v2_sparse_classes_75kplus_train_002108 | 3,602 | no_license | [
{
"docstring": "logs: {step: timestamp, step1: timestamp}",
"name": "__init__",
"signature": "def __init__(self, uid=None)"
},
{
"docstring": "记录步骤 :param step: :return:",
"name": "add_step",
"signature": "def add_step(self, step)"
}
] | 2 | null | Implement the Python class `Step` described below.
Class description:
详细的用户行为记录 用来记录用户所到的每一个阶段
Method signatures and docstrings:
- def __init__(self, uid=None): logs: {step: timestamp, step1: timestamp}
- def add_step(self, step): 记录步骤 :param step: :return: | Implement the Python class `Step` described below.
Class description:
详细的用户行为记录 用来记录用户所到的每一个阶段
Method signatures and docstrings:
- def __init__(self, uid=None): logs: {step: timestamp, step1: timestamp}
- def add_step(self, step): 记录步骤 :param step: :return:
<|skeleton|>
class Step:
"""详细的用户行为记录 用来记录用户所到的每一个阶段"""... | fa1591863985a418fd361eb6dac36d1301bc1231 | <|skeleton|>
class Step:
"""详细的用户行为记录 用来记录用户所到的每一个阶段"""
def __init__(self, uid=None):
"""logs: {step: timestamp, step1: timestamp}"""
<|body_0|>
def add_step(self, step):
"""记录步骤 :param step: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Step:
"""详细的用户行为记录 用来记录用户所到的每一个阶段"""
def __init__(self, uid=None):
"""logs: {step: timestamp, step1: timestamp}"""
self.uid = uid
self._attrs = {'steps': {}}
super(Step, self).__init__(uid)
def add_step(self, step):
"""记录步骤 :param step: :return:"""
if ... | the_stack_v2_python_sparse | learn_backend/models/logging.py | isoundy000/learn_python | train | 0 |
ebc4265b7bec08003fc3b39970afb794a2f91c94 | [
"size = len(nums)\nif size == 0 or k <= 0:\n return\nk = k % len(nums)\nself.__reverse(nums, 0, size - 1)\nself.__reverse(nums, 0, k - 1)\nself.__reverse(nums, k, size - 1)",
"while index1 < index2:\n nums[index1], nums[index2] = (nums[index2], nums[index1])\n index1 += 1\n index2 -= 1"
] | <|body_start_0|>
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1)
self.__reverse(nums, k, size - 1)
<|end_body_0|>
<|body_start_1|>
while index1 < index2:
nu... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_75kplus_train_002109 | 1,050 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:",
"name": "__reverse",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_040489 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | baabdb1990fd49ab82a712e121f49c4f68b29459 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1... | the_stack_v2_python_sparse | array/Python/0189-rotate-array.py | lemonnader/LeetCode-Solution-Well-Formed | train | 1 | |
f8316750579568bd2149f9dfd21267fd9c467e39 | [
"outputs = []\nvalid_output = []\nmodule.reset()\nfor sample in dataset.getSequenceIterator(sequence_index):\n out = module.activate(sample[0])\n outputs.append(out)\n valid_output.append(out[sample[1].argmax()])\nplt.fill_between(list(range(len(valid_output))), 1, valid_output, facecolor='k', alpha=0.8)\n... | <|body_start_0|>
outputs = []
valid_output = []
module.reset()
for sample in dataset.getSequenceIterator(sequence_index):
out = module.activate(sample[0])
outputs.append(out)
valid_output.append(out[sample[1].argmax()])
plt.fill_between(list(ra... | ClassificationDataSetPlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationDataSetPlot:
def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)):
"""Plot all outputs and fill the value of the output of the correct category. The grapth of a good classifier should be like all white, with all other values ve... | stack_v2_sparse_classes_75kplus_train_002110 | 5,041 | permissive | [
{
"docstring": "Plot all outputs and fill the value of the output of the correct category. The grapth of a good classifier should be like all white, with all other values very low. A graph with lot of black is a bad sign. :param module: The module/network to plot. :type module: pybrain.structure.modules.module.... | 3 | null | Implement the Python class `ClassificationDataSetPlot` described below.
Class description:
Implement the ClassificationDataSetPlot class.
Method signatures and docstrings:
- def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)): Plot all outputs and fill the value of the ... | Implement the Python class `ClassificationDataSetPlot` described below.
Class description:
Implement the ClassificationDataSetPlot class.
Method signatures and docstrings:
- def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)): Plot all outputs and fill the value of the ... | 33ead60704d126e58c10d458ddd1e5e5fd17b65d | <|skeleton|>
class ClassificationDataSetPlot:
def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)):
"""Plot all outputs and fill the value of the output of the correct category. The grapth of a good classifier should be like all white, with all other values ve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassificationDataSetPlot:
def plot_module_classification_sequence_performance(module, dataset, sequence_index, bounds=(0, 1)):
"""Plot all outputs and fill the value of the output of the correct category. The grapth of a good classifier should be like all white, with all other values very low. A grap... | the_stack_v2_python_sparse | pybrain/tools/plotting/classification.py | pybrain2/pybrain2 | train | 14 | |
a5ba3ba14e744d0c9ca6a5cce20d6a92d49e316c | [
"args = image_download.parse_args()\nas_attachment = args.get('asAttachment')\nthumbnail = args.get('thumbnail')\nimage = current_user.images.filter(id=image_id, deleted=False).first()\nif image is None:\n return ({'success': False}, 400)\nwidth = args.get('width')\nheight = args.get('height')\nif not width:\n ... | <|body_start_0|>
args = image_download.parse_args()
as_attachment = args.get('asAttachment')
thumbnail = args.get('thumbnail')
image = current_user.images.filter(id=image_id, deleted=False).first()
if image is None:
return ({'success': False}, 400)
width = arg... | ImageId | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageId:
def get(self, image_id):
"""Returns category by ID"""
<|body_0|>
def delete(self, image_id):
"""Deletes an image by ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = image_download.parse_args()
as_attachment = args.get('asAt... | stack_v2_sparse_classes_75kplus_train_002111 | 6,500 | permissive | [
{
"docstring": "Returns category by ID",
"name": "get",
"signature": "def get(self, image_id)"
},
{
"docstring": "Deletes an image by ID",
"name": "delete",
"signature": "def delete(self, image_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051480 | Implement the Python class `ImageId` described below.
Class description:
Implement the ImageId class.
Method signatures and docstrings:
- def get(self, image_id): Returns category by ID
- def delete(self, image_id): Deletes an image by ID | Implement the Python class `ImageId` described below.
Class description:
Implement the ImageId class.
Method signatures and docstrings:
- def get(self, image_id): Returns category by ID
- def delete(self, image_id): Deletes an image by ID
<|skeleton|>
class ImageId:
def get(self, image_id):
"""Returns c... | 9cce5d2f64944e2aa7ca829ca4032624e3305138 | <|skeleton|>
class ImageId:
def get(self, image_id):
"""Returns category by ID"""
<|body_0|>
def delete(self, image_id):
"""Deletes an image by ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageId:
def get(self, image_id):
"""Returns category by ID"""
args = image_download.parse_args()
as_attachment = args.get('asAttachment')
thumbnail = args.get('thumbnail')
image = current_user.images.filter(id=image_id, deleted=False).first()
if image is None:
... | the_stack_v2_python_sparse | backend/webserver/api/images.py | jsbroks/coco-annotator | train | 1,987 | |
401a35798d7986f79d41204cd43b74cba00eca3f | [
"super().load(fname)\ndb_const_dict = seq2nums(self.index)\nX = np.eye(len(db_const_dict), dtype=int)\nval_count = len(self.css)\ny = np.array([set2bits(val_count, xs) for xs in self.index.values()])\nprint('X:', X.shape, '\\n', X)\nprint('\\ny:', y.shape, '\\n', y, '\\n')\nlearner.fit(X, y)\nself.learner, self.db_... | <|body_start_0|>
super().load(fname)
db_const_dict = seq2nums(self.index)
X = np.eye(len(db_const_dict), dtype=int)
val_count = len(self.css)
y = np.array([set2bits(val_count, xs) for xs in self.index.values()])
print('X:', X.shape, '\n', X)
print('\ny:', y.shape,... | replaces indexing in Db with machine-learned equivalent | Ndb | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ndb:
"""replaces indexing in Db with machine-learned equivalent"""
def load(self, fname, learner=neural_learner):
"""overrides loading mechanism to fit learner"""
<|body_0|>
def ground_match_of(self, query_tuple):
"""overrides database matching with learned predi... | stack_v2_sparse_classes_75kplus_train_002112 | 2,123 | permissive | [
{
"docstring": "overrides loading mechanism to fit learner",
"name": "load",
"signature": "def load(self, fname, learner=neural_learner)"
},
{
"docstring": "overrides database matching with learned predictions",
"name": "ground_match_of",
"signature": "def ground_match_of(self, query_tup... | 2 | stack_v2_sparse_classes_30k_train_025032 | Implement the Python class `Ndb` described below.
Class description:
replaces indexing in Db with machine-learned equivalent
Method signatures and docstrings:
- def load(self, fname, learner=neural_learner): overrides loading mechanism to fit learner
- def ground_match_of(self, query_tuple): overrides database matchi... | Implement the Python class `Ndb` described below.
Class description:
replaces indexing in Db with machine-learned equivalent
Method signatures and docstrings:
- def load(self, fname, learner=neural_learner): overrides loading mechanism to fit learner
- def ground_match_of(self, query_tuple): overrides database matchi... | a9b65f0dc5721155b899e4748b425655cb541c23 | <|skeleton|>
class Ndb:
"""replaces indexing in Db with machine-learned equivalent"""
def load(self, fname, learner=neural_learner):
"""overrides loading mechanism to fit learner"""
<|body_0|>
def ground_match_of(self, query_tuple):
"""overrides database matching with learned predi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ndb:
"""replaces indexing in Db with machine-learned equivalent"""
def load(self, fname, learner=neural_learner):
"""overrides loading mechanism to fit learner"""
super().load(fname)
db_const_dict = seq2nums(self.index)
X = np.eye(len(db_const_dict), dtype=int)
val... | the_stack_v2_python_sparse | natlog/ndb.py | ptarau/pypro | train | 16 |
3fd0a8159c47f37dc722effb3043458e5c0b3bd6 | [
"super(BaseKeyword, self).__init__()\nif keyword != None:\n self.keyword = keyword\n ' Input keyword. '\nif raw is not None:\n self.raw = raw\n ' Extra input to keyword. '",
"args = []\nif 'keyword' in self.__dict__:\n args.append('keyword={0.keyword!r}'.format(self))\nif 'raw' in self.__dict__:\n ... | <|body_start_0|>
super(BaseKeyword, self).__init__()
if keyword != None:
self.keyword = keyword
' Input keyword. '
if raw is not None:
self.raw = raw
' Extra input to keyword. '
<|end_body_0|>
<|body_start_1|>
args = []
if 'keyword... | Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to read the original input files meaningfully, while also providing a more pythonic... | BaseKeyword | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseKeyword:
"""Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to read the original input files meaningfull... | stack_v2_sparse_classes_75kplus_train_002113 | 22,395 | no_license | [
{
"docstring": "Creates a block. :param str keyword: Keyword indicating the name of the block.",
"name": "__init__",
"signature": "def __init__(self, keyword=None, raw=None)"
},
{
"docstring": "Dumps representation to string.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
... | 3 | null | Implement the Python class `BaseKeyword` described below.
Class description:
Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to re... | Implement the Python class `BaseKeyword` described below.
Class description:
Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to re... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class BaseKeyword:
"""Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to read the original input files meaningfull... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseKeyword:
"""Defines keyword input to different functionals. The object is to make functionals act and behave as close as possible to the original input-file based approach, while allowing some automation. We want functional wrappers to both be able to read the original input files meaningfully, while also... | the_stack_v2_python_sparse | tools/input/keywords.py | Shibu778/LaDa | train | 0 |
9b28b5caf1bad0f16a5c6d308f1583263a2dbaab | [
"response = dict()\ntry:\n response['stores'] = store_service.get_all_stores_by_dynamodb()\nexcept:\n response['stores'] = store_service.get_list()\nreturn Response(StoresResponse(response).data, status=status.HTTP_200_OK)",
"params = StoreProductsForm(data=request.GET)\nparams.is_valid(raise_exception=True... | <|body_start_0|>
response = dict()
try:
response['stores'] = store_service.get_all_stores_by_dynamodb()
except:
response['stores'] = store_service.get_list()
return Response(StoresResponse(response).data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>... | StoreView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreView:
def list(self, request):
"""전체 스토어 리스트"""
<|body_0|>
def products(self, request, pk=None):
"""스토어별 제품 순위 리스트"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response = dict()
try:
response['stores'] = store_service.get... | stack_v2_sparse_classes_75kplus_train_002114 | 4,279 | no_license | [
{
"docstring": "전체 스토어 리스트",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "스토어별 제품 순위 리스트",
"name": "products",
"signature": "def products(self, request, pk=None)"
}
] | 2 | null | Implement the Python class `StoreView` described below.
Class description:
Implement the StoreView class.
Method signatures and docstrings:
- def list(self, request): 전체 스토어 리스트
- def products(self, request, pk=None): 스토어별 제품 순위 리스트 | Implement the Python class `StoreView` described below.
Class description:
Implement the StoreView class.
Method signatures and docstrings:
- def list(self, request): 전체 스토어 리스트
- def products(self, request, pk=None): 스토어별 제품 순위 리스트
<|skeleton|>
class StoreView:
def list(self, request):
"""전체 스토어 리스트"""... | 0edc046f57a1c171c10be5dfa4b4e26f440847be | <|skeleton|>
class StoreView:
def list(self, request):
"""전체 스토어 리스트"""
<|body_0|>
def products(self, request, pk=None):
"""스토어별 제품 순위 리스트"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoreView:
def list(self, request):
"""전체 스토어 리스트"""
response = dict()
try:
response['stores'] = store_service.get_all_stores_by_dynamodb()
except:
response['stores'] = store_service.get_list()
return Response(StoresResponse(response).data, statu... | the_stack_v2_python_sparse | backends/api/v2/stores.py | jmp7786/coins | train | 0 | |
4083b8ab3830d693e4e77761a1185262087fc9ae | [
"logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.local_data['x'] = 0.0\nself.local_data['y'] = 0.0\nself.local_data['z'] = 0.0\nlogger.info('Component initialized')",
"x = self.position_3d.x\ny = self.position_3d.y\nz = self.position_3d.z\nself.local_data['x'] ... | <|body_start_0|>
logger.info('%s initialization' % obj.name)
super(self.__class__, self).__init__(obj, parent)
self.local_data['x'] = 0.0
self.local_data['y'] = 0.0
self.local_data['z'] = 0.0
logger.info('Component initialized')
<|end_body_0|>
<|body_start_1|>
x ... | Class definition for the gyroscope sensor. Sub class of Morse_Object. | GPSClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002115 | 1,160 | permissive | [
{
"docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.",
"name": "__init__",
"signature": "def __init__(self, obj, parent=None)"
},
{
"docstring": "Main function of this component.",
"name": "default_a... | 2 | stack_v2_sparse_classes_30k_train_036323 | Implement the Python class `GPSClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the... | Implement the Python class `GPSClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the... | 07fcb64fea3b58b258e917eb1aed0a585f863418 | <|skeleton|>
class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
logger.info('%s initializatio... | the_stack_v2_python_sparse | src/morse/sensors/gps.py | DefaultUser/morse | train | 2 |
45d20ae48bd16c576781606ff4a3640e669ee53a | [
"attributes = super(Simulation, self).to_datacite_json()\nif self.simulation_type_other:\n attributes['types']['resourceType'] = 'Simulation/{simulation_type}'.format(simulation_type=self.simulation_type_other.title())\nelse:\n attributes['types']['resourceType'] = 'Simulation/{simulation_type}'.format(simula... | <|body_start_0|>
attributes = super(Simulation, self).to_datacite_json()
if self.simulation_type_other:
attributes['types']['resourceType'] = 'Simulation/{simulation_type}'.format(simulation_type=self.simulation_type_other.title())
else:
attributes['types']['resourceType'... | Simulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def to_datacite_json(self):
"""Serialize object to datacite JSON."""
<|body_0|>
def to_dataset_json(self):
"""Serialize object to dataset JSON."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
attributes = super(Simulation, self).to_datac... | stack_v2_sparse_classes_75kplus_train_002116 | 8,274 | no_license | [
{
"docstring": "Serialize object to datacite JSON.",
"name": "to_datacite_json",
"signature": "def to_datacite_json(self)"
},
{
"docstring": "Serialize object to dataset JSON.",
"name": "to_dataset_json",
"signature": "def to_dataset_json(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013561 | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def to_datacite_json(self): Serialize object to datacite JSON.
- def to_dataset_json(self): Serialize object to dataset JSON. | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def to_datacite_json(self): Serialize object to datacite JSON.
- def to_dataset_json(self): Serialize object to dataset JSON.
<|skeleton|>
class Simulation:
def to_data... | 040e0d88eac6037703a6128d6f4644b5a99ea11b | <|skeleton|>
class Simulation:
def to_datacite_json(self):
"""Serialize object to datacite JSON."""
<|body_0|>
def to_dataset_json(self):
"""Serialize object to dataset JSON."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Simulation:
def to_datacite_json(self):
"""Serialize object to datacite JSON."""
attributes = super(Simulation, self).to_datacite_json()
if self.simulation_type_other:
attributes['types']['resourceType'] = 'Simulation/{simulation_type}'.format(simulation_type=self.simulatio... | the_stack_v2_python_sparse | designsafe/apps/projects/models/agave/simulation.py | DesignSafe-CI/portal | train | 12 | |
f5629e682fd4bc02a02a90ffed28960461a4f6c6 | [
"event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason)\nflow.Events.PublishEvent('Audit', event, token=self.token)\nreturn self.ApprovalUrnBuilder(self.client_id.Path(), self.token.username, self.args.reason)",
"cli... | <|body_start_0|>
event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason)
flow.Events.PublishEvent('Audit', event, token=self.token)
return self.ApprovalUrnBuilder(self.client_id.Path(), self.token.us... | Grant an approval in an emergency. | BreakGlassGrantClientApprovalFlow | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BreakGlassGrantClientApprovalFlow:
"""Grant an approval in an emergency."""
def BuildApprovalUrn(self):
"""Builds approval object urn."""
<|body_0|>
def BuildSubjectTitle(self):
"""Returns the string with subject's title."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_002117 | 28,119 | permissive | [
{
"docstring": "Builds approval object urn.",
"name": "BuildApprovalUrn",
"signature": "def BuildApprovalUrn(self)"
},
{
"docstring": "Returns the string with subject's title.",
"name": "BuildSubjectTitle",
"signature": "def BuildSubjectTitle(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017457 | Implement the Python class `BreakGlassGrantClientApprovalFlow` described below.
Class description:
Grant an approval in an emergency.
Method signatures and docstrings:
- def BuildApprovalUrn(self): Builds approval object urn.
- def BuildSubjectTitle(self): Returns the string with subject's title. | Implement the Python class `BreakGlassGrantClientApprovalFlow` described below.
Class description:
Grant an approval in an emergency.
Method signatures and docstrings:
- def BuildApprovalUrn(self): Builds approval object urn.
- def BuildSubjectTitle(self): Returns the string with subject's title.
<|skeleton|>
class ... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class BreakGlassGrantClientApprovalFlow:
"""Grant an approval in an emergency."""
def BuildApprovalUrn(self):
"""Builds approval object urn."""
<|body_0|>
def BuildSubjectTitle(self):
"""Returns the string with subject's title."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BreakGlassGrantClientApprovalFlow:
"""Grant an approval in an emergency."""
def BuildApprovalUrn(self):
"""Builds approval object urn."""
event = rdfvalue.AuditEvent(user=self.token.username, action='CLIENT_APPROVAL_BREAK_GLASS_REQUEST', client=self.client_id, description=self.args.reason... | the_stack_v2_python_sparse | lib/aff4_objects/security.py | defaultnamehere/grr | train | 3 |
a95c4655b95d98a938a0144f01c8fdddea4e0a86 | [
"super(LAGOU, self).__init__(param=param)\nself.base_url = param.get('base_url') + '.json'\nself.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', 'Referer': param.get('base_url')}",
"data = {'first': 'false', 'sortField': '0'... | <|body_start_0|>
super(LAGOU, self).__init__(param=param)
self.base_url = param.get('base_url') + '.json'
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', 'Referer': param.get('base_url')}
<|end_body_0|... | 继承父类:BASEZHAOPIN | LAGOU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LAGOU:
"""继承父类:BASEZHAOPIN"""
def __init__(self, param):
"""初始化属性 :param param:"""
<|body_0|>
def parse_list(self):
"""解析列表页 :param start_url: :return:"""
<|body_1|>
def run(self):
"""执行过程 :return:"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_002118 | 6,117 | no_license | [
{
"docstring": "初始化属性 :param param:",
"name": "__init__",
"signature": "def __init__(self, param)"
},
{
"docstring": "解析列表页 :param start_url: :return:",
"name": "parse_list",
"signature": "def parse_list(self)"
},
{
"docstring": "执行过程 :return:",
"name": "run",
"signature"... | 3 | null | Implement the Python class `LAGOU` described below.
Class description:
继承父类:BASEZHAOPIN
Method signatures and docstrings:
- def __init__(self, param): 初始化属性 :param param:
- def parse_list(self): 解析列表页 :param start_url: :return:
- def run(self): 执行过程 :return: | Implement the Python class `LAGOU` described below.
Class description:
继承父类:BASEZHAOPIN
Method signatures and docstrings:
- def __init__(self, param): 初始化属性 :param param:
- def parse_list(self): 解析列表页 :param start_url: :return:
- def run(self): 执行过程 :return:
<|skeleton|>
class LAGOU:
"""继承父类:BASEZHAOPIN"""
... | ac01a1cba0e0068cd33d30bfd60d2a5df6bc5114 | <|skeleton|>
class LAGOU:
"""继承父类:BASEZHAOPIN"""
def __init__(self, param):
"""初始化属性 :param param:"""
<|body_0|>
def parse_list(self):
"""解析列表页 :param start_url: :return:"""
<|body_1|>
def run(self):
"""执行过程 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LAGOU:
"""继承父类:BASEZHAOPIN"""
def __init__(self, param):
"""初始化属性 :param param:"""
super(LAGOU, self).__init__(param=param)
self.base_url = param.get('base_url') + '.json'
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Ge... | the_stack_v2_python_sparse | salesmindData/spider/runspider/lagou/spider_lagou_impl.py | piaoxue85/salesmindData | train | 0 |
889e22a7ea6218c1b65a4b169e0b12abbacbbaac | [
"bytes = self.serialize()[offset:]\nterminated = ptypes.utils.strdup(bytes, terminator=b'\\x00')\nreturn terminated.decode('latin1')",
"res, nullbyte = (string if isinstance(string, bytes) else string.encode('latin1'), b'\\x00')\noffset, data = (self.size(), self['Data'])\ndata.length, data.value = (data.length +... | <|body_start_0|>
bytes = self.serialize()[offset:]
terminated = ptypes.utils.strdup(bytes, terminator=b'\x00')
return terminated.decode('latin1')
<|end_body_0|>
<|body_start_1|>
res, nullbyte = (string if isinstance(string, bytes) else string.encode('latin1'), b'\x00')
offset, d... | StringTable | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringTable:
def extract(self, offset):
"""return the string associated with a particular offset"""
<|body_0|>
def add(self, string):
"""appends a string to string table, returns offset"""
<|body_1|>
def find(self, string):
"""returns the offset ... | stack_v2_sparse_classes_75kplus_train_002119 | 12,910 | permissive | [
{
"docstring": "return the string associated with a particular offset",
"name": "extract",
"signature": "def extract(self, offset)"
},
{
"docstring": "appends a string to string table, returns offset",
"name": "add",
"signature": "def add(self, string)"
},
{
"docstring": "returns... | 3 | stack_v2_sparse_classes_30k_train_043367 | Implement the Python class `StringTable` described below.
Class description:
Implement the StringTable class.
Method signatures and docstrings:
- def extract(self, offset): return the string associated with a particular offset
- def add(self, string): appends a string to string table, returns offset
- def find(self, ... | Implement the Python class `StringTable` described below.
Class description:
Implement the StringTable class.
Method signatures and docstrings:
- def extract(self, offset): return the string associated with a particular offset
- def add(self, string): appends a string to string table, returns offset
- def find(self, ... | e02b014dc764ed822288210248c9438a843af8a9 | <|skeleton|>
class StringTable:
def extract(self, offset):
"""return the string associated with a particular offset"""
<|body_0|>
def add(self, string):
"""appends a string to string table, returns offset"""
<|body_1|>
def find(self, string):
"""returns the offset ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringTable:
def extract(self, offset):
"""return the string associated with a particular offset"""
bytes = self.serialize()[offset:]
terminated = ptypes.utils.strdup(bytes, terminator=b'\x00')
return terminated.decode('latin1')
def add(self, string):
"""appends a ... | the_stack_v2_python_sparse | lib/pecoff/portable/symbols.py | arizvisa/syringe | train | 36 | |
8c79dce2d61b8774568e31abf9e6151247e43208 | [
"self.x = cam_pos[0]\nself.y = cam_pos[1]\nself.z = cam_pos[2]\nself.xdir = cam_dir[0]\nself.ydir = cam_dir[1]\nself.zdir = cam_dir[2]\nself.xup = cam_up[0]\nself.yup = cam_up[1]\nself.zup = cam_up[2]\nself.u3_camera = np.array([self.xdir, self.ydir, self.zdir])\nself.u2_camera = np.array([self.xup, self.yup, self.... | <|body_start_0|>
self.x = cam_pos[0]
self.y = cam_pos[1]
self.z = cam_pos[2]
self.xdir = cam_dir[0]
self.ydir = cam_dir[1]
self.zdir = cam_dir[2]
self.xup = cam_up[0]
self.yup = cam_up[1]
self.zup = cam_up[2]
self.u3_camera = np.array([self... | Camera | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction consider... | stack_v2_sparse_classes_75kplus_train_002120 | 17,705 | permissive | [
{
"docstring": ":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction considered up for the camera, in cartesian coordinates :return: set the v... | 4 | stack_v2_sparse_classes_30k_train_013289 | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def __init__(self, cam_pos, cam_dir, cam_up): :param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the c... | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def __init__(self, cam_pos, cam_dir, cam_up): :param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the c... | 5c76276ff658582061dbdf10cadee7cfc3940526 | <|skeleton|>
class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction consider... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Camera:
def __init__(self, cam_pos, cam_dir, cam_up):
""":param cam_pos: translation vector with the camera position, in cartesian coordinates :param cam_dir: unit vector in the direction the camera is poiting, in cartesian coordinates :param cam_up: unit vector in the direction considered up for the ... | the_stack_v2_python_sparse | translate_coordinates.py | gsnyder206/mock-surveys | train | 7 | |
7e880d1c6a04a92448db83355b5f2694ed956ac8 | [
"super().__init__()\nself.optimizer = optimizer\nself.problem = problem\nself.x0 = x0\nself.id = id\nself.options = options\nself.history_options = history_options\nself.report_hess = report_hess\nself.report_sres = report_sres",
"logger.info(f'Executing task {self.id}.')\noptimizer_result = self.optimizer.minimi... | <|body_start_0|>
super().__init__()
self.optimizer = optimizer
self.problem = problem
self.x0 = x0
self.id = id
self.options = options
self.history_options = history_options
self.report_hess = report_hess
self.report_sres = report_sres
<|end_body_0... | A multistart optimization task, performed in `pypesto.minimize`. | OptimizerTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, options: 'pypesto.optimize.OptimizeOptions', history_options: HistoryOptions, report_hess: bool, report... | stack_v2_sparse_classes_75kplus_train_002121 | 2,135 | permissive | [
{
"docstring": "Create the task object. Parameters ---------- optimizer: The optimizer to use. problem: The problem to solve. x0: The point from which to start. id: The multistart id. options: Options object applying to optimization. history_options: Optimizer history options. report_hess: Flag indicating wheth... | 2 | stack_v2_sparse_classes_30k_val_001071 | Implement the Python class `OptimizerTask` described below.
Class description:
A multistart optimization task, performed in `pypesto.minimize`.
Method signatures and docstrings:
- def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, options: 'pypesto.optimize.Optimize... | Implement the Python class `OptimizerTask` described below.
Class description:
A multistart optimization task, performed in `pypesto.minimize`.
Method signatures and docstrings:
- def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, options: 'pypesto.optimize.Optimize... | 2538efc44703e7d676d386cdfa3b0ec8e24e1c24 | <|skeleton|>
class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, options: 'pypesto.optimize.OptimizeOptions', history_options: HistoryOptions, report_hess: bool, report... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptimizerTask:
"""A multistart optimization task, performed in `pypesto.minimize`."""
def __init__(self, optimizer: 'pypesto.optimize.Optimizer', problem: Problem, x0: np.ndarray, id: str, options: 'pypesto.optimize.OptimizeOptions', history_options: HistoryOptions, report_hess: bool, report_sres: bool):... | the_stack_v2_python_sparse | pypesto/optimize/task.py | jdieg0/pyPESTO | train | 0 |
8ecd3a2999f13fbff7ef1c962e89ba64188f57d3 | [
"jsonconfig.JsonConfig.__init__(self)\nself.activated = False\nself.wifipassword = b''\nself.ssid = b''\nself.authmode = b'WPA2-PSK'\nself.ipaddress = b'192.168.3.1'\nself.netmask = b'255.255.255.0'\nself.gateway = b'192.168.3.1'\nself.dns = b'192.168.3.1'",
"ipaddress, netmask, gateway, dns = AccessPoint.wlan.if... | <|body_start_0|>
jsonconfig.JsonConfig.__init__(self)
self.activated = False
self.wifipassword = b''
self.ssid = b''
self.authmode = b'WPA2-PSK'
self.ipaddress = b'192.168.3.1'
self.netmask = b'255.255.255.0'
self.gateway = b'192.168.3.1'
self.dns ... | Access point configuration class | AccessPointConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessPointConfig:
"""Access point configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display accesspoint informations"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
jsonconfig.JsonConfig.__init__(sel... | stack_v2_sparse_classes_75kplus_train_002122 | 6,194 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display accesspoint informations",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012064 | Implement the Python class `AccessPointConfig` described below.
Class description:
Access point configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display accesspoint informations | Implement the Python class `AccessPointConfig` described below.
Class description:
Access point configuration class
Method signatures and docstrings:
- def __init__(self): Constructor
- def __repr__(self): Display accesspoint informations
<|skeleton|>
class AccessPointConfig:
"""Access point configuration class"... | d86814625a7cd2f7e5fa01b8e1652efc811cef3a | <|skeleton|>
class AccessPointConfig:
"""Access point configuration class"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __repr__(self):
"""Display accesspoint informations"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccessPointConfig:
"""Access point configuration class"""
def __init__(self):
"""Constructor"""
jsonconfig.JsonConfig.__init__(self)
self.activated = False
self.wifipassword = b''
self.ssid = b''
self.authmode = b'WPA2-PSK'
self.ipaddress = b'192.16... | the_stack_v2_python_sparse | modules/lib/wifi/accesspoint.py | antiquefu/pycameresp | train | 0 |
47563facd2bdaf6e207fc6345270bb55d37ef7d0 | [
"attrs = iter(attr_map)\nfor sub_key in data[key].values():\n q_obj = query()\n for cur_val_idx, current_value in enumerate(sub_key):\n for t_key in data['funcargs']['terms']:\n for idx, sub_t_key in enumerate(data[t_key]):\n key_to_find = '%s_%s' % (t_key, sub_t_key)\n ... | <|body_start_0|>
attrs = iter(attr_map)
for sub_key in data[key].values():
q_obj = query()
for cur_val_idx, current_value in enumerate(sub_key):
for t_key in data['funcargs']['terms']:
for idx, sub_t_key in enumerate(data[t_key]):
... | ImageBankImporter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageBankImporter:
def iterator(self, data: dict, key: str, query: Any, obj_model: tuple, attr_map: tuple) -> None:
"""Main class data logic. Create DB objects & set class attributes. This was created with easy expandability of the setup data dictionary in mind. We are using save() throu... | stack_v2_sparse_classes_75kplus_train_002123 | 5,994 | permissive | [
{
"docstring": "Main class data logic. Create DB objects & set class attributes. This was created with easy expandability of the setup data dictionary in mind. We are using save() throughout this program to avoid race conditions with update_or_create()",
"name": "iterator",
"signature": "def iterator(se... | 5 | stack_v2_sparse_classes_30k_train_000984 | Implement the Python class `ImageBankImporter` described below.
Class description:
Implement the ImageBankImporter class.
Method signatures and docstrings:
- def iterator(self, data: dict, key: str, query: Any, obj_model: tuple, attr_map: tuple) -> None: Main class data logic. Create DB objects & set class attributes... | Implement the Python class `ImageBankImporter` described below.
Class description:
Implement the ImageBankImporter class.
Method signatures and docstrings:
- def iterator(self, data: dict, key: str, query: Any, obj_model: tuple, attr_map: tuple) -> None: Main class data logic. Create DB objects & set class attributes... | 0bd632badaa5a96c3a83927ccf1d828f09b92e73 | <|skeleton|>
class ImageBankImporter:
def iterator(self, data: dict, key: str, query: Any, obj_model: tuple, attr_map: tuple) -> None:
"""Main class data logic. Create DB objects & set class attributes. This was created with easy expandability of the setup data dictionary in mind. We are using save() throu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageBankImporter:
def iterator(self, data: dict, key: str, query: Any, obj_model: tuple, attr_map: tuple) -> None:
"""Main class data logic. Create DB objects & set class attributes. This was created with easy expandability of the setup data dictionary in mind. We are using save() throughout this pro... | the_stack_v2_python_sparse | events/importer/turku_image_bank.py | City-of-Turku/linkedevents | train | 4 | |
e75d3d3aca0ca96427fcc1899891369bdf945eef | [
"self.calc_tf = calc_tf\nself.calc_df = calc_df\nself.k = k\nself.wordSet = set()\nself.U, self.Sigma, self.VT = (None, None, None)\nreturn",
"docs = []\nwordSet = set()\nfor doc in corpus:\n words = doc.split(' ')\n words = [word.lower() for word in words]\n wordSet = wordSet | set(words)\n docs.appe... | <|body_start_0|>
self.calc_tf = calc_tf
self.calc_df = calc_df
self.k = k
self.wordSet = set()
self.U, self.Sigma, self.VT = (None, None, None)
return
<|end_body_0|>
<|body_start_1|>
docs = []
wordSet = set()
for doc in corpus:
words =... | Latent Semantic Indexing | LatentSemanticIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatentSemanticIndex:
"""Latent Semantic Indexing"""
def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2):
"""Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all documents frequnecy.(global) - k : the top k eigenvectors ... | stack_v2_sparse_classes_75kplus_train_002124 | 2,688 | no_license | [
{
"docstring": "Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all documents frequnecy.(global) - k : the top k eigenvectors to use.",
"name": "__init__",
"signature": "def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_015782 | Implement the Python class `LatentSemanticIndex` described below.
Class description:
Latent Semantic Indexing
Method signatures and docstrings:
- def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2): Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all d... | Implement the Python class `LatentSemanticIndex` described below.
Class description:
Latent Semantic Indexing
Method signatures and docstrings:
- def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2): Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all d... | 3fd252c10399e9057ba9a23e75651875ab6d89f2 | <|skeleton|>
class LatentSemanticIndex:
"""Latent Semantic Indexing"""
def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2):
"""Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all documents frequnecy.(global) - k : the top k eigenvectors ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LatentSemanticIndex:
"""Latent Semantic Indexing"""
def __init__(self, calc_tf=raw_count_tf, calc_df=binary_df, k=2):
"""Initialization - calc_tf : compute term frequency in a document. (local) - calc_df : compute term in all documents frequnecy.(global) - k : the top k eigenvectors to use."""
... | the_stack_v2_python_sparse | 00-review/03-svd-lsi/lsi.py | AaronFlower/Jupyter | train | 1 |
35cfa53256eefca2ed5e0c4429c1ae4275be0a24 | [
"rows, cols = (len(board), len(board[0]))\ndp = [0] * (cols + 1)\nmax_len = prev = 0\nfor row in range(1, rows + 1):\n for col in range(1, cols + 1):\n temp = dp[col]\n if board[row - 1][col - 1] == '1':\n dp[col] = min(min(dp[col], prev), dp[col - 1]) + 1\n max_len = max(max_... | <|body_start_0|>
rows, cols = (len(board), len(board[0]))
dp = [0] * (cols + 1)
max_len = prev = 0
for row in range(1, rows + 1):
for col in range(1, cols + 1):
temp = dp[col]
if board[row - 1][col - 1] == '1':
dp[col] = min... | Square | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
<|body_0|>
def maximal_area(self, board: List[List[int]]) -> int:
"""Approach: DP (2D Array) Time Comple... | stack_v2_sparse_classes_75kplus_train_002125 | 1,900 | no_license | [
{
"docstring": "Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:",
"name": "maximal_area_",
"signature": "def maximal_area_(self, board: List[List[int]]) -> int"
},
{
"docstring": "Approach: DP (2D Array) Time Complexity: O(MN) Space Complexity: O(MN) ... | 2 | stack_v2_sparse_classes_30k_train_018545 | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def maximal_area_(self, board: List[List[int]]) -> int: Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:
- def maximal_area(self, board: L... | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def maximal_area_(self, board: List[List[int]]) -> int: Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:
- def maximal_area(self, board: L... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
<|body_0|>
def maximal_area(self, board: List[List[int]]) -> int:
"""Approach: DP (2D Array) Time Comple... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Square:
def maximal_area_(self, board: List[List[int]]) -> int:
"""Approach: DP (1D Array) Time Complexity: O(MN) Space Complexity: O(N) :param board: :return:"""
rows, cols = (len(board), len(board[0]))
dp = [0] * (cols + 1)
max_len = prev = 0
for row in range(1, rows ... | the_stack_v2_python_sparse | amazon/dynamic_programming/maximal_square.py | Shiv2157k/leet_code | train | 1 | |
883d23d74accb202a6cc3d59a8028613a187c7c8 | [
"if p_node is None:\n return\nstack = []\nstack.append(p_node)\nwhile len(stack) > 0:\n current_node = stack.pop(0)\n if current_node.left:\n stack.append(current_node.left)\n if current_node.right:\n stack.append(current_node.right)\n print(current_node.val, end=' ')\nprint(end='\\n')"... | <|body_start_0|>
if p_node is None:
return
stack = []
stack.append(p_node)
while len(stack) > 0:
current_node = stack.pop(0)
if current_node.left:
stack.append(current_node.left)
if current_node.right:
stack.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def print_tree_level(self, p_node):
"""层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点"""
<|body_0|>
def print_tree_level_lines(self, p_node):
"""层次遍历分行打印二叉树 :param p_node: 根节点 :return: 分行打印节点"""
<|body_1|>
def print_tree_level_S(self, p_node... | stack_v2_sparse_classes_75kplus_train_002126 | 3,250 | no_license | [
{
"docstring": "层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点",
"name": "print_tree_level",
"signature": "def print_tree_level(self, p_node)"
},
{
"docstring": "层次遍历分行打印二叉树 :param p_node: 根节点 :return: 分行打印节点",
"name": "print_tree_level_lines",
"signature": "def print_tree_level_lines... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_tree_level(self, p_node): 层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点
- def print_tree_level_lines(self, p_node): 层次遍历分行打印二叉树 :param p_node: 根节点 :return: 分行打印节点
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_tree_level(self, p_node): 层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点
- def print_tree_level_lines(self, p_node): 层次遍历分行打印二叉树 :param p_node: 根节点 :return: 分行打印节点
-... | 9fdc4b1a2b59b7aed22ddfe92aade487b4c19b71 | <|skeleton|>
class Solution:
def print_tree_level(self, p_node):
"""层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点"""
<|body_0|>
def print_tree_level_lines(self, p_node):
"""层次遍历分行打印二叉树 :param p_node: 根节点 :return: 分行打印节点"""
<|body_1|>
def print_tree_level_S(self, p_node... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def print_tree_level(self, p_node):
"""层次遍历不分行打印二叉树 :param p_node: 根节点 :return: 从左向右打印节点"""
if p_node is None:
return
stack = []
stack.append(p_node)
while len(stack) > 0:
current_node = stack.pop(0)
if current_node.left:
... | the_stack_v2_python_sparse | my_target_offer/32_print_binary_tree_level.py | MemoryForSky/Data-Structures-and-Algorithms | train | 0 | |
0b9e919edc46827a4a479b086c07386232267ffd | [
"self.all_vehicles = vehicles\nself.all_add_events = add_events\nself.all_lc_events = lc_events\nif lc_event_fun is None:\n self.lc_event = lc_event\nelse:\n self.lc_event = lc_event_fun\nself.starttime = add_events[-1][0]\nself.endtime = endtime\nself.dt = dt",
"for veh in self.vehicles:\n veh.set_cf(se... | <|body_start_0|>
self.all_vehicles = vehicles
self.all_add_events = add_events
self.all_lc_events = lc_events
if lc_event_fun is None:
self.lc_event = lc_event
else:
self.lc_event = lc_event_fun
self.starttime = add_events[-1][0]
self.endti... | Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in the simulation starttime: first time index endtime: last time index dt: times... | Calibration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calibration:
"""Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in the simulation starttime: first time i... | stack_v2_sparse_classes_75kplus_train_002127 | 23,835 | permissive | [
{
"docstring": "Inits Calibration. Args: vehicles: list of all Vehicle objects to be simulated add_events: list of add events, sorted in time lc_events: list of lead change (lc) events, sorted in time dt: timestep, float lc_event_fun: can give a custom function for handling lc_events, otherwise we use the defau... | 3 | null | Implement the Python class `Calibration` described below.
Class description:
Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in... | Implement the Python class `Calibration` described below.
Class description:
Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in... | 0aaf9674e987822ff2dc90c74613d5e68e8ef0ce | <|skeleton|>
class Calibration:
"""Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in the simulation starttime: first time i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Calibration:
"""Does a simulation of a single CalibrationVehicle, and returns the loss. Attributes: all_vehicles: list of all vehicles in the simulation all_add_events: list of all add events in the simulation all_lc_events: list of all lead change events in the simulation starttime: first time index endtime:... | the_stack_v2_python_sparse | havsim/calibration/calibration.py | seccode/havsim | train | 0 |
08d3685d1eeabced68dc29df9ab5d0144a239061 | [
"super(Langmuir, self).__init__(**kwargs)\nself.array_types.update(('area', 'fay_area', 'frac_coverage', 'spill_num', 'bulk_init_volume', 'density', 'positions'))\nself.wind = wind\nself.water = water",
"v_max = np.max(self.get_wind_speed(points, model_time) * 0.005)\ncr_k = (v_max ** 2 * 4 * np.pi ** 2 / (thickn... | <|body_start_0|>
super(Langmuir, self).__init__(**kwargs)
self.array_types.update(('area', 'fay_area', 'frac_coverage', 'spill_num', 'bulk_init_volume', 'density', 'positions'))
self.wind = wind
self.water = water
<|end_body_0|>
<|body_start_1|>
v_max = np.max(self.get_wind_spee... | Easiest to define this as a weathering process that updates 'area' array | Langmuir | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
<|body_0|>
def _get_frac_coverage(self, points, model_time, rel_buoy, thickness):
... | stack_v2_sparse_classes_75kplus_train_002128 | 26,568 | no_license | [
{
"docstring": "initialize wind to (0, 0) if it is None",
"name": "__init__",
"signature": "def __init__(self, water=None, wind=None, **kwargs)"
},
{
"docstring": "return fractional coverage for a blob of oil with inputs; relative_buoyancy, and thickness Assumes the thickness is the minimum oil ... | 4 | stack_v2_sparse_classes_30k_test_001074 | Implement the Python class `Langmuir` described below.
Class description:
Easiest to define this as a weathering process that updates 'area' array
Method signatures and docstrings:
- def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None
- def _get_frac_coverage(self, points, mod... | Implement the Python class `Langmuir` described below.
Class description:
Easiest to define this as a weathering process that updates 'area' array
Method signatures and docstrings:
- def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None
- def _get_frac_coverage(self, points, mod... | 2e24d53b8b1099022a08ad73377ed6d1c7838f0f | <|skeleton|>
class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
<|body_0|>
def _get_frac_coverage(self, points, model_time, rel_buoy, thickness):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Langmuir:
"""Easiest to define this as a weathering process that updates 'area' array"""
def __init__(self, water=None, wind=None, **kwargs):
"""initialize wind to (0, 0) if it is None"""
super(Langmuir, self).__init__(**kwargs)
self.array_types.update(('area', 'fay_area', 'frac_c... | the_stack_v2_python_sparse | py_gnome/gnome/weatherers/spreading.py | bhattvihang/PyGnome | train | 1 |
d1bd666538526a5164051b8e37846b8b62aadc79 | [
"if 'modifier' in kwargs:\n self.modifier = kwargs['modifier']\nelif len(args) > 2:\n self.modifier = args[2]\n args = args[:2]\nelse:\n self.modifier = lambda x: x\nif not callable(self.modifier):\n raise TypeError('modify_iter(o, modifier): modifier must be callable')\nsuper().__init__(*args)",
"... | <|body_start_0|>
if 'modifier' in kwargs:
self.modifier = kwargs['modifier']
elif len(args) > 2:
self.modifier = args[2]
args = args[:2]
else:
self.modifier = lambda x: x
if not callable(self.modifier):
raise TypeError('modify_i... | An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either the iteration protocol or the sequence... | modify_iter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class modify_iter:
"""An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either... | stack_v2_sparse_classes_75kplus_train_002129 | 22,562 | permissive | [
{
"docstring": "__init__(o, sentinel=None, modifier=lambda x: x)",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Cache `n` modified items. If `n` is 0 or None, 1 item is cached. Each item returned by the iterator is passed through the `modify_iter.modi... | 2 | stack_v2_sparse_classes_30k_train_047505 | Implement the Python class `modify_iter` described below.
Class description:
An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a ... | Implement the Python class `modify_iter` described below.
Class description:
An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a ... | 59e1ca2f4b15ca3d1bc814330ab8ef0beb8d9af0 | <|skeleton|>
class modify_iter:
"""An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class modify_iter:
"""An iterator object that supports modifying items as they are returned. Parameters ---------- o : iterable or callable `o` is interpreted very differently depending on the presence of `sentinel`. If `sentinel` is not given, then `o` must be a collection object which supports either the iteratio... | the_stack_v2_python_sparse | moldesign/utils/docparsers/google.py | maxbates/molecular-design-toolkit | train | 1 |
d4d0081531fe0da503738abd16ff13fff8f9bc23 | [
"if self == InfoPageActionControl.UNKNOWN:\n return False\nif self == InfoPageActionControl.DETACH:\n return target_uid is not None\nif self == InfoPageActionControl.DELETE:\n return True\nraise NotImplementedError()",
"if s == 'detach':\n return InfoPageActionControl.DETACH\nif s == 'delete':\n re... | <|body_start_0|>
if self == InfoPageActionControl.UNKNOWN:
return False
if self == InfoPageActionControl.DETACH:
return target_uid is not None
if self == InfoPageActionControl.DELETE:
return True
raise NotImplementedError()
<|end_body_0|>
<|body_start... | Enum to represent the type of action to be performed. | InfoPageActionControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :... | stack_v2_sparse_classes_75kplus_train_002130 | 7,451 | permissive | [
{
"docstring": "Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :raises NotImplementedError: if the validating action is not yet implemented",
"name": "is_argument_valid",
"signature": "def is_argument_va... | 4 | stack_v2_sparse_classes_30k_train_001907 | Implement the Python class `InfoPageActionControl` described below.
Class description:
Enum to represent the type of action to be performed.
Method signatures and docstrings:
- def is_argument_valid(self, target_uid) -> bool: Check if the argument for the action is valid. :param target_uid: UID of the profile action ... | Implement the Python class `InfoPageActionControl` described below.
Class description:
Enum to represent the type of action to be performed.
Method signatures and docstrings:
- def is_argument_valid(self, target_uid) -> bool: Check if the argument for the action is valid. :param target_uid: UID of the profile action ... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :raises NotImp... | the_stack_v2_python_sparse | JellyBot/views/info/profile.py | RxJellyBot/Jelly-Bot | train | 5 |
1e51413f7c010a7f88a668e51dd9ec5098a5c13f | [
"if not matrix:\n return None\nm, n = (len(matrix), len(matrix[0]))\nself.accuSum = [[0] * n for _ in xrange(m)]\nfor i in xrange(m):\n for j in xrange(n):\n self.accuSum[i][j] = matrix[i][j]\n if j > 0:\n self.accuSum[i][j] += self.accuSum[i][j - 1]",
"ans = 0\nfor i in xrange(row1... | <|body_start_0|>
if not matrix:
return None
m, n = (len(matrix), len(matrix[0]))
self.accuSum = [[0] * n for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
self.accuSum[i][j] = matrix[i][j]
if j > 0:
sel... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_002131 | 986 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_022792 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 6d012496b7f0279b3e2c31c1f444eebb7a7a20b9 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix:
return None
m, n = (len(matrix), len(matrix[0]))
self.accuSum = [[0] * n for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
self.ac... | the_stack_v2_python_sparse | rangeSumQuery2D.py | xmy7080/leetcode | train | 0 | |
07a7f26fcabc5488a5f3907a550fc92af83078ae | [
"with io.open(filename, 'r', encoding='ascii') as file_handle:\n tokens = []\n version = 1\n count = 0\n for count, line in enumerate(file_handle):\n line_tokens = line.split()\n if count == 0:\n if len(line_tokens) > 0 and line_tokens[0] == 'XPARM.XDS':\n version... | <|body_start_0|>
with io.open(filename, 'r', encoding='ascii') as file_handle:
tokens = []
version = 1
count = 0
for count, line in enumerate(file_handle):
line_tokens = line.split()
if count == 0:
if len(line_to... | A class to read the XPARM.XDS/GXPARM.XDS file used in XDS | reader | [
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XD... | stack_v2_sparse_classes_75kplus_train_002132 | 11,104 | permissive | [
{
"docstring": "Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XDS it is the new style version 2 file. If the file contains segment definitions then it is a version 3 file. Params:... | 5 | stack_v2_sparse_classes_30k_train_048791 | Implement the Python class `reader` described below.
Class description:
A class to read the XPARM.XDS/GXPARM.XDS file used in XDS
Method signatures and docstrings:
- def find_version(filename): Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the o... | Implement the Python class `reader` described below.
Class description:
A class to read the XPARM.XDS/GXPARM.XDS file used in XDS
Method signatures and docstrings:
- def find_version(filename): Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the o... | 7f4dfb6c873fd560920f697cbfd8a5ff6eed82fa | <|skeleton|>
class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XD... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XDS it is the n... | the_stack_v2_python_sparse | iotbx/xds/xparm.py | cctbx/cctbx_project | train | 206 |
964b79c3d1cb0c68b807170c41c18a5c765fd68d | [
"super(UnitsAvailableDetails, self).__init__()\nself.default = kwargs.get('default')\nself.reduceFirst = kwargs.get('reduceFirst')\nself.reduceOnly = kwargs.get('reduceOnly')\nself.openOnly = kwargs.get('openOnly')",
"data = data.copy()\nif data.get('default') is not None:\n data['default'] = ctx.convert_decim... | <|body_start_0|>
super(UnitsAvailableDetails, self).__init__()
self.default = kwargs.get('default')
self.reduceFirst = kwargs.get('reduceFirst')
self.reduceOnly = kwargs.get('reduceOnly')
self.openOnly = kwargs.get('openOnly')
<|end_body_0|>
<|body_start_1|>
data = data.... | Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option. | UnitsAvailableDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitsAvailableDetails:
"""Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option."""
def __init__(self, **kwargs):
"""Create a new UnitsAvailableDetails instance"""
<|body_0|>
def from_dict(data, ctx):... | stack_v2_sparse_classes_75kplus_train_002133 | 19,642 | permissive | [
{
"docstring": "Create a new UnitsAvailableDetails instance",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Instantiate a new UnitsAvailableDetails from a dict (generally from loading a JSON response). The data used to instantiate the UnitsAvailableDetails is... | 2 | null | Implement the Python class `UnitsAvailableDetails` described below.
Class description:
Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option.
Method signatures and docstrings:
- def __init__(self, **kwargs): Create a new UnitsAvailableDetails inst... | Implement the Python class `UnitsAvailableDetails` described below.
Class description:
Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option.
Method signatures and docstrings:
- def __init__(self, **kwargs): Create a new UnitsAvailableDetails inst... | 055f51e55c52d6dd5cfd38550a48892a0fb09b0d | <|skeleton|>
class UnitsAvailableDetails:
"""Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option."""
def __init__(self, **kwargs):
"""Create a new UnitsAvailableDetails instance"""
<|body_0|>
def from_dict(data, ctx):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnitsAvailableDetails:
"""Representation of how many units of an Instrument are available to be traded by an Order depending on its postionFill option."""
def __init__(self, **kwargs):
"""Create a new UnitsAvailableDetails instance"""
super(UnitsAvailableDetails, self).__init__()
... | the_stack_v2_python_sparse | forex/env-python2/lib/python2.7/site-packages/v20/pricing.py | phroiland/forex_algos | train | 1 |
72d3c5f0990bc7743b8a5bed3b727c6569bc6ef7 | [
"self.callback = callback\nif callback and (not callable(callback)):\n raise TypeError(f'{callback} is not a callable object.')\nself.is_none = thing is None\n'Flag saying whether `thing` is `None`.'\nif self.is_none:\n self.ref = self.thing = None\nelse:\n try:\n self.ref = Ref(thing, callback)\n ... | <|body_start_0|>
self.callback = callback
if callback and (not callable(callback)):
raise TypeError(f'{callback} is not a callable object.')
self.is_none = thing is None
'Flag saying whether `thing` is `None`.'
if self.is_none:
self.ref = self.thing = None... | Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it can't (like for a `list`) it creates a strong one instead. Thanks to sleekre... | SleekRef | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SleekRef:
"""Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it can't (like for a `list`) it creates a s... | stack_v2_sparse_classes_75kplus_train_002134 | 2,588 | permissive | [
{
"docstring": "Construct the sleekref. `thing` is the object we want to sleekref. `callback` is the callable to call when the weakref to the object dies. (Only relevant for weakreffable objects.)",
"name": "__init__",
"signature": "def __init__(self, thing, callback=None)"
},
{
"docstring": "Ob... | 2 | stack_v2_sparse_classes_30k_train_020038 | Implement the Python class `SleekRef` described below.
Class description:
Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it c... | Implement the Python class `SleekRef` described below.
Class description:
Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it c... | cb9ef64b48f1d03275484d707dc5079b6701ad0c | <|skeleton|>
class SleekRef:
"""Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it can't (like for a `list`) it creates a s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SleekRef:
"""Sleekref tries to reference an object weakly but if can't does it strongly. The problem with weakrefs is that some objects can't be weakreffed, for example `list` and `dict` objects. A sleekref tries to create a weakref to an object, but if it can't (like for a `list`) it creates a strong one ins... | the_stack_v2_python_sparse | python_toolbox/sleek_reffing/sleek_ref.py | cool-RR/python_toolbox | train | 130 |
f4390320fd282d7f51a97983600409b69edbea7d | [
"self._cache: dict[str, dict[str, str]] = {}\nself._exact = exact\nself._domain = domain\nif glob is None:\n compiled: dict[re.Pattern[str], Any] | None = None\nelse:\n compiled = OrderedDict()\n for key, value in glob.items():\n compiled[re.compile(fnmatch.translate(key))] = value\nself._glob = com... | <|body_start_0|>
self._cache: dict[str, dict[str, str]] = {}
self._exact = exact
self._domain = domain
if glob is None:
compiled: dict[re.Pattern[str], Any] | None = None
else:
compiled = OrderedDict()
for key, value in glob.items():
... | Class to store entity id based values. | EntityValues | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002135 | 1,631 | permissive | [
{
"docstring": "Initialize an EntityConfigDict.",
"name": "__init__",
"signature": "def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None"
},
{
"docstring": "Get config for an entity id... | 2 | stack_v2_sparse_classes_30k_train_040159 | Implement the Python class `EntityValues` described below.
Class description:
Class to store entity id based values.
Method signatures and docstrings:
- def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:... | Implement the Python class `EntityValues` described below.
Class description:
Class to store entity id based values.
Method signatures and docstrings:
- def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
self._cache: dict[str, dic... | the_stack_v2_python_sparse | homeassistant/helpers/entity_values.py | konnected-io/home-assistant | train | 24 |
a883d178a7852e1a9f490a8fbcad32fcd6aa2436 | [
"if db.exist_row('activity', id=activity_id):\n try:\n activity = db.expr_query('activity', id=activity_id)[0]\n if not activity:\n admin_logger.warning('%d: no such activity', activity_id)\n return json_dump_http_response({'status': 'failure', 'message': '未知活动ID'})\n excep... | <|body_start_0|>
if db.exist_row('activity', id=activity_id):
try:
activity = db.expr_query('activity', id=activity_id)[0]
if not activity:
admin_logger.warning('%d: no such activity', activity_id)
return json_dump_http_response... | activity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class activity:
def get(self, activity_id):
"""get a activity with a specific id"""
<|body_0|>
def delete(self, activity_id):
"""delete a activity with a specific id"""
<|body_1|>
def post(self, activity_id):
"""update a activity with a specific id"""
... | stack_v2_sparse_classes_75kplus_train_002136 | 43,123 | permissive | [
{
"docstring": "get a activity with a specific id",
"name": "get",
"signature": "def get(self, activity_id)"
},
{
"docstring": "delete a activity with a specific id",
"name": "delete",
"signature": "def delete(self, activity_id)"
},
{
"docstring": "update a activity with a specif... | 3 | stack_v2_sparse_classes_30k_train_038406 | Implement the Python class `activity` described below.
Class description:
Implement the activity class.
Method signatures and docstrings:
- def get(self, activity_id): get a activity with a specific id
- def delete(self, activity_id): delete a activity with a specific id
- def post(self, activity_id): update a activi... | Implement the Python class `activity` described below.
Class description:
Implement the activity class.
Method signatures and docstrings:
- def get(self, activity_id): get a activity with a specific id
- def delete(self, activity_id): delete a activity with a specific id
- def post(self, activity_id): update a activi... | 457dcc732827568bfbc133daacf4fc5c04c8cee7 | <|skeleton|>
class activity:
def get(self, activity_id):
"""get a activity with a specific id"""
<|body_0|>
def delete(self, activity_id):
"""delete a activity with a specific id"""
<|body_1|>
def post(self, activity_id):
"""update a activity with a specific id"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class activity:
def get(self, activity_id):
"""get a activity with a specific id"""
if db.exist_row('activity', id=activity_id):
try:
activity = db.expr_query('activity', id=activity_id)[0]
if not activity:
admin_logger.warning('%d: no ... | the_stack_v2_python_sparse | server/core/route/web_admin.py | Grimm-Source/Grimm | train | 13 | |
b6caafbe2d0d82c07a62ad89c0e127d7818bc4e6 | [
"if root == None:\n return ''\nencoding = []\n\ndef traverse(root: TreeNode):\n if root == None:\n encoding.append(None)\n else:\n encoding.append(root.val)\n traverse(root.left)\n traverse(root.right)\ntraverse(root)\nreturn ' '.join(map(str, encoding))",
"if data == '':\n ... | <|body_start_0|>
if root == None:
return ''
encoding = []
def traverse(root: TreeNode):
if root == None:
encoding.append(None)
else:
encoding.append(root.val)
traverse(root.left)
traverse(root.ri... | 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_75kplus_train_002137 | 1,966 | 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_016829 | 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:... | 22c078fb589196b9695a65d2a2c4977a808279d5 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
encoding = []
def traverse(root: TreeNode):
if root == None:
encoding.append(None)
else:
... | the_stack_v2_python_sparse | 297_serialize_and_deserialize_binary_tree/solution.py | leo-du/leetcode | train | 0 | |
a690d0d5c5aab675496b52eacc8b5d7491a209a7 | [
"self._target = master\nif checkpoint_dir and checkpoint_filename_with_path:\n raise ValueError('Can not provide both checkpoint_dir and checkpoint_filename_with_path.')\nprint('checkpoint_dir', checkpoint_dir)\nprint('checkpoint_filename_with_path', checkpoint_filename_with_path)\nif not saver or not (checkpoin... | <|body_start_0|>
self._target = master
if checkpoint_dir and checkpoint_filename_with_path:
raise ValueError('Can not provide both checkpoint_dir and checkpoint_filename_with_path.')
print('checkpoint_dir', checkpoint_dir)
print('checkpoint_filename_with_path', checkpoint_fil... | TransferSessionManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferSessionManager:
def _restore_checkpoint(self, master, sess, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, load_fc=False):
"""Creates a `Session`, and tries to restore a checkpoint. Args: master: `S... | stack_v2_sparse_classes_75kplus_train_002138 | 21,713 | permissive | [
{
"docstring": "Creates a `Session`, and tries to restore a checkpoint. Args: master: `String` representation of the TensorFlow master to use. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filen... | 2 | stack_v2_sparse_classes_30k_train_030658 | Implement the Python class `TransferSessionManager` described below.
Class description:
Implement the TransferSessionManager class.
Method signatures and docstrings:
- def _restore_checkpoint(self, master, sess, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_s... | Implement the Python class `TransferSessionManager` described below.
Class description:
Implement the TransferSessionManager class.
Method signatures and docstrings:
- def _restore_checkpoint(self, master, sess, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_s... | 12cca87bac44514c55f6ecc9113ee92795ce6800 | <|skeleton|>
class TransferSessionManager:
def _restore_checkpoint(self, master, sess, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, load_fc=False):
"""Creates a `Session`, and tries to restore a checkpoint. Args: master: `S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransferSessionManager:
def _restore_checkpoint(self, master, sess, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, load_fc=False):
"""Creates a `Session`, and tries to restore a checkpoint. Args: master: `String` represe... | the_stack_v2_python_sparse | open_seq2seq/utils/helpers.py | FazedAI/OpenSeq2Seq | train | 2 | |
4218e899c58ff21aefc71adfab6b7216eda90cc8 | [
"self.ID = ID\nself.admin = admin\nself.name = name\nself.cord = (float(X), float(Y))\nself.check = check",
"k = 0.004\np = 0.5\nq = 0.5\nself.mass = 1\nreturn self.mass"
] | <|body_start_0|>
self.ID = ID
self.admin = admin
self.name = name
self.cord = (float(X), float(Y))
self.check = check
<|end_body_0|>
<|body_start_1|>
k = 0.004
p = 0.5
q = 0.5
self.mass = 1
return self.mass
<|end_body_1|>
| This class defines center village which creates center village instance. | Center_Village | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the n... | stack_v2_sparse_classes_75kplus_train_002139 | 7,338 | permissive | [
{
"docstring": "Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the name of village check -- mark whether a village is hollow or center X & Y -- geographical coordinates represented as a tuple type",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_test_000720 | Implement the Python class `Center_Village` described below.
Class description:
This class defines center village which creates center village instance.
Method signatures and docstrings:
- def __init__(self, ID, admin, name: str, check, X, Y): Meaning of arguments: ID -- object id admin -- the administrative village ... | Implement the Python class `Center_Village` described below.
Class description:
This class defines center village which creates center village instance.
Method signatures and docstrings:
- def __init__(self, ID, admin, name: str, check, X, Y): Meaning of arguments: ID -- object id admin -- the administrative village ... | 407d61b3583c472707a4e7b077a9a3ab12743996 | <|skeleton|>
class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the name of villag... | the_stack_v2_python_sparse | VillageMerger/village_new.py | spencerzhang91/coconuts-on-fire | train | 0 |
2bc327d29910be6f3817dd6587b5d93ebbf9e71c | [
"self.room_size_cap = room_size_cap\nself.z_pad = z_pad\nself.img_size = img_size\nself.x_scale = self.img_size / self.room_size_cap[0]\nself.y_scale = self.img_size / self.room_size_cap[2]\nself.z_scale = 1.0 / (self.room_size_cap[1] + self.z_pad)",
"x_scale, y_scale, z_scale = (self.x_scale, self.y_scale, self.... | <|body_start_0|>
self.room_size_cap = room_size_cap
self.z_pad = z_pad
self.img_size = img_size
self.x_scale = self.img_size / self.room_size_cap[0]
self.y_scale = self.img_size / self.room_size_cap[2]
self.z_scale = 1.0 / (self.room_size_cap[1] + self.z_pad)
<|end_body_0... | ProjectionGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
<|body_0|>
def get_projection(self, room):
"""Generates projection matrices specific to a room, need to be r... | stack_v2_sparse_classes_75kplus_train_002140 | 17,039 | permissive | [
{
"docstring": ":param room_size_cap: :param z_pad: :param img_size:",
"name": "__init__",
"signature": "def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512)"
},
{
"docstring": "Generates projection matrices specific to a room, need to be room-specific since every room i... | 2 | stack_v2_sparse_classes_30k_train_047424 | Implement the Python class `ProjectionGenerator` described below.
Class description:
Implement the ProjectionGenerator class.
Method signatures and docstrings:
- def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512): :param room_size_cap: :param z_pad: :param img_size:
- def get_projection(sel... | Implement the Python class `ProjectionGenerator` described below.
Class description:
Implement the ProjectionGenerator class.
Method signatures and docstrings:
- def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512): :param room_size_cap: :param z_pad: :param img_size:
- def get_projection(sel... | 8cdf1cc7d30e9425350548cef364fa25a8be19cf | <|skeleton|>
class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
<|body_0|>
def get_projection(self, room):
"""Generates projection matrices specific to a room, need to be r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectionGenerator:
def __init__(self, room_size_cap=(6.05, 4.05, 6.05), z_pad=0.5, img_size=512):
""":param room_size_cap: :param z_pad: :param img_size:"""
self.room_size_cap = room_size_cap
self.z_pad = z_pad
self.img_size = img_size
self.x_scale = self.img_size / s... | the_stack_v2_python_sparse | dataset/preprocess/View.py | WillisWong/Deep-sync-front | train | 0 | |
25d0d8ac7bebfc2a16555ae0e1aebb024ed7692c | [
"super(slurm_sm, self).check()\nif 'WALLTIME' not in PAR:\n setattr(PAR, 'WALLTIME', 30.0)\nif 'SLURMARGS' not in PAR:\n setattr(PAR, 'SLURMARGS', '')",
"unix.mkdir(PATH.OUTPUT)\nunix.cd(PATH.OUTPUT)\nself.checkpoint()\nunix.run('sbatch ' + '%s ' % PAR.SLURMARGS + '--job-name=%s ' % PAR.TITLE + '--output=%s... | <|body_start_0|>
super(slurm_sm, self).check()
if 'WALLTIME' not in PAR:
setattr(PAR, 'WALLTIME', 30.0)
if 'SLURMARGS' not in PAR:
setattr(PAR, 'SLURMARGS', '')
<|end_body_0|>
<|body_start_1|>
unix.mkdir(PATH.OUTPUT)
unix.cd(PATH.OUTPUT)
self.chec... | An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files are written to a global scratch p... | slurm_sm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class slurm_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate fil... | stack_v2_sparse_classes_75kplus_train_002141 | 1,946 | permissive | [
{
"docstring": "Checks parameters and paths",
"name": "check",
"signature": "def check(self)"
},
{
"docstring": "Submits workflow",
"name": "submit",
"signature": "def submit(self, workflow)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053038 | Implement the Python class `slurm_sm` described below.
Class description:
An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different c... | Implement the Python class `slurm_sm` described below.
Class description:
An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different c... | 47725866ac516767c9eb536f4a0e86c7c0b97482 | <|skeleton|>
class slurm_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate fil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class slurm_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files are writte... | the_stack_v2_python_sparse | seisflows/system/slurm_sm.py | yanhuay/seisflows | train | 1 |
18f2b72990cd56490e71b21967ff35fbabf71892 | [
"LossyExchange.__init__(self, subswarm_keys, crashed_list, msg_publisher, lock, own_id)\nself._short_list_parser = bytes.UShortListParser()\nself._short_list_parser.source_id = self._own_id\nself._value_pair_parser = bytes.IdShortValuePairParser()\nself._value_pair_parser.source_id = self._own_id",
"if msg.id == ... | <|body_start_0|>
LossyExchange.__init__(self, subswarm_keys, crashed_list, msg_publisher, lock, own_id)
self._short_list_parser = bytes.UShortListParser()
self._short_list_parser.source_id = self._own_id
self._value_pair_parser = bytes.IdShortValuePairParser()
self._value_pair_pa... | Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV messaging. All values other than the one for th... | EagerConsensusSort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV m... | stack_v2_sparse_classes_75kplus_train_002142 | 11,562 | no_license | [
{
"docstring": "Initializer for the class sets up class variables used for sorting @param subswarm_keys: Set object containing active subswarm IDs @param crashed_list: Set object containing IDs of possible crashed UAVs @param msg_publisher: ROS publisher to the swarm_data_msg topic @param lock: reentrant lock t... | 4 | stack_v2_sparse_classes_30k_train_030652 | Implement the Python class `EagerConsensusSort` described below.
Class description:
Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort un... | Implement the Python class `EagerConsensusSort` described below.
Class description:
Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort un... | ec2b5c43abed51a37c17bde0c000c2dfbfcbb9b1 | <|skeleton|>
class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EagerConsensusSort:
"""Implements a consensus algorithm (more or less) for numerical sorting The algorithm sorts UAVs by an arbitrary numerical value that each UAV computes on its own behalf. Sorting is from low to high. NOTE: the sorter is set up to sort unsigned shorts to facilitate inter-UAV messaging. All... | the_stack_v2_python_sparse | ap_lib/src/ap_lib/distributed_algorithms.py | jaymonty/autonomy-payload | train | 0 |
9b1cd12520de0df0ded8456e22d603a20f5c62ee | [
"match self:\n case ComponentCase.ANY:\n return string\n case ComponentCase.AS_IS:\n return string\n case ComponentCase.UPPER:\n return string.upper()\n case ComponentCase.LOWER:\n return string.lower()\n case ComponentCase.CAPITALIZED:\n return string.capitalize()"... | <|body_start_0|>
match self:
case ComponentCase.ANY:
return string
case ComponentCase.AS_IS:
return string
case ComponentCase.UPPER:
return string.upper()
case ComponentCase.LOWER:
return string.lower... | Describes the casing for a CompoundSymbolName.Component. | ComponentCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentCase:
"""Describes the casing for a CompoundSymbolName.Component."""
def change_case(self, string: str) -> str:
"""Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the string is returned as-is. >>> ComponentCase.ANY.change_case(... | stack_v2_sparse_classes_75kplus_train_002143 | 27,880 | permissive | [
{
"docstring": "Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the string is returned as-is. >>> ComponentCase.ANY.change_case(\"AString\") 'AString' >>> ComponentCase.UPPER.change_case(\"AString\") 'ASTRING' >>> ComponentCase.LOWER.change_case(\"AString\") 'astr... | 2 | stack_v2_sparse_classes_30k_train_021156 | Implement the Python class `ComponentCase` described below.
Class description:
Describes the casing for a CompoundSymbolName.Component.
Method signatures and docstrings:
- def change_case(self, string: str) -> str: Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the str... | Implement the Python class `ComponentCase` described below.
Class description:
Describes the casing for a CompoundSymbolName.Component.
Method signatures and docstrings:
- def change_case(self, string: str) -> str: Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the str... | 5c5d85e2d9e6b727486d872fbd8e6fa8eceeaf72 | <|skeleton|>
class ComponentCase:
"""Describes the casing for a CompoundSymbolName.Component."""
def change_case(self, string: str) -> str:
"""Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the string is returned as-is. >>> ComponentCase.ANY.change_case(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComponentCase:
"""Describes the casing for a CompoundSymbolName.Component."""
def change_case(self, string: str) -> str:
"""Changes a string to a case matching the one specified by 'self'. If the casing is ANY or AS_IS, the string is returned as-is. >>> ComponentCase.ANY.change_case("AString") 'A... | the_stack_v2_python_sparse | utils/data/compound_symbol_name.py | LuizZak/swift-z3 | train | 8 |
a9c302c0ee50339e86e98224ba679d39c64d4305 | [
"argument = []\nexpected = []\navg.average(argument)\nself.assertEqual(expected, argument, 'The list is empty.')",
"argument = [20]\nexpected = [20]\navg.average(argument)\nself.assertEqual(expected, argument, 'The list has one item')",
"argument = None\nexpected = None\nargument = avg.average(argument)\nself.a... | <|body_start_0|>
argument = []
expected = []
avg.average(argument)
self.assertEqual(expected, argument, 'The list is empty.')
<|end_body_0|>
<|body_start_1|>
argument = [20]
expected = [20]
avg.average(argument)
self.assertEqual(expected, argument, 'The l... | Tests for average. | test_average | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_average:
"""Tests for average."""
def test_empty(self):
"""Test an empty list."""
<|body_0|>
def test_one_item(self):
"""Test a list with one item."""
<|body_1|>
def test_one(self):
"""Test a list with 'None'."""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_002144 | 1,303 | no_license | [
{
"docstring": "Test an empty list.",
"name": "test_empty",
"signature": "def test_empty(self)"
},
{
"docstring": "Test a list with one item.",
"name": "test_one_item",
"signature": "def test_one_item(self)"
},
{
"docstring": "Test a list with 'None'.",
"name": "test_one",
... | 5 | stack_v2_sparse_classes_30k_train_043239 | Implement the Python class `test_average` described below.
Class description:
Tests for average.
Method signatures and docstrings:
- def test_empty(self): Test an empty list.
- def test_one_item(self): Test a list with one item.
- def test_one(self): Test a list with 'None'.
- def test_normal(self): Test a list with ... | Implement the Python class `test_average` described below.
Class description:
Tests for average.
Method signatures and docstrings:
- def test_empty(self): Test an empty list.
- def test_one_item(self): Test a list with one item.
- def test_one(self): Test a list with 'None'.
- def test_normal(self): Test a list with ... | fec4446bb4c4bec34a04e90586d70367332a6881 | <|skeleton|>
class test_average:
"""Tests for average."""
def test_empty(self):
"""Test an empty list."""
<|body_0|>
def test_one_item(self):
"""Test a list with one item."""
<|body_1|>
def test_one(self):
"""Test a list with 'None'."""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_average:
"""Tests for average."""
def test_empty(self):
"""Test an empty list."""
argument = []
expected = []
avg.average(argument)
self.assertEqual(expected, argument, 'The list is empty.')
def test_one_item(self):
"""Test a list with one item.""... | the_stack_v2_python_sparse | test_average.py | ainnes84/DATA520_HW_Notes | train | 0 |
486bf90aaebe5f015056c626ce14a695a50a6c63 | [
"super().__init__()\nself.overhead_time_queue = queue\nself.data_incoming = True\nConsumerThread.id_counter += 1\nself.id = ConsumerThread.id_counter",
"if len(self.overhead_time_queue) == 0:\n print(f'Consumer {self.id} is sleeping since queue is empty')\n time.sleep(0.75)\nwhile self.data_incoming or len(... | <|body_start_0|>
super().__init__()
self.overhead_time_queue = queue
self.data_incoming = True
ConsumerThread.id_counter += 1
self.id = ConsumerThread.id_counter
<|end_body_0|>
<|body_start_1|>
if len(self.overhead_time_queue) == 0:
print(f'Consumer {self.id}... | Consumes data from CityOverheadTimeQueue. | ConsumerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerThread:
"""Consumes data from CityOverheadTimeQueue."""
def __init__(self, queue: CityOverheadTimeQueue):
""":param queue: a CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""Gets data from the queue and prints it."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_002145 | 3,229 | no_license | [
{
"docstring": ":param queue: a CityOverheadTimeQueue",
"name": "__init__",
"signature": "def __init__(self, queue: CityOverheadTimeQueue)"
},
{
"docstring": "Gets data from the queue and prints it.",
"name": "run",
"signature": "def run(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_040817 | Implement the Python class `ConsumerThread` described below.
Class description:
Consumes data from CityOverheadTimeQueue.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue): :param queue: a CityOverheadTimeQueue
- def run(self) -> None: Gets data from the queue and prints it. | Implement the Python class `ConsumerThread` described below.
Class description:
Consumes data from CityOverheadTimeQueue.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue): :param queue: a CityOverheadTimeQueue
- def run(self) -> None: Gets data from the queue and prints it.
<|skel... | 11c3806aee78fa0e78bdf8037d4c203645df5500 | <|skeleton|>
class ConsumerThread:
"""Consumes data from CityOverheadTimeQueue."""
def __init__(self, queue: CityOverheadTimeQueue):
""":param queue: a CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""Gets data from the queue and prints it."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsumerThread:
"""Consumes data from CityOverheadTimeQueue."""
def __init__(self, queue: CityOverheadTimeQueue):
""":param queue: a CityOverheadTimeQueue"""
super().__init__()
self.overhead_time_queue = queue
self.data_incoming = True
ConsumerThread.id_counter += ... | the_stack_v2_python_sparse | Labs/Lab10/producer_consumer.py | chrisyandev/PythonAssignments | train | 0 |
10fc9321325ff983425ab8585dd390d70c3e5554 | [
"ub = str(n)\n\n@lru_cache(None)\ndef dp(i, relaxed):\n if i == len(ub):\n return 1\n ret = 0\n for d in digits:\n if relaxed or d < ub[i]:\n ret += dp(i + 1, True)\n elif d == ub[i]:\n ret += dp(i + 1, False)\n return ret\nret = dp(0, False)\nfor i in range(1,... | <|body_start_0|>
ub = str(n)
@lru_cache(None)
def dp(i, relaxed):
if i == len(ub):
return 1
ret = 0
for d in digits:
if relaxed or d < ub[i]:
ret += dp(i + 1, True)
elif d == ub[i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|bo... | stack_v2_sparse_classes_75kplus_train_002146 | 3,328 | no_license | [
{
"docstring": "Time complexity: O(n) Space complexity: O(n)",
"name": "atMostNGivenDigitSet",
"signature": "def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(1)",
"name": "atMostNGivenDigitSet",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_017863 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: Time complexity: O(n) Space complexity: O(n)
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: Time complexity: O(n) Space complexity: O(n)
- def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
"""Time complexity: O(n) Space complexity: O(n)"""
ub = str(n)
@lru_cache(None)
def dp(i, relaxed):
if i == len(ub):
return 1
ret = 0
for d in digits... | the_stack_v2_python_sparse | leetcode/solved/938_Numbers_At_Most_N_Given_Digit_Set/solution.py | sungminoh/algorithms | train | 0 | |
1fbaaf78678e15b60b81157f09a223fefc183a57 | [
"self.string = self.string.join([str(i) for i in range(10)])\nassert self.string == '0123456789'\nassert self.string.isnumeric()",
"self.string = 'stringy string'\nbuff_list = self.string.split(' ')\nassert len(buff_list) == 2\nassert buff_list[0] == 'stringy' and buff_list[1] == 'string'"
] | <|body_start_0|>
self.string = self.string.join([str(i) for i in range(10)])
assert self.string == '0123456789'
assert self.string.isnumeric()
<|end_body_0|>
<|body_start_1|>
self.string = 'stringy string'
buff_list = self.string.split(' ')
assert len(buff_list) == 2
... | тесты методов, связанных со списками | TestStr3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStr3:
"""тесты методов, связанных со списками"""
def test_str_3_1(self):
"""тест метода join и метода isnumeric"""
<|body_0|>
def test_str_3_2(self):
"""тест метода split"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.string = self.str... | stack_v2_sparse_classes_75kplus_train_002147 | 1,978 | no_license | [
{
"docstring": "тест метода join и метода isnumeric",
"name": "test_str_3_1",
"signature": "def test_str_3_1(self)"
},
{
"docstring": "тест метода split",
"name": "test_str_3_2",
"signature": "def test_str_3_2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042381 | Implement the Python class `TestStr3` described below.
Class description:
тесты методов, связанных со списками
Method signatures and docstrings:
- def test_str_3_1(self): тест метода join и метода isnumeric
- def test_str_3_2(self): тест метода split | Implement the Python class `TestStr3` described below.
Class description:
тесты методов, связанных со списками
Method signatures and docstrings:
- def test_str_3_1(self): тест метода join и метода isnumeric
- def test_str_3_2(self): тест метода split
<|skeleton|>
class TestStr3:
"""тесты методов, связанных со сп... | 9c468bc73dc4e326f423cb7932090f59b50a4371 | <|skeleton|>
class TestStr3:
"""тесты методов, связанных со списками"""
def test_str_3_1(self):
"""тест метода join и метода isnumeric"""
<|body_0|>
def test_str_3_2(self):
"""тест метода split"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStr3:
"""тесты методов, связанных со списками"""
def test_str_3_1(self):
"""тест метода join и метода isnumeric"""
self.string = self.string.join([str(i) for i in range(10)])
assert self.string == '0123456789'
assert self.string.isnumeric()
def test_str_3_2(self):... | the_stack_v2_python_sparse | hw1/test_str.py | ikramanop/2020-1-Atom-QA-Python-L-Marder | train | 1 |
5a8b0fd2fb40ca98919e32e661265235ac734f2d | [
"self.sock = None\nself.socketfile = socketfile\nif os.path.exists(socketfile):\n os.remove(socketfile)",
"self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\nself.sock.bind(self.socketfile)\nos.chmod(self.socketfile, 511)\nprint('open socket')\nself.sock.listen(0)\nreturn self.sock",
"self.sock.s... | <|body_start_0|>
self.sock = None
self.socketfile = socketfile
if os.path.exists(socketfile):
os.remove(socketfile)
<|end_body_0|>
<|body_start_1|>
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.bind(self.socketfile)
os.chmod(self.soc... | context wrapper around unix socket | OpenUnixSocketServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenUnixSocketServer:
"""context wrapper around unix socket"""
def __init__(self, socketfile):
"""init fn"""
<|body_0|>
def __enter__(self):
"""enter fn"""
<|body_1|>
def __exit__(self, exc_type, exc_value, traceback):
"""exit fn"""
<... | stack_v2_sparse_classes_75kplus_train_002148 | 8,088 | no_license | [
{
"docstring": "init fn",
"name": "__init__",
"signature": "def __init__(self, socketfile)"
},
{
"docstring": "enter fn",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "exit fn",
"name": "__exit__",
"signature": "def __exit__(self, exc_type, ex... | 3 | stack_v2_sparse_classes_30k_train_038275 | Implement the Python class `OpenUnixSocketServer` described below.
Class description:
context wrapper around unix socket
Method signatures and docstrings:
- def __init__(self, socketfile): init fn
- def __enter__(self): enter fn
- def __exit__(self, exc_type, exc_value, traceback): exit fn | Implement the Python class `OpenUnixSocketServer` described below.
Class description:
context wrapper around unix socket
Method signatures and docstrings:
- def __init__(self, socketfile): init fn
- def __enter__(self): enter fn
- def __exit__(self, exc_type, exc_value, traceback): exit fn
<|skeleton|>
class OpenUni... | cf7b401d32df537b26525035e72397a6729d3672 | <|skeleton|>
class OpenUnixSocketServer:
"""context wrapper around unix socket"""
def __init__(self, socketfile):
"""init fn"""
<|body_0|>
def __enter__(self):
"""enter fn"""
<|body_1|>
def __exit__(self, exc_type, exc_value, traceback):
"""exit fn"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenUnixSocketServer:
"""context wrapper around unix socket"""
def __init__(self, socketfile):
"""init fn"""
self.sock = None
self.socketfile = socketfile
if os.path.exists(socketfile):
os.remove(socketfile)
def __enter__(self):
"""enter fn"""
... | the_stack_v2_python_sparse | garmin_app/util.py | ddboline/garmin_app | train | 2 |
fb4e3e5edc53763e35ebc03cbd4caf8d7036946f | [
"try:\n instance = self.get_object()\n serializer = self.get_serializer(instance, many=False)\n data = {DATA: serializer.data}\n return Response(self.encrypt_long_data(json.dumps(data)), status=status.HTTP_200_OK)\nexcept Exception as e:\n data = {MESSAGE: 'There was an error; error: {0}'.format(str(... | <|body_start_0|>
try:
instance = self.get_object()
serializer = self.get_serializer(instance, many=False)
data = {DATA: serializer.data}
return Response(self.encrypt_long_data(json.dumps(data)), status=status.HTTP_200_OK)
except Exception as e:
... | AreaTypeDetailAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AreaTypeDetailAPIView:
def retrieve(self, request, *args, **kwargs):
"""retrieve object with id"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""update object with id"""
<|body_1|>
def destroy(self, request, *args, **kwargs):
"""delet... | stack_v2_sparse_classes_75kplus_train_002149 | 27,954 | no_license | [
{
"docstring": "retrieve object with id",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "update object with id",
"name": "update",
"signature": "def update(self, request, *args, **kwargs)"
},
{
"docstring": "delete object with i... | 3 | stack_v2_sparse_classes_30k_train_023356 | Implement the Python class `AreaTypeDetailAPIView` described below.
Class description:
Implement the AreaTypeDetailAPIView class.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): retrieve object with id
- def update(self, request, *args, **kwargs): update object with id
- def destroy(... | Implement the Python class `AreaTypeDetailAPIView` described below.
Class description:
Implement the AreaTypeDetailAPIView class.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): retrieve object with id
- def update(self, request, *args, **kwargs): update object with id
- def destroy(... | ddcaf61932588200f57cd9de246d45a4015eab24 | <|skeleton|>
class AreaTypeDetailAPIView:
def retrieve(self, request, *args, **kwargs):
"""retrieve object with id"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""update object with id"""
<|body_1|>
def destroy(self, request, *args, **kwargs):
"""delet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AreaTypeDetailAPIView:
def retrieve(self, request, *args, **kwargs):
"""retrieve object with id"""
try:
instance = self.get_object()
serializer = self.get_serializer(instance, many=False)
data = {DATA: serializer.data}
return Response(self.encryp... | the_stack_v2_python_sparse | products/api_views.py | BALPRES/BALPRES_BE | train | 0 | |
c6bb655eef84681e7e65bb8139ae9d7bf621c18d | [
"if not config_file:\n raise BaseException('10100', 'Error config file')\nconfigParser.read(config_file, encoding='UTF-8')\nself.assemble()",
"try:\n if isinstance(self._dict[section][item], dict):\n config = ast.literal_eval(configParser.get(section, item))\n self._dict[section][item].update(... | <|body_start_0|>
if not config_file:
raise BaseException('10100', 'Error config file')
configParser.read(config_file, encoding='UTF-8')
self.assemble()
<|end_body_0|>
<|body_start_1|>
try:
if isinstance(self._dict[section][item], dict):
config = a... | Parser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
def load(self, config_file=None):
"""load config data from config file :param config_file: :return:"""
<|body_0|>
def parse(self, section, item):
"""parse config :param section: :param item: :return:"""
<|body_1|>
def assemble(self):
"""a... | stack_v2_sparse_classes_75kplus_train_002150 | 3,548 | permissive | [
{
"docstring": "load config data from config file :param config_file: :return:",
"name": "load",
"signature": "def load(self, config_file=None)"
},
{
"docstring": "parse config :param section: :param item: :return:",
"name": "parse",
"signature": "def parse(self, section, item)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_021209 | Implement the Python class `Parser` described below.
Class description:
Implement the Parser class.
Method signatures and docstrings:
- def load(self, config_file=None): load config data from config file :param config_file: :return:
- def parse(self, section, item): parse config :param section: :param item: :return:
... | Implement the Python class `Parser` described below.
Class description:
Implement the Parser class.
Method signatures and docstrings:
- def load(self, config_file=None): load config data from config file :param config_file: :return:
- def parse(self, section, item): parse config :param section: :param item: :return:
... | 148139eeca0f3cd8a8c2196ae2a6f8cea519d9b5 | <|skeleton|>
class Parser:
def load(self, config_file=None):
"""load config data from config file :param config_file: :return:"""
<|body_0|>
def parse(self, section, item):
"""parse config :param section: :param item: :return:"""
<|body_1|>
def assemble(self):
"""a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parser:
def load(self, config_file=None):
"""load config data from config file :param config_file: :return:"""
if not config_file:
raise BaseException('10100', 'Error config file')
configParser.read(config_file, encoding='UTF-8')
self.assemble()
def parse(self,... | the_stack_v2_python_sparse | torstack/config/parser.py | longniao/torstack | train | 8 | |
0b064402621ad2117faf228067a0d9c6b7c264da | [
"vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS, num_padding_vertices=1)\nself.assertTrue(numpy.allclose(vertex_x_coords_padded, POLYLINE_X_COORDS_PADDED1, atol=TOLERANCE))\nself.assertTrue(numpy.allclose(vertex_y_coords_padded, POLYLINE_Y_COORDS_PADDE... | <|body_start_0|>
vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS, num_padding_vertices=1)
self.assertTrue(numpy.allclose(vertex_x_coords_padded, POLYLINE_X_COORDS_PADDED1, atol=TOLERANCE))
self.assertTrue(numpy.allclose(vertex_y_coor... | Each method is a unit test for shape_utils.py. | ShapeUtilsTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
<|body_0|>
def test_pad_polyline_3vertices(self):
"""Ensures correct output from pad... | stack_v2_sparse_classes_75kplus_train_002151 | 3,833 | permissive | [
{
"docstring": "Ensures correct output from pad_polyline with one padding vertex.",
"name": "test_pad_polyline_1vertex",
"signature": "def test_pad_polyline_1vertex(self)"
},
{
"docstring": "Ensures correct output from pad_polyline with 3 padding vertices.",
"name": "test_pad_polyline_3verti... | 4 | stack_v2_sparse_classes_30k_train_032404 | Implement the Python class `ShapeUtilsTests` described below.
Class description:
Each method is a unit test for shape_utils.py.
Method signatures and docstrings:
- def test_pad_polyline_1vertex(self): Ensures correct output from pad_polyline with one padding vertex.
- def test_pad_polyline_3vertices(self): Ensures co... | Implement the Python class `ShapeUtilsTests` described below.
Class description:
Each method is a unit test for shape_utils.py.
Method signatures and docstrings:
- def test_pad_polyline_1vertex(self): Ensures correct output from pad_polyline with one padding vertex.
- def test_pad_polyline_3vertices(self): Ensures co... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
<|body_0|>
def test_pad_polyline_3vertices(self):
"""Ensures correct output from pad... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShapeUtilsTests:
"""Each method is a unit test for shape_utils.py."""
def test_pad_polyline_1vertex(self):
"""Ensures correct output from pad_polyline with one padding vertex."""
vertex_x_coords_padded, vertex_y_coords_padded = shape_utils.pad_polyline(POLYLINE_X_COORDS, POLYLINE_Y_COORDS... | the_stack_v2_python_sparse | gewittergefahr/gg_utils/shape_utils_test.py | thunderhoser/GewitterGefahr | train | 29 |
311a75d990d50170b1aa6a228895890966cf193a | [
"if T is None:\n T = len(index)\nout = generate_gbm_paths(S0, mu, sigma, T, len(index), I, seed=seed)[1:]\nif out.shape[1] == 1:\n return pd.Series(out[:, 0], index=index)\ncolumns = pd.RangeIndex(stop=out.shape[1], name='path')\nreturn pd.DataFrame(out, index=index, columns=columns)",
"download_kwargs = se... | <|body_start_0|>
if T is None:
T = len(index)
out = generate_gbm_paths(S0, mu, sigma, T, len(index), I, seed=seed)[1:]
if out.shape[1] == 1:
return pd.Series(out[:, 0], index=index)
columns = pd.RangeIndex(stop=out.shape[1], name='path')
return pd.DataFram... | `SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-05-02 14:14:15.182089+00:00 102.386... | GBMData | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-... | stack_v2_sparse_classes_75kplus_train_002152 | 30,831 | permissive | [
{
"docstring": "Generate the symbol using `generate_gbm_paths`. Args: symbol (str): Symbol. index (pd.Index): Pandas index. S0 (float): Value at time 0. Does not appear as the first value in the output data. mu (float): Drift, or mean of the percentage change. sigma (float): Standard deviation of the percentage... | 2 | stack_v2_sparse_classes_30k_val_002673 | Implement the Python class `GBMData` described below.
Class description:
`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1... | Implement the Python class `GBMData` described below.
Class description:
`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1... | 0cd596e1be975d4af6379d883090ffb5b7375d08 | <|skeleton|>
class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GBMData:
"""`SyntheticData` for data generated using Geometric Brownian Motion (GBM). ## Example See the example under `BinanceData`. ```python-repl >>> import vectorbt as vbt >>> gbm_data = vbt.GBMData.download('GBM', start='2 hours ago', end='now', freq='1min', seed=42) >>> gbm_data.get() 2021-05-02 14:14:1... | the_stack_v2_python_sparse | vectorbt/data/custom.py | davidandreoletti/vectorbt | train | 0 |
0319f4809c5da883fc22f96ce71a75daf22f95c8 | [
"queryset = super(InviteListView, self).get_queryset()\nquery = self.request.GET.get('q')\nif query:\n queryset = queryset.filter(email__icontains=query)\nreturn queryset",
"context = super(InviteListView, self).get_context_data(**kwargs)\ncontext['q'] = self.request.GET.get('q', '')\nreturn context"
] | <|body_start_0|>
queryset = super(InviteListView, self).get_queryset()
query = self.request.GET.get('q')
if query:
queryset = queryset.filter(email__icontains=query)
return queryset
<|end_body_0|>
<|body_start_1|>
context = super(InviteListView, self).get_context_dat... | View for listing invites. | InviteListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InviteListView:
"""View for listing invites."""
def get_queryset(self):
"""Get the queryset."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get context data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = super(InviteListView... | stack_v2_sparse_classes_75kplus_train_002153 | 18,678 | permissive | [
{
"docstring": "Get the queryset.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Get context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001356 | Implement the Python class `InviteListView` described below.
Class description:
View for listing invites.
Method signatures and docstrings:
- def get_queryset(self): Get the queryset.
- def get_context_data(self, **kwargs): Get context data. | Implement the Python class `InviteListView` described below.
Class description:
View for listing invites.
Method signatures and docstrings:
- def get_queryset(self): Get the queryset.
- def get_context_data(self, **kwargs): Get context data.
<|skeleton|>
class InviteListView:
"""View for listing invites."""
... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class InviteListView:
"""View for listing invites."""
def get_queryset(self):
"""Get the queryset."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get context data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InviteListView:
"""View for listing invites."""
def get_queryset(self):
"""Get the queryset."""
queryset = super(InviteListView, self).get_queryset()
query = self.request.GET.get('q')
if query:
queryset = queryset.filter(email__icontains=query)
return q... | the_stack_v2_python_sparse | open_connect/accounts/views.py | ofa/connect | train | 66 |
a0b074843eb919ca31ea389f9f15c00d6c47e3f8 | [
"time_start = datetime.datetime(2017, 11, 1, 3)\ntime_mid = datetime.datetime(2017, 11, 1, 6)\ntime_end = datetime.datetime(2017, 11, 1, 9)\nself.npoints = 3\nequalarea_domain_corner, equalarea_grid_spacing = _grid_params('equalarea', self.npoints)\nlatlon_domain_corner, latlon_grid_spacing = _grid_params('latlon',... | <|body_start_0|>
time_start = datetime.datetime(2017, 11, 1, 3)
time_mid = datetime.datetime(2017, 11, 1, 6)
time_end = datetime.datetime(2017, 11, 1, 9)
self.npoints = 3
equalarea_domain_corner, equalarea_grid_spacing = _grid_params('equalarea', self.npoints)
latlon_doma... | Test Calculate lats and lons. | Test_calc_lats_lons | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_calc_lats_lons:
"""Test Calculate lats and lons."""
def setUp(self):
"""Set up the test inputs."""
<|body_0|>
def test_lat_lon(self):
"""Test that the function returns the lats and lons expected."""
<|body_1|>
def test_x_y(self):
"""Test... | stack_v2_sparse_classes_75kplus_train_002154 | 33,531 | permissive | [
{
"docstring": "Set up the test inputs.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the function returns the lats and lons expected.",
"name": "test_lat_lon",
"signature": "def test_lat_lon(self)"
},
{
"docstring": "Test that the function return... | 3 | null | Implement the Python class `Test_calc_lats_lons` described below.
Class description:
Test Calculate lats and lons.
Method signatures and docstrings:
- def setUp(self): Set up the test inputs.
- def test_lat_lon(self): Test that the function returns the lats and lons expected.
- def test_x_y(self): Test that the funct... | Implement the Python class `Test_calc_lats_lons` described below.
Class description:
Test Calculate lats and lons.
Method signatures and docstrings:
- def setUp(self): Set up the test inputs.
- def test_lat_lon(self): Test that the function returns the lats and lons expected.
- def test_x_y(self): Test that the funct... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_calc_lats_lons:
"""Test Calculate lats and lons."""
def setUp(self):
"""Set up the test inputs."""
<|body_0|>
def test_lat_lon(self):
"""Test that the function returns the lats and lons expected."""
<|body_1|>
def test_x_y(self):
"""Test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_calc_lats_lons:
"""Test Calculate lats and lons."""
def setUp(self):
"""Set up the test inputs."""
time_start = datetime.datetime(2017, 11, 1, 3)
time_mid = datetime.datetime(2017, 11, 1, 6)
time_end = datetime.datetime(2017, 11, 1, 9)
self.npoints = 3
... | the_stack_v2_python_sparse | improver_tests/utilities/test_TemporalInterpolation.py | metoppv/improver | train | 101 |
6ebeca076a8bd8ce3170b8068e21293a00ff6c95 | [
"QThread.__init__(self, parent=parent)\nself.isRunning = True\nself.loca = directory",
"r = open(self.loca, 'r')\nlines = r.readlines()\nr.close()\nnums = []\nfor line in lines:\n num = line.split(sep=',')\n nums.append(num)\nfirst_number = int(nums[-2][-2])\nself.t = open(self.loca, 'w')\nnew_number = firs... | <|body_start_0|>
QThread.__init__(self, parent=parent)
self.isRunning = True
self.loca = directory
<|end_body_0|>
<|body_start_1|>
r = open(self.loca, 'r')
lines = r.readlines()
r.close()
nums = []
for line in lines:
num = line.split(sep=',')
... | Thread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Thread:
def __init__(self, directory, parent=None):
"""Setting up the thread"""
<|body_0|>
def run(self):
"""Writing the job numbers and updating the progress bar"""
<|body_1|>
def stop(self):
"""Stopping the thread"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_002155 | 6,218 | permissive | [
{
"docstring": "Setting up the thread",
"name": "__init__",
"signature": "def __init__(self, directory, parent=None)"
},
{
"docstring": "Writing the job numbers and updating the progress bar",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Stopping the thread",
... | 3 | stack_v2_sparse_classes_30k_test_001616 | Implement the Python class `Thread` described below.
Class description:
Implement the Thread class.
Method signatures and docstrings:
- def __init__(self, directory, parent=None): Setting up the thread
- def run(self): Writing the job numbers and updating the progress bar
- def stop(self): Stopping the thread | Implement the Python class `Thread` described below.
Class description:
Implement the Thread class.
Method signatures and docstrings:
- def __init__(self, directory, parent=None): Setting up the thread
- def run(self): Writing the job numbers and updating the progress bar
- def stop(self): Stopping the thread
<|skel... | d4156d96f11cbcc736d524eb69a5cd21ddb713e0 | <|skeleton|>
class Thread:
def __init__(self, directory, parent=None):
"""Setting up the thread"""
<|body_0|>
def run(self):
"""Writing the job numbers and updating the progress bar"""
<|body_1|>
def stop(self):
"""Stopping the thread"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Thread:
def __init__(self, directory, parent=None):
"""Setting up the thread"""
QThread.__init__(self, parent=parent)
self.isRunning = True
self.loca = directory
def run(self):
"""Writing the job numbers and updating the progress bar"""
r = open(self.loca, ... | the_stack_v2_python_sparse | JobNumbers.py | alangburl/BEI_Invoice | train | 0 | |
b2335e57994164743df1ac49174db7bd7d9e9c54 | [
"SeleniumService.__init__(self)\nself.engine = 'bing'\nself.URLBASE = 'http://bing.com/search?'",
"params = {'q': query}\nbrowser_url = '{}{}'.format(self.URLBASE, urlencode(params))\nself.load_page(browser_url)\ntitles = list()\nurls = list()\nsnippets = list()\nresult_divs = self.browser.find_elements_by_class_... | <|body_start_0|>
SeleniumService.__init__(self)
self.engine = 'bing'
self.URLBASE = 'http://bing.com/search?'
<|end_body_0|>
<|body_start_1|>
params = {'q': query}
browser_url = '{}{}'.format(self.URLBASE, urlencode(params))
self.load_page(browser_url)
titles = l... | Specialized service for scraping bing.com search engine | BingService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BingService:
"""Specialized service for scraping bing.com search engine"""
def __init__(self):
"""Initialize virtual browser and set correct url base"""
<|body_0|>
def process_query(self, query):
"""Process query and return all titles and snippets in one list Arg... | stack_v2_sparse_classes_75kplus_train_002156 | 8,761 | permissive | [
{
"docstring": "Initialize virtual browser and set correct url base",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Process query and return all titles and snippets in one list Arguments: query -- query that we want to answer",
"name": "process_query",
"signatu... | 2 | stack_v2_sparse_classes_30k_test_001485 | Implement the Python class `BingService` described below.
Class description:
Specialized service for scraping bing.com search engine
Method signatures and docstrings:
- def __init__(self): Initialize virtual browser and set correct url base
- def process_query(self, query): Process query and return all titles and sni... | Implement the Python class `BingService` described below.
Class description:
Specialized service for scraping bing.com search engine
Method signatures and docstrings:
- def __init__(self): Initialize virtual browser and set correct url base
- def process_query(self, query): Process query and return all titles and sni... | af03252e19075feec3fa478fa271ea3ae8cf8d11 | <|skeleton|>
class BingService:
"""Specialized service for scraping bing.com search engine"""
def __init__(self):
"""Initialize virtual browser and set correct url base"""
<|body_0|>
def process_query(self, query):
"""Process query and return all titles and snippets in one list Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BingService:
"""Specialized service for scraping bing.com search engine"""
def __init__(self):
"""Initialize virtual browser and set correct url base"""
SeleniumService.__init__(self)
self.engine = 'bing'
self.URLBASE = 'http://bing.com/search?'
def process_query(self... | the_stack_v2_python_sparse | services/SeleniumServices.py | kubasikora/WEDT-Projekt | train | 0 |
3b2eaffae9c871e915c92b7f4c0e827580397f0e | [
"v.update({'Accept': 'application/vnd.github.v3+json'})\nif values['use_GH_token'] and (token := marvin.settings.GITHUB_TOKEN.get_secret_value()):\n v['Authorization'] = f'Bearer {token}'\nreturn v",
"url = f'https://api.github.com/repos/{repo}/issues/{issue_number}/comments'\ncomments = []\npage = 1\nasync wi... | <|body_start_0|>
v.update({'Accept': 'application/vnd.github.v3+json'})
if values['use_GH_token'] and (token := marvin.settings.GITHUB_TOKEN.get_secret_value()):
v['Authorization'] = f'Bearer {token}'
return v
<|end_body_0|>
<|body_start_1|>
url = f'https://api.github.com/re... | Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` environment variable and increase the rate limit. | GitHubIssueLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitHubIssueLoader:
"""Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` environment variable and increase the rate li... | stack_v2_sparse_classes_75kplus_train_002157 | 8,754 | permissive | [
{
"docstring": "Add authentication headers if a GitHub token is available.",
"name": "auth_headers",
"signature": "def auth_headers(cls, v, values)"
},
{
"docstring": "Get a list of all comments for the given issue. Returns: A list of dictionaries, each representing a comment.",
"name": "_ge... | 4 | stack_v2_sparse_classes_30k_val_002148 | Implement the Python class `GitHubIssueLoader` described below.
Class description:
Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` enviro... | Implement the Python class `GitHubIssueLoader` described below.
Class description:
Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` enviro... | 00ef03a7bb4938459f39f4e01dff42f0b0fb0d3e | <|skeleton|>
class GitHubIssueLoader:
"""Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` environment variable and increase the rate li... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitHubIssueLoader:
"""Loader for GitHub issues in a given repository. **Beware** the [GitHub API rate limit](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting). Use `use_GH_token` to authenticate with your `GITHUB_TOKEN` environment variable and increase the rate limit."""
... | the_stack_v2_python_sparse | src/marvin/loaders/github.py | foxgrover/marvin | train | 0 |
8c9ec614f83314eb3b68788a60ccd2359d719b59 | [
"super(BaselineEarlyFusionSE, self).__init__()\nself.multi_extractor = MultiExtractor(cfg)\nconv_style = 'Conv1d'\nif corr_matrix:\n conv_style = 'Conv2d'\nif max_pool:\n self.se_layer = MaxSELayer(channel=cfg.MODALITY.NUMS, reduction=1, conv_style=conv_style)\nelse:\n self.se_layer = SELayer(channel=cfg.M... | <|body_start_0|>
super(BaselineEarlyFusionSE, self).__init__()
self.multi_extractor = MultiExtractor(cfg)
conv_style = 'Conv1d'
if corr_matrix:
conv_style = 'Conv2d'
if max_pool:
self.se_layer = MaxSELayer(channel=cfg.MODALITY.NUMS, reduction=1, conv_style... | BaselineEarlyFusionSE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineEarlyFusionSE:
def __init__(self, cfg, max_pool=False, corr_matrix=False):
""":param num_class: :param requirements: Should not include class part."""
<|body_0|>
def forward(self, x, return_feature=False):
""":param x: A list of tensor :return:"""
<|b... | stack_v2_sparse_classes_75kplus_train_002158 | 8,984 | no_license | [
{
"docstring": ":param num_class: :param requirements: Should not include class part.",
"name": "__init__",
"signature": "def __init__(self, cfg, max_pool=False, corr_matrix=False)"
},
{
"docstring": ":param x: A list of tensor :return:",
"name": "forward",
"signature": "def forward(self... | 2 | stack_v2_sparse_classes_30k_train_020790 | Implement the Python class `BaselineEarlyFusionSE` described below.
Class description:
Implement the BaselineEarlyFusionSE class.
Method signatures and docstrings:
- def __init__(self, cfg, max_pool=False, corr_matrix=False): :param num_class: :param requirements: Should not include class part.
- def forward(self, x,... | Implement the Python class `BaselineEarlyFusionSE` described below.
Class description:
Implement the BaselineEarlyFusionSE class.
Method signatures and docstrings:
- def __init__(self, cfg, max_pool=False, corr_matrix=False): :param num_class: :param requirements: Should not include class part.
- def forward(self, x,... | 390acce96c8422fff1a6e14e86437b3cc2e414cb | <|skeleton|>
class BaselineEarlyFusionSE:
def __init__(self, cfg, max_pool=False, corr_matrix=False):
""":param num_class: :param requirements: Should not include class part."""
<|body_0|>
def forward(self, x, return_feature=False):
""":param x: A list of tensor :return:"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaselineEarlyFusionSE:
def __init__(self, cfg, max_pool=False, corr_matrix=False):
""":param num_class: :param requirements: Should not include class part."""
super(BaselineEarlyFusionSE, self).__init__()
self.multi_extractor = MultiExtractor(cfg)
conv_style = 'Conv1d'
... | the_stack_v2_python_sparse | libs/models/baseline.py | wkoa/Multimodal_USMC | train | 0 | |
7f17220bdc515fdeb651e91c932625f9dd41b390 | [
"ThresholdStrategy.__init__(self, **kwargs)\nself._kernel_size = kwargs.get('kernel_size', (3, 3))\nself._gain = kwargs.get('gain')\nself._n_sigma_b = kwargs.get('n_sigma_b', 6)\nself._n_sigma_s = kwargs.get('n_sigma_s', 3)\nself._min_count = kwargs.get('min_count', 2)\nself._threshold = kwargs.get('global_threshol... | <|body_start_0|>
ThresholdStrategy.__init__(self, **kwargs)
self._kernel_size = kwargs.get('kernel_size', (3, 3))
self._gain = kwargs.get('gain')
self._n_sigma_b = kwargs.get('n_sigma_b', 6)
self._n_sigma_s = kwargs.get('n_sigma_s', 3)
self._min_count = kwargs.get('min_co... | A class implementing a 'gain' threshold. | DispersionExtendedThresholdStrategy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispersionExtendedThresholdStrategy:
"""A class implementing a 'gain' threshold."""
def __init__(self, **kwargs):
"""Set the threshold algorithm up"""
<|body_0|>
def __call__(self, image, mask):
"""Call the thresholding function :param image: The image to process... | stack_v2_sparse_classes_75kplus_train_002159 | 4,405 | permissive | [
{
"docstring": "Set the threshold algorithm up",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Call the thresholding function :param image: The image to process :param mask: The mask to use :return: The thresholded image",
"name": "__call__",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_007513 | Implement the Python class `DispersionExtendedThresholdStrategy` described below.
Class description:
A class implementing a 'gain' threshold.
Method signatures and docstrings:
- def __init__(self, **kwargs): Set the threshold algorithm up
- def __call__(self, image, mask): Call the thresholding function :param image:... | Implement the Python class `DispersionExtendedThresholdStrategy` described below.
Class description:
A class implementing a 'gain' threshold.
Method signatures and docstrings:
- def __init__(self, **kwargs): Set the threshold algorithm up
- def __call__(self, image, mask): Call the thresholding function :param image:... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class DispersionExtendedThresholdStrategy:
"""A class implementing a 'gain' threshold."""
def __init__(self, **kwargs):
"""Set the threshold algorithm up"""
<|body_0|>
def __call__(self, image, mask):
"""Call the thresholding function :param image: The image to process... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DispersionExtendedThresholdStrategy:
"""A class implementing a 'gain' threshold."""
def __init__(self, **kwargs):
"""Set the threshold algorithm up"""
ThresholdStrategy.__init__(self, **kwargs)
self._kernel_size = kwargs.get('kernel_size', (3, 3))
self._gain = kwargs.get('... | the_stack_v2_python_sparse | src/dials/algorithms/spot_finding/threshold.py | dials/dials | train | 71 |
a1519afed19f12a189ff0ab46e6c003914650f5e | [
"ret = []\nfor mail in self.mails:\n if partial_content in mail.content:\n ret.append(mail)\n if first:\n break\nreturn ret",
"ret = []\nfor mail in self.mails:\n if exact and mail.subject == subject_keyword or subject_keyword in mail.subject:\n ret.append(mail)\n if f... | <|body_start_0|>
ret = []
for mail in self.mails:
if partial_content in mail.content:
ret.append(mail)
if first:
break
return ret
<|end_body_0|>
<|body_start_1|>
ret = []
for mail in self.mails:
if exact... | Class representing a mocking email box. | EmailBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailBox:
"""Class representing a mocking email box."""
def get_mail_with_content(self, partial_content: str, *, first=False) -> List[EmailEntry]:
"""Get the email(s) which content contains ``partial_content``. :param partial_content: partial content of the email(s) to get :param fir... | stack_v2_sparse_classes_75kplus_train_002160 | 3,068 | permissive | [
{
"docstring": "Get the email(s) which content contains ``partial_content``. :param partial_content: partial content of the email(s) to get :param first: if returning the first matching email only :return: list of emails which content contains `partial_content`",
"name": "get_mail_with_content",
"signat... | 2 | stack_v2_sparse_classes_30k_train_025341 | Implement the Python class `EmailBox` described below.
Class description:
Class representing a mocking email box.
Method signatures and docstrings:
- def get_mail_with_content(self, partial_content: str, *, first=False) -> List[EmailEntry]: Get the email(s) which content contains ``partial_content``. :param partial_c... | Implement the Python class `EmailBox` described below.
Class description:
Class representing a mocking email box.
Method signatures and docstrings:
- def get_mail_with_content(self, partial_content: str, *, first=False) -> List[EmailEntry]: Get the email(s) which content contains ``partial_content``. :param partial_c... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class EmailBox:
"""Class representing a mocking email box."""
def get_mail_with_content(self, partial_content: str, *, first=False) -> List[EmailEntry]:
"""Get the email(s) which content contains ``partial_content``. :param partial_content: partial content of the email(s) to get :param fir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailBox:
"""Class representing a mocking email box."""
def get_mail_with_content(self, partial_content: str, *, first=False) -> List[EmailEntry]:
"""Get the email(s) which content contains ``partial_content``. :param partial_content: partial content of the email(s) to get :param first: if return... | the_stack_v2_python_sparse | extutils/emailutils/mock.py | RxJellyBot/Jelly-Bot | train | 5 |
bf8ef45c14e5749f4023d9ebcb497e59a4bfd861 | [
"workflow_collection_subscription = WorkflowCollectionSubscription.objects.create(user=validated_data['user'], active=validated_data['active'] if validated_data.get('active') else True, workflow_collection=validated_data['workflow_collection'])\nworkflowcollectionsubscriptionschedule_data = validated_data.pop('work... | <|body_start_0|>
workflow_collection_subscription = WorkflowCollectionSubscription.objects.create(user=validated_data['user'], active=validated_data['active'] if validated_data.get('active') else True, workflow_collection=validated_data['workflow_collection'])
workflowcollectionsubscriptionschedule_data... | ModelSerializer for Workflow Collection Subscription Objects. | WorkflowCollectionSubscriptionSummarySerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowCollectionSubscriptionSummarySerializer:
"""ModelSerializer for Workflow Collection Subscription Objects."""
def create(self, validated_data):
"""Override create() method to be able to handle nested WorkflowCollectionSubscriptionSchedule object creations."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_002161 | 4,366 | permissive | [
{
"docstring": "Override create() method to be able to handle nested WorkflowCollectionSubscriptionSchedule object creations.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update WorkflowCollectionSubscription and WorkflowCollectionSubscriptionSchedule ob... | 2 | stack_v2_sparse_classes_30k_train_020501 | Implement the Python class `WorkflowCollectionSubscriptionSummarySerializer` described below.
Class description:
ModelSerializer for Workflow Collection Subscription Objects.
Method signatures and docstrings:
- def create(self, validated_data): Override create() method to be able to handle nested WorkflowCollectionSu... | Implement the Python class `WorkflowCollectionSubscriptionSummarySerializer` described below.
Class description:
ModelSerializer for Workflow Collection Subscription Objects.
Method signatures and docstrings:
- def create(self, validated_data): Override create() method to be able to handle nested WorkflowCollectionSu... | dc0e8807263266713d3d7fa46e240e8d72db28d1 | <|skeleton|>
class WorkflowCollectionSubscriptionSummarySerializer:
"""ModelSerializer for Workflow Collection Subscription Objects."""
def create(self, validated_data):
"""Override create() method to be able to handle nested WorkflowCollectionSubscriptionSchedule object creations."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowCollectionSubscriptionSummarySerializer:
"""ModelSerializer for Workflow Collection Subscription Objects."""
def create(self, validated_data):
"""Override create() method to be able to handle nested WorkflowCollectionSubscriptionSchedule object creations."""
workflow_collection_su... | the_stack_v2_python_sparse | django_workflow_system/api/serializers/user/workflows/subscription.py | kwang1971/django-workflow-system | train | 0 |
2bad838e29bd81682cecb3bf5c6295af7d9e10a2 | [
"super().__init__(min_mz=min_mz, max_mz=max_mz)\nself.mzml_file_name = mzml_file_name\nself.source_polarity = source_polarity\nself._get_distributions()",
"mzml_file_object = MZMLFile(str(self.mzml_file_name))\nmz_bins = {}\nfor scan in mzml_file_object.scans:\n if not scan.ms_level == 1:\n continue\n ... | <|body_start_0|>
super().__init__(min_mz=min_mz, max_mz=max_mz)
self.mzml_file_name = mzml_file_name
self.source_polarity = source_polarity
self._get_distributions()
<|end_body_0|>
<|body_start_1|>
mzml_file_object = MZMLFile(str(self.mzml_file_name))
mz_bins = {}
... | A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file | MZMLFormulaSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MZMLFormulaSampler:
"""A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file"""
def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_MZ, source_polarity=POSITIVE):
"""Create an mzML formula sampler Args: mzml_file_name: the source mzML ... | stack_v2_sparse_classes_75kplus_train_002162 | 36,021 | permissive | [
{
"docstring": "Create an mzML formula sampler Args: mzml_file_name: the source mzML file min_mz: the minimum m/z to consider max_mz: the maximum m/z to consider source_polarity: either POSITIVE or NEGATIVE",
"name": "__init__",
"signature": "def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_... | 3 | null | Implement the Python class `MZMLFormulaSampler` described below.
Class description:
A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file
Method signatures and docstrings:
- def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_MZ, source_polarity=POSITIVE): Create an mz... | Implement the Python class `MZMLFormulaSampler` described below.
Class description:
A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file
Method signatures and docstrings:
- def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_MZ, source_polarity=POSITIVE): Create an mz... | e5d97ae4ff42d613fc55db51443e1e733999b908 | <|skeleton|>
class MZMLFormulaSampler:
"""A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file"""
def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_MZ, source_polarity=POSITIVE):
"""Create an mzML formula sampler Args: mzml_file_name: the source mzML ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MZMLFormulaSampler:
"""A sampler to generate m/z values from a histogram of m/z taken from a user supplied mzML file"""
def __init__(self, mzml_file_name, min_mz=MIN_MZ, max_mz=MAX_MZ, source_polarity=POSITIVE):
"""Create an mzML formula sampler Args: mzml_file_name: the source mzML file min_mz: ... | the_stack_v2_python_sparse | vimms/ChemicalSamplers.py | glasgowcompbio/vimms | train | 22 |
4f91bfd2089fdb28fe03e287621db3f9eedebdb9 | [
"from bars_items.models.sellitem import SellItem\nfrom bars_stats.utils import compute_ranking\nf = {'stockitems__itemoperation__transaction__bar': pk, 'stockitems__itemoperation__transaction__type__in': ('buy', 'meal'), 'stockitems__deleted': False}\nann = Count('stockitems__itemoperation__transaction') / Count('s... | <|body_start_0|>
from bars_items.models.sellitem import SellItem
from bars_stats.utils import compute_ranking
f = {'stockitems__itemoperation__transaction__bar': pk, 'stockitems__itemoperation__transaction__type__in': ('buy', 'meal'), 'stockitems__deleted': False}
ann = Count('stockitems... | BarViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - nam... | stack_v2_sparse_classes_75kplus_train_002163 | 7,957 | no_license | [
{
"docstring": "Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - name: date_end required: false type: datetime paramType: query",
... | 3 | stack_v2_sparse_classes_30k_train_002429 | Implement the Python class `BarViewSet` described below.
Class description:
Implement the BarViewSet class.
Method signatures and docstrings:
- def sellitem_ranking(self, request, pk): Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_se... | Implement the Python class `BarViewSet` described below.
Class description:
Implement the BarViewSet class.
Method signatures and docstrings:
- def sellitem_ranking(self, request, pk): Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_se... | 7e464d4398e14b94d5b802bbd73c563639b5f125 | <|skeleton|>
class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BarViewSet:
def sellitem_ranking(self, request, pk):
"""Return a ranking of the most consumed SellItems in the bar. Response format: `[{sellitem: id, total: (float)total}, ...]` --- omit_serializer: true parameters: - name: date_start required: false type: datetime paramType: query - name: date_end re... | the_stack_v2_python_sparse | bars_core/models/bar.py | BinetReseau/chocapix-server | train | 2 | |
46e78d276eb7b8e1463b3a9f193df66d9c9ced3f | [
"M, N, D = (len(A), len(A[0]), len(B[0]))\nresult = [[0 for x in xrange(D)] for x in xrange(M)]\ncache = defaultdict(list)\nfor i in range(M):\n for j in range(N):\n if A[i][j] != 0:\n cache[i].append(j)\nfor i in range(M):\n for k in range(D):\n val = 0\n for col in cache[i]:\... | <|body_start_0|>
M, N, D = (len(A), len(A[0]), len(B[0]))
result = [[0 for x in xrange(D)] for x in xrange(M)]
cache = defaultdict(list)
for i in range(M):
for j in range(N):
if A[i][j] != 0:
cache[i].append(j)
for i in range(M):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def dumb_multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_002164 | 1,732 | permissive | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "multiply",
"signature": "def multiply(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "dumb_multiply",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_026277 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def dumb_multiply(self, A, B): :type A: List[List[int]] :type B: List[List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def dumb_multiply(self, A, B): :type A: List[List[int]] :type B: List[List[i... | 91db15a686a2f36bf0a00c9bedd5b14b46aaa97b | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def dumb_multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
M, N, D = (len(A), len(A[0]), len(B[0]))
result = [[0 for x in xrange(D)] for x in xrange(M)]
cache = defaultdict(list)
for i in range(M):
for... | the_stack_v2_python_sparse | problems/311_sparse-matrix-multiplication/main.py | young-geng/leet_code | train | 0 | |
7fa046e92ae745dab30e1f6d57a67417b35c612c | [
"state_id = self.request.get('sid')\nif not state_id:\n self.ReportError('Missing required parameters.', status=400)\n return\nstate = ndb.Key(page_state.PageState, state_id).get()\nif not state:\n self.ReportError('Invalid sid.', status=400)\n return\nself.response.out.write(state.value)",
"state = s... | <|body_start_0|>
state_id = self.request.get('sid')
if not state_id:
self.ReportError('Missing required parameters.', status=400)
return
state = ndb.Key(page_state.PageState, state_id).get()
if not state:
self.ReportError('Invalid sid.', status=400)
... | Handles short URI. | ShortUriHandler | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShortUriHandler:
"""Handles short URI."""
def get(self):
"""Handles getting page states."""
<|body_0|>
def post(self):
"""Handles saving page states and getting state id."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
state_id = self.request.ge... | stack_v2_sparse_classes_75kplus_train_002165 | 1,456 | permissive | [
{
"docstring": "Handles getting page states.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Handles saving page states and getting state id.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001448 | Implement the Python class `ShortUriHandler` described below.
Class description:
Handles short URI.
Method signatures and docstrings:
- def get(self): Handles getting page states.
- def post(self): Handles saving page states and getting state id. | Implement the Python class `ShortUriHandler` described below.
Class description:
Handles short URI.
Method signatures and docstrings:
- def get(self): Handles getting page states.
- def post(self): Handles saving page states and getting state id.
<|skeleton|>
class ShortUriHandler:
"""Handles short URI."""
... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ShortUriHandler:
"""Handles short URI."""
def get(self):
"""Handles getting page states."""
<|body_0|>
def post(self):
"""Handles saving page states and getting state id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShortUriHandler:
"""Handles short URI."""
def get(self):
"""Handles getting page states."""
state_id = self.request.get('sid')
if not state_id:
self.ReportError('Missing required parameters.', status=400)
return
state = ndb.Key(page_state.PageState,... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/short_uri.py | metux/chromium-suckless | train | 5 |
5c0aa3049c4806c69022cedb2da6f92f990031e5 | [
"from sklearn.linear_model import TheilSenRegressor\nmodel = TheilSenRegressor()\nreturn self._solve(regression_input, model)",
"from sklearn.linear_model import TheilSenRegressor\nn_subsamples = None\nif self.n_subsamples is not None:\n n_subsamples = int(self.n_subsamples * obs.shape[0])\nmodel = TheilSenReg... | <|body_start_0|>
from sklearn.linear_model import TheilSenRegressor
model = TheilSenRegressor()
return self._solve(regression_input, model)
<|end_body_0|>
<|body_start_1|>
from sklearn.linear_model import TheilSenRegressor
n_subsamples = None
if self.n_subsamples is not ... | Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html | SolverScikitTheilSen | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolverScikitTheilSen:
"""Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html"""
def run(self, regression_input: RegressionI... | stack_v2_sparse_classes_75kplus_train_002166 | 36,895 | permissive | [
{
"docstring": "Run TheilSen regression on the RegressionInputData",
"name": "run",
"signature": "def run(self, regression_input: RegressionInputData) -> Solution"
},
{
"docstring": "Get coefficients for a single evaluation frequency and output channel Parameters ---------- model : BaseEstimator... | 2 | stack_v2_sparse_classes_30k_test_000000 | Implement the Python class `SolverScikitTheilSen` described below.
Class description:
Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html
Method sign... | Implement the Python class `SolverScikitTheilSen` described below.
Class description:
Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html
Method sign... | cba60747803b6c582eaaf1a670a7f455f5724ebd | <|skeleton|>
class SolverScikitTheilSen:
"""Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html"""
def run(self, regression_input: RegressionI... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolverScikitTheilSen:
"""Scikit Theil Sen solver This is simply a wrapper around the scikit learn Theil Sen Regressor. For more information, please see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html"""
def run(self, regression_input: RegressionInputData) -> ... | the_stack_v2_python_sparse | resistics/regression.py | resistics/resistics | train | 47 |
16c3c2469b6f31aae5220c7c2ad830d196c5c0fc | [
"data = memcache.get(sid)\nif not data:\n session = ndb.model.Key(cls, sid).get()\n if session:\n data = session.data\n memcache.set(sid, data)\nreturn data",
"usersessions = Session.query(Session.user_id == int(user_id)).fetch()\nlogging.info(usersessions)\nfor session in usersessions:\n s... | <|body_start_0|>
data = memcache.get(sid)
if not data:
session = ndb.model.Key(cls, sid).get()
if session:
data = session.data
memcache.set(sid, data)
return data
<|end_body_0|>
<|body_start_1|>
usersessions = Session.query(Session... | Session | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
<|body_0|>
def delete_by_user_id(cls, self, user_id):
"""Returns a ``Session`` instance by session id. :param si... | stack_v2_sparse_classes_75kplus_train_002167 | 7,647 | no_license | [
{
"docstring": "Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.",
"name": "get_by_sid",
"signature": "def get_by_sid(cls, sid)"
},
{
"docstring": "Returns a ``Session`` instance by session id. :param sid: A session id. :returns: A... | 2 | stack_v2_sparse_classes_30k_train_029811 | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get_by_sid(cls, sid): Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.
- def delete_by_user_id(cls, self, user_... | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def get_by_sid(cls, sid): Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity.
- def delete_by_user_id(cls, self, user_... | 2dd85af47312c4a229c927b28ca02d443d03053e | <|skeleton|>
class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
<|body_0|>
def delete_by_user_id(cls, self, user_id):
"""Returns a ``Session`` instance by session id. :param si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Session:
def get_by_sid(cls, sid):
"""Returns a ``Session`` instance by session id. :param sid: A session id. :returns: An existing ``Session`` entity."""
data = memcache.get(sid)
if not data:
session = ndb.model.Key(cls, sid).get()
if session:
d... | the_stack_v2_python_sparse | models.py | resida/cointemplebotph1 | train | 1 | |
cec4325b3cb154ce77ab0b3e6d677ba17595c922 | [
"if self.window.editors:\n self.enabled = True\nelse:\n self.enabled = False",
"active_editor = self.window.active_editor\nif self.enabled and active_editor is not None:\n active_editor.save_as()"
] | <|body_start_0|>
if self.window.editors:
self.enabled = True
else:
self.enabled = False
<|end_body_0|>
<|body_start_1|>
active_editor = self.window.active_editor
if self.enabled and active_editor is not None:
active_editor.save_as()
<|end_body_1|>
| Defines an action that save the contents of the current editor to a new name. | SaveAsAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveAsAction:
"""Defines an action that save the contents of the current editor to a new name."""
def _active_editor_changed_for_window(self):
"""Enables the action if the window has editors."""
<|body_0|>
def perform(self, event):
"""Performs the action."""
... | stack_v2_sparse_classes_75kplus_train_002168 | 3,865 | permissive | [
{
"docstring": "Enables the action if the window has editors.",
"name": "_active_editor_changed_for_window",
"signature": "def _active_editor_changed_for_window(self)"
},
{
"docstring": "Performs the action.",
"name": "perform",
"signature": "def perform(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047439 | Implement the Python class `SaveAsAction` described below.
Class description:
Defines an action that save the contents of the current editor to a new name.
Method signatures and docstrings:
- def _active_editor_changed_for_window(self): Enables the action if the window has editors.
- def perform(self, event): Perform... | Implement the Python class `SaveAsAction` described below.
Class description:
Defines an action that save the contents of the current editor to a new name.
Method signatures and docstrings:
- def _active_editor_changed_for_window(self): Enables the action if the window has editors.
- def perform(self, event): Perform... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class SaveAsAction:
"""Defines an action that save the contents of the current editor to a new name."""
def _active_editor_changed_for_window(self):
"""Enables the action if the window has editors."""
<|body_0|>
def perform(self, event):
"""Performs the action."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaveAsAction:
"""Defines an action that save the contents of the current editor to a new name."""
def _active_editor_changed_for_window(self):
"""Enables the action if the window has editors."""
if self.window.editors:
self.enabled = True
else:
self.enabled... | the_stack_v2_python_sparse | puddle/resource/action/save_as_action.py | rwl/puddle | train | 2 |
cab0eacdf0041b98e925da80778997868efcfcba | [
"self.top_stack_1 = None\nself.bottom_stack_1 = None\nself.items_1 = []\nself.items_3 = []",
"try:\n new_node = Node(value)\n if self.top_stack_1 == None:\n self.top_stack_1 = new_node\n self.items_1.append(self.top_stack_1.value)\n else:\n current = self.top_stack_1\n print('... | <|body_start_0|>
self.top_stack_1 = None
self.bottom_stack_1 = None
self.items_1 = []
self.items_3 = []
<|end_body_0|>
<|body_start_1|>
try:
new_node = Node(value)
if self.top_stack_1 == None:
self.top_stack_1 = new_node
se... | Pseudo_Queue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pseudo_Queue:
def __init__(self):
"""This is initial method of class Stack, it has one attribute, it's called top."""
<|body_0|>
def enqueue(self, value):
"""This is enqueue method of class Pseudo_Queue, it has two attribute, they're called new_node, temp. push metho... | stack_v2_sparse_classes_75kplus_train_002169 | 4,406 | no_license | [
{
"docstring": "This is initial method of class Stack, it has one attribute, it's called top.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This is enqueue method of class Pseudo_Queue, it has two attribute, they're called new_node, temp. push method use to add an it... | 4 | stack_v2_sparse_classes_30k_train_019448 | Implement the Python class `Pseudo_Queue` described below.
Class description:
Implement the Pseudo_Queue class.
Method signatures and docstrings:
- def __init__(self): This is initial method of class Stack, it has one attribute, it's called top.
- def enqueue(self, value): This is enqueue method of class Pseudo_Queue... | Implement the Python class `Pseudo_Queue` described below.
Class description:
Implement the Pseudo_Queue class.
Method signatures and docstrings:
- def __init__(self): This is initial method of class Stack, it has one attribute, it's called top.
- def enqueue(self, value): This is enqueue method of class Pseudo_Queue... | 59911228986fc54588b8e3aa6ec7cb7e3aeb33bc | <|skeleton|>
class Pseudo_Queue:
def __init__(self):
"""This is initial method of class Stack, it has one attribute, it's called top."""
<|body_0|>
def enqueue(self, value):
"""This is enqueue method of class Pseudo_Queue, it has two attribute, they're called new_node, temp. push metho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pseudo_Queue:
def __init__(self):
"""This is initial method of class Stack, it has one attribute, it's called top."""
self.top_stack_1 = None
self.bottom_stack_1 = None
self.items_1 = []
self.items_3 = []
def enqueue(self, value):
"""This is enqueue method ... | the_stack_v2_python_sparse | data_structures_and_algorithm/challenge/queue_with_stacks/queue_with_stacks.py | MohamadSheikhAlshabab/data-structures-and-algorithm | train | 0 | |
9aa392a0be30880f93ea0fba78741a4c8dc039d9 | [
"super(InstrumentHeaderGenerator, self).__init__(context, [], datasets_since)\nself.instruments = instruments\nself.sources = self.determine_source_ids()\nself.save_pickles = save_pickles\ntry:\n self.segment_size = server_info.max_headers_per_rpc\nexcept Exception:\n self.segment_size = 5000",
"server = ap... | <|body_start_0|>
super(InstrumentHeaderGenerator, self).__init__(context, [], datasets_since)
self.instruments = instruments
self.sources = self.determine_source_ids()
self.save_pickles = save_pickles
try:
self.segment_size = server_info.max_headers_per_rpc
ex... | Generates lookup parameters and historical best references from a list of instrument names. Server/DB based. | InstrumentHeaderGenerator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstrumentHeaderGenerator:
"""Generates lookup parameters and historical best references from a list of instrument names. Server/DB based."""
def __init__(self, context, instruments, datasets_since, save_pickles, server_info):
""""Contact the CRDS server and get headers for the list ... | stack_v2_sparse_classes_75kplus_train_002170 | 18,932 | permissive | [
{
"docstring": "\"Contact the CRDS server and get headers for the list of `instruments` names with respect to `context`.",
"name": "__init__",
"signature": "def __init__(self, context, instruments, datasets_since, save_pickles, server_info)"
},
{
"docstring": "Return the dataset ids for all inst... | 4 | null | Implement the Python class `InstrumentHeaderGenerator` described below.
Class description:
Generates lookup parameters and historical best references from a list of instrument names. Server/DB based.
Method signatures and docstrings:
- def __init__(self, context, instruments, datasets_since, save_pickles, server_info... | Implement the Python class `InstrumentHeaderGenerator` described below.
Class description:
Generates lookup parameters and historical best references from a list of instrument names. Server/DB based.
Method signatures and docstrings:
- def __init__(self, context, instruments, datasets_since, save_pickles, server_info... | 08da10721c0e979877dc9579b4092c79f4ceee27 | <|skeleton|>
class InstrumentHeaderGenerator:
"""Generates lookup parameters and historical best references from a list of instrument names. Server/DB based."""
def __init__(self, context, instruments, datasets_since, save_pickles, server_info):
""""Contact the CRDS server and get headers for the list ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstrumentHeaderGenerator:
"""Generates lookup parameters and historical best references from a list of instrument names. Server/DB based."""
def __init__(self, context, instruments, datasets_since, save_pickles, server_info):
""""Contact the CRDS server and get headers for the list of `instrumen... | the_stack_v2_python_sparse | crds/bestrefs/headers.py | spacetelescope/crds | train | 9 |
8cde3ad6fe45973fbc75ad87986a27d0b8f8a12e | [
"self._app = _app\nself.viewer = viewer\nself.tournament = tournament",
"from app.controllers.tournament_ranking import TournamentRankingController\nself._app.change_controller(TournamentRankingController(self.tournament))\nself.viewer.warning = ''\nreturn False",
"if command_name == CommandField.RANKING:\n ... | <|body_start_0|>
self._app = _app
self.viewer = viewer
self.tournament = tournament
<|end_body_0|>
<|body_start_1|>
from app.controllers.tournament_ranking import TournamentRankingController
self._app.change_controller(TournamentRankingController(self.tournament))
self.v... | Project go_to_ranking_menu command class. | GotoRankingMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GotoRankingMenu:
"""Project go_to_ranking_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_ranking_menu command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<... | stack_v2_sparse_classes_75kplus_train_002171 | 9,466 | no_license | [
{
"docstring": "Init go_to_ranking_menu command class.",
"name": "__init__",
"signature": "def __init__(self, _app, viewer, tournament)"
},
{
"docstring": "Execute command and return False to not exit application.",
"name": "exe_command",
"signature": "def exe_command(self)"
},
{
... | 3 | null | Implement the Python class `GotoRankingMenu` described below.
Class description:
Project go_to_ranking_menu command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer, tournament): Init go_to_ranking_menu command class.
- def exe_command(self): Execute command and return False to not exit appl... | Implement the Python class `GotoRankingMenu` described below.
Class description:
Project go_to_ranking_menu command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer, tournament): Init go_to_ranking_menu command class.
- def exe_command(self): Execute command and return False to not exit appl... | be6089cd71c762f23725b61e8d2745cfabe4f0c0 | <|skeleton|>
class GotoRankingMenu:
"""Project go_to_ranking_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_ranking_menu command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GotoRankingMenu:
"""Project go_to_ranking_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_ranking_menu command class."""
self._app = _app
self.viewer = viewer
self.tournament = tournament
def exe_command(self):
"""Execute com... | the_stack_v2_python_sparse | app/commands/navigation.py | FortranVBA/DAP4 | train | 0 |
f106f14db434e94eaae65c507743dca5f9e8bdaa | [
"super(Dexpression, self).__init__()\nself.conv1 = Conv2d(in_channels=1, out_channels=64, kernel_size=7, stride=2, padding=3)\nself.pool1 = MaxPool2d(kernel_size=3, stride=2, padding=0)\nself.lrn1 = LayerNorm([64, 55, 55])\nself.conv2a = Conv2d(in_channels=64, out_channels=96, kernel_size=1, stride=1, padding=0)\ns... | <|body_start_0|>
super(Dexpression, self).__init__()
self.conv1 = Conv2d(in_channels=1, out_channels=64, kernel_size=7, stride=2, padding=3)
self.pool1 = MaxPool2d(kernel_size=3, stride=2, padding=0)
self.lrn1 = LayerNorm([64, 55, 55])
self.conv2a = Conv2d(in_channels=64, out_cha... | Convolutional Neural Network for facial expression recognition. | Dexpression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dexpression:
"""Convolutional Neural Network for facial expression recognition."""
def __init__(self):
"""The constructor for Dexpression class."""
<|body_0|>
def forward(self, x, dropout=True, batch_normalization=True):
"""Performs a single forward pass through ... | stack_v2_sparse_classes_75kplus_train_002172 | 3,798 | permissive | [
{
"docstring": "The constructor for Dexpression class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Performs a single forward pass through the network. Parameters ---------- x : object The training batch containing input and output variables. dropout : bool, optiona... | 2 | stack_v2_sparse_classes_30k_train_011616 | Implement the Python class `Dexpression` described below.
Class description:
Convolutional Neural Network for facial expression recognition.
Method signatures and docstrings:
- def __init__(self): The constructor for Dexpression class.
- def forward(self, x, dropout=True, batch_normalization=True): Performs a single ... | Implement the Python class `Dexpression` described below.
Class description:
Convolutional Neural Network for facial expression recognition.
Method signatures and docstrings:
- def __init__(self): The constructor for Dexpression class.
- def forward(self, x, dropout=True, batch_normalization=True): Performs a single ... | 6aac1fffee31062afda5fb1403f328d9c2502137 | <|skeleton|>
class Dexpression:
"""Convolutional Neural Network for facial expression recognition."""
def __init__(self):
"""The constructor for Dexpression class."""
<|body_0|>
def forward(self, x, dropout=True, batch_normalization=True):
"""Performs a single forward pass through ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dexpression:
"""Convolutional Neural Network for facial expression recognition."""
def __init__(self):
"""The constructor for Dexpression class."""
super(Dexpression, self).__init__()
self.conv1 = Conv2d(in_channels=1, out_channels=64, kernel_size=7, stride=2, padding=3)
s... | the_stack_v2_python_sparse | dexpression_pytorch/cnn_model/dexpression.py | rdgozum/dexpression-pytorch | train | 8 |
649e76e35a2eeddbe8137017412deca4265b62d4 | [
"X_2D_zero = X_2D * self.real_val_mask\ncolumn_vals = self._impute_columns(X_2D_zero)\nimputed_vals = tf.gather(column_vals, self.missing_ind[:, 1])\nX_new = tf.scatter_nd(self.missing_ind, imputed_vals, shape=tf.shape(X_2D, out_type=tf.int64))\nX_imp = X_2D_zero + X_new\nreturn X_imp",
"raise NotImplementedError... | <|body_start_0|>
X_2D_zero = X_2D * self.real_val_mask
column_vals = self._impute_columns(X_2D_zero)
imputed_vals = tf.gather(column_vals, self.missing_ind[:, 1])
X_new = tf.scatter_nd(self.missing_ind, imputed_vals, shape=tf.shape(X_2D, out_type=tf.int64))
X_imp = X_2D_zero + X_... | Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need to supply the ``_impute_columns`` method. | ImputeColumnWise | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImputeColumnWise:
"""Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need to supply the ``_impute_columns`` method... | stack_v2_sparse_classes_75kplus_train_002173 | 10,387 | permissive | [
{
"docstring": "Randomly impute a rank 2 tensor. Parameters ---------- X_2D : Tensor a rank 2 Tensor with missing data Returns ------- X_imputed : Tensor a rank 2 Tensor with imputed data",
"name": "_impute2D",
"signature": "def _impute2D(self, X_2D)"
},
{
"docstring": "Generate a vector to subt... | 2 | null | Implement the Python class `ImputeColumnWise` described below.
Class description:
Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need t... | Implement the Python class `ImputeColumnWise` described below.
Class description:
Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need t... | 53a3de23dce4d607ffec92be936e83d2dd7ebb3c | <|skeleton|>
class ImputeColumnWise:
"""Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need to supply the ``_impute_columns`` method... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImputeColumnWise:
"""Abstract class for imputing column-wise from a vector or scalar. This implements ``_impute2D`` and this calls the ``_impute_columns`` method that returns a vector or scalar to impute X column-wise (as opposed to element-wise). You need to supply the ``_impute_columns`` method."""
def... | the_stack_v2_python_sparse | aboleth/impute.py | LaplaceKorea/aboleth | train | 0 |
3eae08e8accfe55a283d49e2202f4555a4ee2252 | [
"self.variables = main_variables['settings']\nself.queue_to_measure = queue_to_measurement_event_loop\nself.final_job = {}\nself.log = logging.getLogger(__name__)",
"self.final_job = additional_settings_dict\nheader = '# Measurement file: \\n # Project: ' + self.variables['Current_project'] + '\\n # Sensor Type: ... | <|body_start_0|>
self.variables = main_variables['settings']
self.queue_to_measure = queue_to_measurement_event_loop
self.final_job = {}
self.log = logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
self.final_job = additional_settings_dict
header = '# Measureme... | This class handles all measurement generation items | measurement_job_generation | [
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class measurement_job_generation:
"""This class handles all measurement generation items"""
def __init__(self, main_variables, queue_to_measurement_event_loop):
""":param main_variables: Simply the state machine variables ('defaults') :param queue_to_measurement_event_loop:"""
<|bo... | stack_v2_sparse_classes_75kplus_train_002174 | 11,845 | permissive | [
{
"docstring": ":param main_variables: Simply the state machine variables ('defaults') :param queue_to_measurement_event_loop:",
"name": "__init__",
"signature": "def __init__(self, main_variables, queue_to_measurement_event_loop)"
},
{
"docstring": "This function handles all the work need to be... | 4 | stack_v2_sparse_classes_30k_train_027098 | Implement the Python class `measurement_job_generation` described below.
Class description:
This class handles all measurement generation items
Method signatures and docstrings:
- def __init__(self, main_variables, queue_to_measurement_event_loop): :param main_variables: Simply the state machine variables ('defaults'... | Implement the Python class `measurement_job_generation` described below.
Class description:
This class handles all measurement generation items
Method signatures and docstrings:
- def __init__(self, main_variables, queue_to_measurement_event_loop): :param main_variables: Simply the state machine variables ('defaults'... | 121e5c0530f5195a8f7c6b8de96a1653322f6e48 | <|skeleton|>
class measurement_job_generation:
"""This class handles all measurement generation items"""
def __init__(self, main_variables, queue_to_measurement_event_loop):
""":param main_variables: Simply the state machine variables ('defaults') :param queue_to_measurement_event_loop:"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class measurement_job_generation:
"""This class handles all measurement generation items"""
def __init__(self, main_variables, queue_to_measurement_event_loop):
""":param main_variables: Simply the state machine variables ('defaults') :param queue_to_measurement_event_loop:"""
self.variables = ... | the_stack_v2_python_sparse | COMET/ui_plugins/QTCMain_window.py | Chilldose/COMET | train | 0 |
9062bc5df67d87f18a30a1fdd9de05725e3e8cfc | [
"try:\n group = Group.objects.get(name=group_name)\n bgroup = BossGroup.objects.get(group=group)\n if not check_is_member_or_maintainer(request.user, group_name):\n return BossHTTPError('The user {} is not a member or maintainer of the group {} '.format(request.user.username, group_name), ErrorCodes... | <|body_start_0|>
try:
group = Group.objects.get(name=group_name)
bgroup = BossGroup.objects.get(group=group)
if not check_is_member_or_maintainer(request.user, group_name):
return BossHTTPError('The user {} is not a member or maintainer of the group {} '.forma... | View to add a maintainer to a group | BossGroupMaintainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BossGroupMaintainer:
"""View to add a maintainer to a group"""
def get(self, request, group_name, user_name=None):
"""Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Group name from the request user_name: User name from the re... | stack_v2_sparse_classes_75kplus_train_002175 | 19,131 | permissive | [
{
"docstring": "Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Group name from the request user_name: User name from the request Returns: bool : True if the user is a member of the group",
"name": "get",
"signature": "def get(self, request, grou... | 3 | null | Implement the Python class `BossGroupMaintainer` described below.
Class description:
View to add a maintainer to a group
Method signatures and docstrings:
- def get(self, request, group_name, user_name=None): Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Gro... | Implement the Python class `BossGroupMaintainer` described below.
Class description:
View to add a maintainer to a group
Method signatures and docstrings:
- def get(self, request, group_name, user_name=None): Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Gro... | c2e26d272bd7b8d54abdc2948193163537e31291 | <|skeleton|>
class BossGroupMaintainer:
"""View to add a maintainer to a group"""
def get(self, request, group_name, user_name=None):
"""Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Group name from the request user_name: User name from the re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BossGroupMaintainer:
"""View to add a maintainer to a group"""
def get(self, request, group_name, user_name=None):
"""Gets the maintianer status of a user for a group Args: request: Django rest framework request group_name: Group name from the request user_name: User name from the request Returns... | the_stack_v2_python_sparse | django/bosscore/views/views_group.py | jhuapl-boss/boss | train | 20 |
8df6a2c611ec0b231297b531ecb457fded5a8281 | [
"for start in range(0, 101, 20):\n page_url = self.url.format(start)\n yield scrapy.Request(url=page_url, callback=self.parse)",
"html = json.loads(response.text)\nfor one_dict in html:\n item = DoubanItem()\n item['rank'] = one_dict['rank']\n item['title'] = one_dict['title']\n item['score'] = ... | <|body_start_0|>
for start in range(0, 101, 20):
page_url = self.url.format(start)
yield scrapy.Request(url=page_url, callback=self.parse)
<|end_body_0|>
<|body_start_1|>
html = json.loads(response.text)
for one_dict in html:
item = DoubanItem()
i... | DoubanSpider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoubanSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,交给调度器入队列"""
<|body_0|>
def parse(self, response):
"""解析提取数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for start in range(0, 101, 20):
page_url = self.url.format(start)
... | stack_v2_sparse_classes_75kplus_train_002176 | 996 | permissive | [
{
"docstring": "生成所有要抓取的URL地址,交给调度器入队列",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "解析提取数据",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043532 | Implement the Python class `DoubanSpider` described below.
Class description:
Implement the DoubanSpider class.
Method signatures and docstrings:
- def start_requests(self): 生成所有要抓取的URL地址,交给调度器入队列
- def parse(self, response): 解析提取数据 | Implement the Python class `DoubanSpider` described below.
Class description:
Implement the DoubanSpider class.
Method signatures and docstrings:
- def start_requests(self): 生成所有要抓取的URL地址,交给调度器入队列
- def parse(self, response): 解析提取数据
<|skeleton|>
class DoubanSpider:
def start_requests(self):
"""生成所有要抓取的U... | abe983ddc52690f4726cf42cc6390cba815026d8 | <|skeleton|>
class DoubanSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,交给调度器入队列"""
<|body_0|>
def parse(self, response):
"""解析提取数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoubanSpider:
def start_requests(self):
"""生成所有要抓取的URL地址,交给调度器入队列"""
for start in range(0, 101, 20):
page_url = self.url.format(start)
yield scrapy.Request(url=page_url, callback=self.parse)
def parse(self, response):
"""解析提取数据"""
html = json.loads(... | the_stack_v2_python_sparse | month05/spider/day07_course/day07_code/Douban/Douban/spiders/douban.py | chaofan-zheng/tedu-python-demo | train | 4 | |
f73e4bcf78273940cbba1f31c19d6d28be77824b | [
"for fld in ['TargetNameFields', 'TargetInfoFields']:\n yield (fld, self[fld])\nreturn",
"for _, item in self.enumerate():\n yield item\nreturn",
"for item in self.iterate():\n yield item\nreturn"
] | <|body_start_0|>
for fld in ['TargetNameFields', 'TargetInfoFields']:
yield (fld, self[fld])
return
<|end_body_0|>
<|body_start_1|>
for _, item in self.enumerate():
yield item
return
<|end_body_1|>
<|body_start_2|>
for item in self.iterate():
... | CHALLENGE_MESSAGE | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CHALLENGE_MESSAGE:
def enumerate(self):
"""Yield the name and field that compose the message type payload."""
<|body_0|>
def iterate(self):
"""Yield each field that composes the message type payload."""
<|body_1|>
def Fields(self):
"""Yield all o... | stack_v2_sparse_classes_75kplus_train_002177 | 31,838 | permissive | [
{
"docstring": "Yield the name and field that compose the message type payload.",
"name": "enumerate",
"signature": "def enumerate(self)"
},
{
"docstring": "Yield each field that composes the message type payload.",
"name": "iterate",
"signature": "def iterate(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_test_000285 | Implement the Python class `CHALLENGE_MESSAGE` described below.
Class description:
Implement the CHALLENGE_MESSAGE class.
Method signatures and docstrings:
- def enumerate(self): Yield the name and field that compose the message type payload.
- def iterate(self): Yield each field that composes the message type payloa... | Implement the Python class `CHALLENGE_MESSAGE` described below.
Class description:
Implement the CHALLENGE_MESSAGE class.
Method signatures and docstrings:
- def enumerate(self): Yield the name and field that compose the message type payload.
- def iterate(self): Yield each field that composes the message type payloa... | e02b014dc764ed822288210248c9438a843af8a9 | <|skeleton|>
class CHALLENGE_MESSAGE:
def enumerate(self):
"""Yield the name and field that compose the message type payload."""
<|body_0|>
def iterate(self):
"""Yield each field that composes the message type payload."""
<|body_1|>
def Fields(self):
"""Yield all o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CHALLENGE_MESSAGE:
def enumerate(self):
"""Yield the name and field that compose the message type payload."""
for fld in ['TargetNameFields', 'TargetInfoFields']:
yield (fld, self[fld])
return
def iterate(self):
"""Yield each field that composes the message typ... | the_stack_v2_python_sparse | template/protocol/nlmp.py | arizvisa/syringe | train | 36 | |
4b5ac54d0f16099f7167679f1643b7a2e6d736a4 | [
"self.chart_type = 'PieChart'\nself.options = options\nself.columns = columns\nself.rows = rows",
"data_init = 'var data = new google.visualization.DataTable();'\ncolumns_code = self.create_columns(self.columns)\nrows_code = self.create_rows(self.rows)\ncontent = data_init + columns_code + rows_code\noptions = se... | <|body_start_0|>
self.chart_type = 'PieChart'
self.options = options
self.columns = columns
self.rows = rows
<|end_body_0|>
<|body_start_1|>
data_init = 'var data = new google.visualization.DataTable();'
columns_code = self.create_columns(self.columns)
rows_code ... | Class to create PieCharts | PieChart | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PieChart:
"""Class to create PieCharts"""
def __init__(self, columns, rows, options=None):
"""Initialization"""
<|body_0|>
def render(self):
"""Method that returns the html code with js code embedded"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002178 | 10,734 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, columns, rows, options=None)"
},
{
"docstring": "Method that returns the html code with js code embedded",
"name": "render",
"signature": "def render(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001883 | Implement the Python class `PieChart` described below.
Class description:
Class to create PieCharts
Method signatures and docstrings:
- def __init__(self, columns, rows, options=None): Initialization
- def render(self): Method that returns the html code with js code embedded | Implement the Python class `PieChart` described below.
Class description:
Class to create PieCharts
Method signatures and docstrings:
- def __init__(self, columns, rows, options=None): Initialization
- def render(self): Method that returns the html code with js code embedded
<|skeleton|>
class PieChart:
"""Class... | a7dd3abc48730cd223e2131b3b5e44c614ac77f3 | <|skeleton|>
class PieChart:
"""Class to create PieCharts"""
def __init__(self, columns, rows, options=None):
"""Initialization"""
<|body_0|>
def render(self):
"""Method that returns the html code with js code embedded"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PieChart:
"""Class to create PieCharts"""
def __init__(self, columns, rows, options=None):
"""Initialization"""
self.chart_type = 'PieChart'
self.options = options
self.columns = columns
self.rows = rows
def render(self):
"""Method that returns the htm... | the_stack_v2_python_sparse | libs/charting.py | ankeshanand/benchmark | train | 1 |
42adfa548cad9d2e0ce89e1696786a04422b0d4d | [
"self.open_ticket_office_manage()\nself.input_ticket_office_add_info(self.add_list, self.info_dict)\nself.click_button_for_one(u'确 定')",
"self.ticket_office_add()\ntips = self.get_tips()\nself.assert_result_equal(u'新增成功', tips, u'兑奖处管理新增')\nsleep(2)\nself.put_away_main_menu()\nself.choose_ticket_province_city(sel... | <|body_start_0|>
self.open_ticket_office_manage()
self.input_ticket_office_add_info(self.add_list, self.info_dict)
self.click_button_for_one(u'确 定')
<|end_body_0|>
<|body_start_1|>
self.ticket_office_add()
tips = self.get_tips()
self.assert_result_equal(u'新增成功', tips, u'... | 彩票兑奖管理(兑奖处理) | TicketOfficeManageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
<|body_0|>
def test_ticket_office_manage_add(self):
"""兑奖处管理"""
<|body_1|>
def test_ticket_office_manage_edite(self):
"""兑奖处管理编辑"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_002179 | 3,702 | no_license | [
{
"docstring": "统一的新增入口",
"name": "ticket_office_add",
"signature": "def ticket_office_add(self)"
},
{
"docstring": "兑奖处管理",
"name": "test_ticket_office_manage_add",
"signature": "def test_ticket_office_manage_add(self)"
},
{
"docstring": "兑奖处管理编辑",
"name": "test_ticket_offic... | 5 | stack_v2_sparse_classes_30k_train_022320 | Implement the Python class `TicketOfficeManageTest` described below.
Class description:
彩票兑奖管理(兑奖处理)
Method signatures and docstrings:
- def ticket_office_add(self): 统一的新增入口
- def test_ticket_office_manage_add(self): 兑奖处管理
- def test_ticket_office_manage_edite(self): 兑奖处管理编辑
- def test_ticket_office_status_cancel(sel... | Implement the Python class `TicketOfficeManageTest` described below.
Class description:
彩票兑奖管理(兑奖处理)
Method signatures and docstrings:
- def ticket_office_add(self): 统一的新增入口
- def test_ticket_office_manage_add(self): 兑奖处管理
- def test_ticket_office_manage_edite(self): 兑奖处管理编辑
- def test_ticket_office_status_cancel(sel... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
<|body_0|>
def test_ticket_office_manage_add(self):
"""兑奖处管理"""
<|body_1|>
def test_ticket_office_manage_edite(self):
"""兑奖处管理编辑"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TicketOfficeManageTest:
"""彩票兑奖管理(兑奖处理)"""
def ticket_office_add(self):
"""统一的新增入口"""
self.open_ticket_office_manage()
self.input_ticket_office_add_info(self.add_list, self.info_dict)
self.click_button_for_one(u'确 定')
def test_ticket_office_manage_add(self):
"... | the_stack_v2_python_sparse | genlot_vlt2/cases/BusinessOperation/lottery_manage/ticket_office_manage_test.py | bbwdi/auto | train | 1 |
2419b86baa784cba60e27f93da8c99778a1a7d93 | [
"self.msgType = None\nself.msgNr = None\nself.dest = None\nself.origin = None\nself.content = None",
"if self.msgType is None:\n raise SerializationError('The message is missing the message type.')\nif self.dest is None:\n raise SerializationError('The message is missing the destination.')\nif len(self.dest... | <|body_start_0|>
self.msgType = None
self.msgNr = None
self.dest = None
self.origin = None
self.content = None
<|end_body_0|>
<|body_start_1|>
if self.msgType is None:
raise SerializationError('The message is missing the message type.')
if self.dest i... | This class represents a message which should be sent from one communication node to another. | Message | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""This class represents a message which should be sent from one communication node to another."""
def __init__(self):
"""Initialize the message fields with None."""
<|body_0|>
def serialize(self, manager):
"""Serialize the message. The fields msgType, d... | stack_v2_sparse_classes_75kplus_train_002180 | 4,920 | permissive | [
{
"docstring": "Initialize the message fields with None.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Serialize the message. The fields msgType, dest and depending on msgType content has to be set before this method is called. @param manager: CommManager which has a... | 3 | stack_v2_sparse_classes_30k_train_042684 | Implement the Python class `Message` described below.
Class description:
This class represents a message which should be sent from one communication node to another.
Method signatures and docstrings:
- def __init__(self): Initialize the message fields with None.
- def serialize(self, manager): Serialize the message. ... | Implement the Python class `Message` described below.
Class description:
This class represents a message which should be sent from one communication node to another.
Method signatures and docstrings:
- def __init__(self): Initialize the message fields with None.
- def serialize(self, manager): Serialize the message. ... | c277efd809fce8f0f18b009fb3b9c7f785cc3739 | <|skeleton|>
class Message:
"""This class represents a message which should be sent from one communication node to another."""
def __init__(self):
"""Initialize the message fields with None."""
<|body_0|>
def serialize(self, manager):
"""Serialize the message. The fields msgType, d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Message:
"""This class represents a message which should be sent from one communication node to another."""
def __init__(self):
"""Initialize the message fields with None."""
self.msgType = None
self.msgNr = None
self.dest = None
self.origin = None
self.con... | the_stack_v2_python_sparse | framework/comm/message.py | LCROBOT/rce | train | 0 |
aab86d3af7f45effafe1c3c08d3ab5c16c4218a8 | [
"super(DS2Scorer, self).__init__()\nself.infer = DS2Encoder()\nself.ckpt_filename = ckpt_filename\nself.is_restored = False\nself.collect_names = ['pooled_activations']",
"ckpt_filename = ckpt_filename or self.ckpt_filename\nself.infer(waves=tf.ones([16, 48000, 1]))\nreader = tf.train.load_checkpoint(ckpt_filenam... | <|body_start_0|>
super(DS2Scorer, self).__init__()
self.infer = DS2Encoder()
self.ckpt_filename = ckpt_filename
self.is_restored = False
self.collect_names = ['pooled_activations']
<|end_body_0|>
<|body_start_1|>
ckpt_filename = ckpt_filename or self.ckpt_filename
... | Speech scorer based on DeepSpeech2. | DS2Scorer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
<|body_0|>
def restore(self, ckpt_filename=None):
"""Restore the model from a checkpoint. Args: ckpt_filename... | stack_v2_sparse_classes_75kplus_train_002181 | 7,341 | permissive | [
{
"docstring": "Constructor. Args: ckpt_filename: Str. Checkpoint filename.",
"name": "__init__",
"signature": "def __init__(self, ckpt_filename)"
},
{
"docstring": "Restore the model from a checkpoint. Args: ckpt_filename: Str. Checkpoint filename. Returns: Nothing.",
"name": "restore",
... | 3 | stack_v2_sparse_classes_30k_train_043525 | Implement the Python class `DS2Scorer` described below.
Class description:
Speech scorer based on DeepSpeech2.
Method signatures and docstrings:
- def __init__(self, ckpt_filename): Constructor. Args: ckpt_filename: Str. Checkpoint filename.
- def restore(self, ckpt_filename=None): Restore the model from a checkpoint... | Implement the Python class `DS2Scorer` described below.
Class description:
Speech scorer based on DeepSpeech2.
Method signatures and docstrings:
- def __init__(self, ckpt_filename): Constructor. Args: ckpt_filename: Str. Checkpoint filename.
- def restore(self, ckpt_filename=None): Restore the model from a checkpoint... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
<|body_0|>
def restore(self, ckpt_filename=None):
"""Restore the model from a checkpoint. Args: ckpt_filename... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
super(DS2Scorer, self).__init__()
self.infer = DS2Encoder()
self.ckpt_filename = ckpt_filename
self.is_restored... | the_stack_v2_python_sparse | ged_tts/fdsd/eval/tts_scorer.py | Jimmy-INL/google-research | train | 1 |
1b77fe056340d4361686e9ad1a45bf576492f71f | [
"self.c2s = {1: 'Thousand', 2: 'Million', 3: 'Billion'}\nself.n2s = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}\nself.t2s = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 1... | <|body_start_0|>
self.c2s = {1: 'Thousand', 2: 'Million', 3: 'Billion'}
self.n2s = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
self.t2s = {10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', ... | 总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
""... | stack_v2_sparse_classes_75kplus_train_002182 | 3,864 | permissive | [
{
"docstring": "初始化不同位数的数字英文单词映射关系",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "每隔3位,分区而治, 1,3位以内转换英文, 2,3位之间添加后缀 最后把结果合并即可",
"name": "numberToWords",
"signature": "def numberToWords(self, num: int) -> str"
},
{
"docstring": "3位以内的数字 -> 英文 转换... | 3 | stack_v2_sparse_classes_30k_train_029080 | Implement the Python class `Solution` described below.
Class description:
总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand
Method... | Implement the Python class `Solution` described below.
Class description:
总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand
Method... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""总体思路是,按英文数字表示习惯,每3位,变换一次表示后缀,Billion,Million,Thousand 3位以内,可以共用一个规则表示,用 lower 函数来单独处理 本题是Hard的主要原因是 英文数字表达的细节容易出错, 此外 1,000,000 - > one million, 程序容易输出 one million thousand 这就需要在每隔3位 添加 billion million 的时候,判断 高位部分时候如果为空, 则不添加多余的 thousand"""
def __init__(self) -> None:
"""初始化不同位数的数字英文... | the_stack_v2_python_sparse | src/273.integer-to-english-words.py | wisesky/LeetCode-Practice | train | 0 |
0bbfc8cf59f2a4b0273284db2abdac4d4615fb5e | [
"user_id = payload['user_id']\nrows = await get_blueprints(self.db, user_id=user_id)\nblueprints, errors = BlueprintSchema(many=True).dump(rows)\nif errors:\n json_response({'error': errors}, status=400)\nreturn json_response({'blueprints': blueprints})",
"user_id = payload['user_id']\ndata = await self.reques... | <|body_start_0|>
user_id = payload['user_id']
rows = await get_blueprints(self.db, user_id=user_id)
blueprints, errors = BlueprintSchema(many=True).dump(rows)
if errors:
json_response({'error': errors}, status=400)
return json_response({'blueprints': blueprints})
<|en... | Views to handle blueprints. | Blueprint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blueprint:
"""Views to handle blueprints."""
async def get(self, payload):
"""Get blueprints."""
<|body_0|>
async def delete(self, payload):
"""Delete a blueprint."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user_id = payload['user_id']
... | stack_v2_sparse_classes_75kplus_train_002183 | 5,954 | permissive | [
{
"docstring": "Get blueprints.",
"name": "get",
"signature": "async def get(self, payload)"
},
{
"docstring": "Delete a blueprint.",
"name": "delete",
"signature": "async def delete(self, payload)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024055 | Implement the Python class `Blueprint` described below.
Class description:
Views to handle blueprints.
Method signatures and docstrings:
- async def get(self, payload): Get blueprints.
- async def delete(self, payload): Delete a blueprint. | Implement the Python class `Blueprint` described below.
Class description:
Views to handle blueprints.
Method signatures and docstrings:
- async def get(self, payload): Get blueprints.
- async def delete(self, payload): Delete a blueprint.
<|skeleton|>
class Blueprint:
"""Views to handle blueprints."""
asyn... | e94889ce784f4399ca74f78be3bc42a5cd880d70 | <|skeleton|>
class Blueprint:
"""Views to handle blueprints."""
async def get(self, payload):
"""Get blueprints."""
<|body_0|>
async def delete(self, payload):
"""Delete a blueprint."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Blueprint:
"""Views to handle blueprints."""
async def get(self, payload):
"""Get blueprints."""
user_id = payload['user_id']
rows = await get_blueprints(self.db, user_id=user_id)
blueprints, errors = BlueprintSchema(many=True).dump(rows)
if errors:
jso... | the_stack_v2_python_sparse | blueprints/views.py | cassinyio/cassiny-spawner | train | 1 |
fe35a416008fe22430b51b9de591ddb2c81fa175 | [
"self._each_result_cont = each_result_cont\nself._num_expected_results = num_expected_results\nself._num_continuations_issued = 0\nself._all_results_cont = all_results_cont\nself._results_received = 0",
"assert self._num_continuations_issued < self._num_expected_results\nself._num_continuations_issued += 1\nthis_... | <|body_start_0|>
self._each_result_cont = each_result_cont
self._num_expected_results = num_expected_results
self._num_continuations_issued = 0
self._all_results_cont = all_results_cont
self._results_received = 0
<|end_body_0|>
<|body_start_1|>
assert self._num_continuat... | A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as well as another when all have arrived. Note nothing is done to combine together the results... | WhenAllResultsReceived | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhenAllResultsReceived:
"""A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as well as another when all have arrived. No... | stack_v2_sparse_classes_75kplus_train_002184 | 12,637 | permissive | [
{
"docstring": "Creates a ResultsCombiner that will invoke <all_results_cont> (with no arguments) when it has received <num_expected_results> (via the `continuation_for_result` method). <each_result_cont> is a continuation which is invoked with each individual result.",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_029611 | Implement the Python class `WhenAllResultsReceived` described below.
Class description:
A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as we... | Implement the Python class `WhenAllResultsReceived` described below.
Class description:
A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as we... | 8fa75e67c0db8f632b135379740051cd10ff31f2 | <|skeleton|>
class WhenAllResultsReceived:
"""A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as well as another when all have arrived. No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhenAllResultsReceived:
"""A simple utility class for scheduling an continuation to be executed when several calls have all completed (regardless of the order in which they complete). Allows an action to be executed when each individual result arrives, as well as another when all have arrived. Note nothing is... | the_stack_v2_python_sparse | rlo/src/rlo/worker.py | tomjaguarpaw/knossos-ksc | train | 0 |
eba04aba123364ef30b3ad1131b4dcb1afb60735 | [
"self._capacity = capacity\nself._size = 0\nself._insert_index = 0\n\ndef init_array(signature):\n shape = (self._capacity,) + signature.shape\n return np.zeros(shape, dtype=signature.dtype)\nself._data_buffer = data.nested_map(init_array, datapoint_signature)",
"n_elems = data.choose_leaf(data.nested_map(l... | <|body_start_0|>
self._capacity = capacity
self._size = 0
self._insert_index = 0
def init_array(signature):
shape = (self._capacity,) + signature.shape
return np.zeros(shape, dtype=signature.dtype)
self._data_buffer = data.nested_map(init_array, datapoint... | Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones. | UniformReplayBuffer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniformReplayBuffer:
"""Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones."""
def __init__(self, datapoint_signature, capacity):
"""Initializes the replay buffer. Args: datapoint_signature (pytree): Pyt... | stack_v2_sparse_classes_75kplus_train_002185 | 5,699 | permissive | [
{
"docstring": "Initializes the replay buffer. Args: datapoint_signature (pytree): Pytree of TensorSignatures, defining the structure of data to be stored. capacity (int): Maximum size of the buffer.",
"name": "__init__",
"signature": "def __init__(self, datapoint_signature, capacity)"
},
{
"doc... | 3 | null | Implement the Python class `UniformReplayBuffer` described below.
Class description:
Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones.
Method signatures and docstrings:
- def __init__(self, datapoint_signature, capacity): Initializes t... | Implement the Python class `UniformReplayBuffer` described below.
Class description:
Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones.
Method signatures and docstrings:
- def __init__(self, datapoint_signature, capacity): Initializes t... | 2d9f19a40c7fb1c637dd3bd230942c01f14927e1 | <|skeleton|>
class UniformReplayBuffer:
"""Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones."""
def __init__(self, datapoint_signature, capacity):
"""Initializes the replay buffer. Args: datapoint_signature (pytree): Pyt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniformReplayBuffer:
"""Replay buffer with uniform sampling. Stores datapoints in a queue of fixed size. Adding to a full buffer overwrites the oldest ones."""
def __init__(self, datapoint_signature, capacity):
"""Initializes the replay buffer. Args: datapoint_signature (pytree): Pytree of Tensor... | the_stack_v2_python_sparse | alpacka/trainers/replay_buffers.py | shoot-tree-search/sts | train | 2 |
bf37fb402b0884c911d6e576f1b6b0c1abfc35db | [
"found_item = plotter.plots.meshes.get(item_key_name, None)\nif found_item is None:\n plotter.plots.meshes[item_key_name] = render_item\n plotter.ui.plt += render_item\n found_item = render_item\n if not defer_render:\n plotter.ui.plt.render()\nreturn found_item",
"found_item = plotter.plots.me... | <|body_start_0|>
found_item = plotter.plots.meshes.get(item_key_name, None)
if found_item is None:
plotter.plots.meshes[item_key_name] = render_item
plotter.ui.plt += render_item
found_item = render_item
if not defer_render:
plotter.ui.plt.... | docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers | VedoPlotterHelpers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VedoPlotterHelpers:
"""docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers"""
def vedo_create_if_needed(cls, plotter, item_key_name, render_item, defer_render=False):
"""Creates a new mesh if it exists in spike_... | stack_v2_sparse_classes_75kplus_train_002186 | 3,367 | permissive | [
{
"docstring": "Creates a new mesh if it exists in spike_raster_plt_3d_vedo plotter: Spike3DRaster_Vedo the main 3d plotter. item_key_name: str - like 'new_active_axes' render_item: a valid vedo object that can be added to the plotter, like a Mesh or Text3D defer_render: bool - whether to immediately render aft... | 2 | stack_v2_sparse_classes_30k_train_000153 | Implement the Python class `VedoPlotterHelpers` described below.
Class description:
docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers
Method signatures and docstrings:
- def vedo_create_if_needed(cls, plotter, item_key_name, render_item, defer... | Implement the Python class `VedoPlotterHelpers` described below.
Class description:
docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers
Method signatures and docstrings:
- def vedo_create_if_needed(cls, plotter, item_key_name, render_item, defer... | 212399d826284b394fce8894ff1a93133aef783f | <|skeleton|>
class VedoPlotterHelpers:
"""docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers"""
def vedo_create_if_needed(cls, plotter, item_key_name, render_item, defer_render=False):
"""Creates a new mesh if it exists in spike_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VedoPlotterHelpers:
"""docstring for VedoHelpers. Import with: from pyphoplacecellanalysis.GUI.Vedo.VedoMeshManipulatable import VedoPlotterHelpers"""
def vedo_create_if_needed(cls, plotter, item_key_name, render_item, defer_render=False):
"""Creates a new mesh if it exists in spike_raster_plt_3d... | the_stack_v2_python_sparse | src/pyphoplacecellanalysis/GUI/Vedo/VedoMeshManipulatable.py | CommanderPho/pyPhoPlaceCellAnalysis | train | 1 |
ae3c32b93921c5df08d556c4b36f8d4678ca8993 | [
"self.matrix = dict()\nself.max_num = maxChoosableInteger\nif (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:\n return False\nif maxChoosableInteger >= desiredTotal:\n return True\nalways_win = False\nfor i in range(1, maxChoosableInteger + 1):\n result = self.dfs(1 << i, desiredTotal ... | <|body_start_0|>
self.matrix = dict()
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:
return False
if maxChoosableInteger >= desiredTotal:
return True
always_win = False
for i in range(1, m... | SolutionError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, choose, target):
""":type choose: int :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_002187 | 4,497 | no_license | [
{
"docstring": ":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool",
"name": "canIWin",
"signature": "def canIWin(self, maxChoosableInteger, desiredTotal)"
},
{
"docstring": ":type choose: int :type target: int :rtype: int",
"name": "dfs",
"signature": "def dfs(self, cho... | 2 | stack_v2_sparse_classes_30k_train_014186 | Implement the Python class `SolutionError` described below.
Class description:
Implement the SolutionError class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, choose, target): :type choose:... | Implement the Python class `SolutionError` described below.
Class description:
Implement the SolutionError class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, choose, target): :type choose:... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, choose, target):
""":type choose: int :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
self.matrix = dict()
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:
... | the_stack_v2_python_sparse | 464.py | Gackle/leetcode_practice | train | 0 | |
cf754d1216bea6b69655063f4aac0330ba5d10a2 | [
"for member in [self.team2_admin, self.team2_member, self.common_member]:\n self.client.force_login(member)\n response = self.client.get(self.list_url)\n self.assertContains(response, 'Ratings for Category %s' % self.team2_category3.name, status_code=200)\n for rating in self.team2_category3.ratings.all... | <|body_start_0|>
for member in [self.team2_admin, self.team2_member, self.common_member]:
self.client.force_login(member)
response = self.client.get(self.list_url)
self.assertContains(response, 'Ratings for Category %s' % self.team2_category3.name, status_code=200)
... | Test RatingListView | RatingListViewTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatingListViewTest:
"""Test RatingListView"""
def test_rating_list_member(self):
"""Assert that all the right ratings are listed for the team admin and regular members"""
<|body_0|>
def test_rating_list_nonmember(self):
"""Assert that non-members can not list rat... | stack_v2_sparse_classes_75kplus_train_002188 | 3,396 | permissive | [
{
"docstring": "Assert that all the right ratings are listed for the team admin and regular members",
"name": "test_rating_list_member",
"signature": "def test_rating_list_member(self)"
},
{
"docstring": "Assert that non-members can not list ratings",
"name": "test_rating_list_nonmember",
... | 2 | stack_v2_sparse_classes_30k_train_048858 | Implement the Python class `RatingListViewTest` described below.
Class description:
Test RatingListView
Method signatures and docstrings:
- def test_rating_list_member(self): Assert that all the right ratings are listed for the team admin and regular members
- def test_rating_list_nonmember(self): Assert that non-mem... | Implement the Python class `RatingListViewTest` described below.
Class description:
Test RatingListView
Method signatures and docstrings:
- def test_rating_list_member(self): Assert that all the right ratings are listed for the team admin and regular members
- def test_rating_list_nonmember(self): Assert that non-mem... | b3a61462d46d33de25fb96c029b2bd822001b669 | <|skeleton|>
class RatingListViewTest:
"""Test RatingListView"""
def test_rating_list_member(self):
"""Assert that all the right ratings are listed for the team admin and regular members"""
<|body_0|>
def test_rating_list_nonmember(self):
"""Assert that non-members can not list rat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RatingListViewTest:
"""Test RatingListView"""
def test_rating_list_member(self):
"""Assert that all the right ratings are listed for the team admin and regular members"""
for member in [self.team2_admin, self.team2_member, self.common_member]:
self.client.force_login(member)
... | the_stack_v2_python_sparse | src/rating/tests.py | tykling/socialrating | train | 3 |
d4ae88850d5dbd871d0ca92f0b1e9d9d07469f1b | [
"super(SQLiteParser, self).__init__(pre_obj, config)\nself._local_zone = False\nself.db = None\nparser_filter_string = getattr(self._config, 'parsers', None)\nself._plugins = plugin.GetRegisteredPlugins(interface.SQLitePlugin, self._pre_obj, parser_filter_string)",
"with interface.SQLiteDatabase(file_entry) as da... | <|body_start_0|>
super(SQLiteParser, self).__init__(pre_obj, config)
self._local_zone = False
self.db = None
parser_filter_string = getattr(self._config, 'parsers', None)
self._plugins = plugin.GetRegisteredPlugins(interface.SQLitePlugin, self._pre_obj, parser_filter_string)
<|en... | A SQLite parser for Plaso. | SQLiteParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
<|body_0|>
def Parse(self, file_entry):
"""Parses an SQLite database. Args: file_ent... | stack_v2_sparse_classes_75kplus_train_002189 | 2,847 | permissive | [
{
"docstring": "Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.",
"name": "__init__",
"signature": "def __init__(self, pre_obj, config)"
},
{
"docstring": "Parses an SQLite database. Args: file_entry: the file entry object. Returns: A event object generat... | 2 | stack_v2_sparse_classes_30k_train_013480 | Implement the Python class `SQLiteParser` described below.
Class description:
A SQLite parser for Plaso.
Method signatures and docstrings:
- def __init__(self, pre_obj, config): Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.
- def Parse(self, file_entry): Parses an SQLite dat... | Implement the Python class `SQLiteParser` described below.
Class description:
A SQLite parser for Plaso.
Method signatures and docstrings:
- def __init__(self, pre_obj, config): Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.
- def Parse(self, file_entry): Parses an SQLite dat... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
<|body_0|>
def Parse(self, file_entry):
"""Parses an SQLite database. Args: file_ent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
super(SQLiteParser, self).__init__(pre_obj, config)
self._local_zone = False
self.db = None
... | the_stack_v2_python_sparse | plaso/parsers/sqlite.py | iwm911/plaso | train | 0 |
4f3166837612a99ec6db4e251c7efd05ad466f5f | [
"self.a_ray = 0.0 * 100.0\nself.a_mie = 20.0 * 100.0\nself.b_mie = 1.286\nself.g = 0.0",
"norm_wavelength = wavelength / (500 * 10 ** (-9))\nus_ray = self.a_ray * norm_wavelength ** (-4)\nus_mie = self.a_mie * norm_wavelength ** (-self.b_mie)\nus_prime = us_ray + us_mie\nus = us_prime / (1 - self.g)\nreturn (us, ... | <|body_start_0|>
self.a_ray = 0.0 * 100.0
self.a_mie = 20.0 * 100.0
self.b_mie = 1.286
self.g = 0.0
<|end_body_0|>
<|body_start_1|>
norm_wavelength = wavelength / (500 * 10 ** (-9))
us_ray = self.a_ray * norm_wavelength ** (-4)
us_mie = self.a_mie * norm_waveleng... | UsgJacques | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsgJacques:
def __init__(self):
"""To be set externally: a':"""
<|body_0|>
def __call__(self, wavelength):
"""Calculate the scattering parameters relevant for monte carlo simulation. Uses equation (2) from: Optical properties of biological tissues: a Review Args ____... | stack_v2_sparse_classes_75kplus_train_002190 | 6,713 | permissive | [
{
"docstring": "To be set externally: a':",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculate the scattering parameters relevant for monte carlo simulation. Uses equation (2) from: Optical properties of biological tissues: a Review Args ____ wavelength: wavelengt... | 2 | null | Implement the Python class `UsgJacques` described below.
Class description:
Implement the UsgJacques class.
Method signatures and docstrings:
- def __init__(self): To be set externally: a':
- def __call__(self, wavelength): Calculate the scattering parameters relevant for monte carlo simulation. Uses equation (2) fro... | Implement the Python class `UsgJacques` described below.
Class description:
Implement the UsgJacques class.
Method signatures and docstrings:
- def __init__(self): To be set externally: a':
- def __call__(self, wavelength): Calculate the scattering parameters relevant for monte carlo simulation. Uses equation (2) fro... | 52252d60e42702e292d188e30f6717fe50c23962 | <|skeleton|>
class UsgJacques:
def __init__(self):
"""To be set externally: a':"""
<|body_0|>
def __call__(self, wavelength):
"""Calculate the scattering parameters relevant for monte carlo simulation. Uses equation (2) from: Optical properties of biological tissues: a Review Args ____... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsgJacques:
def __init__(self):
"""To be set externally: a':"""
self.a_ray = 0.0 * 100.0
self.a_mie = 20.0 * 100.0
self.b_mie = 1.286
self.g = 0.0
def __call__(self, wavelength):
"""Calculate the scattering parameters relevant for monte carlo simulation. Us... | the_stack_v2_python_sparse | Modules/Biophotonics/python/iMC/mc/usuag.py | SVRTK/MITK | train | 0 | |
20c5c7ad8c2751f270e41a4a5765798beaeca94d | [
"logging.Handler.__init__(self, level)\nformatter = logging.Formatter(_guiLogFormat, _guiDateFormat)\nself.setFormatter(formatter)\nself.__callbackHandler = utils.CallbackEventHandler()\nself.__logWidget = logWidget\nself.__logMessageQueue = Queue.Queue()",
"message = self.format(record)\nif self.level <= record.... | <|body_start_0|>
logging.Handler.__init__(self, level)
formatter = logging.Formatter(_guiLogFormat, _guiDateFormat)
self.setFormatter(formatter)
self.__callbackHandler = utils.CallbackEventHandler()
self.__logWidget = logWidget
self.__logMessageQueue = Queue.Queue()
<|end... | Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}. | GuiLoggerHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuiLoggerHandler:
"""Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}."""
def __init__(self, logWidget, level=loggin... | stack_v2_sparse_classes_75kplus_train_002191 | 3,878 | no_license | [
{
"docstring": "Constuctor. @param logWidget: A qt widget with an C{append} interface. @type logWidget: L{QWidget<qt.QWidget>} @param level: Level constant. @see: L{logging<logging>} module.",
"name": "__init__",
"signature": "def __init__(self, logWidget, level=logging.INFO)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_012080 | Implement the Python class `GuiLoggerHandler` described below.
Class description:
Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}.
Method sig... | Implement the Python class `GuiLoggerHandler` described below.
Class description:
Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}.
Method sig... | 958fda4f3064f9f6b2034da396a20ac9d9abd52f | <|skeleton|>
class GuiLoggerHandler:
"""Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}."""
def __init__(self, logWidget, level=loggin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GuiLoggerHandler:
"""Handler class used to display logging messages in a widget. The logging widget used for output has only to implement the method C{append} that takes a C{unicode} as input, the method C{scrollToBottom} and the method C{clear}."""
def __init__(self, logWidget, level=logging.INFO):
... | the_stack_v2_python_sparse | src/datafinder/gui/admin/common/logger_handler.py | DLR-SC/DataFinder | train | 9 |
9ee264bb2e7ebc00a76231cf671a7d1ac5df8c3f | [
"label = \"Heroes' Day\"\nif year == 2017:\n day = date(year, 2, 27)\nelse:\n day = date(year, 3, 1)\nreturn (day, label)",
"label = 'Founding of Asunción'\nif year == 2017:\n day = date(year, 8, 14)\nelse:\n day = date(year, 8, 15)\nreturn (day, label)",
"label = 'Boqueron Battle Victory Day'\nif y... | <|body_start_0|>
label = "Heroes' Day"
if year == 2017:
day = date(year, 2, 27)
else:
day = date(year, 3, 1)
return (day, label)
<|end_body_0|>
<|body_start_1|>
label = 'Founding of Asunción'
if year == 2017:
day = date(year, 8, 14)
... | Paraguay | Paraguay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
<|body_0|>
def get_founding_of_... | stack_v2_sparse_classes_75kplus_train_002192 | 2,194 | permissive | [
{
"docstring": "Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay",
"name": "get_heroes_day",
"signature": "def get_heroes_day(self, year)"
},
{
"docstring": "Return the... | 4 | stack_v2_sparse_classes_30k_train_030848 | Implement the Python class `Paraguay` described below.
Class description:
Paraguay
Method signatures and docstrings:
- def get_heroes_day(self, year): Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in... | Implement the Python class `Paraguay` described below.
Class description:
Paraguay
Method signatures and docstrings:
- def get_heroes_day(self, year): Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in... | 0a3b05706fcd0b8a2c4c761694b91b5fc12d1383 | <|skeleton|>
class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
<|body_0|>
def get_founding_of_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Paraguay:
"""Paraguay"""
def get_heroes_day(self, year):
"""Heroes Day is a fixed holidays. In 2017, it has been moved to February 27th ; otherwise, it happens on March 1st. ref: https://en.wikipedia.org/wiki/Public_holidays_in_Paraguay"""
label = "Heroes' Day"
if year == 2017:
... | the_stack_v2_python_sparse | calendra/america/paraguay.py | jaraco/calendra | train | 5 |
2138d129db05084930d43da3afb94205740b7b2f | [
"user_form = self.form_class(request.POST)\nregistered = False\nif user_form.is_valid():\n user = user_form.save(commit=False)\n user.set_password(user_form.cleaned_data['password'])\n user.save()\n appuser = AppUser()\n appuser.user = user\n appuser.save()\n registered = True\nelse:\n self.... | <|body_start_0|>
user_form = self.form_class(request.POST)
registered = False
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user_form.cleaned_data['password'])
user.save()
appuser = AppUser()
appuser.use... | Class RegisterView is used to render register html page and add new app's users | RegisterView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterView:
"""Class RegisterView is used to render register html page and add new app's users"""
def post(self, request):
"""POST method gets registration form and checks for its validity. If it's valid, it creates Django User class instance, sets its password, creates companion o... | stack_v2_sparse_classes_75kplus_train_002193 | 4,595 | no_license | [
{
"docstring": "POST method gets registration form and checks for its validity. If it's valid, it creates Django User class instance, sets its password, creates companion object AppUser and saves them in database :param request: POST request :return: register.html page with appropriate message and form",
"n... | 2 | null | Implement the Python class `RegisterView` described below.
Class description:
Class RegisterView is used to render register html page and add new app's users
Method signatures and docstrings:
- def post(self, request): POST method gets registration form and checks for its validity. If it's valid, it creates Django Us... | Implement the Python class `RegisterView` described below.
Class description:
Class RegisterView is used to render register html page and add new app's users
Method signatures and docstrings:
- def post(self, request): POST method gets registration form and checks for its validity. If it's valid, it creates Django Us... | ebef90f2f1e5964a17e349fa96ea4e0b63276dde | <|skeleton|>
class RegisterView:
"""Class RegisterView is used to render register html page and add new app's users"""
def post(self, request):
"""POST method gets registration form and checks for its validity. If it's valid, it creates Django User class instance, sets its password, creates companion o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterView:
"""Class RegisterView is used to render register html page and add new app's users"""
def post(self, request):
"""POST method gets registration form and checks for its validity. If it's valid, it creates Django User class instance, sets its password, creates companion object AppUser... | the_stack_v2_python_sparse | apps/users/views.py | gorbart/scripting_languages_project | train | 0 |
43aadfcb992af6da2411316a5593008d31ce20a8 | [
"c_a = []\nfor i in range(0, len(nums) - 1):\n gt = -1\n if nums[i] == max(nums):\n c_a.append(gt)\n else:\n if i == len(nums) - 1:\n current_index = 0\n else:\n current_index = i + 1\n while current_index != i:\n print(nums)\n if curr... | <|body_start_0|>
c_a = []
for i in range(0, len(nums) - 1):
gt = -1
if nums[i] == max(nums):
c_a.append(gt)
else:
if i == len(nums) - 1:
current_index = 0
else:
current_index = i +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElements_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
c_a = []
... | stack_v2_sparse_classes_75kplus_train_002194 | 1,648 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements_1",
"signature": "def nextGreaterElements_1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements",
"signature": "def nextGreaterElements(self, nums)"
... | 2 | stack_v2_sparse_classes_30k_train_049915 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements_1(self, nums): :type nums: List[int] :rtype: List[int]
- def nextGreaterElements(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements_1(self, nums): :type nums: List[int] :rtype: List[int]
- def nextGreaterElements(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class ... | 1a44518bc1be558b74ce4a94a07021fa382e1715 | <|skeleton|>
class Solution:
def nextGreaterElements_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextGreaterElements_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
c_a = []
for i in range(0, len(nums) - 1):
gt = -1
if nums[i] == max(nums):
c_a.append(gt)
else:
if i == len(nums) - 1:
... | the_stack_v2_python_sparse | LeetCode Questions/Stacks/503. Next Greater Element II/solution.py | rpereira91/interview-questions | train | 0 | |
dc9242ee420a6691b8c50ddae8286278cdeb2eab | [
"if file_format[0] != '.':\n file_format = '.' + file_format\nurl = 'http://www.uniprot.org/uniprot/'\nreq = ''.join([url, accession, file_format])\ntry:\n data = urlopen(req)\n return data.read().decode()\nexcept HTTPError:\n print('Entry :', accession, 'not found.')\n return None",
"result = cls.... | <|body_start_0|>
if file_format[0] != '.':
file_format = '.' + file_format
url = 'http://www.uniprot.org/uniprot/'
req = ''.join([url, accession, file_format])
try:
data = urlopen(req)
return data.read().decode()
except HTTPError:
p... | Tools for querying the UniProt database. | UniProtTools | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniProtTools:
"""Tools for querying the UniProt database."""
def get_uniprot(cls, accession, file_format='.fasta'):
"""Retrieve UniProt data for a given accession."""
<|body_0|>
def get_gene_id(cls, accession):
"""Retrieve the gene id for a given accession."""
... | stack_v2_sparse_classes_75kplus_train_002195 | 9,507 | permissive | [
{
"docstring": "Retrieve UniProt data for a given accession.",
"name": "get_uniprot",
"signature": "def get_uniprot(cls, accession, file_format='.fasta')"
},
{
"docstring": "Retrieve the gene id for a given accession.",
"name": "get_gene_id",
"signature": "def get_gene_id(cls, accession)... | 3 | stack_v2_sparse_classes_30k_train_005709 | Implement the Python class `UniProtTools` described below.
Class description:
Tools for querying the UniProt database.
Method signatures and docstrings:
- def get_uniprot(cls, accession, file_format='.fasta'): Retrieve UniProt data for a given accession.
- def get_gene_id(cls, accession): Retrieve the gene id for a g... | Implement the Python class `UniProtTools` described below.
Class description:
Tools for querying the UniProt database.
Method signatures and docstrings:
- def get_uniprot(cls, accession, file_format='.fasta'): Retrieve UniProt data for a given accession.
- def get_gene_id(cls, accession): Retrieve the gene id for a g... | bedb36eafe681401c11d562f8d7117aad3d758d7 | <|skeleton|>
class UniProtTools:
"""Tools for querying the UniProt database."""
def get_uniprot(cls, accession, file_format='.fasta'):
"""Retrieve UniProt data for a given accession."""
<|body_0|>
def get_gene_id(cls, accession):
"""Retrieve the gene id for a given accession."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniProtTools:
"""Tools for querying the UniProt database."""
def get_uniprot(cls, accession, file_format='.fasta'):
"""Retrieve UniProt data for a given accession."""
if file_format[0] != '.':
file_format = '.' + file_format
url = 'http://www.uniprot.org/uniprot/'
... | the_stack_v2_python_sparse | omin/utils/network_tools.py | dmpio/omin | train | 0 |
8b44b3e1f7a451cf4076ccc875df59795ae48bc3 | [
"time = self.flowsheet().config.time\nt = self.flowsheet().config.time.first()\nself.lift_height = Var(time, initialize=400, domain=NonNegativeReals, units=pyunits.ft, doc='Lift height for pump [ft]')\nself.flow_in = pyunits.convert(self.flow_vol_in[t], to_units=pyunits.m ** 3 / pyunits.hr)\ntry:\n self.lift_hei... | <|body_start_0|>
time = self.flowsheet().config.time
t = self.flowsheet().config.time.first()
self.lift_height = Var(time, initialize=400, domain=NonNegativeReals, units=pyunits.ft, doc='Lift height for pump [ft]')
self.flow_in = pyunits.convert(self.flow_vol_in[t], to_units=pyunits.m **... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping dista... | stack_v2_sparse_classes_75kplus_train_002196 | 3,523 | permissive | [
{
"docstring": "Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping distance to deep well injection site :type pipe_distance: float... | 3 | stack_v2_sparse_classes_30k_train_005060 | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :para... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :para... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping dista... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping distance to deep we... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/deep_well_injection.py | JamariMurke/WaterTAP3 | train | 0 | |
358cbad9fc22d8f3993566b5d3d9102c2eab5e86 | [
"default_sep = seps[0]\nfor sep in seps[1:]:\n if sep:\n txt = txt.replace(sep, default_sep)\nraw_words = txt.split(default_sep)\nwords = set()\nfor word in raw_words:\n if word.replace('_', '').isalpha():\n words.add(word)\nreturn sorted(words)",
"completions = []\nfor word in self.split(code... | <|body_start_0|>
default_sep = seps[0]
for sep in seps[1:]:
if sep:
txt = txt.replace(sep, default_sep)
raw_words = txt.split(default_sep)
words = set()
for word in raw_words:
if word.replace('_', '').isalpha():
words.add(wo... | Provides completions based on the document words | DocumentWordsProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentWordsProvider:
"""Provides completions based on the document words"""
def split(txt, seps):
"""Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :retu... | stack_v2_sparse_classes_75kplus_train_002197 | 8,151 | permissive | [
{
"docstring": "Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :return: A **set** of words found in the document (excluding punctuations, numbers, ...)",
"name": "split",
"sig... | 2 | null | Implement the Python class `DocumentWordsProvider` described below.
Class description:
Provides completions based on the document words
Method signatures and docstrings:
- def split(txt, seps): Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: ... | Implement the Python class `DocumentWordsProvider` described below.
Class description:
Provides completions based on the document words
Method signatures and docstrings:
- def split(txt, seps): Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: ... | 0ffabebe4f0397d53429024f6f44db3fe97b0828 | <|skeleton|>
class DocumentWordsProvider:
"""Provides completions based on the document words"""
def split(txt, seps):
"""Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentWordsProvider:
"""Provides completions based on the document words"""
def split(txt, seps):
"""Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :return: A **set**... | the_stack_v2_python_sparse | pyqode/core/backend/workers.py | pyQode/pyqode.core | train | 24 |
088473175cd1a1125c0ddae1fa5c215a80b2198f | [
"obj = object.__new__(cls)\nobj.custom_status = custom_status\nobj.original_status = original_status\nreturn obj",
"try:\n return RoutingSlipCustomStatus[key]\nexcept KeyError:\n return None"
] | <|body_start_0|>
obj = object.__new__(cls)
obj.custom_status = custom_status
obj.original_status = original_status
return obj
<|end_body_0|>
<|body_start_1|>
try:
return RoutingSlipCustomStatus[key]
except KeyError:
return None
<|end_body_1|>
| Routing slip custom statuses. | RoutingSlipCustomStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoutingSlipCustomStatus:
"""Routing slip custom statuses."""
def __new__(cls, custom_status, original_status):
"""Attributes for the enum."""
<|body_0|>
def from_key(cls, key):
"""Return instance from key of the enum."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_002198 | 6,852 | permissive | [
{
"docstring": "Attributes for the enum.",
"name": "__new__",
"signature": "def __new__(cls, custom_status, original_status)"
},
{
"docstring": "Return instance from key of the enum.",
"name": "from_key",
"signature": "def from_key(cls, key)"
}
] | 2 | null | Implement the Python class `RoutingSlipCustomStatus` described below.
Class description:
Routing slip custom statuses.
Method signatures and docstrings:
- def __new__(cls, custom_status, original_status): Attributes for the enum.
- def from_key(cls, key): Return instance from key of the enum. | Implement the Python class `RoutingSlipCustomStatus` described below.
Class description:
Routing slip custom statuses.
Method signatures and docstrings:
- def __new__(cls, custom_status, original_status): Attributes for the enum.
- def from_key(cls, key): Return instance from key of the enum.
<|skeleton|>
class Rout... | 0d71d37b0e08d11f6b6d9f59a4b202dfabc98fc1 | <|skeleton|>
class RoutingSlipCustomStatus:
"""Routing slip custom statuses."""
def __new__(cls, custom_status, original_status):
"""Attributes for the enum."""
<|body_0|>
def from_key(cls, key):
"""Return instance from key of the enum."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoutingSlipCustomStatus:
"""Routing slip custom statuses."""
def __new__(cls, custom_status, original_status):
"""Attributes for the enum."""
obj = object.__new__(cls)
obj.custom_status = custom_status
obj.original_status = original_status
return obj
def from_... | the_stack_v2_python_sparse | pay-api/src/pay_api/utils/enums.py | bcgov/sbc-pay | train | 6 |
28243be8f2d9fbe71fc8494db51bc3d143920a58 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\ntimestamp = int(timestamp)\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = IOSTwitterContactEventData()\nevent_data.creation_time = self._GetDateTimeRowValue(... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
timestamp = int(timestamp)
return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event... | SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db | IOSTwitterPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
... | stack_v2_sparse_classes_75kplus_train_002199 | 12,718 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if not available.",
"name... | 3 | stack_v2_sparse_classes_30k_train_022374 | Implement the Python class `IOSTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db
Method signatures and docstrings... | Implement the Python class `IOSTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db
Method signatures and docstrings... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IOSTwitterPlugin:
"""SQLite parser plugin for Twitter on iOS 8+ database files. The Twitter on iOS 8+ database file is typically stored in: /private/var/mobile/Containers/Data/Application/Library/Caches/databases/ twitter.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retri... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/ios_twitter.py | log2timeline/plaso | train | 1,506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.