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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
720d6b3cd0efc383c3f896faba4fb884eb91f113 | [
"LayoutItem.__init__(self, dom, parent_element, line_object, mxd, arc_doc)\nself.dom = dom\nself.parent_element = parent_element\nself.line_object = line_object\nself.mxd = mxd\nself.arc_doc = arc_doc",
"arcpy_item = LayoutItem.get_arcpy_layout_element(self, self.line_object)\nLineElement.set_size_and_position(se... | <|body_start_0|>
LayoutItem.__init__(self, dom, parent_element, line_object, mxd, arc_doc)
self.dom = dom
self.parent_element = parent_element
self.line_object = line_object
self.mxd = mxd
self.arc_doc = arc_doc
<|end_body_0|>
<|body_start_1|>
arcpy_item = Layout... | LineElement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineElement:
def __init__(self, dom, parent_element, line_object, mxd, arc_doc):
"""This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param line_object: the line_object as ... | stack_v2_sparse_classes_75kplus_train_008200 | 2,296 | permissive | [
{
"docstring": "This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param line_object: the line_object as ArcObject :param mxd: the arcpy mxd-document :param arc_doc: the ArcObject IMxDocument",
... | 2 | stack_v2_sparse_classes_30k_train_012897 | Implement the Python class `LineElement` described below.
Class description:
Implement the LineElement class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, line_object, mxd, arc_doc): This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_ele... | Implement the Python class `LineElement` described below.
Class description:
Implement the LineElement class.
Method signatures and docstrings:
- def __init__(self, dom, parent_element, line_object, mxd, arc_doc): This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_ele... | cd0aa5f533194c85cf6e098fadc079ea61b63fce | <|skeleton|>
class LineElement:
def __init__(self, dom, parent_element, line_object, mxd, arc_doc):
"""This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param line_object: the line_object as ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LineElement:
def __init__(self, dom, parent_element, line_object, mxd, arc_doc):
"""This function creates a Line-Item for the layout :param dom: the Document Object Model :param parent_element: the main layout element, where to put the layout-items :param line_object: the line_object as ArcObject :par... | the_stack_v2_python_sparse | layout/lineElement.py | avaldeon/mapqonverter | train | 0 | |
bf9225d6b7873e1a0983e446633270de40a3ce8d | [
"self.nn_depth = nn_kwargs['depth']\nself.nn_hid_units = nn_kwargs['hid_units']\nself.nn_hid_nonlinearity = nn_kwargs['hid_nonlinearity']\nsuper(RecMLP, self).__init__(input_max_len_x, input_max_len_y, vocab_size, z_dim, z_dist)\nself.mean_x, self.cov_x = self.nn_fn(input_max_len_x)\nself.mean_y, self.cov_y = self.... | <|body_start_0|>
self.nn_depth = nn_kwargs['depth']
self.nn_hid_units = nn_kwargs['hid_units']
self.nn_hid_nonlinearity = nn_kwargs['hid_nonlinearity']
super(RecMLP, self).__init__(input_max_len_x, input_max_len_y, vocab_size, z_dim, z_dist)
self.mean_x, self.cov_x = self.nn_fn(i... | RecMLP | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecMLP:
def __init__(self, input_max_len_x, input_max_len_y, vocab_size, nn_kwargs, z_dim, z_dist):
""":param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (int) maximum length of input data (y) :param input_vocab_size_x: (int) size of the vocabulary fro... | stack_v2_sparse_classes_75kplus_train_008201 | 25,399 | permissive | [
{
"docstring": ":param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (int) maximum length of input data (y) :param input_vocab_size_x: (int) size of the vocabulary from input language x :param input_vocab_size_y: (int) size of the vocabulary from input language y :param nn_kwar... | 2 | null | Implement the Python class `RecMLP` described below.
Class description:
Implement the RecMLP class.
Method signatures and docstrings:
- def __init__(self, input_max_len_x, input_max_len_y, vocab_size, nn_kwargs, z_dim, z_dist): :param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (in... | Implement the Python class `RecMLP` described below.
Class description:
Implement the RecMLP class.
Method signatures and docstrings:
- def __init__(self, input_max_len_x, input_max_len_y, vocab_size, nn_kwargs, z_dim, z_dist): :param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (in... | 48a59c73b6afcabba457d65c7596a71b515533e6 | <|skeleton|>
class RecMLP:
def __init__(self, input_max_len_x, input_max_len_y, vocab_size, nn_kwargs, z_dim, z_dist):
""":param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (int) maximum length of input data (y) :param input_vocab_size_x: (int) size of the vocabulary fro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecMLP:
def __init__(self, input_max_len_x, input_max_len_y, vocab_size, nn_kwargs, z_dim, z_dist):
""":param input_max_len_x: (int) maximum length of input data (x) :param input_max_len_y: (int) maximum length of input data (y) :param input_vocab_size_x: (int) size of the vocabulary from input langua... | the_stack_v2_python_sparse | Translation/src/models/recognition_models.py | IsakFalk/project | train | 0 | |
4253aa4ac0e41ca5e2fa9e00e54db78befc79d85 | [
"playbooks = self._client.get_playbooks(**kwargs)['items']\nif check:\n assert_that(playbooks, is_not(empty()))\nreturn playbooks",
"playbooks = self.get_playbooks(**kwargs)\nfor playbook in playbooks:\n if playbook['id'] == playbook_id:\n break\nelse:\n playbook = None\nif check:\n assert_that... | <|body_start_0|>
playbooks = self._client.get_playbooks(**kwargs)['items']
if check:
assert_that(playbooks, is_not(empty()))
return playbooks
<|end_body_0|>
<|body_start_1|>
playbooks = self.get_playbooks(**kwargs)
for playbook in playbooks:
if playbook['... | Playbook steps. | PlaybookSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if c... | stack_v2_sparse_classes_75kplus_train_008202 | 2,018 | no_license | [
{
"docstring": "Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if check failed",
"name": "get_playbooks",
"signature": "def get_playbooks(self, check=True, **... | 2 | stack_v2_sparse_classes_30k_train_046236 | Implement the Python class `PlaybookSteps` described below.
Class description:
Playbook steps.
Method signatures and docstrings:
- def get_playbooks(self, check=True, **kwargs): Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns:... | Implement the Python class `PlaybookSteps` described below.
Class description:
Playbook steps.
Method signatures and docstrings:
- def get_playbooks(self, check=True, **kwargs): Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns:... | 78950b95d98e791e6e5852aaef05ce9b7266be04 | <|skeleton|>
class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlaybookSteps:
"""Playbook steps."""
def get_playbooks(self, check=True, **kwargs):
"""Step to get all available playbooks. Args: check (bool): flag whether to check step or not **kwargs: any suitable keyword arguments Returns: list: list of all playbooks Raises: AssertionError: if check failed""... | the_stack_v2_python_sparse | whale/decapod/steps/playbooks.py | Mirantis/whale | train | 1 |
fc7191b168f300acb8a3cb84cb9a4b42af2fa7d0 | [
"self._renderer = renderer\nself._width = self._renderer.width\nself._height = self._renderer.height\nself._big = int(self._height / 10)\nself.small = int(self._height / 20)\nself._lines = []",
"self._lines.append(['ENTER YOUR NICKNAME', self.small, self._width / 2, self._height / 2])\nself._lines.append([nicknam... | <|body_start_0|>
self._renderer = renderer
self._width = self._renderer.width
self._height = self._renderer.height
self._big = int(self._height / 10)
self.small = int(self._height / 20)
self._lines = []
<|end_body_0|>
<|body_start_1|>
self._lines.append(['ENTER Y... | A class to represent new game view of UI. Attributes: renderer: Renderer object. | NewGameView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewGameView:
"""A class to represent new game view of UI. Attributes: renderer: Renderer object."""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer object which renders the display."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_008203 | 1,934 | no_license | [
{
"docstring": "Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer object which renders the display.",
"name": "__init__",
"signature": "def __init__(self, renderer)"
},
{
"docstring": "Prepares all information to show for the renderer object. New game v... | 2 | null | Implement the Python class `NewGameView` described below.
Class description:
A class to represent new game view of UI. Attributes: renderer: Renderer object.
Method signatures and docstrings:
- def __init__(self, renderer): Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer o... | Implement the Python class `NewGameView` described below.
Class description:
A class to represent new game view of UI. Attributes: renderer: Renderer object.
Method signatures and docstrings:
- def __init__(self, renderer): Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer o... | 29cd15dddff620de068a479595a5cb9aba855343 | <|skeleton|>
class NewGameView:
"""A class to represent new game view of UI. Attributes: renderer: Renderer object."""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer object which renders the display."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewGameView:
"""A class to represent new game view of UI. Attributes: renderer: Renderer object."""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view. Args: renderer (Renderer): Renderer object which renders the display."""
self._renderer = renderer
... | the_stack_v2_python_sparse | src/ui/new_game_view.py | TopiasHarjunpaa/ot-harjoitustyo | train | 0 |
60392b959b52d3e8e49f8e465d1a3644d085de2c | [
"with open(path, 'r') as stream:\n lines = []\n for line in stream:\n if line.startswith(self.separator):\n yield self._parse(''.join(lines))\n lines = []\n else:\n lines.append(line)",
"with open(path, 'r') as stream:\n for line in stream:\n yield se... | <|body_start_0|>
with open(path, 'r') as stream:
lines = []
for line in stream:
if line.startswith(self.separator):
yield self._parse(''.join(lines))
lines = []
else:
lines.append(line)
<|end_body... | Parser reads trace log files generated by the Fluidinfo API service. | TraceLogParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraceLogParser:
"""Parser reads trace log files generated by the Fluidinfo API service."""
def parseOldFormat(self, path):
"""Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatib... | stack_v2_sparse_classes_75kplus_train_008204 | 10,436 | permissive | [
{
"docstring": "Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatibility. @param path: The path to a trace log file.",
"name": "parseOldFormat",
"signature": "def parseOldFormat(self, path)"
},
... | 3 | stack_v2_sparse_classes_30k_train_001550 | Implement the Python class `TraceLogParser` described below.
Class description:
Parser reads trace log files generated by the Fluidinfo API service.
Method signatures and docstrings:
- def parseOldFormat(self, path): Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for eac... | Implement the Python class `TraceLogParser` described below.
Class description:
Parser reads trace log files generated by the Fluidinfo API service.
Method signatures and docstrings:
- def parseOldFormat(self, path): Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for eac... | b5a8c8349f3eaf3364cc4efba4736c3e33b30d96 | <|skeleton|>
class TraceLogParser:
"""Parser reads trace log files generated by the Fluidinfo API service."""
def parseOldFormat(self, path):
"""Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatib... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TraceLogParser:
"""Parser reads trace log files generated by the Fluidinfo API service."""
def parseOldFormat(self, path):
"""Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatibility. @param... | the_stack_v2_python_sparse | fluiddb/scripts/logs.py | fluidinfo/fluiddb | train | 3 |
aebf74c7a423da1aea7c9bcbc05a9562b76a712b | [
"variant = super().create(**kwargs)\nfrom .tasks import update_product_minimal_variant_price_task\nupdate_product_minimal_variant_price_task.delay(variant.product_id)\nreturn variant",
"variants = super().bulk_create(objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts)\nproduct_ids = set()\nfor obj in ... | <|body_start_0|>
variant = super().create(**kwargs)
from .tasks import update_product_minimal_variant_price_task
update_product_minimal_variant_price_task.delay(variant.product_id)
return variant
<|end_body_0|>
<|body_start_1|>
variants = super().bulk_create(objs, batch_size=bat... | ProductVariantQueryset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductVariantQueryset:
def create(self, **kwargs):
"""Create a product's variant. After the creation update the "minimal_variant_price" of the product."""
<|body_0|>
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
"""Insert each of the product'... | stack_v2_sparse_classes_75kplus_train_008205 | 20,044 | permissive | [
{
"docstring": "Create a product's variant. After the creation update the \"minimal_variant_price\" of the product.",
"name": "create",
"signature": "def create(self, **kwargs)"
},
{
"docstring": "Insert each of the product's variant instances into the database. After the creation update the \"m... | 2 | stack_v2_sparse_classes_30k_train_023229 | Implement the Python class `ProductVariantQueryset` described below.
Class description:
Implement the ProductVariantQueryset class.
Method signatures and docstrings:
- def create(self, **kwargs): Create a product's variant. After the creation update the "minimal_variant_price" of the product.
- def bulk_create(self, ... | Implement the Python class `ProductVariantQueryset` described below.
Class description:
Implement the ProductVariantQueryset class.
Method signatures and docstrings:
- def create(self, **kwargs): Create a product's variant. After the creation update the "minimal_variant_price" of the product.
- def bulk_create(self, ... | 0a190ca9bcf96cf44f7773686205f2c1f83f3769 | <|skeleton|>
class ProductVariantQueryset:
def create(self, **kwargs):
"""Create a product's variant. After the creation update the "minimal_variant_price" of the product."""
<|body_0|>
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
"""Insert each of the product'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductVariantQueryset:
def create(self, **kwargs):
"""Create a product's variant. After the creation update the "minimal_variant_price" of the product."""
variant = super().create(**kwargs)
from .tasks import update_product_minimal_variant_price_task
update_product_minimal_var... | the_stack_v2_python_sparse | product/new_product.py | rajeshr188/django-onex | train | 2 | |
d79a915a8848ee13b1992776d28b756122ddc83d | [
"super().__init__(fmc, **kwargs)\nlogging.debug('In __init__() for SLAMonitors class.')\nself.parse_kwargs(**kwargs)\nself.type = 'SLAMonitor'",
"logging.debug('In interfaces() for SLAMonitors class.')\nzones = []\nfor name in names:\n sz = SecurityZones(fmc=self.fmc)\n sz.get(name=name)\n if 'id' in sz.... | <|body_start_0|>
super().__init__(fmc, **kwargs)
logging.debug('In __init__() for SLAMonitors class.')
self.parse_kwargs(**kwargs)
self.type = 'SLAMonitor'
<|end_body_0|>
<|body_start_1|>
logging.debug('In interfaces() for SLAMonitors class.')
zones = []
for name... | The SLAMonitors Object in the FMC. | SLAMonitors | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLAMonitors:
"""The SLAMonitors Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize SLAMonitors object. Set self.type to "SLAMonitor" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any other values passed during instantiation. :return: None"""... | stack_v2_sparse_classes_75kplus_train_008206 | 2,469 | permissive | [
{
"docstring": "Initialize SLAMonitors object. Set self.type to \"SLAMonitor\" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any other values passed during instantiation. :return: None",
"name": "__init__",
"signature": "def __init__(self, fmc, **kwargs)"
},
{
"docstring":... | 2 | null | Implement the Python class `SLAMonitors` described below.
Class description:
The SLAMonitors Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize SLAMonitors object. Set self.type to "SLAMonitor" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any o... | Implement the Python class `SLAMonitors` described below.
Class description:
The SLAMonitors Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize SLAMonitors object. Set self.type to "SLAMonitor" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any o... | fd924de96e200ca8e0d5088b27a5abaf6f915bc6 | <|skeleton|>
class SLAMonitors:
"""The SLAMonitors Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize SLAMonitors object. Set self.type to "SLAMonitor" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any other values passed during instantiation. :return: None"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SLAMonitors:
"""The SLAMonitors Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize SLAMonitors object. Set self.type to "SLAMonitor" and parse the kwargs. :param fmc: (object) FMC object :param kwargs: Any other values passed during instantiation. :return: None"""
supe... | the_stack_v2_python_sparse | fmcapi/api_objects/object_services/slamonitors.py | banzigaga/fmcapi | train | 1 |
e482bcd3a61f50d5a3068bbdc0fe1a82b7324000 | [
"try:\n user = request.REQUEST.get('from')\n message = request.REQUEST.get('text')\n sms = SmsMessage.objects.create(user=user, message=message)\n sms.save()\n return Response('Your message is noted. Thank you.', status=HTTP_200_OK)\nexcept Exception:\n return Response('Could not send message', st... | <|body_start_0|>
try:
user = request.REQUEST.get('from')
message = request.REQUEST.get('text')
sms = SmsMessage.objects.create(user=user, message=message)
sms.save()
return Response('Your message is noted. Thank you.', status=HTTP_200_OK)
excep... | SmsMessageViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmsMessageViewSet:
def sms(self, request):
"""Receive sms from smsgh"""
<|body_0|>
def verified(self, request):
"""Receive only verified and unverified sms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
user = request.REQUEST.get('... | stack_v2_sparse_classes_75kplus_train_008207 | 2,061 | no_license | [
{
"docstring": "Receive sms from smsgh",
"name": "sms",
"signature": "def sms(self, request)"
},
{
"docstring": "Receive only verified and unverified sms",
"name": "verified",
"signature": "def verified(self, request)"
}
] | 2 | null | Implement the Python class `SmsMessageViewSet` described below.
Class description:
Implement the SmsMessageViewSet class.
Method signatures and docstrings:
- def sms(self, request): Receive sms from smsgh
- def verified(self, request): Receive only verified and unverified sms | Implement the Python class `SmsMessageViewSet` described below.
Class description:
Implement the SmsMessageViewSet class.
Method signatures and docstrings:
- def sms(self, request): Receive sms from smsgh
- def verified(self, request): Receive only verified and unverified sms
<|skeleton|>
class SmsMessageViewSet:
... | 7a6a9c55df471a67ff0e34e229297d7cc0cd7d56 | <|skeleton|>
class SmsMessageViewSet:
def sms(self, request):
"""Receive sms from smsgh"""
<|body_0|>
def verified(self, request):
"""Receive only verified and unverified sms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmsMessageViewSet:
def sms(self, request):
"""Receive sms from smsgh"""
try:
user = request.REQUEST.get('from')
message = request.REQUEST.get('text')
sms = SmsMessage.objects.create(user=user, message=message)
sms.save()
return Respon... | the_stack_v2_python_sparse | ouroilmoney/utils/api/views.py | pharingee/OuroilMoney | train | 0 | |
2708f7a7f22568988075f8b06b46d07ec4fd12f9 | [
"self.network = network\nip_network = ipaddress.ip_network('{}/{}'.format(self.network.ip, self.network.prefix))\nif ip_network.prefixlen < 24 and ip_network.version == 4:\n self.subnets = []\n for subnet in ip_network.subnets(new_prefix=24):\n self.subnets.append(subnet)\nelse:\n self.subnets = [ip... | <|body_start_0|>
self.network = network
ip_network = ipaddress.ip_network('{}/{}'.format(self.network.ip, self.network.prefix))
if ip_network.prefixlen < 24 and ip_network.version == 4:
self.subnets = []
for subnet in ip_network.subnets(new_prefix=24):
sel... | This class manage Bind9 file production. This only reverse IP resolution. | BindReverse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BindReverse:
"""This class manage Bind9 file production. This only reverse IP resolution."""
def __init__(self, network, directory):
"""Just a constructor for bind, we need a network name to produce and a directory where to put data generated. :param network: network name :param dire... | stack_v2_sparse_classes_75kplus_train_008208 | 10,711 | no_license | [
{
"docstring": "Just a constructor for bind, we need a network name to produce and a directory where to put data generated. :param network: network name :param directory: directory where to put",
"name": "__init__",
"signature": "def __init__(self, network, directory)"
},
{
"docstring": "This me... | 5 | stack_v2_sparse_classes_30k_val_000622 | Implement the Python class `BindReverse` described below.
Class description:
This class manage Bind9 file production. This only reverse IP resolution.
Method signatures and docstrings:
- def __init__(self, network, directory): Just a constructor for bind, we need a network name to produce and a directory where to put... | Implement the Python class `BindReverse` described below.
Class description:
This class manage Bind9 file production. This only reverse IP resolution.
Method signatures and docstrings:
- def __init__(self, network, directory): Just a constructor for bind, we need a network name to produce and a directory where to put... | ec2f6f07ec6ce275d23b4482889bb1fbd27830ca | <|skeleton|>
class BindReverse:
"""This class manage Bind9 file production. This only reverse IP resolution."""
def __init__(self, network, directory):
"""Just a constructor for bind, we need a network name to produce and a directory where to put data generated. :param network: network name :param dire... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BindReverse:
"""This class manage Bind9 file production. This only reverse IP resolution."""
def __init__(self, network, directory):
"""Just a constructor for bind, we need a network name to produce and a directory where to put data generated. :param network: network name :param directory: direct... | the_stack_v2_python_sparse | slam/slam_core/producer/bind.py | guillaume-philippon/slam-v2 | train | 0 |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nmod = adm.get_module_by_id(module_id)\nreturn mod",
"adm = ProjectAdministration()\nmod = adm.get_module_by_id(module_id)\nif mod is not None:\n adm.delete_module(mod)\n return ('gelöscht', 200)\nelse:\n return ('There was some error', 500)"
] | <|body_start_0|>
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
return mod
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
if mod is not None:
adm.delete_module(mod)
return (... | ModuleOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, module_id):
"""Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem ... | stack_v2_sparse_classes_75kplus_train_008209 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, module_id)"
},
{
"docstring": "Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.",
"name... | 2 | stack_v2_sparse_classes_30k_train_032925 | Implement the Python class `ModuleOperations` described below.
Class description:
Implement the ModuleOperations class.
Method signatures and docstrings:
- def get(self, module_id): Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.
- def delete(self, module_id): Löschen ... | Implement the Python class `ModuleOperations` described below.
Class description:
Implement the ModuleOperations class.
Method signatures and docstrings:
- def get(self, module_id): Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird.
- def delete(self, module_id): Löschen ... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, module_id):
"""Löschen eines bestimmten Module-Objektes, welches durch die module_id in dem ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleOperations:
def get(self, module_id):
"""Auslesen eines bestimmten Module-Objektes, welches durch die module_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
mod = adm.get_module_by_id(module_id)
return mod
def delete(self, module_id):
"""Löschen... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
d1ce4d3dd79b6c6f518439459f11d4cff72d0534 | [
"self.Q = Q\nself.env = env\nself.mode = mode\nself.epsilon = 0.0",
"if self.mode == 'learning_mode':\n if self.epsilon <= np.random.uniform(0, 1):\n action = np.argmax(self.Q[state])\n else:\n action = np.random.choice(4)\nelse:\n action = np.argmax(self.Q[state])\nreturn action",
"max_e... | <|body_start_0|>
self.Q = Q
self.env = env
self.mode = mode
self.epsilon = 0.0
<|end_body_0|>
<|body_start_1|>
if self.mode == 'learning_mode':
if self.epsilon <= np.random.uniform(0, 1):
action = np.argmax(self.Q[state])
else:
... | Agent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
def __init__(self, Q, env, mode):
"""initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode"""
<|body_0|>
def select_action(self, state):
"""choose action w.r.t state and modes :param state: current stat... | stack_v2_sparse_classes_75kplus_train_008210 | 2,439 | no_license | [
{
"docstring": "initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode",
"name": "__init__",
"signature": "def __init__(self, Q, env, mode)"
},
{
"docstring": "choose action w.r.t state and modes :param state: current states :return: actio... | 3 | stack_v2_sparse_classes_30k_train_044316 | Implement the Python class `Agent` described below.
Class description:
Implement the Agent class.
Method signatures and docstrings:
- def __init__(self, Q, env, mode): initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode
- def select_action(self, state): choo... | Implement the Python class `Agent` described below.
Class description:
Implement the Agent class.
Method signatures and docstrings:
- def __init__(self, Q, env, mode): initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode
- def select_action(self, state): choo... | eee8df550d65e1831364e578a70b05d8eda86629 | <|skeleton|>
class Agent:
def __init__(self, Q, env, mode):
"""initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode"""
<|body_0|>
def select_action(self, state):
"""choose action w.r.t state and modes :param state: current stat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Agent:
def __init__(self, Q, env, mode):
"""initialize values :param Q: Q table :param env: open ai gym environment :param mode: learning mode or test mode"""
self.Q = Q
self.env = env
self.mode = mode
self.epsilon = 0.0
def select_action(self, state):
"""c... | the_stack_v2_python_sparse | assignment1/agent.py | psycoder-sup/RL | train | 0 | |
694c38324e3bf23b4398aefe1d0871af5e873463 | [
"if stack:\n node = stack.pop()\n if node.right:\n node = node.right\n stack.append(node)\n while node.left:\n node = node.left\n stack.append(node)\n else:\n while stack and stack[-1].val < node.val:\n stack.pop()\n return stack[-1] if stack ... | <|body_start_0|>
if stack:
node = stack.pop()
if node.right:
node = node.right
stack.append(node)
while node.left:
node = node.left
stack.append(node)
else:
while stack and... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _nextGT(self, stack):
"""find node with smallest value > stack[-1].val."""
<|body_0|>
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
"""Q0272, inorder predecessor and successor."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_008211 | 921 | no_license | [
{
"docstring": "find node with smallest value > stack[-1].val.",
"name": "_nextGT",
"signature": "def _nextGT(self, stack)"
},
{
"docstring": "Q0272, inorder predecessor and successor.",
"name": "inorderSuccessor",
"signature": "def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> ... | 2 | stack_v2_sparse_classes_30k_train_023234 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _nextGT(self, stack): find node with smallest value > stack[-1].val.
- def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: Q0272, inorder predecessor and suc... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _nextGT(self, stack): find node with smallest value > stack[-1].val.
- def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: Q0272, inorder predecessor and suc... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def _nextGT(self, stack):
"""find node with smallest value > stack[-1].val."""
<|body_0|>
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
"""Q0272, inorder predecessor and successor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _nextGT(self, stack):
"""find node with smallest value > stack[-1].val."""
if stack:
node = stack.pop()
if node.right:
node = node.right
stack.append(node)
while node.left:
node = node.lef... | the_stack_v2_python_sparse | src/0200-0299/0285.inorder.successor.bst.py | gyang274/leetcode | train | 1 | |
728b20229b80d8dfac05b05ee5a35e76c5e7c970 | [
"messages = []\nif not self.preventEffects(user, target):\n for effect in self.parent.effectDelegates:\n messages += effect.tryToApplyEffect(user, target, environment)\nreturn messages",
"nullDamage = hasattr(self.parent.damageDelegate, 'isNull')\ncanUse = user.getAbility().canUseEffects() and target.ge... | <|body_start_0|>
messages = []
if not self.preventEffects(user, target):
for effect in self.parent.effectDelegates:
messages += effect.tryToApplyEffect(user, target, environment)
return messages
<|end_body_0|>
<|body_start_1|>
nullDamage = hasattr(self.parent... | Represents the Effects Step in the Attack Process | EffectsStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EffectsStep:
"""Represents the Effects Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
<|body_0|>
def preventEffects(self, user, target):
"""Return whether the effects are prevented"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_008212 | 813 | no_license | [
{
"docstring": "Perform this step",
"name": "perform",
"signature": "def perform(self, user, target, environment)"
},
{
"docstring": "Return whether the effects are prevented",
"name": "preventEffects",
"signature": "def preventEffects(self, user, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047755 | Implement the Python class `EffectsStep` described below.
Class description:
Represents the Effects Step in the Attack Process
Method signatures and docstrings:
- def perform(self, user, target, environment): Perform this step
- def preventEffects(self, user, target): Return whether the effects are prevented | Implement the Python class `EffectsStep` described below.
Class description:
Represents the Effects Step in the Attack Process
Method signatures and docstrings:
- def perform(self, user, target, environment): Perform this step
- def preventEffects(self, user, target): Return whether the effects are prevented
<|skele... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class EffectsStep:
"""Represents the Effects Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
<|body_0|>
def preventEffects(self, user, target):
"""Return whether the effects are prevented"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EffectsStep:
"""Represents the Effects Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
messages = []
if not self.preventEffects(user, target):
for effect in self.parent.effectDelegates:
messages += eff... | the_stack_v2_python_sparse | src/Battle/Attack/Steps/effects_step.py | sgtnourry/Pokemon-Project | train | 0 |
ec33233536d7869246af2ec9a48aecbced517060 | [
"category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]\nvideo_evaluator = coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)\nvideo_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict=[{standard_fields.InputDataFields.groundtruth_boxes: np.array([[50.0, 50.... | <|body_start_0|>
category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]
video_evaluator = coco_evaluation_all_frames.CocoEvaluationAllFrames(category_list)
video_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict=[{standard_fields.InputDataFields.groun... | CocoEvaluationAllFramesTest | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
<|body_0|>
def testGroundtruthAndDetections(self):
"""Tests that mAP is calculated correctly on GT and Detec... | stack_v2_sparse_classes_75kplus_train_008213 | 6,730 | permissive | [
{
"docstring": "Tests that mAP is calculated on several different frame results.",
"name": "testGroundtruthAndDetectionsDisagreeOnAllFrames",
"signature": "def testGroundtruthAndDetectionsDisagreeOnAllFrames(self)"
},
{
"docstring": "Tests that mAP is calculated correctly on GT and Detections.",... | 3 | stack_v2_sparse_classes_30k_train_013679 | Implement the Python class `CocoEvaluationAllFramesTest` described below.
Class description:
Implement the CocoEvaluationAllFramesTest class.
Method signatures and docstrings:
- def testGroundtruthAndDetectionsDisagreeOnAllFrames(self): Tests that mAP is calculated on several different frame results.
- def testGround... | Implement the Python class `CocoEvaluationAllFramesTest` described below.
Class description:
Implement the CocoEvaluationAllFramesTest class.
Method signatures and docstrings:
- def testGroundtruthAndDetectionsDisagreeOnAllFrames(self): Tests that mAP is calculated on several different frame results.
- def testGround... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
<|body_0|>
def testGroundtruthAndDetections(self):
"""Tests that mAP is calculated correctly on GT and Detec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CocoEvaluationAllFramesTest:
def testGroundtruthAndDetectionsDisagreeOnAllFrames(self):
"""Tests that mAP is calculated on several different frame results."""
category_list = [{'id': 0, 'name': 'dog'}, {'id': 1, 'name': 'cat'}]
video_evaluator = coco_evaluation_all_frames.CocoEvaluatio... | the_stack_v2_python_sparse | models/research/lstm_object_detection/metrics/coco_evaluation_all_frames_test.py | finnickniu/tensorflow_object_detection_tflite | train | 60 | |
db263ab9fb132c603fa1568b119ab4c0bdbafa96 | [
"domain = Site.objects.get_current().domain\nwebhook_url = f'https://{domain}/webhooks/twitter/'\nself.stdout.write(f' Registering {webhook_url}...')\nendpoint = f'account_activity/all/:{settings.TWITTER_API_ENV}/webhooks'\nresponse = self.twitter_api.request(endpoint, params={'url': webhook_url})\n'\\n try:... | <|body_start_0|>
domain = Site.objects.get_current().domain
webhook_url = f'https://{domain}/webhooks/twitter/'
self.stdout.write(f' Registering {webhook_url}...')
endpoint = f'account_activity/all/:{settings.TWITTER_API_ENV}/webhooks'
response = self.twitter_api.request(endpoint... | Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url. | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url."""
def handle(self, *args, **options):
"""Handle the command."""
<|bo... | stack_v2_sparse_classes_75kplus_train_008214 | 2,065 | permissive | [
{
"docstring": "Handle the command.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Write each in item to stdout with style.",
"name": "write_stylized_response_items",
"signature": "def write_stylized_response_items(self, items, error=False)"
}
... | 2 | stack_v2_sparse_classes_30k_val_002593 | Implement the Python class `Command` described below.
Class description:
Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url.
Method signatures and docstrings:
- def handle(sel... | Implement the Python class `Command` described below.
Class description:
Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url.
Method signatures and docstrings:
- def handle(sel... | 06294ee4655734108850577774d3caf615f66520 | <|skeleton|>
class Command:
"""Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url."""
def handle(self, *args, **options):
"""Handle the command."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""Register a webhook url for the current domain. Sends a POST request to the webhooks endpoint of Twitter's Account Activity API. This triggers a CRC request from Twitter to the app's webhook url."""
def handle(self, *args, **options):
"""Handle the command."""
domain = Site.obj... | the_stack_v2_python_sparse | tweets2text/management/commands/registerwebhook.py | realAyinde/tweets-to-text | train | 0 |
73e58d9ea43f2632dd821d4bb6eb12543e0ba8d0 | [
"IO_files = {}\nfile_names = set()\nfor fl in in_dir.files:\n if self.name not in fl.users:\n if utils.splitext(fl.name)[-1] in self.input_types:\n IO_files['--!xcf'] = os.path.join(in_dir.path, fl.name)\n command_ids = [utils.infer_path_id(IO_files['--!xcf'])]\n in_dir.us... | <|body_start_0|>
IO_files = {}
file_names = set()
for fl in in_dir.files:
if self.name not in fl.users:
if utils.splitext(fl.name)[-1] in self.input_types:
IO_files['--!xcf'] = os.path.join(in_dir.path, fl.name)
command_ids = [u... | Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attributes: name: Name of the... | VCFtools | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VCFtools:
"""Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file ... | stack_v2_sparse_classes_75kplus_train_008215 | 11,470 | permissive | [
{
"docstring": "Infers the input and output file paths. This method must keep the directory objects up to date of the file edits! Parameters: in_cmd: A dict containing the command line. in_dir: Input directory (instance of filetypes.Directory). out_dir: Output directory (instance of filetypes.Directory). Return... | 4 | stack_v2_sparse_classes_30k_train_006330 | Implement the Python class `VCFtools` described below.
Class description:
Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the d... | Implement the Python class `VCFtools` described below.
Class description:
Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the d... | fd83eee4be0bb78c67a111fd1c1c1dff4c16aefe | <|skeleton|>
class VCFtools:
"""Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VCFtools:
"""Class for generic command lines, also superclass for STAPLER input classes. Parameters: in_cmd: String containing a command line in_dir: Directory object containing input files out_dir: Directory object containing output files NOTICE! Keep the directory objects up to date about file edits! Attrib... | the_stack_v2_python_sparse | modules/VCFtools.py | tyrmi/STAPLER | train | 4 |
e0ae544a730e81eee7ecc97803ee144a586ce760 | [
"self.graph = graph\nif not self._is_eulerian():\n raise ValueError('the graph is not eulerian')\nself.eulerian_cycle = list()\nself._graph_copy = self.graph.copy()",
"if source is None:\n source = next(self.graph.iternodes())\nnode = source\nwhile self._graph_copy.outdegree(node) > 0:\n for edge in list... | <|body_start_0|>
self.graph = graph
if not self._is_eulerian():
raise ValueError('the graph is not eulerian')
self.eulerian_cycle = list()
self._graph_copy = self.graph.copy()
<|end_body_0|>
<|body_start_1|>
if source is None:
source = next(self.graph.ite... | Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eulerian_path | FleuryDFSWithEdges | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FleuryDFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eul... | stack_v2_sparse_classes_75kplus_train_008216 | 9,406 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
},
{
"docstring": "Bridge test.",
"name": "_is_bridge",
"signa... | 4 | stack_v2_sparse_classes_30k_train_046706 | Implement the Python class `FleuryDFSWithEdges` described below.
Class description:
Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description ... | Implement the Python class `FleuryDFSWithEdges` described below.
Class description:
Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description ... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class FleuryDFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FleuryDFSWithEdges:
"""Fleury's algorithm for finding an Eulerian cycle (multigraphs). Complexity O(V*E). Attributes ---------- graph : input graph eulerian_cycle : list of edges (length |E|) _graph_copy : graph, private Notes ----- Based on the description from: https://en.wikipedia.org/wiki/Eulerian_path"""... | the_stack_v2_python_sparse | graphtheory/eulerian/fleury.py | kgashok/graphs-dict | train | 0 |
ba7134249d73290e583fa50201bdf7934538348c | [
"if not nums:\n return 1\nmax_num = len(nums)\nif max_num == 1:\n if nums[0] == 1:\n return 2\n else:\n return 1\nfor idx, val in enumerate(nums):\n if val < 0 or val >= max_num:\n nums[idx] = 0\nfor num in nums:\n nums[num % max_num] += max_num\nidx = 1\nwhile idx < max_num:\n ... | <|body_start_0|>
if not nums:
return 1
max_num = len(nums)
if max_num == 1:
if nums[0] == 1:
return 2
else:
return 1
for idx, val in enumerate(nums):
if val < 0 or val >= max_num:
nums[idx] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
r... | stack_v2_sparse_classes_75kplus_train_008217 | 2,115 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive2",
"signature": "def firstMissingPositive2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 1
max_num = len(nums)
if max_num == 1:
if nums[0] == 1:
return 2
else:
return 1
for idx, val i... | the_stack_v2_python_sparse | LC41.py | Qiao-Liang/LeetCode | train | 0 | |
463c6ea75dbc6aa278fc77fffa97b8b666fb1102 | [
"if user_id is None or not isinstance(user_id, str):\n return None\nsession_id = str(uuid4())\nSessionAuth.user_id_by_session_id[session_id] = user_id\nreturn session_id",
"if session_id is None or not isinstance(session_id, str):\n return None\nreturn SessionAuth.user_id_by_session_id.get(session_id)",
"... | <|body_start_0|>
if user_id is None or not isinstance(user_id, str):
return None
session_id = str(uuid4())
SessionAuth.user_id_by_session_id[session_id] = user_id
return session_id
<|end_body_0|>
<|body_start_1|>
if session_id is None or not isinstance(session_id, st... | Extend behavior of Auth class for session authentication. | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""Extend behavior of Auth class for session authentication."""
def create_session(self, user_id: str=None) -> str:
"""Create and return a session ID for a user ID."""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""Retur... | stack_v2_sparse_classes_75kplus_train_008218 | 1,753 | no_license | [
{
"docstring": "Create and return a session ID for a user ID.",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "Return user ID associated with specified session ID.",
"name": "user_id_for_session_id",
"signature": "def user_i... | 4 | null | Implement the Python class `SessionAuth` described below.
Class description:
Extend behavior of Auth class for session authentication.
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create and return a session ID for a user ID.
- def user_id_for_session_id(self, session_id: st... | Implement the Python class `SessionAuth` described below.
Class description:
Extend behavior of Auth class for session authentication.
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: Create and return a session ID for a user ID.
- def user_id_for_session_id(self, session_id: st... | 609a1679d2c31400979d96523565db8c2d12d794 | <|skeleton|>
class SessionAuth:
"""Extend behavior of Auth class for session authentication."""
def create_session(self, user_id: str=None) -> str:
"""Create and return a session ID for a user ID."""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionAuth:
"""Extend behavior of Auth class for session authentication."""
def create_session(self, user_id: str=None) -> str:
"""Create and return a session ID for a user ID."""
if user_id is None or not isinstance(user_id, str):
return None
session_id = str(uuid4()... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | agzsoftsi/holbertonschool-web_back_end | train | 2 |
b221bdfc6076c89845c73d36b8bbc78e055507c9 | [
"self.pin = button_pin\nself.gpio_up_down = gpio_up_down\nself.callback = callback\nself.double_press = double_press\nself.debounce = debounce\nself.previous_press = time.time()\nself.first_press = True\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nif self.gpio_up_down == 'up':\n GPIO.setup(self.pin, GPIO.IN... | <|body_start_0|>
self.pin = button_pin
self.gpio_up_down = gpio_up_down
self.callback = callback
self.double_press = double_press
self.debounce = debounce
self.previous_press = time.time()
self.first_press = True
GPIO.setmode(GPIO.BCM)
GPIO.setwarn... | Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But, class assumes pi is setup for GPIO.BCM. Saw no need to make this an attribute of t... | DoublePushButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoublePushButton:
"""Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But, class assumes pi is setup for GPIO.BCM... | stack_v2_sparse_classes_75kplus_train_008219 | 40,088 | no_license | [
{
"docstring": ":param button_pin: GPIO pin for the raspberry pi input :type button_pin: int :param callback: method that does something with the output from the button (either 'short' or 'long') :type callback: object ( name of method ) :param long_press: maximum duration, in seconds, for a short button press.... | 2 | stack_v2_sparse_classes_30k_train_017707 | Implement the Python class `DoublePushButton` described below.
Class description:
Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But,... | Implement the Python class `DoublePushButton` described below.
Class description:
Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But,... | 622cc666019753c4736c03be0d41308212c84291 | <|skeleton|>
class DoublePushButton:
"""Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But, class assumes pi is setup for GPIO.BCM... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoublePushButton:
"""Simple generic non-latching pushbutton. Returns single or double press to a callback function NOT RELIABLE YET Uses threaded callback from GPIO pins to call button_press method Works with GPIO pins set to either pull up or pull down But, class assumes pi is setup for GPIO.BCM. Saw no need... | the_stack_v2_python_sparse | SonosHW.py | gshorten/SonosController | train | 5 |
3468a7058b89474ded019dc0b9a4e4cf2ce782bf | [
"circuit = ic.IBMCircuit(10)\nw1 = iw.IBMInputWire('w1', circuit)\nw2 = iw.IBMInputWire('w2', circuit)\ng = igm.IBMMulGate('g', w1, w2, circuit)\nself.assertEquals('g:LMUL(w1,w2)', g.get_full_display_string())",
"circuit = ic.IBMCircuit(10)\nw1 = iw.IBMInputWire('w1', circuit)\nw2 = iw.IBMInputWire('w2', circuit)... | <|body_start_0|>
circuit = ic.IBMCircuit(10)
w1 = iw.IBMInputWire('w1', circuit)
w2 = iw.IBMInputWire('w2', circuit)
g = igm.IBMMulGate('g', w1, w2, circuit)
self.assertEquals('g:LMUL(w1,w2)', g.get_full_display_string())
<|end_body_0|>
<|body_start_1|>
circuit = ic.IBMC... | TestMulGate | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMulGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
<|body_0|>
def test_get_depth(self):
"""Tests that the get_depth method returns the correct depth, as defined by IBM."""
<|bod... | stack_v2_sparse_classes_75kplus_train_008220 | 2,364 | permissive | [
{
"docstring": "Tests that the method get_full_display_string returns the correct string.",
"name": "test_get_full_display_string",
"signature": "def test_get_full_display_string(self)"
},
{
"docstring": "Tests that the get_depth method returns the correct depth, as defined by IBM.",
"name":... | 2 | null | Implement the Python class `TestMulGate` described below.
Class description:
Implement the TestMulGate class.
Method signatures and docstrings:
- def test_get_full_display_string(self): Tests that the method get_full_display_string returns the correct string.
- def test_get_depth(self): Tests that the get_depth metho... | Implement the Python class `TestMulGate` described below.
Class description:
Implement the TestMulGate class.
Method signatures and docstrings:
- def test_get_full_display_string(self): Tests that the method get_full_display_string returns the correct string.
- def test_get_depth(self): Tests that the get_depth metho... | 264459a8fa1480c7b65d946f88d94af1a038fbf1 | <|skeleton|>
class TestMulGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
<|body_0|>
def test_get_depth(self):
"""Tests that the get_depth method returns the correct depth, as defined by IBM."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMulGate:
def test_get_full_display_string(self):
"""Tests that the method get_full_display_string returns the correct string."""
circuit = ic.IBMCircuit(10)
w1 = iw.IBMInputWire('w1', circuit)
w2 = iw.IBMInputWire('w2', circuit)
g = igm.IBMMulGate('g', w1, w2, circu... | the_stack_v2_python_sparse | hetest/python/circuit_generation/ibm/ibm_gate_mul_test.py | y4n9squared/HEtest | train | 7 | |
27ff63f741de8b635f93f11d12545105d0dfad6a | [
"self._driver = driver\nself.input_field_locator = input_field_locator\nself.parent_element = parent_element\nself.error_message = ErrorMessageComponent(self._driver, self.input_field_locator)",
"if self.parent_element:\n self.input_field = self.parent_element.find_element(*self.input_field_locator)\nelse:\n ... | <|body_start_0|>
self._driver = driver
self.input_field_locator = input_field_locator
self.parent_element = parent_element
self.error_message = ErrorMessageComponent(self._driver, self.input_field_locator)
<|end_body_0|>
<|body_start_1|>
if self.parent_element:
self.... | An input field to fill with data from user. | InputFieldComponent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputFieldComponent:
"""An input field to fill with data from user."""
def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> None:
"""Initialize the input field. :param driver: Remote :param input_field_locator: tuple (example: PASSWORD_FI... | stack_v2_sparse_classes_75kplus_train_008221 | 29,601 | no_license | [
{
"docstring": "Initialize the input field. :param driver: Remote :param input_field_locator: tuple (example: PASSWORD_FIELD=(By.ID, 'input-password')) :return: None",
"name": "__init__",
"signature": "def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> Non... | 3 | stack_v2_sparse_classes_30k_train_009829 | Implement the Python class `InputFieldComponent` described below.
Class description:
An input field to fill with data from user.
Method signatures and docstrings:
- def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> None: Initialize the input field. :param driver: Remot... | Implement the Python class `InputFieldComponent` described below.
Class description:
An input field to fill with data from user.
Method signatures and docstrings:
- def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> None: Initialize the input field. :param driver: Remot... | 28a402f435195f58e47752e98cfffee9734c7bc9 | <|skeleton|>
class InputFieldComponent:
"""An input field to fill with data from user."""
def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> None:
"""Initialize the input field. :param driver: Remote :param input_field_locator: tuple (example: PASSWORD_FI... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InputFieldComponent:
"""An input field to fill with data from user."""
def __init__(self, driver: Remote, input_field_locator: tuple, parent_element: WebElement=None) -> None:
"""Initialize the input field. :param driver: Remote :param input_field_locator: tuple (example: PASSWORD_FIELD=(By.ID, '... | the_stack_v2_python_sparse | dp189/components.py | maksym-bielyshev/opencart-automation-dp189taqc | train | 1 |
1c339c172ec7f9cffcf8ad5b76c0e88c3e4e6f34 | [
"base = self.base or self.settings['pipeline']['base']\nemail = self.settings['pipeline']['notifications']['email']\nslack = self.settings['pipeline']['notifications']['slack']\ndeploy_type = self.settings['pipeline']['type']\npipeline_id = self.compare_with_existing(region=region)\ndata = {'app': {'appname': self.... | <|body_start_0|>
base = self.base or self.settings['pipeline']['base']
email = self.settings['pipeline']['notifications']['email']
slack = self.settings['pipeline']['notifications']['slack']
deploy_type = self.settings['pipeline']['type']
pipeline_id = self.compare_with_existing(... | Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json. | SpinnakerPipelineDataPipeline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpinnakerPipelineDataPipeline:
"""Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json."""
def render_wrapper(self, region='us-east-1'):
"... | stack_v2_sparse_classes_75kplus_train_008222 | 4,599 | permissive | [
{
"docstring": "Generate the base Pipeline wrapper. This renders the non-repeatable stages in a pipeline, like jenkins, baking, tagging and notifications. Args: region (str): AWS Region. Returns: dict: Rendered Pipeline wrapper.",
"name": "render_wrapper",
"signature": "def render_wrapper(self, region='... | 2 | stack_v2_sparse_classes_30k_train_007881 | Implement the Python class `SpinnakerPipelineDataPipeline` described below.
Class description:
Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json.
Method signatures and d... | Implement the Python class `SpinnakerPipelineDataPipeline` described below.
Class description:
Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json.
Method signatures and d... | d88001ea0e33fcd09707b81b5c4ed40e5e21fb59 | <|skeleton|>
class SpinnakerPipelineDataPipeline:
"""Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json."""
def render_wrapper(self, region='us-east-1'):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpinnakerPipelineDataPipeline:
"""Manipulate Spinnaker Pipelines. Args: app (str): Application name. trigger_job (str): Jenkins trigger job. base (str): Base image name (i.e: fedora). prop_path (str): Path to the raw.properties.json."""
def render_wrapper(self, region='us-east-1'):
"""Generate th... | the_stack_v2_python_sparse | src/foremast/pipeline/create_pipeline_datapipeline.py | foremast/foremast | train | 151 |
c147a2b746def4c944fee5dd763cdf7043d1dddb | [
"session = Session()\ntry:\n query = session.query(Organization).order_by(Organization.legal_name, Organization.created_on)\n data, paging = get_collection_page(req, query)\n resp.media = {'data': data, 'paging': paging}\nfinally:\n session.close()",
"session = Session()\ntry:\n errors = validate_p... | <|body_start_0|>
session = Session()
try:
query = session.query(Organization).order_by(Organization.legal_name, Organization.created_on)
data, paging = get_collection_page(req, query)
resp.media = {'data': data, 'paging': paging}
finally:
session.c... | GET and POST organizations. | Collection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collection:
"""GET and POST organizations."""
def on_get(self, req, resp):
"""GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation."""
<|body_0|>
def on_post(self, req, resp):
"""Cr... | stack_v2_sparse_classes_75kplus_train_008223 | 7,046 | no_license | [
{
"docstring": "GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation.",
"name": "on_get",
"signature": "def on_get(self, req, resp)"
},
{
"docstring": "Creates a new organization. :param req: See Falcon Request doc... | 2 | stack_v2_sparse_classes_30k_test_001217 | Implement the Python class `Collection` described below.
Class description:
GET and POST organizations.
Method signatures and docstrings:
- def on_get(self, req, resp): GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation.
- def on_post... | Implement the Python class `Collection` described below.
Class description:
GET and POST organizations.
Method signatures and docstrings:
- def on_get(self, req, resp): GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation.
- def on_post... | 62723133595829230e5b589431a32cda3b092460 | <|skeleton|>
class Collection:
"""GET and POST organizations."""
def on_get(self, req, resp):
"""GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation."""
<|body_0|>
def on_post(self, req, resp):
"""Cr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collection:
"""GET and POST organizations."""
def on_get(self, req, resp):
"""GETs a paged collection of organizations. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation."""
session = Session()
try:
query = session.query(Organ... | the_stack_v2_python_sparse | knoweak/api/resources/organization.py | psvaiter/knoweak-api | train | 0 |
be863ef157bf82d4eb0e5afa555372c0470f3255 | [
"cursor = connection.cursor()\ntable = self.model._meta.db_table\nlogger.debug('Locking table %s' % table)\ncursor.execute('LOCK TABLES %s WRITE' % table)\nrow = cursor.fetchone()\nreturn row",
"cursor = connection.cursor()\ntable = self.model._meta.db_table\ncursor.execute('UNLOCK TABLES')\nrow = cursor.fetchone... | <|body_start_0|>
cursor = connection.cursor()
table = self.model._meta.db_table
logger.debug('Locking table %s' % table)
cursor.execute('LOCK TABLES %s WRITE' % table)
row = cursor.fetchone()
return row
<|end_body_0|>
<|body_start_1|>
cursor = connection.cursor()... | Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP request can do this update at once. Job.objec... | LockingManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP req... | stack_v2_sparse_classes_75kplus_train_008224 | 1,989 | permissive | [
{
"docstring": "Lock table. Locks the object model table so that atomic update is possible. Simulatenous database access request pend until the lock is unlock()'ed. Note: If you need to lock multiple tables, you need to do lock them all in one SQL clause and this function is not enough. To avoid dead lock, all ... | 2 | stack_v2_sparse_classes_30k_train_007969 | Implement the Python class `LockingManager` described below.
Class description:
Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it belo... | Implement the Python class `LockingManager` described below.
Class description:
Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it belo... | be5222d9c5ce57a169b94b0afd1ae9f7f10a66c1 | <|skeleton|>
class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): objects = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP request can do t... | the_stack_v2_python_sparse | generator/locking_manager.py | cometsong/jaxid_generator | train | 2 |
029444e43d804a82fc36db3644e27a2756142db1 | [
"context.require_admin_context(request.context)\nregions = [region_name] if region_name else cfg.CONF.regions\nDELETE_METHODS = services.RESOURCE_DELETE_METHOD\nfor region_name in regions:\n LOG.warn('deleting resources of tenant(%s) in region(%s)' % (project_id, region_name))\n for method in DELETE_METHODS:\... | <|body_start_0|>
context.require_admin_context(request.context)
regions = [region_name] if region_name else cfg.CONF.regions
DELETE_METHODS = services.RESOURCE_DELETE_METHOD
for region_name in regions:
LOG.warn('deleting resources of tenant(%s) in region(%s)' % (project_id, r... | Operations on resources. | ResourcesController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcesController:
"""Operations on resources."""
def delete(self, project_id, region_name=None):
"""Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this parameter must be specified."""
<|body_0|>
def get_a... | stack_v2_sparse_classes_75kplus_train_008225 | 2,490 | no_license | [
{
"docstring": "Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this parameter must be specified.",
"name": "delete",
"signature": "def delete(self, project_id, region_name=None)"
},
{
"docstring": "Get all resources of specified pro... | 3 | stack_v2_sparse_classes_30k_test_002048 | Implement the Python class `ResourcesController` described below.
Class description:
Operations on resources.
Method signatures and docstrings:
- def delete(self, project_id, region_name=None): Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this paramete... | Implement the Python class `ResourcesController` described below.
Class description:
Operations on resources.
Method signatures and docstrings:
- def delete(self, project_id, region_name=None): Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this paramete... | 75f656398c11b0dbddf99bf429994624915c3565 | <|skeleton|>
class ResourcesController:
"""Operations on resources."""
def delete(self, project_id, region_name=None):
"""Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this parameter must be specified."""
<|body_0|>
def get_a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourcesController:
"""Operations on resources."""
def delete(self, project_id, region_name=None):
"""Delete all resources in specified region that belongs to a tenant :param region_name: when in multiple region, this parameter must be specified."""
context.require_admin_context(request.... | the_stack_v2_python_sparse | gringotts/api/v2/resource.py | rogeroger-yu/ustack-gringotts | train | 1 |
e0a5856f0d0d8b8de9fc2901f0bb13aeae2a6d4b | [
"super(ContentSelectionCell, self).__init__()\nself._attention = attention_type()\nself._non_linearity = tf.keras.layers.Dense(hidden_size, activation='sigmoid')\nself._last_alignment = None\nself.hidden_size = hidden_size\nself.input_size = input_size\nself.state_size = [tf.TensorShape((max_timesteps, input_size))... | <|body_start_0|>
super(ContentSelectionCell, self).__init__()
self._attention = attention_type()
self._non_linearity = tf.keras.layers.Dense(hidden_size, activation='sigmoid')
self._last_alignment = None
self.hidden_size = hidden_size
self.input_size = input_size
... | ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mechanism and regulate flow of the information from the record (explanation can be found in... | ContentSelectionCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentSelectionCell:
"""ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mechanism and regulate flow of the informat... | stack_v2_sparse_classes_75kplus_train_008226 | 20,690 | no_license | [
{
"docstring": "Initialize the ContentSelectionCell Args: attention_type (callable): method which initializes the attention mechanism used as the self attention max_timesteps (int): the lenght of the longest sequence to be processed hidden_size (int): dimensionality of the hidden states input_size (int): dimens... | 2 | stack_v2_sparse_classes_30k_train_028382 | Implement the Python class `ContentSelectionCell` described below.
Class description:
ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mech... | Implement the Python class `ContentSelectionCell` described below.
Class description:
ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mech... | bba791d9337a30fdadef28645525dc75bf926132 | <|skeleton|>
class ContentSelectionCell:
"""ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mechanism and regulate flow of the informat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContentSelectionCell:
"""ContentSelectionCell is a subclass of tf.keras.layers.Layer which should be used as the Cell argument in tf.keras.layers.RNN interface ContentSelectionCell traverse all the time-steps and compute self-attention to provide gating mechanism and regulate flow of the information from the ... | the_stack_v2_python_sparse | rotowire/neural_nets/layers.py | gortibaldik/TTTGen | train | 4 |
f4503046ed5d189d64a00d836f4ef43d96c3d307 | [
"num = self.request.query_params.get('num', 100)\nfilms = Film.objects.all().order_by('-rs232_time')[:int(num)]\nserializer = FilmSerializer(films, many=True)\nreturn Response(serializer.data)",
"if isinstance(request.data, dict):\n data = request.data\nelse:\n data = json.loads(request.data)\nserializer = ... | <|body_start_0|>
num = self.request.query_params.get('num', 100)
films = Film.objects.all().order_by('-rs232_time')[:int(num)]
serializer = FilmSerializer(films, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
if isinstance(request.data, dict):
... | class based view for creating and fetching film records | FilmView | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilmView:
"""class based view for creating and fetching film records"""
def get(self, request, format=None):
"""Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to return to :return: Return a list of film records"""
... | stack_v2_sparse_classes_75kplus_train_008227 | 8,520 | permissive | [
{
"docstring": "Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to return to :return: Return a list of film records",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create film record :param fo... | 2 | stack_v2_sparse_classes_30k_train_053770 | Implement the Python class `FilmView` described below.
Class description:
class based view for creating and fetching film records
Method signatures and docstrings:
- def get(self, request, format=None): Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to... | Implement the Python class `FilmView` described below.
Class description:
class based view for creating and fetching film records
Method signatures and docstrings:
- def get(self, request, format=None): Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to... | 49cdee124bf7414fde5245f28329f65adb359599 | <|skeleton|>
class FilmView:
"""class based view for creating and fetching film records"""
def get(self, request, format=None):
"""Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to return to :return: Return a list of film records"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilmView:
"""class based view for creating and fetching film records"""
def get(self, request, format=None):
"""Get all the film records :param num: record number, default:latest 100 :param format: Format of the film records to return to :return: Return a list of film records"""
num = sel... | the_stack_v2_python_sparse | src/films/api/v1/api_views.py | chairco/dj-realtime-visualization | train | 0 |
33f67203e9d15715d035fdba6ee610fad09716ad | [
"result = set()\nnums.sort()\ncounter = collections.Counter(nums)\nprev = None\nfor i, num1 in enumerate(nums):\n if num1 > 0:\n break\n if num1 == prev:\n continue\n for num2 in nums[i + 1:]:\n num3 = -(num1 + num2)\n if num3 < 0:\n break\n if num3 >= num2 and... | <|body_start_0|>
result = set()
nums.sort()
counter = collections.Counter(nums)
prev = None
for i, num1 in enumerate(nums):
if num1 > 0:
break
if num1 == prev:
continue
for num2 in nums[i + 1:]:
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = set()
num... | stack_v2_sparse_classes_75kplus_train_008228 | 1,868 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 057ed5c6fe19268f36a1d5051d27b07aae0b63e0 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
result = set()
nums.sort()
counter = collections.Counter(nums)
prev = None
for i, num1 in enumerate(nums):
if num1 > 0:
break
if num1 ... | the_stack_v2_python_sparse | 2020/2020-02/25/eugene.py | wavetogether/wave_algorithm_challenge | train | 3 | |
bbd886f51bf0f021f4a26b1677e872c2e09e476b | [
"available_nums = set(nums)\nsequences_len_map: Dict[int, int] = defaultdict(int)\nmax_steak: int = 0\n\ndef get_steak_at(num: int) -> int:\n \"\"\"\n Retrieve steaks for shorter sequences\n \"\"\"\n if num not in available_nums:\n return 0\n if num in sequences_len_map:\n ... | <|body_start_0|>
available_nums = set(nums)
sequences_len_map: Dict[int, int] = defaultdict(int)
max_steak: int = 0
def get_steak_at(num: int) -> int:
"""
Retrieve steaks for shorter sequences
"""
if num not in available_nu... | Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium | LongestConsecutiveSequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestConsecutiveSequence:
"""Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium"""
def longestConsecutive(self, nums: List[int]) -> int:
"""This solution is based on idea that steak for the current number num = 1 + steak(num - 1) Runtime: 3... | stack_v2_sparse_classes_75kplus_train_008229 | 2,316 | no_license | [
{
"docstring": "This solution is based on idea that steak for the current number num = 1 + steak(num - 1) Runtime: 324 ms Memory: 108.5 MB",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums: List[int]) -> int"
},
{
"docstring": "This solution is based on idea of find... | 2 | stack_v2_sparse_classes_30k_train_020574 | Implement the Python class `LongestConsecutiveSequence` described below.
Class description:
Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium
Method signatures and docstrings:
- def longestConsecutive(self, nums: List[int]) -> int: This solution is based on idea that steak f... | Implement the Python class `LongestConsecutiveSequence` described below.
Class description:
Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium
Method signatures and docstrings:
- def longestConsecutive(self, nums: List[int]) -> int: This solution is based on idea that steak f... | 9962d8bc55e2ff3162b1dfa0bce3754568368b00 | <|skeleton|>
class LongestConsecutiveSequence:
"""Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium"""
def longestConsecutive(self, nums: List[int]) -> int:
"""This solution is based on idea that steak for the current number num = 1 + steak(num - 1) Runtime: 3... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LongestConsecutiveSequence:
"""Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/ Complexity: Medium"""
def longestConsecutive(self, nums: List[int]) -> int:
"""This solution is based on idea that steak for the current number num = 1 + steak(num - 1) Runtime: 324 ms Memory:... | the_stack_v2_python_sparse | src/dynamic_programming/longest_consecutive_sequence.py | roma-glushko/leetcode-solutions | train | 3 |
20d4f1422475ed774746138c3911197b439330f0 | [
"self.img = img\nself.scale = scale\nself.width, self.height = (img.shape[1], img.shape[0])\nself._setup_figure(img)",
"fig = mplfigure.Figure(frameon=False)\nself.dpi = fig.get_dpi()\nfig.set_size_inches((self.width * self.scale + 0.01) / self.dpi, (self.height * self.scale + 0.01) / self.dpi)\nself.canvas = Fig... | <|body_start_0|>
self.img = img
self.scale = scale
self.width, self.height = (img.shape[1], img.shape[0])
self._setup_figure(img)
<|end_body_0|>
<|body_start_1|>
fig = mplfigure.Figure(frameon=False)
self.dpi = fig.get_dpi()
fig.set_size_inches((self.width * self... | VisImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisImage:
def __init__(self, img, scale=1.0):
"""Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image"""
<|body_0|>
def _setup_figure(self, img):
"""Args: Same as in :meth:`__init__()`. Returns: fig (matplotlib.pyplot.figure): to... | stack_v2_sparse_classes_75kplus_train_008230 | 3,461 | no_license | [
{
"docstring": "Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image",
"name": "__init__",
"signature": "def __init__(self, img, scale=1.0)"
},
{
"docstring": "Args: Same as in :meth:`__init__()`. Returns: fig (matplotlib.pyplot.figure): top level container ... | 4 | null | Implement the Python class `VisImage` described below.
Class description:
Implement the VisImage class.
Method signatures and docstrings:
- def __init__(self, img, scale=1.0): Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image
- def _setup_figure(self, img): Args: Same as in :m... | Implement the Python class `VisImage` described below.
Class description:
Implement the VisImage class.
Method signatures and docstrings:
- def __init__(self, img, scale=1.0): Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image
- def _setup_figure(self, img): Args: Same as in :m... | cc27bba91331dc50a271eb9397774f979663ae96 | <|skeleton|>
class VisImage:
def __init__(self, img, scale=1.0):
"""Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image"""
<|body_0|>
def _setup_figure(self, img):
"""Args: Same as in :meth:`__init__()`. Returns: fig (matplotlib.pyplot.figure): to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VisImage:
def __init__(self, img, scale=1.0):
"""Args: img (ndarray): an RGB image of shape (H, W, 3). scale (float): scale the input image"""
self.img = img
self.scale = scale
self.width, self.height = (img.shape[1], img.shape[0])
self._setup_figure(img)
def _setu... | the_stack_v2_python_sparse | vis_utils/vis_image.py | cds-mipt/fcnResNetmOCR | train | 4 | |
b3b07e99a9855fff88514c26ee1c2fc5842245b5 | [
"if sample_name == 'CUSTOM':\n self._likelihood = CustomSneLikelihood(**kwargs_sne_likelihood)\nelse:\n self._likelihood = SneLikelihoodFromFile(sample_name=sample_name, **kwargs_sne_likelihood)\nself.zhel = self._likelihood.zhel\nself.zcmb = self._likelihood.zcmb",
"angular_diameter_distances = cosmo.angul... | <|body_start_0|>
if sample_name == 'CUSTOM':
self._likelihood = CustomSneLikelihood(**kwargs_sne_likelihood)
else:
self._likelihood = SneLikelihoodFromFile(sample_name=sample_name, **kwargs_sne_likelihood)
self.zhel = self._likelihood.zhel
self.zcmb = self._likeli... | Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file | SneLikelihood | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SneLikelihood:
"""Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file"""
def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood):
""":param sample_name: string, either 'CUSTOM' or a specific name supported b... | stack_v2_sparse_classes_75kplus_train_008231 | 2,077 | permissive | [
{
"docstring": ":param sample_name: string, either 'CUSTOM' or a specific name supported by SneLikelihoodFromFile() class :param kwargs_sne_likelihood: keyword arguments to initiate likelihood class",
"name": "__init__",
"signature": "def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood)"
... | 2 | stack_v2_sparse_classes_30k_train_003071 | Implement the Python class `SneLikelihood` described below.
Class description:
Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file
Method signatures and docstrings:
- def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood): :param sample_nam... | Implement the Python class `SneLikelihood` described below.
Class description:
Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file
Method signatures and docstrings:
- def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood): :param sample_nam... | 1dc2be90f44f99e82ab7014f2027fbb077b14f98 | <|skeleton|>
class SneLikelihood:
"""Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file"""
def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood):
""":param sample_name: string, either 'CUSTOM' or a specific name supported b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SneLikelihood:
"""Supernovae likelihood This class supports custom likelihoods as well as likelihoods from the Pantheon sample from file"""
def __init__(self, sample_name='CUSTOM', **kwargs_sne_likelihood):
""":param sample_name: string, either 'CUSTOM' or a specific name supported by SneLikeliho... | the_stack_v2_python_sparse | hierarc/Likelihood/SneLikelihood/sne_likelihood.py | LBJ-Wade/hierarc_SGL | train | 0 |
9a6b15b955025f423918febcc2dd0eebda7a78eb | [
"super().__init__(full.snap_ind, full.rind)\nself.zlimits = self.params['slice_limits']\nself.fi = []\nself.ni = []\nself._extract_from_full(full.pos)\nself.iteration = full.iteration\nself.time = full.time\nself.figtitle3d = f\"MT {self.type}: {self.zlimits['bottom']} to {self.zlimits['top']}\" + self.len_units + ... | <|body_start_0|>
super().__init__(full.snap_ind, full.rind)
self.zlimits = self.params['slice_limits']
self.fi = []
self.ni = []
self._extract_from_full(full.pos)
self.iteration = full.iteration
self.time = full.time
self.figtitle3d = f"MT {self.type}: {se... | Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microscope: a cell content inside a volume slice proximal to basal cell surface... | Slice | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slice:
"""Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microscope: a cell content inside a volume sli... | stack_v2_sparse_classes_75kplus_train_008232 | 27,158 | permissive | [
{
"docstring": ":param full: The original system.",
"name": "__init__",
"signature": "def __init__(self, full: FullDepth)"
},
{
"docstring": "Extract a subvolume from a full system representation. Because the process may involve splitting of the original filaments into apparently independent seg... | 4 | stack_v2_sparse_classes_30k_train_051179 | Implement the Python class `Slice` described below.
Class description:
Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microsc... | Implement the Python class `Slice` described below.
Class description:
Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microsc... | 681a1f6ba1381a5fb293f2310fce5e97d400cfcb | <|skeleton|>
class Slice:
"""Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microscope: a cell content inside a volume sli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Slice:
"""Encapsulates a system resulting from optical volume sectioning. Optical extraction of a cell subvolume between xy-parallel planes. This roughly emulates the subsectioning produced by confpcal or Total Internal Reflection Fluorescence (TIRF) Microscope: a cell content inside a volume slice proximal t... | the_stack_v2_python_sparse | cytoskeleton_analyser/position/spatial_systems.py | vsukhor/cytoskeleton-analyser | train | 0 |
473a39c7c0259e60c6882cd0e22c6af0c1a9a04b | [
"try_count = 0\nresponse = None\nwhile try_count <= PREFECT_CLIENT_MAX_RETRIES.value():\n try_count += 1\n retry_seconds = None\n exc_info = None\n try:\n response = await request()\n except retry_exceptions:\n if try_count > PREFECT_CLIENT_MAX_RETRIES.value():\n raise\n ... | <|body_start_0|>
try_count = 0
response = None
while try_count <= PREFECT_CLIENT_MAX_RETRIES.value():
try_count += 1
retry_seconds = None
exc_info = None
try:
response = await request()
except retry_exceptions:
... | A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details on rate limit headers, see: [Configuring Cloudflare Rate Limiting](https://support.cl... | PrefectHttpxClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefectHttpxClient:
"""A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details on rate limit headers, see: [Configurin... | stack_v2_sparse_classes_75kplus_train_008233 | 11,703 | permissive | [
{
"docstring": "Send a request and retry it if it fails. Sends the provided request and retries it up to PREFECT_CLIENT_MAX_RETRIES times if the request either raises an exception listed in `retry_exceptions` or receives a response with a status code listed in `retry_codes`. Retries will be delayed based on eit... | 2 | null | Implement the Python class `PrefectHttpxClient` described below.
Class description:
A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details ... | Implement the Python class `PrefectHttpxClient` described below.
Class description:
A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details ... | 2c50d2b64c811c364cbc5faa2b5c80a742572090 | <|skeleton|>
class PrefectHttpxClient:
"""A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details on rate limit headers, see: [Configurin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrefectHttpxClient:
"""A Prefect wrapper for the async httpx client with support for retry-after headers for the provided status codes (typically 429, 502 and 503). Additionally, this client will always call `raise_for_status` on responses. For more details on rate limit headers, see: [Configuring Cloudflare ... | the_stack_v2_python_sparse | src/prefect/client/base.py | PrefectHQ/prefect | train | 12,917 |
e1a5a5921c01f50232278781cadcd9f821177153 | [
"self.constructor = constructor\nroot = ETree.parse(descriptionFile).getroot()\nunits = [xmlToDict(c) for c in root]\nself.descriptions = {}\nfor u in units:\n self.descriptions[u['name']] = u",
"if name not in self.descriptions:\n raise ValueError('Did not find an object named \"%s\"' % name)\nreturn self.... | <|body_start_0|>
self.constructor = constructor
root = ETree.parse(descriptionFile).getroot()
units = [xmlToDict(c) for c in root]
self.descriptions = {}
for u in units:
self.descriptions[u['name']] = u
<|end_body_0|>
<|body_start_1|>
if name not in self.desc... | Factory for creating objects according to an XML description. | DescribedObjectFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescribedObjectFactory:
"""Factory for creating objects according to an XML description."""
def __init__(self, constructor, descriptionFile):
"""constructor is a function that creates an object from a dictionary description of its properties (see, eg, Unit). descriptionFile is the XM... | stack_v2_sparse_classes_75kplus_train_008234 | 1,708 | no_license | [
{
"docstring": "constructor is a function that creates an object from a dictionary description of its properties (see, eg, Unit). descriptionFile is the XML file containing descriptions of the various objects that can be created.",
"name": "__init__",
"signature": "def __init__(self, constructor, descri... | 2 | stack_v2_sparse_classes_30k_train_015477 | Implement the Python class `DescribedObjectFactory` described below.
Class description:
Factory for creating objects according to an XML description.
Method signatures and docstrings:
- def __init__(self, constructor, descriptionFile): constructor is a function that creates an object from a dictionary description of ... | Implement the Python class `DescribedObjectFactory` described below.
Class description:
Factory for creating objects according to an XML description.
Method signatures and docstrings:
- def __init__(self, constructor, descriptionFile): constructor is a function that creates an object from a dictionary description of ... | 73cd4812b08aa29dfb2993510e76253d41cf1bb4 | <|skeleton|>
class DescribedObjectFactory:
"""Factory for creating objects according to an XML description."""
def __init__(self, constructor, descriptionFile):
"""constructor is a function that creates an object from a dictionary description of its properties (see, eg, Unit). descriptionFile is the XM... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DescribedObjectFactory:
"""Factory for creating objects according to an XML description."""
def __init__(self, constructor, descriptionFile):
"""constructor is a function that creates an object from a dictionary description of its properties (see, eg, Unit). descriptionFile is the XML file contai... | the_stack_v2_python_sparse | described_object_factory.py | jneem/clashadash | train | 0 |
efa6825b49527f1a6d6c0c806d8c96760604018f | [
"self.url = url\nself.make_soup()\nself.get_title()\nself.get_image()\nself.get_ingredients()\nself.get_contents()\nself.get_portions()",
"try:\n self.title = self.soup.find('div', {'class': re.compile('recipe_gridLeftWrapper*')}).find('h1').text.strip()\nexcept Exception:\n current_app.logger.error(f'Could... | <|body_start_0|>
self.url = url
self.make_soup()
self.get_title()
self.get_image()
self.get_ingredients()
self.get_contents()
self.get_portions()
<|end_body_0|>
<|body_start_1|>
try:
self.title = self.soup.find('div', {'class': re.compile('rec... | Parser for recipes at koket.se. | KoketParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KoketParser:
"""Parser for recipes at koket.se."""
def __init__(self, url):
"""Init the parser."""
<|body_0|>
def get_title(self):
"""Get recipe title."""
<|body_1|>
def get_image(self):
"""Get recipe main image."""
<|body_2|>
de... | stack_v2_sparse_classes_75kplus_train_008235 | 2,797 | permissive | [
{
"docstring": "Init the parser.",
"name": "__init__",
"signature": "def __init__(self, url)"
},
{
"docstring": "Get recipe title.",
"name": "get_title",
"signature": "def get_title(self)"
},
{
"docstring": "Get recipe main image.",
"name": "get_image",
"signature": "def ... | 6 | stack_v2_sparse_classes_30k_train_021030 | Implement the Python class `KoketParser` described below.
Class description:
Parser for recipes at koket.se.
Method signatures and docstrings:
- def __init__(self, url): Init the parser.
- def get_title(self): Get recipe title.
- def get_image(self): Get recipe main image.
- def get_ingredients(self): Get recipe ingr... | Implement the Python class `KoketParser` described below.
Class description:
Parser for recipes at koket.se.
Method signatures and docstrings:
- def __init__(self, url): Init the parser.
- def get_title(self): Get recipe title.
- def get_image(self): Get recipe main image.
- def get_ingredients(self): Get recipe ingr... | df3ca44eeefb1c3c3f4c54272f63059be47990bf | <|skeleton|>
class KoketParser:
"""Parser for recipes at koket.se."""
def __init__(self, url):
"""Init the parser."""
<|body_0|>
def get_title(self):
"""Get recipe title."""
<|body_1|>
def get_image(self):
"""Get recipe main image."""
<|body_2|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KoketParser:
"""Parser for recipes at koket.se."""
def __init__(self, url):
"""Init the parser."""
self.url = url
self.make_soup()
self.get_title()
self.get_image()
self.get_ingredients()
self.get_contents()
self.get_portions()
def get_... | the_stack_v2_python_sparse | recapi/html_parsers/koketparser.py | anne17/recapi | train | 2 |
6e23bedfed67d0d27ac470c985b5012178d290e5 | [
"Function.__init__(self)\nself.rgbindices = rgbindices\nself.aindex = aindex",
"if self.rgbindices is None:\n ones = numpy.ones_like(layer)\n image = numpy.asarray([layer, layer, layer, ones])\nelse:\n if self.aindex is None:\n alpha = numpy.ones(layer.shape[1:])\n else:\n alpha = layer[... | <|body_start_0|>
Function.__init__(self)
self.rgbindices = rgbindices
self.aindex = aindex
<|end_body_0|>
<|body_start_1|>
if self.rgbindices is None:
ones = numpy.ones_like(layer)
image = numpy.asarray([layer, layer, layer, ones])
else:
if se... | Generates PIL images from numpy ndarrays. | PILext | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PILext:
"""Generates PIL images from numpy ndarrays."""
def __init__(self, rgbindices=None, aindex=None):
"""*rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices* is ``None``, then the array will be intereted as graysca... | stack_v2_sparse_classes_75kplus_train_008236 | 1,532 | permissive | [
{
"docstring": "*rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices* is ``None``, then the array will be intereted as grayscale, and *aindex* is ignored. *aindex* is either ``None`` (alpha channel opaque) or the index where to take the alpha chan... | 2 | null | Implement the Python class `PILext` described below.
Class description:
Generates PIL images from numpy ndarrays.
Method signatures and docstrings:
- def __init__(self, rgbindices=None, aindex=None): *rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices*... | Implement the Python class `PILext` described below.
Class description:
Generates PIL images from numpy ndarrays.
Method signatures and docstrings:
- def __init__(self, rgbindices=None, aindex=None): *rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices*... | 7941a06d43bbbb63e45496044040a163ab97d78d | <|skeleton|>
class PILext:
"""Generates PIL images from numpy ndarrays."""
def __init__(self, rgbindices=None, aindex=None):
"""*rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices* is ``None``, then the array will be intereted as graysca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PILext:
"""Generates PIL images from numpy ndarrays."""
def __init__(self, rgbindices=None, aindex=None):
"""*rgbindices* should give the indices for ``R, G, B, A`` to take from the array fed to *self.__call__*. If *rgbindices* is ``None``, then the array will be intereted as grayscale, and *aind... | the_stack_v2_python_sparse | moviemaker3/ext/PILext.py | friedrichromstedt/moviemaker3 | train | 2 |
25a37b381847da5cc83a0ef0fb4ca098ce5af34f | [
"super(CFRHTMLBuilder, self).process_node(node, indexes=indexes)\nlabel_id = '-'.join(node['label'])\nnode['toc_id'] = '-'.join(self.id_prefix + node['label'][:2])\nnode['accepts_comments'] = label_id in self.diff_applier.diff\nnode['comments_calledout'] = label_id in self.diff_applier.diff\nhas_diff = label_id in ... | <|body_start_0|>
super(CFRHTMLBuilder, self).process_node(node, indexes=indexes)
label_id = '-'.join(node['label'])
node['toc_id'] = '-'.join(self.id_prefix + node['label'][:2])
node['accepts_comments'] = label_id in self.diff_applier.diff
node['comments_calledout'] = label_id in... | Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set | CFRChangeHTMLBuilder | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_0|>
def preprocess(... | stack_v2_sparse_classes_75kplus_train_008237 | 9,837 | permissive | [
{
"docstring": "Overrides with custom, additional processing",
"name": "process_node",
"signature": "def process_node(self, node, indexes=None)"
},
{
"docstring": "Pre-generate all of the \"paths\" associated with diffs; if there's a diff for 111-22-c-4-v, we'd capture (111,) (111, 22) (111, 22,... | 2 | stack_v2_sparse_classes_30k_train_041428 | Implement the Python class `CFRChangeHTMLBuilder` described below.
Class description:
Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set
Method signatures and docstrings:
- def process_node(self, node, indexes=None): Overrides with custom, additio... | Implement the Python class `CFRChangeHTMLBuilder` described below.
Class description:
Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set
Method signatures and docstrings:
- def process_node(self, node, indexes=None): Overrides with custom, additio... | 4035701a953409bbb1987d371edc6630fd97a862 | <|skeleton|>
class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
<|body_0|>
def preprocess(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CFRChangeHTMLBuilder:
"""Generated HTML specifically related to changing CFR data, as displayed in a notice. This assumes self.diff_applier is set"""
def process_node(self, node, indexes=None):
"""Overrides with custom, additional processing"""
super(CFRHTMLBuilder, self).process_node(nod... | the_stack_v2_python_sparse | regulations/generator/html_builder.py | fecgov/regulations-site | train | 1 |
c093645b38ab683021e11c21a957bd94a4a0b0b8 | [
"self._design = design\ntry:\n self.requested_bands = algo_config[self.name][producttype_to_sat(product_type)]\nexcept KeyError as invalid_product:\n msg = f'{product_type} is not allowed with {self.name}'\n raise InputError(msg) from invalid_product\ncalibration_dict, calibration_name = load_calib(calibra... | <|body_start_0|>
self._design = design
try:
self.requested_bands = algo_config[self.name][producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
... | Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740nm B6 MSI. This algorithm was published i... | CHLAGitelson | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CHLAGitelson:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740n... | stack_v2_sparse_classes_75kplus_train_008238 | 23,282 | permissive | [
{
"docstring": "Inits an 'CHLAGitelson' instance with specific settings. Args: product_type: The type of the input satellite product (e.g. S2_ESA_L2A or L8_USGS_L1GT) calibration: The calibration (set of parameters) used by the algorithm (default=_default_calibration_name). **_ignored: Unused kwargs sent to tra... | 2 | stack_v2_sparse_classes_30k_train_036839 | Implement the Python class `CHLAGitelson` described below.
Class description:
Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1)... | Implement the Python class `CHLAGitelson` described below.
Class description:
Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1)... | f516bb778b505739fdf320affe651b715ed75324 | <|skeleton|>
class CHLAGitelson:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CHLAGitelson:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008 Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs, in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740nm B6 MSI. Thi... | the_stack_v2_python_sparse | sisppeo/wcproducts/chla.py | inrae/SISPPEO | train | 11 |
e313911d9d4030dcb4de24f2498f46cfab6e6190 | [
"permission_classes = [IsAuthenticated]\nif self.action in ('add_balance',):\n permission_classes += [IsAdminUser]\nelif self.action in ('update', 'partial_update'):\n permission_classes += [IsProfileOwnerOrStaff]\nreturn [permission() for permission in permission_classes]",
"if self.action == 'add_balance'... | <|body_start_0|>
permission_classes = [IsAuthenticated]
if self.action in ('add_balance',):
permission_classes += [IsAdminUser]
elif self.action in ('update', 'partial_update'):
permission_classes += [IsProfileOwnerOrStaff]
return [permission() for permission in p... | ProfileViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileViewSet:
def get_permissions(self) -> List[BasePermission]:
"""Allow `add_balance` only to staff, updating to staff and the current user"""
<|body_0|>
def get_serializer_class(self) -> Type[BaseSerializer]:
"""Change serializer class for custom actions"""
... | stack_v2_sparse_classes_75kplus_train_008239 | 5,976 | permissive | [
{
"docstring": "Allow `add_balance` only to staff, updating to staff and the current user",
"name": "get_permissions",
"signature": "def get_permissions(self) -> List[BasePermission]"
},
{
"docstring": "Change serializer class for custom actions",
"name": "get_serializer_class",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_048884 | Implement the Python class `ProfileViewSet` described below.
Class description:
Implement the ProfileViewSet class.
Method signatures and docstrings:
- def get_permissions(self) -> List[BasePermission]: Allow `add_balance` only to staff, updating to staff and the current user
- def get_serializer_class(self) -> Type[... | Implement the Python class `ProfileViewSet` described below.
Class description:
Implement the ProfileViewSet class.
Method signatures and docstrings:
- def get_permissions(self) -> List[BasePermission]: Allow `add_balance` only to staff, updating to staff and the current user
- def get_serializer_class(self) -> Type[... | a898caa068cd82d223161fa62a0561f75333d50e | <|skeleton|>
class ProfileViewSet:
def get_permissions(self) -> List[BasePermission]:
"""Allow `add_balance` only to staff, updating to staff and the current user"""
<|body_0|>
def get_serializer_class(self) -> Type[BaseSerializer]:
"""Change serializer class for custom actions"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileViewSet:
def get_permissions(self) -> List[BasePermission]:
"""Allow `add_balance` only to staff, updating to staff and the current user"""
permission_classes = [IsAuthenticated]
if self.action in ('add_balance',):
permission_classes += [IsAdminUser]
elif sel... | the_stack_v2_python_sparse | users/views.py | coma64/kaffee-kasse-backend | train | 0 | |
899dbfd858fad2f1a839c5273b03e8473c346a94 | [
"dp = [0 for _ in range(len(nums))]\ndp[0] = 1\nfor i in range(1, len(nums)):\n max_lis = 0\n for j in range(i):\n if nums[i] > nums[j] and dp[j] > max_lis:\n max_lis = dp[j]\n dp[i] = max_lis + 1\nprint(dp)\nreturn max(dp)",
"dp = [1 for _ in range(len(nums))]\ndp[0] = 1\nfor i in rang... | <|body_start_0|>
dp = [0 for _ in range(len(nums))]
dp[0] = 1
for i in range(1, len(nums)):
max_lis = 0
for j in range(i):
if nums[i] > nums[j] and dp[j] > max_lis:
max_lis = dp[j]
dp[i] = max_lis + 1
print(dp)
... | Solution300 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution300:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0 for _ in range(len(nums))]
... | stack_v2_sparse_classes_75kplus_train_008240 | 18,033 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS2",
"signature": "def lengthOfLIS2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054533 | Implement the Python class `Solution300` described below.
Class description:
Implement the Solution300 class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution300` described below.
Class description:
Implement the Solution300 class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution300:
def l... | fcf79f4f7354454a28b60ef3c845dd6defddbf42 | <|skeleton|>
class Solution300:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution300:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
dp = [0 for _ in range(len(nums))]
dp[0] = 1
for i in range(1, len(nums)):
max_lis = 0
for j in range(i):
if nums[i] > nums[j] and dp[j] > max_lis:
... | the_stack_v2_python_sparse | python_data_structure/dynamic_programming.py | liunlll/LiuLeetCode | train | 0 | |
eeebe423569ef6cf4136970db4bfecb076d286c6 | [
"self._max_action_loops = max_loops\nself._max_combination_length = max_combination_length\nself._action_history = []",
"loops_detected = False\nself._action_history.append(action_key)\nfor combination_length in xrange(1, self._max_combination_length + 1):\n if self._is_combination_compatible(combination_lengt... | <|body_start_0|>
self._max_action_loops = max_loops
self._max_combination_length = max_combination_length
self._action_history = []
<|end_body_0|>
<|body_start_1|>
loops_detected = False
self._action_history.append(action_key)
for combination_length in xrange(1, self._ma... | Help to detect loops for action combinations | ActionLoopDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionLoopDetector:
"""Help to detect loops for action combinations"""
def __init__(self, max_loops, max_combination_length):
""":param max_loops: :param max_combination_length: :return:"""
<|body_0|>
def loops_detected(self, action_key):
"""Add action key to the... | stack_v2_sparse_classes_75kplus_train_008241 | 11,421 | no_license | [
{
"docstring": ":param max_loops: :param max_combination_length: :return:",
"name": "__init__",
"signature": "def __init__(self, max_loops, max_combination_length)"
},
{
"docstring": "Add action key to the history and detect loops :param action_key: :return:",
"name": "loops_detected",
"... | 4 | stack_v2_sparse_classes_30k_train_026119 | Implement the Python class `ActionLoopDetector` described below.
Class description:
Help to detect loops for action combinations
Method signatures and docstrings:
- def __init__(self, max_loops, max_combination_length): :param max_loops: :param max_combination_length: :return:
- def loops_detected(self, action_key): ... | Implement the Python class `ActionLoopDetector` described below.
Class description:
Help to detect loops for action combinations
Method signatures and docstrings:
- def __init__(self, max_loops, max_combination_length): :param max_loops: :param max_combination_length: :return:
- def loops_detected(self, action_key): ... | e5a06f75483fed89ed615523ef505eb2a20653aa | <|skeleton|>
class ActionLoopDetector:
"""Help to detect loops for action combinations"""
def __init__(self, max_loops, max_combination_length):
""":param max_loops: :param max_combination_length: :return:"""
<|body_0|>
def loops_detected(self, action_key):
"""Add action key to the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionLoopDetector:
"""Help to detect loops for action combinations"""
def __init__(self, max_loops, max_combination_length):
""":param max_loops: :param max_combination_length: :return:"""
self._max_action_loops = max_loops
self._max_combination_length = max_combination_length
... | the_stack_v2_python_sparse | Shells/cloudshell-L1-l1mock/dependencies/cloudshell-l1-networking-core/common/cli/expect_session.py | LeeorV/Quali-University-Prep | train | 0 |
635edba85fc9c2235db820ba19dc36adf5153b29 | [
"self.algo = algo\nself.windowSize = windowSize\nself.numHidden = numHidden\nself.nEpochs = nEpochs\nself.text = text\nself.learningRate = learningRate",
"h = np.dot(weights1.T, center)\nu = np.dot(weights2.T, h)\nyPred = softmax(u)\nerror = np.array([yPred.T - label for label in context])\ndweights2 = np.outer(h... | <|body_start_0|>
self.algo = algo
self.windowSize = windowSize
self.numHidden = numHidden
self.nEpochs = nEpochs
self.text = text
self.learningRate = learningRate
<|end_body_0|>
<|body_start_1|>
h = np.dot(weights1.T, center)
u = np.dot(weights2.T, h)
... | Word2Vec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Word2Vec:
def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1):
"""initializer for word2vec :param type: :param windowSize: :param numHidden: :param nEpochs: :param text: :param learningRate:"""
<|body_0|>
def skipgram(self, co... | stack_v2_sparse_classes_75kplus_train_008242 | 2,045 | permissive | [
{
"docstring": "initializer for word2vec :param type: :param windowSize: :param numHidden: :param nEpochs: :param text: :param learningRate:",
"name": "__init__",
"signature": "def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_009045 | Implement the Python class `Word2Vec` described below.
Class description:
Implement the Word2Vec class.
Method signatures and docstrings:
- def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1): initializer for word2vec :param type: :param windowSize: :param numHidden: :... | Implement the Python class `Word2Vec` described below.
Class description:
Implement the Word2Vec class.
Method signatures and docstrings:
- def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1): initializer for word2vec :param type: :param windowSize: :param numHidden: :... | 65bc3e69637f0d39ec53c1b0317370d18946c0e9 | <|skeleton|>
class Word2Vec:
def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1):
"""initializer for word2vec :param type: :param windowSize: :param numHidden: :param nEpochs: :param text: :param learningRate:"""
<|body_0|>
def skipgram(self, co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Word2Vec:
def __init__(self, algo='skipgram', windowSize=2, numHidden=2, nEpochs=1, text='', learningRate=0.1):
"""initializer for word2vec :param type: :param windowSize: :param numHidden: :param nEpochs: :param text: :param learningRate:"""
self.algo = algo
self.windowSize = windowSi... | the_stack_v2_python_sparse | Chapter08/word2vec/word2vec.py | kumarikumari/Keras-Deep-Learning-Cookbook | train | 0 | |
fdf2b56ea98ebec15e4fc75a9585cf1e97c7f173 | [
"super(channel_selection, self).__init__()\nself.indexes = nn.Parameter(torch.ones(num_channels))\nassert len(mask) == num_channels\nmask = torch.from_numpy(mask)\nself.indexes.data.mul_(mask)",
"selected_index = np.squeeze(np.argwhere(self.indexes.data.cpu().numpy()))\nif selected_index.size == 1:\n selected_... | <|body_start_0|>
super(channel_selection, self).__init__()
self.indexes = nn.Parameter(torch.ones(num_channels))
assert len(mask) == num_channels
mask = torch.from_numpy(mask)
self.indexes.data.mul_(mask)
<|end_body_0|>
<|body_start_1|>
selected_index = np.squeeze(np.arg... | Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`. | channel_selection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class channel_selection:
"""Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`."""
def __init__(self, num_channels, mask):
"""Initialize the `indexes` wit... | stack_v2_sparse_classes_75kplus_train_008243 | 26,099 | no_license | [
{
"docstring": "Initialize the `indexes` with all one vector with the length same as the number of channels. During pruning, the places in `indexes` which correpond to the channels to be pruned will be set to 0.",
"name": "__init__",
"signature": "def __init__(self, num_channels, mask)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_000270 | Implement the Python class `channel_selection` described below.
Class description:
Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`.
Method signatures and docstrings:
- def __init_... | Implement the Python class `channel_selection` described below.
Class description:
Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`.
Method signatures and docstrings:
- def __init_... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class channel_selection:
"""Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`."""
def __init__(self, num_channels, mask):
"""Initialize the `indexes` wit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class channel_selection:
"""Select channels from the output of BatchNorm2d layer. It should be put directly after BatchNorm2d layer. The output shape of this layer is determined by the number of 1 in `self.indexes`."""
def __init__(self, num_channels, mask):
"""Initialize the `indexes` with all one vec... | the_stack_v2_python_sparse | generated/test_Eric_mingjie_rethinking_network_pruning.py | jansel/pytorch-jit-paritybench | train | 35 |
9ecf5be9dab65c1850dee52e34715500c48ff671 | [
"super(PointNetEstimation, self).__init__()\nself.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=False)\nself.concat = ms.ops.Concat(axis=1)\nself.wconv1 = WarpConv1d(3, 128, kernel_size=1, BN=True, use_activity=True)\nself.wconv2 = WarpConv1d(128, 128, kernel_size=1, BN=True, use_activity=True)\nself.wconv3 = W... | <|body_start_0|>
super(PointNetEstimation, self).__init__()
self.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=False)
self.concat = ms.ops.Concat(axis=1)
self.wconv1 = WarpConv1d(3, 128, kernel_size=1, BN=True, use_activity=True)
self.wconv2 = WarpConv1d(128, 128, kernel_size... | PointNetEstimation | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def construct(self, pts: ms.Tenso... | stack_v2_sparse_classes_75kplus_train_008244 | 19,684 | permissive | [
{
"docstring": "v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]",
"name": "__init__",
"signature": "def __init__(self, n_classes=3)"
},
{
"docstring": ":param pts: [bs,3,m]... | 2 | stack_v2_sparse_classes_30k_train_012328 | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param... | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def construct(self, pts: ms.Tenso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
super(PointNetEstimation, self).__init__()
self.max_op ... | the_stack_v2_python_sparse | research/cv/frustum-pointnet/src/frustum_pointnets_v1.py | mindspore-ai/models | train | 301 | |
417fc9895ec757b5edf32a4cae2136aff65d0071 | [
"while m > 0 and n > 0:\n if nums1[m - 1] >= nums2[n - 1]:\n nums1[m + n - 1] = nums1[m - 1]\n m -= 1\n else:\n nums1[m + n - 1] = nums2[n - 1]\n n -= 1\nif n > 0:\n nums1[:n] = nums2[:n]",
"if not nums1 or not nums2:\n return\nnums1[m:] = nums2[:]\nnums1.sort()"
] | <|body_start_0|>
while m > 0 and n > 0:
if nums1[m - 1] >= nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge_cheat(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything... | stack_v2_sparse_classes_75kplus_train_008245 | 1,058 | no_license | [
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None"
},
{
"docstring": "Do not return anything, modify nums1 in-place instead.",
"name": "merge_cheat",
"signatu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge_cheat(self, nums1: List[int], m: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: Do not return anything, modify nums1 in-place instead.
- def merge_cheat(self, nums1: List[int], m: i... | e9620cc0035de94d6b1789b21717ed236fc9069e | <|skeleton|>
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge_cheat(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""Do not return anything, modify nums1 in-place instead."""
while m > 0 and n > 0:
if nums1[m - 1] >= nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
... | the_stack_v2_python_sparse | Python/LeetCodeTest/lc088_MergeSortedArray.py | Olddays/myExercise | train | 0 | |
588b1e7ec922834ad5143bae0e228b55142a06a4 | [
"self.dimension = dimension\nself.a1 = np.array(a1)\nself.a2 = np.array(a2)\nself.a3 = np.array(a3)\nself.sites = []\nself.bonds = []\nself.Nsites = 0\nself.Nbonds = 0",
"if site.label == None:\n site.label = site_label_dir[str(self.Nsites)]\nif site.color == None:\n site.color = site_color_dir[str(self.Nsi... | <|body_start_0|>
self.dimension = dimension
self.a1 = np.array(a1)
self.a2 = np.array(a2)
self.a3 = np.array(a3)
self.sites = []
self.bonds = []
self.Nsites = 0
self.Nbonds = 0
<|end_body_0|>
<|body_start_1|>
if site.label == None:
sit... | Primitive cell of the lattice | Cell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitiv... | stack_v2_sparse_classes_75kplus_train_008246 | 7,577 | permissive | [
{
"docstring": "Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitive vector a3 : list third component of primitive vector",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_001884 | Implement the Python class `Cell` described below.
Class description:
Primitive cell of the lattice
Method signatures and docstrings:
- def __init__(self, dimension, a1, a2, a3): Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component o... | Implement the Python class `Cell` described below.
Class description:
Primitive cell of the lattice
Method signatures and docstrings:
- def __init__(self, dimension, a1, a2, a3): Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component o... | 9b6323857fc27b17056ad6c8520d4a10a23dad4b | <|skeleton|>
class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitiv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cell:
"""Primitive cell of the lattice"""
def __init__(self, dimension, a1, a2, a3):
"""Initialize of cell instance Parameters ---------- dimension : int dimension of the cell, which can be 1, 2 or 3 a1 : list first component of primitive vector a2 : list second component of primitive vector a3 :... | the_stack_v2_python_sparse | moha/modelsystem/lattice.py | xujunyao0928/moha | train | 0 |
09505808e73c7142cea3ffed9cc99c9149c569a4 | [
"if not root:\n return 0\ni = 0\ncurLevel = [root]\nlastLvCnt = 0\nwhile curLevel:\n lastLvCnt = len(curLevel)\n _curLevel = []\n while curLevel:\n t = curLevel.pop(0)\n if t.left:\n _curLevel.append(t.left)\n if t.right:\n _curLevel.append(t.right)\n curLev... | <|body_start_0|>
if not root:
return 0
i = 0
curLevel = [root]
lastLvCnt = 0
while curLevel:
lastLvCnt = len(curLevel)
_curLevel = []
while curLevel:
t = curLevel.pop(0)
if t.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNodes(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
i = 0
... | stack_v2_sparse_classes_75kplus_train_008247 | 1,408 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "countNodes",
"signature": "def countNodes(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "countNodes1",
"signature": "def countNodes1(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041849 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root): :type root: TreeNode :rtype: int
- def countNodes1(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root): :type root: TreeNode :rtype: int
- def countNodes1(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def countNodes(sel... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def countNodes(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countNodes(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
i = 0
curLevel = [root]
lastLvCnt = 0
while curLevel:
lastLvCnt = len(curLevel)
_curLevel = []
while curLevel:
... | the_stack_v2_python_sparse | py/leetcode/222.py | wfeng1991/learnpy | train | 0 | |
258b25351b08bd4184886e76564ee8d23b1513e8 | [
"self.mobile_number = mobile_number\nself.date_of_birth = date_of_birth\nself.get_social_security_number = get_social_security_number\nself.external_reference = external_reference\nself.addonservices = addonservices\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nmo... | <|body_start_0|>
self.mobile_number = mobile_number
self.date_of_birth = date_of_birth
self.get_social_security_number = get_social_security_number
self.external_reference = external_reference
self.addonservices = addonservices
self.additional_properties = additional_prop... | Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified get_social_security_number (bool): Should the social... | CreateBankIDMobileRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateBankIDMobileRequest:
"""Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified... | stack_v2_sparse_classes_75kplus_train_008248 | 3,537 | permissive | [
{
"docstring": "Constructor for the CreateBankIDMobileRequest class",
"name": "__init__",
"signature": "def __init__(self, mobile_number=None, date_of_birth=None, get_social_security_number=None, external_reference=None, addonservices=None, additional_properties={})"
},
{
"docstring": "Creates a... | 2 | stack_v2_sparse_classes_30k_val_002254 | Implement the Python class `CreateBankIDMobileRequest` described below.
Class description:
Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birt... | Implement the Python class `CreateBankIDMobileRequest` described below.
Class description:
Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birt... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class CreateBankIDMobileRequest:
"""Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateBankIDMobileRequest:
"""Implementation of the 'CreateBankIDMobileRequest' model. Creates a BankID mobile identification process Attributes: mobile_number (string): Mobile number for the user that is to be identified date_of_birth (string): Date of birth for the user that is to be identified get_social_s... | the_stack_v2_python_sparse | idfy_rest_client/models/create_bank_id_mobile_request.py | dealflowteam/Idfy | train | 0 |
a0d76895e28f09417d36b0ef92499a4a098f0cc9 | [
"def cal(indexes: List[int]) -> int:\n res, left = (0, 0)\n for right in range(len(indexes)):\n while left <= right and indexes[right] - indexes[left] + 1 > k + right - left + 1:\n left += 1\n res = max(res, right - left + 1)\n return res\nmp = defaultdict(list)\nfor i, v in enumer... | <|body_start_0|>
def cal(indexes: List[int]) -> int:
res, left = (0, 0)
for right in range(len(indexes)):
while left <= right and indexes[right] - indexes[left] + 1 > k + right - left + 1:
left += 1
res = max(res, right - left + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
"""哈希表+不定长滑动窗口"""
<|body_0|>
def longestEqualSubarray2(self, nums: List[int], k: int) -> int:
"""二分+定长滑动窗口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def cal(indexes: Lis... | stack_v2_sparse_classes_75kplus_train_008249 | 2,316 | no_license | [
{
"docstring": "哈希表+不定长滑动窗口",
"name": "longestEqualSubarray",
"signature": "def longestEqualSubarray(self, nums: List[int], k: int) -> int"
},
{
"docstring": "二分+定长滑动窗口",
"name": "longestEqualSubarray2",
"signature": "def longestEqualSubarray2(self, nums: List[int], k: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_012008 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestEqualSubarray(self, nums: List[int], k: int) -> int: 哈希表+不定长滑动窗口
- def longestEqualSubarray2(self, nums: List[int], k: int) -> int: 二分+定长滑动窗口 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestEqualSubarray(self, nums: List[int], k: int) -> int: 哈希表+不定长滑动窗口
- def longestEqualSubarray2(self, nums: List[int], k: int) -> int: 二分+定长滑动窗口
<|skeleton|>
class Solut... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
"""哈希表+不定长滑动窗口"""
<|body_0|>
def longestEqualSubarray2(self, nums: List[int], k: int) -> int:
"""二分+定长滑动窗口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestEqualSubarray(self, nums: List[int], k: int) -> int:
"""哈希表+不定长滑动窗口"""
def cal(indexes: List[int]) -> int:
res, left = (0, 0)
for right in range(len(indexes)):
while left <= right and indexes[right] - indexes[left] + 1 > k + right - ... | the_stack_v2_python_sparse | 16_滑动窗口/2831. 找出最长等值子数组.py | 981377660LMT/algorithm-study | train | 225 | |
e2063b4154f217d2ff5041f56af8865f22ccaa65 | [
"challenges: List[Dict[str, Any]] = []\nchallenges = WeaponUnlockChallenges.Table(self, challenges)\nUtility.WriteFile(self, f'{self.eXAssets}/weaponUnlockChallenges.json', challenges)\nlog.info(f'Compiled {len(challenges):,} Weapon Unlock Challenges')",
"table: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{sel... | <|body_start_0|>
challenges: List[Dict[str, Any]] = []
challenges = WeaponUnlockChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXAssets}/weaponUnlockChallenges.json', challenges)
log.info(f'Compiled {len(challenges):,} Weapon Unlock Challenges')
<|end_body_0|>
<|body... | Weapon Unlock Challenge XAssets. | WeaponUnlockChallenges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeaponUnlockChallenges:
"""Weapon Unlock Challenge XAssets."""
def Compile(self: Any) -> None:
"""Compile the Weapon Unlock Challenge XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the gun_unlock_... | stack_v2_sparse_classes_75kplus_train_008250 | 13,794 | permissive | [
{
"docstring": "Compile the Weapon Unlock Challenge XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the gun_unlock_challenges.csv XAsset.",
"name": "Table",
"signature": "def Table(self: Any, challenges: List[Dict[str, Any]]) -> List... | 2 | stack_v2_sparse_classes_30k_train_050054 | Implement the Python class `WeaponUnlockChallenges` described below.
Class description:
Weapon Unlock Challenge XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Weapon Unlock Challenge XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Co... | Implement the Python class `WeaponUnlockChallenges` described below.
Class description:
Weapon Unlock Challenge XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Weapon Unlock Challenge XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Co... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class WeaponUnlockChallenges:
"""Weapon Unlock Challenge XAssets."""
def Compile(self: Any) -> None:
"""Compile the Weapon Unlock Challenge XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the gun_unlock_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeaponUnlockChallenges:
"""Weapon Unlock Challenge XAssets."""
def Compile(self: Any) -> None:
"""Compile the Weapon Unlock Challenge XAssets."""
challenges: List[Dict[str, Any]] = []
challenges = WeaponUnlockChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{se... | the_stack_v2_python_sparse | ModernWarfare/XAssets/challenges.py | dbuentello/Hyde | train | 0 |
41d0a4eeef47b8a2478b32980f723c1eab1456b0 | [
"request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': unicode}, 'group_name': {'type': unicode}, 'role': {'type': unicode}})\nrest_utils.validate_inputs(request_dict)\nrole_name = request_dict.get('role')\nif role_name:\n rest_utils.verify_role(role_name)\nelse:\n role_name = constant... | <|body_start_0|>
request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': unicode}, 'group_name': {'type': unicode}, 'role': {'type': unicode}})
rest_utils.validate_inputs(request_dict)
role_name = request_dict.get('role')
if role_name:
rest_utils.verify_... | TenantGroups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantGroups:
def put(self, multi_tenancy):
"""Add a group to a tenant"""
<|body_0|>
def patch(self, multi_tenancy):
"""Update role in group tenant association."""
<|body_1|>
def delete(self, multi_tenancy):
"""Remove a group from a tenant"""
... | stack_v2_sparse_classes_75kplus_train_008251 | 9,658 | permissive | [
{
"docstring": "Add a group to a tenant",
"name": "put",
"signature": "def put(self, multi_tenancy)"
},
{
"docstring": "Update role in group tenant association.",
"name": "patch",
"signature": "def patch(self, multi_tenancy)"
},
{
"docstring": "Remove a group from a tenant",
... | 3 | stack_v2_sparse_classes_30k_train_036612 | Implement the Python class `TenantGroups` described below.
Class description:
Implement the TenantGroups class.
Method signatures and docstrings:
- def put(self, multi_tenancy): Add a group to a tenant
- def patch(self, multi_tenancy): Update role in group tenant association.
- def delete(self, multi_tenancy): Remove... | Implement the Python class `TenantGroups` described below.
Class description:
Implement the TenantGroups class.
Method signatures and docstrings:
- def put(self, multi_tenancy): Add a group to a tenant
- def patch(self, multi_tenancy): Update role in group tenant association.
- def delete(self, multi_tenancy): Remove... | 760affb83facbe154c35c6ce20acb9432daa8bbd | <|skeleton|>
class TenantGroups:
def put(self, multi_tenancy):
"""Add a group to a tenant"""
<|body_0|>
def patch(self, multi_tenancy):
"""Update role in group tenant association."""
<|body_1|>
def delete(self, multi_tenancy):
"""Remove a group from a tenant"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TenantGroups:
def put(self, multi_tenancy):
"""Add a group to a tenant"""
request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': unicode}, 'group_name': {'type': unicode}, 'role': {'type': unicode}})
rest_utils.validate_inputs(request_dict)
role_name = re... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3/tenants.py | Metaswitch/cloudify-manager | train | 0 | |
ec9e578bb1d5c13d965e393791128852ef05874e | [
"ctx.save_for_backward(input)\noutput = torch.ones_like(input)\nreturn output",
"grad_input = None\ninput, = ctx.saved_tensors\nif ctx.needs_input_grad[0]:\n grad_input = input.clone()\nreturn grad_input"
] | <|body_start_0|>
ctx.save_for_backward(input)
output = torch.ones_like(input)
return output
<|end_body_0|>
<|body_start_1|>
grad_input = None
input, = ctx.saved_tensors
if ctx.needs_input_grad[0]:
grad_input = input.clone()
return grad_input
<|end_bod... | Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_activation = brelu.apply >>> t = torch.randn((5,5), dtype=torch.float, ... | bact | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bact:
"""Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_activation = brelu.apply >>> t = torch.... | stack_v2_sparse_classes_75kplus_train_008252 | 6,737 | permissive | [
{
"docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.",
... | 2 | stack_v2_sparse_classes_30k_train_003224 | Implement the Python class `bact` described below.
Class description:
Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_... | Implement the Python class `bact` described below.
Class description:
Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_... | db0d39757f97c2fa5711f2d8f0b680af479dc2cb | <|skeleton|>
class bact:
"""Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_activation = brelu.apply >>> t = torch.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class bact:
"""Implementation of BReLU activation function. Shape: - Input: (N, *) where * means, any number of additional dimensions - Output: (N, *), same shape as the input References: - See BReLU paper: https://arxiv.org/pdf/1709.04054.pdf Examples: >>> brelu_activation = brelu.apply >>> t = torch.randn((5,5), ... | the_stack_v2_python_sparse | dynamic_selection/loss/archive/cl.py | jaychoi12/FINE | train | 3 |
f481ba089e8c18dc7f52dd65a48ce43984550a78 | [
"us_state_abbrev = {'alabama': 'AL', 'alaska': 'AK', 'arizona': 'AZ', 'arkansas': 'AR', 'california': 'CA', 'colorado': 'CO', 'connecticut': 'CT', 'delaware': 'DE', 'florida': 'FL', 'georgia': 'GA', 'hawaii': 'HI', 'idaho': 'ID', 'illinois': 'IL', 'indiana': 'IN', 'iowa': 'IA', 'kansas': 'KS', 'kentucky': 'KY', 'lo... | <|body_start_0|>
us_state_abbrev = {'alabama': 'AL', 'alaska': 'AK', 'arizona': 'AZ', 'arkansas': 'AR', 'california': 'CA', 'colorado': 'CO', 'connecticut': 'CT', 'delaware': 'DE', 'florida': 'FL', 'georgia': 'GA', 'hawaii': 'HI', 'idaho': 'ID', 'illinois': 'IL', 'indiana': 'IN', 'iowa': 'IA', 'kansas': 'KS', '... | WeatherManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeatherManager:
def retrieve_weather_object(self, city, state):
"""Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns None if no weather object could be created. args city - a string representing a city name state - a stri... | stack_v2_sparse_classes_75kplus_train_008253 | 21,243 | no_license | [
{
"docstring": "Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns None if no weather object could be created. args city - a string representing a city name state - a string representing the state abbreviation",
"name": "retrieve_weather_obje... | 2 | stack_v2_sparse_classes_30k_test_001915 | Implement the Python class `WeatherManager` described below.
Class description:
Implement the WeatherManager class.
Method signatures and docstrings:
- def retrieve_weather_object(self, city, state): Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns N... | Implement the Python class `WeatherManager` described below.
Class description:
Implement the WeatherManager class.
Method signatures and docstrings:
- def retrieve_weather_object(self, city, state): Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns N... | 00db9c77c725c9f0a02d9120296c70313d02bfdd | <|skeleton|>
class WeatherManager:
def retrieve_weather_object(self, city, state):
"""Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns None if no weather object could be created. args city - a string representing a city name state - a stri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeatherManager:
def retrieve_weather_object(self, city, state):
"""Returns a weather object based on a city and state pair from the database. If it does not exist, creates it. Returns None if no weather object could be created. args city - a string representing a city name state - a string representin... | the_stack_v2_python_sparse | weather_service/models.py | jitesh-cloudmaaya/cloudmaaya | train | 0 | |
ba3fe3891cfaab36da0bf47caaf39ff4a5bf5e1f | [
"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... | Missing associated documentation comment in .proto file. | DiscoveryServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscoveryServicer:
"""Missing associated documentation comment in .proto file."""
def ExchangeNode(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Hello(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_75kplus_train_008254 | 24,581 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "ExchangeNode",
"signature": "def ExchangeNode(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Hello",
"signature": "def Hello(self, request,... | 4 | stack_v2_sparse_classes_30k_train_023310 | Implement the Python class `DiscoveryServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def ExchangeNode(self, request, context): Missing associated documentation comment in .proto file.
- def Hello(self, request, context): Missin... | Implement the Python class `DiscoveryServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def ExchangeNode(self, request, context): Missing associated documentation comment in .proto file.
- def Hello(self, request, context): Missin... | 345bf7df822c4ae5cd9988ffdedae2fa5c1ffd99 | <|skeleton|>
class DiscoveryServicer:
"""Missing associated documentation comment in .proto file."""
def ExchangeNode(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Hello(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscoveryServicer:
"""Missing associated documentation comment in .proto file."""
def ExchangeNode(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')... | the_stack_v2_python_sparse | grpc_pb2_grpc.py | isSPDL/SPDL | train | 3 |
d5a107d3f06b0f0ed33cda4810e159f50dcdee47 | [
"values = self.shift_data.getlist('ids', self.key_type)\nif not values:\n return Response(status=status.HTTP_200_OK)\nfield = self.shift_data.get('field')\nif field not in self.batch_set_fields:\n raise exceptions.PermissionDenied()\nfilter_config = self.batch_set_fields[field]\nallow_null = False\nif isinsta... | <|body_start_0|>
values = self.shift_data.getlist('ids', self.key_type)
if not values:
return Response(status=status.HTTP_200_OK)
field = self.shift_data.get('field')
if field not in self.batch_set_fields:
raise exceptions.PermissionDenied()
filter_config ... | 批量设置字段值混入类 | BatchSetModelMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchSetModelMixin:
"""批量设置字段值混入类"""
def batch_set(self, request):
"""批量设置字段通用api :param request: 请求对象 :return: 响应对象"""
<|body_0|>
def perform_batch_set(self, queryset, field, value):
"""批量设置字段通用更新 :param queryset: 更新的queryset :param field: 字段名称 :param value: 更新后... | stack_v2_sparse_classes_75kplus_train_008255 | 11,301 | no_license | [
{
"docstring": "批量设置字段通用api :param request: 请求对象 :return: 响应对象",
"name": "batch_set",
"signature": "def batch_set(self, request)"
},
{
"docstring": "批量设置字段通用更新 :param queryset: 更新的queryset :param field: 字段名称 :param value: 更新后的值 :return: 是否有更新",
"name": "perform_batch_set",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_008583 | Implement the Python class `BatchSetModelMixin` described below.
Class description:
批量设置字段值混入类
Method signatures and docstrings:
- def batch_set(self, request): 批量设置字段通用api :param request: 请求对象 :return: 响应对象
- def perform_batch_set(self, queryset, field, value): 批量设置字段通用更新 :param queryset: 更新的queryset :param field: 字... | Implement the Python class `BatchSetModelMixin` described below.
Class description:
批量设置字段值混入类
Method signatures and docstrings:
- def batch_set(self, request): 批量设置字段通用api :param request: 请求对象 :return: 响应对象
- def perform_batch_set(self, queryset, field, value): 批量设置字段通用更新 :param queryset: 更新的queryset :param field: 字... | a4502d14652c6a926e74be6d0f53b2b50ada9c3c | <|skeleton|>
class BatchSetModelMixin:
"""批量设置字段值混入类"""
def batch_set(self, request):
"""批量设置字段通用api :param request: 请求对象 :return: 响应对象"""
<|body_0|>
def perform_batch_set(self, queryset, field, value):
"""批量设置字段通用更新 :param queryset: 更新的queryset :param field: 字段名称 :param value: 更新后... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchSetModelMixin:
"""批量设置字段值混入类"""
def batch_set(self, request):
"""批量设置字段通用api :param request: 请求对象 :return: 响应对象"""
values = self.shift_data.getlist('ids', self.key_type)
if not values:
return Response(status=status.HTTP_200_OK)
field = self.shift_data.get(... | the_stack_v2_python_sparse | sv/sv_base/extensions/rest/mixins.py | xianzhishenqie/project_template | train | 1 |
50bfa94f976ed95b12dd2a8d1f81271675ce2246 | [
"try:\n collection = []\n for doc in Collection.objects(id=id):\n collection.append({'_id': str(ObjectId(doc['id'])), 'name': doc['name'], 'owner': doc['owner']['username'], 'private': doc['private'], 'snippets_id': [{'label': i['title'], 'value': str(ObjectId(i['id']))} for i in doc['snippets']], 'sni... | <|body_start_0|>
try:
collection = []
for doc in Collection.objects(id=id):
collection.append({'_id': str(ObjectId(doc['id'])), 'name': doc['name'], 'owner': doc['owner']['username'], 'private': doc['private'], 'snippets_id': [{'label': i['title'], 'value': str(ObjectId(i... | Requests against the Collection model to `api/collections/<id>` (singular) | CollectionApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionApi:
"""Requests against the Collection model to `api/collections/<id>` (singular)"""
def get(self, id):
"""Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection model Flags: If it doesn't exist. Returns: [{dict}] mappa... | stack_v2_sparse_classes_75kplus_train_008256 | 9,315 | permissive | [
{
"docstring": "Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection model Flags: If it doesn't exist. Returns: [{dict}] mappable JSON Flask Response, 200, with dereferenced nested fields full of data, as an array even for one document to keep the frontend... | 3 | stack_v2_sparse_classes_30k_train_029753 | Implement the Python class `CollectionApi` described below.
Class description:
Requests against the Collection model to `api/collections/<id>` (singular)
Method signatures and docstrings:
- def get(self, id): Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection ... | Implement the Python class `CollectionApi` described below.
Class description:
Requests against the Collection model to `api/collections/<id>` (singular)
Method signatures and docstrings:
- def get(self, id): Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection ... | 76fa490b6b3e5c4f5d554df4498c485f974c7581 | <|skeleton|>
class CollectionApi:
"""Requests against the Collection model to `api/collections/<id>` (singular)"""
def get(self, id):
"""Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection model Flags: If it doesn't exist. Returns: [{dict}] mappa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollectionApi:
"""Requests against the Collection model to `api/collections/<id>` (singular)"""
def get(self, id):
"""Retrieve one Collection object with a matching id. Yields: Identify a Collection object against a Collection model Flags: If it doesn't exist. Returns: [{dict}] mappable JSON Flas... | the_stack_v2_python_sparse | backend/resources/collection.py | taralika/cheathub | train | 0 |
75101d62ab7a284807bbfe6f4a4c2e54ca683062 | [
"record = super().__new__(cls, name, bases, attributes, **kwds)\nif pyre_extent or not hasattr(record, 'pyre_extent'):\n record.pyre_extent = weakref.WeakSet()\nreturn record",
"instance = super().__call__(*args, **kwds)\nself.pyre_extent.add(instance)\nreturn instance"
] | <|body_start_0|>
record = super().__new__(cls, name, bases, attributes, **kwds)
if pyre_extent or not hasattr(record, 'pyre_extent'):
record.pyre_extent = weakref.WeakSet()
return record
<|end_body_0|>
<|body_start_1|>
instance = super().__call__(*args, **kwds)
self.... | Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and all descendants are counted by that class. Descendants that want to keep... | Extent | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Extent:
"""Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and all descendants are counted by that cl... | stack_v2_sparse_classes_75kplus_train_008257 | 2,557 | permissive | [
{
"docstring": "Endow the class record being created, with a registry of instances of all classes whose base it is. The implementation here attaches a {weakset} of instances to the first class in a hierarchy that mentions {Extent} as its metaclass, by taking advantage of the way python metaclasses work. Do not ... | 2 | null | Implement the Python class `Extent` described below.
Class description:
Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and... | Implement the Python class `Extent` described below.
Class description:
Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Extent:
"""Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and all descendants are counted by that cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Extent:
"""Metaclass that endows its instances with awareness of their extent, defined as the set of instances of the class and all its subclasses. The class extent is stored with the first base class in a hierarchy that mentions {Extent} as a metaclass, and all descendants are counted by that class. Descenda... | the_stack_v2_python_sparse | packages/pyre/patterns/Extent.py | pyre/pyre | train | 27 |
d1ed43bab6171c876b2ad9ef9db834ab8f9026d5 | [
"query = User.Q\nif 'status' in where.keys():\n query = query.filter(User.status == where['status'])\nelse:\n query = query.filter(User.status != -1)\npagelist_obj = query.paginate(page=page, per_page=per_page)\nreturn pagelist_obj",
"if not id:\n raise JsonError('ID不能为空')\nobj = User.Q.filter(User.id ==... | <|body_start_0|>
query = User.Q
if 'status' in where.keys():
query = query.filter(User.status == where['status'])
else:
query = query.filter(User.status != -1)
pagelist_obj = query.paginate(page=page, per_page=per_page)
return pagelist_obj
<|end_body_0|>
... | UserService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
<|body_0|>
def get(id):
"""获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None"""
... | stack_v2_sparse_classes_75kplus_train_008258 | 2,701 | permissive | [
{
"docstring": "列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None",
"name": "page_list",
"signature": "def page_list(where, page, per_page)"
},
{
"docstring": "获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None",
"name"... | 4 | stack_v2_sparse_classes_30k_val_002633 | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def page_list(where, page, per_page): 列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None
- def get(id): 获取单条记录 [description... | Implement the Python class `UserService` described below.
Class description:
Implement the UserService class.
Method signatures and docstrings:
- def page_list(where, page, per_page): 列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None
- def get(id): 获取单条记录 [description... | 3300561c5686b674197ffc097cf781a931fd4787 | <|skeleton|>
class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
<|body_0|>
def get(id):
"""获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserService:
def page_list(where, page, per_page):
"""列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None"""
query = User.Q
if 'status' in where.keys():
query = query.filter(User.status == where['status'])
else:
... | the_stack_v2_python_sparse | applications/admin/services/user.py | leeyisoft/py_admin | train | 17 | |
f25e1a1992eb1f82a50da46d1195c7b214f415be | [
"super().__init__()\nself._logger = logger\nself._interval = interval\nself._lock = threading.Lock()\nself._shouldStop = False",
"with self._lock:\n self._shouldStop = True\nif self.is_alive() == True:\n self.join()",
"dockerInfo = DockerUtils.info()\nrootDir = dockerInfo['DockerRootDir']\nreportDisk = os... | <|body_start_0|>
super().__init__()
self._logger = logger
self._interval = interval
self._lock = threading.Lock()
self._shouldStop = False
<|end_body_0|>
<|body_start_1|>
with self._lock:
self._shouldStop = True
if self.is_alive() == True:
... | ResourceMonitor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceMonitor:
def __init__(self, logger, interval):
"""Creates a resource monitor with the specified configuration"""
<|body_0|>
def stop(self):
"""Stops the resource monitor thread"""
<|body_1|>
def run(self):
"""The resource monitor loop its... | stack_v2_sparse_classes_75kplus_train_008259 | 3,055 | permissive | [
{
"docstring": "Creates a resource monitor with the specified configuration",
"name": "__init__",
"signature": "def __init__(self, logger, interval)"
},
{
"docstring": "Stops the resource monitor thread",
"name": "stop",
"signature": "def stop(self)"
},
{
"docstring": "The resour... | 3 | stack_v2_sparse_classes_30k_train_025589 | Implement the Python class `ResourceMonitor` described below.
Class description:
Implement the ResourceMonitor class.
Method signatures and docstrings:
- def __init__(self, logger, interval): Creates a resource monitor with the specified configuration
- def stop(self): Stops the resource monitor thread
- def run(self... | Implement the Python class `ResourceMonitor` described below.
Class description:
Implement the ResourceMonitor class.
Method signatures and docstrings:
- def __init__(self, logger, interval): Creates a resource monitor with the specified configuration
- def stop(self): Stops the resource monitor thread
- def run(self... | 58e5c058b72a81c4eef0d2cdea896e253c8da2fc | <|skeleton|>
class ResourceMonitor:
def __init__(self, logger, interval):
"""Creates a resource monitor with the specified configuration"""
<|body_0|>
def stop(self):
"""Stops the resource monitor thread"""
<|body_1|>
def run(self):
"""The resource monitor loop its... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceMonitor:
def __init__(self, logger, interval):
"""Creates a resource monitor with the specified configuration"""
super().__init__()
self._logger = logger
self._interval = interval
self._lock = threading.Lock()
self._shouldStop = False
def stop(self)... | the_stack_v2_python_sparse | src/ue4docker/infrastructure/ResourceMonitor.py | slonopotamus/ue4-docker | train | 0 | |
e9520b0229d51424a4fec399f32987722990a4f1 | [
"location_columns = ['precinct', 'LOCATION_ZIPCODE', 'Latitude', 'Longitude']\ndescriptor = ['TYPE', 'REASON']\ndate_cols = ['open_dt', 'target_dt', 'closed_dt']\npunctual = ['OnTime_Status', 'CASE_STATUS']\nidentif = ['CASE_ENQUIRY_ID']\ndf[date_cols] = df[date_cols].apply(pd.to_datetime, errors='coerce')\ncomplet... | <|body_start_0|>
location_columns = ['precinct', 'LOCATION_ZIPCODE', 'Latitude', 'Longitude']
descriptor = ['TYPE', 'REASON']
date_cols = ['open_dt', 'target_dt', 'closed_dt']
punctual = ['OnTime_Status', 'CASE_STATUS']
identif = ['CASE_ENQUIRY_ID']
df[date_cols] = df[dat... | three_one_one | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class three_one_one:
def clean_transform_data(df):
"""Project data, and clean empty values"""
<|body_0|>
def execute(trial=False, custom_url=None):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_1|>
def provenance(doc... | stack_v2_sparse_classes_75kplus_train_008260 | 5,946 | no_license | [
{
"docstring": "Project data, and clean empty values",
"name": "clean_transform_data",
"signature": "def clean_transform_data(df)"
},
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False, c... | 3 | stack_v2_sparse_classes_30k_train_008241 | Implement the Python class `three_one_one` described below.
Class description:
Implement the three_one_one class.
Method signatures and docstrings:
- def clean_transform_data(df): Project data, and clean empty values
- def execute(trial=False, custom_url=None): Retrieve some data sets (not using the API here for the ... | Implement the Python class `three_one_one` described below.
Class description:
Implement the three_one_one class.
Method signatures and docstrings:
- def clean_transform_data(df): Project data, and clean empty values
- def execute(trial=False, custom_url=None): Retrieve some data sets (not using the API here for the ... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class three_one_one:
def clean_transform_data(df):
"""Project data, and clean empty values"""
<|body_0|>
def execute(trial=False, custom_url=None):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_1|>
def provenance(doc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class three_one_one:
def clean_transform_data(df):
"""Project data, and clean empty values"""
location_columns = ['precinct', 'LOCATION_ZIPCODE', 'Latitude', 'Longitude']
descriptor = ['TYPE', 'REASON']
date_cols = ['open_dt', 'target_dt', 'closed_dt']
punctual = ['OnTime_Sta... | the_stack_v2_python_sparse | kaidb_vilin/three_one_one.py | dwang1995/course-2018-spr-proj | train | 1 | |
8b5a10084a16973458219212d4e72249a8dd9c30 | [
"self._data = {}\nself._rows = M\nself._cols = N\nself._zaxis = O",
"row, col, zaxis = self._validate_key(key)\ntry:\n return self._data[row, col, zaxis]\nexcept KeyError:\n return 0",
"row, col, zaxis = self._validate_key(key)\nif value == 0:\n try:\n del self._data[row, col, zaxis]\n except... | <|body_start_0|>
self._data = {}
self._rows = M
self._cols = N
self._zaxis = O
<|end_body_0|>
<|body_start_1|>
row, col, zaxis = self._validate_key(key)
try:
return self._data[row, col, zaxis]
except KeyError:
return 0
<|end_body_1|>
<|bo... | array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class array:
def __init__(self, M, N, O):
"""Create an M-element list of N-element row lists with O-element zaxis lists."""
<|body_0|>
def __getitem__(self, key):
"""Returns the appropriate element for the three-element subscript tuple"""
<|body_1|>
def __seti... | stack_v2_sparse_classes_75kplus_train_008261 | 1,386 | no_license | [
{
"docstring": "Create an M-element list of N-element row lists with O-element zaxis lists.",
"name": "__init__",
"signature": "def __init__(self, M, N, O)"
},
{
"docstring": "Returns the appropriate element for the three-element subscript tuple",
"name": "__getitem__",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_train_009461 | Implement the Python class `array` described below.
Class description:
Implement the array class.
Method signatures and docstrings:
- def __init__(self, M, N, O): Create an M-element list of N-element row lists with O-element zaxis lists.
- def __getitem__(self, key): Returns the appropriate element for the three-ele... | Implement the Python class `array` described below.
Class description:
Implement the array class.
Method signatures and docstrings:
- def __init__(self, M, N, O): Create an M-element list of N-element row lists with O-element zaxis lists.
- def __getitem__(self, key): Returns the appropriate element for the three-ele... | 5c689afd7830d82cdf8b6b6f39ccf8a92931b93c | <|skeleton|>
class array:
def __init__(self, M, N, O):
"""Create an M-element list of N-element row lists with O-element zaxis lists."""
<|body_0|>
def __getitem__(self, key):
"""Returns the appropriate element for the three-element subscript tuple"""
<|body_1|>
def __seti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class array:
def __init__(self, M, N, O):
"""Create an M-element list of N-element row lists with O-element zaxis lists."""
self._data = {}
self._rows = M
self._cols = N
self._zaxis = O
def __getitem__(self, key):
"""Returns the appropriate element for the three-... | the_stack_v2_python_sparse | homework/Python4_Homework02/src/arr.py | rwehner/rl | train | 0 | |
c5a57c82805ddd3513d067f1bff35e37c02142a6 | [
"if not matrix or not matrix[0]:\n return\nself.tree = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n m = i + 1\n while m < len(matrix) + 1:\n n = j + 1\n while n < len(matrix[0]) + ... | <|body_start_0|>
if not matrix or not matrix[0]:
return
self.tree = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
m = i + 1
while m < len(matrix) + 1:
... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_75kplus_train_008262 | 4,302 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_034594 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | 9eb44afa4233fdedc2e5c72be0fdf54b25d1c45c | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix or not matrix[0]:
return
self.tree = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)]
for i in range(len(matrix)):
for j in range(len(matrix[... | the_stack_v2_python_sparse | Google/Pro308.Range Sum Query 2D-Mutable.py | YoyinZyc/Leetcode_Python | train | 0 | |
10fd9ccd9ba33448b3634438d04be0075875d54f | [
"cls.wb_metadata = {'key': 'value'}\nsuper(GetWebhook, cls).setUpClass(metadata=cls.wb_metadata)\ncls.get_webhook_response = cls.autoscale_client.get_webhook(cls.group.id, cls.policy['id'], cls.webhook['id'])\ncls.get_webhook = cls.get_webhook_response.entity",
"self.assertEquals(self.get_webhook_response.status_... | <|body_start_0|>
cls.wb_metadata = {'key': 'value'}
super(GetWebhook, cls).setUpClass(metadata=cls.wb_metadata)
cls.get_webhook_response = cls.autoscale_client.get_webhook(cls.group.id, cls.policy['id'], cls.webhook['id'])
cls.get_webhook = cls.get_webhook_response.entity
<|end_body_0|>
... | Verify get webhook | GetWebhook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetWebhook:
"""Verify get webhook"""
def setUpClass(cls):
"""Create scaling group with webhook."""
<|body_0|>
def test_get_webhook(self):
"""Get a webhook and verify response code 200, headers and the data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_008263 | 1,888 | permissive | [
{
"docstring": "Create scaling group with webhook.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Get a webhook and verify response code 200, headers and the data.",
"name": "test_get_webhook",
"signature": "def test_get_webhook(self)"
}
] | 2 | null | Implement the Python class `GetWebhook` described below.
Class description:
Verify get webhook
Method signatures and docstrings:
- def setUpClass(cls): Create scaling group with webhook.
- def test_get_webhook(self): Get a webhook and verify response code 200, headers and the data. | Implement the Python class `GetWebhook` described below.
Class description:
Verify get webhook
Method signatures and docstrings:
- def setUpClass(cls): Create scaling group with webhook.
- def test_get_webhook(self): Get a webhook and verify response code 200, headers and the data.
<|skeleton|>
class GetWebhook:
... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class GetWebhook:
"""Verify get webhook"""
def setUpClass(cls):
"""Create scaling group with webhook."""
<|body_0|>
def test_get_webhook(self):
"""Get a webhook and verify response code 200, headers and the data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetWebhook:
"""Verify get webhook"""
def setUpClass(cls):
"""Create scaling group with webhook."""
cls.wb_metadata = {'key': 'value'}
super(GetWebhook, cls).setUpClass(metadata=cls.wb_metadata)
cls.get_webhook_response = cls.autoscale_client.get_webhook(cls.group.id, cls.p... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/functional/webhooks/test_get_webhook.py | rackerlabs/otter | train | 20 |
6f11a93820d1f8f053b07934b0238a3ba8a4af93 | [
"response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')\nevents = response.json()\nself.assertEqual(response.status_code, status.HTTP_200_OK)\nself.assertEqual(response.headers['Content-Type'], 'application/json')\nself.assertGreater(len(events), 1)",
"response = requests.get(... | <|body_start_0|>
response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')
events = response.json()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.headers['Content-Type'], 'application/json')
self.assertGreat... | SamoaTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
<|body_0|>
def test_17012_returns_systems_coffee(self):
"""Tests whether the event with id 17012 returns the correct seminar."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_008264 | 13,057 | permissive | [
{
"docstring": "Tests whether a connection to samoa is successful.",
"name": "test_connection_to_samoa_api",
"signature": "def test_connection_to_samoa_api(self)"
},
{
"docstring": "Tests whether the event with id 17012 returns the correct seminar.",
"name": "test_17012_returns_systems_coffe... | 2 | stack_v2_sparse_classes_30k_train_002548 | Implement the Python class `SamoaTests` described below.
Class description:
Implement the SamoaTests class.
Method signatures and docstrings:
- def test_connection_to_samoa_api(self): Tests whether a connection to samoa is successful.
- def test_17012_returns_systems_coffee(self): Tests whether the event with id 1701... | Implement the Python class `SamoaTests` described below.
Class description:
Implement the SamoaTests class.
Method signatures and docstrings:
- def test_connection_to_samoa_api(self): Tests whether a connection to samoa is successful.
- def test_17012_returns_systems_coffee(self): Tests whether the event with id 1701... | c8330258778dd7f71b1289c5dfe611e5637cf71d | <|skeleton|>
class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
<|body_0|>
def test_17012_returns_systems_coffee(self):
"""Tests whether the event with id 17012 returns the correct seminar."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')
events = response.json()
self.assertEqual(response.status_code, status.HTTP_2... | the_stack_v2_python_sparse | seminar-roulette/backend/tests.py | olliegardner/seminar-roulette | train | 0 | |
b559ab8b7486db3cf3287307c1c447045b63ba13 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Agreement()",
"from .agreement_acceptance import AgreementAcceptance\nfrom .agreement_file import AgreementFile\nfrom .agreement_file_localization import AgreementFileLocalization\nfrom .entity import Entity\nfrom .terms_expiration imp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Agreement()
<|end_body_0|>
<|body_start_1|>
from .agreement_acceptance import AgreementAcceptance
from .agreement_file import AgreementFile
from .agreement_file_localization impo... | Agreement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agreement:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Agreement:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Agreem... | stack_v2_sparse_classes_75kplus_train_008265 | 5,510 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Agreement",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | null | Implement the Python class `Agreement` described below.
Class description:
Implement the Agreement class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Agreement: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `Agreement` described below.
Class description:
Implement the Agreement class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Agreement: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Agreement:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Agreement:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Agreem... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Agreement:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Agreement:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Agreement"""
... | the_stack_v2_python_sparse | msgraph/generated/models/agreement.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a5843c092b533200e039c8b9013af4c99543248a | [
"lengths = [len(s) for s in strs]\nnstrs = len(strs)\nencoded = str(nstrs) + '|' + '|'.join([str(l) for l in lengths]) + '|'\nencoded += ''.join(strs)\nreturn encoded",
"i, j = (0, 0)\nwhile s[j] != '|':\n j += 1\nnstrs = int(s[i:j])\ni = j + 1\nj += 1\nlengths = list()\nfor _ in range(nstrs):\n while s[j] ... | <|body_start_0|>
lengths = [len(s) for s in strs]
nstrs = len(strs)
encoded = str(nstrs) + '|' + '|'.join([str(l) for l in lengths]) + '|'
encoded += ''.join(strs)
return encoded
<|end_body_0|>
<|body_start_1|>
i, j = (0, 0)
while s[j] != '|':
j += 1
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lengths =... | stack_v2_sparse_classes_75kplus_train_008266 | 995 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_013635 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 78ed11f34fd03e9a188c9c6cb352e883016d05d9 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
lengths = [len(s) for s in strs]
nstrs = len(strs)
encoded = str(nstrs) + '|' + '|'.join([str(l) for l in lengths]) + '|'
encoded += ''.join(strs)
return encoded
... | the_stack_v2_python_sparse | 271_Encode_and_Decode_Strings.py | 26XINXIN/leetcode | train | 0 | |
07d5ba0d0f2986dd04816ab1ac5efb376333feda | [
"land_data = np.ones((2, 3, 4), dtype=np.float32)\nsea_data = np.ones((2, 3, 4), dtype=np.float32) * 3.0\nmask = np.array([[[True, False, False, False], [True, False, False, False], [False, False, False, True]], [[True, False, False, False], [True, False, False, False], [False, False, False, True]]])\nland_data = n... | <|body_start_0|>
land_data = np.ones((2, 3, 4), dtype=np.float32)
sea_data = np.ones((2, 3, 4), dtype=np.float32) * 3.0
mask = np.array([[[True, False, False, False], [True, False, False, False], [False, False, False, True]], [[True, False, False, False], [True, False, False, False], [False, Fal... | Test merge_land_and_sea | Test_merge_land_and_sea | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_merge_land_and_sea:
"""Test merge_land_and_sea"""
def setUp(self):
"""Set up a percentile cube"""
<|body_0|>
def test_missing_dim(self):
"""Check that an error is raised if missing dimensional coordinate"""
<|body_1|>
def test_mismatch_dim_lengt... | stack_v2_sparse_classes_75kplus_train_008267 | 38,867 | permissive | [
{
"docstring": "Set up a percentile cube",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check that an error is raised if missing dimensional coordinate",
"name": "test_missing_dim",
"signature": "def test_missing_dim(self)"
},
{
"docstring": "Check an error ... | 6 | null | Implement the Python class `Test_merge_land_and_sea` described below.
Class description:
Test merge_land_and_sea
Method signatures and docstrings:
- def setUp(self): Set up a percentile cube
- def test_missing_dim(self): Check that an error is raised if missing dimensional coordinate
- def test_mismatch_dim_length(se... | Implement the Python class `Test_merge_land_and_sea` described below.
Class description:
Test merge_land_and_sea
Method signatures and docstrings:
- def setUp(self): Set up a percentile cube
- def test_missing_dim(self): Check that an error is raised if missing dimensional coordinate
- def test_mismatch_dim_length(se... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_merge_land_and_sea:
"""Test merge_land_and_sea"""
def setUp(self):
"""Set up a percentile cube"""
<|body_0|>
def test_missing_dim(self):
"""Check that an error is raised if missing dimensional coordinate"""
<|body_1|>
def test_mismatch_dim_lengt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_merge_land_and_sea:
"""Test merge_land_and_sea"""
def setUp(self):
"""Set up a percentile cube"""
land_data = np.ones((2, 3, 4), dtype=np.float32)
sea_data = np.ones((2, 3, 4), dtype=np.float32) * 3.0
mask = np.array([[[True, False, False, False], [True, False, False,... | the_stack_v2_python_sparse | improver_tests/calibration/utilities/test_utilities.py | metoppv/improver | train | 101 |
df6645a3d0087aebb93e94304fe3248f079335dc | [
"if request.user.is_authenticated():\n return redirect(reverse(settings.LOGIN_REDIRECT_URL))\ntoken = kwargs.get('registration_token')\npending_homebuyer_filter = PendingHomebuyer.objects.filter(registration_token=token)\nif not pending_homebuyer_filter.exists():\n messages.error(request, 'Invalid Registratio... | <|body_start_0|>
if request.user.is_authenticated():
return redirect(reverse(settings.LOGIN_REDIRECT_URL))
token = kwargs.get('registration_token')
pending_homebuyer_filter = PendingHomebuyer.objects.filter(registration_token=token)
if not pending_homebuyer_filter.exists():
... | This form is used to register homebuyers that have been invited to the app by a Realtor. | HomebuyerSignupView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomebuyerSignupView:
"""This form is used to register homebuyers that have been invited to the app by a Realtor."""
def dispatch(self, request, *args, **kwargs):
"""Manages registration of Homebuyers who have been invited. For all request methods: - If the user is already logged in, ... | stack_v2_sparse_classes_75kplus_train_008268 | 5,776 | no_license | [
{
"docstring": "Manages registration of Homebuyers who have been invited. For all request methods: - If the user is already logged in, redirect home. - If the registration token does not correspond to a valid token, redirect to the login page with an error. - If the registration token corresponds to an already ... | 3 | stack_v2_sparse_classes_30k_train_052583 | Implement the Python class `HomebuyerSignupView` described below.
Class description:
This form is used to register homebuyers that have been invited to the app by a Realtor.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Manages registration of Homebuyers who have been invited. For ... | Implement the Python class `HomebuyerSignupView` described below.
Class description:
This form is used to register homebuyers that have been invited to the app by a Realtor.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Manages registration of Homebuyers who have been invited. For ... | 69638dc2378846aa70d90202d81e72d18ca753e1 | <|skeleton|>
class HomebuyerSignupView:
"""This form is used to register homebuyers that have been invited to the app by a Realtor."""
def dispatch(self, request, *args, **kwargs):
"""Manages registration of Homebuyers who have been invited. For all request methods: - If the user is already logged in, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomebuyerSignupView:
"""This form is used to register homebuyers that have been invited to the app by a Realtor."""
def dispatch(self, request, *args, **kwargs):
"""Manages registration of Homebuyers who have been invited. For all request methods: - If the user is already logged in, redirect home... | the_stack_v2_python_sparse | RealEstate/apps/pending/views.py | fabiopiovam/RealEstate-1 | train | 0 |
9acb8e88722b1681bb55ebcbc23c391d8fdf6396 | [
"async with ClientSession() as session:\n async with session.get(url=url) as response:\n if response.status < 200 or response.status > 399:\n raise APIError(await response.text())\n return await response.json()",
"async with ClientSession() as session:\n async with session.post(url=... | <|body_start_0|>
async with ClientSession() as session:
async with session.get(url=url) as response:
if response.status < 200 or response.status > 399:
raise APIError(await response.text())
return await response.json()
<|end_body_0|>
<|body_start_... | An interface to the REST API. | Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.... | stack_v2_sparse_classes_75kplus_train_008269 | 12,017 | no_license | [
{
"docstring": "Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.",
"name": "get",
"signature": "async def get(self, url)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_028092 | Implement the Python class `Resource` described below.
Class description:
An interface to the REST API.
Method signatures and docstrings:
- async def get(self, url): Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: AP... | Implement the Python class `Resource` described below.
Class description:
An interface to the REST API.
Method signatures and docstrings:
- async def get(self, url): Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: AP... | 72f407f8c8862e59383bfb913edf55e367d4f45a | <|skeleton|>
class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resource:
"""An interface to the REST API."""
async def get(self, url):
"""Execute a GET request on the specified url. Note: awaitable method. Args: url (str): URL of the request. Returns: dict: Body of the response. Raises: APIError: If remote server responds with a non-200 OK code."""
a... | the_stack_v2_python_sparse | core/api.py | gorolykmaxim/loadbalancer | train | 0 |
f91bfdf5084794ca51e0e7978f9da96abda9ea2c | [
"request = self.oauth_request(access_token, SKYROCK_CHECK_AUTH)\njson = self.fetch_response(request)\ntry:\n return simplejson.loads(json)\nexcept ValueError:\n return None",
"if 'denied' in self.data:\n raise ValueError('Authentication denied')\nelse:\n return super(SkyrockAuth, self).auth_complete(*... | <|body_start_0|>
request = self.oauth_request(access_token, SKYROCK_CHECK_AUTH)
json = self.fetch_response(request)
try:
return simplejson.loads(json)
except ValueError:
return None
<|end_body_0|>
<|body_start_1|>
if 'denied' in self.data:
rai... | Skyrock OAuth authentication mechanism | SkyrockAuth | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkyrockAuth:
"""Skyrock OAuth authentication mechanism"""
def user_data(self, access_token):
"""Return user data provided"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_008270 | 2,573 | permissive | [
{
"docstring": "Return user data provided",
"name": "user_data",
"signature": "def user_data(self, access_token)"
},
{
"docstring": "Completes loging process, must return user instance",
"name": "auth_complete",
"signature": "def auth_complete(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001259 | Implement the Python class `SkyrockAuth` described below.
Class description:
Skyrock OAuth authentication mechanism
Method signatures and docstrings:
- def user_data(self, access_token): Return user data provided
- def auth_complete(self, *args, **kwargs): Completes loging process, must return user instance | Implement the Python class `SkyrockAuth` described below.
Class description:
Skyrock OAuth authentication mechanism
Method signatures and docstrings:
- def user_data(self, access_token): Return user data provided
- def auth_complete(self, *args, **kwargs): Completes loging process, must return user instance
<|skelet... | e47512f568b7dc7d247d0f667d8ef34972beb1d1 | <|skeleton|>
class SkyrockAuth:
"""Skyrock OAuth authentication mechanism"""
def user_data(self, access_token):
"""Return user data provided"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SkyrockAuth:
"""Skyrock OAuth authentication mechanism"""
def user_data(self, access_token):
"""Return user data provided"""
request = self.oauth_request(access_token, SKYROCK_CHECK_AUTH)
json = self.fetch_response(request)
try:
return simplejson.loads(json)
... | the_stack_v2_python_sparse | social_auth/backends/contrib/skyrock.py | gugu/django-social-auth-1 | train | 3 |
fe962177072d4f8af63debe4dd6a5fcec650f34e | [
"if isinstance(data, np.ndarray):\n data = [data]\ndata = [arr.astype(arr.dtype.kind) for arr in data]\naxis = 0 if P.data_format() == 'batch_first' else -1\nassert all((data[0].shape[axis] == arr.shape[axis] for arr in data)), f'Unequal num of examples in {P.data_format()} (axis={axis}): {[arr.shape for arr in ... | <|body_start_0|>
if isinstance(data, np.ndarray):
data = [data]
data = [arr.astype(arr.dtype.kind) for arr in data]
axis = 0 if P.data_format() == 'batch_first' else -1
assert all((data[0].shape[axis] == arr.shape[axis] for arr in data)), f'Unequal num of examples in {P.data_... | Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead. | NumpySerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumpySerializer:
"""Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead."""
def save(data: Union[np.ndarray, List[np.ndarray]], path: str, compress: bool=True) -> None:
... | stack_v2_sparse_classes_75kplus_train_008271 | 23,574 | permissive | [
{
"docstring": "Save data to .npz file. Params: ------- data: np.ndarray or list of np.ndarray The ndarray's to serialize. path: str Output npz file. compress: bool, default=True If True, uses gzip to compress the file. If False, no compression is performed.",
"name": "save",
"signature": "def save(data... | 2 | null | Implement the Python class `NumpySerializer` described below.
Class description:
Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead.
Method signatures and docstrings:
- def save(data: Union[np.ndarr... | Implement the Python class `NumpySerializer` described below.
Class description:
Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead.
Method signatures and docstrings:
- def save(data: Union[np.ndarr... | f3c4d601078b52513af6832c3faf75ddafc59ac5 | <|skeleton|>
class NumpySerializer:
"""Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead."""
def save(data: Union[np.ndarray, List[np.ndarray]], path: str, compress: bool=True) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumpySerializer:
"""Serialize ndarray's to a npz dict. Note that npz files do not support lazy loading and are >10x slower than LMDB/TFRecord serializers. Use :class:`LMDBSerializer` instead."""
def save(data: Union[np.ndarray, List[np.ndarray]], path: str, compress: bool=True) -> None:
"""Save d... | the_stack_v2_python_sparse | profit/utils/data_utils/serializers.py | ayushkarnawat/profit | train | 0 |
42583bca2b26c879d2c50fe54ab9659817235656 | [
"self._if_index = dict()\nsp = subprocess.run(['/usr/local/sbin/ifinfo'], capture_output=True, text=True)\ninterfaces = re.findall('Interface ([^ ]+)', sp.stdout)\nfor index, interface in enumerate(interfaces, start=1):\n self._if_index['%s' % index] = interface",
"if '%s' % if_index in self._if_index:\n re... | <|body_start_0|>
self._if_index = dict()
sp = subprocess.run(['/usr/local/sbin/ifinfo'], capture_output=True, text=True)
interfaces = re.findall('Interface ([^ ]+)', sp.stdout)
for index, interface in enumerate(interfaces, start=1):
self._if_index['%s' % index] = interface
<|... | mapper for local interface index to interface name (1 -> em0 for example) | Interfaces | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interfaces:
"""mapper for local interface index to interface name (1 -> em0 for example)"""
def __init__(self):
"""construct local interface mapping"""
<|body_0|>
def if_device(self, if_index):
"""convert index to device (if found)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_008272 | 3,400 | permissive | [
{
"docstring": "construct local interface mapping",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "convert index to device (if found)",
"name": "if_device",
"signature": "def if_device(self, if_index)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042349 | Implement the Python class `Interfaces` described below.
Class description:
mapper for local interface index to interface name (1 -> em0 for example)
Method signatures and docstrings:
- def __init__(self): construct local interface mapping
- def if_device(self, if_index): convert index to device (if found) | Implement the Python class `Interfaces` described below.
Class description:
mapper for local interface index to interface name (1 -> em0 for example)
Method signatures and docstrings:
- def __init__(self): construct local interface mapping
- def if_device(self, if_index): convert index to device (if found)
<|skeleto... | a702cf9fb3300e125cd7acc8af3813474606e509 | <|skeleton|>
class Interfaces:
"""mapper for local interface index to interface name (1 -> em0 for example)"""
def __init__(self):
"""construct local interface mapping"""
<|body_0|>
def if_device(self, if_index):
"""convert index to device (if found)"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interfaces:
"""mapper for local interface index to interface name (1 -> em0 for example)"""
def __init__(self):
"""construct local interface mapping"""
self._if_index = dict()
sp = subprocess.run(['/usr/local/sbin/ifinfo'], capture_output=True, text=True)
interfaces = re.f... | the_stack_v2_python_sparse | src/opnsense/scripts/netflow/lib/parse.py | opnsense/core | train | 2,778 |
b0c7f2ce5c4d44ff3a8c63eae415a1bc9ef8e618 | [
"nn.Module.__init__(self)\nself.conv1 = nn.Conv2d(in_channel, out_channel, kernel_size=3, stride=1, bias=False, padding=1, dilation=1)\nself.bn1 = nn.BatchNorm2d(out_channel)\nself.relu = nn.ReLU(inplace=True)\nif stride == 1:\n self.conv2 = nn.Conv2d(out_channel, out_channel, kernel_size=3, stride=1, bias=False... | <|body_start_0|>
nn.Module.__init__(self)
self.conv1 = nn.Conv2d(in_channel, out_channel, kernel_size=3, stride=1, bias=False, padding=1, dilation=1)
self.bn1 = nn.BatchNorm2d(out_channel)
self.relu = nn.ReLU(inplace=True)
if stride == 1:
self.conv2 = nn.Conv2d(out_ch... | Up Residual Block for the ResNet18-like decoder (without bottleneck). | UpResidualBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpResidualBlock:
"""Up Residual Block for the ResNet18-like decoder (without bottleneck)."""
def __init__(self, in_channel, out_channel, stride=1, upsample=None):
"""in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]-> + -> out |__________________________[upsample]________... | stack_v2_sparse_classes_75kplus_train_008273 | 10,410 | permissive | [
{
"docstring": "in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]-> + -> out |__________________________[upsample]________________________| ---------- INPUT |---- in_channel (int) the number of input channels. |---- out_channel (int) the number of output channels. |---- stride (int) the stride for t... | 2 | stack_v2_sparse_classes_30k_train_020674 | Implement the Python class `UpResidualBlock` described below.
Class description:
Up Residual Block for the ResNet18-like decoder (without bottleneck).
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel, stride=1, upsample=None): in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]... | Implement the Python class `UpResidualBlock` described below.
Class description:
Up Residual Block for the ResNet18-like decoder (without bottleneck).
Method signatures and docstrings:
- def __init__(self, in_channel, out_channel, stride=1, upsample=None): in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class UpResidualBlock:
"""Up Residual Block for the ResNet18-like decoder (without bottleneck)."""
def __init__(self, in_channel, out_channel, stride=1, upsample=None):
"""in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]-> + -> out |__________________________[upsample]________... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpResidualBlock:
"""Up Residual Block for the ResNet18-like decoder (without bottleneck)."""
def __init__(self, in_channel, out_channel, stride=1, upsample=None):
"""in ->[Conv3x3]->[BN]->[ReLU]->[Conv3x3 / ConvTransp3x3]->[BN]-> + -> out |__________________________[upsample]_____________________... | the_stack_v2_python_sparse | Code/src/models/networks/ResNetBlocks.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
877752c66b8b5ccdd5658b49bd61b78652e65a86 | [
"query = dict()\nproject and query.update(project=project)\naction and query.update(action=action)\nobj = ProjectLog.objects.filter(**query).order_by('-updated')\ndataset = [dict()]\nreturn self.result_class(data=obj)(serialize=True)",
"obj = ProjectLog.objects.create(project=project, action=action, content=kwarg... | <|body_start_0|>
query = dict()
project and query.update(project=project)
action and query.update(action=action)
obj = ProjectLog.objects.filter(**query).order_by('-updated')
dataset = [dict()]
return self.result_class(data=obj)(serialize=True)
<|end_body_0|>
<|body_star... | ProjectLogViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
<|body_0|>
def create(self, request, project=None, action=None, attatchment=None, **kwargs):
"""新建项目日志 content: {date: '', content: ''}"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008274 | 29,085 | no_license | [
{
"docstring": "获取项目日志,如签证,工作日志,审核日志等",
"name": "list",
"signature": "def list(self, request, project=None, action=None, **kwargs)"
},
{
"docstring": "新建项目日志 content: {date: '', content: ''}",
"name": "create",
"signature": "def create(self, request, project=None, action=None, attatchmen... | 2 | stack_v2_sparse_classes_30k_train_011069 | Implement the Python class `ProjectLogViewSet` described below.
Class description:
Implement the ProjectLogViewSet class.
Method signatures and docstrings:
- def list(self, request, project=None, action=None, **kwargs): 获取项目日志,如签证,工作日志,审核日志等
- def create(self, request, project=None, action=None, attatchment=None, **k... | Implement the Python class `ProjectLogViewSet` described below.
Class description:
Implement the ProjectLogViewSet class.
Method signatures and docstrings:
- def list(self, request, project=None, action=None, **kwargs): 获取项目日志,如签证,工作日志,审核日志等
- def create(self, request, project=None, action=None, attatchment=None, **k... | f5fe197a3624dd993e6f4cf8de547d1f45f40681 | <|skeleton|>
class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
<|body_0|>
def create(self, request, project=None, action=None, attatchment=None, **kwargs):
"""新建项目日志 content: {date: '', content: ''}"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
query = dict()
project and query.update(project=project)
action and query.update(action=action)
obj = ProjectLog.objects.filter(**query).order_by('-updated')
... | the_stack_v2_python_sparse | ssrd/users/views.py | BronzeKing/ssrd | train | 1 | |
309c36b977b42e29b343503272e9ba1351df1aa2 | [
"res = ''\nwhile True:\n receive = (yield res)\n if 'hi' in receive or 'hello' in receive:\n res = 'nihao'\n elif 'name' in receive:\n res = 'yangtuo'\n elif 'age' in receive:\n res = '1'\n elif 'hobby' in receive:\n res = 'dayouxi'\n elif 'country' in receive:\n ... | <|body_start_0|>
res = ''
while True:
receive = (yield res)
if 'hi' in receive or 'hello' in receive:
res = 'nihao'
elif 'name' in receive:
res = 'yangtuo'
elif 'age' in receive:
res = '1'
elif 'h... | small_robot_chat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class small_robot_chat:
def chat_robot(self):
"""生成器 高级用法 类似于一个协程函数 :return:"""
<|body_0|>
def window_chat(self):
"""前台不断的获取用户的输入,然后利用协程发送给后台处理 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ''
while True:
receive = (yi... | stack_v2_sparse_classes_75kplus_train_008275 | 2,903 | no_license | [
{
"docstring": "生成器 高级用法 类似于一个协程函数 :return:",
"name": "chat_robot",
"signature": "def chat_robot(self)"
},
{
"docstring": "前台不断的获取用户的输入,然后利用协程发送给后台处理 :return:",
"name": "window_chat",
"signature": "def window_chat(self)"
}
] | 2 | null | Implement the Python class `small_robot_chat` described below.
Class description:
Implement the small_robot_chat class.
Method signatures and docstrings:
- def chat_robot(self): 生成器 高级用法 类似于一个协程函数 :return:
- def window_chat(self): 前台不断的获取用户的输入,然后利用协程发送给后台处理 :return: | Implement the Python class `small_robot_chat` described below.
Class description:
Implement the small_robot_chat class.
Method signatures and docstrings:
- def chat_robot(self): 生成器 高级用法 类似于一个协程函数 :return:
- def window_chat(self): 前台不断的获取用户的输入,然后利用协程发送给后台处理 :return:
<|skeleton|>
class small_robot_chat:
def chat... | 25986e44b65228dd0f5ccdee6bedb0fcd93e5b7c | <|skeleton|>
class small_robot_chat:
def chat_robot(self):
"""生成器 高级用法 类似于一个协程函数 :return:"""
<|body_0|>
def window_chat(self):
"""前台不断的获取用户的输入,然后利用协程发送给后台处理 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class small_robot_chat:
def chat_robot(self):
"""生成器 高级用法 类似于一个协程函数 :return:"""
res = ''
while True:
receive = (yield res)
if 'hi' in receive or 'hello' in receive:
res = 'nihao'
elif 'name' in receive:
res = 'yangtuo'
... | the_stack_v2_python_sparse | 每天100行/testcase/t3.py | Nightwish555/Weekly---practice | train | 3 | |
ce24a91ca8b71e0eb47145a13fcb9a5e8b16dc81 | [
"if digits == '':\n return []\nself.letters = dict()\nself.letters['2'] = ['a', 'b', 'c']\nself.letters['3'] = ['d', 'e', 'f']\nself.letters['4'] = ['g', 'h', 'i']\nself.letters['5'] = ['j', 'k', 'l']\nself.letters['6'] = ['m', 'n', 'o']\nself.letters['7'] = ['p', 'q', 'r', 's']\nself.letters['8'] = ['t', 'u', '... | <|body_start_0|>
if digits == '':
return []
self.letters = dict()
self.letters['2'] = ['a', 'b', 'c']
self.letters['3'] = ['d', 'e', 'f']
self.letters['4'] = ['g', 'h', 'i']
self.letters['5'] = ['j', 'k', 'l']
self.letters['6'] = ['m', 'n', 'o']
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def _letterCombinations(self, curr_str, digits):
"""Helper method to compute letter combinations of a digit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008276 | 1,142 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": "Helper method to compute letter combinations of a digit",
"name": "_letterCombinations",
"signature": "def _letterCombinations(self, ... | 2 | stack_v2_sparse_classes_30k_train_006349 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def _letterCombinations(self, curr_str, digits): Helper method to compute letter combinations of a dig... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def _letterCombinations(self, curr_str, digits): Helper method to compute letter combinations of a dig... | 43dbcc129de3092d1ef24b95eaf35e20363cbd93 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def _letterCombinations(self, curr_str, digits):
"""Helper method to compute letter combinations of a digit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
if digits == '':
return []
self.letters = dict()
self.letters['2'] = ['a', 'b', 'c']
self.letters['3'] = ['d', 'e', 'f']
self.letters['4'] = ['g', 'h', 'i']
... | the_stack_v2_python_sparse | letter-combinations-of-a-phone-number.py | iyyuan/leetcode-practice | train | 0 | |
08d1b0e44208f0c21473c946d0234a16bb913445 | [
"self.setDomainRange(domain, range)\nself.nz = domain.getNdArray().shape[-1]\nif self.nz != range.getNdArray().shape[-1]:\n raise ValueError('Number of element of the image spaces must be the same (z samples: offset %s, angle %s )' % (self.nz, range.getNdArray().shape[-1]))\nself.ng = domain.getNdArray().shape[0... | <|body_start_0|>
self.setDomainRange(domain, range)
self.nz = domain.getNdArray().shape[-1]
if self.nz != range.getNdArray().shape[-1]:
raise ValueError('Number of element of the image spaces must be the same (z samples: offset %s, angle %s )' % (self.nz, range.getNdArray().shape[-1]... | Operator class to transform ADCIGs to ODCIGs and vice versa | off2ang2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class off2ang2D:
"""Operator class to transform ADCIGs to ODCIGs and vice versa"""
def __init__(self, domain, range, oz, dz, oh, dh, og, dg, p_inv=True, anti_alias=True):
"""Operator to convert imagese from/to angles to/from subsurface offsets :param domain: vector class, Vector defining t... | stack_v2_sparse_classes_75kplus_train_008277 | 4,469 | no_license | [
{
"docstring": "Operator to convert imagese from/to angles to/from subsurface offsets :param domain: vector class, Vector defining the size of the angle-domain image (z,x,gamma) :param range: vector class, Vector defining the size of the subsurface-offset-domain image (z,x,h) :param oz: int, Origin of the z axi... | 3 | null | Implement the Python class `off2ang2D` described below.
Class description:
Operator class to transform ADCIGs to ODCIGs and vice versa
Method signatures and docstrings:
- def __init__(self, domain, range, oz, dz, oh, dh, og, dg, p_inv=True, anti_alias=True): Operator to convert imagese from/to angles to/from subsurfa... | Implement the Python class `off2ang2D` described below.
Class description:
Operator class to transform ADCIGs to ODCIGs and vice versa
Method signatures and docstrings:
- def __init__(self, domain, range, oz, dz, oh, dh, og, dg, p_inv=True, anti_alias=True): Operator to convert imagese from/to angles to/from subsurfa... | a1aa5c595c7829a2405d54ffb4a3190d5e75f8fc | <|skeleton|>
class off2ang2D:
"""Operator class to transform ADCIGs to ODCIGs and vice versa"""
def __init__(self, domain, range, oz, dz, oh, dh, og, dg, p_inv=True, anti_alias=True):
"""Operator to convert imagese from/to angles to/from subsurface offsets :param domain: vector class, Vector defining t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class off2ang2D:
"""Operator class to transform ADCIGs to ODCIGs and vice versa"""
def __init__(self, domain, range, oz, dz, oh, dh, og, dg, p_inv=True, anti_alias=True):
"""Operator to convert imagese from/to angles to/from subsurface offsets :param domain: vector class, Vector defining the size of th... | the_stack_v2_python_sparse | acoustic_iso_lib/seis_utils/seis_utils_float/python/off2angModule.py | kristiantorres/acoustic_isotropic_operators | train | 0 |
d4c0422c97195fb79950977c565e2ad2c56b54d7 | [
"size = len(prices)\nif size <= 0:\n return 0\nmemo = {}\n\ndef dp(start, k):\n if k == 0:\n return 0\n if start >= size:\n return 0\n if (start, k) in memo:\n return memo[start, k]\n minIdx = start\n maxPro = 0\n for i in range(start + 1, size):\n if prices[i] < pri... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
return 0
if (start, k) in memo:
return memo[start, k]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_75kplus_train_008278 | 5,547 | permissive | [
{
"docstring": "暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化",
"name": "maxProfit",
"signature": "def maxProfit(self, k: int, prices: List[int]) -> int"
},
{
"docstring": "动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + ... | 3 | stack_v2_sparse_classes_30k_train_043245 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
... | the_stack_v2_python_sparse | 123-best-time-to-buy-and-sell-stock-iii.py | yuenliou/leetcode | train | 0 | |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"assert isinstance(request, HttpRequest)\nqapp_id = request.GET.get('qapp_id', None)\nqapp = Qapp.objects.get(id=qapp_id)\nedit_message = ''\nif not check_can_edit(qapp, request.user):\n edit_message = 'You cannot edit this QAPP.'\nexisting_section_d = SectionD.objects.filter(qapp=qapp).first()\nif existing_sect... | <|body_start_0|>
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_id)
edit_message = ''
if not check_can_edit(qapp, request.user):
edit_message = 'You cannot edit this QAPP.'
existing_section_d ... | Class for processing QAPP Section D information. | SectionDView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionD form fil... | stack_v2_sparse_classes_75kplus_train_008279 | 36,787 | no_license | [
{
"docstring": "Return the index page for QAPP Section D.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process the post request with a SectionD form filled out.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001954 | Implement the Python class `SectionDView` described below.
Class description:
Class for processing QAPP Section D information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section D.
- def post(self, request, *args, **kwargs): Process the post request wit... | Implement the Python class `SectionDView` described below.
Class description:
Class for processing QAPP Section D information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section D.
- def post(self, request, *args, **kwargs): Process the post request wit... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionD form fil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SectionDView:
"""Class for processing QAPP Section D information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section D."""
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
d9644addbd1c00ba06e0811c3cfbfe174649afc7 | [
"xout = tf.py_function(compute_optical_flow, [xin], 'float32', name='OpticalFlow')\nxout = K.stop_gradient(xout)\nxout.set_shape([xin.shape[0], 66, 200, xin.shape[-1]])\nreturn xout",
"img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\nflow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)\nmag,... | <|body_start_0|>
xout = tf.py_function(compute_optical_flow, [xin], 'float32', name='OpticalFlow')
xout = K.stop_gradient(xout)
xout.set_shape([xin.shape[0], 66, 200, xin.shape[-1]])
return xout
<|end_body_0|>
<|body_start_1|>
img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
f... | Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer | OpticalFlowLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpticalFlowLayer:
"""Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer"""
def call(self, xin):
"""Tensorflow hook Args: xin (tensor): 2 image tensor Returns: optical_flow_vector : a tensor containing the results of... | stack_v2_sparse_classes_75kplus_train_008280 | 1,890 | no_license | [
{
"docstring": "Tensorflow hook Args: xin (tensor): 2 image tensor Returns: optical_flow_vector : a tensor containing the results of the optical flow computation",
"name": "call",
"signature": "def call(self, xin)"
},
{
"docstring": "Computes Farneback vector between two images Args: prevs (imag... | 3 | stack_v2_sparse_classes_30k_train_016668 | Implement the Python class `OpticalFlowLayer` described below.
Class description:
Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer
Method signatures and docstrings:
- def call(self, xin): Tensorflow hook Args: xin (tensor): 2 image tensor Returns:... | Implement the Python class `OpticalFlowLayer` described below.
Class description:
Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer
Method signatures and docstrings:
- def call(self, xin): Tensorflow hook Args: xin (tensor): 2 image tensor Returns:... | b872a827657a861abe187fe4170fabeef65439b0 | <|skeleton|>
class OpticalFlowLayer:
"""Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer"""
def call(self, xin):
"""Tensorflow hook Args: xin (tensor): 2 image tensor Returns: optical_flow_vector : a tensor containing the results of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpticalFlowLayer:
"""Extends keras Layer to support opencv Farneback Optical Flow Calculation Args: Layer (keras.Layer): Generic Keras Layer"""
def call(self, xin):
"""Tensorflow hook Args: xin (tensor): 2 image tensor Returns: optical_flow_vector : a tensor containing the results of the optical ... | the_stack_v2_python_sparse | models/OpticalFlowLayer.py | mech0ctopus/damNN-vslam | train | 8 |
027a15ae3706e9532903c9cac79dff5ab1804384 | [
"self.driver.find_element_by_class_name('login').click()\nlogger.info('点击登录按钮')\nsleep(1)\nself.driver.find_element_by_xpath('//*[@id=\"app\"]/div[1]/div[1]/div/div[2]/div[1]/input').send_keys('18273675403')\nlogger.info('输入手机号码')\nsleep(1)\nself.driver.find_element_by_xpath('//*[@id=\"app\"]/div[1]/div[1]/div/div[... | <|body_start_0|>
self.driver.find_element_by_class_name('login').click()
logger.info('点击登录按钮')
sleep(1)
self.driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/div/div[2]/div[1]/input').send_keys('18273675403')
logger.info('输入手机号码')
sleep(1)
self.driver.fi... | Test_MobileLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_MobileLogin:
def test_case01(self):
"""官网移动直客登录 :return:"""
<|body_0|>
def test_case02(self):
"""官网移动合作商登录 :return:"""
<|body_1|>
def test_case03(self):
"""官网移动直客注册 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_75kplus_train_008281 | 6,690 | no_license | [
{
"docstring": "官网移动直客登录 :return:",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "官网移动合作商登录 :return:",
"name": "test_case02",
"signature": "def test_case02(self)"
},
{
"docstring": "官网移动直客注册 :return:",
"name": "test_case03",
"signature": "... | 3 | null | Implement the Python class `Test_MobileLogin` described below.
Class description:
Implement the Test_MobileLogin class.
Method signatures and docstrings:
- def test_case01(self): 官网移动直客登录 :return:
- def test_case02(self): 官网移动合作商登录 :return:
- def test_case03(self): 官网移动直客注册 :return: | Implement the Python class `Test_MobileLogin` described below.
Class description:
Implement the Test_MobileLogin class.
Method signatures and docstrings:
- def test_case01(self): 官网移动直客登录 :return:
- def test_case02(self): 官网移动合作商登录 :return:
- def test_case03(self): 官网移动直客注册 :return:
<|skeleton|>
class Test_MobileLog... | cf92e8e81ceb5cb67217bf36993cf94fe470fd0b | <|skeleton|>
class Test_MobileLogin:
def test_case01(self):
"""官网移动直客登录 :return:"""
<|body_0|>
def test_case02(self):
"""官网移动合作商登录 :return:"""
<|body_1|>
def test_case03(self):
"""官网移动直客注册 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_MobileLogin:
def test_case01(self):
"""官网移动直客登录 :return:"""
self.driver.find_element_by_class_name('login').click()
logger.info('点击登录按钮')
sleep(1)
self.driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/div/div[2]/div[1]/input').send_keys('18273675403')
... | the_stack_v2_python_sparse | hhr/case/mobile_qiantai/test_mobilelogin.py | aixin2000/Test_Scripts | train | 0 | |
257d8817325a6df6a6b526dd638213b5c4ea7b64 | [
"if file_dir is not None:\n if not os.path.exists(file_dir):\n if verbose:\n print('File directory specified not found. trying to create a new one.')\n os.system(f'touch {file_dir}')\nself.file_dir = file_dir\nself.verbose = verbose",
"assert isinstance(param, dict), 'Param argument sh... | <|body_start_0|>
if file_dir is not None:
if not os.path.exists(file_dir):
if verbose:
print('File directory specified not found. trying to create a new one.')
os.system(f'touch {file_dir}')
self.file_dir = file_dir
self.verbose = v... | This is a file writer for neural net configuration This writer saves given model parameter file to disk. | ParamWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamWriter:
"""This is a file writer for neural net configuration This writer saves given model parameter file to disk."""
def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None:
"""Initialization method."""
<|body_0|>
def write(self, param: Di... | stack_v2_sparse_classes_75kplus_train_008282 | 3,063 | permissive | [
{
"docstring": "Initialization method.",
"name": "__init__",
"signature": "def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None"
},
{
"docstring": "Write config parameter to json file.",
"name": "write",
"signature": "def write(self, param: Dict[str, object], ... | 3 | stack_v2_sparse_classes_30k_train_017280 | Implement the Python class `ParamWriter` described below.
Class description:
This is a file writer for neural net configuration This writer saves given model parameter file to disk.
Method signatures and docstrings:
- def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None: Initialization met... | Implement the Python class `ParamWriter` described below.
Class description:
This is a file writer for neural net configuration This writer saves given model parameter file to disk.
Method signatures and docstrings:
- def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None: Initialization met... | 648bb05498f333811021c07b04000d5f81ddc7f8 | <|skeleton|>
class ParamWriter:
"""This is a file writer for neural net configuration This writer saves given model parameter file to disk."""
def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None:
"""Initialization method."""
<|body_0|>
def write(self, param: Di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParamWriter:
"""This is a file writer for neural net configuration This writer saves given model parameter file to disk."""
def __init__(self, file_dir: Union[str, None]=None, verbose: bool=False) -> None:
"""Initialization method."""
if file_dir is not None:
if not os.path.ex... | the_stack_v2_python_sparse | core/tools/json_rec.py | TianyuDu/AnnEconForecast | train | 7 |
48cd774e133b620203e7c99677bdeb5ceac7cddf | [
"from nestedworld_api.db import MonsterAttack as DbMonsterAttack\nmonster = DbMonsterAttack.query.filter(DbMonsterAttack.monster_id == monster_id, DbMonsterAttack.id == attack_id).first()\nreturn monster",
"from nestedworld_api.db import db\nfrom nestedworld_api.db import MonsterAttack as DbMonsterAttack\nDbMonst... | <|body_start_0|>
from nestedworld_api.db import MonsterAttack as DbMonsterAttack
monster = DbMonsterAttack.query.filter(DbMonsterAttack.monster_id == monster_id, DbMonsterAttack.id == attack_id).first()
return monster
<|end_body_0|>
<|body_start_1|>
from nestedworld_api.db import db
... | MonsterAttack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonsterAttack:
def get(self, monster_id, attack_id):
"""Retrieve a specific monster of the user This request is used by a user for retrieve his own monster."""
<|body_0|>
def delete(self, monster_id, attack_id):
"""Delete an attack to a monster This request is used f... | stack_v2_sparse_classes_75kplus_train_008283 | 3,837 | no_license | [
{
"docstring": "Retrieve a specific monster of the user This request is used by a user for retrieve his own monster.",
"name": "get",
"signature": "def get(self, monster_id, attack_id)"
},
{
"docstring": "Delete an attack to a monster This request is used for delete an existing link between an a... | 2 | stack_v2_sparse_classes_30k_train_014776 | Implement the Python class `MonsterAttack` described below.
Class description:
Implement the MonsterAttack class.
Method signatures and docstrings:
- def get(self, monster_id, attack_id): Retrieve a specific monster of the user This request is used by a user for retrieve his own monster.
- def delete(self, monster_id... | Implement the Python class `MonsterAttack` described below.
Class description:
Implement the MonsterAttack class.
Method signatures and docstrings:
- def get(self, monster_id, attack_id): Retrieve a specific monster of the user This request is used by a user for retrieve his own monster.
- def delete(self, monster_id... | af2262742b04c823d2cf6e0fa40fa0fc6456671e | <|skeleton|>
class MonsterAttack:
def get(self, monster_id, attack_id):
"""Retrieve a specific monster of the user This request is used by a user for retrieve his own monster."""
<|body_0|>
def delete(self, monster_id, attack_id):
"""Delete an attack to a monster This request is used f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonsterAttack:
def get(self, monster_id, attack_id):
"""Retrieve a specific monster of the user This request is used by a user for retrieve his own monster."""
from nestedworld_api.db import MonsterAttack as DbMonsterAttack
monster = DbMonsterAttack.query.filter(DbMonsterAttack.monster... | the_stack_v2_python_sparse | nestedworld_api/views/api/v1/monster/attacks.py | NestedWorld/NestedWorld-Server-API | train | 1 | |
43bce7e4329a5f913304236abb4ff71f3e32de8b | [
"super(PositionalEncoding, self).__init__()\nposition_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])\nposition_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])\nposition_encoding[:, 1::2] = np.cos(position_encoding[:, 1::2])\npad_... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])
position_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])
position_encoding[:, 1::2] =... | PositionalEncoding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus_train_008284 | 9,090 | permissive | [
{
"docstring": "初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度",
"name": "__init__",
"signature": "def __init__(self, d_model, max_seq_len)"
},
{
"docstring": "神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回这一批序列的位置编码,进行了对齐。",
"nam... | 2 | stack_v2_sparse_classes_30k_test_002298 | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | b5d0b340a7042c1010a5f769b9091687bd70d0a2 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for... | the_stack_v2_python_sparse | Backend/Secondary Structure Prediction/ModelV1/Full_Transformer.py | Lizz647/SJTU-Software | train | 2 | |
571307be1e1d20222afe3cbe4527af5fcb38f445 | [
"try:\n return Member.objects.get(pk=pk)\nexcept Member.DoesNotExist:\n raise Http404",
"if pk is not None:\n member = self.get_member(int(pk))\nelse:\n member = None\nself.check_object_permissions(request, member)\nsecurity = SecuritySavings.get_members_securities(member=member)\nserializer = Securit... | <|body_start_0|>
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if pk is not None:
member = self.get_member(int(pk))
else:
member = None
self.check_object_permissions... | LoanSecuritySavingsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer"""
<|body_1|>
def post(self, requ... | stack_v2_sparse_classes_75kplus_train_008285 | 13,511 | no_license | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, pk)"
},
{
"docstring": "List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_018794 | Implement the Python class `LoanSecuritySavingsView` described below.
Class description:
Implement the LoanSecuritySavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of savings --- serializer: loans.serializ... | Implement the Python class `LoanSecuritySavingsView` described below.
Class description:
Implement the LoanSecuritySavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of savings --- serializer: loans.serializ... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer"""
<|body_1|>
def post(self, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loa... | the_stack_v2_python_sparse | loans/views.py | lubegamark/gosacco | train | 2 | |
69c61670c91bf5714be11c990282ae2e3581ac0c | [
"if not s:\n return ''\nres = s\ns = '#' + '#'.join(list(s)) + '#'\nlength = len(s)\nmid = length // 2\nfor i in range(mid, -1, -1):\n left = i - 1\n right = i + 1\n flag = True\n while left >= 0 and right < length and flag:\n if s[left] != s[right]:\n flag = False\n left -= ... | <|body_start_0|>
if not s:
return ''
res = s
s = '#' + '#'.join(list(s)) + '#'
length = len(s)
mid = length // 2
for i in range(mid, -1, -1):
left = i - 1
right = i + 1
flag = True
while left >= 0 and right < len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestPalindrome(self, s: str) -> str:
"""超时解法"""
<|body_0|>
def shortestPalindrom1e(self, s: str) -> str:
"""kmp 永远滴神"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return ''
res = s
s = '#' + ... | stack_v2_sparse_classes_75kplus_train_008286 | 1,709 | no_license | [
{
"docstring": "超时解法",
"name": "shortestPalindrome",
"signature": "def shortestPalindrome(self, s: str) -> str"
},
{
"docstring": "kmp 永远滴神",
"name": "shortestPalindrom1e",
"signature": "def shortestPalindrom1e(self, s: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_014217 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPalindrome(self, s: str) -> str: 超时解法
- def shortestPalindrom1e(self, s: str) -> str: kmp 永远滴神 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestPalindrome(self, s: str) -> str: 超时解法
- def shortestPalindrom1e(self, s: str) -> str: kmp 永远滴神
<|skeleton|>
class Solution:
def shortestPalindrome(self, s: str)... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def shortestPalindrome(self, s: str) -> str:
"""超时解法"""
<|body_0|>
def shortestPalindrom1e(self, s: str) -> str:
"""kmp 永远滴神"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def shortestPalindrome(self, s: str) -> str:
"""超时解法"""
if not s:
return ''
res = s
s = '#' + '#'.join(list(s)) + '#'
length = len(s)
mid = length // 2
for i in range(mid, -1, -1):
left = i - 1
right = i + 1
... | the_stack_v2_python_sparse | 二刷+题解/每日一题/shortestPalindrome.py | 1oser5/LeetCode | train | 0 | |
88aed54edc0b139701b0940f0d2a45156f248298 | [
"try:\n article = Article.objects.get(slug=slug)\nexcept Article.DoesNotExist:\n raise NotFound('article does not exist')\nif article.author != request.user:\n FavouriteArticle.objects.get_or_create(article=article, user=request.user)\n return Response({'slug': article.slug, 'favourited': True})\nelse:\... | <|body_start_0|>
try:
article = Article.objects.get(slug=slug)
except Article.DoesNotExist:
raise NotFound('article does not exist')
if article.author != request.user:
FavouriteArticle.objects.get_or_create(article=article, user=request.user)
retur... | define method to favourite article | FavouriteArticleApiView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavouriteArticleApiView:
"""define method to favourite article"""
def post(self, request, slug):
"""a registered user can favourite an article"""
<|body_0|>
def delete(self, request, slug):
"""a registered user can favourite an article"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_008287 | 34,279 | permissive | [
{
"docstring": "a registered user can favourite an article",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "a registered user can favourite an article",
"name": "delete",
"signature": "def delete(self, request, slug)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029440 | Implement the Python class `FavouriteArticleApiView` described below.
Class description:
define method to favourite article
Method signatures and docstrings:
- def post(self, request, slug): a registered user can favourite an article
- def delete(self, request, slug): a registered user can favourite an article | Implement the Python class `FavouriteArticleApiView` described below.
Class description:
define method to favourite article
Method signatures and docstrings:
- def post(self, request, slug): a registered user can favourite an article
- def delete(self, request, slug): a registered user can favourite an article
<|ske... | 20993253c2fb72608f21e2a19e999fbd85db904d | <|skeleton|>
class FavouriteArticleApiView:
"""define method to favourite article"""
def post(self, request, slug):
"""a registered user can favourite an article"""
<|body_0|>
def delete(self, request, slug):
"""a registered user can favourite an article"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavouriteArticleApiView:
"""define method to favourite article"""
def post(self, request, slug):
"""a registered user can favourite an article"""
try:
article = Article.objects.get(slug=slug)
except Article.DoesNotExist:
raise NotFound('article does not exi... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-code-blooded | train | 3 |
8702a664fee7703c48db3aef5d829cd76fe8286f | [
"settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Lash', self, '')\nself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://www.bits... | <|body_start_0|>
settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Lash', self, '')
self.openWikiManualHelpPage = settings.HelpPage().ge... | A class to handle the lash settings. | LashRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Lash button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_008288 | 6,957 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Lash button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023243 | Implement the Python class `LashRepository` described below.
Class description:
A class to handle the lash settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Lash button has been clicked. | Implement the Python class `LashRepository` described below.
Class description:
A class to handle the lash settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Lash button has been clicked.
<|skeleton|>
class LashRepositor... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Lash button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)
self.fileNameInput = settings.FileNameInput().getFr... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/lash.py | bmander/skeinforge | train | 34 |
6d0c6787512ab67073c125a994031ad5987d3918 | [
"self._args = args\nrecorder_str = self._get_recorder(self._args.log)\ncriteria_dict = self._get_criteria(self._args.criteria)\nmap_name = self._get_recorder_map(recorder_str)\nworld = self._client.load_world(map_name)\ntown_map = world.get_map()\nlog = MetricsLog(recorder_str)\nmetric_class = self._get_metric_clas... | <|body_start_0|>
self._args = args
recorder_str = self._get_recorder(self._args.log)
criteria_dict = self._get_criteria(self._args.criteria)
map_name = self._get_recorder_map(recorder_str)
world = self._client.load_world(map_name)
town_map = world.get_map()
log = ... | Main class of the metrics module. Handles the parsing and execution of the metrics. | MetricsManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricsManager:
"""Main class of the metrics module. Handles the parsing and execution of the metrics."""
def __init__(self, args):
"""Initialization of the metrics manager. This creates the client, needed to parse the information from the recorder, extract the metrics class, and run... | stack_v2_sparse_classes_75kplus_train_008289 | 5,255 | permissive | [
{
"docstring": "Initialization of the metrics manager. This creates the client, needed to parse the information from the recorder, extract the metrics class, and runs it",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Parses the log argument into readable informa... | 5 | stack_v2_sparse_classes_30k_train_009623 | Implement the Python class `MetricsManager` described below.
Class description:
Main class of the metrics module. Handles the parsing and execution of the metrics.
Method signatures and docstrings:
- def __init__(self, args): Initialization of the metrics manager. This creates the client, needed to parse the informat... | Implement the Python class `MetricsManager` described below.
Class description:
Main class of the metrics module. Handles the parsing and execution of the metrics.
Method signatures and docstrings:
- def __init__(self, args): Initialization of the metrics manager. This creates the client, needed to parse the informat... | 7fe8bf9581c7df140947468c6d90d7217a299d1b | <|skeleton|>
class MetricsManager:
"""Main class of the metrics module. Handles the parsing and execution of the metrics."""
def __init__(self, args):
"""Initialization of the metrics manager. This creates the client, needed to parse the information from the recorder, extract the metrics class, and run... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetricsManager:
"""Main class of the metrics module. Handles the parsing and execution of the metrics."""
def __init__(self, args):
"""Initialization of the metrics manager. This creates the client, needed to parse the information from the recorder, extract the metrics class, and runs it"""
... | the_stack_v2_python_sparse | scenario_runner/metrics_manager.py | leotimus/WorldOnRails | train | 1 |
3fbb731f7d3dcdf519373ccc398ce25e7136dc4d | [
"self.junction_sim = junction_sim\nself.rm_duplicates = rm_duplicates\nself.correct = correct\nself.correct_by = correct_by\nself.tol = tol",
"if self.rm_duplicates and x1.junc == x2.junc:\n return 0.0\nif abs(x1.junction_length - x2.junction_length) > self.tol or len(x1.setV & x2.setV) < 1:\n return 0.0\ns... | <|body_start_0|>
self.junction_sim = junction_sim
self.rm_duplicates = rm_duplicates
self.correct = correct
self.correct_by = correct_by
self.tol = tol
<|end_body_0|>
<|body_start_1|>
if self.rm_duplicates and x1.junc == x2.junc:
return 0.0
if abs(x1.... | Container for computing distance between IgRecords. | IgSimilarity | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IgSimilarity:
"""Container for computing distance between IgRecords."""
def __init__(self, junction_sim, tol=3, rm_duplicates=False, correct=True, correct_by=None):
"""Calculate a similarity between two input immunoglobulins. Parameters ---------- tol : int, optional, default: 3 Tole... | stack_v2_sparse_classes_75kplus_train_008290 | 5,473 | permissive | [
{
"docstring": "Calculate a similarity between two input immunoglobulins. Parameters ---------- tol : int, optional, default: 3 Tolerance in the length of the sequences. Default is 3 (3 nucleotides form an amminoacid. If seq1 and seq2 represent amminoacidic sequences, use tol = 1). Returns ------- similarity : ... | 2 | null | Implement the Python class `IgSimilarity` described below.
Class description:
Container for computing distance between IgRecords.
Method signatures and docstrings:
- def __init__(self, junction_sim, tol=3, rm_duplicates=False, correct=True, correct_by=None): Calculate a similarity between two input immunoglobulins. P... | Implement the Python class `IgSimilarity` described below.
Class description:
Container for computing distance between IgRecords.
Method signatures and docstrings:
- def __init__(self, junction_sim, tol=3, rm_duplicates=False, correct=True, correct_by=None): Calculate a similarity between two input immunoglobulins. P... | a9320007387c4c94d84045044806099c3e2e09e6 | <|skeleton|>
class IgSimilarity:
"""Container for computing distance between IgRecords."""
def __init__(self, junction_sim, tol=3, rm_duplicates=False, correct=True, correct_by=None):
"""Calculate a similarity between two input immunoglobulins. Parameters ---------- tol : int, optional, default: 3 Tole... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IgSimilarity:
"""Container for computing distance between IgRecords."""
def __init__(self, junction_sim, tol=3, rm_duplicates=False, correct=True, correct_by=None):
"""Calculate a similarity between two input immunoglobulins. Parameters ---------- tol : int, optional, default: 3 Tolerance in the ... | the_stack_v2_python_sparse | icing/similarity_.py | vijaykarthik123/icing | train | 0 |
c0842e1f7964bb37d045041e7d17b4bb7c5a0373 | [
"super().__init__(config_entry, driver, info)\nproperty_key_name = self.info.primary_value.property_key_name\nself._attr_name = self.generate_name(alternate_value_name=self.info.primary_value.property_name, additional_info=[property_key_name] if property_key_name else None)",
"if not self.info.primary_value.metad... | <|body_start_0|>
super().__init__(config_entry, driver, info)
property_key_name = self.info.primary_value.property_key_name
self._attr_name = self.generate_name(alternate_value_name=self.info.primary_value.property_name, additional_info=[property_key_name] if property_key_name else None)
<|end_b... | Representation of a Z-Wave config parameter number. | ZWaveConfigParameterNumberEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
<|body_0|>
def extra_state_a... | stack_v2_sparse_classes_75kplus_train_008291 | 6,343 | permissive | [
{
"docstring": "Initialize a ZWaveConfigParameterNumber entity.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None"
},
{
"docstring": "Return extra state attributes for entity.",
"name": "extra_state_attributes"... | 2 | stack_v2_sparse_classes_30k_train_017981 | Implement the Python class `ZWaveConfigParameterNumberEntity` described below.
Class description:
Representation of a Z-Wave config parameter number.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveConfigParameterNu... | Implement the Python class `ZWaveConfigParameterNumberEntity` described below.
Class description:
Representation of a Z-Wave config parameter number.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveConfigParameterNu... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
<|body_0|>
def extra_state_a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZWaveConfigParameterNumberEntity:
"""Representation of a Z-Wave config parameter number."""
def __init__(self, config_entry: ConfigEntry, driver: Driver, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveConfigParameterNumber entity."""
super().__init__(config_entry, driver, info)
... | the_stack_v2_python_sparse | homeassistant/components/zwave_js/number.py | home-assistant/core | train | 35,501 |
8851b16101e5baac483bc3a25d13bee50f94693e | [
"super().__init__()\nself.p = patch_dim\nself.num_classes = num_classes\nself.n = subvol_dim // patch_dim\nself.tokens = self.n ** 3\nself.mid_token = self.tokens // 2\nself.token_dim = in_channels * self.p ** 3\nself.dim = dim\nself.project_patches = nn.Linear(self.token_dim, dim)\nself.emb_dropout = nn.Dropout(dr... | <|body_start_0|>
super().__init__()
self.p = patch_dim
self.num_classes = num_classes
self.n = subvol_dim // patch_dim
self.tokens = self.n ** 3
self.mid_token = self.tokens // 2
self.token_dim = in_channels * self.p ** 3
self.dim = dim
self.projec... | Transformer3dSeg | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer3dSeg:
def __init__(self, *, subvol_dim=24, patch_dim=8, num_classes=2, in_channels=3, dim=1024, blocks=7, heads=4, dim_linear_block=1024, dropout=0, transformer=None):
"""Replication/re-implementation based on the paper: Convolution-Free Medical Image Segmentation using Trans... | stack_v2_sparse_classes_75kplus_train_008292 | 3,914 | permissive | [
{
"docstring": "Replication/re-implementation based on the paper: Convolution-Free Medical Image Segmentation using Transformers Paper: https://arxiv.org/abs/2102.13645 The model accepts a sub-volume of subvol_dim X subvol_dim X subvol_dim, and return a cube segmentation of n = subvol_dim//patch_dim Args: subvo... | 2 | stack_v2_sparse_classes_30k_train_054383 | Implement the Python class `Transformer3dSeg` described below.
Class description:
Implement the Transformer3dSeg class.
Method signatures and docstrings:
- def __init__(self, *, subvol_dim=24, patch_dim=8, num_classes=2, in_channels=3, dim=1024, blocks=7, heads=4, dim_linear_block=1024, dropout=0, transformer=None): ... | Implement the Python class `Transformer3dSeg` described below.
Class description:
Implement the Transformer3dSeg class.
Method signatures and docstrings:
- def __init__(self, *, subvol_dim=24, patch_dim=8, num_classes=2, in_channels=3, dim=1024, blocks=7, heads=4, dim_linear_block=1024, dropout=0, transformer=None): ... | 25622d56490ccca60a62a492fe48743e874a3e16 | <|skeleton|>
class Transformer3dSeg:
def __init__(self, *, subvol_dim=24, patch_dim=8, num_classes=2, in_channels=3, dim=1024, blocks=7, heads=4, dim_linear_block=1024, dropout=0, transformer=None):
"""Replication/re-implementation based on the paper: Convolution-Free Medical Image Segmentation using Trans... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transformer3dSeg:
def __init__(self, *, subvol_dim=24, patch_dim=8, num_classes=2, in_channels=3, dim=1024, blocks=7, heads=4, dim_linear_block=1024, dropout=0, transformer=None):
"""Replication/re-implementation based on the paper: Convolution-Free Medical Image Segmentation using Transformers Paper:... | the_stack_v2_python_sparse | self_attention_cv/Transformer3Dsegmentation/tranf3Dseg.py | cumtChenLL/self-attention-cv | train | 1 | |
eeff29d9a3f876458d44544251839019f0fdfcff | [
"request.user = None\nheader = authentication.get_authorization_header(request).split()\nprefix = self.authentication_header_prefix.lower()\nif not header:\n message = 'Token is missing.'\n raise exceptions.AuthenticationFailed(message)\nif len(header) == 1 or len(header) > 2:\n message = 'Invalid Token, h... | <|body_start_0|>
request.user = None
header = authentication.get_authorization_header(request).split()
prefix = self.authentication_header_prefix.lower()
if not header:
message = 'Token is missing.'
raise exceptions.AuthenticationFailed(message)
if len(hea... | Authenticate requests by using tokens. | JWTAuthentication | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWTAuthentication:
"""Authenticate requests by using tokens."""
def authenticate(self, request):
"""Check for authorization header."""
<|body_0|>
def authenticate_credentials(self, request, token):
"""Identify a user using the token provided."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_008293 | 2,064 | permissive | [
{
"docstring": "Check for authorization header.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Identify a user using the token provided.",
"name": "authenticate_credentials",
"signature": "def authenticate_credentials(self, request, token)"
... | 2 | null | Implement the Python class `JWTAuthentication` described below.
Class description:
Authenticate requests by using tokens.
Method signatures and docstrings:
- def authenticate(self, request): Check for authorization header.
- def authenticate_credentials(self, request, token): Identify a user using the token provided. | Implement the Python class `JWTAuthentication` described below.
Class description:
Authenticate requests by using tokens.
Method signatures and docstrings:
- def authenticate(self, request): Check for authorization header.
- def authenticate_credentials(self, request, token): Identify a user using the token provided.... | a9cf930934e8cbcb4ee370a088df57abe50ee6d6 | <|skeleton|>
class JWTAuthentication:
"""Authenticate requests by using tokens."""
def authenticate(self, request):
"""Check for authorization header."""
<|body_0|>
def authenticate_credentials(self, request, token):
"""Identify a user using the token provided."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JWTAuthentication:
"""Authenticate requests by using tokens."""
def authenticate(self, request):
"""Check for authorization header."""
request.user = None
header = authentication.get_authorization_header(request).split()
prefix = self.authentication_header_prefix.lower()
... | the_stack_v2_python_sparse | authors/apps/authentication/backends.py | andela/ah-backend-invictus | train | 2 |
62bc33ba740e2c96d5f6d5b8f1c41417bbf266cd | [
"self.find(By.ID, 'username').send_keys(username)\nself.find(By.ID, 'memberAdd_acctid').send_keys(account)\nself.find(By.ID, 'memberAdd_phone').send_keys(phonenum)\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()\nreturn True",
"locator = (By.CSS_SELECTOR, '.member_colRight_memberTable_th_Checkbox')\nself.wait... | <|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_SELECTOR, '.js_btn_save').click()
return True
<|end_body_0|>
<|body_start_1|>
... | AddMemberPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
... | stack_v2_sparse_classes_75kplus_train_008294 | 1,787 | no_license | [
{
"docstring": "添加联系人,详细信息 :return:",
"name": "add_member",
"signature": "def add_member(self, username, account, phonenum)"
},
{
"docstring": "获取所有的联系人姓名 :return:",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043666 | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有的联系人姓名 :return: | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有的联系人姓名 :return:
<|skeleton|>
class AddMemberPage:
def add_membe... | 7fcafbfed7b581c48a9effe9302661aa7250e1c4 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_... | the_stack_v2_python_sparse | live_selenium_po/seleniumPO/page/add_member_page.py | GaoPangPang0318/SDET_Study | train | 0 | |
7e5c75cca57193dceb1fad2f58015debc04dd8df | [
"for envname, envtree in self.envs.items():\n if not isinstance(envtree, SaltEnv):\n if isinstance(envtree, str):\n envtree = [envtree]\n self.envs[envname] = SaltEnv(name=envname, paths=envtree)\n setattr(self, envname, self.envs[envname])",
"config = {}\nfor env in self.envs.value... | <|body_start_0|>
for envname, envtree in self.envs.items():
if not isinstance(envtree, SaltEnv):
if isinstance(envtree, str):
envtree = [envtree]
self.envs[envname] = SaltEnv(name=envname, paths=envtree)
setattr(self, envname, self.envs... | This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.SaltEnv` or a list of strings(paths). I... | SaltEnvs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.Sal... | stack_v2_sparse_classes_75kplus_train_008295 | 14,449 | permissive | [
{
"docstring": "Post attrs initialization routines.",
"name": "__attrs_post_init__",
"signature": "def __attrs_post_init__(self)"
},
{
"docstring": "Returns a dictionary of the right types to update the salt configuration. :return dict:",
"name": "as_dict",
"signature": "def as_dict(self... | 2 | stack_v2_sparse_classes_30k_train_049831 | Implement the Python class `SaltEnvs` described below.
Class description:
This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:cl... | Implement the Python class `SaltEnvs` described below.
Class description:
This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:cl... | 7440e0923afabc9837537c3871dc7f16cf83a1de | <|skeleton|>
class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.Sal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaltEnvs:
"""This class serves as a container for multiple salt environments for states or pillar. :keyword dict envs: The `envs` dictionary should be a mapping of a string as key, the `saltenv`, commonly 'base' or 'prod', and the value an instance of :py:class:`~saltfactories.utils.tempfiles.SaltEnv` or a li... | the_stack_v2_python_sparse | src/saltfactories/utils/tempfiles.py | s0undt3ch/pytest-salt-factories | train | 0 |
ad70bde19d58ca6f727c6f70dcafeedb8b43b900 | [
"if scale_factor is None:\n scale_factor = -1\nctx.scale_factor = scale_factor\nctx.mode = mode\nctx.align_corners = align_corners\nctx.x_start = x_start\nctx.x_stop = x_stop\nctx.y_start = y_start\nctx.x_global_shape = x_global_shape\nctx.y_global_shape = y_global_shape\ny_shape = torch.as_tensor(y_stop) - torc... | <|body_start_0|>
if scale_factor is None:
scale_factor = -1
ctx.scale_factor = scale_factor
ctx.mode = mode
ctx.align_corners = align_corners
ctx.x_start = x_start
ctx.x_stop = x_stop
ctx.y_start = y_start
ctx.x_global_shape = x_global_shape
... | Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- This implementation currently requires that tensors have data stored in main memory (CP... | InterpolateFunction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolateFunction:
"""Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- This implementation currently requires t... | stack_v2_sparse_classes_75kplus_train_008296 | 4,808 | permissive | [
{
"docstring": "Forward function of interpolation layer. Currently, only `\"nearest\"` and `\"linear\"` are valid interpolation modes. Parameters ---------- ctx : PyTorch context. input : `torch.tensor` Input tensor. x_local_start : torch.Tensor Starting index (e.g., `start` in a Python slice) of the source sub... | 2 | null | Implement the Python class `InterpolateFunction` described below.
Class description:
Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- T... | Implement the Python class `InterpolateFunction` described below.
Class description:
Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- T... | a641638bf448cbad3e0a3ec09a1a0bcb7b7432c3 | <|skeleton|>
class InterpolateFunction:
"""Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- This implementation currently requires t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpolateFunction:
"""Functional implementation of a general interpolation layer. Implements the required `forward()` and adjoint (`backward()`) operations for piecewise constant (nearest-left neighbor) and piecewise linear interpolation. Warning ------- This implementation currently requires that tensors h... | the_stack_v2_python_sparse | src/distdl/functional/interpolate/interpolate.py | distdl/distdl | train | 25 |
a68d4c07a335bb1c4e1f55f32006464f6a6a3794 | [
"client = test_client.TestClient(context.node['baseurl'])\nwith pytest.raises(xml.parsers.expat.ExpatError):\n client.describe(context.TOKEN, '_invalid_pid_')",
"for object_list in context.slices:\n for object_info in object_list.objectInfo:\n client = test_client.TestClient(context.node['baseurl'])\... | <|body_start_0|>
client = test_client.TestClient(context.node['baseurl'])
with pytest.raises(xml.parsers.expat.ExpatError):
client.describe(context.TOKEN, '_invalid_pid_')
<|end_body_0|>
<|body_start_1|>
for object_list in context.slices:
for object_info in object_list.o... | Test060Describe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
<|body_0|>
def test_020_describe_by_valid_pid(self):
"""Successful describe for known objects. - Verify that required headers a... | stack_v2_sparse_classes_75kplus_train_008297 | 3,506 | permissive | [
{
"docstring": "404 NotFound when attempting to get description for non-existing object.",
"name": "test_010_describe_by_invalid_pid",
"signature": "def test_010_describe_by_invalid_pid(self)"
},
{
"docstring": "Successful describe for known objects. - Verify that required headers are present. -... | 2 | stack_v2_sparse_classes_30k_test_002153 | Implement the Python class `Test060Describe` described below.
Class description:
Implement the Test060Describe class.
Method signatures and docstrings:
- def test_010_describe_by_invalid_pid(self): 404 NotFound when attempting to get description for non-existing object.
- def test_020_describe_by_valid_pid(self): Suc... | Implement the Python class `Test060Describe` described below.
Class description:
Implement the Test060Describe class.
Method signatures and docstrings:
- def test_010_describe_by_invalid_pid(self): 404 NotFound when attempting to get description for non-existing object.
- def test_020_describe_by_valid_pid(self): Suc... | d72a9461894d9be7d71178fb7310101b8ef9066a | <|skeleton|>
class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
<|body_0|>
def test_020_describe_by_valid_pid(self):
"""Successful describe for known objects. - Verify that required headers a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test060Describe:
def test_010_describe_by_invalid_pid(self):
"""404 NotFound when attempting to get description for non-existing object."""
client = test_client.TestClient(context.node['baseurl'])
with pytest.raises(xml.parsers.expat.ExpatError):
client.describe(context.TOK... | the_stack_v2_python_sparse | test_utilities/src/d1_test/stress_tester/projects/_unit_test_bases_for_stress_tests/tier_1_mn_read_describe.py | DataONEorg/d1_python | train | 15 | |
06e9f4077f61656b975c39cb5c9ca4e53048f417 | [
"cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'\ncherrypy.response.headers['Content-Language'] = 'en'\ns = '<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=... | <|body_start_0|>
cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'
cherrypy.response.headers['Content-Language'] = 'en'
s = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html xmlns="http://www.w3.org/1999/xh... | Output a gallery of cover pages. | CoverPages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
<|body_0|>
def index(self, count, size, order, **kwargs):
"""Internal help function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_008298 | 3,091 | no_license | [
{
"docstring": "Output a gallery of coverpages.",
"name": "serve",
"signature": "def serve(rows, size)"
},
{
"docstring": "Internal help function.",
"name": "index",
"signature": "def index(self, count, size, order, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020053 | Implement the Python class `CoverPages` described below.
Class description:
Output a gallery of cover pages.
Method signatures and docstrings:
- def serve(rows, size): Output a gallery of coverpages.
- def index(self, count, size, order, **kwargs): Internal help function. | Implement the Python class `CoverPages` described below.
Class description:
Output a gallery of cover pages.
Method signatures and docstrings:
- def serve(rows, size): Output a gallery of coverpages.
- def index(self, count, size, order, **kwargs): Internal help function.
<|skeleton|>
class CoverPages:
"""Output... | 62ead004375ef24ac13f6bf80f48742cf0b40625 | <|skeleton|>
class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
<|body_0|>
def index(self, count, size, order, **kwargs):
"""Internal help function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoverPages:
"""Output a gallery of cover pages."""
def serve(rows, size):
"""Output a gallery of coverpages."""
cherrypy.response.headers['Content-Type'] = 'text/html; charset=utf-8'
cherrypy.response.headers['Content-Language'] = 'en'
s = '<!DOCTYPE html PUBLIC "-//W3C//D... | the_stack_v2_python_sparse | CoverPages.py | eshellman/autocat3_gutenberg1 | train | 1 |
a7bd68f593c7015d2231c31a28a2facd43e1703d | [
"i, p0, p2 = (0, 0, len(nums) - 1)\nwhile i <= p2:\n while nums[i] == 2 and i < p2:\n nums[p2], nums[i] = (nums[i], nums[p2])\n p2 -= 1\n if nums[i] == 0:\n nums[p0], nums[i] = (nums[i], nums[p0])\n p0 += 1\n i += 1",
"head = 0\nfor i in range(0, len(nums)):\n if nums[i] ==... | <|body_start_0|>
i, p0, p2 = (0, 0, len(nums) - 1)
while i <= p2:
while nums[i] == 2 and i < p2:
nums[p2], nums[i] = (nums[i], nums[p2])
p2 -= 1
if nums[i] == 0:
nums[p0], nums[i] = (nums[i], nums[p0])
p0 += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。"""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元... | stack_v2_sparse_classes_75kplus_train_008299 | 1,674 | no_license | [
{
"docstring": "75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
},
{
"docstring": "75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白... | 2 | stack_v2_sparse_classes_30k_train_053175 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: 75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
- def sortColors2(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: 75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
- def sortColors2(sel... | d74389704de4ce519a22061191b626b7204d4dbc | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。"""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。"""
i, p0, p2 = (0, 0, len(nums) - 1)
while i <= p2:
while nums[i] == 2 and i < p2:
nums[... | the_stack_v2_python_sparse | 05_doublepoint/middle_75_sortColors.py | MrLW/algorithm | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.