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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7aec99c67811b3049589f1b45b8d8ec77d8b8a31 | [
"if isinstance(event_item, list):\n event = {field: {'title': 'New values', 'data': [str(item) for item in event_item]}}\n self.create_event(get_current_user(), event)",
"if not isinstance(events, list):\n events = [events]\nchange_history = json.dumps(events)\ncontent_type = self.content_type\nLogEntry.... | <|body_start_0|>
if isinstance(event_item, list):
event = {field: {'title': 'New values', 'data': [str(item) for item in event_item]}}
self.create_event(get_current_user(), event)
<|end_body_0|>
<|body_start_1|>
if not isinstance(events, list):
events = [events]
... | Write and read model events using Django's LogEntry. | EventHandlingMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventHandlingMixin:
"""Write and read model events using Django's LogEntry."""
def create_related_event(self, field, event_item):
"""Create related event to model history."""
<|body_0|>
def create_event(self, user, events, action=ADDITION):
"""Create change or ev... | stack_v2_sparse_classes_75kplus_train_008100 | 13,966 | permissive | [
{
"docstring": "Create related event to model history.",
"name": "create_related_event",
"signature": "def create_related_event(self, field, event_item)"
},
{
"docstring": "Create change or event message related to model.",
"name": "create_event",
"signature": "def create_event(self, use... | 3 | null | Implement the Python class `EventHandlingMixin` described below.
Class description:
Write and read model events using Django's LogEntry.
Method signatures and docstrings:
- def create_related_event(self, field, event_item): Create related event to model history.
- def create_event(self, user, events, action=ADDITION)... | Implement the Python class `EventHandlingMixin` described below.
Class description:
Write and read model events using Django's LogEntry.
Method signatures and docstrings:
- def create_related_event(self, field, event_item): Create related event to model history.
- def create_event(self, user, events, action=ADDITION)... | 3d3f5a53efe32c721c34d7e48267328a4e9e8402 | <|skeleton|>
class EventHandlingMixin:
"""Write and read model events using Django's LogEntry."""
def create_related_event(self, field, event_item):
"""Create related event to model history."""
<|body_0|>
def create_event(self, user, events, action=ADDITION):
"""Create change or ev... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventHandlingMixin:
"""Write and read model events using Django's LogEntry."""
def create_related_event(self, field, event_item):
"""Create related event to model history."""
if isinstance(event_item, list):
event = {field: {'title': 'New values', 'data': [str(item) for item i... | the_stack_v2_python_sparse | draalcore/models/base_model.py | jojanper/draalcore | train | 1 |
8ef4e2c8a66b23fffd05394de4111ee6cfc2a2e3 | [
"if not self._device.supports_set_brightness():\n raise HomeAssistantError('This device does not support setting brightness')\nif brightness == 0:\n await self.async_set_power_belief(False)\n return\ntry:\n await self._hub.bond.action(self._device.device_id, Action.set_brightness_belief(round(brightness... | <|body_start_0|>
if not self._device.supports_set_brightness():
raise HomeAssistantError('This device does not support setting brightness')
if brightness == 0:
await self.async_set_power_belief(False)
return
try:
await self._hub.bond.action(self._d... | Representation of a Bond light. | BondBaseLight | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BondBaseLight:
"""Representation of a Bond light."""
async def async_set_brightness_belief(self, brightness: int) -> None:
"""Set the belief state of the light."""
<|body_0|>
async def async_set_power_belief(self, power_state: bool) -> None:
"""Set the belief sta... | stack_v2_sparse_classes_75kplus_train_008101 | 12,277 | permissive | [
{
"docstring": "Set the belief state of the light.",
"name": "async_set_brightness_belief",
"signature": "async def async_set_brightness_belief(self, brightness: int) -> None"
},
{
"docstring": "Set the belief state of the light.",
"name": "async_set_power_belief",
"signature": "async de... | 2 | stack_v2_sparse_classes_30k_train_041664 | Implement the Python class `BondBaseLight` described below.
Class description:
Representation of a Bond light.
Method signatures and docstrings:
- async def async_set_brightness_belief(self, brightness: int) -> None: Set the belief state of the light.
- async def async_set_power_belief(self, power_state: bool) -> Non... | Implement the Python class `BondBaseLight` described below.
Class description:
Representation of a Bond light.
Method signatures and docstrings:
- async def async_set_brightness_belief(self, brightness: int) -> None: Set the belief state of the light.
- async def async_set_power_belief(self, power_state: bool) -> Non... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BondBaseLight:
"""Representation of a Bond light."""
async def async_set_brightness_belief(self, brightness: int) -> None:
"""Set the belief state of the light."""
<|body_0|>
async def async_set_power_belief(self, power_state: bool) -> None:
"""Set the belief sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BondBaseLight:
"""Representation of a Bond light."""
async def async_set_brightness_belief(self, brightness: int) -> None:
"""Set the belief state of the light."""
if not self._device.supports_set_brightness():
raise HomeAssistantError('This device does not support setting bri... | the_stack_v2_python_sparse | homeassistant/components/bond/light.py | home-assistant/core | train | 35,501 |
97716d2035f0d8eb31ff1b3778a65d43b00e3349 | [
"self.a = 0.0\nself.b = 0.0\nself.c = 0.0\nself.d = 0.0",
"_normal_to_plane = OpenMaya.MVector(normal_to_plane)\n_normal_to_plane.normalize()\nself.a = _normal_to_plane.x\nself.b = _normal_to_plane.y\nself.c = _normal_to_plane.z\nself.d = -(self.a * point_on_plane.x + self.b * point_on_plane.y + self.c * point_on... | <|body_start_0|>
self.a = 0.0
self.b = 0.0
self.c = 0.0
self.d = 0.0
<|end_body_0|>
<|body_start_1|>
_normal_to_plane = OpenMaya.MVector(normal_to_plane)
_normal_to_plane.normalize()
self.a = _normal_to_plane.x
self.b = _normal_to_plane.y
self.c =... | This utility class represents a mathematical plane and performs intersection tests with a line. | PlaneMath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaneMath:
"""This utility class represents a mathematical plane and performs intersection tests with a line."""
def __init__(self):
"""Initialze the member variables of the class."""
<|body_0|>
def set_plane(self, point_on_plane, normal_to_plane):
"""Define the ... | stack_v2_sparse_classes_75kplus_train_008102 | 25,695 | no_license | [
{
"docstring": "Initialze the member variables of the class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Define the plane by supplying a point on the plane and the plane's normal.",
"name": "set_plane",
"signature": "def set_plane(self, point_on_plane, norm... | 3 | stack_v2_sparse_classes_30k_train_023983 | Implement the Python class `PlaneMath` described below.
Class description:
This utility class represents a mathematical plane and performs intersection tests with a line.
Method signatures and docstrings:
- def __init__(self): Initialze the member variables of the class.
- def set_plane(self, point_on_plane, normal_t... | Implement the Python class `PlaneMath` described below.
Class description:
This utility class represents a mathematical plane and performs intersection tests with a line.
Method signatures and docstrings:
- def __init__(self): Initialze the member variables of the class.
- def set_plane(self, point_on_plane, normal_t... | 028b6d7ed6f7cf135798450ffe423f8fd0660256 | <|skeleton|>
class PlaneMath:
"""This utility class represents a mathematical plane and performs intersection tests with a line."""
def __init__(self):
"""Initialze the member variables of the class."""
<|body_0|>
def set_plane(self, point_on_plane, normal_to_plane):
"""Define the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlaneMath:
"""This utility class represents a mathematical plane and performs intersection tests with a line."""
def __init__(self):
"""Initialze the member variables of the class."""
self.a = 0.0
self.b = 0.0
self.c = 0.0
self.d = 0.0
def set_plane(self, poin... | the_stack_v2_python_sparse | devkit2020/squareScaleManipContext.py | crosslife/MayaPythonExamples | train | 0 |
a460047617835c7510cd9b1aed3c3d1fe68db5cc | [
"if _cfg.server_backend == 'cassandra':\n clear_graph()\nelse:\n Gremlin().gremlin_post('graph.truncateBackend();')\nInsertData(gremlin='gremlin_alg_05.txt').gremlin_graph()",
"body = {'depth': 5, 'limit': 2}\ncode, res = Algorithm().post_rings_detect(body, auth=auth)\nid = res['task_id']\nif id > 0:\n r... | <|body_start_0|>
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_05.txt').gremlin_graph()
<|end_body_0|>
<|body_start_1|>
body = {'depth': 5, 'limit': 2}
code, r... | 接口rings_detect:环路检测 | TestRingsDetect02 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRingsDetect02:
"""接口rings_detect:环路检测"""
def setup_class(self):
"""测试类开始"""
<|body_0|>
def test_rings_detect_01(self):
""":return:"""
<|body_1|>
def test_rings_detect_02(self):
""":return:"""
<|body_2|>
def test_rings_detect_... | stack_v2_sparse_classes_75kplus_train_008103 | 11,594 | no_license | [
{
"docstring": "测试类开始",
"name": "setup_class",
"signature": "def setup_class(self)"
},
{
"docstring": ":return:",
"name": "test_rings_detect_01",
"signature": "def test_rings_detect_01(self)"
},
{
"docstring": ":return:",
"name": "test_rings_detect_02",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_044443 | Implement the Python class `TestRingsDetect02` described below.
Class description:
接口rings_detect:环路检测
Method signatures and docstrings:
- def setup_class(self): 测试类开始
- def test_rings_detect_01(self): :return:
- def test_rings_detect_02(self): :return:
- def test_rings_detect_03(self): :return: | Implement the Python class `TestRingsDetect02` described below.
Class description:
接口rings_detect:环路检测
Method signatures and docstrings:
- def setup_class(self): 测试类开始
- def test_rings_detect_01(self): :return:
- def test_rings_detect_02(self): :return:
- def test_rings_detect_03(self): :return:
<|skeleton|>
class T... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class TestRingsDetect02:
"""接口rings_detect:环路检测"""
def setup_class(self):
"""测试类开始"""
<|body_0|>
def test_rings_detect_01(self):
""":return:"""
<|body_1|>
def test_rings_detect_02(self):
""":return:"""
<|body_2|>
def test_rings_detect_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRingsDetect02:
"""接口rings_detect:环路检测"""
def setup_class(self):
"""测试类开始"""
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_05.txt').gremlin_graph()
... | the_stack_v2_python_sparse | src/graph_function_test/server/algorithm_olap/test_ringsDetect.py | hugegraph/hugegraph-test | train | 1 |
80b7654cc0fb801091e38653b10c2342086ae260 | [
"self.doors = ['a', 'b', 'c']\nself.wins = 0\nself.total = 0",
"prize = random.choice(self.doors)\nempty = (set(self.doors) - {prize, chosen}).pop()\nself.total += 1\nif strategy(self.doors, chosen, empty) == prize:\n self.wins += 1\n return True\nreturn False",
"for i in xrange(n):\n self.play(strateg... | <|body_start_0|>
self.doors = ['a', 'b', 'c']
self.wins = 0
self.total = 0
<|end_body_0|>
<|body_start_1|>
prize = random.choice(self.doors)
empty = (set(self.doors) - {prize, chosen}).pop()
self.total += 1
if strategy(self.doors, chosen, empty) == prize:
... | Monty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
<|body_0|>
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by... | stack_v2_sparse_classes_75kplus_train_008104 | 1,547 | no_license | [
{
"docstring": "Initialize instance variables: doors: list of strings wins: integer total: integer",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by the argument chosen. R... | 3 | stack_v2_sparse_classes_30k_train_003953 | Implement the Python class `Monty` described below.
Class description:
Implement the Monty class.
Method signatures and docstrings:
- def __init__(self): Initialize instance variables: doors: list of strings wins: integer total: integer
- def play(self, strategy, chosen='a'): INPUT: function, string OUTPUT: Boolean P... | Implement the Python class `Monty` described below.
Class description:
Implement the Monty class.
Method signatures and docstrings:
- def __init__(self): Initialize instance variables: doors: list of strings wins: integer total: integer
- def play(self, strategy, chosen='a'): INPUT: function, string OUTPUT: Boolean P... | 560334017c5748aa29431fa918ed7a35e8f2699c | <|skeleton|>
class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
<|body_0|>
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the Monty Hall game once. The first choice is given by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Monty:
def __init__(self):
"""Initialize instance variables: doors: list of strings wins: integer total: integer"""
self.doors = ['a', 'b', 'c']
self.wins = 0
self.total = 0
def play(self, strategy, chosen='a'):
"""INPUT: function, string OUTPUT: Boolean Play the M... | the_stack_v2_python_sparse | power-bayesian/monty.py | knakamor/projects | train | 1 | |
feaf8ed5054566e5c92b79ae0869b43d41d8173c | [
"if isinstance(resource_attrs, AttributeInfo):\n resource_attrs = resource_attrs.attributes\nelif getattr(resource_attrs, 'RESOURCE_ATTRIBUTE_MAP', None) is not None:\n resource_attrs = resource_attrs.RESOURCE_ATTRIBUTE_MAP\nself.attributes = resource_attrs",
"for attr, attr_vals in self.attributes.items():... | <|body_start_0|>
if isinstance(resource_attrs, AttributeInfo):
resource_attrs = resource_attrs.attributes
elif getattr(resource_attrs, 'RESOURCE_ATTRIBUTE_MAP', None) is not None:
resource_attrs = resource_attrs.RESOURCE_ATTRIBUTE_MAP
self.attributes = resource_attrs
<|en... | Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes. | AttributeInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeInfo:
"""Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes."""
def __init__(self, resource_attrs):
"""Create a new... | stack_v2_sparse_classes_75kplus_train_008105 | 12,764 | permissive | [
{
"docstring": "Create a new instance that wraps the given resource attributes. :param resource_attrs: The resource's attributes that can be any of the following types: an instance of AttributeInfo, an API definition that contains a RESOURCE_ATTRIBUTE_MAP attribute or a dict of attributes for the resource.",
... | 5 | null | Implement the Python class `AttributeInfo` described below.
Class description:
Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes.
Method signatures and docst... | Implement the Python class `AttributeInfo` described below.
Class description:
Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes.
Method signatures and docst... | 4232815d2055c9043ddceb3e1bbadf534e1cd279 | <|skeleton|>
class AttributeInfo:
"""Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes."""
def __init__(self, resource_attrs):
"""Create a new... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributeInfo:
"""Provides operations on a resource's attribute map. AttributeInfo wraps an API resource's attribute dict and provides methods for filling defaults, validating, converting, etc. based on the underlying attributes."""
def __init__(self, resource_attrs):
"""Create a new instance tha... | the_stack_v2_python_sparse | neutron_lib/api/attributes.py | openstack/neutron-lib | train | 43 |
70716cd42162faaa4fb32feda47f1aea36b63610 | [
"schema = getattr(cls, '__schema__')\nif schema is None:\n raise Exception(f'{cls.__name__}: not serializable; missing schema')\nreturn schema",
"d = self.schema().dump(self) if camel_case else {humps.decamelize(k): v for k, v in self.schema().dump(self).items()}\nif drop_nulls:\n d = _drop_nulls(d)\ns = js... | <|body_start_0|>
schema = getattr(cls, '__schema__')
if schema is None:
raise Exception(f'{cls.__name__}: not serializable; missing schema')
return schema
<|end_body_0|>
<|body_start_1|>
d = self.schema().dump(self) if camel_case else {humps.decamelize(k): v for k, v in self... | Marks that a class is serializeable to JSON. | Serializable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
<|body_0|>
def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bool=False) -> str:
"""Con... | stack_v2_sparse_classes_75kplus_train_008106 | 2,677 | permissive | [
{
"docstring": "Gets the marshmallow serializer for the implementing class.",
"name": "schema",
"signature": "def schema(cls)"
},
{
"docstring": "Convert an implementing instance to JSON. Parameters ---------- camel_case : bool (default True) If True, the keys of the returned dict will be camel-... | 3 | stack_v2_sparse_classes_30k_train_031926 | Implement the Python class `Serializable` described below.
Class description:
Marks that a class is serializeable to JSON.
Method signatures and docstrings:
- def schema(cls): Gets the marshmallow serializer for the implementing class.
- def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bo... | Implement the Python class `Serializable` described below.
Class description:
Marks that a class is serializeable to JSON.
Method signatures and docstrings:
- def schema(cls): Gets the marshmallow serializer for the implementing class.
- def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bo... | dca436188e062fd07dfe589ee61e8bb97aa3ea98 | <|skeleton|>
class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
<|body_0|>
def to_json(self, camel_case: bool=True, pretty_print: bool=True, drop_nulls: bool=False) -> str:
"""Con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serializable:
"""Marks that a class is serializeable to JSON."""
def schema(cls):
"""Gets the marshmallow serializer for the implementing class."""
schema = getattr(cls, '__schema__')
if schema is None:
raise Exception(f'{cls.__name__}: not serializable; missing schema... | the_stack_v2_python_sparse | core/json.py | clohr/model-service | train | 1 |
acaf830c80d28d3f5028a205a87269b8fc0d69cd | [
"if flt.shape != msk.shape:\n raise Exception('model and data must have same shape')\nmsk[:] = flt[:]\nmsk[0] = 0.0",
"if flt.shape != msk.shape:\n raise Exception('model and data must have same shape')\nflt[:] = msk[:]\nflt[0] = 0.0"
] | <|body_start_0|>
if flt.shape != msk.shape:
raise Exception('model and data must have same shape')
msk[:] = flt[:]
msk[0] = 0.0
<|end_body_0|>
<|body_start_1|>
if flt.shape != msk.shape:
raise Exception('model and data must have same shape')
flt[:] = msk[... | Mask operator for not updating the zero lag coefficient | pef1dmask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pef1dmask:
"""Mask operator for not updating the zero lag coefficient"""
def forward(self, add, flt, msk):
"""Applies the mask to the filter"""
<|body_0|>
def adjoint(self, add, flt, msk):
"""Applies adjoint mask"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_008107 | 7,358 | no_license | [
{
"docstring": "Applies the mask to the filter",
"name": "forward",
"signature": "def forward(self, add, flt, msk)"
},
{
"docstring": "Applies adjoint mask",
"name": "adjoint",
"signature": "def adjoint(self, add, flt, msk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025412 | Implement the Python class `pef1dmask` described below.
Class description:
Mask operator for not updating the zero lag coefficient
Method signatures and docstrings:
- def forward(self, add, flt, msk): Applies the mask to the filter
- def adjoint(self, add, flt, msk): Applies adjoint mask | Implement the Python class `pef1dmask` described below.
Class description:
Mask operator for not updating the zero lag coefficient
Method signatures and docstrings:
- def forward(self, add, flt, msk): Applies the mask to the filter
- def adjoint(self, add, flt, msk): Applies adjoint mask
<|skeleton|>
class pef1dmask... | db8c81f6a98cd665a493b54099eae1d28ee092e7 | <|skeleton|>
class pef1dmask:
"""Mask operator for not updating the zero lag coefficient"""
def forward(self, add, flt, msk):
"""Applies the mask to the filter"""
<|body_0|>
def adjoint(self, add, flt, msk):
"""Applies adjoint mask"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class pef1dmask:
"""Mask operator for not updating the zero lag coefficient"""
def forward(self, add, flt, msk):
"""Applies the mask to the filter"""
if flt.shape != msk.shape:
raise Exception('model and data must have same shape')
msk[:] = flt[:]
msk[0] = 0.0
d... | the_stack_v2_python_sparse | adf/adf/stat/pef1d.py | ke0m/process_f3_data | train | 1 |
704f263fc429f8f9a3d384ab1dd83372127d741e | [
"l = []\nfor fieldname in _columns.getColumnIds():\n l.append(getattr(self, fieldname))\nreturn l",
"assert isinstance(_columns, Columns)\nl = []\nfor column in _columns:\n assert isinstance(column, Column)\n if column.isDataField():\n data_id = getattr(self, column.getId())\n if data_id is... | <|body_start_0|>
l = []
for fieldname in _columns.getColumnIds():
l.append(getattr(self, fieldname))
return l
<|end_body_0|>
<|body_start_1|>
assert isinstance(_columns, Columns)
l = []
for column in _columns:
assert isinstance(column, Column)
... | CsvMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvMixin:
def to_list_old(self, _columns):
"""called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model."""
<|body_0|>
def to_list(self, _columns):
"""similar to to_list including dataId resolver."""
... | stack_v2_sparse_classes_75kplus_train_008108 | 1,681 | no_license | [
{
"docstring": "called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model.",
"name": "to_list_old",
"signature": "def to_list_old(self, _columns)"
},
{
"docstring": "similar to to_list including dataId resolver.",
"name": "to_list",
... | 2 | stack_v2_sparse_classes_30k_train_021255 | Implement the Python class `CsvMixin` described below.
Class description:
Implement the CsvMixin class.
Method signatures and docstrings:
- def to_list_old(self, _columns): called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model.
- def to_list(self, _column... | Implement the Python class `CsvMixin` described below.
Class description:
Implement the CsvMixin class.
Method signatures and docstrings:
- def to_list_old(self, _columns): called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model.
- def to_list(self, _column... | 890d12095ac04b4fe6e60d7aacf6f46aa3865a81 | <|skeleton|>
class CsvMixin:
def to_list_old(self, _columns):
"""called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model."""
<|body_0|>
def to_list(self, _columns):
"""similar to to_list including dataId resolver."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CsvMixin:
def to_list_old(self, _columns):
"""called by JsonRpcDispatcher to create TSV or CSV record. This is named after to_dict() which is defined in ndb.Model."""
l = []
for fieldname in _columns.getColumnIds():
l.append(getattr(self, fieldname))
return l
d... | the_stack_v2_python_sparse | odenkiapi/model/CsvMixin.py | TakashiSasaki/odenkiapi | train | 0 | |
30a5ee229f4c1f7362685acc48abbe857b53741a | [
"clen = len(prerequisites)\nif clen == 0:\n return True\nvisited = [0 for _ in range(numCourses)]\ninverse_adj = [set() for _ in range(numCourses)]\nfor second, first in prerequisites:\n inverse_adj[second].add(first)\nfor i in range(numCourses):\n if self.__dfs(i, inverse_adj, visited):\n return Fa... | <|body_start_0|>
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numCourses)]
inverse_adj = [set() for _ in range(numCourses)]
for second, first in prerequisites:
inverse_adj[second].add(first)
for i in range(numCour... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inver... | stack_v2_sparse_classes_75kplus_train_008109 | 8,289 | no_license | [
{
"docstring": ":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool",
"name": "canFinish",
"signature": "def canFinish(self, numCourses, prerequisites)"
},
{
"docstring": "注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_adj: 逆邻接表,记录的是当前结点的前驱结点的集合 :par... | 2 | stack_v2_sparse_classes_30k_val_000270 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(self, vertex, inverse_adj, vis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(self, vertex, inverse_adj, vis... | fd89d81943d862d9d6e8da661b50afa268b413c8 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inver... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numCourses)]
inverse_adj =... | the_stack_v2_python_sparse | 207.课程表.py | jzijin/leetcode | train | 1 | |
665a7577576b79da151d370760a12b2bea42c378 | [
"connect_mysql = ConnectMysql(host='202.104.102.166', user='rz_cm_master', password='TbLuENLK', port=3306, db='jydb')\nday = \"'2019-03-31'\"\nsql = 'SELECT m.roe,s.SecuCode FROM jydb.LC_MainIndexNew m INNER JOIN jydb.SecuMain s ON (m.CompanyCode = s.CompanyCode) INNER JOIN jydb.CT_SystemConst c ON (s.ListedState =... | <|body_start_0|>
connect_mysql = ConnectMysql(host='202.104.102.166', user='rz_cm_master', password='TbLuENLK', port=3306, db='jydb')
day = "'2019-03-31'"
sql = 'SELECT m.roe,s.SecuCode FROM jydb.LC_MainIndexNew m INNER JOIN jydb.SecuMain s ON (m.CompanyCode = s.CompanyCode) INNER JOIN jydb.CT_S... | TestAssetFinancialAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAssetFinancialAnalysis:
def test_check_roe_threshold_greater_zero():
"""检查数据库绩优股(roe大于0)阈值数据准确性"""
<|body_0|>
def test_check_roe_threshold_less_zero():
"""检查数据库绩优股(roe小于0)阈值数据准确性"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
connect_mysql = Co... | stack_v2_sparse_classes_75kplus_train_008110 | 4,578 | no_license | [
{
"docstring": "检查数据库绩优股(roe大于0)阈值数据准确性",
"name": "test_check_roe_threshold_greater_zero",
"signature": "def test_check_roe_threshold_greater_zero()"
},
{
"docstring": "检查数据库绩优股(roe小于0)阈值数据准确性",
"name": "test_check_roe_threshold_less_zero",
"signature": "def test_check_roe_threshold_less... | 2 | stack_v2_sparse_classes_30k_train_019289 | Implement the Python class `TestAssetFinancialAnalysis` described below.
Class description:
Implement the TestAssetFinancialAnalysis class.
Method signatures and docstrings:
- def test_check_roe_threshold_greater_zero(): 检查数据库绩优股(roe大于0)阈值数据准确性
- def test_check_roe_threshold_less_zero(): 检查数据库绩优股(roe小于0)阈值数据准确性 | Implement the Python class `TestAssetFinancialAnalysis` described below.
Class description:
Implement the TestAssetFinancialAnalysis class.
Method signatures and docstrings:
- def test_check_roe_threshold_greater_zero(): 检查数据库绩优股(roe大于0)阈值数据准确性
- def test_check_roe_threshold_less_zero(): 检查数据库绩优股(roe小于0)阈值数据准确性
<|sk... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class TestAssetFinancialAnalysis:
def test_check_roe_threshold_greater_zero():
"""检查数据库绩优股(roe大于0)阈值数据准确性"""
<|body_0|>
def test_check_roe_threshold_less_zero():
"""检查数据库绩优股(roe小于0)阈值数据准确性"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAssetFinancialAnalysis:
def test_check_roe_threshold_greater_zero():
"""检查数据库绩优股(roe大于0)阈值数据准确性"""
connect_mysql = ConnectMysql(host='202.104.102.166', user='rz_cm_master', password='TbLuENLK', port=3306, db='jydb')
day = "'2019-03-31'"
sql = 'SELECT m.roe,s.SecuCode FROM j... | the_stack_v2_python_sparse | test_case/combination_master/fund_research/fund_page/position_analysis/test_asset_financial_analysis.py | liufubin-git/python | train | 0 | |
d7df72c6a44d1cbeba1db77e46c9f2c90c04edb2 | [
"super(BinaryExpression, self).__init__()\nself.args = []\nself.operator = operator",
"if len(self.args) == 2:\n return '({0!s}) {1:s} {2!s}'.format(self.args[0], self.operator, self.args[1])\nreturn self.operator",
"if not isinstance(lhs, Expression):\n raise errors.ParseError('Left hand side is not an e... | <|body_start_0|>
super(BinaryExpression, self).__init__()
self.args = []
self.operator = operator
<|end_body_0|>
<|body_start_1|>
if len(self.args) == 2:
return '({0!s}) {1:s} {2!s}'.format(self.args[0], self.operator, self.args[1])
return self.operator
<|end_body_1|... | An event filter parser expression which takes two other expressions. | BinaryExpression | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryExpression:
"""An event filter parser expression which takes two other expressions."""
def __init__(self, operator=''):
"""Initializes an event filter parser binary expression. Args: operator (str): operator, such as "and" or "&&"."""
<|body_0|>
def __repr__(self):... | stack_v2_sparse_classes_75kplus_train_008111 | 7,105 | permissive | [
{
"docstring": "Initializes an event filter parser binary expression. Args: operator (str): operator, such as \"and\" or \"&&\".",
"name": "__init__",
"signature": "def __init__(self, operator='')"
},
{
"docstring": "Retrieves a string representation of the object for debugging.",
"name": "_... | 4 | stack_v2_sparse_classes_30k_train_007196 | Implement the Python class `BinaryExpression` described below.
Class description:
An event filter parser expression which takes two other expressions.
Method signatures and docstrings:
- def __init__(self, operator=''): Initializes an event filter parser binary expression. Args: operator (str): operator, such as "and... | Implement the Python class `BinaryExpression` described below.
Class description:
An event filter parser expression which takes two other expressions.
Method signatures and docstrings:
- def __init__(self, operator=''): Initializes an event filter parser binary expression. Args: operator (str): operator, such as "and... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class BinaryExpression:
"""An event filter parser expression which takes two other expressions."""
def __init__(self, operator=''):
"""Initializes an event filter parser binary expression. Args: operator (str): operator, such as "and" or "&&"."""
<|body_0|>
def __repr__(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryExpression:
"""An event filter parser expression which takes two other expressions."""
def __init__(self, operator=''):
"""Initializes an event filter parser binary expression. Args: operator (str): operator, such as "and" or "&&"."""
super(BinaryExpression, self).__init__()
... | the_stack_v2_python_sparse | plaso/filters/expressions.py | log2timeline/plaso | train | 1,506 |
af274f1ff83ca538fcaec1ad970db9b20004ca93 | [
"if not SetupManagerFactory.__instance:\n SetupManagerFactory.__instance = SetupManagerFactory()\nreturn SetupManagerFactory.__instance",
"setups = {}\nfor setup_name in data:\n setup_data = data[setup_name]\n setup_objs = []\n for obj_name in setup_data:\n obj_data = setup_data[obj_name]\n ... | <|body_start_0|>
if not SetupManagerFactory.__instance:
SetupManagerFactory.__instance = SetupManagerFactory()
return SetupManagerFactory.__instance
<|end_body_0|>
<|body_start_1|>
setups = {}
for setup_name in data:
setup_data = data[setup_name]
setu... | Factory singleton that creates a SetupManager | SetupManagerFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetupManagerFactory:
"""Factory singleton that creates a SetupManager"""
def get_instance(self):
"""Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rtype: SetupManagerFactory"""
<|body_0|>
def cr... | stack_v2_sparse_classes_75kplus_train_008112 | 9,539 | no_license | [
{
"docstring": "Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rtype: SetupManagerFactory",
"name": "get_instance",
"signature": "def get_instance(self)"
},
{
"docstring": "Creates a new SetupManager @param data: Dictio... | 2 | stack_v2_sparse_classes_30k_train_025261 | Implement the Python class `SetupManagerFactory` described below.
Class description:
Factory singleton that creates a SetupManager
Method signatures and docstrings:
- def get_instance(self): Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rty... | Implement the Python class `SetupManagerFactory` described below.
Class description:
Factory singleton that creates a SetupManager
Method signatures and docstrings:
- def get_instance(self): Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rty... | 04697e8bb8fb5b498eb5ffd70e1d4fa5f973e7bd | <|skeleton|>
class SetupManagerFactory:
"""Factory singleton that creates a SetupManager"""
def get_instance(self):
"""Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rtype: SetupManagerFactory"""
<|body_0|>
def cr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetupManagerFactory:
"""Factory singleton that creates a SetupManager"""
def get_instance(self):
"""Returns a shared instance of this SetupManagerFactory, creating it if necessary @return: Shared instance of this singleton @rtype: SetupManagerFactory"""
if not SetupManagerFactory.__instan... | the_stack_v2_python_sparse | configurable.py | sampottinger/Haikw | train | 0 |
ca4125ef3b0234925661cf58038880d80571f753 | [
"open_ptr = 0\nback_ptr = -1\nwhile len(A) + back_ptr >= open_ptr:\n if A[open_ptr] == elem:\n A[open_ptr], A[back_ptr] = (A[back_ptr], A[open_ptr])\n back_ptr -= 1\n else:\n open_ptr += 1\nreturn len(A) + back_ptr + 1",
"open_ptr = 0\nend_ptr = len(A)\nwhile open_ptr < end_ptr:\n if... | <|body_start_0|>
open_ptr = 0
back_ptr = -1
while len(A) + back_ptr >= open_ptr:
if A[open_ptr] == elem:
A[open_ptr], A[back_ptr] = (A[back_ptr], A[open_ptr])
back_ptr -= 1
else:
open_ptr += 1
return len(A) + back_pt... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement_negative_index(self, A, elem):
"""Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: list :param elem: integer :return: "shrunk" list"""
<|body_0|>
def removeElement(self... | stack_v2_sparse_classes_75kplus_train_008113 | 1,709 | permissive | [
{
"docstring": "Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: list :param elem: integer :return: \"shrunk\" list",
"name": "removeElement_negative_index",
"signature": "def removeElement_negative_index(self, A, elem)"
},... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_negative_index(self, A, elem): Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_negative_index(self, A, elem): Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: l... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def removeElement_negative_index(self, A, elem):
"""Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: list :param elem: integer :return: "shrunk" list"""
<|body_0|>
def removeElement(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeElement_negative_index(self, A, elem):
"""Constant space Algorithms: Two Pointers Partitioning the array into 3 parts, closed, open, back Data structure: array :param A: list :param elem: integer :return: "shrunk" list"""
open_ptr = 0
back_ptr = -1
while len... | the_stack_v2_python_sparse | 025 Remove Element.py | Aminaba123/LeetCode | train | 1 | |
7935ec5baf3757dd2c6f49a5472002217e2ff807 | [
"super(GNFFlowModel, self).__init__()\nself.biject = biject\nself.base_dist = base_dist\nself.bijectors = nn.ModuleList(self.biject)\nself.log_det = []",
"self.log_det = []\nfor b in range(len(self.bijectors) - 1, -1, -1):\n self.log_det.append(self.bijectors[b].log_abs_det_jacobian(x))\n x = self.bijectors... | <|body_start_0|>
super(GNFFlowModel, self).__init__()
self.biject = biject
self.base_dist = base_dist
self.bijectors = nn.ModuleList(self.biject)
self.log_det = []
<|end_body_0|>
<|body_start_1|>
self.log_det = []
for b in range(len(self.bijectors) - 1, -1, -1):
... | GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution. | GNFFlowModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GNFFlowModel:
"""GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution."""
def __init__(self, biject: List[GRevNet], base_dist: Mul... | stack_v2_sparse_classes_75kplus_train_008114 | 19,571 | permissive | [
{
"docstring": ":param biject: List of flow layers. :param base_dist: Base distribution, specified for non-conditional flow.",
"name": "__init__",
"signature": "def __init__(self, biject: List[GRevNet], base_dist: MultivariateNormal)"
},
{
"docstring": "Compute the inverse of a target distributi... | 3 | stack_v2_sparse_classes_30k_train_032216 | Implement the Python class `GNFFlowModel` described below.
Class description:
GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution.
Method signatures and do... | Implement the Python class `GNFFlowModel` described below.
Class description:
GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution.
Method signatures and do... | f470849d5b7b90dc5a65bab8a536de1d57c1021a | <|skeleton|>
class GNFFlowModel:
"""GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution."""
def __init__(self, biject: List[GRevNet], base_dist: Mul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GNFFlowModel:
"""GNF class. The forward function computes the cumulative log absolute value of the determinant of the jacobians of the transformations, and the sample function samples from the flow starting at the base distribution."""
def __init__(self, biject: List[GRevNet], base_dist: MultivariateNorm... | the_stack_v2_python_sparse | conformation/flows.py | ks8/conformation | train | 1 |
4cd440f33b8c5441252951785b3be9ba9c777d79 | [
"sym, arg_params, aux_params = mx.model.load_checkpoint(prefix=checkpoint_path, epoch=checkpoint_epoch)\nh5f = h5py.File(dst_filepath, 'w')\nfor k, v in arg_params.items():\n name = k\n if name.endswith('_bias'):\n name = name[:-5] + '/b'\n if name.endswith('_weight'):\n name = name[:-7] + '/... | <|body_start_0|>
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix=checkpoint_path, epoch=checkpoint_epoch)
h5f = h5py.File(dst_filepath, 'w')
for k, v in arg_params.items():
name = k
if name.endswith('_bias'):
name = name[:-5] + '/b'
... | Class, which provides saving (and loading) models' weights into universal format. | Converter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Class, which provides saving (and loading) models' weights into universal format."""
def export_to_h5(checkpoint_path, checkpoint_epoch, dst_filepath):
"""Saving models' weights into universal format. Parameters: ---------- checkpoint_path : str path to checkpoint file ... | stack_v2_sparse_classes_75kplus_train_008115 | 3,403 | permissive | [
{
"docstring": "Saving models' weights into universal format. Parameters: ---------- checkpoint_path : str path to checkpoint file with the prefix checkpoint_epoch : int number of epoch for the checkpoint file dst_filepath : str path to output h5 file",
"name": "export_to_h5",
"signature": "def export_t... | 2 | stack_v2_sparse_classes_30k_train_035631 | Implement the Python class `Converter` described below.
Class description:
Class, which provides saving (and loading) models' weights into universal format.
Method signatures and docstrings:
- def export_to_h5(checkpoint_path, checkpoint_epoch, dst_filepath): Saving models' weights into universal format. Parameters: ... | Implement the Python class `Converter` described below.
Class description:
Class, which provides saving (and loading) models' weights into universal format.
Method signatures and docstrings:
- def export_to_h5(checkpoint_path, checkpoint_epoch, dst_filepath): Saving models' weights into universal format. Parameters: ... | 7cf32823a83812d2eadce66d3effea6bee538109 | <|skeleton|>
class Converter:
"""Class, which provides saving (and loading) models' weights into universal format."""
def export_to_h5(checkpoint_path, checkpoint_epoch, dst_filepath):
"""Saving models' weights into universal format. Parameters: ---------- checkpoint_path : str path to checkpoint file ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Converter:
"""Class, which provides saving (and loading) models' weights into universal format."""
def export_to_h5(checkpoint_path, checkpoint_epoch, dst_filepath):
"""Saving models' weights into universal format. Parameters: ---------- checkpoint_path : str path to checkpoint file with the pref... | the_stack_v2_python_sparse | MXNet/converter.py | osmr/utct | train | 0 |
f66d1552df68fff9583e6c4dfce2320ab00cc7e0 | [
"self.tasks = tasks\nself.task_validation = task_validation\nself.settings = EmmetBuildSettings.autoload(settings)\nself.query = query\nself.kwargs = kwargs\nsuper().__init__(source=tasks, target=task_validation, projection=['orig_inputs', 'input.hubbards', 'output.structure', 'output.bandgap', 'chemsys', 'calcs_re... | <|body_start_0|>
self.tasks = tasks
self.task_validation = task_validation
self.settings = EmmetBuildSettings.autoload(settings)
self.query = query
self.kwargs = kwargs
super().__init__(source=tasks, target=task_validation, projection=['orig_inputs', 'input.hubbards', 'ou... | TaskValidator | [
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskValidator:
def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks: Store of task documents task_validation: Store of task_types for ... | stack_v2_sparse_classes_75kplus_train_008116 | 2,511 | permissive | [
{
"docstring": "Creates task_types from tasks and type definitions Args: tasks: Store of task documents task_validation: Store of task_types for tasks",
"name": "__init__",
"signature": "def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional... | 2 | stack_v2_sparse_classes_30k_train_000122 | Implement the Python class `TaskValidator` described below.
Class description:
Implement the TaskValidator class.
Method signatures and docstrings:
- def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs): Creates task_types from tas... | Implement the Python class `TaskValidator` described below.
Class description:
Implement the TaskValidator class.
Method signatures and docstrings:
- def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs): Creates task_types from tas... | 82be5d03850cce7609396ac787b31b5d0512d3f4 | <|skeleton|>
class TaskValidator:
def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks: Store of task documents task_validation: Store of task_types for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskValidator:
def __init__(self, tasks: Store, task_validation: Store, settings: Optional[EmmetBuildSettings]=None, query: Optional[Dict]=None, **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks: Store of task documents task_validation: Store of task_types for tasks"""
... | the_stack_v2_python_sparse | emmet-builders/emmet/builders/vasp/task_validator.py | sailfish009/emmet | train | 0 | |
9e4eae77ec00fe1fcb0cf779812c6172876b0031 | [
"self.script_type = script_type\nself.default_shell = default_shell\nname = '%s-script' % self.script_type\nfacility = logging.handlers.SysLogHandler.LOG_DAEMON\nself.logger = logger.Logger(name=name, debug=debug, facility=facility)\nself.retriever = script_retriever.ScriptRetriever(self.logger, script_type)\nself.... | <|body_start_0|>
self.script_type = script_type
self.default_shell = default_shell
name = '%s-script' % self.script_type
facility = logging.handlers.SysLogHandler.LOG_DAEMON
self.logger = logger.Logger(name=name, debug=debug, facility=facility)
self.retriever = script_ret... | A class for retrieving and executing metadata scripts. | ScriptManager | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScriptManager:
"""A class for retrieving and executing metadata scripts."""
def __init__(self, script_type, default_shell=None, run_dir=None, debug=False):
"""Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute ... | stack_v2_sparse_classes_75kplus_train_008117 | 4,004 | permissive | [
{
"docstring": "Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. run_dir: string, the base directory location of the temporary directory. debug: bool, True if debug output should write to the console.",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_017703 | Implement the Python class `ScriptManager` described below.
Class description:
A class for retrieving and executing metadata scripts.
Method signatures and docstrings:
- def __init__(self, script_type, default_shell=None, run_dir=None, debug=False): Constructor. Args: script_type: string, the metadata script type to ... | Implement the Python class `ScriptManager` described below.
Class description:
A class for retrieving and executing metadata scripts.
Method signatures and docstrings:
- def __init__(self, script_type, default_shell=None, run_dir=None, debug=False): Constructor. Args: script_type: string, the metadata script type to ... | cf4b33214f770da2299923a5fa73d3d95f66ec35 | <|skeleton|>
class ScriptManager:
"""A class for retrieving and executing metadata scripts."""
def __init__(self, script_type, default_shell=None, run_dir=None, debug=False):
"""Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScriptManager:
"""A class for retrieving and executing metadata scripts."""
def __init__(self, script_type, default_shell=None, run_dir=None, debug=False):
"""Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. r... | the_stack_v2_python_sparse | packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py | GoogleCloudPlatform/compute-image-packages | train | 329 |
a8d2b35618c7e8af528a5d027f5298704b583431 | [
"input_file = XSDataInputControlDozor()\ninput_file.setTemplate(XSDataString(self.params_dict['template']))\ninput_file.setFirst_image_number(XSDataInteger(self.params_dict['first_image_num']))\ninput_file.setLast_image_number(XSDataInteger(self.params_dict['images_num']))\ninput_file.setFirst_run_number(XSDataInte... | <|body_start_0|>
input_file = XSDataInputControlDozor()
input_file.setTemplate(XSDataString(self.params_dict['template']))
input_file.setFirst_image_number(XSDataInteger(self.params_dict['first_image_num']))
input_file.setLast_image_number(XSDataInteger(self.params_dict['images_num']))
... | DozorParallelProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DozorParallelProcessing:
def create_processing_input_file(self, processing_input_filename):
"""Creates dozor input file base on data collection parameters :param processing_input_filename :type : str"""
<|body_0|>
def batch_processed(self, batch):
"""Method called fr... | stack_v2_sparse_classes_75kplus_train_008118 | 3,473 | no_license | [
{
"docstring": "Creates dozor input file base on data collection parameters :param processing_input_filename :type : str",
"name": "create_processing_input_file",
"signature": "def create_processing_input_file(self, processing_input_filename)"
},
{
"docstring": "Method called from EDNA via xmlrp... | 2 | stack_v2_sparse_classes_30k_train_021941 | Implement the Python class `DozorParallelProcessing` described below.
Class description:
Implement the DozorParallelProcessing class.
Method signatures and docstrings:
- def create_processing_input_file(self, processing_input_filename): Creates dozor input file base on data collection parameters :param processing_inp... | Implement the Python class `DozorParallelProcessing` described below.
Class description:
Implement the DozorParallelProcessing class.
Method signatures and docstrings:
- def create_processing_input_file(self, processing_input_filename): Creates dozor input file base on data collection parameters :param processing_inp... | 8ab972c42b89d953b897b9745edec7156b156103 | <|skeleton|>
class DozorParallelProcessing:
def create_processing_input_file(self, processing_input_filename):
"""Creates dozor input file base on data collection parameters :param processing_input_filename :type : str"""
<|body_0|>
def batch_processed(self, batch):
"""Method called fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DozorParallelProcessing:
def create_processing_input_file(self, processing_input_filename):
"""Creates dozor input file base on data collection parameters :param processing_input_filename :type : str"""
input_file = XSDataInputControlDozor()
input_file.setTemplate(XSDataString(self.par... | the_stack_v2_python_sparse | HardwareObjects/DozorParallelProcessing.py | schurmann/HardwareRepository | train | 0 | |
18b7748484504df832dec43c317cd135fb6b4229 | [
"self.error_message = {}\ndata_source_list = Operation('ModelDataSource').read(name=data_source_name)\nif data_source_list:\n self.data_source = data_source_list[0]\nelse:\n self.error_message['message'] = 'No {} found with values: {}'.format('DataSource', {'name': data_source_name})\n log.error(self.error... | <|body_start_0|>
self.error_message = {}
data_source_list = Operation('ModelDataSource').read(name=data_source_name)
if data_source_list:
self.data_source = data_source_list[0]
else:
self.error_message['message'] = 'No {} found with values: {}'.format('DataSource'... | MethodDataSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodDataSource:
def __init__(self, data_source_name):
"""Initialize class."""
<|body_0|>
def get_database_connection(self):
"""Connect to a data source of type database using an ODBC connection. Return a connection object."""
<|body_1|>
def get_data_fr... | stack_v2_sparse_classes_75kplus_train_008119 | 4,194 | permissive | [
{
"docstring": "Initialize class.",
"name": "__init__",
"signature": "def __init__(self, data_source_name)"
},
{
"docstring": "Connect to a data source of type database using an ODBC connection. Return a connection object.",
"name": "get_database_connection",
"signature": "def get_databa... | 3 | stack_v2_sparse_classes_30k_train_000354 | Implement the Python class `MethodDataSource` described below.
Class description:
Implement the MethodDataSource class.
Method signatures and docstrings:
- def __init__(self, data_source_name): Initialize class.
- def get_database_connection(self): Connect to a data source of type database using an ODBC connection. R... | Implement the Python class `MethodDataSource` described below.
Class description:
Implement the MethodDataSource class.
Method signatures and docstrings:
- def __init__(self, data_source_name): Initialize class.
- def get_database_connection(self): Connect to a data source of type database using an ODBC connection. R... | eaa9f2df5536d1bac678571cee1040f0667fd25f | <|skeleton|>
class MethodDataSource:
def __init__(self, data_source_name):
"""Initialize class."""
<|body_0|>
def get_database_connection(self):
"""Connect to a data source of type database using an ODBC connection. Return a connection object."""
<|body_1|>
def get_data_fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MethodDataSource:
def __init__(self, data_source_name):
"""Initialize class."""
self.error_message = {}
data_source_list = Operation('ModelDataSource').read(name=data_source_name)
if data_source_list:
self.data_source = data_source_list[0]
else:
... | the_stack_v2_python_sparse | api/method_data_source.py | teddycarebears/data-quality | train | 0 | |
98b7c0f992ba8a7122124311bc7fcc5957ae4353 | [
"if not strs:\n return ''\nif len(strs) == 1:\n return strs[0]\nstr1, str2 = (strs[0], strs[1])\nres = ''\nfor i in range(min(len(str1), len(str2))):\n if str1[i] == str2[i]:\n res += str1[i]\n else:\n break\nif not res:\n return res\nfor j in range(2, len(strs)):\n if not strs[j]:\n... | <|body_start_0|>
if not strs:
return ''
if len(strs) == 1:
return strs[0]
str1, str2 = (strs[0], strs[1])
res = ''
for i in range(min(len(str1), len(str2))):
if str1[i] == str2[i]:
res += str1[i]
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix1(self, strs):
""":type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str 通过zip(*list)可以将原打包的可迭代对向分开"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_008120 | 1,479 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较",
"name": "longestCommonPrefix1",
"signature": "def longestCommonPrefix1(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str 通过zip(*list)可以将原打包的可迭代对向分开",
"name": "longestCommonPrefix",
"sign... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix1(self, strs): :type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix1(self, strs): :type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str... | 328fdd303af1c8cde5bc9bb4c4f039e777de20e5 | <|skeleton|>
class Solution:
def longestCommonPrefix1(self, strs):
""":type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str 通过zip(*list)可以将原打包的可迭代对向分开"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix1(self, strs):
""":type strs: List[str] :rtype: str 先比较前两个字符串的最长公共前缀,之后用前缀依次与后面的字符串比较"""
if not strs:
return ''
if len(strs) == 1:
return strs[0]
str1, str2 = (strs[0], strs[1])
res = ''
for i in range(min... | the_stack_v2_python_sparse | leetcode/-14. 最长公共前缀.py | zhangzeyang0/code | train | 0 | |
22184c8eac42798d7b2fea28edccdb0164569b91 | [
"countDict = {}\nans = []\nfor item in nums1:\n countDict[item] = countDict.get(item, 0) + 1\nfor item in nums2:\n if countDict.get(item, 0) != 0:\n ans.append(item)\n countDict[item] -= 1\nreturn ans",
"nums1 = sorted(nums1)\nnums2 = sorted(nums2)\ni = 0\nj = 0\nans = []\nwhile i < len(nums1)... | <|body_start_0|>
countDict = {}
ans = []
for item in nums1:
countDict[item] = countDict.get(item, 0) + 1
for item in nums2:
if countDict.get(item, 0) != 0:
ans.append(item)
countDict[item] -= 1
return ans
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_008121 | 1,333 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect2",
"signature": "def intersect2(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect2(self, nums1, nums2): :type nums1: List[int] :type nums2: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect2(self, nums1, nums2): :type nums1: List[int] :type nums2: List[... | 65226cdd7ac68e63991a02d09341a17043664281 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: 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 intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
countDict = {}
ans = []
for item in nums1:
countDict[item] = countDict.get(item, 0) + 1
for item in nums2:
if countDict.get(item, 0... | the_stack_v2_python_sparse | leetcode-python/350_Intersection_of_Two_Arrays_II.py | inzy/leetcode | train | 0 | |
0ad3d46b1c840031470142e972aa704b87e9360f | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | TestCheckVIPCarRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test_checkMonthTicketListRecord(se... | stack_v2_sparse_classes_75kplus_train_008122 | 1,918 | no_license | [
{
"docstring": "创建自定义月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "用自定义月票类型开通月票",
"name": "test_openMonthTicketBill",
"signature": "def test_openMonthTicketBill(self, userLogin, send_d... | 3 | stack_v2_sparse_classes_30k_val_001313 | Implement the Python class `TestCheckVIPCarRecord` described below.
Class description:
Implement the TestCheckVIPCarRecord class.
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义... | Implement the Python class `TestCheckVIPCarRecord` described below.
Class description:
Implement the TestCheckVIPCarRecord class.
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test_checkMonthTicketListRecord(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
... | the_stack_v2_python_sparse | test_suite/centerMonitorRoom/carInOutHandle/test_checkVIPCarRecord.py | oyebino/pomp_api | train | 1 | |
1ce21a4c2ae325f65a68d865af5a577432fa0760 | [
"try:\n connection = lcu.connect(os.path.expanduser(settings.league_client_path))\nexcept IndexError:\n raise LeagueConnectionException\nif connection == 'Ensure the client is running and that you supplied the correct path':\n raise LeagueConnectionException\nself.kwargs = {'verify': False, 'auth': ('riot'... | <|body_start_0|>
try:
connection = lcu.connect(os.path.expanduser(settings.league_client_path))
except IndexError:
raise LeagueConnectionException
if connection == 'Ensure the client is running and that you supplied the correct path':
raise LeagueConnectionExc... | Connects to league client and communicates with it | LeagueConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeagueConnection:
"""Connects to league client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
<|body_0|>
def get_connection_ft(self, settings):
"""Parses connection url and port from lockfile fau... | stack_v2_sparse_classes_75kplus_train_008123 | 1,890 | permissive | [
{
"docstring": "Parses connection url and port from lockfile",
"name": "get_connection",
"signature": "def get_connection(self, settings)"
},
{
"docstring": "Parses connection url and port from lockfile fault tolerant version",
"name": "get_connection_ft",
"signature": "def get_connectio... | 2 | stack_v2_sparse_classes_30k_train_022493 | Implement the Python class `LeagueConnection` described below.
Class description:
Connects to league client and communicates with it
Method signatures and docstrings:
- def get_connection(self, settings): Parses connection url and port from lockfile
- def get_connection_ft(self, settings): Parses connection url and p... | Implement the Python class `LeagueConnection` described below.
Class description:
Connects to league client and communicates with it
Method signatures and docstrings:
- def get_connection(self, settings): Parses connection url and port from lockfile
- def get_connection_ft(self, settings): Parses connection url and p... | 61a96e4a4bfd19ab686a9706e74931fe71291330 | <|skeleton|>
class LeagueConnection:
"""Connects to league client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
<|body_0|>
def get_connection_ft(self, settings):
"""Parses connection url and port from lockfile fau... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LeagueConnection:
"""Connects to league client and communicates with it"""
def get_connection(self, settings):
"""Parses connection url and port from lockfile"""
try:
connection = lcu.connect(os.path.expanduser(settings.league_client_path))
except IndexError:
... | the_stack_v2_python_sparse | connection/league.py | LegendaryZone/auto_disenchanter | train | 1 |
38beb8b34bae56f1d0b67facdf48c1c957c05cb0 | [
"self.module = module\nself.module_path = module_path\nself.members_to_exclude = members_to_exclude\nself.members_to_set_manually = members_to_set_manually\nself.at_end_of_file = at_end_of_file\nself.generate_rest_of_the_code = generate_rest_of_the_code",
"names = dir(self.module)\nret = dict()\nfor name in names... | <|body_start_0|>
self.module = module
self.module_path = module_path
self.members_to_exclude = members_to_exclude
self.members_to_set_manually = members_to_set_manually
self.at_end_of_file = at_end_of_file
self.generate_rest_of_the_code = generate_rest_of_the_code
<|end_b... | Class that deal with manual type assignment code generation | ModuleMemberTypes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleMemberTypes:
"""Class that deal with manual type assignment code generation"""
def __init__(self, module, module_path, at_end_of_file, members_to_exclude, members_to_set_manually, generate_rest_of_the_code=True):
"""Initializes manual type assignment code generation :param modu... | stack_v2_sparse_classes_75kplus_train_008124 | 7,705 | no_license | [
{
"docstring": "Initializes manual type assignment code generation :param module: Module to put manual code into :param module_path: Place of the module :param at_end_of_file: Determines if the type assignment code will be placed at the end of the file or just after the type store creation :param members_to_exc... | 4 | null | Implement the Python class `ModuleMemberTypes` described below.
Class description:
Class that deal with manual type assignment code generation
Method signatures and docstrings:
- def __init__(self, module, module_path, at_end_of_file, members_to_exclude, members_to_set_manually, generate_rest_of_the_code=True): Initi... | Implement the Python class `ModuleMemberTypes` described below.
Class description:
Class that deal with manual type assignment code generation
Method signatures and docstrings:
- def __init__(self, module, module_path, at_end_of_file, members_to_exclude, members_to_set_manually, generate_rest_of_the_code=True): Initi... | be66ae846c82ac40ba7b48f9880d6e3990681a5b | <|skeleton|>
class ModuleMemberTypes:
"""Class that deal with manual type assignment code generation"""
def __init__(self, module, module_path, at_end_of_file, members_to_exclude, members_to_set_manually, generate_rest_of_the_code=True):
"""Initializes manual type assignment code generation :param modu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleMemberTypes:
"""Class that deal with manual type assignment code generation"""
def __init__(self, module, module_path, at_end_of_file, members_to_exclude, members_to_set_manually, generate_rest_of_the_code=True):
"""Initializes manual type assignment code generation :param module: Module to... | the_stack_v2_python_sparse | stypy/visitor/python_src_generation/manual_module_types_generation.py | ComputationalReflection/stypy | train | 2 |
5404941c9dab8dd0907b8e6545a46a1e0013c3a6 | [
"self.source_type = source_type.lower()\nself.source = self._set_source()\nif not self.source:\n raise AccountsAccessorError('Invalid source type specified.')",
"if self.source_type == 'db':\n return CURAccountsDB()\nreturn None",
"if utils.ingest_method_for_provider(account.get('provider_type')) == POLL_... | <|body_start_0|>
self.source_type = source_type.lower()
self.source = self._set_source()
if not self.source:
raise AccountsAccessorError('Invalid source type specified.')
<|end_body_0|>
<|body_start_1|>
if self.source_type == 'db':
return CURAccountsDB()
... | Interface for masu to use to get CUR accounts. | AccountsAccessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
<|body_0|>
def _set_source(self):
"""Create the provider service object. Set what source... | stack_v2_sparse_classes_75kplus_train_008125 | 3,451 | permissive | [
{
"docstring": "Set the CUR accounts external source.",
"name": "__init__",
"signature": "def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE)"
},
{
"docstring": "Create the provider service object. Set what source should be used to get CUR accounts. Args: None Returns: (Object) : Some obj... | 4 | stack_v2_sparse_classes_30k_train_017148 | Implement the Python class `AccountsAccessor` described below.
Class description:
Interface for masu to use to get CUR accounts.
Method signatures and docstrings:
- def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE): Set the CUR accounts external source.
- def _set_source(self): Create the provider service ob... | Implement the Python class `AccountsAccessor` described below.
Class description:
Interface for masu to use to get CUR accounts.
Method signatures and docstrings:
- def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE): Set the CUR accounts external source.
- def _set_source(self): Create the provider service ob... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
<|body_0|>
def _set_source(self):
"""Create the provider service object. Set what source... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountsAccessor:
"""Interface for masu to use to get CUR accounts."""
def __init__(self, source_type=Config.ACCOUNT_ACCESS_TYPE):
"""Set the CUR accounts external source."""
self.source_type = source_type.lower()
self.source = self._set_source()
if not self.source:
... | the_stack_v2_python_sparse | koku/masu/external/accounts_accessor.py | project-koku/koku | train | 225 |
8c2ee77066bf0f9155a7797ad5cc5d62c40c071d | [
"super(TFRecordProvider, self).__init__(data_dir)\nif split not in ['all', 'train', 'valid', 'test']:\n raise ValueError('split must be either all, train, valid or test.')\nif split == 'all':\n file_name = '*.tfrecord'\nelse:\n file_name = '*%s.tfrecord' % split\nself.split = split\nself.file_pattern = os.... | <|body_start_0|>
super(TFRecordProvider, self).__init__(data_dir)
if split not in ['all', 'train', 'valid', 'test']:
raise ValueError('split must be either all, train, valid or test.')
if split == 'all':
file_name = '*.tfrecord'
else:
file_name = '*%s.... | Class for handling data stored in TFRecords. | TFRecordProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFRecordProvider:
"""Class for handling data stored in TFRecords."""
def __init__(self, data_dir=None, split='all'):
"""TFRecordProvider constructor."""
<|body_0|>
def get_dataset(self, shuffle=True):
"""Read dataset from files."""
<|body_1|>
def fea... | stack_v2_sparse_classes_75kplus_train_008126 | 3,804 | no_license | [
{
"docstring": "TFRecordProvider constructor.",
"name": "__init__",
"signature": "def __init__(self, data_dir=None, split='all')"
},
{
"docstring": "Read dataset from files.",
"name": "get_dataset",
"signature": "def get_dataset(self, shuffle=True)"
},
{
"docstring": "Dictionary ... | 3 | stack_v2_sparse_classes_30k_train_000376 | Implement the Python class `TFRecordProvider` described below.
Class description:
Class for handling data stored in TFRecords.
Method signatures and docstrings:
- def __init__(self, data_dir=None, split='all'): TFRecordProvider constructor.
- def get_dataset(self, shuffle=True): Read dataset from files.
- def feature... | Implement the Python class `TFRecordProvider` described below.
Class description:
Class for handling data stored in TFRecords.
Method signatures and docstrings:
- def __init__(self, data_dir=None, split='all'): TFRecordProvider constructor.
- def get_dataset(self, shuffle=True): Read dataset from files.
- def feature... | bafaeea12e77b6168ce24da672b1026ab284d260 | <|skeleton|>
class TFRecordProvider:
"""Class for handling data stored in TFRecords."""
def __init__(self, data_dir=None, split='all'):
"""TFRecordProvider constructor."""
<|body_0|>
def get_dataset(self, shuffle=True):
"""Read dataset from files."""
<|body_1|>
def fea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TFRecordProvider:
"""Class for handling data stored in TFRecords."""
def __init__(self, data_dir=None, split='all'):
"""TFRecordProvider constructor."""
super(TFRecordProvider, self).__init__(data_dir)
if split not in ['all', 'train', 'valid', 'test']:
raise ValueError... | the_stack_v2_python_sparse | data/data_provider.py | erl-j/thesis | train | 0 |
f5eea5ea63e09180b243bd7bd60404b2795e6ef1 | [
"self.start_all_services(client=False)\ndeproxy_cl = self.get_client('deproxy3')\ndeproxy_cl.start()\ndeproxy_cl2 = self.get_client('deproxy4')\ndeproxy_cl2.start()\ndeproxy_cl.make_requests(self.requests * 10)\ndeproxy_cl.wait_for_response(timeout=4)\ndeproxy_cl2.make_requests(self.requests2 * 10)\ndeproxy_cl2.wai... | <|body_start_0|>
self.start_all_services(client=False)
deproxy_cl = self.get_client('deproxy3')
deproxy_cl.start()
deproxy_cl2 = self.get_client('deproxy4')
deproxy_cl2.start()
deproxy_cl.make_requests(self.requests * 10)
deproxy_cl.wait_for_response(timeout=4)
... | Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second. | HttpRespCodeBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpRespCodeBlock:
"""Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second."""
def test_two_clients_one_ip(self):
"""Two clients to be blocked by ip for a total of 404 requests"""
... | stack_v2_sparse_classes_75kplus_train_008127 | 9,324 | no_license | [
{
"docstring": "Two clients to be blocked by ip for a total of 404 requests",
"name": "test_two_clients_one_ip",
"signature": "def test_two_clients_one_ip(self)"
},
{
"docstring": "Two clients. One client sends 12 requests by 6 per second during 2 seconds. Of these, 6 requests by 3 per second gi... | 2 | stack_v2_sparse_classes_30k_train_004907 | Implement the Python class `HttpRespCodeBlock` described below.
Class description:
Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second.
Method signatures and docstrings:
- def test_two_clients_one_ip(self): Two clients ... | Implement the Python class `HttpRespCodeBlock` described below.
Class description:
Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second.
Method signatures and docstrings:
- def test_two_clients_one_ip(self): Two clients ... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class HttpRespCodeBlock:
"""Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second."""
def test_two_clients_one_ip(self):
"""Two clients to be blocked by ip for a total of 404 requests"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpRespCodeBlock:
"""Blocks an attacker's IP address if a protected web application return 5 error responses with codes 404 or 405 within 2 seconds. This is 2,5 per second."""
def test_two_clients_one_ip(self):
"""Two clients to be blocked by ip for a total of 404 requests"""
self.start_... | the_stack_v2_python_sparse | t_frang/test_http_resp_code_block.py | tempesta-tech/tempesta-test | train | 13 |
b6097b4c63f518525db01388204409c9f298a60a | [
"query_condition = self.request.GET\nq = Q()\nfor i in query_condition:\n if i == 'format':\n continue\n q.add(Q(**{i: query_condition[i]}), Q.OR)\ntry:\n users = User.objects.filter(q)\nexcept FieldError:\n return JsonResponse({'ERROR': 'invalid query condition!'})\nserializer = UserSerializer(u... | <|body_start_0|>
query_condition = self.request.GET
q = Q()
for i in query_condition:
if i == 'format':
continue
q.add(Q(**{i: query_condition[i]}), Q.OR)
try:
users = User.objects.filter(q)
except FieldError:
return... | ManageUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageUser:
def get(self, request, *args, **kwargs):
"""获取用户信息"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建、修改、删除用户 curl -w %{http_code} -l -H "Content-type: application/json" -X POST -u admin:chenlin1989 -d '{"username":"snakechen"}' http://192.168.... | stack_v2_sparse_classes_75kplus_train_008128 | 2,671 | no_license | [
{
"docstring": "获取用户信息",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "创建、修改、删除用户 curl -w %{http_code} -l -H \"Content-type: application/json\" -X POST -u admin:chenlin1989 -d '{\"username\":\"snakechen\"}' http://192.168.102.128:8000/api/manage_user/",... | 2 | stack_v2_sparse_classes_30k_train_018510 | Implement the Python class `ManageUser` described below.
Class description:
Implement the ManageUser class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取用户信息
- def post(self, request, *args, **kwargs): 创建、修改、删除用户 curl -w %{http_code} -l -H "Content-type: application/json" -X POST -u ... | Implement the Python class `ManageUser` described below.
Class description:
Implement the ManageUser class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取用户信息
- def post(self, request, *args, **kwargs): 创建、修改、删除用户 curl -w %{http_code} -l -H "Content-type: application/json" -X POST -u ... | 015fdf12a73425acfbaabd46ebc6cebbae52e570 | <|skeleton|>
class ManageUser:
def get(self, request, *args, **kwargs):
"""获取用户信息"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建、修改、删除用户 curl -w %{http_code} -l -H "Content-type: application/json" -X POST -u admin:chenlin1989 -d '{"username":"snakechen"}' http://192.168.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManageUser:
def get(self, request, *args, **kwargs):
"""获取用户信息"""
query_condition = self.request.GET
q = Q()
for i in query_condition:
if i == 'format':
continue
q.add(Q(**{i: query_condition[i]}), Q.OR)
try:
users = U... | the_stack_v2_python_sparse | api/views.py | zeus911/Lynn.Django | train | 0 | |
ca9121e59df1401194bc9bde005f3661a78ac7bc | [
"if not isinstance(input_goods, dict):\n input_goods = {good: self[good] for good in input_goods}\nresult = production_function(**input_goods)\nfor good, quantity in input_goods.items():\n if self._inventory.haves[good] - quantity + result.get(good, 0) < -epsilon:\n raise NotEnoughGoods\nfor good, quan... | <|body_start_0|>
if not isinstance(input_goods, dict):
input_goods = {good: self[good] for good in input_goods}
result = production_function(**input_goods)
for good, quantity in input_goods.items():
if self._inventory.haves[good] - quantity + result.get(good, 0) < -epsilo... | With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_cobb_douglas({'land': 0.7, 'capital': 0.1, 'labor': 0.2}) def firming(s... | Firm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Firm:
"""With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_cobb_douglas({'land': 0.7, 'capital': 0... | stack_v2_sparse_classes_75kplus_train_008129 | 10,480 | no_license | [
{
"docstring": "Produces output goods given the specified amount of inputs. Transforms the Agent's goods specified in input goods according to a given production_function to output goods. Automatically changes the agent's belonging. Raises an exception, when the agent does not have sufficient resources. Args: p... | 4 | stack_v2_sparse_classes_30k_train_034231 | Implement the Python class `Firm` described below.
Class description:
With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_... | Implement the Python class `Firm` described below.
Class description:
With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_... | 07a581a6fbfd263976bb5123c5dad97a2a833d29 | <|skeleton|>
class Firm:
"""With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_cobb_douglas({'land': 0.7, 'capital': 0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Firm:
"""With :code:`self.produce` a firm produces a good using production functions. For example the following farm has a cobb-douglas production function: class Farm(abcEconomics.Agent, abcEconomics.Firm): def init(self): self.production_function = create_cobb_douglas({'land': 0.7, 'capital': 0.1, 'labor': ... | the_stack_v2_python_sparse | abcEconomics/agents/firm.py | rht/abce | train | 1 |
8b208bf3a284d5782f2906755dfdca28b6e155a3 | [
"range = kwargs.pop('range', None)\nsuper(RayTransform, self).__init__(reco_space=domain, proj_space=range, geometry=geometry, variant='forward', **kwargs)\nif self.impl.startswith('astra'):\n backend, data_impl = self.impl.split('_')\n if data_impl == 'cuda':\n if self._astra_wrapper is None:\n ... | <|body_start_0|>
range = kwargs.pop('range', None)
super(RayTransform, self).__init__(reco_space=domain, proj_space=range, geometry=geometry, variant='forward', **kwargs)
if self.impl.startswith('astra'):
backend, data_impl = self.impl.split('_')
if data_impl == 'cuda':
... | Discrete Ray transform between L^p spaces. | RayTransform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RayTransform:
"""Discrete Ray transform between L^p spaces."""
def __init__(self, domain, geometry, **kwargs):
"""Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geomet... | stack_v2_sparse_classes_75kplus_train_008130 | 23,312 | permissive | [
{
"docstring": "Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geometry of the transform, containing information about the operator range (projection/sinogram space). Other Parameters -----------... | 3 | stack_v2_sparse_classes_30k_train_051527 | Implement the Python class `RayTransform` described below.
Class description:
Discrete Ray transform between L^p spaces.
Method signatures and docstrings:
- def __init__(self, domain, geometry, **kwargs): Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the doma... | Implement the Python class `RayTransform` described below.
Class description:
Discrete Ray transform between L^p spaces.
Method signatures and docstrings:
- def __init__(self, domain, geometry, **kwargs): Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the doma... | cb9f08f105285a56337fa21f275aa3a15fcd74ab | <|skeleton|>
class RayTransform:
"""Discrete Ray transform between L^p spaces."""
def __init__(self, domain, geometry, **kwargs):
"""Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geomet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RayTransform:
"""Discrete Ray transform between L^p spaces."""
def __init__(self, domain, geometry, **kwargs):
"""Initialize a new instance. Parameters ---------- domain : `DiscreteLp` Discretized reconstruction space, the domain of the forward projector. geometry : `Geometry` Geometry of the tra... | the_stack_v2_python_sparse | fastatomography/tomo/operators/ray_trafo.py | PhilippPelz/fasta-tomography | train | 2 |
ab7c20dc6fa2d672e9299a3cdd5172ef63029f34 | [
"if filename or not getattr(self, 'filename', None):\n self.filename = filename\nif not self.filename:\n raise ValueError('`filename` must be set.')\nwith open(self.filename, 'r') as f:\n data = json.load(f)\nif data is None:\n data = {}\nif not isinstance(data, dict):\n raise TypeError('Data was rep... | <|body_start_0|>
if filename or not getattr(self, 'filename', None):
self.filename = filename
if not self.filename:
raise ValueError('`filename` must be set.')
with open(self.filename, 'r') as f:
data = json.load(f)
if data is None:
data = ... | This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it will be created when a filename is passed to `load` or `save`. If either is ca... | JSONMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONMixin:
"""This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it will be created when a filename is passed... | stack_v2_sparse_classes_75kplus_train_008131 | 3,192 | no_license | [
{
"docstring": "Load this dict from a JSON file. Raises the same errors as open() and json.load().",
"name": "load",
"signature": "def load(self, filename=None)"
},
{
"docstring": "Save this dict to a JSON file. Raises the same errors as open() and json.dump().",
"name": "save",
"signatu... | 2 | null | Implement the Python class `JSONMixin` described below.
Class description:
This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it wi... | Implement the Python class `JSONMixin` described below.
Class description:
This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it wi... | 0097be3c9da21f3cf4ced5eef8527f670402f47a | <|skeleton|>
class JSONMixin:
"""This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it will be created when a filename is passed... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONMixin:
"""This mixin provides two methods that both operate on `self.data`. `self.load(filename=None)` `self.save(filename=None, sort_keys=False)` These will load and save `self.data` in JSON format. If the attribute `self.filename` does not exist, it will be created when a filename is passed to `load` or... | the_stack_v2_python_sparse | projects/static/files/easysettings/source/json_settings.py | welbornprod/wp_site | train | 0 |
c7d22085bc815e6cdc8530691714f1204140d47f | [
"simulate_insert_data()\ndata = {'id': 1, 'name': 'Development', 'color': '#f00', 'company': 1}\nresponse = self.client.post('/api/company/1/roles/', data, format='json')\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)",
"simulate_insert_data()\nresponse = self.client.get('/api/company/1/roles/',... | <|body_start_0|>
simulate_insert_data()
data = {'id': 1, 'name': 'Development', 'color': '#f00', 'company': 1}
response = self.client.post('/api/company/1/roles/', data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
<|end_body_0|>
<|body_start_1|>
... | CompanyRoles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyRoles:
def test_insert_role(self):
"""Insert new company role"""
<|body_0|>
def test_roles_list(self):
"""Retrieve company roles"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
simulate_insert_data()
data = {'id': 1, 'name': 'Developm... | stack_v2_sparse_classes_75kplus_train_008132 | 3,622 | no_license | [
{
"docstring": "Insert new company role",
"name": "test_insert_role",
"signature": "def test_insert_role(self)"
},
{
"docstring": "Retrieve company roles",
"name": "test_roles_list",
"signature": "def test_roles_list(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017931 | Implement the Python class `CompanyRoles` described below.
Class description:
Implement the CompanyRoles class.
Method signatures and docstrings:
- def test_insert_role(self): Insert new company role
- def test_roles_list(self): Retrieve company roles | Implement the Python class `CompanyRoles` described below.
Class description:
Implement the CompanyRoles class.
Method signatures and docstrings:
- def test_insert_role(self): Insert new company role
- def test_roles_list(self): Retrieve company roles
<|skeleton|>
class CompanyRoles:
def test_insert_role(self):... | 905f071ff963b9bad61610e944b1cef01fc95b33 | <|skeleton|>
class CompanyRoles:
def test_insert_role(self):
"""Insert new company role"""
<|body_0|>
def test_roles_list(self):
"""Retrieve company roles"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompanyRoles:
def test_insert_role(self):
"""Insert new company role"""
simulate_insert_data()
data = {'id': 1, 'name': 'Development', 'color': '#f00', 'company': 1}
response = self.client.post('/api/company/1/roles/', data, format='json')
self.assertEqual(response.stat... | the_stack_v2_python_sparse | companies/tests.py | rcdigital/kanban-server | train | 0 | |
8bc74e0b23dcee617aa4211b2a2fd2c024887e92 | [
"url = reverse('configuration:loggedinuserdetail')\nuser = User.objects.get(username='api')\nself.client.force_authenticate(user=user)\nresponse = self.client.get(url, format='json')\nself.assertEqual(response.status_code, status.HTTP_200_OK)\nself.assertEqual(response.data['username'], 'api')",
"url = reverse('c... | <|body_start_0|>
url = reverse('configuration:loggedinuserdetail')
user = User.objects.get(username='api')
self.client.force_authenticate(user=user)
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(... | UserTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTests:
def test_curuser(self):
"""Test that we can get the currently logged in user"""
<|body_0|>
def test_user_not_logged_in(self):
"""Test that we don't get anything if there's no user logged in"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008133 | 977 | no_license | [
{
"docstring": "Test that we can get the currently logged in user",
"name": "test_curuser",
"signature": "def test_curuser(self)"
},
{
"docstring": "Test that we don't get anything if there's no user logged in",
"name": "test_user_not_logged_in",
"signature": "def test_user_not_logged_in... | 2 | stack_v2_sparse_classes_30k_train_035051 | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_curuser(self): Test that we can get the currently logged in user
- def test_user_not_logged_in(self): Test that we don't get anything if there's no user logged in | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_curuser(self): Test that we can get the currently logged in user
- def test_user_not_logged_in(self): Test that we don't get anything if there's no user logged in
<|s... | e157630933e93f78c57e43ce9b7f8f61e5dfb23b | <|skeleton|>
class UserTests:
def test_curuser(self):
"""Test that we can get the currently logged in user"""
<|body_0|>
def test_user_not_logged_in(self):
"""Test that we don't get anything if there's no user logged in"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserTests:
def test_curuser(self):
"""Test that we can get the currently logged in user"""
url = reverse('configuration:loggedinuserdetail')
user = User.objects.get(username='api')
self.client.force_authenticate(user=user)
response = self.client.get(url, format='json')
... | the_stack_v2_python_sparse | configuration/tests_user.py | Eising/viconf-backend | train | 0 | |
eac06fed4aca059f4f218b692d313ef35cb27b01 | [
"self.sdict = defaultdict(lambda: defaultdict(int))\nself.cur_search = []\nfor sentence, time in zip(sentences, times):\n for idx in range(1, len(sentence) + 1):\n self.sdict[sentence[:idx]][sentence] = time",
"if c == '#':\n s = ''.join(self.cur_search)\n self.cur_search = []\n for idx in rang... | <|body_start_0|>
self.sdict = defaultdict(lambda: defaultdict(int))
self.cur_search = []
for sentence, time in zip(sentences, times):
for idx in range(1, len(sentence) + 1):
self.sdict[sentence[:idx]][sentence] = time
<|end_body_0|>
<|body_start_1|>
if c == '... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sdict = defaultdi... | stack_v2_sparse_classes_75kplus_train_008134 | 1,459 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021077 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | db64a67869aae4f0e55e78b65a7e04f5bc2e671c | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.sdict = defaultdict(lambda: defaultdict(int))
self.cur_search = []
for sentence, time in zip(sentences, times):
for idx in range(1, len(sentence) +... | the_stack_v2_python_sparse | Questiondir/642.design-search-autocomplete-system/642.design-search-autocomplete-system_109795297.py | cczhong11/Leetcode-contest-code-downloader | train | 0 | |
275c3e554f07a727d948fdc54bb0fdcfa7103c66 | [
"super().__init__()\nassert cell_type in {'LSTM', 'GRU'}, 'Unknown cell type for BiRNN: {}'.format(cell_type)\nrnn_cell = nn.LSTM if cell_type == 'LSTM' else nn.GRU\nself.rnn = rnn_cell(embed_dim, hidden_dim, num_layers, batch_first=True, dropout=dropout, bidirectional=True)\nif embed_dropout is not None:\n if e... | <|body_start_0|>
super().__init__()
assert cell_type in {'LSTM', 'GRU'}, 'Unknown cell type for BiRNN: {}'.format(cell_type)
rnn_cell = nn.LSTM if cell_type == 'LSTM' else nn.GRU
self.rnn = rnn_cell(embed_dim, hidden_dim, num_layers, batch_first=True, dropout=dropout, bidirectional=True)... | Bi-directional LSTM or GRU | BiRNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidde... | stack_v2_sparse_classes_75kplus_train_008135 | 3,213 | permissive | [
{
"docstring": "Args: embed_dim: dimension of input token embeddings hidden_dim: dimensions of hidden states of RNN in each direction. num_layers: number of layers of BiRNN. dropout: the dropout rate. The input is assumed to be before any dropout. cell_type: \"LSTM\" or \"GRU\" embed_dropout: when None, follow ... | 2 | stack_v2_sparse_classes_30k_train_018447 | Implement the Python class `BiRNN` described below.
Class description:
Bi-directional LSTM or GRU
Method signatures and docstrings:
- def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None): A... | Implement the Python class `BiRNN` described below.
Class description:
Bi-directional LSTM or GRU
Method signatures and docstrings:
- def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None): A... | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | <|skeleton|>
class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidde... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiRNN:
"""Bi-directional LSTM or GRU"""
def __init__(self, embed_dim: int, hidden_dim: int, num_layers: int, dropout: float, cell_type: str, embed_dropout: float=None, word_dropout: float=None, locked_dropout: float=None):
"""Args: embed_dim: dimension of input token embeddings hidden_dim: dimens... | the_stack_v2_python_sparse | nsr/model/sentence_encoder.py | GaoSida/Neural-SampleRank | train | 3 |
1be7690b54b5cdd754c9e1a6455449796c7e406c | [
"super(ProbPacConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=1, padding=padding, dilation=1, bias=bias, kernel_type=kernel_type, smooth_kernel_type='none', normalize_kernel=False, shared_filters=shared_filters, filler='uniform', native_impl=False)\nself.weight_normalization = torch.nn.paramet... | <|body_start_0|>
super(ProbPacConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=1, padding=padding, dilation=1, bias=bias, kernel_type=kernel_type, smooth_kernel_type='none', normalize_kernel=False, shared_filters=shared_filters, filler='uniform', native_impl=False)
self.weight_norma... | Implements a probabilistic pixel-adaptive convolution. | ProbPacConv2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbPacConv2d:
"""Implements a probabilistic pixel-adaptive convolution."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PPAC. Args: in_channels: Number of input channels. out_channels: ... | stack_v2_sparse_classes_75kplus_train_008136 | 7,401 | permissive | [
{
"docstring": "Initializes PPAC. Args: in_channels: Number of input channels. out_channels: Number of output channels. kernel_size: Filter size of used kernel. padding: Number of zero padding elements applied at all borders. bias: Usage of bias term. kernel_type: Type of kernel function K. See original PAC for... | 2 | stack_v2_sparse_classes_30k_train_029822 | Implement the Python class `ProbPacConv2d` described below.
Class description:
Implements a probabilistic pixel-adaptive convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False): Initializes PPAC. Ar... | Implement the Python class `ProbPacConv2d` described below.
Class description:
Implements a probabilistic pixel-adaptive convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False): Initializes PPAC. Ar... | 04a8676f5eb96c41ec6b1125c6bcad430218ef30 | <|skeleton|>
class ProbPacConv2d:
"""Implements a probabilistic pixel-adaptive convolution."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PPAC. Args: in_channels: Number of input channels. out_channels: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProbPacConv2d:
"""Implements a probabilistic pixel-adaptive convolution."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PPAC. Args: in_channels: Number of input channels. out_channels: Number of out... | the_stack_v2_python_sparse | src/probabilistic_pac.py | visinf/ppac_refinement | train | 81 |
36d18c044b9c66530ea8e7c65eb6cb34bfe4c8f4 | [
"super().__init__(name=name, unique_id=f'{unique_id}-{description.key}', coordinator=weather_coordinator, description=description)\nself._forecast_mode = forecast_mode\nself._attr_entity_registry_enabled_default = self._forecast_mode == FORECAST_MODE_DAILY",
"forecast = None\nforecasts = self.coordinator.data.get... | <|body_start_0|>
super().__init__(name=name, unique_id=f'{unique_id}-{description.key}', coordinator=weather_coordinator, description=description)
self._forecast_mode = forecast_mode
self._attr_entity_registry_enabled_default = self._forecast_mode == FORECAST_MODE_DAILY
<|end_body_0|>
<|body_st... | Implementation of an AEMET OpenData forecast sensor. | AemetForecastSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def native_val... | stack_v2_sparse_classes_75kplus_train_008137 | 4,096 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription)"
},
{
"docstring": "Return the state of the device.",
"name": "native_value",
... | 2 | null | Implement the Python class `AemetForecastSensor` described below.
Class description:
Implementation of an AEMET OpenData forecast sensor.
Method signatures and docstrings:
- def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription): Initial... | Implement the Python class `AemetForecastSensor` described below.
Class description:
Implementation of an AEMET OpenData forecast sensor.
Method signatures and docstrings:
- def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription): Initial... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def native_val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, weather_coordinator: WeatherUpdateCoordinator, forecast_mode, description: SensorEntityDescription):
"""Initialize the sensor."""
super().__init__(name=name, unique_id=f'{un... | the_stack_v2_python_sparse | homeassistant/components/aemet/sensor.py | AlexxIT/home-assistant | train | 9 |
af6ed47939d17863694b4425c57d80a21f9ded3a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Inference Server GRPC endpoints. | GRPCInferenceServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRPCInferenceServiceServicer:
"""Inference Server GRPC endpoints."""
def ServerLive(self, request, context):
"""Check liveness of the inference server."""
<|body_0|>
def ServerReady(self, request, context):
"""Check readiness of the inference server."""
<... | stack_v2_sparse_classes_75kplus_train_008138 | 10,518 | permissive | [
{
"docstring": "Check liveness of the inference server.",
"name": "ServerLive",
"signature": "def ServerLive(self, request, context)"
},
{
"docstring": "Check readiness of the inference server.",
"name": "ServerReady",
"signature": "def ServerReady(self, request, context)"
},
{
"... | 6 | null | Implement the Python class `GRPCInferenceServiceServicer` described below.
Class description:
Inference Server GRPC endpoints.
Method signatures and docstrings:
- def ServerLive(self, request, context): Check liveness of the inference server.
- def ServerReady(self, request, context): Check readiness of the inference... | Implement the Python class `GRPCInferenceServiceServicer` described below.
Class description:
Inference Server GRPC endpoints.
Method signatures and docstrings:
- def ServerLive(self, request, context): Check liveness of the inference server.
- def ServerReady(self, request, context): Check readiness of the inference... | 07a36f2cacf4eea6ed3ac28436792f31adb04d01 | <|skeleton|>
class GRPCInferenceServiceServicer:
"""Inference Server GRPC endpoints."""
def ServerLive(self, request, context):
"""Check liveness of the inference server."""
<|body_0|>
def ServerReady(self, request, context):
"""Check readiness of the inference server."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRPCInferenceServiceServicer:
"""Inference Server GRPC endpoints."""
def ServerLive(self, request, context):
"""Check liveness of the inference server."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedErr... | the_stack_v2_python_sparse | mlserver/grpc/dataplane_pb2_grpc.py | LiangTsao/MLServer | train | 0 |
5811661e9227cd9bc2355abb8a729aa3e3db981e | [
"payload, user = self.get_payload(request)\nif not payload:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\nif user.profile != 'admin':\n return Response(status=status.HTTP_403_FORBIDDEN)\nvalidator = Validator({'place_code': {'required': True, 'type': 'string'}})\nif not validator.validate(request.da... | <|body_start_0|>
payload, user = self.get_payload(request)
if not payload:
return Response(status=status.HTTP_401_UNAUTHORIZED)
if user.profile != 'admin':
return Response(status=status.HTTP_403_FORBIDDEN)
validator = Validator({'place_code': {'required': True, 't... | Defines the HTTP verbs to parking slot model management. | ParkingSlotApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSlotApi:
"""Defines the HTTP verbs to parking slot model management."""
def post(self, request):
"""Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
... | stack_v2_sparse_classes_75kplus_train_008139 | 7,435 | permissive | [
{
"docstring": "Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Retrieve a list of slots. Parameters ... | 2 | stack_v2_sparse_classes_30k_train_010680 | Implement the Python class `ParkingSlotApi` described below.
Class description:
Defines the HTTP verbs to parking slot model management.
Method signatures and docstrings:
- def post(self, request): Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Respo... | Implement the Python class `ParkingSlotApi` described below.
Class description:
Defines the HTTP verbs to parking slot model management.
Method signatures and docstrings:
- def post(self, request): Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Respo... | d56d365dd840ecd272ce933c26f2d408e01c44c7 | <|skeleton|>
class ParkingSlotApi:
"""Defines the HTTP verbs to parking slot model management."""
def post(self, request):
"""Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParkingSlotApi:
"""Defines the HTTP verbs to parking slot model management."""
def post(self, request):
"""Create a parking slot. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
payload, use... | the_stack_v2_python_sparse | api/views/parking_slot.py | santiagoSSAA/ParkingLot_Back | train | 0 |
fee7606f5e9f9b4afb2eb016c20326e4b19120e6 | [
"configure_logging()\ntry:\n self.config = ResponseBotConfig(*args, **kwargs)\nexcept MissingConfigError as e:\n logging.error(str(e))\n sys.exit()\nself.error_time_log = {}\nself.error_sleep_log = {}",
"logging.info('ResponseBot started')\nhandler_classes = handler_utils.discover_handler_classes(self.co... | <|body_start_0|>
configure_logging()
try:
self.config = ResponseBotConfig(*args, **kwargs)
except MissingConfigError as e:
logging.error(str(e))
sys.exit()
self.error_time_log = {}
self.error_sleep_log = {}
<|end_body_0|>
<|body_start_1|>
... | The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, tweet streamer, etc.) and handle errors if necessary | ResponseBot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseBot:
"""The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, tweet streamer, etc.) and handle errors if... | stack_v2_sparse_classes_75kplus_train_008140 | 3,425 | permissive | [
{
"docstring": "Try to init & configure the bot from configurations read from ``.responsebot`` file, from CLI arguments or from direct call in code :param kwargs: Options for :class:`~responsebot.utils.config_utils.ResponseBotConfig`",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs... | 3 | stack_v2_sparse_classes_30k_train_035731 | Implement the Python class `ResponseBot` described below.
Class description:
The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, twe... | Implement the Python class `ResponseBot` described below.
Class description:
The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, twe... | e224fe5251190f2f4a8901afbd622c411601e86e | <|skeleton|>
class ResponseBot:
"""The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, tweet streamer, etc.) and handle errors if... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResponseBot:
"""The entry point of ResponseBot. :func:`~responsebot.responsebot.ResponseBot.__init__` inits & configures the bot. :func:`~responsebot.responsebot.ResponseBot.start` tries to init the main sub-components (handler discoverer, authenticator, tweet streamer, etc.) and handle errors if necessary"""... | the_stack_v2_python_sparse | responsebot/responsebot.py | openjusticebaltimore/ResponseBot | train | 0 |
d214c48e10421e0d5014368ad970f76ec577805f | [
"super().__init__(**kwargs)\nself.density: float = kwargs.get('density', 1)\nself.specific_heat: float = kwargs.get('specific_heat', 4.184)\nself.min_flow_rate: float = kwargs.get('min_flow_rate', 0)\nself.power: Callable[[float], float] = kwargs.get('power', lambda x: 0)",
"flow_rate = self.min_flow_rate\nif sel... | <|body_start_0|>
super().__init__(**kwargs)
self.density: float = kwargs.get('density', 1)
self.specific_heat: float = kwargs.get('specific_heat', 4.184)
self.min_flow_rate: float = kwargs.get('min_flow_rate', 0)
self.power: Callable[[float], float] = kwargs.get('power', lambda x... | TwoPhaseImmersionCoolerPowerModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoPhaseImmersionCoolerPowerModel:
def __init__(self, **kwargs):
"""Two-Phase Immersion cooling system power consumption model. :param float density: Density of the fluid (in g/cm^3). By default, it is set to 1 (i.e., water). :param float specific_heat: Specific heat of the fluid (in J/g... | stack_v2_sparse_classes_75kplus_train_008141 | 3,314 | permissive | [
{
"docstring": "Two-Phase Immersion cooling system power consumption model. :param float density: Density of the fluid (in g/cm^3). By default, it is set to 1 (i.e., water). :param float specific_heat: Specific heat of the fluid (in J/gK). By default, it is set to 4.184 (i.e., water). :param float t_difference:... | 2 | stack_v2_sparse_classes_30k_train_010877 | Implement the Python class `TwoPhaseImmersionCoolerPowerModel` described below.
Class description:
Implement the TwoPhaseImmersionCoolerPowerModel class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Two-Phase Immersion cooling system power consumption model. :param float density: Density of the f... | Implement the Python class `TwoPhaseImmersionCoolerPowerModel` described below.
Class description:
Implement the TwoPhaseImmersionCoolerPowerModel class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Two-Phase Immersion cooling system power consumption model. :param float density: Density of the f... | cb425605de3341d27ce43fb326b300cb8ac781f6 | <|skeleton|>
class TwoPhaseImmersionCoolerPowerModel:
def __init__(self, **kwargs):
"""Two-Phase Immersion cooling system power consumption model. :param float density: Density of the fluid (in g/cm^3). By default, it is set to 1 (i.e., water). :param float specific_heat: Specific heat of the fluid (in J/g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoPhaseImmersionCoolerPowerModel:
def __init__(self, **kwargs):
"""Two-Phase Immersion cooling system power consumption model. :param float density: Density of the fluid (in g/cm^3). By default, it is set to 1 (i.e., water). :param float specific_heat: Specific heat of the fluid (in J/gK). By default... | the_stack_v2_python_sparse | mercury/plugin/edc/cooler_power.py | greenlsi/mercury_mso_framework | train | 2 | |
72445125dc62c1762c7a47ba5167e6d91faced17 | [
"self.node_dict = {}\nself.freq_dict = collections.defaultdict(DoublyLinkedList)\nself.capacity = capacity\nself.size = 0\nself.min_freq = 0",
"if key not in self.node_dict:\n return -1\nelse:\n node = self.node_dict[key]\n old_cnt = node.cnt\n node.cnt += 1\n self.freq_dict[old_cnt].remove_node(no... | <|body_start_0|>
self.node_dict = {}
self.freq_dict = collections.defaultdict(DoublyLinkedList)
self.capacity = capacity
self.size = 0
self.min_freq = 0
<|end_body_0|>
<|body_start_1|>
if key not in self.node_dict:
return -1
else:
node = s... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_008142 | 2,956 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_val_000341 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | a321d165c6a92552ca283757ea5f57ae509a17c1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.node_dict = {}
self.freq_dict = collections.defaultdict(DoublyLinkedList)
self.capacity = capacity
self.size = 0
self.min_freq = 0
def get(self, key):
""":type key: int :rtype: i... | the_stack_v2_python_sparse | python/460.py | annaiszhou/LC | train | 0 | |
58a306bb434f6c13f88abca8308cba60fdf96cf1 | [
"self.sub = eo_acq_object.sub\nself.md = eo_acq_object.md\nself.logger = eo_acq_object.logger\nself._exptime = exptime\nself._buffertime = 2.0\nif exptime > 0.5:\n nplc = 0.5\nelse:\n nplc = 0.25\nself.navg = int(10)\nnreads = min((exptime + self._buffertime) * 60.0 / nplc / self.navg, max_reads)\nself.nreads... | <|body_start_0|>
self.sub = eo_acq_object.sub
self.md = eo_acq_object.md
self.logger = eo_acq_object.logger
self._exptime = exptime
self._buffertime = 2.0
if exptime > 0.5:
nplc = 0.5
else:
nplc = 0.25
self.navg = int(10)
nr... | Class to handle monitoring photodiode readout. | PhotodiodeReadout | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotodiodeReadout:
"""Class to handle monitoring photodiode readout."""
def __init__(self, exptime, eo_acq_object, max_reads=2048):
"""Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo_acq_object : EOAcquisition object An instance of a subcl... | stack_v2_sparse_classes_75kplus_train_008143 | 23,099 | permissive | [
{
"docstring": "Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo_acq_object : EOAcquisition object An instance of a subclass of EOAcquisition. max_reads : int, optional Maximum number of reads of monitoring photodiode. Default: 2048.",
"name": "__init__",
"sig... | 5 | stack_v2_sparse_classes_30k_train_011911 | Implement the Python class `PhotodiodeReadout` described below.
Class description:
Class to handle monitoring photodiode readout.
Method signatures and docstrings:
- def __init__(self, exptime, eo_acq_object, max_reads=2048): Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo... | Implement the Python class `PhotodiodeReadout` described below.
Class description:
Class to handle monitoring photodiode readout.
Method signatures and docstrings:
- def __init__(self, exptime, eo_acq_object, max_reads=2048): Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo... | f3a31b94a60caf91d67cda99c56368f212f380c9 | <|skeleton|>
class PhotodiodeReadout:
"""Class to handle monitoring photodiode readout."""
def __init__(self, exptime, eo_acq_object, max_reads=2048):
"""Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo_acq_object : EOAcquisition object An instance of a subcl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhotodiodeReadout:
"""Class to handle monitoring photodiode readout."""
def __init__(self, exptime, eo_acq_object, max_reads=2048):
"""Parameters ---------- exptime : float Exposure time in seconds for the frame to be taken. eo_acq_object : EOAcquisition object An instance of a subclass of EOAcqu... | the_stack_v2_python_sparse | python/eo_acquisition.py | lsst-camera-dh/IandT-jobs | train | 3 |
b69b306cec6c483f55ef6f5eada8367b4b519800 | [
"self.mus = mus\nself.sigmas = sigmas\nself.weights = weights / weights.sum() if normalize_weights else weights\nself.tilted = tilted\nself.min_birth = min_birth\nself.fastQ = fastQ\nself._compute_normalizing_constants()",
"Qs = np.zeros(self.mus.shape[0])\nfor i, params in enumerate(zip(self.mus, self.sigmas)):\... | <|body_start_0|>
self.mus = mus
self.sigmas = sigmas
self.weights = weights / weights.sum() if normalize_weights else weights
self.tilted = tilted
self.min_birth = min_birth
self.fastQ = fastQ
self._compute_normalizing_constants()
<|end_body_0|>
<|body_start_1|>
... | Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2. | RGaussianMixture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RGaussianMixture:
"""Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2."""
def __init__(self, mus, sigmas, weights, normalize_weights=True, tilted=True, min_birth=0, fastQ=False):
"""Parameters ---------- mus : array-like, shape = (num_means, 2). Means of e... | stack_v2_sparse_classes_75kplus_train_008144 | 17,403 | no_license | [
{
"docstring": "Parameters ---------- mus : array-like, shape = (num_means, 2). Means of each Gaussian component in mixture. sigmas : array_like, shape = (num_means,). Diagonal entries in covariance matrices of each Gaussian component in mixture. weights: array-like, shape = (num_means,). Non-negative weights o... | 5 | null | Implement the Python class `RGaussianMixture` described below.
Class description:
Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2.
Method signatures and docstrings:
- def __init__(self, mus, sigmas, weights, normalize_weights=True, tilted=True, min_birth=0, fastQ=False): Parameters ------... | Implement the Python class `RGaussianMixture` described below.
Class description:
Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2.
Method signatures and docstrings:
- def __init__(self, mus, sigmas, weights, normalize_weights=True, tilted=True, min_birth=0, fastQ=False): Parameters ------... | 42e3f688ed757a3068e9dbf52abc8141a124bc0c | <|skeleton|>
class RGaussianMixture:
"""Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2."""
def __init__(self, mus, sigmas, weights, normalize_weights=True, tilted=True, min_birth=0, fastQ=False):
"""Parameters ---------- mus : array-like, shape = (num_means, 2). Means of e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RGaussianMixture:
"""Mixture of two-dimensional isotropic Gaussians restricted to a subset of R^2."""
def __init__(self, mus, sigmas, weights, normalize_weights=True, tilted=True, min_birth=0, fastQ=False):
"""Parameters ---------- mus : array-like, shape = (num_means, 2). Means of each Gaussian ... | the_stack_v2_python_sparse | src/build/lib/bayes_tda/intensities.py | coballejr/bayes_tda | train | 3 |
3b190e7412dc2e4ac29d30904af216a2f6bde551 | [
"task_counts = collections.Counter(tasks).values()\nM = max(task_counts)\nMct = task_counts.count(M)\nreturn max(len(tasks), (M - 1) * (N + 1) + Mct)",
"n += 1\nans = 0\nd = collections.Counter(tasks)\nheap = [-c for c in d.values()]\nheapq.heapify(heap)\nwhile heap:\n stack = []\n cnt = 0\n for _ in ran... | <|body_start_0|>
task_counts = collections.Counter(tasks).values()
M = max(task_counts)
Mct = task_counts.count(M)
return max(len(tasks), (M - 1) * (N + 1) + Mct)
<|end_body_0|>
<|body_start_1|>
n += 1
ans = 0
d = collections.Counter(tasks)
heap = [-c for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def _leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
task... | stack_v2_sparse_classes_75kplus_train_008145 | 1,366 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "_leastInterval",
"signature": "def _leastInterval(self, tasks, n)"
}... | 2 | stack_v2_sparse_classes_30k_train_037636 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def _leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def _leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
<|skelet... | 16e8a7935811fa71ce71998da8549e29ba68f847 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def _leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
task_counts = collections.Counter(tasks).values()
M = max(task_counts)
Mct = task_counts.count(M)
return max(len(tasks), (M - 1) * (N + 1) + Mct)
def _leastInterval(s... | the_stack_v2_python_sparse | leetcode7/leastInterval.py | lizyang95/leetcode | train | 0 | |
d1645e45b77fc87e06f1f88679fdc1b52741fd58 | [
"if type(hidden) in (tuple, list):\n return (func(hidden[0], *func_args, **func_kwargs), func(hidden[1], *func_args, **func_kwargs))\nelse:\n return func(hidden, *func_args, **func_kwargs)",
"if type(hidden) == tuple:\n return hidden[0]\nelse:\n return hidden"
] | <|body_start_0|>
if type(hidden) in (tuple, list):
return (func(hidden[0], *func_args, **func_kwargs), func(hidden[1], *func_args, **func_kwargs))
else:
return func(hidden, *func_args, **func_kwargs)
<|end_body_0|>
<|body_start_1|>
if type(hidden) == tuple:
r... | Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap every state inside another iterable. | RNNCompatabilityMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCompatabilityMixin:
"""Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap every state inside another iterable."""
... | stack_v2_sparse_classes_75kplus_train_008146 | 2,240 | no_license | [
{
"docstring": "Ensure compatibility between GRU and LSTM RNNs by applying a function to both the hidden and cell state inside the hidden variable if necessary. Parameters ---------- hidden: AmbiguousHidden Either one hidden state or tuple of hidden and cell state. func: Callable Function being applied to hidde... | 2 | stack_v2_sparse_classes_30k_train_035380 | Implement the Python class `RNNCompatabilityMixin` described below.
Class description:
Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap ev... | Implement the Python class `RNNCompatabilityMixin` described below.
Class description:
Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap ev... | 6443bea8d325fa948e117b32a063e5383db2de14 | <|skeleton|>
class RNNCompatabilityMixin:
"""Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap every state inside another iterable."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNCompatabilityMixin:
"""Define the following operations on hidden variables with a single hidden state or hidden / cell state tuple: map: Apply a function to every every state. select: Only select the actual hidden state, discard the rest. scatter: Wrap every state inside another iterable."""
def map(h... | the_stack_v2_python_sparse | src/utils/compatability.py | Kaleidophon/tenacious-toucan | train | 0 |
e51492f2dd2cad288eff1ca0cc612c448c94d74c | [
"l = [0 for i in range(32)]\nindex = 31\nwhile n != 0:\n l[index] = n % 2\n n = n // 2\n index -= 1\nnumber = 0\nfor i in range(len(l)):\n number += l[i] * 2 ** i\nreturn number",
"num = bin(n)[2:]\nnum = str((32 - len(num)) * '0' + num)[::-1]\nreturn int(num, 2)"
] | <|body_start_0|>
l = [0 for i in range(32)]
index = 31
while n != 0:
l[index] = n % 2
n = n // 2
index -= 1
number = 0
for i in range(len(l)):
number += l[i] * 2 ** i
return number
<|end_body_0|>
<|body_start_1|>
nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_bits(self, n):
"""Generic Style"""
<|body_0|>
def reverse_bits2(self, n):
"""Python Style"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = [0 for i in range(32)]
index = 31
while n != 0:
l[index] ... | stack_v2_sparse_classes_75kplus_train_008147 | 845 | no_license | [
{
"docstring": "Generic Style",
"name": "reverse_bits",
"signature": "def reverse_bits(self, n)"
},
{
"docstring": "Python Style",
"name": "reverse_bits2",
"signature": "def reverse_bits2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022101 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_bits(self, n): Generic Style
- def reverse_bits2(self, n): Python Style | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_bits(self, n): Generic Style
- def reverse_bits2(self, n): Python Style
<|skeleton|>
class Solution:
def reverse_bits(self, n):
"""Generic Style"""
... | b7e92f9a7c4d6652d4901b189f51063ce5520653 | <|skeleton|>
class Solution:
def reverse_bits(self, n):
"""Generic Style"""
<|body_0|>
def reverse_bits2(self, n):
"""Python Style"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse_bits(self, n):
"""Generic Style"""
l = [0 for i in range(32)]
index = 31
while n != 0:
l[index] = n % 2
n = n // 2
index -= 1
number = 0
for i in range(len(l)):
number += l[i] * 2 ** i
... | the_stack_v2_python_sparse | leetcode/easy/reverse_bits.py | abkunal/Data-Structures-and-Algorithms | train | 2 | |
2afd2f4bf803f1c7b94b4dfeaea99c6b90f336a1 | [
"p = super().Params()\np.Define('input_dims', 0, 'Depth of the input to the network.')\np.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')\np.Define('scale', True, 'Whether to use a learned scaling.')\np.Define('bias', True, 'Whether to use bias.')\nreturn p",
"super().create_layer_variables()\np = self.par... | <|body_start_0|>
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')
p.Define('scale', True, 'Whether to use a learned scaling.')
p.Define('bias', True, 'Whether to use bias.')
retur... | Layer normalization. | LayerNorm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerNorm:
"""Layer normalization."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with LayerNorm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates layer normalization variables."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_008148 | 17,959 | permissive | [
{
"docstring": "Returns the layer params with LayerNorm specific params.",
"name": "Params",
"signature": "def Params(cls) -> InstantiableParams"
},
{
"docstring": "Creates layer normalization variables.",
"name": "create_layer_variables",
"signature": "def create_layer_variables(self) -... | 3 | stack_v2_sparse_classes_30k_train_020485 | Implement the Python class `LayerNorm` described below.
Class description:
Layer normalization.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with LayerNorm specific params.
- def create_layer_variables(self) -> None: Creates layer normalization variables.
- def f... | Implement the Python class `LayerNorm` described below.
Class description:
Layer normalization.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with LayerNorm specific params.
- def create_layer_variables(self) -> None: Creates layer normalization variables.
- def f... | c00a74b260fcf6ba11199cc4a340c127d6616479 | <|skeleton|>
class LayerNorm:
"""Layer normalization."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with LayerNorm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates layer normalization variables."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayerNorm:
"""Layer normalization."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with LayerNorm specific params."""
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon', 1e-06, 'Tiny value to guard ... | the_stack_v2_python_sparse | lingvo/jax/layers/normalizations.py | tensorflow/lingvo | train | 2,963 |
2dd896ed0cc23e600ac1bfbc6f8a7cb282f0a84b | [
"stack = [root]\nvals = []\nwhile stack:\n node = stack.pop()\n if isinstance(node, TreeNode):\n stack.extend([node.right, node.val, node.left])\n if isinstance(node, int):\n vals.append(node)\nreturn vals == sorted(list(set(vals)))",
"def dfs(node, left_val, right_val):\n if node is Non... | <|body_start_0|>
stack = [root]
vals = []
while stack:
node = stack.pop()
if isinstance(node, TreeNode):
stack.extend([node.right, node.val, node.left])
if isinstance(node, int):
vals.append(node)
return vals == sorted(l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
<|body_0|>
def isValidBST2(self, root) -> bool:
"""优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永... | stack_v2_sparse_classes_75kplus_train_008149 | 2,518 | no_license | [
{
"docstring": "满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的",
"name": "isValidBST1",
"signature": "def isValidBST1(self, root) -> bool"
},
{
"docstring": "优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永远单调递增。",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_023355 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST1(self, root) -> bool: 满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的
- def isValidBST2(self, root) -> bool: 优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对roo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST1(self, root) -> bool: 满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的
- def isValidBST2(self, root) -> bool: 优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对roo... | f0f4ba0cb91096e55e21b7a2240afbd347187351 | <|skeleton|>
class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
<|body_0|>
def isValidBST2(self, root) -> bool:
"""优化:使用递归判断 对root左边的节点,val值都应该满足大于最小值,并且小于上层节点的最小值, 对root右边的节点,val值都应该满足小于最大值,并且大于上层节点的最大值, 最左边的一条线,永远单调递减, 最右边的一条线,永... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST1(self, root) -> bool:
"""满足二叉树搜索树说明该二叉树的中序遍历是单调递增的 使用栈中序遍历该二叉树,然后看是否是有序的"""
stack = [root]
vals = []
while stack:
node = stack.pop()
if isinstance(node, TreeNode):
stack.extend([node.right, node.val, node.left])
... | the_stack_v2_python_sparse | coding_test/98_isValidBST.py | zhuheng-mark/myDL | train | 2 | |
2956ee1bc27eeae31538da7430d17b310a6bb29d | [
"super().__init__(session, _id, name, server, options)\nmtu = self.session.options.get_int('mtu')\nself.mtu: int = mtu if mtu > 0 else DEFAULT_MTU\nself.brname: Optional[str] = None\nself.linked: dict[CoreInterface, dict[CoreInterface, bool]] = {}\nself.linked_lock: threading.Lock = threading.Lock()",
"iface_id =... | <|body_start_0|>
super().__init__(session, _id, name, server, options)
mtu = self.session.options.get_int('mtu')
self.mtu: int = mtu if mtu > 0 else DEFAULT_MTU
self.brname: Optional[str] = None
self.linked: dict[CoreInterface, dict[CoreInterface, bool]] = {}
self.linked_... | Base class for networks | CoreNetworkBase | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: obj... | stack_v2_sparse_classes_75kplus_train_008150 | 32,238 | permissive | [
{
"docstring": "Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: object name :param server: remote server node will run on, default is None for localhost :param options: options to create node with",
"name": "__init__",
"signature": "def __init__(self,... | 3 | stack_v2_sparse_classes_30k_train_037137 | Implement the Python class `CoreNetworkBase` described below.
Class description:
Base class for networks
Method signatures and docstrings:
- def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None: Create a CoreNetworkBase instance. :param sessi... | Implement the Python class `CoreNetworkBase` described below.
Class description:
Base class for networks
Method signatures and docstrings:
- def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None: Create a CoreNetworkBase instance. :param sessi... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: obj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: object name :par... | the_stack_v2_python_sparse | daemon/core/nodes/base.py | coreemu/core | train | 606 |
d7c4c557f992fae72ee0c2d7f1fc2faf4bf7a3a1 | [
"super().__init__()\nself.level1 = CBR2(3, 16)\nself.sample1 = InputProjectionA(1)\nself.sample2 = InputProjectionA(2)\nself.b1 = BR(16 + 3)\nself.level2_0 = DownSamplerB(16 + 3, 64)\nself.level2 = nn.ModuleList()\nfor i in range(0, p):\n self.level2.append(DilatedParllelResidualBlockB(64, 64))\nself.b2 = BR(128... | <|body_start_0|>
super().__init__()
self.level1 = CBR2(3, 16)
self.sample1 = InputProjectionA(1)
self.sample2 = InputProjectionA(2)
self.b1 = BR(16 + 3)
self.level2_0 = DownSamplerB(16 + 3, 64)
self.level2 = nn.ModuleList()
for i in range(0, p):
... | This class defines the ESPNetX3-C network in the paper | ESPNetX3_Encoder | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPNetX3_Encoder:
"""This class defines the ESPNetX3-C network in the paper"""
def __init__(self, classes=19, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_008151 | 45,316 | permissive | [
{
"docstring": ":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier",
"name": "__init__",
"signature": "def __init__(self, classes=19, p=5, q=3)"
},
{
"docstring": ":param input: Receives the input RGB image :re... | 2 | null | Implement the Python class `ESPNetX3_Encoder` described below.
Class description:
This class defines the ESPNetX3-C network in the paper
Method signatures and docstrings:
- def __init__(self, classes=19, p=5, q=3): :param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth mult... | Implement the Python class `ESPNetX3_Encoder` described below.
Class description:
This class defines the ESPNetX3-C network in the paper
Method signatures and docstrings:
- def __init__(self, classes=19, p=5, q=3): :param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth mult... | 27272e43126a507a6d93b21cd2372f5432f61237 | <|skeleton|>
class ESPNetX3_Encoder:
"""This class defines the ESPNetX3-C network in the paper"""
def __init__(self, classes=19, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ESPNetX3_Encoder:
"""This class defines the ESPNetX3-C network in the paper"""
def __init__(self, classes=19, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
super().__init__()
... | the_stack_v2_python_sparse | model/ESPNetX3.py | Ethan-ye/Efficient-Segmentation-Networks | train | 0 |
4ccd010f6c02d0eb8412624617b03e5630867050 | [
"self.login = None\nself.name = None\nself.surname = None\nself.email = None\nself.active = True\nself.is_user = True\nself.is_responsible = False\nself.is_manager = False\nself.is_tech = False\nself.is_committee = False\nself.is_admin = False\nself.password = None",
"description = task.get_description()\nif 'WIT... | <|body_start_0|>
self.login = None
self.name = None
self.surname = None
self.email = None
self.active = True
self.is_user = True
self.is_responsible = False
self.is_manager = False
self.is_tech = False
self.is_committee = False
self... | Class representing a user which has to be added to the system and doesn't exist yet | TmpUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TmpUser:
"""Class representing a user which has to be added to the system and doesn't exist yet"""
def __init__(self):
"""Init takes no argument"""
<|body_0|>
def from_task(self, task):
"""Takes a task's action string and fill up the properties of TmpUser object ... | stack_v2_sparse_classes_75kplus_train_008152 | 36,510 | no_license | [
{
"docstring": "Init takes no argument",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Takes a task's action string and fill up the properties of TmpUser object :param task: Object. Instance of Task object :return: Object. Instance of TmpUser class",
"name": "from_... | 3 | stack_v2_sparse_classes_30k_train_032255 | Implement the Python class `TmpUser` described below.
Class description:
Class representing a user which has to be added to the system and doesn't exist yet
Method signatures and docstrings:
- def __init__(self): Init takes no argument
- def from_task(self, task): Takes a task's action string and fill up the properti... | Implement the Python class `TmpUser` described below.
Class description:
Class representing a user which has to be added to the system and doesn't exist yet
Method signatures and docstrings:
- def __init__(self): Init takes no argument
- def from_task(self, task): Takes a task's action string and fill up the properti... | bb9a7539487e77b3e6d7e0b82124da438ca0e8ab | <|skeleton|>
class TmpUser:
"""Class representing a user which has to be added to the system and doesn't exist yet"""
def __init__(self):
"""Init takes no argument"""
<|body_0|>
def from_task(self, task):
"""Takes a task's action string and fill up the properties of TmpUser object ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TmpUser:
"""Class representing a user which has to be added to the system and doesn't exist yet"""
def __init__(self):
"""Init takes no argument"""
self.login = None
self.name = None
self.surname = None
self.email = None
self.active = True
self.is_u... | the_stack_v2_python_sparse | base/classes.py | msapunov/Copernicus | train | 0 |
0c59967f1881b5947a4ea1252d63417ebb7b249e | [
"self.matrix = matrix\nself.level = level\nself.f_value = f_value\nself.parent = parent\nself.move = move",
"print(f'Node Level = {self.level}, Node H Value = {self.f_value - self.level}, Node F Value = {self.f_value}\\nNode matrix:')\nfor i in self.matrix:\n for j in i:\n print(j, ' ', end='')\n pri... | <|body_start_0|>
self.matrix = matrix
self.level = level
self.f_value = f_value
self.parent = parent
self.move = move
<|end_body_0|>
<|body_start_1|>
print(f'Node Level = {self.level}, Node H Value = {self.f_value - self.level}, Node F Value = {self.f_value}\nNode matrix... | Class to represent a node | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Class to represent a node"""
def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start'):
"""Parameterized constructor for a node"""
<|body_0|>
def info(self):
"""Prints some information about the node"""
<|... | stack_v2_sparse_classes_75kplus_train_008153 | 7,027 | no_license | [
{
"docstring": "Parameterized constructor for a node",
"name": "__init__",
"signature": "def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start')"
},
{
"docstring": "Prints some information about the node",
"name": "info",
"signature": "def info(... | 4 | stack_v2_sparse_classes_30k_train_047489 | Implement the Python class `Node` described below.
Class description:
Class to represent a node
Method signatures and docstrings:
- def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start'): Parameterized constructor for a node
- def info(self): Prints some information about t... | Implement the Python class `Node` described below.
Class description:
Class to represent a node
Method signatures and docstrings:
- def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start'): Parameterized constructor for a node
- def info(self): Prints some information about t... | 1bc56503e73005fcfda9ce77f139129b0bc97163 | <|skeleton|>
class Node:
"""Class to represent a node"""
def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start'):
"""Parameterized constructor for a node"""
<|body_0|>
def info(self):
"""Prints some information about the node"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
"""Class to represent a node"""
def __init__(self, matrix: Matrix, level: int, f_value: int, parent: Node=None, move: str='Start'):
"""Parameterized constructor for a node"""
self.matrix = matrix
self.level = level
self.f_value = f_value
self.parent = parent
... | the_stack_v2_python_sparse | ai/astar.py | akhilnarang/CollegeStuff | train | 3 |
39b05b5c97884a87c35419ed7a87d304ba9a8f95 | [
"self.cancel_check_conn = None\nprotocol = AsyncTCPMySensorsProtocol\ntransport = AsyncTransport(self, async_connect, protocol=protocol, **kwargs)\nsuper().__init__(transport, *args, **kwargs)",
"try:\n super().check_connection()\nexcept OSError as exc:\n _LOGGER.error(exc)\n self.tasks.transport.protoco... | <|body_start_0|>
self.cancel_check_conn = None
protocol = AsyncTCPMySensorsProtocol
transport = AsyncTransport(self, async_connect, protocol=protocol, **kwargs)
super().__init__(transport, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
super().check_connection... | MySensors async TCP gateway. | AsyncTCPGateway | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncTCPGateway:
"""MySensors async TCP gateway."""
def __init__(self, *args, **kwargs):
"""Set up TCP gateway."""
<|body_0|>
def check_connection(self):
"""Check if connection is alive every reconnect_timeout seconds."""
<|body_1|>
async def get_gat... | stack_v2_sparse_classes_75kplus_train_008154 | 9,517 | permissive | [
{
"docstring": "Set up TCP gateway.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check if connection is alive every reconnect_timeout seconds.",
"name": "check_connection",
"signature": "def check_connection(self)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_036912 | Implement the Python class `AsyncTCPGateway` described below.
Class description:
MySensors async TCP gateway.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set up TCP gateway.
- def check_connection(self): Check if connection is alive every reconnect_timeout seconds.
- async def get_gateway... | Implement the Python class `AsyncTCPGateway` described below.
Class description:
MySensors async TCP gateway.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set up TCP gateway.
- def check_connection(self): Check if connection is alive every reconnect_timeout seconds.
- async def get_gateway... | f7264321986a66193192a10f3261fe268eeb7601 | <|skeleton|>
class AsyncTCPGateway:
"""MySensors async TCP gateway."""
def __init__(self, *args, **kwargs):
"""Set up TCP gateway."""
<|body_0|>
def check_connection(self):
"""Check if connection is alive every reconnect_timeout seconds."""
<|body_1|>
async def get_gat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsyncTCPGateway:
"""MySensors async TCP gateway."""
def __init__(self, *args, **kwargs):
"""Set up TCP gateway."""
self.cancel_check_conn = None
protocol = AsyncTCPMySensorsProtocol
transport = AsyncTransport(self, async_connect, protocol=protocol, **kwargs)
super(... | the_stack_v2_python_sparse | mysensors/gateway_tcp.py | theolind/pymysensors | train | 68 |
5cca21ac0a9d05358377f9d01ffcf0737cce1996 | [
"self.interpolator = interpolator\nself.absorption = absorption\nself.background = background",
"if data is None:\n data = []\nassert 'p' in data or p is not None\nassert 'T' in data or T is not None\nassert 'lnq' in data or lnq is not None\np = np.array(data['p']) if 'p' in data else np.array(p)\nT = np.array... | <|body_start_0|>
self.interpolator = interpolator
self.absorption = absorption
self.background = background
<|end_body_0|>
<|body_start_1|>
if data is None:
data = []
assert 'p' in data or p is not None
assert 'T' in data or T is not None
assert 'lnq'... | Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, i.e vapor + liquid). The .forward method only calculates the brightness ... | MWRTM | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MWRTM:
"""Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, i.e vapor + liquid). The .forward metho... | stack_v2_sparse_classes_75kplus_train_008155 | 7,810 | permissive | [
{
"docstring": "Initialize a radiative transfer model. The interpolator is used to transform quantities from the input to the model grid. The absorption model is used to calculate absorption coefficients from pressure, temperature and total water content. The background temperature is used for the value of brig... | 5 | stack_v2_sparse_classes_30k_train_008287 | Implement the Python class `MWRTM` described below.
Class description:
Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, ... | Implement the Python class `MWRTM` described below.
Class description:
Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, ... | 52918f8452b6459cf19fc43a3103f2e37215fdae | <|skeleton|>
class MWRTM:
"""Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, i.e vapor + liquid). The .forward metho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MWRTM:
"""Microwave radiative transfer model for ground based applications. Default mode of model (using __call__) uses full forward differentiation, providing Jacobians for temperature and humidity (input as the natural logarithm of specific water content, i.e vapor + liquid). The .forward method only calcul... | the_stack_v2_python_sparse | software/mwrt/model.py | chpolste/MScAtmosphericSciences | train | 3 |
9981baaff44d2c5a4e994bc9866d61eb52f65c6d | [
"ret = 0\nsums = defaultdict(int)\nsums[0] += 1\nacc = 0\nfor n in nums:\n acc += n\n for s in sums:\n if (acc - s) % k == 0:\n ret += sums[s]\n sums[acc] += 1\nreturn ret",
"ret = 0\ncnt = [0] * k\ncnt[0] = 1\nacc = 0\nfor n in nums:\n acc += n\n ret += cnt[acc % k]\n cnt[acc ... | <|body_start_0|>
ret = 0
sums = defaultdict(int)
sums[0] += 1
acc = 0
for n in nums:
acc += n
for s in sums:
if (acc - s) % k == 0:
ret += sums[s]
sums[acc] += 1
return ret
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Mar 05, 2023 22:16 TLE"""
<|body_0|>
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Mar 05, 2023 22:20"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = 0
... | stack_v2_sparse_classes_75kplus_train_008156 | 1,821 | no_license | [
{
"docstring": "Mar 05, 2023 22:16 TLE",
"name": "subarraysDivByK",
"signature": "def subarraysDivByK(self, nums: List[int], k: int) -> int"
},
{
"docstring": "Mar 05, 2023 22:20",
"name": "subarraysDivByK",
"signature": "def subarraysDivByK(self, nums: List[int], k: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_026064 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Mar 05, 2023 22:16 TLE
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Mar 05, 2023 22:20 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Mar 05, 2023 22:16 TLE
- def subarraysDivByK(self, nums: List[int], k: int) -> int: Mar 05, 2023 22:20
<|skeleton|>
cl... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Mar 05, 2023 22:16 TLE"""
<|body_0|>
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Mar 05, 2023 22:20"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
"""Mar 05, 2023 22:16 TLE"""
ret = 0
sums = defaultdict(int)
sums[0] += 1
acc = 0
for n in nums:
acc += n
for s in sums:
if (acc - s) % k == 0:
... | the_stack_v2_python_sparse | leetcode/solved/1016_Subarray_Sums_Divisible_by_K/solution.py | sungminoh/algorithms | train | 0 | |
ec91a38dd820bf812318970d298c6e73bf9cbb2e | [
"try:\n vtp_output = abstract.parser.show_vtp.ShowVtpStatus(device=uut).parse()\n if vtp_output['vtp']['enabled']:\n method = 'conf'\nexcept:\n pass\nself.method = method\nif 'conf' not in self.method:\n self.lib = abstract.sdk.libs.abstrtacted_libs.restore.Restore()\n try:\n self.lib.s... | <|body_start_0|>
try:
vtp_output = abstract.parser.show_vtp.ShowVtpStatus(device=uut).parse()
if vtp_output['vtp']['enabled']:
method = 'conf'
except:
pass
self.method = method
if 'conf' not in self.method:
self.lib = abstra... | Trigger class for UnconfigConfig action | TriggerUnconfigConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerUnconfigConfig:
"""Trigger class for UnconfigConfig action"""
def save_configuration(self, uut, method, abstract, steps):
"""Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS) Args: uut (`obj`): Device object. method (`str`): Save m... | stack_v2_sparse_classes_75kplus_train_008157 | 2,656 | permissive | [
{
"docstring": "Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS) Args: uut (`obj`): Device object. method (`str`): Save method from trigger datafile. Only accpet \"local\" and \"checkpoint\" Returns: None Raises: pyATS Results",
"name": "save_configuration",
... | 2 | null | Implement the Python class `TriggerUnconfigConfig` described below.
Class description:
Trigger class for UnconfigConfig action
Method signatures and docstrings:
- def save_configuration(self, uut, method, abstract, steps): Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS)... | Implement the Python class `TriggerUnconfigConfig` described below.
Class description:
Trigger class for UnconfigConfig action
Method signatures and docstrings:
- def save_configuration(self, uut, method, abstract, steps): Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS)... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerUnconfigConfig:
"""Trigger class for UnconfigConfig action"""
def save_configuration(self, uut, method, abstract, steps):
"""Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS) Args: uut (`obj`): Device object. method (`str`): Save m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TriggerUnconfigConfig:
"""Trigger class for UnconfigConfig action"""
def save_configuration(self, uut, method, abstract, steps):
"""Save current configuration Can be either done via TFTP or checkpoint feature (If exists for OS) Args: uut (`obj`): Device object. method (`str`): Save method from tr... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/unconfigconfig/vlan/unconfigconfig.py | CiscoTestAutomation/genielibs | train | 109 |
7429562c02ebe41371bec9ee1645ab56392bc9db | [
"super().__init__()\nd_k = d_v = d_model // n_heads\nself.n_heads, self.d_k, self.d_v = (n_heads, d_k, d_v)\nself.W_Q = nn.Linear(d_model, d_k * n_heads, bias=qkv_bias)\nself.W_K = nn.Linear(d_model, d_k * n_heads, bias=qkv_bias)\nself.W_V = nn.Linear(d_model, d_v * n_heads, bias=qkv_bias)\nself.res_attention = res... | <|body_start_0|>
super().__init__()
d_k = d_v = d_model // n_heads
self.n_heads, self.d_k, self.d_v = (n_heads, d_k, d_v)
self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=qkv_bias)
self.W_K = nn.Linear(d_model, d_k * n_heads, bias=qkv_bias)
self.W_V = nn.Linear(d_model, ... | _MultiheadAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _MultiheadAttention:
def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True):
"""Multi Head Attention Layer"""
<|body_0|>
def forward(self, Q: Tensor, K: Optional[Tensor]=None, V: Optional[Tensor]=None,... | stack_v2_sparse_classes_75kplus_train_008158 | 19,902 | permissive | [
{
"docstring": "Multi Head Attention Layer",
"name": "__init__",
"signature": "def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True)"
},
{
"docstring": "Args: Q: [batch_size (bs) x max_q_len x d_model] K, V: [batch_size (... | 2 | null | Implement the Python class `_MultiheadAttention` described below.
Class description:
Implement the _MultiheadAttention class.
Method signatures and docstrings:
- def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True): Multi Head Attention Layer... | Implement the Python class `_MultiheadAttention` described below.
Class description:
Implement the _MultiheadAttention class.
Method signatures and docstrings:
- def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True): Multi Head Attention Layer... | 06ab2a9c6870b311fa0efe4cb3fc4df0009d1965 | <|skeleton|>
class _MultiheadAttention:
def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True):
"""Multi Head Attention Layer"""
<|body_0|>
def forward(self, Q: Tensor, K: Optional[Tensor]=None, V: Optional[Tensor]=None,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _MultiheadAttention:
def __init__(self, d_model, n_heads, d_k=None, d_v=None, res_attention=False, attn_dropout=0.0, proj_dropout=0.0, qkv_bias=True):
"""Multi Head Attention Layer"""
super().__init__()
d_k = d_v = d_model // n_heads
self.n_heads, self.d_k, self.d_v = (n_heads,... | the_stack_v2_python_sparse | tsai/models/PatchTST.py | timeseriesAI/tsai | train | 3,526 | |
c55115cbdfedee65b12683debb025d43596f4d7f | [
"is_merchant = self.checkout_session.is_merchant_address()\nif is_merchant or shipping_addr.country.iso_3166_1_a2 != 'US':\n try:\n user_addr = user.addresses.get(hash=shipping_addr.generate_hash())\n except ObjectDoesNotExist:\n user_addr = UserAddress(user=user)\n user_addr.is_merchant ... | <|body_start_0|>
is_merchant = self.checkout_session.is_merchant_address()
if is_merchant or shipping_addr.country.iso_3166_1_a2 != 'US':
try:
user_addr = user.addresses.get(hash=shipping_addr.generate_hash())
except ObjectDoesNotExist:
user_addr =... | OrderPlacementMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderPlacementMixin:
def update_address_book(self, user, shipping_addr):
"""extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We don't save US addresses in address book as we don't allow shipments within the US anymore"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_008159 | 2,234 | no_license | [
{
"docstring": "extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We don't save US addresses in address book as we don't allow shipments within the US anymore",
"name": "update_address_book",
"signature": "def update_address_book(self, user, shipping_addr... | 2 | stack_v2_sparse_classes_30k_train_004110 | Implement the Python class `OrderPlacementMixin` described below.
Class description:
Implement the OrderPlacementMixin class.
Method signatures and docstrings:
- def update_address_book(self, user, shipping_addr): extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We do... | Implement the Python class `OrderPlacementMixin` described below.
Class description:
Implement the OrderPlacementMixin class.
Method signatures and docstrings:
- def update_address_book(self, user, shipping_addr): extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We do... | 8c3286e9a7da8f4ae0401a81c8037585b3bb7ba6 | <|skeleton|>
class OrderPlacementMixin:
def update_address_book(self, user, shipping_addr):
"""extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We don't save US addresses in address book as we don't allow shipments within the US anymore"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderPlacementMixin:
def update_address_book(self, user, shipping_addr):
"""extend Oscar functionality by setting the is_merchant attribute based on the data saved in session We don't save US addresses in address book as we don't allow shipments within the US anymore"""
is_merchant = self.chec... | the_stack_v2_python_sparse | apps/checkout/mixins.py | embedded1/django-package-forwarding | train | 0 | |
4b3edcd6fafe2174ab0f19bb94e4d075b116fbe7 | [
"super(ranker, self).__init__()\nself.scoring_function = scoring_function\nself.all_kb = all_kb\nself.knowns_o = {}\nself.knowns_s = {}\nfor fact in self.all_kb.facts:\n if (fact[0], fact[1]) not in self.knowns_o:\n self.knowns_o[fact[0], fact[1]] = set()\n self.knowns_o[fact[0], fact[1]].add(fact[2])\... | <|body_start_0|>
super(ranker, self).__init__()
self.scoring_function = scoring_function
self.all_kb = all_kb
self.knowns_o = {}
self.knowns_s = {}
for fact in self.all_kb.facts:
if (fact[0], fact[1]) not in self.knowns_o:
self.knowns_o[fact[0]... | A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.py | ranker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ranker:
"""A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.py"""
def __init__(self, scoring_f... | stack_v2_sparse_classes_75kplus_train_008160 | 11,823 | no_license | [
{
"docstring": "The initializer :param scoring_function: The model function to used to rank the entities :param all_kb: A union of all the knowledge bases (train/test/valid)",
"name": "__init__",
"signature": "def __init__(self, scoring_function, all_kb)"
},
{
"docstring": "computes and returns ... | 3 | stack_v2_sparse_classes_30k_train_021213 | Implement the Python class `ranker` described below.
Class description:
A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.... | Implement the Python class `ranker` described below.
Class description:
A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.... | 81e6f1ea24968303a6c426f704228e8618966f6a | <|skeleton|>
class ranker:
"""A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.py"""
def __init__(self, scoring_f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ranker:
"""A network that ranks entities based on a scoring function. It excludes entities that have already been seen in any kb to compute the ranking as in ####### cite paper here ########. It can be constructed from any scoring function/model from models.py"""
def __init__(self, scoring_function, all_... | the_stack_v2_python_sparse | combined/type_complex/evaluate.py | YerayL/IterefinE | train | 0 |
de2c1fb080b40559cac5fdb6710e8ec24bbf8ef3 | [
"assert sr > 9000, 'Sampling rate too low!'\nself.gbank = Gammatone(sr, num_chan, (130.0, 4500.0))\nself.gammawgt = self.gbank.gammawgt(nfft)\n\ndef _stft(sig):\n return stft(sig, wind, hop, nfft, synth=True, zphase=True)\n\ndef _istft(spec):\n return istft(spec, wind, hop, nfft, zphase=True)\nself.stft = _st... | <|body_start_0|>
assert sr > 9000, 'Sampling rate too low!'
self.gbank = Gammatone(sr, num_chan, (130.0, 4500.0))
self.gammawgt = self.gbank.gammawgt(nfft)
def _stft(sig):
return stft(sig, wind, hop, nfft, synth=True, zphase=True)
def _istft(spec):
retur... | Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference of the International Speech Communication Association. 2010. See Also -------- ... | SSFEnhancer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSFEnhancer:
"""Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference of the International Speech Communicatio... | stack_v2_sparse_classes_75kplus_train_008161 | 19,410 | permissive | [
{
"docstring": "Instantiate an SSF enhancer. Parameters ---------- sr: int Sampling rate in Hz. wind: numpy.ndarray Window function. hop: float Hop fraction. nfft: int Number of DFT points. Keyword Parameters ------------------ num_chan: int, 40 Number of channels in the Gammatone filterbank. ptype: int, 2 SSF ... | 2 | stack_v2_sparse_classes_30k_train_022257 | Implement the Python class `SSFEnhancer` described below.
Class description:
Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference o... | Implement the Python class `SSFEnhancer` described below.
Class description:
Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference o... | 740139490208ca7605e9b520f1a28214fa3903dc | <|skeleton|>
class SSFEnhancer:
"""Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference of the International Speech Communicatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSFEnhancer:
"""Suppression of Slowly-varying components and the Falling edge. This implementation follows paper by Kim and Stern: Kim, Chanwoo, and Richard M. Stern."Nonlinear enhancement of onset for robust speech recognition." Eleventh Annual Conference of the International Speech Communication Association... | the_stack_v2_python_sparse | audlib/enhance.py | templeblock/pyaudlib | train | 0 |
27b208530fe66ec69778041938d149358e55ea0e | [
"TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)\nself.data = []\nself.parse_data()",
"inserts = 0\nfor sect in self.data:\n for ts in sect['data']:\n if not sect['data'][ts]:\n continue\n fst = f\"INSERT into t{sect['initts'].year} (station, model, runtime, ftim... | <|body_start_0|>
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = []
self.parse_data()
<|end_body_0|>
<|body_start_1|>
inserts = 0
for sect in self.data:
for ts in sect['data']:
if not sect['data'][ts]:
... | Represents a Model Output Statistics file | MOSProduct | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MOSProduct:
"""Represents a Model Output Statistics file"""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Persist our data to the database Args: txn: Database cursor Returns: int... | stack_v2_sparse_classes_75kplus_train_008162 | 6,041 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None)"
},
{
"docstring": "Persist our data to the database Args: txn: Database cursor Returns: int number of inserts made to the database",
"name": "sql",
... | 3 | stack_v2_sparse_classes_30k_train_018389 | Implement the Python class `MOSProduct` described below.
Class description:
Represents a Model Output Statistics file
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Persist our data to the database Args: txn: Databas... | Implement the Python class `MOSProduct` described below.
Class description:
Represents a Model Output Statistics file
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Persist our data to the database Args: txn: Databas... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class MOSProduct:
"""Represents a Model Output Statistics file"""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Persist our data to the database Args: txn: Database cursor Returns: int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MOSProduct:
"""Represents a Model Output Statistics file"""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = []
self.parse_data()
def sql... | the_stack_v2_python_sparse | src/pyiem/nws/products/mos.py | akrherz/pyIEM | train | 38 |
ba4dc2412b533cf212530b1270fac3ada2303f4b | [
"self.robot = hsrb_interface.Robot()\nself.rgbd_map = RGBD2Map()\nself.omni_base = self.robot.get('omni_base')\nself.whole_body = self.robot.get('whole_body')\nself.side = 'BOTTOM'\nself.cam = RGBD()\nself.com = COM()\nself.com.go_to_initial_state(self.whole_body)\nself.grasp_count = 0\nself.br = tf.TransformBroadc... | <|body_start_0|>
self.robot = hsrb_interface.Robot()
self.rgbd_map = RGBD2Map()
self.omni_base = self.robot.get('omni_base')
self.whole_body = self.robot.get('whole_body')
self.side = 'BOTTOM'
self.cam = RGBD()
self.com = COM()
self.com.go_to_initial_state... | CollectData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectData:
def __init__(self):
"""Class to run HSR lego task"""
<|body_0|>
def collect_data(self):
"""Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this "for ... | stack_v2_sparse_classes_75kplus_train_008163 | 5,598 | no_license | [
{
"docstring": "Class to run HSR lego task",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this \"for real\".",
... | 2 | stack_v2_sparse_classes_30k_train_017621 | Implement the Python class `CollectData` described below.
Class description:
Implement the CollectData class.
Method signatures and docstrings:
- def __init__(self): Class to run HSR lego task
- def collect_data(self): Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and t... | Implement the Python class `CollectData` described below.
Class description:
Implement the CollectData class.
Method signatures and docstrings:
- def __init__(self): Class to run HSR lego task
- def collect_data(self): Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and t... | 0f183702d6cfb56e3811a9acff92ce6d1829eaf8 | <|skeleton|>
class CollectData:
def __init__(self):
"""Class to run HSR lego task"""
<|body_0|>
def collect_data(self):
"""Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this "for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollectData:
def __init__(self):
"""Class to run HSR lego task"""
self.robot = hsrb_interface.Robot()
self.rgbd_map = RGBD2Map()
self.omni_base = self.robot.get('omni_base')
self.whole_body = self.robot.get('whole_body')
self.side = 'BOTTOM'
self.cam = R... | the_stack_v2_python_sparse | quick_img_collection/get_hsr_imgs.py | BerkeleyAutomation/siemens_challenge | train | 6 | |
446f93db141f6f425732417fb84e211bbd69465d | [
"super().__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enc_output = self.encoder(inputs, training, encoder_mask)\ndec_output, atten... | <|body_start_0|>
super().__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_start_1|>
... | class Transform | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""class Transform"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""* N - the number of blocks in the encoder and decoder * dm - the dimensionality of the model * h - the number of heads * hidden - the n... | stack_v2_sparse_classes_75kplus_train_008164 | 18,002 | no_license | [
{
"docstring": "* N - the number of blocks in the encoder and decoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layers * input_vocab - the size of the input vocabulary * target_vocab - the size of the target vocabulary * max_seq... | 2 | stack_v2_sparse_classes_30k_test_001111 | Implement the Python class `Transformer` described below.
Class description:
class Transform
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): * N - the number of blocks in the encoder and decoder * dm - the dimensionalit... | Implement the Python class `Transformer` described below.
Class description:
class Transform
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): * N - the number of blocks in the encoder and decoder * dm - the dimensionalit... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class Transformer:
"""class Transform"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""* N - the number of blocks in the encoder and decoder * dm - the dimensionality of the model * h - the number of heads * hidden - the n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer:
"""class Transform"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""* N - the number of blocks in the encoder and decoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidd... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
3e9a11b314f396c010b3ca092bef9140e11d9d02 | [
"embedded_DataSet = []\nfor book in books:\n clean_book = Embedding.Embedding.clean_str(book)\n splited_word = clean_book.split()\n emb_Data = Embedding.Embedding.AraVec(splited_word, embedding_dimension)\n emb_Data = emb_Data.astype(dtype='f')\n for i in range(0, len(emb_Data), tweet_size):\n ... | <|body_start_0|>
embedded_DataSet = []
for book in books:
clean_book = Embedding.Embedding.clean_str(book)
splited_word = clean_book.split()
emb_Data = Embedding.Embedding.AraVec(splited_word, embedding_dimension)
emb_Data = emb_Data.astype(dtype='f')
... | Embedd_DataSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedd_DataSet:
def embedd_Aravec(books: [str], tweet_size: int, embedding_dimension=100, epselon=0.001) -> [[[[int]]]]:
"""Take the data and return the embedded result using AraVec The Embedding is applied at each book as one (word by word), and then the results of the embedding are div... | stack_v2_sparse_classes_75kplus_train_008165 | 3,312 | no_license | [
{
"docstring": "Take the data and return the embedded result using AraVec The Embedding is applied at each book as one (word by word), and then the results of the embedding are divided into tweets and each tweet in size of tweet size words :parameter books:[str] array of books text tweet_size:int tweet size in ... | 2 | null | Implement the Python class `Embedd_DataSet` described below.
Class description:
Implement the Embedd_DataSet class.
Method signatures and docstrings:
- def embedd_Aravec(books: [str], tweet_size: int, embedding_dimension=100, epselon=0.001) -> [[[[int]]]]: Take the data and return the embedded result using AraVec The... | Implement the Python class `Embedd_DataSet` described below.
Class description:
Implement the Embedd_DataSet class.
Method signatures and docstrings:
- def embedd_Aravec(books: [str], tweet_size: int, embedding_dimension=100, epselon=0.001) -> [[[[int]]]]: Take the data and return the embedded result using AraVec The... | c7349dd0501e9a0d47a8f1024762ee15b225c6e0 | <|skeleton|>
class Embedd_DataSet:
def embedd_Aravec(books: [str], tweet_size: int, embedding_dimension=100, epselon=0.001) -> [[[[int]]]]:
"""Take the data and return the embedded result using AraVec The Embedding is applied at each book as one (word by word), and then the results of the embedding are div... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedd_DataSet:
def embedd_Aravec(books: [str], tweet_size: int, embedding_dimension=100, epselon=0.001) -> [[[[int]]]]:
"""Take the data and return the embedded result using AraVec The Embedding is applied at each book as one (word by word), and then the results of the embedding are divided into twee... | the_stack_v2_python_sparse | Algs/Embedd_DataSet.py | saleems11/Final_Project_B | train | 0 | |
2dd75df93e391e19156a825341b9076c9baaae10 | [
"self.index = 0\nself.A = A\nself.len_a = len(A)",
"for i in range(self.index, self.len_a, 2):\n mask = n - self.A[i]\n if mask > 0:\n n = mask\n self.index = i + 2\n continue\n elif mask < 0:\n self.A[i] -= n\n self.index = i\n return self.A[i + 1]\n else:\n ... | <|body_start_0|>
self.index = 0
self.A = A
self.len_a = len(A)
<|end_body_0|>
<|body_start_1|>
for i in range(self.index, self.len_a, 2):
mask = n - self.A[i]
if mask > 0:
n = mask
self.index = i + 2
continue
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.index = 0
self.A = A
self.len_a = len(A)
<|end_body_0|>
<|bo... | stack_v2_sparse_classes_75kplus_train_008166 | 1,420 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003430 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 4292e531854f0a2d25699a2fc1e029bb4d7ac61f | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.index = 0
self.A = A
self.len_a = len(A)
def next(self, n):
""":type n: int :rtype: int"""
for i in range(self.index, self.len_a, 2):
mask = n - self.A[i]
if mask > 0:... | the_stack_v2_python_sparse | lc900.py | Azureki/LeetCode | train | 0 | |
01c8185e8947c68bdb314c0389e2b864ed05855b | [
"if isinstance(string, str) and isinstance(target_array, list):\n return string in target_array\nelse:\n raise ValueError('wrong type')",
"print('string', string)\nprint('pattern_array', pattern_array)\nif isinstance(pattern_array, str):\n pattern_array[0] = pattern_array\nfor pattern in pattern_array:\n... | <|body_start_0|>
if isinstance(string, str) and isinstance(target_array, list):
return string in target_array
else:
raise ValueError('wrong type')
<|end_body_0|>
<|body_start_1|>
print('string', string)
print('pattern_array', pattern_array)
if isinstance(... | 进行字符串匹配 | StringInArrayComparison | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringInArrayComparison:
"""进行字符串匹配"""
def is_in(self, string, target_array):
"""严格匹配 :param string: :param target_array: :return:"""
<|body_0|>
def is_any_regular_match(self, string, pattern_array):
"""字符串满足列表中任意一个元素的正则匹配 :param string: 字符串(不能是正则) :param pattern... | stack_v2_sparse_classes_75kplus_train_008167 | 7,596 | no_license | [
{
"docstring": "严格匹配 :param string: :param target_array: :return:",
"name": "is_in",
"signature": "def is_in(self, string, target_array)"
},
{
"docstring": "字符串满足列表中任意一个元素的正则匹配 :param string: 字符串(不能是正则) :param pattern_array: 正则表达式的列表 :return:",
"name": "is_any_regular_match",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_053048 | Implement the Python class `StringInArrayComparison` described below.
Class description:
进行字符串匹配
Method signatures and docstrings:
- def is_in(self, string, target_array): 严格匹配 :param string: :param target_array: :return:
- def is_any_regular_match(self, string, pattern_array): 字符串满足列表中任意一个元素的正则匹配 :param string: 字符串(... | Implement the Python class `StringInArrayComparison` described below.
Class description:
进行字符串匹配
Method signatures and docstrings:
- def is_in(self, string, target_array): 严格匹配 :param string: :param target_array: :return:
- def is_any_regular_match(self, string, pattern_array): 字符串满足列表中任意一个元素的正则匹配 :param string: 字符串(... | 228802c69a26b6e72694dcecf84d25083e938a44 | <|skeleton|>
class StringInArrayComparison:
"""进行字符串匹配"""
def is_in(self, string, target_array):
"""严格匹配 :param string: :param target_array: :return:"""
<|body_0|>
def is_any_regular_match(self, string, pattern_array):
"""字符串满足列表中任意一个元素的正则匹配 :param string: 字符串(不能是正则) :param pattern... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringInArrayComparison:
"""进行字符串匹配"""
def is_in(self, string, target_array):
"""严格匹配 :param string: :param target_array: :return:"""
if isinstance(string, str) and isinstance(target_array, list):
return string in target_array
else:
raise ValueError('wrong ... | the_stack_v2_python_sparse | app/auth/abac.py | zhujinhe/myops | train | 4 |
2156c6cf2f31037ac062f41684e259d63f1978f9 | [
"InspectorPage.__init__(self, *args, **kwargs)\nlabel = wx.StaticText(self, -1, 'URI')\ntext = wx.TextCtrl(self, -1, '', style=wx.TE_READONLY)\nself.uri_text = text\nh_sizer = wx.BoxSizer(wx.HORIZONTAL)\nh_sizer.Add(label, 0, wx.EXPAND | wx.ALL, 0)\nh_sizer.Add(text, 1, wx.EXPAND | wx.ALL, 0)\nself.sizer.Add(h_size... | <|body_start_0|>
InspectorPage.__init__(self, *args, **kwargs)
label = wx.StaticText(self, -1, 'URI')
text = wx.TextCtrl(self, -1, '', style=wx.TE_READONLY)
self.uri_text = text
h_sizer = wx.BoxSizer(wx.HORIZONTAL)
h_sizer.Add(label, 0, wx.EXPAND | wx.ALL, 0)
h_si... | Datasource inspector page. | DatasourceInspectorPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasourceInspectorPage:
"""Datasource inspector page."""
def __init__(self, *args, **kwargs):
"""Initializer."""
<|body_0|>
def update(self):
"""Update UI."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
InspectorPage.__init__(self, *args, **kw... | stack_v2_sparse_classes_75kplus_train_008168 | 1,433 | no_license | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Update UI.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052791 | Implement the Python class `DatasourceInspectorPage` described below.
Class description:
Datasource inspector page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializer.
- def update(self): Update UI. | Implement the Python class `DatasourceInspectorPage` described below.
Class description:
Datasource inspector page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializer.
- def update(self): Update UI.
<|skeleton|>
class DatasourceInspectorPage:
"""Datasource inspector page."""
... | 016515772e3ca4d9e59319450fc7a13668f00d11 | <|skeleton|>
class DatasourceInspectorPage:
"""Datasource inspector page."""
def __init__(self, *args, **kwargs):
"""Initializer."""
<|body_0|>
def update(self):
"""Update UI."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasourceInspectorPage:
"""Datasource inspector page."""
def __init__(self, *args, **kwargs):
"""Initializer."""
InspectorPage.__init__(self, *args, **kwargs)
label = wx.StaticText(self, -1, 'URI')
text = wx.TextCtrl(self, -1, '', style=wx.TE_READONLY)
self.uri_te... | the_stack_v2_python_sparse | ec4vis/inspector/datasource/page.py | ecell/ecell4-vis | train | 0 |
efae1a9e376c3011676daf83a65c3c31f155c398 | [
"d = odict()\nfor name, field in self.items():\n d[name] = field._dump()\nreturn d",
"d = odict()\nfor name, field in self.items():\n if field.may_store_entities:\n d[name] = field._entities_in_value()\nreturn d",
"for name, field in other.iteritems():\n if name in self:\n f = self[name]\... | <|body_start_0|>
d = odict()
for name, field in self.items():
d[name] = field._dump()
return d
<|end_body_0|>
<|body_start_1|>
d = odict()
for name, field in self.items():
if field.may_store_entities:
d[name] = field._entities_in_value()
... | Field Mapping based on Ordered Dictionary. | FieldMap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
<|body_0|>
def related_entity_map(self):
"""Return a dictionary of field_name:related_entity_set pairs."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_008169 | 7,952 | permissive | [
{
"docstring": "Return a dictionary of field_name:dumped_value pairs.",
"name": "dump_map",
"signature": "def dump_map(self)"
},
{
"docstring": "Return a dictionary of field_name:related_entity_set pairs.",
"name": "related_entity_map",
"signature": "def related_entity_map(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_026350 | Implement the Python class `FieldMap` described below.
Class description:
Field Mapping based on Ordered Dictionary.
Method signatures and docstrings:
- def dump_map(self): Return a dictionary of field_name:dumped_value pairs.
- def related_entity_map(self): Return a dictionary of field_name:related_entity_set pairs.... | Implement the Python class `FieldMap` described below.
Class description:
Field Mapping based on Ordered Dictionary.
Method signatures and docstrings:
- def dump_map(self): Return a dictionary of field_name:dumped_value pairs.
- def related_entity_map(self): Return a dictionary of field_name:related_entity_set pairs.... | d57a41f8b7b514ed48dc0164dcd3412a89e9873b | <|skeleton|>
class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
<|body_0|>
def related_entity_map(self):
"""Return a dictionary of field_name:related_entity_set pairs."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
d = odict()
for name, field in self.items():
d[name] = field._dump()
return d
def related_entity_map(self):
"... | the_stack_v2_python_sparse | schevo/fieldspec.py | Schevo/schevo | train | 2 |
1b7f5c10e17ded528c8279bfebf64598af2700d9 | [
"cart = utils.get_or_create_cart(request)\ncart.update(request)\nreturn self.render_to_response({'cart': cart})",
"if self.data.get('pk'):\n item_instance = get_object_or_404(core_models.Offer, pk=int(self.data.get('pk')))\nelif self.data.get('slug'):\n item_instance = get_object_or_404(core_models.Offer, s... | <|body_start_0|>
cart = utils.get_or_create_cart(request)
cart.update(request)
return self.render_to_response({'cart': cart})
<|end_body_0|>
<|body_start_1|>
if self.data.get('pk'):
item_instance = get_object_or_404(core_models.Offer, pk=int(self.data.get('pk')))
eli... | Handle CartItem-related operations. | CartItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartItem:
"""Handle CartItem-related operations."""
def get(self, request, *args, **kwargs):
"""Simply render cart tag."""
<|body_0|>
def put(self, *args, **kwargs):
"""Add a new item to the cart with optional `quantity` (defaults to 1)."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008170 | 3,988 | permissive | [
{
"docstring": "Simply render cart tag.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Add a new item to the cart with optional `quantity` (defaults to 1).",
"name": "put",
"signature": "def put(self, *args, **kwargs)"
},
{
"docstring":... | 3 | null | Implement the Python class `CartItem` described below.
Class description:
Handle CartItem-related operations.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Simply render cart tag.
- def put(self, *args, **kwargs): Add a new item to the cart with optional `quantity` (defaults to 1).
- de... | Implement the Python class `CartItem` described below.
Class description:
Handle CartItem-related operations.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Simply render cart tag.
- def put(self, *args, **kwargs): Add a new item to the cart with optional `quantity` (defaults to 1).
- de... | 84c4fa10aefbd792a956cef3d727623ca78cb5fd | <|skeleton|>
class CartItem:
"""Handle CartItem-related operations."""
def get(self, request, *args, **kwargs):
"""Simply render cart tag."""
<|body_0|>
def put(self, *args, **kwargs):
"""Add a new item to the cart with optional `quantity` (defaults to 1)."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartItem:
"""Handle CartItem-related operations."""
def get(self, request, *args, **kwargs):
"""Simply render cart tag."""
cart = utils.get_or_create_cart(request)
cart.update(request)
return self.render_to_response({'cart': cart})
def put(self, *args, **kwargs):
... | the_stack_v2_python_sparse | market/checkout/views/cart.py | katomaso/django-market | train | 0 |
0de297d4598a3d0beab37f98951daeb01570ddde | [
"received_1st_or_2nd_person, received_3rd_person = pronouns.pronoun_to_viewpoints(pronoun)\nself.assertEqual(expected_1st_or_2nd_person, received_1st_or_2nd_person)\nself.assertEqual(expected_3rd_person, received_3rd_person)",
"received_1st_or_2nd_person, received_3rd_person = pronouns.pronoun_to_viewpoints(prono... | <|body_start_0|>
received_1st_or_2nd_person, received_3rd_person = pronouns.pronoun_to_viewpoints(pronoun)
self.assertEqual(expected_1st_or_2nd_person, received_1st_or_2nd_person)
self.assertEqual(expected_3rd_person, received_3rd_person)
<|end_body_0|>
<|body_start_1|>
received_1st_or_... | Test pronoun viewpoint mapping | TestPronounMapping | [
"GPL-2.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPronounMapping:
"""Test pronoun viewpoint mapping"""
def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person):
"""Test the pronoun mapper."""
<|body_0|>
def test_mapping_with_options(self, pronoun, options, expected_1st_or_2nd_person, ... | stack_v2_sparse_classes_75kplus_train_008171 | 10,493 | permissive | [
{
"docstring": "Test the pronoun mapper.",
"name": "test_default_mapping",
"signature": "def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person)"
},
{
"docstring": "Test the pronoun mapper.",
"name": "test_mapping_with_options",
"signature": "def test_map... | 3 | stack_v2_sparse_classes_30k_train_025039 | Implement the Python class `TestPronounMapping` described below.
Class description:
Test pronoun viewpoint mapping
Method signatures and docstrings:
- def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person): Test the pronoun mapper.
- def test_mapping_with_options(self, pronoun, optio... | Implement the Python class `TestPronounMapping` described below.
Class description:
Test pronoun viewpoint mapping
Method signatures and docstrings:
- def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person): Test the pronoun mapper.
- def test_mapping_with_options(self, pronoun, optio... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TestPronounMapping:
"""Test pronoun viewpoint mapping"""
def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person):
"""Test the pronoun mapper."""
<|body_0|>
def test_mapping_with_options(self, pronoun, options, expected_1st_or_2nd_person, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPronounMapping:
"""Test pronoun viewpoint mapping"""
def test_default_mapping(self, pronoun, expected_1st_or_2nd_person, expected_3rd_person):
"""Test the pronoun mapper."""
received_1st_or_2nd_person, received_3rd_person = pronouns.pronoun_to_viewpoints(pronoun)
self.assertEq... | the_stack_v2_python_sparse | evennia/utils/verb_conjugation/tests.py | evennia/evennia | train | 1,781 |
a4caaff346c655ac9152322be52495b2f4874106 | [
"super(BiRNNEncoder, self).__init__(model_proto, is_training)\nif not isinstance(model_proto, text_encoders_pb2.BiRNNEncoder):\n raise ValueError('The model_proto has to be an instance of BiRNNEncoder.')\nif model_proto.cell_type != 'LSTM':\n raise ValueError('Only LSTM is supported.')\n\ndef _rnn_cell():\n ... | <|body_start_0|>
super(BiRNNEncoder, self).__init__(model_proto, is_training)
if not isinstance(model_proto, text_encoders_pb2.BiRNNEncoder):
raise ValueError('The model_proto has to be an instance of BiRNNEncoder.')
if model_proto.cell_type != 'LSTM':
raise ValueError('O... | BiRNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiRNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
<|body_0|>
def _set_init_fn(self, embedding_weights, filename):
"""Sets th... | stack_v2_sparse_classes_75kplus_train_008172 | 4,638 | no_license | [
{
"docstring": "Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invalid.",
"name": "__init__",
"signature": "def __init__(self, model_proto, is_training)"
},
{
"docstring": "Sets the initialization function. Args: embedding_we... | 3 | stack_v2_sparse_classes_30k_train_013608 | Implement the Python class `BiRNNEncoder` described below.
Class description:
Implement the BiRNNEncoder class.
Method signatures and docstrings:
- def __init__(self, model_proto, is_training): Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invali... | Implement the Python class `BiRNNEncoder` described below.
Class description:
Implement the BiRNNEncoder class.
Method signatures and docstrings:
- def __init__(self, model_proto, is_training): Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invali... | 2ea5e1405b1ab178b95f9c2cd9158b16847ac6a3 | <|skeleton|>
class BiRNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
<|body_0|>
def _set_init_fn(self, embedding_weights, filename):
"""Sets th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiRNNEncoder:
def __init__(self, model_proto, is_training):
"""Initializes BiRNNEncoder. Args: model_proto: an instance of BiRNNEncoder proto. Raises: ValueError: if model_proto is invalid."""
super(BiRNNEncoder, self).__init__(model_proto, is_training)
if not isinstance(model_proto, t... | the_stack_v2_python_sparse | text_encoders/bi_rnn_encoder.py | yekeren/ADVISE-Image_ads_understanding | train | 22 | |
9184301c89a2edc25492e96944f288d030d5e551 | [
"iMillisecondsIP = int(cMillisecondsIP)\ndummy_event = threading.Event()\ndummy_event.wait(timeout=iMillisecondsIP / 1000.0)\nreturn ''",
"dummy_event = threading.Event()\ndummy_event.wait(timeout=seconds)\nreturn ''",
"tObjects = gc.get_objects()\nfor o in tObjects:\n if getattr(o, '__class__', None):\n ... | <|body_start_0|>
iMillisecondsIP = int(cMillisecondsIP)
dummy_event = threading.Event()
dummy_event.wait(timeout=iMillisecondsIP / 1000.0)
return ''
<|end_body_0|>
<|body_start_1|>
dummy_event = threading.Event()
dummy_event.wait(timeout=seconds)
return ''
<|end_... | sc_mspysys | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sc_mspysys:
def MicroSleep(cls, cMillisecondsIP):
"""Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)"""
<|body_0|>
def Sleep(cls, seconds):
"""Python called only. Does the same as time.sleep(), but enables resp... | stack_v2_sparse_classes_75kplus_train_008173 | 2,813 | permissive | [
{
"docstring": "Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)",
"name": "MicroSleep",
"signature": "def MicroSleep(cls, cMillisecondsIP)"
},
{
"docstring": "Python called only. Does the same as time.sleep(), but enables responding to sig... | 4 | null | Implement the Python class `sc_mspysys` described below.
Class description:
Implement the sc_mspysys class.
Method signatures and docstrings:
- def MicroSleep(cls, cMillisecondsIP): Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)
- def Sleep(cls, seconds): Pyth... | Implement the Python class `sc_mspysys` described below.
Class description:
Implement the sc_mspysys class.
Method signatures and docstrings:
- def MicroSleep(cls, cMillisecondsIP): Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)
- def Sleep(cls, seconds): Pyth... | 3662c9d598e92870b0d409035336b94e6c195920 | <|skeleton|>
class sc_mspysys:
def MicroSleep(cls, cMillisecondsIP):
"""Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)"""
<|body_0|>
def Sleep(cls, seconds):
"""Python called only. Does the same as time.sleep(), but enables resp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sc_mspysys:
def MicroSleep(cls, cMillisecondsIP):
"""Called by bridge. Does the same as time.sleep(), but enables responding to signals like kill -2 (SIGINT)"""
iMillisecondsIP = int(cMillisecondsIP)
dummy_event = threading.Event()
dummy_event.wait(timeout=iMillisecondsIP / 100... | the_stack_v2_python_sparse | src/panaedra/msroot/msutil/logic/sc_mspysys.py | Panaedra/panaedra_py_platform_base | train | 1 | |
4a2686406b220a6c21244889000fa0b7a858aa81 | [
"tests = ['test.1', 'test.2']\nexpected = 'test.1:test.2'\nself.assertEqual(test_apps.get_gtest_filter(tests), expected)",
"tests = ['test.1', 'test.2']\nexpected = '-test.1:test.2'\nself.assertEqual(test_apps.get_gtest_filter(tests, invert=True), expected)"
] | <|body_start_0|>
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_apps.get_gtest_filter(tests), expected)
<|end_body_0|>
<|body_start_1|>
tests = ['test.1', 'test.2']
expected = '-test.1:test.2'
self.assertEqual(test_apps.get_gtest_filter(tes... | Tests for test_runner.get_gtest_filter. | GetGTestFilterTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_008174 | 1,492 | permissive | [
{
"docstring": "Ensures correctness of filter.",
"name": "test_correct",
"signature": "def test_correct(self)"
},
{
"docstring": "Ensures correctness of inverted filter.",
"name": "test_correct_inverted",
"signature": "def test_correct_inverted(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033790 | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter. | Implement the Python class `GetGTestFilterTest` described below.
Class description:
Tests for test_runner.get_gtest_filter.
Method signatures and docstrings:
- def test_correct(self): Ensures correctness of filter.
- def test_correct_inverted(self): Ensures correctness of inverted filter.
<|skeleton|>
class GetGTest... | 64bee65c921db7e78e25d08f1e98da2668b57be5 | <|skeleton|>
class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
<|body_0|>
def test_correct_inverted(self):
"""Ensures correctness of inverted filter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetGTestFilterTest:
"""Tests for test_runner.get_gtest_filter."""
def test_correct(self):
"""Ensures correctness of filter."""
tests = ['test.1', 'test.2']
expected = 'test.1:test.2'
self.assertEqual(test_apps.get_gtest_filter(tests), expected)
def test_correct_invert... | the_stack_v2_python_sparse | ios/build/bots/scripts/test_apps_test.py | otcshare/chromium-src | train | 18 |
dded1c8c32c34bcb55c183eb11f467c7d1bdc356 | [
"for i in recipe.ingredients.all():\n for l in self.dislikes.all():\n if i == l:\n return True\nreturn False",
"for i in recipe.ingredients.all():\n for l in self.likes.all():\n if i == l:\n return True\nreturn False",
"eaten = self.user.planner_set.all().order_by('-dat... | <|body_start_0|>
for i in recipe.ingredients.all():
for l in self.dislikes.all():
if i == l:
return True
return False
<|end_body_0|>
<|body_start_1|>
for i in recipe.ingredients.all():
for l in self.likes.all():
if i ==... | UserFoodPrefs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFoodPrefs:
def checkRecipeDislikes(self, recipe):
"""Checks food preferences versus a recipe"""
<|body_0|>
def checkRecipeLikes(self, recipe):
"""Checks food preferences versus a recipe"""
<|body_1|>
def recipeInXLastEaten(self, recipe, x):
"... | stack_v2_sparse_classes_75kplus_train_008175 | 1,110 | no_license | [
{
"docstring": "Checks food preferences versus a recipe",
"name": "checkRecipeDislikes",
"signature": "def checkRecipeDislikes(self, recipe)"
},
{
"docstring": "Checks food preferences versus a recipe",
"name": "checkRecipeLikes",
"signature": "def checkRecipeLikes(self, recipe)"
},
... | 3 | stack_v2_sparse_classes_30k_train_047805 | Implement the Python class `UserFoodPrefs` described below.
Class description:
Implement the UserFoodPrefs class.
Method signatures and docstrings:
- def checkRecipeDislikes(self, recipe): Checks food preferences versus a recipe
- def checkRecipeLikes(self, recipe): Checks food preferences versus a recipe
- def recip... | Implement the Python class `UserFoodPrefs` described below.
Class description:
Implement the UserFoodPrefs class.
Method signatures and docstrings:
- def checkRecipeDislikes(self, recipe): Checks food preferences versus a recipe
- def checkRecipeLikes(self, recipe): Checks food preferences versus a recipe
- def recip... | c3259f4857d2d21f545dab39af1bc8798c63a45e | <|skeleton|>
class UserFoodPrefs:
def checkRecipeDislikes(self, recipe):
"""Checks food preferences versus a recipe"""
<|body_0|>
def checkRecipeLikes(self, recipe):
"""Checks food preferences versus a recipe"""
<|body_1|>
def recipeInXLastEaten(self, recipe, x):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserFoodPrefs:
def checkRecipeDislikes(self, recipe):
"""Checks food preferences versus a recipe"""
for i in recipe.ingredients.all():
for l in self.dislikes.all():
if i == l:
return True
return False
def checkRecipeLikes(self, recip... | the_stack_v2_python_sparse | recipemonkeyapp/models/userfoodprefs.py | vanessacochrane/Recipe-Monkey | train | 1 | |
bca017c41983058da2bdfe59721da8a61b2561fd | [
"self.lock = Lock()\nself.rate = rate\nself.period = period\nself.burst = max(min(burst, rate), 0)\nself.count = 0\nself.ts = None\nself.end = None",
"with self.lock:\n now = time.time()\n if self.ts is None:\n self.ts = now\n self.end = now + self.period\n if now > self.end:\n self.... | <|body_start_0|>
self.lock = Lock()
self.rate = rate
self.period = period
self.burst = max(min(burst, rate), 0)
self.count = 0
self.ts = None
self.end = None
<|end_body_0|>
<|body_start_1|>
with self.lock:
now = time.time()
if self... | Throttle Class | Throttle | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Throttle:
"""Throttle Class"""
def __init__(self, rate=150, period=60, burst=0):
"""Create a throttle for a specific rate/sec"""
<|body_0|>
def __call__(self):
"""Return when the throttle limit is acceptable"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_008176 | 1,618 | permissive | [
{
"docstring": "Create a throttle for a specific rate/sec",
"name": "__init__",
"signature": "def __init__(self, rate=150, period=60, burst=0)"
},
{
"docstring": "Return when the throttle limit is acceptable",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | null | Implement the Python class `Throttle` described below.
Class description:
Throttle Class
Method signatures and docstrings:
- def __init__(self, rate=150, period=60, burst=0): Create a throttle for a specific rate/sec
- def __call__(self): Return when the throttle limit is acceptable | Implement the Python class `Throttle` described below.
Class description:
Throttle Class
Method signatures and docstrings:
- def __init__(self, rate=150, period=60, burst=0): Create a throttle for a specific rate/sec
- def __call__(self): Return when the throttle limit is acceptable
<|skeleton|>
class Throttle:
... | 0f2e6a2d1c71f104b1522fd68ec01b9f9f3b92f9 | <|skeleton|>
class Throttle:
"""Throttle Class"""
def __init__(self, rate=150, period=60, burst=0):
"""Create a throttle for a specific rate/sec"""
<|body_0|>
def __call__(self):
"""Return when the throttle limit is acceptable"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Throttle:
"""Throttle Class"""
def __init__(self, rate=150, period=60, burst=0):
"""Create a throttle for a specific rate/sec"""
self.lock = Lock()
self.rate = rate
self.period = period
self.burst = max(min(burst, rate), 0)
self.count = 0
self.ts = ... | the_stack_v2_python_sparse | apps/TCPB_-_Expressions/src/throttle.py | ThreatConnect-Inc/threatconnect-playbooks | train | 76 |
ec48323557d550a1684dbe4115bb2bf57247f71c | [
"self.hass.listen_event(self.response_from_push_notification, 'ios.notification_action_fired', actionName=self.properties['ios_emptied_key'], constrain_input_boolean=self.constraint)\nself.hass.listen_state(self.power_changed, self.hass.manager_app.entities['power'], constrain_input_boolean=self.constraint)\nself.h... | <|body_start_0|>
self.hass.listen_event(self.response_from_push_notification, 'ios.notification_action_fired', actionName=self.properties['ios_emptied_key'], constrain_input_boolean=self.constraint)
self.hass.listen_state(self.power_changed, self.hass.manager_app.entities['power'], constrain_input_boole... | Define a feature to notify a target when the appliancer is done. | NotifyDone | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifyDone:
"""Define a feature to notify a target when the appliancer is done."""
def initialize(self) -> None:
"""Initialize."""
<|body_0|>
def power_changed(self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dict) -> None:
"""Deal with... | stack_v2_sparse_classes_75kplus_train_008177 | 17,182 | no_license | [
{
"docstring": "Initialize.",
"name": "initialize",
"signature": "def initialize(self) -> None"
},
{
"docstring": "Deal with changes to the power draw.",
"name": "power_changed",
"signature": "def power_changed(self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: d... | 4 | stack_v2_sparse_classes_30k_train_044530 | Implement the Python class `NotifyDone` described below.
Class description:
Define a feature to notify a target when the appliancer is done.
Method signatures and docstrings:
- def initialize(self) -> None: Initialize.
- def power_changed(self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dic... | Implement the Python class `NotifyDone` described below.
Class description:
Define a feature to notify a target when the appliancer is done.
Method signatures and docstrings:
- def initialize(self) -> None: Initialize.
- def power_changed(self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dic... | a5ad47d6db1c09c6f84a97b350f5862f3bff9945 | <|skeleton|>
class NotifyDone:
"""Define a feature to notify a target when the appliancer is done."""
def initialize(self) -> None:
"""Initialize."""
<|body_0|>
def power_changed(self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dict) -> None:
"""Deal with... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotifyDone:
"""Define a feature to notify a target when the appliancer is done."""
def initialize(self) -> None:
"""Initialize."""
self.hass.listen_event(self.response_from_push_notification, 'ios.notification_action_fired', actionName=self.properties['ios_emptied_key'], constrain_input_b... | the_stack_v2_python_sparse | conf/appdaemon/apps/appliances.py | vageesh79/smart-home | train | 0 |
3132548e6694e1c3dcec3749f81c8210035ea0ae | [
"user1 = User.objects.get(username='admin')\nuser2 = User.objects.get(username='doc')\nself.assertTrue(user1.is_profile_visible(user2))",
"user1 = User.objects.get(username='admin')\nuser2 = User.objects.get(username='doc')\nprofile = user1.get_profile()\nprofile.is_private = True\nprofile.save()\nself.assertFals... | <|body_start_0|>
user1 = User.objects.get(username='admin')
user2 = User.objects.get(username='doc')
self.assertTrue(user1.is_profile_visible(user2))
<|end_body_0|>
<|body_start_1|>
user1 = User.objects.get(username='admin')
user2 = User.objects.get(username='doc')
profi... | Test the Profile model. | ProfileTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileTests:
"""Test the Profile model."""
def test_is_profile_visible_with_public(self):
"""Testing User.is_profile_public with public profiles."""
<|body_0|>
def test_is_profile_visible_with_private(self):
"""Testing User.is_profile_public with private profile... | stack_v2_sparse_classes_75kplus_train_008178 | 19,866 | permissive | [
{
"docstring": "Testing User.is_profile_public with public profiles.",
"name": "test_is_profile_visible_with_public",
"signature": "def test_is_profile_visible_with_public(self)"
},
{
"docstring": "Testing User.is_profile_public with private profiles.",
"name": "test_is_profile_visible_with_... | 3 | stack_v2_sparse_classes_30k_train_015990 | Implement the Python class `ProfileTests` described below.
Class description:
Test the Profile model.
Method signatures and docstrings:
- def test_is_profile_visible_with_public(self): Testing User.is_profile_public with public profiles.
- def test_is_profile_visible_with_private(self): Testing User.is_profile_public... | Implement the Python class `ProfileTests` described below.
Class description:
Test the Profile model.
Method signatures and docstrings:
- def test_is_profile_visible_with_public(self): Testing User.is_profile_public with public profiles.
- def test_is_profile_visible_with_private(self): Testing User.is_profile_public... | 02e1ef3a4e9a8117977b053805234a713c31a699 | <|skeleton|>
class ProfileTests:
"""Test the Profile model."""
def test_is_profile_visible_with_public(self):
"""Testing User.is_profile_public with public profiles."""
<|body_0|>
def test_is_profile_visible_with_private(self):
"""Testing User.is_profile_public with private profile... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileTests:
"""Test the Profile model."""
def test_is_profile_visible_with_public(self):
"""Testing User.is_profile_public with public profiles."""
user1 = User.objects.get(username='admin')
user2 = User.objects.get(username='doc')
self.assertTrue(user1.is_profile_visibl... | the_stack_v2_python_sparse | reviewboard/accounts/tests.py | parthyz/reviewboard | train | 1 |
8cde3ad6fe45973fbc75ad87986a27d0b8f8a12e | [
"self._app = _app\nself.viewer = viewer\nself.tournament = tournament",
"from app.controllers.turns import TurnsController\nself._app.change_controller(TurnsController(self.tournament))\nself.viewer.warning = ''\nreturn False",
"if command_name == CommandField.TURNS:\n return True\nelse:\n return False"
] | <|body_start_0|>
self._app = _app
self.viewer = viewer
self.tournament = tournament
<|end_body_0|>
<|body_start_1|>
from app.controllers.turns import TurnsController
self._app.change_controller(TurnsController(self.tournament))
self.viewer.warning = ''
return Fal... | Project go_to_turns_menu command class. | GotoTurnsMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GotoTurnsMenu:
"""Project go_to_turns_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_turns_menu command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<|body_... | stack_v2_sparse_classes_75kplus_train_008179 | 9,466 | no_license | [
{
"docstring": "Init go_to_turns_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 `GotoTurnsMenu` described below.
Class description:
Project go_to_turns_menu command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer, tournament): Init go_to_turns_menu command class.
- def exe_command(self): Execute command and return False to not exit applicatio... | Implement the Python class `GotoTurnsMenu` described below.
Class description:
Project go_to_turns_menu command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer, tournament): Init go_to_turns_menu command class.
- def exe_command(self): Execute command and return False to not exit applicatio... | be6089cd71c762f23725b61e8d2745cfabe4f0c0 | <|skeleton|>
class GotoTurnsMenu:
"""Project go_to_turns_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_turns_menu command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GotoTurnsMenu:
"""Project go_to_turns_menu command class."""
def __init__(self, _app, viewer, tournament):
"""Init go_to_turns_menu command class."""
self._app = _app
self.viewer = viewer
self.tournament = tournament
def exe_command(self):
"""Execute command a... | the_stack_v2_python_sparse | app/commands/navigation.py | FortranVBA/DAP4 | train | 0 |
2305e6b6a4f0f81d395bdba3ef11e27460945c71 | [
"table = Table(table)\nvalues_table = []\nfor i in range(len(list_values)):\n values_table.append(tuple(list_values[i]))\nq = BuildInjectQuery.function_insert(MySQLQuery.into(table).insert(values_table[0]), values_table, table, 0)\nif key_duplicate:\n q = q.on_duplicate_key_update(table.lei, Values(table.lei)... | <|body_start_0|>
table = Table(table)
values_table = []
for i in range(len(list_values)):
values_table.append(tuple(list_values[i]))
q = BuildInjectQuery.function_insert(MySQLQuery.into(table).insert(values_table[0]), values_table, table, 0)
if key_duplicate:
... | BuildInjectQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildInjectQuery:
def build_query_insert(table, key_duplicate, list_values):
"""Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table : table name :param list_values: list of values to insert return query"""
<|body_0|>
def fun... | stack_v2_sparse_classes_75kplus_train_008180 | 8,841 | permissive | [
{
"docstring": "Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table : table name :param list_values: list of values to insert return query",
"name": "build_query_insert",
"signature": "def build_query_insert(table, key_duplicate, list_values)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000340 | Implement the Python class `BuildInjectQuery` described below.
Class description:
Implement the BuildInjectQuery class.
Method signatures and docstrings:
- def build_query_insert(table, key_duplicate, list_values): Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table ... | Implement the Python class `BuildInjectQuery` described below.
Class description:
Implement the BuildInjectQuery class.
Method signatures and docstrings:
- def build_query_insert(table, key_duplicate, list_values): Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table ... | c98eb8c483a05af938a2f6f49d8ea803f5711572 | <|skeleton|>
class BuildInjectQuery:
def build_query_insert(table, key_duplicate, list_values):
"""Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table : table name :param list_values: list of values to insert return query"""
<|body_0|>
def fun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildInjectQuery:
def build_query_insert(table, key_duplicate, list_values):
"""Build query Insert :param key_duplicate : boolean in oredr to have dupliacte key on query :param table : table name :param list_values: list of values to insert return query"""
table = Table(table)
values_t... | the_stack_v2_python_sparse | engage-analytics/lei/src/read_lei/inject_sql.py | oliveriopt/mood-analytics | train | 0 | |
ef9af024a00c829bfb773d16dea0cd6cbb8fd4ee | [
"course_keys = value\nfor course in course_keys:\n try:\n CourseKey.from_string(course)\n except InvalidKeyError:\n raise serializers.ValidationError(f'Course key not valid: {course}')\nreturn value",
"if attrs.get('cohorts'):\n if attrs['action'] != 'enroll':\n raise serializers.Val... | <|body_start_0|>
course_keys = value
for course in course_keys:
try:
CourseKey.from_string(course)
except InvalidKeyError:
raise serializers.ValidationError(f'Course key not valid: {course}')
return value
<|end_body_0|>
<|body_start_1|>
... | Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations. | BulkEnrollmentSerializer | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkEnrollmentSerializer:
"""Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations."""
def validate_courses(self, value):
"""Check that each course key in list is valid."""
... | stack_v2_sparse_classes_75kplus_train_008181 | 2,612 | permissive | [
{
"docstring": "Check that each course key in list is valid.",
"name": "validate_courses",
"signature": "def validate_courses(self, value)"
},
{
"docstring": "Check that the cohorts list is the same size as the courses list.",
"name": "validate",
"signature": "def validate(self, attrs)"
... | 2 | stack_v2_sparse_classes_30k_train_028055 | Implement the Python class `BulkEnrollmentSerializer` described below.
Class description:
Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.
Method signatures and docstrings:
- def validate_courses(self, ... | Implement the Python class `BulkEnrollmentSerializer` described below.
Class description:
Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations.
Method signatures and docstrings:
- def validate_courses(self, ... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BulkEnrollmentSerializer:
"""Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations."""
def validate_courses(self, value):
"""Check that each course key in list is valid."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BulkEnrollmentSerializer:
"""Serializes enrollment information for a collection of students/emails. This is mainly useful for implementing validation when performing bulk enrollment operations."""
def validate_courses(self, value):
"""Check that each course key in list is valid."""
course... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/bulk_enroll/serializers.py | luque/better-ways-of-thinking-about-software | train | 3 |
67791acdfd7270f749d39143148337731e8cb0cd | [
"j = 0\nfor i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n j += 1\n nums[j] = nums[i]\nreturn j + 1 if len(nums) else 0",
"\"\"\"\n 解法2:\n \"\"\"\nfor i in range(len(nums) - 1, 1, -1):\n if nums[i] == nums[i - 2]:\n nums.pop(i)\nreturn len(nums)"
] | <|body_start_0|>
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
j += 1
nums[j] = nums[i]
return j + 1 if len(nums) else 0
<|end_body_0|>
<|body_start_1|>
"""
解法2:
"""
for i in range(len(n... | 删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 你不需要考虑数组中超出新长度后面的元素。 说明: 为什么返... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2,... | stack_v2_sparse_classes_75kplus_train_008182 | 4,181 | no_license | [
{
"docstring": "解法:快慢指针,快指针正常遍历数组,慢指针在遇到不重复的数字时才加1",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums: list) -> int"
},
{
"docstring": "解法1:双指针,一次扫描,直接修改数组中的值",
"name": "removeDuplicates2",
"signature": "def removeDuplicates2(self, nums: list) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_014820 | Implement the Python class `Solution` described below.
Class description:
删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返... | Implement the Python class `Solution` described below.
Class description:
删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返... | ad25281be49dfb9de211ba324b398e946e49025d | <|skeleton|>
class Solution:
"""删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""删除排序数组中的重复项 II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 你不需要考虑... | the_stack_v2_python_sparse | 人生苦短/删除排序数组中的重复项(1-2).py | Jsonlmy/leetcode | train | 0 |
d5a0eff22189f166c7455c2bc5c7c0946f3c6595 | [
"self.resolver = Resolver(configure=False)\nself.resolver.nameservers = dns_servers\nself.resolver.search = [dns.name.from_text(domain)]\nself.resolver.port = port\nself.resolver.timeout = 1.0\nself.resolver.lifetime = lifetime",
"try:\n answer = self.resolver.query(qname, 'A')\nexcept dns.exception.Timeout:\n... | <|body_start_0|>
self.resolver = Resolver(configure=False)
self.resolver.nameservers = dns_servers
self.resolver.search = [dns.name.from_text(domain)]
self.resolver.port = port
self.resolver.timeout = 1.0
self.resolver.lifetime = lifetime
<|end_body_0|>
<|body_start_1|>
... | DNS client class. Allows querying of `dns_server` for service discovery. | DNSClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNSClient:
"""DNS client class. Allows querying of `dns_server` for service discovery."""
def __init__(self, dns_servers, domain, lifetime=5.0, port=SCION_DNS_PORT):
""":param list dns_servers: DNS server IP addresses as strings. E.g. ``["127.0.0.1", "8.8.8.8"]`` :param string domain... | stack_v2_sparse_classes_75kplus_train_008183 | 6,599 | permissive | [
{
"docstring": ":param list dns_servers: DNS server IP addresses as strings. E.g. ``[\"127.0.0.1\", \"8.8.8.8\"]`` :param string domain: The DNS domain to query. :param float lifetime: Number of seconds in total to try resolving before failing. :param int port: DNS server port.",
"name": "__init__",
"si... | 3 | stack_v2_sparse_classes_30k_train_050047 | Implement the Python class `DNSClient` described below.
Class description:
DNS client class. Allows querying of `dns_server` for service discovery.
Method signatures and docstrings:
- def __init__(self, dns_servers, domain, lifetime=5.0, port=SCION_DNS_PORT): :param list dns_servers: DNS server IP addresses as string... | Implement the Python class `DNSClient` described below.
Class description:
DNS client class. Allows querying of `dns_server` for service discovery.
Method signatures and docstrings:
- def __init__(self, dns_servers, domain, lifetime=5.0, port=SCION_DNS_PORT): :param list dns_servers: DNS server IP addresses as string... | 06f3f0b82dc8a535ce8b0a128282af00a8425a06 | <|skeleton|>
class DNSClient:
"""DNS client class. Allows querying of `dns_server` for service discovery."""
def __init__(self, dns_servers, domain, lifetime=5.0, port=SCION_DNS_PORT):
""":param list dns_servers: DNS server IP addresses as strings. E.g. ``["127.0.0.1", "8.8.8.8"]`` :param string domain... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DNSClient:
"""DNS client class. Allows querying of `dns_server` for service discovery."""
def __init__(self, dns_servers, domain, lifetime=5.0, port=SCION_DNS_PORT):
""":param list dns_servers: DNS server IP addresses as strings. E.g. ``["127.0.0.1", "8.8.8.8"]`` :param string domain: The DNS dom... | the_stack_v2_python_sparse | lib/dnsclient.py | marcoeilers/scion | train | 1 |
76234a31da876af5664d45294a19409368869f3d | [
"cfg = '# auto-generated by DHCP service (utility.py)\\n# NOTE: move these option lines into the desired pool { } block(s) below\\n#option domain-name \"test.com\";\\n#option domain-name-servers 10.0.0.1;\\n#option routers 10.0.0.1;\\n\\nlog-facility local6;\\n\\ndefault-lease-time 600;\\nmax-lease-time 7200;\\n\\n... | <|body_start_0|>
cfg = '# auto-generated by DHCP service (utility.py)\n# NOTE: move these option lines into the desired pool { } block(s) below\n#option domain-name "test.com";\n#option domain-name-servers 10.0.0.1;\n#option routers 10.0.0.1;\n\nlog-facility local6;\n\ndefault-lease-time 600;\nmax-lease-time 72... | DhcpService | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DhcpService:
def generate_config(cls, node: CoreNode, filename: str) -> str:
"""Generate a dhcpd config file using the network address of each interface."""
<|body_0|>
def subnetentry(ip: netaddr.IPNetwork) -> str:
"""Generate a subnet declaration block given an IPv4... | stack_v2_sparse_classes_75kplus_train_008184 | 19,801 | permissive | [
{
"docstring": "Generate a dhcpd config file using the network address of each interface.",
"name": "generate_config",
"signature": "def generate_config(cls, node: CoreNode, filename: str) -> str"
},
{
"docstring": "Generate a subnet declaration block given an IPv4 prefix string for inclusion in... | 2 | stack_v2_sparse_classes_30k_train_049733 | Implement the Python class `DhcpService` described below.
Class description:
Implement the DhcpService class.
Method signatures and docstrings:
- def generate_config(cls, node: CoreNode, filename: str) -> str: Generate a dhcpd config file using the network address of each interface.
- def subnetentry(ip: netaddr.IPNe... | Implement the Python class `DhcpService` described below.
Class description:
Implement the DhcpService class.
Method signatures and docstrings:
- def generate_config(cls, node: CoreNode, filename: str) -> str: Generate a dhcpd config file using the network address of each interface.
- def subnetentry(ip: netaddr.IPNe... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class DhcpService:
def generate_config(cls, node: CoreNode, filename: str) -> str:
"""Generate a dhcpd config file using the network address of each interface."""
<|body_0|>
def subnetentry(ip: netaddr.IPNetwork) -> str:
"""Generate a subnet declaration block given an IPv4... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DhcpService:
def generate_config(cls, node: CoreNode, filename: str) -> str:
"""Generate a dhcpd config file using the network address of each interface."""
cfg = '# auto-generated by DHCP service (utility.py)\n# NOTE: move these option lines into the desired pool { } block(s) below\n#option d... | the_stack_v2_python_sparse | daemon/core/services/utility.py | coreemu/core | train | 606 | |
09426208dd6bee3641b2b712c4aeea3d9f355484 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(units=vocab, kernel_initializer='gloro... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Den... | Class RNNDecoder | RNNDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer repre... | stack_v2_sparse_classes_75kplus_train_008185 | 2,958 | permissive | [
{
"docstring": "Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the number of hidden units in the RNN cell batch is an integer representing the batch size Ret... | 2 | null | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensi... | Implement the Python class `RNNDecoder` described below.
Class description:
Class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensi... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class RNNDecoder:
"""Class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer repre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""Class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""Parameters ---------- vocab is an integer representing the size of the output vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the n... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
9188db78d02b9514801d97f07574b431d6007f40 | [
"super(Decoder, self).__init__()\nself.gru1 = nn.GRUCell(ninp, dec_nhid)\nself.gru2 = nn.GRUCell(enc_ncontext, dec_nhid)\nself.enc_attn = Attention(dec_nhid, enc_ncontext, natt)\nself.e2o = nn.Linear(ninp, dec_nout)\nself.h2o = nn.Linear(dec_nhid, dec_nout)\nself.c2o = nn.Linear(enc_ncontext, dec_nout)\nself.readou... | <|body_start_0|>
super(Decoder, self).__init__()
self.gru1 = nn.GRUCell(ninp, dec_nhid)
self.gru2 = nn.GRUCell(enc_ncontext, dec_nhid)
self.enc_attn = Attention(dec_nhid, enc_ncontext, natt)
self.e2o = nn.Linear(ninp, dec_nout)
self.h2o = nn.Linear(dec_nhid, dec_nout)
... | Decoder that decodes information from both encoder and attention mechanism | Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder that decodes information from both encoder and attention mechanism"""
def __init__(self, ninp, dec_nhid, enc_ncontext, natt, dec_nout, dec_out_dropout):
""":param ninp: the number of features in input target word embeddings :param dec_nhid: the number of features ... | stack_v2_sparse_classes_75kplus_train_008186 | 2,792 | permissive | [
{
"docstring": ":param ninp: the number of features in input target word embeddings :param dec_nhid: the number of features in decoder hidden states, the same as that of the hidden states proposal :param enc_ncontext: the number of features in context vectors :param natt: the number of features in intermediate ... | 2 | stack_v2_sparse_classes_30k_train_015123 | Implement the Python class `Decoder` described below.
Class description:
Decoder that decodes information from both encoder and attention mechanism
Method signatures and docstrings:
- def __init__(self, ninp, dec_nhid, enc_ncontext, natt, dec_nout, dec_out_dropout): :param ninp: the number of features in input target... | Implement the Python class `Decoder` described below.
Class description:
Decoder that decodes information from both encoder and attention mechanism
Method signatures and docstrings:
- def __init__(self, ninp, dec_nhid, enc_ncontext, natt, dec_nout, dec_out_dropout): :param ninp: the number of features in input target... | c3cd7883c7cf907ab65625e8de7ca9dd23ba2b82 | <|skeleton|>
class Decoder:
"""Decoder that decodes information from both encoder and attention mechanism"""
def __init__(self, ninp, dec_nhid, enc_ncontext, natt, dec_nout, dec_out_dropout):
""":param ninp: the number of features in input target word embeddings :param dec_nhid: the number of features ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""Decoder that decodes information from both encoder and attention mechanism"""
def __init__(self, ninp, dec_nhid, enc_ncontext, natt, dec_nout, dec_out_dropout):
""":param ninp: the number of features in input target word embeddings :param dec_nhid: the number of features in decoder hi... | the_stack_v2_python_sparse | Backup/RNNSearch_v2/decoder.py | Encyclomen/Neural-Machine-Translation | train | 2 |
e2186cfa2eec3860b93e01f30a9beed1a7fe1a8d | [
"n = len(nums)\nj = 0\nfor i in range(n):\n if nums[i] != 0:\n nums[j] = nums[i]\n j += 1\nfor i in range(j, n):\n nums[i] = 0",
"if not nums:\n return\ni, j = (0, len(nums) - 1)\nwhile i <= j:\n while i <= j and nums[i] != 0:\n i += 1\n while i <= j and nums[j] == 0:\n ... | <|body_start_0|>
n = len(nums)
j = 0
for i in range(n):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
for i in range(j, n):
nums[i] = 0
<|end_body_0|>
<|body_start_1|>
if not nums:
return
i, j = (0, len(nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_75kplus_train_008187 | 1,493 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "mo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums): :type nums: List[int] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums): :type nums: List[int] :rtype: ... | f2c4f727689567e00ee06560132fca55a6fd9286 | <|skeleton|>
class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
n = len(nums)
j = 0
for i in range(n):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
for i in ran... | the_stack_v2_python_sparse | leetcode/283_Move_Zeroes.py | JianxiangWang/python-journey | train | 1 | |
7bc75e72dfb1bcf1d3e302368fca234537fc45fc | [
"self.SetTitle('This is an example Dialog')\nself.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)\nreturn True",
"if messageId == c4d.DLG_OK:\n print('User Click on Ok')\n return True\nelif messageId == c4d.DLG_CANCEL:\n print('User Click on Cancel')\n self.Close()\n return True\nreturn True"
] | <|body_start_0|>
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
return True
<|end_body_0|>
<|body_start_1|>
if messageId == c4d.DLG_OK:
print('User Click on Ok')
return True
elif messageId == c4d.DLG_CANCEL:
... | ExampleDialog | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_75kplus_train_008188 | 1,800 | permissive | [
{
"docstring": "This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.",
"name": "CreateLayout",
"signature": "def CreateLayout(self)"
},
{
"docstring": "This Method is called automatically when the user clicks on a gadget and/or changes its value this func... | 2 | stack_v2_sparse_classes_30k_train_026419 | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
self.SetTitle('This is an example Dialog')
self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL)
return True
def Command(self, messageId, bc):... | the_stack_v2_python_sparse | scripts/03_application_development/gui/dialog/gedialog_modal_r13.py | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
c69bc51f5564ee1a54a4df266e40b6854d3befa7 | [
"opts = Options()\nopts.minimizers = {k: [v[0]] for k, v in opts.minimizers.items()}\nopts.software = sorted(opts.minimizers.keys())\nopts.results_dir = os.path.join(os.path.dirname(__file__), 'results')\nopt_file = tempfile.NamedTemporaryFile(suffix='.ini')\nopts.write(opt_file.name)\nproblem = os.path.abspath(os.... | <|body_start_0|>
opts = Options()
opts.minimizers = {k: [v[0]] for k, v in opts.minimizers.items()}
opts.software = sorted(opts.minimizers.keys())
opts.results_dir = os.path.join(os.path.dirname(__file__), 'results')
opt_file = tempfile.NamedTemporaryFile(suffix='.ini')
o... | Regression tests for the Fitbenchmarking software | TestRegression | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRegression:
"""Regression tests for the Fitbenchmarking software"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent(self):
"""Regression testing that the results of fitting a set of proble... | stack_v2_sparse_classes_75kplus_train_008189 | 2,914 | permissive | [
{
"docstring": "Create an options file, run it, and get the results.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Regression testing that the results of fitting a set of problems containing all problem types against a single minimiser from each of the supported s... | 2 | stack_v2_sparse_classes_30k_train_024712 | Implement the Python class `TestRegression` described below.
Class description:
Regression tests for the Fitbenchmarking software
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent(self): Regression testing that the results of fi... | Implement the Python class `TestRegression` described below.
Class description:
Regression tests for the Fitbenchmarking software
Method signatures and docstrings:
- def setUpClass(cls): Create an options file, run it, and get the results.
- def test_results_consistent(self): Regression testing that the results of fi... | f1dd0fd2f32f2eb1356e8ac514c981861d83b698 | <|skeleton|>
class TestRegression:
"""Regression tests for the Fitbenchmarking software"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
<|body_0|>
def test_results_consistent(self):
"""Regression testing that the results of fitting a set of proble... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRegression:
"""Regression tests for the Fitbenchmarking software"""
def setUpClass(cls):
"""Create an options file, run it, and get the results."""
opts = Options()
opts.minimizers = {k: [v[0]] for k, v in opts.minimizers.items()}
opts.software = sorted(opts.minimizers... | the_stack_v2_python_sparse | fitbenchmarking/systests/test_regression.py | AtomAnu/fitbenchmarking | train | 0 |
7264cff04caf9037ab667041186075a8df83de50 | [
"parameters = dict()\nparameters['filter'] = GraphQLParam(key_value_filter, 'KeyValueFilter', True)\nresponse = self._query(name='getKeyValues', params=parameters, fields=KeyValueList.fields())\nreturn KeyValueList(response)",
"parameters = dict()\nparameters['input'] = GraphQLParam(upsert_key_value_input, 'Upser... | <|body_start_0|>
parameters = dict()
parameters['filter'] = GraphQLParam(key_value_filter, 'KeyValueFilter', True)
response = self._query(name='getKeyValues', params=parameters, fields=KeyValueList.fields())
return KeyValueList(response)
<|end_body_0|>
<|body_start_1|>
parameter... | Mixin to add key value related methods to the GraphQL client | KeyValueMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyValueMixin:
"""Mixin to add key value related methods to the GraphQL client"""
def get_key_values(self, key_value_filter: KeyValueFilter) -> KeyValueList:
"""Retrieves a list of key value objects :param key_value_filter: A filter object to filter key value objects on the server. :... | stack_v2_sparse_classes_75kplus_train_008190 | 12,105 | permissive | [
{
"docstring": "Retrieves a list of key value objects :param key_value_filter: A filter object to filter key value objects on the server. :type key_value_filter: KeyValueFilter :returns KeyValueList: A list of key value objects. :raises GraphQLError: An error with the GraphQL endpoint.",
"name": "get_key_va... | 3 | stack_v2_sparse_classes_30k_train_002524 | Implement the Python class `KeyValueMixin` described below.
Class description:
Mixin to add key value related methods to the GraphQL client
Method signatures and docstrings:
- def get_key_values(self, key_value_filter: KeyValueFilter) -> KeyValueList: Retrieves a list of key value objects :param key_value_filter: A f... | Implement the Python class `KeyValueMixin` described below.
Class description:
Mixin to add key value related methods to the GraphQL client
Method signatures and docstrings:
- def get_key_values(self, key_value_filter: KeyValueFilter) -> KeyValueList: Retrieves a list of key value objects :param key_value_filter: A f... | 8ea044096bd18aaccbfb81eca4e26ec29895a18c | <|skeleton|>
class KeyValueMixin:
"""Mixin to add key value related methods to the GraphQL client"""
def get_key_values(self, key_value_filter: KeyValueFilter) -> KeyValueList:
"""Retrieves a list of key value objects :param key_value_filter: A filter object to filter key value objects on the server. :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyValueMixin:
"""Mixin to add key value related methods to the GraphQL client"""
def get_key_values(self, key_value_filter: KeyValueFilter) -> KeyValueList:
"""Retrieves a list of key value objects :param key_value_filter: A filter object to filter key value objects on the server. :type key_valu... | the_stack_v2_python_sparse | nebpyclient/api/keyvalue.py | firefly707/nebpyclient | train | 0 |
f3c886e115df58e90175fcbe1883bbc7c694fbb4 | [
"if HostUpdater.__host_updater is None:\n HostUpdater()\nreturn HostUpdater.__host_updater",
"if HostUpdater.__host_updater is None:\n HostUpdater.__host_updater = self\n self.__common = Common.get_instance()\n self.__grid_draw = GridDraw.get_instance()\n self.__monitoring = Monitoring.get_instance... | <|body_start_0|>
if HostUpdater.__host_updater is None:
HostUpdater()
return HostUpdater.__host_updater
<|end_body_0|>
<|body_start_1|>
if HostUpdater.__host_updater is None:
HostUpdater.__host_updater = self
self.__common = Common.get_instance()
... | Update sender to mobile | HostUpdater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostUpdater:
"""Update sender to mobile"""
def get_instance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
def __send_update_to_host(self, image):
"""Updates the mobile host"""
... | stack_v2_sparse_classes_75kplus_train_008191 | 5,438 | no_license | [
{
"docstring": "Static access method.",
"name": "get_instance",
"signature": "def get_instance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Updates the mobile host",
"name": "__send_update_to_h... | 5 | null | Implement the Python class `HostUpdater` described below.
Class description:
Update sender to mobile
Method signatures and docstrings:
- def get_instance(): Static access method.
- def __init__(self): Virtually private constructor.
- def __send_update_to_host(self, image): Updates the mobile host
- def run(self, new_... | Implement the Python class `HostUpdater` described below.
Class description:
Update sender to mobile
Method signatures and docstrings:
- def get_instance(): Static access method.
- def __init__(self): Virtually private constructor.
- def __send_update_to_host(self, image): Updates the mobile host
- def run(self, new_... | 871d7e8da240d28ab4bab2b371d7b6c89913d898 | <|skeleton|>
class HostUpdater:
"""Update sender to mobile"""
def get_instance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
def __send_update_to_host(self, image):
"""Updates the mobile host"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostUpdater:
"""Update sender to mobile"""
def get_instance():
"""Static access method."""
if HostUpdater.__host_updater is None:
HostUpdater()
return HostUpdater.__host_updater
def __init__(self):
"""Virtually private constructor."""
if HostUpdate... | the_stack_v2_python_sparse | hddzids/dist/scripts/host_updater.py | MACNICA-CLAVIS-NV/dangerzone | train | 3 |
70324fc97aa52c579200d4389a8a21a45aed213d | [
"super(ResBlock, self).__init__()\nself.act = activation\nassert res_type in ['basic', 'bottleneck'], 'residual type only support basic and bottleneck, not:{}'.format(res_type)\nself.res_type = res_type\nif self.res_type == 'basic':\n self.conv1 = conv2d_block(in_channels, in_channels, 3, 1, 1, activation=self.a... | <|body_start_0|>
super(ResBlock, self).__init__()
self.act = activation
assert res_type in ['basic', 'bottleneck'], 'residual type only support basic and bottleneck, not:{}'.format(res_type)
self.res_type = res_type
if self.res_type == 'basic':
self.conv1 = conv2d_blo... | Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> norm -> act -> 3*3*(1/4*C) -> norm -> act -> 1*1*C -> norm -> act -> out \\_... | ResBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
"""Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> norm -> act -> 3*3*(1/4*C) -> norm -> ac... | stack_v2_sparse_classes_75kplus_train_008192 | 4,174 | permissive | [
{
"docstring": "Overview: Init the Residual Block Arguments: - in_channels (:obj:`int`): Number of channels in the input tensor - activation (:obj:`nn.Module`): the optional activation function - norm_type (:obj:`str`): type of the normalization, defalut set to 'BN'(Batch Normalization), \\\\ supports ['BN', 'I... | 2 | stack_v2_sparse_classes_30k_train_022318 | Implement the Python class `ResBlock` described below.
Class description:
Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> n... | Implement the Python class `ResBlock` described below.
Class description:
Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> n... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class ResBlock:
"""Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> norm -> act -> 3*3*(1/4*C) -> norm -> ac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResBlock:
"""Overview: Residual Block with 2D convolution layers, including 2 types: basic block: input channel: C x -> 3*3*C -> norm -> act -> 3*3*C -> norm -> act -> out \\__________________________________________/+ bottleneck block: x -> 1*1*(1/4*C) -> norm -> act -> 3*3*(1/4*C) -> norm -> act -> 1*1*C ->... | the_stack_v2_python_sparse | ding/torch_utils/network/res_block.py | shengxuesun/DI-engine | train | 1 |
0816f2977fd3a45262fd87b27311ccfb103954ad | [
"if ircutils.strEqual(capability, 'owner'):\n irc.error('The \"owner\" capability can\\'t be added in the bot. Use the supybot-adduser program (or edit the users.conf file yourself) to add an owner capability.')\n return\nif ircdb.isAntiCapability(capability) or ircdb.checkCapability(msg.prefix, capability):... | <|body_start_0|>
if ircutils.strEqual(capability, 'owner'):
irc.error('The "owner" capability can\'t be added in the bot. Use the supybot-adduser program (or edit the users.conf file yourself) to add an owner capability.')
return
if ircdb.isAntiCapability(capability) or ircdb.ch... | capability | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class capability:
def add(self, irc, msg, args, user, capability):
"""<name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified capability <capability>"""
<|body_0|>
def remove(self, irc, msg, args, user, capabili... | stack_v2_sparse_classes_75kplus_train_008193 | 14,162 | permissive | [
{
"docstring": "<name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified capability <capability>",
"name": "add",
"signature": "def add(self, irc, msg, args, user, capability)"
},
{
"docstring": "<name|hostmask> <capability> Ta... | 2 | null | Implement the Python class `capability` described below.
Class description:
Implement the capability class.
Method signatures and docstrings:
- def add(self, irc, msg, args, user, capability): <name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified... | Implement the Python class `capability` described below.
Class description:
Implement the capability class.
Method signatures and docstrings:
- def add(self, irc, msg, args, user, capability): <name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified... | a7b12c97479e1236d5370166b15ca9f29d7d4265 | <|skeleton|>
class capability:
def add(self, irc, msg, args, user, capability):
"""<name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified capability <capability>"""
<|body_0|>
def remove(self, irc, msg, args, user, capabili... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class capability:
def add(self, irc, msg, args, user, capability):
"""<name|hostmask> <capability> Gives the user specified by <name> (or the user to whom <hostmask> currently maps) the specified capability <capability>"""
if ircutils.strEqual(capability, 'owner'):
irc.error('The "owner"... | the_stack_v2_python_sparse | blades/Supybot/plugins/Admin/plugin.py | krattai/AEBL | train | 4 | |
ebb18c219250e7caaa4b65bdf00f4b9db23a11d7 | [
"if fields is None:\n fields = self._default_fields\nfmt = json.dumps({field: f'%({field})s' for field in fields})\nfmt = fmt[:-1] + ', %(message)s' + fmt[-1]\nsuper().__init__(fmt)",
"if not isinstance(record.msg, dict):\n record.msg = {'message': record.msg}\nrecord.msg = json.dumps(record.msg, default=st... | <|body_start_0|>
if fields is None:
fields = self._default_fields
fmt = json.dumps({field: f'%({field})s' for field in fields})
fmt = fmt[:-1] + ', %(message)s' + fmt[-1]
super().__init__(fmt)
<|end_body_0|>
<|body_start_1|>
if not isinstance(record.msg, dict):
... | JsonFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonFormatter:
def __init__(self, fields=None):
"""Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format string (ignore spaces): { "levelname": "%(levelname)s", "asctime": "%(asctime)s", "funcName": "%(funcNa... | stack_v2_sparse_classes_75kplus_train_008194 | 4,304 | permissive | [
{
"docstring": "Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format string (ignore spaces): { \"levelname\": \"%(levelname)s\", \"asctime\": \"%(asctime)s\", \"funcName\": \"%(funcName)s\", %(message) }",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_015759 | Implement the Python class `JsonFormatter` described below.
Class description:
Implement the JsonFormatter class.
Method signatures and docstrings:
- def __init__(self, fields=None): Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format s... | Implement the Python class `JsonFormatter` described below.
Class description:
Implement the JsonFormatter class.
Method signatures and docstrings:
- def __init__(self, fields=None): Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format s... | c9ad06438e4d6c8b496b92eabd07d2b12e661e6e | <|skeleton|>
class JsonFormatter:
def __init__(self, fields=None):
"""Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format string (ignore spaces): { "levelname": "%(levelname)s", "asctime": "%(asctime)s", "funcName": "%(funcNa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonFormatter:
def __init__(self, fields=None):
"""Constructs a json-ready format string e.g. JsonFormatter(['levelname', 'asctime', 'name']) creates a simple Formatter with the format string (ignore spaces): { "levelname": "%(levelname)s", "asctime": "%(asctime)s", "funcName": "%(funcName)s", %(messa... | the_stack_v2_python_sparse | pylon/utils/logging.py | mao-liu/pylon-oss | train | 0 | |
0ee6b97f1af112dc4cb78cd78a37fe62d3de36a9 | [
"email_log = EMAIL_TIMES[self.level]\nemail_backlog = EMAIL_BACKLOG[self.level]\nnow = time.time()\noldest_email_time = min(email_log)\nif oldest_email_time < now - EMAIL_THROTTLE_TIME:\n email_log.append(now)\n if len(email_backlog) > 0:\n backlog = '\\n'.join(email_backlog)\n record.msg = str(... | <|body_start_0|>
email_log = EMAIL_TIMES[self.level]
email_backlog = EMAIL_BACKLOG[self.level]
now = time.time()
oldest_email_time = min(email_log)
if oldest_email_time < now - EMAIL_THROTTLE_TIME:
email_log.append(now)
if len(email_backlog) > 0:
... | PyExpLabSys modified SMTP handler | CustomSMTPHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
<|body_0|>
def getSubject(self, record):
"""Returns subject with hostname"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_008195 | 7,447 | no_license | [
{
"docstring": "Custom emit that throttles the number of email sent",
"name": "emit",
"signature": "def emit(self, record)"
},
{
"docstring": "Returns subject with hostname",
"name": "getSubject",
"signature": "def getSubject(self, record)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004859 | Implement the Python class `CustomSMTPHandler` described below.
Class description:
PyExpLabSys modified SMTP handler
Method signatures and docstrings:
- def emit(self, record): Custom emit that throttles the number of email sent
- def getSubject(self, record): Returns subject with hostname | Implement the Python class `CustomSMTPHandler` described below.
Class description:
PyExpLabSys modified SMTP handler
Method signatures and docstrings:
- def emit(self, record): Custom emit that throttles the number of email sent
- def getSubject(self, record): Returns subject with hostname
<|skeleton|>
class CustomS... | 14d2a24c3031a78da0d2d686c42bc01ffe18faca | <|skeleton|>
class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
<|body_0|>
def getSubject(self, record):
"""Returns subject with hostname"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
email_log = EMAIL_TIMES[self.level]
email_backlog = EMAIL_BACKLOG[self.level]
now = time.time()
oldest_email_time = min(emai... | the_stack_v2_python_sparse | PyExpLabSys/common/utilities.py | jlopezBolt/PyExpLabSys | train | 0 |
33dd6597dc36645bf9b6f23b878c80d4f009ee67 | [
"super().__init__()\nself.backbone_model = ElectraModel.from_cfg(backbone_cfg)\nif weight_initializer is None:\n weight_initializer = self.backbone_model.weight_initializer\nif bias_initializer is None:\n bias_initializer = self.backbone_model.bias_initializer\nself.rtd_encoder = nn.HybridSequential()\nself.r... | <|body_start_0|>
super().__init__()
self.backbone_model = ElectraModel.from_cfg(backbone_cfg)
if weight_initializer is None:
weight_initializer = self.backbone_model.weight_initializer
if bias_initializer is None:
bias_initializer = self.backbone_model.bias_initia... | It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether it is an original or a replacement. | ElectraDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectraDiscriminator:
"""It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether... | stack_v2_sparse_classes_75kplus_train_008196 | 45,388 | permissive | [
{
"docstring": "Parameters ---------- backbone_cfg weight_initializer bias_initializer",
"name": "__init__",
"signature": "def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None)"
},
{
"docstring": "Getting the scores of the replaced token detection of the whole sentence... | 2 | stack_v2_sparse_classes_30k_train_001155 | Implement the Python class `ElectraDiscriminator` described below.
Class description:
It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classificati... | Implement the Python class `ElectraDiscriminator` described below.
Class description:
It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classificati... | 1df42c561ae9552960e3f8b5f22e74de812a29c6 | <|skeleton|>
class ElectraDiscriminator:
"""It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElectraDiscriminator:
"""It is slightly different from the traditional mask language model which recover the masked word (find the matched word in dictionary). The Object of Discriminator in Electra is 'replaced token detection' that is a binary classification task to predicts every token whether it is an ori... | the_stack_v2_python_sparse | src/gluonnlp/models/electra.py | akshatgui/gluon-nlp | train | 0 |
c259767bc282f129e3c2b572ab2961d2753ade62 | [
"if not root:\n return []\nlevels = []\n\ndef helper(node, level):\n if len(levels) == level:\n levels.append([])\n levels[level].append(node.val)\n if node.left:\n helper(node.left, level + 1)\n if node.right:\n helper(node.right, level + 1)\nhelper(root, 0)\nreturn levels",
"... | <|body_start_0|>
if not root:
return []
levels = []
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
if node.left:
helper(node.left, level + 1)
if node.r... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
<|body_0|>
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Appr... | stack_v2_sparse_classes_75kplus_train_008197 | 1,611 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:",
"name": "get_level_order_traversal",
"signature": "def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]"
},
{
"docstring": "Approach: Iteration Time Complexity: O(n) Space C... | 2 | stack_v2_sparse_classes_30k_train_044803 | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]: Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:
- def get_level... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]: Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:
- def get_level... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
<|body_0|>
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Appr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
if not root:
return []
levels = []
def helper(node, level):
if len(levels) =... | the_stack_v2_python_sparse | data_structures/tree_node/bst_level_order_traversal.py | Shiv2157k/leet_code | train | 1 | |
920075c5fd7ca8eb5c695ef4b29b238f3b747b72 | [
"essential_keys = ['nvars', 'nu', 'eps', 'newton_maxiter', 'newton_tol', 'lin_tol', 'lin_maxiter', 'radius']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\nif len(prob... | <|body_start_0|>
essential_keys = ['nvars', 'nu', 'eps', 'newton_maxiter', 'newton_tol', 'lin_tol', 'lin_maxiter', 'radius']
for key in essential_keys:
if key not in problem_params:
msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
... | Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions) | allencahn_fullyimplicit | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class allencahn_fullyimplicit:
"""Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions)"""
def __init__(self, problem_para... | stack_v2_sparse_classes_75kplus_train_008198 | 19,260 | permissive | [
{
"docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class)",
"name": "__init__",
"signature": "def __init__(self, problem_params, dtype_u=mesh, dtype_f=m... | 5 | stack_v2_sparse_classes_30k_train_001976 | Implement the Python class `allencahn_fullyimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions)
... | Implement the Python class `allencahn_fullyimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions)
... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class allencahn_fullyimplicit:
"""Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions)"""
def __init__(self, problem_para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class allencahn_fullyimplicit:
"""Example implementing the Allen-Cahn equation in 2D with finite differences and periodic BC Attributes: A: second-order FD discretization of the 2D laplace operator dx: distance between two spatial nodes (same for both directions)"""
def __init__(self, problem_params, dtype_u=m... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AllenCahn_2D_FD.py | ruthschoebel/pySDC | train | 0 |
50f58364e49b6d0a0627849007e33ec0d04cd4d0 | [
"self.char = char\nself.time = 0\nself.max_ready = 1\nself.isrun = True\nself.log = []\nfor char in self.char:\n char.log = self.log\n for a in char.attrib:\n char.attrib[a].log = self.log\n if 'life' in char.attrib:\n char.life = char.max_life = char.attrib['life'].level\n if 'speed' in c... | <|body_start_0|>
self.char = char
self.time = 0
self.max_ready = 1
self.isrun = True
self.log = []
for char in self.char:
char.log = self.log
for a in char.attrib:
char.attrib[a].log = self.log
if 'life' in char.attrib:
... | Class for battle | Battle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
<|body_0|>
def run(self):
"""Runs a battle"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008199 | 1,267 | no_license | [
{
"docstring": "Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])",
"name": "__init__",
"signature": "def __init__(self, char)"
},
{
"docstring": "Runs a battle",
"name": "run",
"signature": "def run(sel... | 2 | stack_v2_sparse_classes_30k_train_054142 | Implement the Python class `Battle` described below.
Class description:
Class for battle
Method signatures and docstrings:
- def __init__(self, char): Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])
- def run(self): Runs a battle | Implement the Python class `Battle` described below.
Class description:
Class for battle
Method signatures and docstrings:
- def __init__(self, char): Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])
- def run(self): Runs a battle
... | 7ba98e5a0c5c3b42b3c3707844daed9b0f4f2856 | <|skeleton|>
class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
<|body_0|>
def run(self):
"""Runs a battle"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
self.char = char
self.time = 0
self.max_ready = 1
self.isrun = True... | the_stack_v2_python_sparse | extsea/battle.py | szatkus/durenV | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.