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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
09afa85effbf5260991f534ab2711b812b5069c7 | [
"timestamp = str(time.time())\npvt_key, pub_key = Signature.get_key_pair()\nsignature = bytes.hex(Signature.sign(pvt_key, transaction.__dict__.__str__()))\nmsg_id = Signature.gen_id_by_sig(signature)\nreturn Message(msg_id=msg_id, msg_type=msg_type, transaction=transaction.__dict__, timestamp=timestamp, pub_key=byt... | <|body_start_0|>
timestamp = str(time.time())
pvt_key, pub_key = Signature.get_key_pair()
signature = bytes.hex(Signature.sign(pvt_key, transaction.__dict__.__str__()))
msg_id = Signature.gen_id_by_sig(signature)
return Message(msg_id=msg_id, msg_type=msg_type, transaction=transa... | MessageService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageService:
def gen_msg(msg_type, transaction):
"""根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:"""
<|body_0|>
def verify_msg(msg):
"""判断 msg 的签名是否正确 :param msg: Message 对象 :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_007100 | 1,605 | permissive | [
{
"docstring": "根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:",
"name": "gen_msg",
"signature": "def gen_msg(msg_type, transaction)"
},
{
"docstring": "判断 msg 的签名是否正确 :param msg: Message 对象 :return:",
"name": "verify_msg",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_009772 | Implement the Python class `MessageService` described below.
Class description:
Implement the MessageService class.
Method signatures and docstrings:
- def gen_msg(msg_type, transaction): 根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:
- def verify_msg(msg): 判断 m... | Implement the Python class `MessageService` described below.
Class description:
Implement the MessageService class.
Method signatures and docstrings:
- def gen_msg(msg_type, transaction): 根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:
- def verify_msg(msg): 判断 m... | 84dfa1461e6d3de40bf78f8ad9079badef095f9e | <|skeleton|>
class MessageService:
def gen_msg(msg_type, transaction):
"""根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:"""
<|body_0|>
def verify_msg(msg):
"""判断 msg 的签名是否正确 :param msg: Message 对象 :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageService:
def gen_msg(msg_type, transaction):
"""根据 msg type 和 transaction 生成一个 Message 类对象 :param msg_type: :param transaction: Transaction对象 :return:"""
timestamp = str(time.time())
pvt_key, pub_key = Signature.get_key_pair()
signature = bytes.hex(Signature.sign(pvt_key... | the_stack_v2_python_sparse | BlockchainDjango/service/message_service.py | just2husky/BlockchainDjango | train | 0 | |
d0ce2bc5736c5f8411b67ae93ce4a8fd23e6fa53 | [
"super(OrderManager, self).__init__()\nself._logger = logging.getLogger(self.__class__.__name__)\nself._logger.info('Market OrderManager initialized')\nassert isinstance(order_repository, OrderRepository), type(order_repository)\nself.order_repository = order_repository",
"assert isinstance(price, Price), type(pr... | <|body_start_0|>
super(OrderManager, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self._logger.info('Market OrderManager initialized')
assert isinstance(order_repository, OrderRepository), type(order_repository)
self.order_repository = order_reposito... | Provides an interface to the user to manage the users orders | OrderManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderManager:
"""Provides an interface to the user to manage the users orders"""
def __init__(self, order_repository):
""":type order_repository: OrderRepository"""
<|body_0|>
def create_ask_order(self, price, quantity, timeout):
"""Create an ask order (sell orde... | stack_v2_sparse_classes_75kplus_train_007101 | 3,087 | no_license | [
{
"docstring": ":type order_repository: OrderRepository",
"name": "__init__",
"signature": "def __init__(self, order_repository)"
},
{
"docstring": "Create an ask order (sell order) :param price: The price for the order :param quantity: The quantity of the order :param timeout: The timeout of th... | 4 | stack_v2_sparse_classes_30k_train_011203 | Implement the Python class `OrderManager` described below.
Class description:
Provides an interface to the user to manage the users orders
Method signatures and docstrings:
- def __init__(self, order_repository): :type order_repository: OrderRepository
- def create_ask_order(self, price, quantity, timeout): Create an... | Implement the Python class `OrderManager` described below.
Class description:
Provides an interface to the user to manage the users orders
Method signatures and docstrings:
- def __init__(self, order_repository): :type order_repository: OrderRepository
- def create_ask_order(self, price, quantity, timeout): Create an... | cc4d1c27166d68c39e5c38e77bb70093f34e19e5 | <|skeleton|>
class OrderManager:
"""Provides an interface to the user to manage the users orders"""
def __init__(self, order_repository):
""":type order_repository: OrderRepository"""
<|body_0|>
def create_ask_order(self, price, quantity, timeout):
"""Create an ask order (sell orde... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderManager:
"""Provides an interface to the user to manage the users orders"""
def __init__(self, order_repository):
""":type order_repository: OrderRepository"""
super(OrderManager, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self._logger.... | the_stack_v2_python_sparse | market/core/order_manager.py | devos50/decentralized-market | train | 0 |
655fe4fedbffc943da80e401d70eddaec7c4778d | [
"self.input = input_data_obj\nself.config = configuration_obj\nself.objectOfCurves = None\nself.countsOfCurvesObj = None\nself.onlyPlentifulCurvesArray = None\nself.wellsWithWantedCurves = None",
"objectOfCurves = {}\nlas_folder_path = self.input.las_folder_path\nwell_format = self.input.well_format\npath = las_f... | <|body_start_0|>
self.input = input_data_obj
self.config = configuration_obj
self.objectOfCurves = None
self.countsOfCurvesObj = None
self.onlyPlentifulCurvesArray = None
self.wellsWithWantedCurves = None
<|end_body_0|>
<|body_start_1|>
objectOfCurves = {}
... | Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want. | CurvesAvailable | [
"MIT",
"CC-BY-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurvesAvailable:
"""Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want."""
def __init__(self, input_data_obj, configuration_obj):
"""doc string goes here"""
... | stack_v2_sparse_classes_75kplus_train_007102 | 21,685 | permissive | [
{
"docstring": "doc string goes here",
"name": "__init__",
"signature": "def __init__(self, input_data_obj, configuration_obj)"
},
{
"docstring": "say what it does here",
"name": "findAllCurvesInGivenWells",
"signature": "def findAllCurvesInGivenWells(self)"
},
{
"docstring": "sa... | 6 | null | Implement the Python class `CurvesAvailable` described below.
Class description:
Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want.
Method signatures and docstrings:
- def __init__(self, input_d... | Implement the Python class `CurvesAvailable` described below.
Class description:
Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want.
Method signatures and docstrings:
- def __init__(self, input_d... | 790ac612b0cf0f2044af9fdb0d3abe924fe094e4 | <|skeleton|>
class CurvesAvailable:
"""Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want."""
def __init__(self, input_data_obj, configuration_obj):
"""doc string goes here"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurvesAvailable:
"""Class that uses the configuration class and data_inpunt class objects and additional user input to find out the number of wells of those available that have the tops we want."""
def __init__(self, input_data_obj, configuration_obj):
"""doc string goes here"""
self.inpu... | the_stack_v2_python_sparse | predictatops/checkdata.py | JustinGOSSES/predictatops | train | 54 |
d98c725e783fb527f5633e7707160a04a149a09b | [
"tenant_id = get_jwt_claims()['tenant_id']\nlogger.info('Get method is called to retrieve all the alerts for the tenant {0}'.format(tenant_id))\nalert = self.alert_service.search({}, tenant_id)\nreturn results(status='success', message='Fetched Alert', data=alert, format_json=True)",
"criteria = request.get_json(... | <|body_start_0|>
tenant_id = get_jwt_claims()['tenant_id']
logger.info('Get method is called to retrieve all the alerts for the tenant {0}'.format(tenant_id))
alert = self.alert_service.search({}, tenant_id)
return results(status='success', message='Fetched Alert', data=alert, format_jso... | AlertController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertController:
def get(self):
"""This controller method is to retrieve all the alerts for the given tenant"""
<|body_0|>
def post(self):
"""This controller method is to retrieve all the alerts for the given tenant"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_007103 | 1,513 | no_license | [
{
"docstring": "This controller method is to retrieve all the alerts for the given tenant",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "This controller method is to retrieve all the alerts for the given tenant",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022383 | Implement the Python class `AlertController` described below.
Class description:
Implement the AlertController class.
Method signatures and docstrings:
- def get(self): This controller method is to retrieve all the alerts for the given tenant
- def post(self): This controller method is to retrieve all the alerts for ... | Implement the Python class `AlertController` described below.
Class description:
Implement the AlertController class.
Method signatures and docstrings:
- def get(self): This controller method is to retrieve all the alerts for the given tenant
- def post(self): This controller method is to retrieve all the alerts for ... | fe9cb286338dce008b1e78b66ff0b4f6a04ee94b | <|skeleton|>
class AlertController:
def get(self):
"""This controller method is to retrieve all the alerts for the given tenant"""
<|body_0|>
def post(self):
"""This controller method is to retrieve all the alerts for the given tenant"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlertController:
def get(self):
"""This controller method is to retrieve all the alerts for the given tenant"""
tenant_id = get_jwt_claims()['tenant_id']
logger.info('Get method is called to retrieve all the alerts for the tenant {0}'.format(tenant_id))
alert = self.alert_servi... | the_stack_v2_python_sparse | productmanagement/alert/controller/alertcontroller.py | rnama22/amzorbit | train | 0 | |
bfa466c23686fa68977400e011a6e42ccaacdf1a | [
"context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)\ncontext['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)\nreturn context",
"try:\n form.instance.escuela = escuela_m.Escuela.objects.get(codigo=form.cleaned_data['udi'])\nexcept ObjectDoesNotExist:\n ... | <|body_start_0|>
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)
return context
<|end_body_0|>
<|body_start_1|>
try:
form.instance.escuela = escuela_m.Escuela.o... | Vista para la creación de :class:`ProcesoNaat`. | ProcesoNaatCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_75kplus_train_007104 | 7,670 | no_license | [
{
"docstring": "Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Asigna al usuario actual como `capacitador` del objeto.",
"name": "form_valid",
"signature": "def form... | 2 | stack_v2_sparse_classes_30k_train_000829 | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | 0e37786d7173abe820fd10b094ffcc2db9593a9c | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_li... | the_stack_v2_python_sparse | src/apps/naat/views.py | jinchuika/app-suni | train | 7 |
68cc61b7bfec9ce2288297615dcae55bf1894c84 | [
"sympify(self.factor)\nif self.target.scale != self.scheme.target_scale:\n raise ValueError('Target operator not at same scale as scheme specifies.')\nif self.source.scale != self.scheme.source_scale:\n raise ValueError('Source operator not at same scale as scheme specifies.')",
"out = 1\nfor expansion in s... | <|body_start_0|>
sympify(self.factor)
if self.target.scale != self.scheme.target_scale:
raise ValueError('Target operator not at same scale as scheme specifies.')
if self.source.scale != self.scheme.source_scale:
raise ValueError('Source operator not at same scale as sche... | Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.) | OperatorRelation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_cons... | stack_v2_sparse_classes_75kplus_train_007105 | 6,555 | permissive | [
{
"docstring": "Runs consistency checks on operator relation. Checks: * factor can be converted to sympy expression * target scale equals scheme target scale * source scale equals scheme source scale * all expansion parameters defined by scheme are present",
"name": "check_consistency",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_033718 | Implement the Python class `OperatorRelation` described below.
Class description:
Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present... | Implement the Python class `OperatorRelation` described below.
Class description:
Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present... | 2131354fd6822b3aa7b7d9c3c0db79723b06b8ca | <|skeleton|>
class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_cons... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OperatorRelation:
"""Table storing information between different oprator representation bridging scales. For example, this quark operator maps to the following nucleon operators: ``source = Bar(q) * q -> target * factor`` at ``order`` (where order is present in the factor.)"""
def check_consistency(self)... | the_stack_v2_python_sparse | strops/schemes/models.py | ckoerber/strops | train | 1 |
2c0818f89d9e4e49bc7563f18b5ce8e14b6baa14 | [
"if form_class is None:\n form_class = self.get_form_class()\nreturn form_class(**self.get_form_kwargs(form_class, empty=empty))",
"kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()}\nif not empty and self.request.method in ('POST', 'PUT'):\n kwargs.update({'data': self.request.POST, 'fil... | <|body_start_0|>
if form_class is None:
form_class = self.get_form_class()
return form_class(**self.get_form_kwargs(form_class, empty=empty))
<|end_body_0|>
<|body_start_1|>
kwargs = {'initial': self.get_initial(), 'prefix': self.get_prefix()}
if not empty and self.request.m... | This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'form_fieldname_trigger' attributes. The firs... | MultiFormView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'for... | stack_v2_sparse_classes_75kplus_train_007106 | 5,377 | permissive | [
{
"docstring": "Returns an instance of the form to be used in this view. Modified to give the 'form_class' to 'get_form_kwargs' and accept 'empty' arg",
"name": "get_form",
"signature": "def get_form(self, form_class=None, empty=False)"
},
{
"docstring": "Returns the keyword arguments for instan... | 6 | stack_v2_sparse_classes_30k_train_046062 | Implement the Python class `MultiFormView` described below.
Class description:
This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms ... | Implement the Python class `MultiFormView` described below.
Class description:
This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms ... | 239326bbdad1e3ff58e7e9b503fbb7b75c8713f8 | <|skeleton|>
class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiFormView:
"""This is a huge rewrite and mixing of some CBV views and mixins to be able to distinctly manage multiple forms in the same view The view can implement some custom method for some forms that will be used during ProcessFormView process. Forms have to implement a 'form_key' and 'form_fieldname_t... | the_stack_v2_python_sparse | project/manager_frontend/utils/views.py | RetroPie/RetroPie-Manager | train | 67 |
d7fc76055ea694a97998d319dda719f8ecdc856b | [
"rows = len(matrix)\nif rows == 0:\n return False\ncols = len(matrix[0])\nif cols == 0:\n return False\nleft, right = (0, rows * cols - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n num = matrix[mid // cols][mid % cols]\n if num == target:\n return True\n elif num < target:\... | <|body_start_0|>
rows = len(matrix)
if rows == 0:
return False
cols = len(matrix[0])
if cols == 0:
return False
left, right = (0, rows * cols - 1)
while left <= right:
mid = left + (right - left) // 2
num = matrix[mid // col... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous row. :param matrix: List[List[int]] :param target: int :return: bool"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_007107 | 2,051 | no_license | [
{
"docstring": "1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous row. :param matrix: List[List[int]] :param target: int :return: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
... | 2 | stack_v2_sparse_classes_30k_train_007962 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): 1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): 1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous r... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
"""1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous row. :param matrix: List[List[int]] :param target: int :return: bool"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
"""1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous row. :param matrix: List[List[int]] :param target: int :return: bool"""
rows = len(matrix)
if ro... | the_stack_v2_python_sparse | python/bin-search/search-2D-matrix.py | euxuoh/leetcode | train | 0 | |
7223eacecb47885da2370922cbcb773f55363b59 | [
"if 'title' not in kwargs:\n kwargs['title'] = 'Member image'\nreturn self.getField('member_image').tag(self, **kwargs)",
"results = CONSTITUENCIES_LIST[master]\nresults = [(item, item) for item in results]\nreturn atapi.DisplayList(results)"
] | <|body_start_0|>
if 'title' not in kwargs:
kwargs['title'] = 'Member image'
return self.getField('member_image').tag(self, **kwargs)
<|end_body_0|>
<|body_start_1|>
results = CONSTITUENCIES_LIST[master]
results = [(item, item) for item in results]
return atapi.Displa... | Member Profile | MemberProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
<|body_0|>
def getConstituencyVocab(self, master):
"""Vocab method that returns a vocabulary consisting of the constituencies from the given coun... | stack_v2_sparse_classes_75kplus_train_007108 | 6,488 | no_license | [
{
"docstring": "Generate image tag using the api of the ImageField",
"name": "tag",
"signature": "def tag(self, **kwargs)"
},
{
"docstring": "Vocab method that returns a vocabulary consisting of the constituencies from the given county.",
"name": "getConstituencyVocab",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_033227 | Implement the Python class `MemberProfile` described below.
Class description:
Member Profile
Method signatures and docstrings:
- def tag(self, **kwargs): Generate image tag using the api of the ImageField
- def getConstituencyVocab(self, master): Vocab method that returns a vocabulary consisting of the constituencie... | Implement the Python class `MemberProfile` described below.
Class description:
Member Profile
Method signatures and docstrings:
- def tag(self, **kwargs): Generate image tag using the api of the ImageField
- def getConstituencyVocab(self, master): Vocab method that returns a vocabulary consisting of the constituencie... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
<|body_0|>
def getConstituencyVocab(self, master):
"""Vocab method that returns a vocabulary consisting of the constituencies from the given coun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
if 'title' not in kwargs:
kwargs['title'] = 'Member image'
return self.getField('member_image').tag(self, **kwargs)
def getConstituencyVocab(self,... | the_stack_v2_python_sparse | plone.products/bungenicms.membershipdirectory/trunk/bungenicms/membershipdirectory/content/memberprofile.py | malangalanga/bungeni-portal | train | 0 |
e47e6942143b121a50bd7380983f1439bca1fcea | [
"if numRows == 1 or numRows >= len(s):\n return s\ntmp, res, period = ([], [], numRows - 1)\nfor idx, ele in enumerate(s):\n tmp.append((ele, abs(idx % (2 * period) - period)))\nfor r in range(numRows)[::-1]:\n res.append(filter(lambda x: x[1] == r, tmp))\nreturn ''.join([item[0] for sublist in res for ite... | <|body_start_0|>
if numRows == 1 or numRows >= len(s):
return s
tmp, res, period = ([], [], numRows - 1)
for idx, ele in enumerate(s):
tmp.append((ele, abs(idx % (2 * period) - period)))
for r in range(numRows)[::-1]:
res.append(filter(lambda x: x[1] =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def import_efficiency(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if numRows ... | stack_v2_sparse_classes_75kplus_train_007109 | 1,252 | no_license | [
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "convert",
"signature": "def convert(self, s, numRows)"
},
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "import_efficiency",
"signature": "def import_efficiency(self, s, numRows)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047021 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def import_efficiency(self, s, numRows): :type s: str :type numRows: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def import_efficiency(self, s, numRows): :type s: str :type numRows: int :rtype: str
<|skeleton|>
cl... | bd003424f4d5720438f0b160f18543a12ed7f189 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def import_efficiency(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
if numRows == 1 or numRows >= len(s):
return s
tmp, res, period = ([], [], numRows - 1)
for idx, ele in enumerate(s):
tmp.append((ele, abs(idx % (2 * period) - per... | the_stack_v2_python_sparse | 6-zigzag-conversion/woodyhuang.py | huangy10/MyLeetCode | train | 0 | |
7497a71613116c038a2e3004612e178c77fd05c2 | [
"if not root:\n return '[]'\nres, node_list = ([], collections.deque([root]))\nwhile node_list:\n node = node_list.popleft()\n if node:\n res.append(str(node.val))\n node_list.append(node.left)\n node_list.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join... | <|body_start_0|>
if not root:
return '[]'
res, node_list = ([], collections.deque([root]))
while node_list:
node = node_list.popleft()
if node:
res.append(str(node.val))
node_list.append(node.left)
node_list.appe... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_007110 | 3,625 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_test_000272 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d00ca813e657cdd384a342983a1357561e246bac | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
res, node_list = ([], collections.deque([root]))
while node_list:
node = node_list.popleft()
if node:
... | the_stack_v2_python_sparse | JZ/JZ37-serialize-and-deserialize-binary-tree.py | GeekDream-x/LeecodeStory | train | 0 | |
59f59cd7eb4b35fc744f32446aa13862591a5c89 | [
"configuration = g.user.get_api().get_configuration(configuration)\nresult = configuration.to_json()\nreturn jsonify(result)",
"configuration = g.user.get_api().get_configuration(configuration)\nconfiguration.delete()\nreturn ('', 204)"
] | <|body_start_0|>
configuration = g.user.get_api().get_configuration(configuration)
result = configuration.to_json()
return jsonify(result)
<|end_body_0|>
<|body_start_1|>
configuration = g.user.get_api().get_configuration(configuration)
configuration.delete()
return ('',... | Configuration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
def get(self, configuration):
"""Get Configuration with specified name."""
<|body_0|>
def delete(self, configuration):
"""Delete Configuration with specified name."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
configuration = g.user... | stack_v2_sparse_classes_75kplus_train_007111 | 4,125 | permissive | [
{
"docstring": "Get Configuration with specified name.",
"name": "get",
"signature": "def get(self, configuration)"
},
{
"docstring": "Delete Configuration with specified name.",
"name": "delete",
"signature": "def delete(self, configuration)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008297 | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def get(self, configuration): Get Configuration with specified name.
- def delete(self, configuration): Delete Configuration with specified name. | Implement the Python class `Configuration` described below.
Class description:
Implement the Configuration class.
Method signatures and docstrings:
- def get(self, configuration): Get Configuration with specified name.
- def delete(self, configuration): Delete Configuration with specified name.
<|skeleton|>
class Co... | 60b36434e689c3ef852ab388ca2aae370e70c62d | <|skeleton|>
class Configuration:
def get(self, configuration):
"""Get Configuration with specified name."""
<|body_0|>
def delete(self, configuration):
"""Delete Configuration with specified name."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Configuration:
def get(self, configuration):
"""Get Configuration with specified name."""
configuration = g.user.get_api().get_configuration(configuration)
result = configuration.to_json()
return jsonify(result)
def delete(self, configuration):
"""Delete Configurat... | the_stack_v2_python_sparse | Community/rest_api/configuration_page.py | bluecatlabs/gateway-workflows | train | 45 | |
924d1c938bd0ba5912840f26fae6e74db2256bcd | [
"num_stack = []\nopear_stack = []\nopeard = {'+': add, '-': sub}\nlevel = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}\ni = n = 0\ns += '$'\nfor i, c in enumerate(s):\n if c == ' ':\n continue\n if c.isdigit():\n n = n * 10 + int(c)\n if not s[i + 1].isdigit():\n num_stack.append(n... | <|body_start_0|>
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerate(s):
if c == ' ':
continue
if c.isdigit():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_007112 | 3,812 | no_license | [
{
"docstring": "使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈",
"name": "calculate",
"signature": "def calculate(self, s: str) -> int"
},
{
"docstring": "双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈",
"name": "calculate",
"signature": "def calcula... | 2 | stack_v2_sparse_classes_30k_train_030326 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: 使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈
- def calculate(self, s: str) -> int: 双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇... | 092a800a15bdd0f3d0c8f521a5e0fc90f964e8a8 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
<|body_0|>
def calculate(self, s: str) -> int:
"""双栈的方法比较通用,因为只涉及加减法,可以把问题 简化,只需要将第一个操作数当做正数,然后后面就每次加上一个符号数。 遇到括号就把符号和操作数一起入栈,遇到右括号,再逐步出栈"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calculate(self, s: str) -> int:
"""使用双栈的方式,为了避免陷入判断的泥潭,需要每次运算完成后,不管什么情况,都把结果入栈"""
num_stack = []
opear_stack = []
opeard = {'+': add, '-': sub}
level = {')': 1, '+': 1, '-': 1, '(': 2, '$': 0}
i = n = 0
s += '$'
for i, c in enumerat... | the_stack_v2_python_sparse | leetcode/400/224. 基本计算器.py | August-us/exam | train | 1 | |
219c7aa63c2a983a891214099e3cff69455bccc9 | [
"super().__init__(name)\nself.database = database\nself.searchTags = searchTags\nself.database.add_sensor_observer(self)",
"if isinstance(keys, (slice, float, int)):\n keys = (keys,)\nreturn [copy.deepcopy(entry.data) for entry in self.database.find_entries(tags=self.searchTags, keys=keys)]",
"sampleTags = [... | <|body_start_0|>
super().__init__(name)
self.database = database
self.searchTags = searchTags
self.database.add_sensor_observer(self)
<|end_body_0|>
<|body_start_1|>
if isinstance(keys, (slice, float, int)):
keys = (keys,)
return [copy.deepcopy(entry.data) fo... | DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observation is done on the database. TODO Consider changing database output interface. ... | DatabaseView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseView:
"""DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observation is done on the database. TODO Consi... | stack_v2_sparse_classes_75kplus_train_007113 | 2,048 | permissive | [
{
"docstring": "Parameters: database : NephelaeDataServer database to which subscribing and from which data will be fetched on a __getitem__. searchTags : list(str, ...) tags to search data in the database.",
"name": "__init__",
"signature": "def __init__(self, name, database, searchTags)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_043725 | Implement the Python class `DatabaseView` described below.
Class description:
DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observat... | Implement the Python class `DatabaseView` described below.
Class description:
DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observat... | d5f1abeae0b0473b895b4735f182ddae0516a1bd | <|skeleton|>
class DatabaseView:
"""DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observation is done on the database. TODO Consi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseView:
"""DatabaseView Dataview without parents made to access a NephelaeDataServer (The NephelaeDataServer play the role of a parent (but is not in the self.parent list). /!\\ This can only be used to manage SensorSample, only the add_sample observation is done on the database. TODO Consider changing ... | the_stack_v2_python_sparse | nephelae/dataviews/types/DatabaseView.py | pnarvor/nephelae_base | train | 0 |
16958f9766fa7c89e9f20f8567ec030538d2398c | [
"self.chn = 0\nself.chn_items = []\nself.fs = -1\nself.fs_bands = {'delta': (1, 4), 'theta': (4, 8), 'alpha': (8, 14), 'beta': (14, 30), 'gamma': (30, 45)}",
"lp = self.fs_bands[band][0]\nhp = self.fs_bands[band][1]\nif l == 0 and h != 0:\n if self.fs_bands[band][0] < h < hp:\n hp = h\n elif h < hp:\... | <|body_start_0|>
self.chn = 0
self.chn_items = []
self.fs = -1
self.fs_bands = {'delta': (1, 4), 'theta': (4, 8), 'alpha': (8, 14), 'beta': (14, 30), 'gamma': (30, 45)}
<|end_body_0|>
<|body_start_1|>
lp = self.fs_bands[band][0]
hp = self.fs_bands[band][1]
if l =... | Class to hold relevant information for computing statistics | SignalStatsInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
<|body_0|>
def _get_power_for_band(self, sig, s, f, band, l, h):
"""Returns the power in the ... | stack_v2_sparse_classes_75kplus_train_007114 | 2,715 | no_license | [
{
"docstring": "Constructor. fs_bands - holds dict of bands, can be expanded",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the power in the given fs band. Args: sig: the signal to use s: where to start in samples f: where to end in samples band: which type of... | 3 | stack_v2_sparse_classes_30k_train_007508 | Implement the Python class `SignalStatsInfo` described below.
Class description:
Class to hold relevant information for computing statistics
Method signatures and docstrings:
- def __init__(self): Constructor. fs_bands - holds dict of bands, can be expanded
- def _get_power_for_band(self, sig, s, f, band, l, h): Retu... | Implement the Python class `SignalStatsInfo` described below.
Class description:
Class to hold relevant information for computing statistics
Method signatures and docstrings:
- def __init__(self): Constructor. fs_bands - holds dict of bands, can be expanded
- def _get_power_for_band(self, sig, s, f, band, l, h): Retu... | 099920716fdab891592ccc7f324445f088827298 | <|skeleton|>
class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
<|body_0|>
def _get_power_for_band(self, sig, s, f, band, l, h):
"""Returns the power in the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
self.chn = 0
self.chn_items = []
self.fs = -1
self.fs_bands = {'delta': (1, 4), 'theta': (4, 8)... | the_stack_v2_python_sparse | visualization/signalStats_info.py | jcraley/jhu-eeg | train | 2 |
03e4efd2d337ecf6a4e6418d1e51ff089c6d3a3c | [
"self._connected_callback = connected_callback\nself._update_callback = update_callback\nself._queries = {}\nsuper(Agent, self).__init__(wss, proxy)\nself.initialize()",
"if self._connected_callback:\n await asyncio.sleep(0.1)\n await self._connected_callback()",
"request_id = tools.get_uuid1()\ndata = {'... | <|body_start_0|>
self._connected_callback = connected_callback
self._update_callback = update_callback
self._queries = {}
super(Agent, self).__init__(wss, proxy)
self.initialize()
<|end_body_0|>
<|body_start_1|>
if self._connected_callback:
await asyncio.slee... | websocket长连接代理 | Agent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
"""websocket长连接代理"""
def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None):
"""初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callback websocket数据更新回调"""
<|body_0|>
async def co... | stack_v2_sparse_classes_75kplus_train_007115 | 2,133 | permissive | [
{
"docstring": "初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callback websocket数据更新回调",
"name": "__init__",
"signature": "def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None)"
},
{
"docstring": "websocket连接... | 4 | stack_v2_sparse_classes_30k_train_050572 | Implement the Python class `Agent` described below.
Class description:
websocket长连接代理
Method signatures and docstrings:
- def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None): 初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callbac... | Implement the Python class `Agent` described below.
Class description:
websocket长连接代理
Method signatures and docstrings:
- def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None): 初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callbac... | 52fb22f5df20d43cb275a08adad81dc97f25a712 | <|skeleton|>
class Agent:
"""websocket长连接代理"""
def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None):
"""初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callback websocket数据更新回调"""
<|body_0|>
async def co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Agent:
"""websocket长连接代理"""
def __init__(self, wss, proxy=None, connected_callback=None, update_callback=None):
"""初始化 @param wss websocket地址 @param proxy HTTP代理 @param connected_callback websocket连接建立成功回调 @param update_callback websocket数据更新回调"""
self._connected_callback = connected_call... | the_stack_v2_python_sparse | quant/utils/agent.py | cdpzyafk/thenextquant | train | 1 |
0341adbcc9667e041ccd24776d3d8b1a0d8eb714 | [
"super().__init__(**kwargs)\nself.alpha = alpha\nself.gamma = gamma\nself.label_smoothing = label_smoothing",
"normalizer, y_true = y\nalpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)\ngamma = tf.convert_to_tensor(self.gamma, dtype=y_pred.dtype)\npositive_label_mask = tf.equal(y_true, 1.0)\nnegative_p... | <|body_start_0|>
super().__init__(**kwargs)
self.alpha = alpha
self.gamma = gamma
self.label_smoothing = label_smoothing
<|end_body_0|>
<|body_start_1|>
normalizer, y_true = y
alpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)
gamma = tf.convert_to_tens... | Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r = gamma, and p_t = sigmod(x) for positive sa... | StableFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r =... | stack_v2_sparse_classes_75kplus_train_007116 | 17,443 | permissive | [
{
"docstring": "Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kw... | 2 | stack_v2_sparse_classes_30k_val_000835 | Implement the Python class `StableFocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For br... | Implement the Python class `StableFocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For br... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r =... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r = gamma, and p... | the_stack_v2_python_sparse | TensorFlow2/Detection/Efficientdet/utils/train_lib.py | NVIDIA/DeepLearningExamples | train | 11,838 |
f5b2ddc69ce7aa7685498782b475b70e9e286dc9 | [
"if action_space_type not in [ActionSpaceTypes.CONTINUOUS.value]:\n log_and_exit('Unsupported action space type passed while defining SACActionSpaceConfig. action_space_type: {}'.format(action_space_type), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_500)\nself.action_space_type = ... | <|body_start_0|>
if action_space_type not in [ActionSpaceTypes.CONTINUOUS.value]:
log_and_exit('Unsupported action space type passed while defining SACActionSpaceConfig. action_space_type: {}'.format(action_space_type), SIMAPP_SIMULATION_WORKER_EXCEPTION, SIMAPP_EVENT_ERROR_CODE_500)... | SACActionSpaceConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SACActionSpaceConfig:
def __init__(self, action_space_type):
"""SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify what action space object to return"""
<|body_0|>
def get_action_space(self, json_actions):
... | stack_v2_sparse_classes_75kplus_train_007117 | 8,765 | permissive | [
{
"docstring": "SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify what action space object to return",
"name": "__init__",
"signature": "def __init__(self, action_space_type)"
},
{
"docstring": "Return the action space for the tra... | 2 | stack_v2_sparse_classes_30k_train_018833 | Implement the Python class `SACActionSpaceConfig` described below.
Class description:
Implement the SACActionSpaceConfig class.
Method signatures and docstrings:
- def __init__(self, action_space_type): SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify... | Implement the Python class `SACActionSpaceConfig` described below.
Class description:
Implement the SACActionSpaceConfig class.
Method signatures and docstrings:
- def __init__(self, action_space_type): SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify... | 2ce50508dd4100eaef7f8729436549a801505705 | <|skeleton|>
class SACActionSpaceConfig:
def __init__(self, action_space_type):
"""SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify what action space object to return"""
<|body_0|>
def get_action_space(self, json_actions):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SACActionSpaceConfig:
def __init__(self, action_space_type):
"""SAC training algorithm action space configuration Args: action_space_type (str): action space type used to identify what action space object to return"""
if action_space_type not in [ActionSpaceTypes.CONTINUOUS.value]:
... | the_stack_v2_python_sparse | bundle/markov/multi_agent_coach/action_space_configs.py | aws-deepracer-community/deepracer-simapp | train | 83 | |
d669ac2f2757a9e51ccbc057e9e46499375445de | [
"super().__init__(fmc, **kwargs)\nlogging.debug('In __init__() for AdvancedSettings class.')\nself.parse_kwargs(**kwargs)\nself.type = 'AdvancedSettings'",
"logging.debug('In vpn_policy() for AdvancedSettings class.')\nftd_s2s = FTDS2SVPNs(fmc=self.fmc)\nftd_s2s.get(name=pol_name)\nif 'id' in ftd_s2s.__dict__:\n ... | <|body_start_0|>
super().__init__(fmc, **kwargs)
logging.debug('In __init__() for AdvancedSettings class.')
self.parse_kwargs(**kwargs)
self.type = 'AdvancedSettings'
<|end_body_0|>
<|body_start_1|>
logging.debug('In vpn_policy() for AdvancedSettings class.')
ftd_s2s = F... | The AdvancedSettings Object in the FMC. | AdvancedSettings | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvancedSettings:
"""The AdvancedSettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiation of AdvancedSettings object. :return: None"""
<... | stack_v2_sparse_classes_75kplus_train_007118 | 1,750 | permissive | [
{
"docstring": "Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiation of AdvancedSettings object. :return: None",
"name": "__init__",
"signature": "def __init__(self, fmc, **kwargs)"
},
{
"docstring": "Associate a Policy w... | 2 | stack_v2_sparse_classes_30k_train_046509 | Implement the Python class `AdvancedSettings` described below.
Class description:
The AdvancedSettings Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiati... | Implement the Python class `AdvancedSettings` described below.
Class description:
The AdvancedSettings Object in the FMC.
Method signatures and docstrings:
- def __init__(self, fmc, **kwargs): Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiati... | fd924de96e200ca8e0d5088b27a5abaf6f915bc6 | <|skeleton|>
class AdvancedSettings:
"""The AdvancedSettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiation of AdvancedSettings object. :return: None"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdvancedSettings:
"""The AdvancedSettings Object in the FMC."""
def __init__(self, fmc, **kwargs):
"""Initialize AdvancedSettings object. :param fmc: (object) FMC object :param **kwargs: Set initial variables during instantiation of AdvancedSettings object. :return: None"""
super().__init... | the_stack_v2_python_sparse | fmcapi/api_objects/policy_services/advancedsettings.py | banzigaga/fmcapi | train | 1 |
563e3df06fc1fffcf57ff4b03901a2b4a2a1543a | [
"y_data = self.cleaned_data['y_data']\nparsed_y_data = y_data.splitlines()\ntry:\n parsed_y_data = list(map(float, parsed_y_data))\nexcept ValueError:\n raise forms.ValidationError('y data must be numeric.')\nreturn y_data",
"cleaned_data = super().clean()\nx_data = cleaned_data.get('x_data')\ny_data = clea... | <|body_start_0|>
y_data = self.cleaned_data['y_data']
parsed_y_data = y_data.splitlines()
try:
parsed_y_data = list(map(float, parsed_y_data))
except ValueError:
raise forms.ValidationError('y data must be numeric.')
return y_data
<|end_body_0|>
<|body_st... | Form for uploading data. | UploadDataForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadDataForm:
"""Form for uploading data."""
def clean_y_data(self):
"""y_data should be numeric"""
<|body_0|>
def clean(self):
"""Number of entries in x and y data should be the same."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
y_data = s... | stack_v2_sparse_classes_75kplus_train_007119 | 1,587 | no_license | [
{
"docstring": "y_data should be numeric",
"name": "clean_y_data",
"signature": "def clean_y_data(self)"
},
{
"docstring": "Number of entries in x and y data should be the same.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017756 | Implement the Python class `UploadDataForm` described below.
Class description:
Form for uploading data.
Method signatures and docstrings:
- def clean_y_data(self): y_data should be numeric
- def clean(self): Number of entries in x and y data should be the same. | Implement the Python class `UploadDataForm` described below.
Class description:
Form for uploading data.
Method signatures and docstrings:
- def clean_y_data(self): y_data should be numeric
- def clean(self): Number of entries in x and y data should be the same.
<|skeleton|>
class UploadDataForm:
"""Form for upl... | 377146ae7b1f35e178ce64891f38b261eeb04ff1 | <|skeleton|>
class UploadDataForm:
"""Form for uploading data."""
def clean_y_data(self):
"""y_data should be numeric"""
<|body_0|>
def clean(self):
"""Number of entries in x and y data should be the same."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploadDataForm:
"""Form for uploading data."""
def clean_y_data(self):
"""y_data should be numeric"""
y_data = self.cleaned_data['y_data']
parsed_y_data = y_data.splitlines()
try:
parsed_y_data = list(map(float, parsed_y_data))
except ValueError:
... | the_stack_v2_python_sparse | barchart/forms.py | Code-Institute-Submissions/dashing-data | train | 0 |
180af0e2f8459b3b0b6b121af00fb575b9d8f0f0 | [
"if not nums:\n return 0\nm = -float('inf')\ni = 0\nwhile i < len(nums) and nums[i] == 0:\n i += 1\nif i > 0:\n m = 0\nwhile i < len(nums):\n p = 1\n for j in range(i, len(nums)):\n if nums[j] == 0:\n for k in range(i, j - 1):\n p //= nums[k]\n m = max(... | <|body_start_0|>
if not nums:
return 0
m = -float('inf')
i = 0
while i < len(nums) and nums[i] == 0:
i += 1
if i > 0:
m = 0
while i < len(nums):
p = 1
for j in range(i, len(nums)):
if nums[j] == 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
"""07/27/2018 22:42"""
<|body_0|>
def maxProduct(self, nums: List[int]) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
... | stack_v2_sparse_classes_75kplus_train_007120 | 3,384 | no_license | [
{
"docstring": "07/27/2018 22:42",
"name": "maxProduct",
"signature": "def maxProduct(self, nums)"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(1)",
"name": "maxProduct",
"signature": "def maxProduct(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_001139 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): 07/27/2018 22:42
- def maxProduct(self, nums: List[int]) -> int: Time complexity: O(n) Space complexity: O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, nums): 07/27/2018 22:42
- def maxProduct(self, nums: List[int]) -> int: Time complexity: O(n) Space complexity: O(1)
<|skeleton|>
class Solution:
def m... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxProduct(self, nums):
"""07/27/2018 22:42"""
<|body_0|>
def maxProduct(self, nums: List[int]) -> int:
"""Time complexity: O(n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProduct(self, nums):
"""07/27/2018 22:42"""
if not nums:
return 0
m = -float('inf')
i = 0
while i < len(nums) and nums[i] == 0:
i += 1
if i > 0:
m = 0
while i < len(nums):
p = 1
... | the_stack_v2_python_sparse | leetcode/solved/152_Maximum_Product_Subarray/solution.py | sungminoh/algorithms | train | 0 | |
224b2a4a397d77f86541eca6934306d2ffd7c419 | [
"self.DATADIR = 'data'\nself.CATEGORIAS = ['Avestruz', 'Otros']\nself.TAM_IMG = 50\nself.datos_entrenados = []\nself.labels = []\nself.features = []",
"for categoria in self.CATEGORIAS:\n ruta = os.path.join(self.DATADIR, categoria)\n class_num = self.CATEGORIAS.index(categoria)\n for img in os.listdir(r... | <|body_start_0|>
self.DATADIR = 'data'
self.CATEGORIAS = ['Avestruz', 'Otros']
self.TAM_IMG = 50
self.datos_entrenados = []
self.labels = []
self.features = []
<|end_body_0|>
<|body_start_1|>
for categoria in self.CATEGORIAS:
ruta = os.path.join(self.... | Clase para preparar las imagenes con las que se entrenara la red | Preparacion_Avestruz | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preparacion_Avestruz:
"""Clase para preparar las imagenes con las que se entrenara la red"""
def __init__(self, *args, **kwargs):
"""Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se construira el directorio para obtener las imagenes con la... | stack_v2_sparse_classes_75kplus_train_007121 | 3,260 | no_license | [
{
"docstring": "Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se construira el directorio para obtener las imagenes con las que se entrenara la red, ademas asigna el tamaño con el que se redimencionara cada imagen para vectorizarlas y crea las listas que mas adelante... | 4 | stack_v2_sparse_classes_30k_test_001383 | Implement the Python class `Preparacion_Avestruz` described below.
Class description:
Clase para preparar las imagenes con las que se entrenara la red
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se ... | Implement the Python class `Preparacion_Avestruz` described below.
Class description:
Clase para preparar las imagenes con las que se entrenara la red
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se ... | 57db72daf8b3833b4d152dd01d2f531d4c43cf3a | <|skeleton|>
class Preparacion_Avestruz:
"""Clase para preparar las imagenes con las que se entrenara la red"""
def __init__(self, *args, **kwargs):
"""Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se construira el directorio para obtener las imagenes con la... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Preparacion_Avestruz:
"""Clase para preparar las imagenes con las que se entrenara la red"""
def __init__(self, *args, **kwargs):
"""Metodo constructor Amacena el nombre de las carpetas data, Avestruz y Otros con las cuales se construira el directorio para obtener las imagenes con las que se entr... | the_stack_v2_python_sparse | Practica05/src/Avestruz/Preparacion_Avestruz.py | Kethrim/MYP_20201_316072212 | train | 0 |
ca74ca63928e7b210aeba68e237112bbc2cdda20 | [
"self.n = n\nself.colors = colors\nself.alpha = 0.4\ntheta = np.linspace(0, 2 * np.pi, n, endpoint=False) + vertex_0_theta\nself.vertex = np.stack([np.cos(theta), np.sin(theta)])",
"if not cliques:\n return\nfor s in cliques:\n v = radius * self.vertex[:, list(s)] + np.array([center]).T\n plt.fill(v[0, :... | <|body_start_0|>
self.n = n
self.colors = colors
self.alpha = 0.4
theta = np.linspace(0, 2 * np.pi, n, endpoint=False) + vertex_0_theta
self.vertex = np.stack([np.cos(theta), np.sin(theta)])
<|end_body_0|>
<|body_start_1|>
if not cliques:
return
for s... | Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot. | CliqueFigure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set ... | stack_v2_sparse_classes_75kplus_train_007122 | 7,114 | permissive | [
{
"docstring": "n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set vertex_0_theta: angle at which to place vertex 0 FIXME - include radius here? - add method to show which edge was zeroed out?",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_050167 | Implement the Python class `CliqueFigure` described below.
Class description:
Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot.
Method signatures and docstrings:
- def __init__(self, n, colors, vertex_0_theta): n: number of vertices in each graph colors: hash from sets (de... | Implement the Python class `CliqueFigure` described below.
Class description:
Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot.
Method signatures and docstrings:
- def __init__(self, n, colors, vertex_0_theta): n: number of vertices in each graph colors: hash from sets (de... | ae7b736d5199085e6b4d0aadd7c05467920cc20e | <|skeleton|>
class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CliqueFigure:
"""Plots cliques in a figure. This assumes that a given hyperedge is the same color in each plot."""
def __init__(self, n, colors, vertex_0_theta):
"""n: number of vertices in each graph colors: hash from sets (defined as sorted lists of k numbers) to color of each set vertex_0_thet... | the_stack_v2_python_sparse | countingBound/py/figure/zeroing.py | joshtburdick/misc | train | 0 |
02d6ae9495c7727ebff2d90697995a08d19818ab | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]",
"hash_table = {}\nfor i in range(len(nums)):\n complement = target - nums[i]\n if complement in hash_table:\n return [hash_table[complement], i]\n hash_table[num... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
hash_table = {}
for i in range(len(nums)):
complement = target - nums[i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_bf(self, nums, target):
"""TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]"""
<|body_0|>
def twoSum_hash_table(self, nums, target):
"""[O(n log n)] Arguments: nums {[List[int]]} target {[int]} Retur... | stack_v2_sparse_classes_75kplus_train_007123 | 1,136 | no_license | [
{
"docstring": "TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]",
"name": "twoSum_bf",
"signature": "def twoSum_bf(self, nums, target)"
},
{
"docstring": "[O(n log n)] Arguments: nums {[List[int]]} target {[int]} Returns: [List[int]] -- [list of in... | 2 | stack_v2_sparse_classes_30k_test_002055 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_bf(self, nums, target): TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]
- def twoSum_hash_table(self, nums, target): [O... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_bf(self, nums, target): TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]
- def twoSum_hash_table(self, nums, target): [O... | 8f775e7ac0d6daf5767cb30ac2739b62dfefc096 | <|skeleton|>
class Solution:
def twoSum_bf(self, nums, target):
"""TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]"""
<|body_0|>
def twoSum_hash_table(self, nums, target):
"""[O(n log n)] Arguments: nums {[List[int]]} target {[int]} Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_bf(self, nums, target):
"""TC: O(n^2) Arguments: nums {[List[int]]} -- [description] target {[List[int]]} -- [description]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return... | the_stack_v2_python_sparse | leetCode/two_sum.py | rhender007/python-ps | train | 0 | |
4814fcb55d469e19d79b191152c1d7a8fb296340 | [
"ia.seed(1)\nif not isinstance(aug_config, AugmentConfig):\n raise TypeError(f'{aug_config} is not a AugmentConfig')\nelse:\n self.aug_config = aug_config\naug_seq = []\nif self.aug_config.random_horz_flip:\n aug_seq.append(iaa.Fliplr(self.aug_config.flip_prob, name='fliplr0'))\nif self.aug_config.random_v... | <|body_start_0|>
ia.seed(1)
if not isinstance(aug_config, AugmentConfig):
raise TypeError(f'{aug_config} is not a AugmentConfig')
else:
self.aug_config = aug_config
aug_seq = []
if self.aug_config.random_horz_flip:
aug_seq.append(iaa.Fliplr(sel... | ImageAugmentizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
<|body_0|>
def augmentize(self, images: np.ndarray):
""":param images: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ia.seed(1)
... | stack_v2_sparse_classes_75kplus_train_007124 | 2,683 | permissive | [
{
"docstring": ":param nrm_config: :type nrm_config: NormalizeConfig",
"name": "__init__",
"signature": "def __init__(self, aug_config)"
},
{
"docstring": ":param images: :return:",
"name": "augmentize",
"signature": "def augmentize(self, images: np.ndarray)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002784 | Implement the Python class `ImageAugmentizer` described below.
Class description:
Implement the ImageAugmentizer class.
Method signatures and docstrings:
- def __init__(self, aug_config): :param nrm_config: :type nrm_config: NormalizeConfig
- def augmentize(self, images: np.ndarray): :param images: :return: | Implement the Python class `ImageAugmentizer` described below.
Class description:
Implement the ImageAugmentizer class.
Method signatures and docstrings:
- def __init__(self, aug_config): :param nrm_config: :type nrm_config: NormalizeConfig
- def augmentize(self, images: np.ndarray): :param images: :return:
<|skelet... | 02ecf1f52ee91e3050b2d30f602a3161ff0726cf | <|skeleton|>
class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
<|body_0|>
def augmentize(self, images: np.ndarray):
""":param images: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
ia.seed(1)
if not isinstance(aug_config, AugmentConfig):
raise TypeError(f'{aug_config} is not a AugmentConfig')
else:
self.aug_config = aug_conf... | the_stack_v2_python_sparse | app/datasets/image_augmentizer.py | normalct/Keras_MedicalImgAI | train | 0 | |
25b082e99efd9f25eb092e1189d48c252608f671 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SharingDetail()",
"from .insight_identity import InsightIdentity\nfrom .resource_reference import ResourceReference\nfrom .insight_identity import InsightIdentity\nfrom .resource_reference import ResourceReference\nfields: Dict[str, Ca... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SharingDetail()
<|end_body_0|>
<|body_start_1|>
from .insight_identity import InsightIdentity
from .resource_reference import ResourceReference
from .insight_identity import Insi... | SharingDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharingDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharingDetail:
"""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... | stack_v2_sparse_classes_75kplus_train_007125 | 4,071 | 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: SharingDetail",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `SharingDetail` described below.
Class description:
Implement the SharingDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharingDetail: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `SharingDetail` described below.
Class description:
Implement the SharingDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharingDetail: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SharingDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharingDetail:
"""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... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SharingDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SharingDetail:
"""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: SharingDetai... | the_stack_v2_python_sparse | msgraph/generated/models/sharing_detail.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ece7029545ec3110ba2e0536cf1fb5f2897efe67 | [
"file_dir = os.path.dirname(__file__)\nfilename = 'data_items.csv'\nabsolute_file_path = os.path.join(file_dir, filename)\nwith open(absolute_file_path, 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n inventory = []\n for row in csv_reader:\n inventory.append({'name': row[0], 'sell_in': int(... | <|body_start_0|>
file_dir = os.path.dirname(__file__)
filename = 'data_items.csv'
absolute_file_path = os.path.join(file_dir, filename)
with open(absolute_file_path, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
inventory = []
for row in csv_read... | Factory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Factory:
def loadInventory():
"""Let us get the data of some Items from "data_items.csv" file which contains some basic items to insert them into database in other functions Returns: (list): Returns a List where each element it's a Dictionary which contains the item"""
<|body_0|>... | stack_v2_sparse_classes_75kplus_train_007126 | 2,875 | permissive | [
{
"docstring": "Let us get the data of some Items from \"data_items.csv\" file which contains some basic items to insert them into database in other functions Returns: (list): Returns a List where each element it's a Dictionary which contains the item",
"name": "loadInventory",
"signature": "def loadInv... | 2 | stack_v2_sparse_classes_30k_train_049736 | Implement the Python class `Factory` described below.
Class description:
Implement the Factory class.
Method signatures and docstrings:
- def loadInventory(): Let us get the data of some Items from "data_items.csv" file which contains some basic items to insert them into database in other functions Returns: (list): R... | Implement the Python class `Factory` described below.
Class description:
Implement the Factory class.
Method signatures and docstrings:
- def loadInventory(): Let us get the data of some Items from "data_items.csv" file which contains some basic items to insert them into database in other functions Returns: (list): R... | 0f9f2589b567c57bd56a8a4161de3043d5639a8b | <|skeleton|>
class Factory:
def loadInventory():
"""Let us get the data of some Items from "data_items.csv" file which contains some basic items to insert them into database in other functions Returns: (list): Returns a List where each element it's a Dictionary which contains the item"""
<|body_0|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Factory:
def loadInventory():
"""Let us get the data of some Items from "data_items.csv" file which contains some basic items to insert them into database in other functions Returns: (list): Returns a List where each element it's a Dictionary which contains the item"""
file_dir = os.path.dirna... | the_stack_v2_python_sparse | repository/repository_sql/repo.py | cifpfbmoll/ollivanders-in-a-docker-pau13-loop | train | 0 | |
521f9f51c98c7984edcf4a1eac589899b02eaea4 | [
"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. | PSIServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
<|body_0|>
def uploadSet(self, request, context):
"""Missing associated documentation comment in .proto file."""
... | stack_v2_sparse_classes_75kplus_train_007127 | 5,542 | permissive | [
{
"docstring": "Gives SHA256 Hash salt",
"name": "getSalt",
"signature": "def getSalt(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "uploadSet",
"signature": "def uploadSet(self, request, context)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_036217 | Implement the Python class `PSIServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def getSalt(self, request, context): Gives SHA256 Hash salt
- def uploadSet(self, request, context): Missing associated documentation comment... | Implement the Python class `PSIServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def getSalt(self, request, context): Gives SHA256 Hash salt
- def uploadSet(self, request, context): Missing associated documentation comment... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
<|body_0|>
def uploadSet(self, request, context):
"""Missing associated documentation comment in .proto file."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PSIServiceServicer:
"""Missing associated documentation comment in .proto file."""
def getSalt(self, request, context):
"""Gives SHA256 Hash salt"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Me... | the_stack_v2_python_sparse | python/ppml/src/bigdl/ppml/fl/nn/generated/psi_service_pb2_grpc.py | intel-analytics/BigDL | train | 4,913 |
83faabb9e02996193882a333b5584eaf2e089acc | [
"try:\n await message.delete()\n args = utils.get_args(message)\n count = int(args[0].strip())\n reply = await message.get_reply_message()\n if reply:\n if reply.media:\n for _ in range(count):\n await message.client.send_file(message.to_id, reply.media)\n ... | <|body_start_0|>
try:
await message.delete()
args = utils.get_args(message)
count = int(args[0].strip())
reply = await message.get_reply_message()
if reply:
if reply.media:
for _ in range(count):
... | Spam Module | SpamMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpamMod:
"""Spam Module"""
async def spamcmd(self, message):
"""Simple spam. Use .spam <count:int> <args or reply>."""
<|body_0|>
async def cspamcmd(self, message):
"""Character spam. Use .cspam <args or reply>."""
<|body_1|>
async def wspamcmd(self,... | stack_v2_sparse_classes_75kplus_train_007128 | 2,796 | no_license | [
{
"docstring": "Simple spam. Use .spam <count:int> <args or reply>.",
"name": "spamcmd",
"signature": "async def spamcmd(self, message)"
},
{
"docstring": "Character spam. Use .cspam <args or reply>.",
"name": "cspamcmd",
"signature": "async def cspamcmd(self, message)"
},
{
"doc... | 5 | null | Implement the Python class `SpamMod` described below.
Class description:
Spam Module
Method signatures and docstrings:
- async def spamcmd(self, message): Simple spam. Use .spam <count:int> <args or reply>.
- async def cspamcmd(self, message): Character spam. Use .cspam <args or reply>.
- async def wspamcmd(self, mes... | Implement the Python class `SpamMod` described below.
Class description:
Spam Module
Method signatures and docstrings:
- async def spamcmd(self, message): Simple spam. Use .spam <count:int> <args or reply>.
- async def cspamcmd(self, message): Character spam. Use .cspam <args or reply>.
- async def wspamcmd(self, mes... | f70ed62e39470335aba81ce0e8cac4e3c71e1500 | <|skeleton|>
class SpamMod:
"""Spam Module"""
async def spamcmd(self, message):
"""Simple spam. Use .spam <count:int> <args or reply>."""
<|body_0|>
async def cspamcmd(self, message):
"""Character spam. Use .cspam <args or reply>."""
<|body_1|>
async def wspamcmd(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpamMod:
"""Spam Module"""
async def spamcmd(self, message):
"""Simple spam. Use .spam <count:int> <args or reply>."""
try:
await message.delete()
args = utils.get_args(message)
count = int(args[0].strip())
reply = await message.get_reply_me... | the_stack_v2_python_sparse | spam.py | SergaTV/FTG-Modules | train | 0 |
51150a4095974d2d452ece500216ccd2cdec12bf | [
"if image_no < len(Explosion.sprites):\n image = Explosion.sprites[image_no]\nelse:\n image = Explosion.sprites[0]\nsuper().__init__(initial_x, initial_y, game_width, game_height, image, debug)\nself.sound.play('explosion')\nself.tts = tick_life",
"if self.tts:\n self.tts -= 1\nelse:\n self.kill()\nsu... | <|body_start_0|>
if image_no < len(Explosion.sprites):
image = Explosion.sprites[image_no]
else:
image = Explosion.sprites[0]
super().__init__(initial_x, initial_y, game_width, game_height, image, debug)
self.sound.play('explosion')
self.tts = tick_life
<|... | Explosion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
<|body_0|>
def update(self):
"""Update the explosion"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_007129 | 1,151 | permissive | [
{
"docstring": "The main class for the explosion",
"name": "__init__",
"signature": "def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False)"
},
{
"docstring": "Update the explosion",
"name": "update",
"sig... | 2 | stack_v2_sparse_classes_30k_train_036439 | Implement the Python class `Explosion` described below.
Class description:
Implement the Explosion class.
Method signatures and docstrings:
- def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False): The main class for the explosion
- de... | Implement the Python class `Explosion` described below.
Class description:
Implement the Explosion class.
Method signatures and docstrings:
- def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False): The main class for the explosion
- de... | 6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9 | <|skeleton|>
class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
<|body_0|>
def update(self):
"""Update the explosion"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Explosion:
def __init__(self, tick_life: int, initial_x: int, initial_y: int, game_width: int, game_height: int, image_no: int=0, debug: bool=False):
"""The main class for the explosion"""
if image_no < len(Explosion.sprites):
image = Explosion.sprites[image_no]
else:
... | the_stack_v2_python_sparse | gym_invaders/gym_game/envs/classes/Game/Sprites/Explosion.py | Jh123x/Orbital | train | 4 | |
327cc2017ca1abfbf8cad4b2419f23e3723e36eb | [
"firstpagedata = xjob.find('.//page/data')\nsourcenode = xjob.find('source')\nif firstpagedata is None or sourcenode is None:\n return False\nbasepath = sourcenode.attrib['href']\nif not os.path.isdir(basepath):\n basepath = os.path.dirname(basepath)\nreturn os.path.isfile(os.path.join(basepath, firstpagedata... | <|body_start_0|>
firstpagedata = xjob.find('.//page/data')
sourcenode = xjob.find('source')
if firstpagedata is None or sourcenode is None:
return False
basepath = sourcenode.attrib['href']
if not os.path.isdir(basepath):
basepath = os.path.dirname(basepat... | A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process. | HashNSizerPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashNSizerPlugin:
"""A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process."""
def canhandle(self, xjob):
"""See if we can actually run the hasher."""
<|body_0|>
def handle(sel... | stack_v2_sparse_classes_75kplus_train_007130 | 2,387 | no_license | [
{
"docstring": "See if we can actually run the hasher.",
"name": "canhandle",
"signature": "def canhandle(self, xjob)"
},
{
"docstring": "Hash and get the size of the pages in the XJOB.",
"name": "handle",
"signature": "def handle(self, level, xjob)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033193 | Implement the Python class `HashNSizerPlugin` described below.
Class description:
A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process.
Method signatures and docstrings:
- def canhandle(self, xjob): See if we can actually ... | Implement the Python class `HashNSizerPlugin` described below.
Class description:
A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process.
Method signatures and docstrings:
- def canhandle(self, xjob): See if we can actually ... | af828e800b26e5d5c3c7ba050cac98f4118d339a | <|skeleton|>
class HashNSizerPlugin:
"""A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process."""
def canhandle(self, xjob):
"""See if we can actually run the hasher."""
<|body_0|>
def handle(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HashNSizerPlugin:
"""A Pipeline plugin to run an Adler32 fasthash transform by chunk on page data (and document data if it exists) Size is calculated during this process."""
def canhandle(self, xjob):
"""See if we can actually run the hasher."""
firstpagedata = xjob.find('.//page/data')
... | the_stack_v2_python_sparse | xjob/plugins/hashplugin.py | ohrite/xjob | train | 0 |
89f490f5df4c5cc284d3c01717ff73c660adc664 | [
"for i in range(1, len(nums)):\n if nums[i] < nums[i - 1]:\n return i - 1\nreturn len(nums) - 1",
"low, high = (0, len(nums) - 1)\nwhile low < high:\n mid = (low + high) / 2\n if nums[mid] < nums[mid + 1]:\n low = mid + 1\n else:\n high = mid\n low = mid + 1"
] | <|body_start_0|>
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return i - 1
return len(nums) - 1
<|end_body_0|>
<|body_start_1|>
low, high = (0, len(nums) - 1)
while low < high:
mid = (low + high) / 2
if nums[mid] < nums[mid ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_2(self, nums):
"""mid element is either the peak element or it can be on the rising or falling edge"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_007131 | 2,058 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": "mid element is either the peak element or it can be on the rising or falling edge",
"name": "findPeakElement_2",
"signature": "def findPeakElem... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_2(self, nums): mid element is either the peak element or it can be on the rising or falli... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_2(self, nums): mid element is either the peak element or it can be on the rising or falli... | 8da310a8bbaf5369be2448e8de72d28eed1a5410 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_2(self, nums):
"""mid element is either the peak element or it can be on the rising or falling edge"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return i - 1
return len(nums) - 1
def findPeakElement_2(self, nums):
"""mid element is either the peak ele... | the_stack_v2_python_sparse | leetcode/162. Find Peak Element.py | varunkudva/Programming | train | 0 | |
40156aeda5db65df5bac7d87240906e4c30c5f1b | [
"super().__init__(num_heads, block, different_layout_per_head)\nself.num_random_blocks = num_random_blocks\nself.num_sliding_window_blocks = num_sliding_window_blocks\nself.num_global_blocks = num_global_blocks\nif attention != 'unidirectional' and attention != 'bidirectional':\n raise NotImplementedError('only ... | <|body_start_0|>
super().__init__(num_heads, block, different_layout_per_head)
self.num_random_blocks = num_random_blocks
self.num_sliding_window_blocks = num_sliding_window_blocks
self.num_global_blocks = num_global_blocks
if attention != 'unidirectional' and attention != 'bidir... | Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent class of `SparsityConfig` and customizes it for `BigBird` sparsity. | BigBirdSparsityConfig | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigBirdSparsityConfig:
"""Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent class of `SparsityConfig` and customizes i... | stack_v2_sparse_classes_75kplus_train_007132 | 42,463 | permissive | [
{
"docstring": "Initialize the BigBird Sparsity Pattern Config. For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial Arguments: num_heads: required: an integer determining number of attention heads of the layer. block: optional: an integer determining the block size. Current implementation o... | 5 | stack_v2_sparse_classes_30k_train_004365 | Implement the Python class `BigBirdSparsityConfig` described below.
Class description:
Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent cla... | Implement the Python class `BigBirdSparsityConfig` described below.
Class description:
Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent cla... | 55d9964c59c0c6e23158b5789a5c36c28939a7b0 | <|skeleton|>
class BigBirdSparsityConfig:
"""Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent class of `SparsityConfig` and customizes i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BigBirdSparsityConfig:
"""Configuration class to store `BigBird` sparsity configuration. For more details about this sparsity config, please see `Big Bird: Transformers for Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf This class extends parent class of `SparsityConfig` and customizes it for `BigBir... | the_stack_v2_python_sparse | deepspeed/ops/sparse_attention/sparsity_config.py | microsoft/DeepSpeed | train | 27,557 |
2f08c44c5785d53f92c3c907240e4e1388b369b7 | [
"if self.my_osid_object._my_map['solution'] is not None:\n return True\nreturn False",
"if not self.has_solution():\n raise IllegalState()\nreturn DisplayText(self.my_osid_object._my_map['solution'])"
] | <|body_start_0|>
if self.my_osid_object._my_map['solution'] is not None:
return True
return False
<|end_body_0|>
<|body_start_1|>
if not self.has_solution():
raise IllegalState()
return DisplayText(self.my_osid_object._my_map['solution'])
<|end_body_1|>
| ItemWithSolutionRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemWithSolutionRecord:
def has_solution(self):
"""stub"""
<|body_0|>
def get_solution(self, parameters=None):
"""stub"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.my_osid_object._my_map['solution'] is not None:
return True
... | stack_v2_sparse_classes_75kplus_train_007133 | 13,840 | permissive | [
{
"docstring": "stub",
"name": "has_solution",
"signature": "def has_solution(self)"
},
{
"docstring": "stub",
"name": "get_solution",
"signature": "def get_solution(self, parameters=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022151 | Implement the Python class `ItemWithSolutionRecord` described below.
Class description:
Implement the ItemWithSolutionRecord class.
Method signatures and docstrings:
- def has_solution(self): stub
- def get_solution(self, parameters=None): stub | Implement the Python class `ItemWithSolutionRecord` described below.
Class description:
Implement the ItemWithSolutionRecord class.
Method signatures and docstrings:
- def has_solution(self): stub
- def get_solution(self, parameters=None): stub
<|skeleton|>
class ItemWithSolutionRecord:
def has_solution(self):
... | 445f968a175d61c8d92c0f617a3c17dc1dc7c584 | <|skeleton|>
class ItemWithSolutionRecord:
def has_solution(self):
"""stub"""
<|body_0|>
def get_solution(self, parameters=None):
"""stub"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemWithSolutionRecord:
def has_solution(self):
"""stub"""
if self.my_osid_object._my_map['solution'] is not None:
return True
return False
def get_solution(self, parameters=None):
"""stub"""
if not self.has_solution():
raise IllegalState()
... | the_stack_v2_python_sparse | dlkit/records/assessment/basic/base_records.py | mitsei/dlkit | train | 2 | |
edf3c2bd5ebe1979d2e48ca1a53ad5c6aa7ad5b6 | [
"self.d_model = d_model\nself.d_f = d_f\nself.k = k\nself.n_outp = n_outp\nself.padding = padding\nself.unit_type = unit_type\nself.first_layer = self.feedforward(inp)\nself.layer_list = [self.first_layer]\nfor i in range(n_blocks):\n self.layer_list.append(self.block(self.layer_list[-1], int(2 ** (i % (np.log2(... | <|body_start_0|>
self.d_model = d_model
self.d_f = d_f
self.k = k
self.n_outp = n_outp
self.padding = padding
self.unit_type = unit_type
self.first_layer = self.feedforward(inp)
self.layer_list = [self.first_layer]
for i in range(n_blocks):
... | Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units. | ResNetV2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNetV2:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units."""
def __init__(self, inp, n_outp, n_blocks, d_model... | stack_v2_sparse_classes_75kplus_train_007134 | 6,159 | no_license | [
{
"docstring": "Argument/s: inp - input placeholder. n_outp - number of output nodes. n_blocks - number of bottlekneck residual blocks. d_model - model size. d_f - bottlekneck size. k - kernel size. max_d_rate - maximum dilation rate. padding - padding type. unit_type - convolutional unit type. sigmoid_outp - u... | 4 | stack_v2_sparse_classes_30k_train_048856 | Implement the Python class `ResNetV2` described below.
Class description:
Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units.
Method signatures... | Implement the Python class `ResNetV2` described below.
Class description:
Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units.
Method signatures... | e455ea79ae1522397c1f46a9fc1ac65a7fabe295 | <|skeleton|>
class ResNetV2:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units."""
def __init__(self, inp, n_outp, n_blocks, d_model... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNetV2:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used with no scale or centre parameters to reduce overfitting, as in [1]. Bias is used for all convolutional units."""
def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max... | the_stack_v2_python_sparse | models/snr_estimation2/network/tcn.py | celpas/SpeakerIdentificationSystem | train | 2 |
748f6671399641fc2c28caa98032679a5ed29ab9 | [
"\"\"\"测试添加购物车\"\"\"\nadd = AddGwcPage(self.driver)\nadd.going_fenlei()\nadd.add_gwc()\ndy = add.dy_add_gwc()\nself.assertEqual(dy, '1')",
"\"\"\"测试添加多个商品\"\"\"\nsort = HomePage(self.driver)\nsort.click_sort()\nadd = AddGwcPage(self.driver)\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\ndy = add.dy_... | <|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
<|end_body_0|>
<|body_start_1|>
"""测试添加多个商品"""
sort = HomePage(self.driver)
sort.click_sort()
add... | AddgwcTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.g... | stack_v2_sparse_classes_75kplus_train_007135 | 1,517 | no_license | [
{
"docstring": "MRYX_ST_classification_004",
"name": "test_add_gwc",
"signature": "def test_add_gwc(self)"
},
{
"docstring": "MRYX_ST_classification_009",
"name": "test_add_goods",
"signature": "def test_add_goods(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002973 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009
<|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
... | 2325c7854c5625babdb51b5c5e40fa860813a400 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
def test_add_goods(self):
"""MRYX_ST_classifica... | the_stack_v2_python_sparse | testcase/test_add_gwc.py | danyubiao/mryx | train | 0 | |
7ee1314c5b7a024d8d711f298c47a22e3eebe767 | [
"inst = None\nif verbose:\n print('notification factory datafile %s dbtype %s verbose %s' % (db_dict, db_type, verbose))\nif db_type == 'csv':\n inst = CsvProgramsTable(db_dict, db_type, verbose)\nelif db_type == 'mysql':\n inst = MySQLProgramsTable(db_dict, db_type, verbose)\nelse:\n ValueError('Invali... | <|body_start_0|>
inst = None
if verbose:
print('notification factory datafile %s dbtype %s verbose %s' % (db_dict, db_type, verbose))
if db_type == 'csv':
inst = CsvProgramsTable(db_dict, db_type, verbose)
elif db_type == 'mysql':
inst = MySQLProgramsT... | Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed. | ProgramsTable | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramsTable:
"""Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed."""
def factory(cls, db_dict, db_type, verbose):
"""Factory method to select subclass based on database type. Currently the types sql and csv are supported. Return... | stack_v2_sparse_classes_75kplus_train_007136 | 9,672 | permissive | [
{
"docstring": "Factory method to select subclass based on database type. Currently the types sql and csv are supported. Returns instance object of the defined type.",
"name": "factory",
"signature": "def factory(cls, db_dict, db_type, verbose)"
},
{
"docstring": "Return record for current progr... | 3 | stack_v2_sparse_classes_30k_train_040526 | Implement the Python class `ProgramsTable` described below.
Class description:
Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed.
Method signatures and docstrings:
- def factory(cls, db_dict, db_type, verbose): Factory method to select subclass based on database ty... | Implement the Python class `ProgramsTable` described below.
Class description:
Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed.
Method signatures and docstrings:
- def factory(cls, db_dict, db_type, verbose): Factory method to select subclass based on database ty... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class ProgramsTable:
"""Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed."""
def factory(cls, db_dict, db_type, verbose):
"""Factory method to select subclass based on database type. Currently the types sql and csv are supported. Return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgramsTable:
"""Abstract class for ProgramsTable This table contains a single entry, the last time a scan was executed."""
def factory(cls, db_dict, db_type, verbose):
"""Factory method to select subclass based on database type. Currently the types sql and csv are supported. Returns instance ob... | the_stack_v2_python_sparse | smipyping/_programstable.py | KSchopmeyer/smipyping | train | 0 |
91fe48768d033d4d3c11037a52c38babc55afa13 | [
"if not strs:\n return [[]]\nstrs.sort()\nresult = []\nhashMap = {}\nfor s in strs:\n sorted_str = ''.join(sorted(s))\n if sorted_str in hashMap:\n hashMap[sorted_str].append(s)\n else:\n hashMap[sorted_str] = [s]\nfor key in hashMap:\n if len(hashMap[key]) >= 1:\n result.append(... | <|body_start_0|>
if not strs:
return [[]]
strs.sort()
result = []
hashMap = {}
for s in strs:
sorted_str = ''.join(sorted(s))
if sorted_str in hashMap:
hashMap[sorted_str].append(s)
else:
hashMap[sort... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams_self(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not strs:... | stack_v2_sparse_classes_75kplus_train_007137 | 971 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams_self",
"signature": "def groupAnagrams_self(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040597 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams_self(self, strs): :type strs: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams_self(self, strs): :type strs: List[str] :rtype: List[List[str]]
<|skeleton|>
cla... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams_self(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
if not strs:
return [[]]
strs.sort()
result = []
hashMap = {}
for s in strs:
sorted_str = ''.join(sorted(s))
if sorted_str in hashMap... | the_stack_v2_python_sparse | 49_group_anagrams/sol.py | lianke123321/leetcode_sol | train | 0 | |
f01bc8d0b733fd19549a0080617c95d73291854d | [
"with open(filename) as config_file:\n config_dict = yaml.load(config_file)\nConfig.import_python_classes(config_dict)\nConfig.config = config_dict",
"if isinstance(obj, dict):\n if 'module' in obj and 'class' in obj:\n obj['module'] = importlib.import_module(obj['module'])\n obj['class'] = ge... | <|body_start_0|>
with open(filename) as config_file:
config_dict = yaml.load(config_file)
Config.import_python_classes(config_dict)
Config.config = config_dict
<|end_body_0|>
<|body_start_1|>
if isinstance(obj, dict):
if 'module' in obj and 'class' in obj:
... | Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object"""
def parse(filename):
"""Read and parse yaml config file, initialized Config.config. Parses a yaml config file and returns a ConfigWrapper object with the attribu... | stack_v2_sparse_classes_75kplus_train_007138 | 1,953 | no_license | [
{
"docstring": "Read and parse yaml config file, initialized Config.config. Parses a yaml config file and returns a ConfigWrapper object with the attributes from the config file but with classes instead of strings as values.",
"name": "parse",
"signature": "def parse(filename)"
},
{
"docstring":... | 2 | null | Implement the Python class `Config` described below.
Class description:
Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object
Method signatures and docstrings:
- def parse(filename): Read and parse yaml config file, initialized Config.config. Parses a yaml config... | Implement the Python class `Config` described below.
Class description:
Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object
Method signatures and docstrings:
- def parse(filename): Read and parse yaml config file, initialized Config.config. Parses a yaml config... | 63a2f6e5ef8a8799321ec3f695c8fe253edfeec1 | <|skeleton|>
class Config:
"""Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object"""
def parse(filename):
"""Read and parse yaml config file, initialized Config.config. Parses a yaml config file and returns a ConfigWrapper object with the attribu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
"""Wrapper class for the config. Before first use call parse_config_file or you will get an empty config object"""
def parse(filename):
"""Read and parse yaml config file, initialized Config.config. Parses a yaml config file and returns a ConfigWrapper object with the attributes from the ... | the_stack_v2_python_sparse | dementia_prediction/config_wrapper.py | vwegmayr/dementia-classification | train | 6 |
3d4a105411af4a4f731c0843bc1965e6d6d1c477 | [
"if not root:\n return []\nres = []\ndict = {}\nself.helper(root, 0, res)\nfor items in res:\n for item in items:\n if item not in dict:\n dict[item] = 1\n else:\n dict[item] += 1\nmax_num = max(dict.values())\nreturn [key for key, value in dict.iteritems() if value == max_... | <|body_start_0|>
if not root:
return []
res = []
dict = {}
self.helper(root, 0, res)
for items in res:
for item in items:
if item not in dict:
dict[item] = 1
else:
dict[item] += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMode(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def helper(self, root, level, res):
""":type root: TreeNode :param level: :TreeNode res: List[List[int]] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007139 | 1,229 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findMode",
"signature": "def findMode(self, root)"
},
{
"docstring": ":type root: TreeNode :param level: :TreeNode res: List[List[int]] :return:",
"name": "helper",
"signature": "def helper(self, root, level, res)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049617 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMode(self, root): :type root: TreeNode :rtype: List[int]
- def helper(self, root, level, res): :type root: TreeNode :param level: :TreeNode res: List[List[int]] :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMode(self, root): :type root: TreeNode :rtype: List[int]
- def helper(self, root, level, res): :type root: TreeNode :param level: :TreeNode res: List[List[int]] :return:
... | 772e047c4e1e9abf0d74b7dd539d684f216799b9 | <|skeleton|>
class Solution:
def findMode(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def helper(self, root, level, res):
""":type root: TreeNode :param level: :TreeNode res: List[List[int]] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMode(self, root):
""":type root: TreeNode :rtype: List[int]"""
if not root:
return []
res = []
dict = {}
self.helper(root, 0, res)
for items in res:
for item in items:
if item not in dict:
... | the_stack_v2_python_sparse | code/FindModeinBinarySearchTree.py | crl0636/Python | train | 1 | |
7d860aa0ca1b8a52b96a328fd7860c5510927a51 | [
"test_data = os.path.join(TEST_DIR_PATH, 'testcases', 'yara_test_data')\nwith tempfile.TemporaryDirectory() as tmp_dir:\n project_name = 'yara'\n old_commit = 'f79be4f2330f4b89ea2f42e1c44ca998c59a0c0f'\n new_commit = 'f50a39051ea8c7f10d6d8db9656658b49601caef'\n fuzzer = 'rules_fuzzer'\n yara_repo_man... | <|body_start_0|>
test_data = os.path.join(TEST_DIR_PATH, 'testcases', 'yara_test_data')
with tempfile.TemporaryDirectory() as tmp_dir:
project_name = 'yara'
old_commit = 'f79be4f2330f4b89ea2f42e1c44ca998c59a0c0f'
new_commit = 'f50a39051ea8c7f10d6d8db9656658b49601caef'... | Testing if an image can be built from different states e.g. a commit. | BuildImageIntegrationTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildImageIntegrationTests:
"""Testing if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a proper commit. This is done by using a known regression range for a specific test case. The old com... | stack_v2_sparse_classes_75kplus_train_007140 | 5,295 | permissive | [
{
"docstring": "Tests if the fuzzers can build at a proper commit. This is done by using a known regression range for a specific test case. The old commit should show the error when its fuzzers run and the new one should not.",
"name": "test_build_fuzzers_from_commit",
"signature": "def test_build_fuzze... | 3 | stack_v2_sparse_classes_30k_train_034917 | Implement the Python class `BuildImageIntegrationTests` described below.
Class description:
Testing if an image can be built from different states e.g. a commit.
Method signatures and docstrings:
- def test_build_fuzzers_from_commit(self): Tests if the fuzzers can build at a proper commit. This is done by using a kno... | Implement the Python class `BuildImageIntegrationTests` described below.
Class description:
Testing if an image can be built from different states e.g. a commit.
Method signatures and docstrings:
- def test_build_fuzzers_from_commit(self): Tests if the fuzzers can build at a proper commit. This is done by using a kno... | 8e2d57684bd49355b80572592c3af5cefc19a69c | <|skeleton|>
class BuildImageIntegrationTests:
"""Testing if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a proper commit. This is done by using a known regression range for a specific test case. The old com... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildImageIntegrationTests:
"""Testing if an image can be built from different states e.g. a commit."""
def test_build_fuzzers_from_commit(self):
"""Tests if the fuzzers can build at a proper commit. This is done by using a known regression range for a specific test case. The old commit should sh... | the_stack_v2_python_sparse | infra/build_specified_commit_test.py | DeepInThought/oss-fuzz | train | 2 |
7309c1a5226dcdfd7341a0e2d2b6bc5161404fc0 | [
"enterprise_client = EnterpriseApiClient(auth_token)\nenterprise_learner_data = enterprise_client.get_enterprise_learner(user)\nif not enterprise_learner_data:\n return None\nreturn {'enterprise_id': enterprise_learner_data['enterprise_customer']['uuid'], 'enterprise_groups': enterprise_learner_data['groups']}",... | <|body_start_0|>
enterprise_client = EnterpriseApiClient(auth_token)
enterprise_learner_data = enterprise_client.get_enterprise_learner(user)
if not enterprise_learner_data:
return None
return {'enterprise_id': enterprise_learner_data['enterprise_customer']['uuid'], 'enterpri... | Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away when JWT Scopes are fully implemented and the associa... | IsStaffOrEnterpriseUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away wh... | stack_v2_sparse_classes_75kplus_train_007141 | 4,847 | no_license | [
{
"docstring": "Get the enterprise learner model from the LMS for the given user. Returns: learner or None if unable to get or user is not associated with an enterprise",
"name": "get_user_enterprise_data",
"signature": "def get_user_enterprise_data(self, auth_token, user)"
},
{
"docstring": "Ve... | 2 | stack_v2_sparse_classes_30k_train_015501 | Implement the Python class `IsStaffOrEnterpriseUser` described below.
Class description:
Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in th... | Implement the Python class `IsStaffOrEnterpriseUser` described below.
Class description:
Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in th... | d16a25b035b2e810b8ab2b0a2ac032b216562e26 | <|skeleton|>
class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away when JWT Scopes... | the_stack_v2_python_sparse | edx/app/analytics_api/venvs/analytics_api/lib/python2.7/site-packages/enterprise_data/permissions.py | JosiahKennedy/openedx-branded | train | 0 |
3a801c63c20d55dd67f77370b28657a6d243273e | [
"menu_id = self.get_args('id', 0)\nif is_empty(menu_id):\n self.send_fail_html('参数错误')\n return\none = Menu().get_one8id(menu_id)\npowers = Power().get_all()\nfathers = Menu().get_some({'fid': 0})\nself.render('system/menu-add.html', one=one, powers=powers, fathers=fathers)",
"try:\n menu_id = self.get_a... | <|body_start_0|>
menu_id = self.get_args('id', 0)
if is_empty(menu_id):
self.send_fail_html('参数错误')
return
one = Menu().get_one8id(menu_id)
powers = Power().get_all()
fathers = Menu().get_some({'fid': 0})
self.render('system/menu-add.html', one=one... | MenuEditHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuEditHandler:
def get(self, *args, **kwargs):
"""加载修改菜单表单页 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""执行修改菜单 :param args: :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
menu_id ... | stack_v2_sparse_classes_75kplus_train_007142 | 29,655 | no_license | [
{
"docstring": "加载修改菜单表单页 :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "执行修改菜单 :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050185 | Implement the Python class `MenuEditHandler` described below.
Class description:
Implement the MenuEditHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 加载修改菜单表单页 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 执行修改菜单 :param args: :param kwargs: :return: | Implement the Python class `MenuEditHandler` described below.
Class description:
Implement the MenuEditHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 加载修改菜单表单页 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 执行修改菜单 :param args: :param kwargs: :return:
<|ske... | d1714c7f44bae2b7ebce489d3d73df6bd55a5e04 | <|skeleton|>
class MenuEditHandler:
def get(self, *args, **kwargs):
"""加载修改菜单表单页 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""执行修改菜单 :param args: :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuEditHandler:
def get(self, *args, **kwargs):
"""加载修改菜单表单页 :param args: :param kwargs: :return:"""
menu_id = self.get_args('id', 0)
if is_empty(menu_id):
self.send_fail_html('参数错误')
return
one = Menu().get_one8id(menu_id)
powers = Power().get_... | the_stack_v2_python_sparse | handlers/system.py | frankiegu/MarketingManager | train | 0 | |
b7650fc1ccb111269ec2f0e2869375396cbb3be3 | [
"prototypes_, omegas_ = model.get_model_params()\nprototypes_labels_ = model.prototypes_labels_\ndistance_function = 'mahalanobis'\nkwarg_str = 'VI'\nif model.force_all_finite == 'allow-nan':\n distance_function = _nan_mahalanobis\n kwarg_str = 'RM'\ncdists = np.zeros((data.shape[0], model._prototypes_shape[0... | <|body_start_0|>
prototypes_, omegas_ = model.get_model_params()
prototypes_labels_ = model.prototypes_labels_
distance_function = 'mahalanobis'
kwarg_str = 'VI'
if model.force_all_finite == 'allow-nan':
distance_function = _nan_mahalanobis
kwarg_str = 'RM... | Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False, "allow-nan"} Parameter to indicate that NaNLVQ distance variant should be used. If true no nans... | LocalAdaptiveSquaredEuclidean | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalAdaptiveSquaredEuclidean:
"""Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False, "allow-nan"} Parameter to indicate tha... | stack_v2_sparse_classes_75kplus_train_007143 | 5,929 | permissive | [
{
"docstring": "Computes the local variant of the adaptive squared Euclidean distance: .. math:: d^{\\\\Lambda}(\\\\mathbf{w}, \\\\mathbf{x}) = (\\\\mathbf{x} - \\\\mathbf{w})^{\\\\top} \\\\Omega_j^{\\\\top} \\\\Omega_j (\\\\mathbf{x} - \\\\mathbf{w}) with :math:`\\\\Omega_j` depending on the localization setti... | 2 | stack_v2_sparse_classes_30k_train_033782 | Implement the Python class `LocalAdaptiveSquaredEuclidean` described below.
Class description:
Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False,... | Implement the Python class `LocalAdaptiveSquaredEuclidean` described below.
Class description:
Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False,... | 9b64b15e0a7db3de90fd80ccc66ed6cdf2cc5ddb | <|skeleton|>
class LocalAdaptiveSquaredEuclidean:
"""Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False, "allow-nan"} Parameter to indicate tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalAdaptiveSquaredEuclidean:
"""Local adaptive squared Euclidean distance Class that holds the localized adaptive squared Euclidean distance function and its gradient as described in `[1]`_ and `[2]`_. Parameters ---------- force_all_finite : {True, False, "allow-nan"} Parameter to indicate that NaNLVQ dist... | the_stack_v2_python_sparse | sklvq/distances/_local_adaptive_squared_euclidean.py | SarahFallmann/sklvq | train | 0 |
99e795009b80a64a729c3884b487c1440dd383c0 | [
"db_session = get_db_session(db_session)\nif status is UserStatuses.Pending:\n return db_session.query(UserPending)\nif status is None:\n return db_session.query(cls.model)\nquery = db_session.query(cls.model)\nusers = []\nif UserStatuses.Pending in status:\n users = list(db_session.query(UserPending))\n ... | <|body_start_0|>
db_session = get_db_session(db_session)
if status is UserStatuses.Pending:
return db_session.query(UserPending)
if status is None:
return db_session.query(cls.model)
query = db_session.query(cls.model)
users = []
if UserStatuses.Pe... | Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with any other :class:`UserStatuses` members, or through the *all* representation, the retu... | UserSearchService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSearchService:
"""Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with any other :class:`UserStatuses` members, ... | stack_v2_sparse_classes_75kplus_train_007144 | 42,346 | permissive | [
{
"docstring": "Search for appropriate :class:`User` and/or :class:`UserPending` according to specified :class:`UserStatuses`. When the :paramref:`status` is ``None``, *normal* retrieval of all non-pending :class:`User` is executed, as if directly using the :class:`UserService` implementation. Otherwise, a comb... | 3 | stack_v2_sparse_classes_30k_train_025316 | Implement the Python class `UserSearchService` described below.
Class description:
Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with an... | Implement the Python class `UserSearchService` described below.
Class description:
Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with an... | f9b00c6142372aff96fd0edf0537c8b383fd5ee9 | <|skeleton|>
class UserSearchService:
"""Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with any other :class:`UserStatuses` members, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSearchService:
"""Extends the :mod:`ziggurat_foundations` :class:`UserService` with additional features provided by `Magpie`. .. note:: For any search result where parameter ``status`` is equal to or contains :attr:`UserStatuses.Pending` combined with any other :class:`UserStatuses` members, or through th... | the_stack_v2_python_sparse | magpie/models.py | Ouranosinc/Magpie | train | 2 |
aaa705be86a9645402b6eb237ede59b215a32ae5 | [
"tests = (('testme', '7A67F5D4-50FD-36F7-BBEB-1C739AB40B8C'), ('helloworldvc7win.vcproj', 'D4B7B275-B4D2-3FEF-86CF-D2D640314544'))\nfor test in tests:\n self.assertEqual(get_uuid(test[0]), test[1])",
"vs_project = VS2003XML('VisualStudioProject')\nself.assertEqual(str(vs_project), '<VisualStudioProject>\\n</Vi... | <|body_start_0|>
tests = (('testme', '7A67F5D4-50FD-36F7-BBEB-1C739AB40B8C'), ('helloworldvc7win.vcproj', 'D4B7B275-B4D2-3FEF-86CF-D2D640314544'))
for test in tests:
self.assertEqual(get_uuid(test[0]), test[1])
<|end_body_0|>
<|body_start_1|>
vs_project = VS2003XML('VisualStudioProj... | Test visual studio text generation | TestVisualStudio | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVisualStudio:
"""Test visual studio text generation"""
def test_get_uuid(self):
"""Test makeprojects.visual_studio.get_uuid"""
<|body_0|>
def test_vs2003xml(self):
"""Test makeprojects.visual_studio.VS2003XML"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_007145 | 4,485 | no_license | [
{
"docstring": "Test makeprojects.visual_studio.get_uuid",
"name": "test_get_uuid",
"signature": "def test_get_uuid(self)"
},
{
"docstring": "Test makeprojects.visual_studio.VS2003XML",
"name": "test_vs2003xml",
"signature": "def test_vs2003xml(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046675 | Implement the Python class `TestVisualStudio` described below.
Class description:
Test visual studio text generation
Method signatures and docstrings:
- def test_get_uuid(self): Test makeprojects.visual_studio.get_uuid
- def test_vs2003xml(self): Test makeprojects.visual_studio.VS2003XML | Implement the Python class `TestVisualStudio` described below.
Class description:
Test visual studio text generation
Method signatures and docstrings:
- def test_get_uuid(self): Test makeprojects.visual_studio.get_uuid
- def test_vs2003xml(self): Test makeprojects.visual_studio.VS2003XML
<|skeleton|>
class TestVisua... | 7f4438073a8bb87dad0068a3dfc1bf41d6caa451 | <|skeleton|>
class TestVisualStudio:
"""Test visual studio text generation"""
def test_get_uuid(self):
"""Test makeprojects.visual_studio.get_uuid"""
<|body_0|>
def test_vs2003xml(self):
"""Test makeprojects.visual_studio.VS2003XML"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestVisualStudio:
"""Test visual studio text generation"""
def test_get_uuid(self):
"""Test makeprojects.visual_studio.get_uuid"""
tests = (('testme', '7A67F5D4-50FD-36F7-BBEB-1C739AB40B8C'), ('helloworldvc7win.vcproj', 'D4B7B275-B4D2-3FEF-86CF-D2D640314544'))
for test in tests:
... | the_stack_v2_python_sparse | unittests/test_visualstudio.py | burgerbecky/makeprojects | train | 28 |
4fc1475c577693a0ff95f2a1174e37dfae028f8f | [
"candidates.sort()\ntable = [None] + [set() for _ in range(target)]\nfor i in candidates:\n if i > target:\n break\n for j in range(target - i, 0, -1):\n table[i + j] |= {elt + (i,) for elt in table[j]}\n table[i].add((i,))\nreturn map(list, table[target])",
"def dfs(candidates, target, dep... | <|body_start_0|>
candidates.sort()
table = [None] + [set() for _ in range(target)]
for i in candidates:
if i > target:
break
for j in range(target - i, 0, -1):
table[i + j] |= {elt + (i,) for elt in table[j]}
table[i].add((i,))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%"""
<|body_0|>
def combinationSum2_1(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List... | stack_v2_sparse_classes_75kplus_train_007146 | 1,499 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%",
"name": "combinationSum2",
"signature": "def combinationSum2(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]] Backtracking solut... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%
- def combinationSum2_1(self, candidates, target... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%
- def combinationSum2_1(self, candidates, target... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%"""
<|body_0|>
def combinationSum2_1(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]] beats 79.58%"""
candidates.sort()
table = [None] + [set() for _ in range(target)]
for i in candidates:
if i > target:
br... | the_stack_v2_python_sparse | LeetCode/040_combination_sum_ii.py | yao23/Machine_Learning_Playground | train | 12 | |
653c6dd98d5eb77c3d548a746dc68ef19ea9ae27 | [
"tokenizedText = []\nfor i in text:\n tokenizedText += [i.replace(',', ' ').replace('.', ' ').replace('?', ' ').replace('!', ' ').replace(';', ' ').split()]\nreturn tokenizedText",
"word_tokenizer = TreebankWordTokenizer()\ntokenizedText = []\nfor i in text:\n tokenizedText += [word_tokenizer.tokenize(i)]\n... | <|body_start_0|>
tokenizedText = []
for i in text:
tokenizedText += [i.replace(',', ' ').replace('.', ' ').replace('?', ' ').replace('!', ' ').replace(';', ' ').split()]
return tokenizedText
<|end_body_0|>
<|body_start_1|>
word_tokenizer = TreebankWordTokenizer()
tok... | Tokenization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
<|body_0|>
def pennTreeB... | stack_v2_sparse_classes_75kplus_train_007147 | 934 | no_license | [
{
"docstring": "Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens",
"name": "naive",
"signature": "def naive(self, text)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_010858 | Implement the Python class `Tokenization` described below.
Class description:
Implement the Tokenization class.
Method signatures and docstrings:
- def naive(self, text): Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list... | Implement the Python class `Tokenization` described below.
Class description:
Implement the Tokenization class.
Method signatures and docstrings:
- def naive(self, text): Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list... | 716495837ce37b0ccf81255cf3b881c7eab191cf | <|skeleton|>
class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
<|body_0|>
def pennTreeB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tokenization:
def naive(self, text):
"""Tokenization using a Naive Approach Parameters ---------- arg1 : list A list of strings where each string is a single sentence Returns ------- list A list of lists where each sub-list is a sequence of tokens"""
tokenizedText = []
for i in text:
... | the_stack_v2_python_sparse | tokenization.py | AbhishekSureddy/Natural-Language-Processing-project-CS6370 | train | 0 | |
3eaf42276629e55a2632c84547234fab76f8d879 | [
"g = Pipeline.__call__(self, *args, **kwargs)\ngs = g.glyph.glyph_source\nif not 'mode' in kwargs:\n gs.glyph_source = gs.glyph_list[-1]\ngs.glyph_position = 'tail'\ngs.glyph_source.center = (0.0, 0.0, 0.5)\ng.glyph.glyph.orient = False\nif not 'color' in kwargs:\n g.glyph.color_mode = 'color_by_scalar'\nif n... | <|body_start_0|>
g = Pipeline.__call__(self, *args, **kwargs)
gs = g.glyph.glyph_source
if not 'mode' in kwargs:
gs.glyph_source = gs.glyph_list[-1]
gs.glyph_position = 'tail'
gs.glyph_source.center = (0.0, 0.0, 0.5)
g.glyph.glyph.orient = False
if not... | 2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of inputs, with positions given in 2-D or in 3... | CustomBarChart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of i... | stack_v2_sparse_classes_75kplus_train_007148 | 5,432 | no_license | [
{
"docstring": "Override the call to be able to scale automaticaly the axis.",
"name": "__call__",
"signature": "def __call__(self, *args, **kwargs)"
},
{
"docstring": "2012.2.21 this function determines the set of possible keys in kwargs. add two keywords, x_scale, y_scale. Returns all the trai... | 2 | stack_v2_sparse_classes_30k_train_012939 | Implement the Python class `CustomBarChart` described below.
Class description:
2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. Thi... | Implement the Python class `CustomBarChart` described below.
Class description:
2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. Thi... | b9333b85daed71032a1cba766585d0be1986ffdb | <|skeleton|>
class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomBarChart:
"""2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of inputs, with p... | the_stack_v2_python_sparse | pymodule/plot/yh_mayavi.py | polyactis/gwasmodules | train | 0 |
9ff57083169c2e53ff90fa0efeee7d4db03e144c | [
"if admin_membership.is_admin is False:\n return None\nnew_membership = InitiativeMembership()\nnew_membership.initiative = self.initiative\nnew_membership.user = self.user\nnew_membership.save()\nself.approved_by = admin_membership\nself.is_open = False\nself.save()\nreturn new_membership",
"if not admin_memb... | <|body_start_0|>
if admin_membership.is_admin is False:
return None
new_membership = InitiativeMembership()
new_membership.initiative = self.initiative
new_membership.user = self.user
new_membership.save()
self.approved_by = admin_membership
self.is_op... | Represents a request from a user to join the initiative. Must be approved by an admin. | JoinRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinRequest:
"""Represents a request from a user to join the initiative. Must be approved by an admin."""
def approve(self, admin_membership):
"""Approve a request for membership. :param admin_membership: The admin's membership that approves the request. :return: A new membership if ... | stack_v2_sparse_classes_75kplus_train_007149 | 7,959 | no_license | [
{
"docstring": "Approve a request for membership. :param admin_membership: The admin's membership that approves the request. :return: A new membership if success, None if fails.",
"name": "approve",
"signature": "def approve(self, admin_membership)"
},
{
"docstring": "Declines membership :param ... | 2 | stack_v2_sparse_classes_30k_train_051584 | Implement the Python class `JoinRequest` described below.
Class description:
Represents a request from a user to join the initiative. Must be approved by an admin.
Method signatures and docstrings:
- def approve(self, admin_membership): Approve a request for membership. :param admin_membership: The admin's membership... | Implement the Python class `JoinRequest` described below.
Class description:
Represents a request from a user to join the initiative. Must be approved by an admin.
Method signatures and docstrings:
- def approve(self, admin_membership): Approve a request for membership. :param admin_membership: The admin's membership... | d099e5f4cb5fa412f6e1aa71b5dd7ba022161501 | <|skeleton|>
class JoinRequest:
"""Represents a request from a user to join the initiative. Must be approved by an admin."""
def approve(self, admin_membership):
"""Approve a request for membership. :param admin_membership: The admin's membership that approves the request. :return: A new membership if ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JoinRequest:
"""Represents a request from a user to join the initiative. Must be approved by an admin."""
def approve(self, admin_membership):
"""Approve a request for membership. :param admin_membership: The admin's membership that approves the request. :return: A new membership if success, None... | the_stack_v2_python_sparse | mapstory/apps/initiatives/models.py | ngageoint/storyscapes | train | 3 |
c9d8497b92b93f2634a81ef19b403eae1cfc20d0 | [
"project_qs = Project.objects.all()\nserializer = ProjectModelSerializer(instance=project_qs, many=True)\nreturn JsonResponse(serializer.data, safe=False)",
"json_data = request.body.decode('utf-8')\npython_data = json.loads(json_data)\nserializer = ProjectModelSerializer(data=python_data)\ntry:\n serializer.i... | <|body_start_0|>
project_qs = Project.objects.all()
serializer = ProjectModelSerializer(instance=project_qs, many=True)
return JsonResponse(serializer.data, safe=False)
<|end_body_0|>
<|body_start_1|>
json_data = request.body.decode('utf-8')
python_data = json.loads(json_data)
... | ProjectsList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsList:
def get(self, request):
"""处理查询项目请求 :param request: :return:"""
<|body_0|>
def post(self, request):
"""处理新增项目请求 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
project_qs = Project.objects.all()
seriali... | stack_v2_sparse_classes_75kplus_train_007150 | 1,850 | no_license | [
{
"docstring": "处理查询项目请求 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "处理新增项目请求 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045176 | Implement the Python class `ProjectsList` described below.
Class description:
Implement the ProjectsList class.
Method signatures and docstrings:
- def get(self, request): 处理查询项目请求 :param request: :return:
- def post(self, request): 处理新增项目请求 :param request: :return: | Implement the Python class `ProjectsList` described below.
Class description:
Implement the ProjectsList class.
Method signatures and docstrings:
- def get(self, request): 处理查询项目请求 :param request: :return:
- def post(self, request): 处理新增项目请求 :param request: :return:
<|skeleton|>
class ProjectsList:
def get(self... | 1c478cee2e60905736eab57e97023472bb8d2e7e | <|skeleton|>
class ProjectsList:
def get(self, request):
"""处理查询项目请求 :param request: :return:"""
<|body_0|>
def post(self, request):
"""处理新增项目请求 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectsList:
def get(self, request):
"""处理查询项目请求 :param request: :return:"""
project_qs = Project.objects.all()
serializer = ProjectModelSerializer(instance=project_qs, many=True)
return JsonResponse(serializer.data, safe=False)
def post(self, request):
"""处理新增项目请... | the_stack_v2_python_sparse | apps/vuetest/views.py | MoloryXiao/QA_platform | train | 0 | |
454e693ba128413c4932d0eaaa442ba159c9b180 | [
"if training_type == TrainingType.NLU:\n core_required = False\n core_target = None\nelse:\n core_required = True\n core_target = config.get('core_target')\nnlu_target = config.get('nlu_target')\nif nlu_target is None or (core_required and core_target is None):\n raise InvalidConfigException(\"Can't ... | <|body_start_0|>
if training_type == TrainingType.NLU:
core_required = False
core_target = None
else:
core_required = True
core_target = config.get('core_target')
nlu_target = config.get('nlu_target')
if nlu_target is None or (core_required... | Recipe which converts the graph model config to train and predict graph. | GraphV1Recipe | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `co... | stack_v2_sparse_classes_75kplus_train_007151 | 3,301 | permissive | [
{
"docstring": "Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `core_target` as fixed values of `run_RegexMessageHandler` and `select_prediction` respectively. For graph recipe, target values are customizable. These can be used in validation (default recipe doe... | 2 | stack_v2_sparse_classes_30k_train_025959 | Implement the Python class `GraphV1Recipe` described below.
Class description:
Recipe which converts the graph model config to train and predict graph.
Method signatures and docstrings:
- def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]: Return NLU and core targets from config dict... | Implement the Python class `GraphV1Recipe` described below.
Class description:
Recipe which converts the graph model config to train and predict graph.
Method signatures and docstrings:
- def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]: Return NLU and core targets from config dict... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphV1Recipe:
"""Recipe which converts the graph model config to train and predict graph."""
def get_targets(self, config: Dict, training_type: TrainingType) -> Tuple[Text, Any]:
"""Return NLU and core targets from config dictionary. Note that default recipe has `nlu_target` and `core_target` as... | the_stack_v2_python_sparse | rasa/engine/recipes/graph_recipe.py | RasaHQ/rasa | train | 13,167 |
ac86efb5679a74153515a92f69c7d05151a62ffd | [
"super(ExportWindow, self).__init__(parent)\nself.gridCheckBox = QtGui.QCheckBox(self.tr('Save with grid'))\nself.namesCheckBox = QtGui.QCheckBox(self.tr('Save with names'))\nself.gridCheckBox.setChecked(True)\nself.namesCheckBox.setChecked(True)\nchooseButton = QtGui.QPushButton('Select File')\nlayout = QtGui.QVBo... | <|body_start_0|>
super(ExportWindow, self).__init__(parent)
self.gridCheckBox = QtGui.QCheckBox(self.tr('Save with grid'))
self.namesCheckBox = QtGui.QCheckBox(self.tr('Save with names'))
self.gridCheckBox.setChecked(True)
self.namesCheckBox.setChecked(True)
chooseButton ... | ExportWindow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportWindow:
def __init__(self, parent=None):
"""Create an export window to save the current canvas as an image."""
<|body_0|>
def chooseFile(self):
"""Pop up a file dialog box to determine a save filename, then save it."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_007152 | 2,229 | permissive | [
{
"docstring": "Create an export window to save the current canvas as an image.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Pop up a file dialog box to determine a save filename, then save it.",
"name": "chooseFile",
"signature": "def chooseFil... | 2 | stack_v2_sparse_classes_30k_val_001472 | Implement the Python class `ExportWindow` described below.
Class description:
Implement the ExportWindow class.
Method signatures and docstrings:
- def __init__(self, parent=None): Create an export window to save the current canvas as an image.
- def chooseFile(self): Pop up a file dialog box to determine a save file... | Implement the Python class `ExportWindow` described below.
Class description:
Implement the ExportWindow class.
Method signatures and docstrings:
- def __init__(self, parent=None): Create an export window to save the current canvas as an image.
- def chooseFile(self): Pop up a file dialog box to determine a save file... | d095076113c1e84c33f52ef46a3df1f8bc8ffa43 | <|skeleton|>
class ExportWindow:
def __init__(self, parent=None):
"""Create an export window to save the current canvas as an image."""
<|body_0|>
def chooseFile(self):
"""Pop up a file dialog box to determine a save filename, then save it."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExportWindow:
def __init__(self, parent=None):
"""Create an export window to save the current canvas as an image."""
super(ExportWindow, self).__init__(parent)
self.gridCheckBox = QtGui.QCheckBox(self.tr('Save with grid'))
self.namesCheckBox = QtGui.QCheckBox(self.tr('Save with... | the_stack_v2_python_sparse | frontend/src/gbuilder/UI/ExportWindow.py | citelab/gini5 | train | 12 | |
bfa0457e263c20e92bf7be278d54247cc18aa0db | [
"m, n = (len(nums1), len(nums2))\nif m > n:\n return self.findMediaSortedArrays(nums2, nums1)\nif m == 0:\n return 0.5 * (nums2[(n - 1) // 2] + nums[n // 2])\ncut = (m + n) // 2\nlo, hi = (0, m)\nMIN, MAX = (float('-inf'), float('inf'))\nwhile True:\n cut1 = lo + (hi - lo) // 2\n cut2 = cut - cut1\n ... | <|body_start_0|>
m, n = (len(nums1), len(nums2))
if m > n:
return self.findMediaSortedArrays(nums2, nums1)
if m == 0:
return 0.5 * (nums2[(n - 1) // 2] + nums[n // 2])
cut = (m + n) // 2
lo, hi = (0, m)
MIN, MAX = (float('-inf'), float('inf'))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float:
"""binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(... | stack_v2_sparse_classes_75kplus_train_007153 | 2,528 | no_license | [
{
"docstring": "binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(log(min(m, n))) space: O(1)",
"name": "findMediaSortedArrays1",
"signature": "def findMediaS... | 2 | stack_v2_sparse_classes_30k_train_048464 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(num... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float: binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(num... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float:
"""binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMediaSortedArrays1(self, nums1: List[int], nums2: List[int]) -> float:
"""binary search: search cutting points cut1 & cut2 in nums1 and nums2 so that cut1 + cut2 == (len(nums1) + len(nums2)) // 2 and nums1[cut1-1] <= nums2[cut2] and nums1[cut1] >= nums2[cut2-1] time: O(log(min(m, n))... | the_stack_v2_python_sparse | Leetcode 0004. Median of Two Sorted Arrays.py | Chaoran-sjsu/leetcode | train | 0 | |
a4254479ee9ae1661f588d95bf8a1a5f8405f8f4 | [
"best_data = {'cuisine_primary': ['thai'], 'restaurant': ['thai garden'], 'boro': ['manhattan'], 'swc_type': ['no cafe'], 'score': [0], 'grade': ['a'], 'inspectiondate': ['1/2/2014']}\nbest_restaurant = pd.DataFrame(best_data, columns=['cuisine_primary', 'restaurant', 'boro', 'swc_type', 'score', 'grade', 'inspecti... | <|body_start_0|>
best_data = {'cuisine_primary': ['thai'], 'restaurant': ['thai garden'], 'boro': ['manhattan'], 'swc_type': ['no cafe'], 'score': [0], 'grade': ['a'], 'inspectiondate': ['1/2/2014']}
best_restaurant = pd.DataFrame(best_data, columns=['cuisine_primary', 'restaurant', 'boro', 'swc_type', ... | Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually | GetBestAndWorstDataTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetBestAndWorstDataTests:
"""Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually"""
def test_get_best_data(self):
"""Test that the fun... | stack_v2_sparse_classes_75kplus_train_007154 | 6,403 | no_license | [
{
"docstring": "Test that the function correctly returns the observations of the best restaurant",
"name": "test_get_best_data",
"signature": "def test_get_best_data(self)"
},
{
"docstring": "Test that the function correctly returns the observations of the worst restaurant",
"name": "test_ge... | 2 | stack_v2_sparse_classes_30k_train_004368 | Implement the Python class `GetBestAndWorstDataTests` described below.
Class description:
Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually
Method signatures and docs... | Implement the Python class `GetBestAndWorstDataTests` described below.
Class description:
Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually
Method signatures and docs... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class GetBestAndWorstDataTests:
"""Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually"""
def test_get_best_data(self):
"""Test that the fun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetBestAndWorstDataTests:
"""Check that get_best_and_worst_data returns the DataFrames of the best and worst restaurants Note: To check for equality of a tuple (DataFrame, DataFrame), I unpack and check each DataFrame individually"""
def test_get_best_data(self):
"""Test that the function correct... | the_stack_v2_python_sparse | lh1036/test_inspectiongrades/test_visualizer.py | ds-ga-1007/final_project | train | 0 |
6d8964c999013cf9977488687b806acf9a02c107 | [
"shots = 100\ncircuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)\ntargets = ref_unitary_gate.unitary_gate_counts_deterministic(shots)\nresult = execute(circuits, self.SIMULATOR, shots=shots).result()\nself.assertTrue(getattr(result, 'success', False))\nself.compare_counts(result, ci... | <|body_start_0|>
shots = 100
circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)
targets = ref_unitary_gate.unitary_gate_counts_deterministic(shots)
result = execute(circuits, self.SIMULATOR, shots=shots).result()
self.assertTrue(getattr(result, 's... | QasmSimulator additional tests. | QasmUnitaryGateTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_random_unitary_gate(self):
"""Test simulation with random unitary gate circuit instructions.... | stack_v2_sparse_classes_75kplus_train_007155 | 3,511 | permissive | [
{
"docstring": "Test simulation with unitary gate circuit instructions.",
"name": "test_unitary_gate",
"signature": "def test_unitary_gate(self)"
},
{
"docstring": "Test simulation with random unitary gate circuit instructions.",
"name": "test_random_unitary_gate",
"signature": "def test... | 2 | stack_v2_sparse_classes_30k_train_034014 | Implement the Python class `QasmUnitaryGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_unitary_gate(self): Test simulation with unitary gate circuit instructions.
- def test_random_unitary_gate(self): Test simulation with random unitary gate ... | Implement the Python class `QasmUnitaryGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_unitary_gate(self): Test simulation with unitary gate circuit instructions.
- def test_random_unitary_gate(self): Test simulation with random unitary gate ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_random_unitary_gate(self):
"""Test simulation with random unitary gate circuit instructions.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QasmUnitaryGateTests:
"""QasmSimulator additional tests."""
def test_unitary_gate(self):
"""Test simulation with unitary gate circuit instructions."""
shots = 100
circuits = ref_unitary_gate.unitary_gate_circuits_deterministic(final_measure=True)
targets = ref_unitary_gate... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits/qiskit-aer/qiskit-aer#707/before/qasm_unitary_gate.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
dea401cc1c16a3e7a12c29295471c8937a0dfc33 | [
"dp = [[1] * n] * m\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn dp[m - 1][n - 1]",
"res = 1\nfor num in range(n, m + n - 1):\n res *= num\nfor num in range(1, m):\n res //= num\nreturn res"
] | <|body_start_0|>
dp = [[1] * n] * m
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
<|end_body_0|>
<|body_start_1|>
res = 1
for num in range(n, m + n - 1):
res *= num
for n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[1] * n] * m
for i in ... | stack_v2_sparse_classes_75kplus_train_007156 | 671 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths1",
"signature": "def uniquePaths1(self, m, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034902 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths1(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths1(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:
def un... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
dp = [[1] * n] * m
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
def uniquePaths1(self, m, n):
... | the_stack_v2_python_sparse | leetcode/062不同路径.py | ShawDa/Coding | train | 0 | |
4d7659709d701132b3d2541a59d3e524eaf31836 | [
"if hsp_ev.dtype == torch.float32:\n eps = 1e-07\nelif hsp_ev.dtype == torch.float64:\n eps = 1e-16\nhsp = hsp_ev / ev\nc = hsp < 0.0\nd1 = (torch.abs(hsp) / D1 ** 2) ** (1.0 / 3.0)\nd1[c] *= -1.0\nd2 = d1 + 0.04\nfor i in range(1, 6):\n hsp1 = 0.5 * d1 - 0.5 / torch.sqrt(4.0 * D1 ** 2 + 1.0 / d1 ** 2)\n ... | <|body_start_0|>
if hsp_ev.dtype == torch.float32:
eps = 1e-07
elif hsp_ev.dtype == torch.float64:
eps = 1e-16
hsp = hsp_ev / ev
c = hsp < 0.0
d1 = (torch.abs(hsp) / D1 ** 2) ** (1.0 / 3.0)
d1[c] *= -1.0
d2 = d1 + 0.04
for i in rang... | additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f | additive_term_rho1 | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class additive_term_rho1:
"""additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f"""
def forward(ctx, hsp_ev, D1):
"""hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] hsp = [mu_pi, mu_pi] rho1 = 1/(2d) hsp = e^2 ( d/2 - 1/2/s... | stack_v2_sparse_classes_75kplus_train_007157 | 6,196 | permissive | [
{
"docstring": "hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] hsp = [mu_pi, mu_pi] rho1 = 1/(2d) hsp = e^2 ( d/2 - 1/2/sqrt( 4 * D1^2 + 1/d^2)) D1 : dipole charge separation, ( dd in mopac ) D1: in atomic unit hsp in atomic units hsp_ev : shape (n_atoms,) D1 : shape (... | 2 | stack_v2_sparse_classes_30k_train_031292 | Implement the Python class `additive_term_rho1` described below.
Class description:
additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f
Method signatures and docstrings:
- def forward(ctx, hsp_ev, D1): hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] h... | Implement the Python class `additive_term_rho1` described below.
Class description:
additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f
Method signatures and docstrings:
- def forward(ctx, hsp_ev, D1): hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] h... | dfda08400bb1328ce6cd45ac6b1dd3e7f9d7d4a6 | <|skeleton|>
class additive_term_rho1:
"""additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f"""
def forward(ctx, hsp_ev, D1):
"""hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] hsp = [mu_pi, mu_pi] rho1 = 1/(2d) hsp = e^2 ( d/2 - 1/2/s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class additive_term_rho1:
"""additive term rho1, rho1 = 1.0/(2*ad) : ad or add(,2) or d in mopac calpar.f"""
def forward(ctx, hsp_ev, D1):
"""hsp_ev : hsp in unit eV hsp_A = (s_A p_alpha_A, s_A p_alpha_A) = [mu_alpha_A, mu_alpha_A] hsp = [mu_pi, mu_pi] rho1 = 1/(2d) hsp = e^2 ( d/2 - 1/2/sqrt( 4 * D1^2... | the_stack_v2_python_sparse | PYSEQM/seqm/seqm_functions/cal_par.py | roehr-lab/SFast-Singlet-Fission-adiabatic-basis-screening | train | 2 |
eaa1426ff468283976dfa51c5ad9016987df4c6d | [
"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... | ////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ////////////////////////////////////////////////////////////////////////////// | TPUProfileAnalysisServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TPUProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ////////////////////////////////////////////////////////////////... | stack_v2_sparse_classes_75kplus_train_007158 | 4,726 | permissive | [
{
"docstring": "Starts a profiling session, blocks until it completes. TPUProfileAnalysis service delegate this to TPUProfiler service. Populate the profiled data in repository, then return status to caller.",
"name": "NewSession",
"signature": "def NewSession(self, request, context)"
},
{
"docs... | 3 | null | Implement the Python class `TPUProfileAnalysisServicer` described below.
Class description:
////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC /////////////////////////... | Implement the Python class `TPUProfileAnalysisServicer` described below.
Class description:
////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC /////////////////////////... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class TPUProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ////////////////////////////////////////////////////////////////... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TPUProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// TPUProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC /////////////////////////////////////////////////////////////////////////////... | the_stack_v2_python_sparse | Keras_tensorflow_nightly/source2.7/tensorflow/contrib/tpu/profiler/tpu_profiler_analysis_pb2_grpc.py | ryfeus/lambda-packs | train | 1,283 |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"q = quantity.Mass(1.0, 'kg')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'kg')",
"q = quantity.Mass(1.0, 'g/mol')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, constants.amu, delta=1e-32)\nself.assertEqua... | <|body_start_0|>
q = quantity.Mass(1.0, 'kg')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
self.assertEqual(q.units, 'kg')
<|end_body_0|>
<|body_start_1|>
q = quantity.Mass(1.0, 'g/mol')
self.assertAlmostEqual(q.value, 1.0,... | Contains unit tests of the Mass unit type object. | TestMass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMass:
"""Contains unit tests of the Mass unit type object."""
def test_kg(self):
"""Test the creation of a mass quantity with units of kg."""
<|body_0|>
def test_gpermol(self):
"""Test the creation of a mass quantity with units of g/mol. Note that g/mol is au... | stack_v2_sparse_classes_75kplus_train_007159 | 33,010 | permissive | [
{
"docstring": "Test the creation of a mass quantity with units of kg.",
"name": "test_kg",
"signature": "def test_kg(self)"
},
{
"docstring": "Test the creation of a mass quantity with units of g/mol. Note that g/mol is automatically coerced to amu.",
"name": "test_gpermol",
"signature"... | 4 | stack_v2_sparse_classes_30k_train_003869 | Implement the Python class `TestMass` described below.
Class description:
Contains unit tests of the Mass unit type object.
Method signatures and docstrings:
- def test_kg(self): Test the creation of a mass quantity with units of kg.
- def test_gpermol(self): Test the creation of a mass quantity with units of g/mol. ... | Implement the Python class `TestMass` described below.
Class description:
Contains unit tests of the Mass unit type object.
Method signatures and docstrings:
- def test_kg(self): Test the creation of a mass quantity with units of kg.
- def test_gpermol(self): Test the creation of a mass quantity with units of g/mol. ... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestMass:
"""Contains unit tests of the Mass unit type object."""
def test_kg(self):
"""Test the creation of a mass quantity with units of kg."""
<|body_0|>
def test_gpermol(self):
"""Test the creation of a mass quantity with units of g/mol. Note that g/mol is au... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMass:
"""Contains unit tests of the Mass unit type object."""
def test_kg(self):
"""Test the creation of a mass quantity with units of kg."""
q = quantity.Mass(1.0, 'kg')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
cde48fe20f7302f880a144c56ca76ac16788e90a | [
"if mode != 'one_vs_all' and mode != 'all_vs_all':\n raise TypeError(\"Wrong value for argument mode, should be either 'one_vs_all', or 'all_vs_all', but \" + str(mode) + ' given')\nself.mode = mode\nself.kwargs = kwargs\nself.classifier = classifier",
"self.binary_classifiers = []\nself.num_of... | <|body_start_0|>
if mode != 'one_vs_all' and mode != 'all_vs_all':
raise TypeError("Wrong value for argument mode, should be either 'one_vs_all', or 'all_vs_all', but " + str(mode) + ' given')
self.mode = mode
self.kwargs = kwargs
self.classifier = classifier
... | MulticlassStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MulticlassStrategy:
def __init__(self, classifier, mode='one_vs_all', **kwargs):
"""Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - способ решения многоклассовой задачи, либо 'one_vs_all', либо 'all_vs_all' **kwargs - параметры классификат... | stack_v2_sparse_classes_75kplus_train_007160 | 3,192 | no_license | [
{
"docstring": "Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - способ решения многоклассовой задачи, либо 'one_vs_all', либо 'all_vs_all' **kwargs - параметры классификатор",
"name": "__init__",
"signature": "def __init__(self, classifier, mode='one_vs_a... | 3 | stack_v2_sparse_classes_30k_train_007788 | Implement the Python class `MulticlassStrategy` described below.
Class description:
Implement the MulticlassStrategy class.
Method signatures and docstrings:
- def __init__(self, classifier, mode='one_vs_all', **kwargs): Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - ... | Implement the Python class `MulticlassStrategy` described below.
Class description:
Implement the MulticlassStrategy class.
Method signatures and docstrings:
- def __init__(self, classifier, mode='one_vs_all', **kwargs): Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - ... | 817ea6d03b68d6db7edbcb11cc44bbb08993dc4f | <|skeleton|>
class MulticlassStrategy:
def __init__(self, classifier, mode='one_vs_all', **kwargs):
"""Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - способ решения многоклассовой задачи, либо 'one_vs_all', либо 'all_vs_all' **kwargs - параметры классификат... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MulticlassStrategy:
def __init__(self, classifier, mode='one_vs_all', **kwargs):
"""Инициализация мультиклассового классификатора classifier - базовый бинарный классификатор mode - способ решения многоклассовой задачи, либо 'one_vs_all', либо 'all_vs_all' **kwargs - параметры классификатор"""
... | the_stack_v2_python_sparse | Machine_Learning/Logistic_regression/multiclass.py | MichaelSolotky/sandbox | train | 0 | |
3c84ca4fa420335d54a90e4f610938c8eb382f5a | [
"self.filename = filename\nself.step = depend_value(name='step', value=step)\nself.stride = stride\nself.overwrite = overwrite\nself._storing = False\nself._continued = False",
"self.simul = simul\nimport ipi.inputs.simulation as isimulation\nself.status = isimulation.InputSimulation()\nself.status.store(simul)",... | <|body_start_0|>
self.filename = filename
self.step = depend_value(name='step', value=step)
self.stride = stride
self.overwrite = overwrite
self._storing = False
self._continued = False
<|end_body_0|>
<|body_start_1|>
self.simul = simul
import ipi.inputs.... | Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. stride: The number of steps that should be taken between outputting the data to file. ... | CheckpointOutput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckpointOutput:
"""Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. stride: The number of steps that should be... | stack_v2_sparse_classes_75kplus_train_007161 | 22,634 | no_license | [
{
"docstring": "Initializes a checkpoint output proxy. Args: filename: A string giving the name of the file to be output to. stride: An integer giving how many steps should be taken between outputting the data to file. overwrite: If True, the checkpoint file is overwritten at each output. If False, will output ... | 4 | stack_v2_sparse_classes_30k_train_029979 | Implement the Python class `CheckpointOutput` described below.
Class description:
Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. str... | Implement the Python class `CheckpointOutput` described below.
Class description:
Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. str... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class CheckpointOutput:
"""Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. stride: The number of steps that should be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckpointOutput:
"""Class dealing with outputting checkpoints. Saves the complete status of the simulation at regular intervals. Attributes: filename: The (base) name of the file to output to. step: the number of times a checkpoint has been written out. stride: The number of steps that should be taken betwee... | the_stack_v2_python_sparse | ipi/engine/outputs.py | i-pi/i-pi | train | 170 |
7aa7648d28ee75acacd20eb3ab5a8fcfa42b15c0 | [
"self.xdrtype = xdrtype\nself.xdrdir = xdrdir\nself.localdir = localdir\nself.suffix = suffix\nfileprefix = 'SC_CD_MOBILE_CNOS_NOKIA_CXDR_RNC003_0005_'\nxdrpath = os.path.join(localdir, self.xdrdate, self.xdrhour, xdrdir)\nlogtime = time.ctime()\nfiletime = []\ntag = []\nsmallfile = []\nlogging.basicConfig(filename... | <|body_start_0|>
self.xdrtype = xdrtype
self.xdrdir = xdrdir
self.localdir = localdir
self.suffix = suffix
fileprefix = 'SC_CD_MOBILE_CNOS_NOKIA_CXDR_RNC003_0005_'
xdrpath = os.path.join(localdir, self.xdrdate, self.xdrhour, xdrdir)
logtime = time.ctime()
... | rename and compress file | groupfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class groupfile:
"""rename and compress file"""
def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt'):
"""rename the original files to the specified filename format"""
<|body_0|>
def compress(self, path, destpath):
"""compress the files w... | stack_v2_sparse_classes_75kplus_train_007162 | 6,037 | no_license | [
{
"docstring": "rename the original files to the specified filename format",
"name": "renamefile",
"signature": "def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt')"
},
{
"docstring": "compress the files with gzip and after compress them rename the orignal files ... | 3 | stack_v2_sparse_classes_30k_train_003642 | Implement the Python class `groupfile` described below.
Class description:
rename and compress file
Method signatures and docstrings:
- def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt'): rename the original files to the specified filename format
- def compress(self, path, destpath):... | Implement the Python class `groupfile` described below.
Class description:
rename and compress file
Method signatures and docstrings:
- def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt'): rename the original files to the specified filename format
- def compress(self, path, destpath):... | dacc8890c286d067fbc6ed4e537cc50c8ee0a199 | <|skeleton|>
class groupfile:
"""rename and compress file"""
def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt'):
"""rename the original files to the specified filename format"""
<|body_0|>
def compress(self, path, destpath):
"""compress the files w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class groupfile:
"""rename and compress file"""
def renamefile(self, xdrtype, xdrdir, localdir='/data04/unicom/group', suffix='txt'):
"""rename the original files to the specified filename format"""
self.xdrtype = xdrtype
self.xdrdir = xdrdir
self.localdir = localdir
sel... | the_stack_v2_python_sparse | renamexdr_class.py | xiaojun54767193/python | train | 0 |
1f01821d795caa3754debb587a47ffc57bc9e977 | [
"self.numInputs = numInputs\nself.hiddenLayerSize1 = hiddenLayerSize1\nself.hiddenLayerSize2 = hiddenLayerSize2\nself.bias = bias\nif bias:\n inputSize = numInputs + 1\nelse:\n inputSize = numInputs\nif randomize:\n self.w1 = np.random.rand(hiddenLayerSize1, inputSize) * 2.0 - 1.0\nelse:\n self.w1 = np.... | <|body_start_0|>
self.numInputs = numInputs
self.hiddenLayerSize1 = hiddenLayerSize1
self.hiddenLayerSize2 = hiddenLayerSize2
self.bias = bias
if bias:
inputSize = numInputs + 1
else:
inputSize = numInputs
if randomize:
self.w1 ... | TwoHiddenLayerNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoHiddenLayerNetwork:
def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True):
"""Create the Two Hidden Layer Network with the above specifications to test capability of a two hidden layer network."""
<|body_0|>
def evaluateHidden1(self,... | stack_v2_sparse_classes_75kplus_train_007163 | 7,257 | no_license | [
{
"docstring": "Create the Two Hidden Layer Network with the above specifications to test capability of a two hidden layer network.",
"name": "__init__",
"signature": "def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True)"
},
{
"docstring": "Evaluate the ou... | 4 | stack_v2_sparse_classes_30k_train_017445 | Implement the Python class `TwoHiddenLayerNetwork` described below.
Class description:
Implement the TwoHiddenLayerNetwork class.
Method signatures and docstrings:
- def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True): Create the Two Hidden Layer Network with the above specifi... | Implement the Python class `TwoHiddenLayerNetwork` described below.
Class description:
Implement the TwoHiddenLayerNetwork class.
Method signatures and docstrings:
- def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True): Create the Two Hidden Layer Network with the above specifi... | 9513364782676a3a0a73253040d86d5f7329a1c2 | <|skeleton|>
class TwoHiddenLayerNetwork:
def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True):
"""Create the Two Hidden Layer Network with the above specifications to test capability of a two hidden layer network."""
<|body_0|>
def evaluateHidden1(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoHiddenLayerNetwork:
def __init__(self, numInputs, hiddenLayerSize1, hiddenLayerSize2, randomize=True, bias=True):
"""Create the Two Hidden Layer Network with the above specifications to test capability of a two hidden layer network."""
self.numInputs = numInputs
self.hiddenLayerSize... | the_stack_v2_python_sparse | 4. MLP Representational Capabilities/4.1 Representational Capability/TwoHiddenLayerCapability.py | jlehett/Neural-Smithing | train | 5 | |
2d2be295ae22ec7be495e9bebc28f5283928e949 | [
"self.base = base\nval = ''\nallowed_chars = self.ALLOWED[:self.base]\nif default is not None:\n if not isinstance(default, (int, str, Decimal)):\n raise ValueError(\"default: Only 'str', 'int', 'long' or Decimal input allowed\")\n if isinstance(default, str) and len(default):\n validation_re = ... | <|body_start_0|>
self.base = base
val = ''
allowed_chars = self.ALLOWED[:self.base]
if default is not None:
if not isinstance(default, (int, str, Decimal)):
raise ValueError("default: Only 'str', 'int', 'long' or Decimal input allowed")
if isinstan... | Edit widget for integer values | IntegerEdit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (1... | stack_v2_sparse_classes_75kplus_train_007164 | 10,901 | permissive | [
{
"docstring": "caption -- caption markup default -- default edit value >>> IntegerEdit(u\"\", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u\"\", \"5002\"), (10,) >>> e.keypress(size, 'home') >>> e.keypress(size, 'delete') >>> assert e.edit_text == \"002\" >>> e.keypress(s... | 2 | stack_v2_sparse_classes_30k_train_001342 | Implement the Python class `IntegerEdit` described below.
Class description:
Edit widget for integer values
Method signatures and docstrings:
- def __init__(self, caption='', default=None, base=10): caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '4... | Implement the Python class `IntegerEdit` described below.
Class description:
Edit widget for integer values
Method signatures and docstrings:
- def __init__(self, caption='', default=None, base=10): caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '4... | 95b7a061eabd6f2b607fba79e007186030f02720 | <|skeleton|>
class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntegerEdit:
"""Edit widget for integer values"""
def __init__(self, caption='', default=None, base=10):
"""caption -- caption markup default -- default edit value >>> IntegerEdit(u"", 42) <IntegerEdit selectable flow widget '42' edit_pos=2> >>> e, size = IntegerEdit(u"", "5002"), (10,) >>> e.key... | the_stack_v2_python_sparse | Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/urwid/numedit.py | icl-rocketry/Avionics | train | 9 |
6df697adb842146ff1c3a990d01a971a2d1cc8a6 | [
"directory = os.path.dirname(__file__)\npg_loc = directory + f'{os.path.sep}knitspeak.pg'\nself._grammar = Grammar.from_file(pg_loc, debug=debugGrammar, ignore_case=True)\nself.parser = Parser(self._grammar, debug=debugParser, debug_layout=debugParserLayout)\nself.parser.symbolTable = Symbol_Table()",
"if pattern... | <|body_start_0|>
directory = os.path.dirname(__file__)
pg_loc = directory + f'{os.path.sep}knitspeak.pg'
self._grammar = Grammar.from_file(pg_loc, debug=debugGrammar, ignore_case=True)
self.parser = Parser(self._grammar, debug=debugParser, debug_layout=debugParserLayout)
self.par... | A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to | KnitSpeak_Interpreter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnitSpeak_Interpreter:
"""A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to"""
def __init__(self, debugGrammar: bool=False, debugParser: bool=False, debugParserLayout: bool=False):
"""Initiali... | stack_v2_sparse_classes_75kplus_train_007165 | 1,687 | no_license | [
{
"docstring": "Initializes a parser :param debugGrammar: If true, parglare is set to debug mode :param debugParser: if true, parglare parser is set to debug mod :param debugParserLayout: if true, parser layout is debuggable",
"name": "__init__",
"signature": "def __init__(self, debugGrammar: bool=False... | 2 | stack_v2_sparse_classes_30k_train_037124 | Implement the Python class `KnitSpeak_Interpreter` described below.
Class description:
A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to
Method signatures and docstrings:
- def __init__(self, debugGrammar: bool=False, debugPar... | Implement the Python class `KnitSpeak_Interpreter` described below.
Class description:
A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to
Method signatures and docstrings:
- def __init__(self, debugGrammar: bool=False, debugPar... | 136cde8d63152155c634f3b0680b53c1fd56775a | <|skeleton|>
class KnitSpeak_Interpreter:
"""A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to"""
def __init__(self, debugGrammar: bool=False, debugParser: bool=False, debugParserLayout: bool=False):
"""Initiali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnitSpeak_Interpreter:
"""A class to manage parsing a knit speak file with parglare ... Attributes ---------- parser: the parglare Parser that we add a symbol table to"""
def __init__(self, debugGrammar: bool=False, debugParser: bool=False, debugParserLayout: bool=False):
"""Initializes a parser ... | the_stack_v2_python_sparse | knitspeak_compiler/knitspeak_interpreter/knitspeak_interpreter.py | mhofmann-uw/599-Knitting-Assignments | train | 0 |
315aeb068bfa0b183aee932f6d6aa48e145030f1 | [
"board = state.board\nfor row in range(0, board.row):\n for col in range(0, board.col):\n if state.is_tile_available((row, col)):\n return (row, col)\nreturn False",
"num_players = len(tree.get_state().players)\nlayers = num_turns * num_players\nmax_player = tree.get_current_player_color()\na... | <|body_start_0|>
board = state.board
for row in range(0, board.row):
for col in range(0, board.col):
if state.is_tile_available((row, col)):
return (row, col)
return False
<|end_body_0|>
<|body_start_1|>
num_players = len(tree.get_state().... | Strategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Strategy:
def place_penguin_across(self, state):
"""Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across the board from left to right, and down a row when the row is filled. Assume that the board is larg... | stack_v2_sparse_classes_75kplus_train_007166 | 6,759 | no_license | [
{
"docstring": "Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across the board from left to right, and down a row when the row is filled. Assume that the board is large enough to accommodate all penguins. If there are not enoug... | 5 | stack_v2_sparse_classes_30k_train_002686 | Implement the Python class `Strategy` described below.
Class description:
Implement the Strategy class.
Method signatures and docstrings:
- def place_penguin_across(self, state): Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across t... | Implement the Python class `Strategy` described below.
Class description:
Implement the Strategy class.
Method signatures and docstrings:
- def place_penguin_across(self, state): Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across t... | 4b25c864d1af9d4ea14f8d033dc042157efac1f8 | <|skeleton|>
class Strategy:
def place_penguin_across(self, state):
"""Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across the board from left to right, and down a row when the row is filled. Assume that the board is larg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Strategy:
def place_penguin_across(self, state):
"""Places penguin at next available spot. The search for the next available spot on the board starts in the top left corner and moves across the board from left to right, and down a row when the row is filled. Assume that the board is large enough to ac... | the_stack_v2_python_sparse | Fish/Player/strategy.py | jdowning27/CS4500-Software-Development | train | 0 | |
4fb231d25e0abd576d2235e6dbfaf8ad8ad3b960 | [
"ans = []\nself.permuteHelper(ans, [], nums)\nreturn ans",
"if len(permuteTemp) == len(nums):\n answer.append(permuteTemp.copy())\nelse:\n for i in nums:\n if i in permuteTemp:\n continue\n else:\n permuteTemp.append(i)\n self.permuteHelper(answer, permuteTemp,... | <|body_start_0|>
ans = []
self.permuteHelper(ans, [], nums)
return ans
<|end_body_0|>
<|body_start_1|>
if len(permuteTemp) == len(nums):
answer.append(permuteTemp.copy())
else:
for i in nums:
if i in permuteTemp:
contin... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteHelper(self, answer, permuteTemp, nums):
""":type answer: List[List[int]] :type permuteTemp: List[int] :type nums: List[int]"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_007167 | 1,121 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": ":type answer: List[List[int]] :type permuteTemp: List[int] :type nums: List[int]",
"name": "permuteHelper",
"signature": "def permuteHelper(self, a... | 2 | stack_v2_sparse_classes_30k_train_018518 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteHelper(self, answer, permuteTemp, nums): :type answer: List[List[int]] :type permuteTemp: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteHelper(self, answer, permuteTemp, nums): :type answer: List[List[int]] :type permuteTemp: List... | da1774fd07b7326e66d9478b3d2619e0499ac2b7 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteHelper(self, answer, permuteTemp, nums):
""":type answer: List[List[int]] :type permuteTemp: List[int] :type nums: List[int]"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
ans = []
self.permuteHelper(ans, [], nums)
return ans
def permuteHelper(self, answer, permuteTemp, nums):
""":type answer: List[List[int]] :type permuteTemp: List[int] :type nums... | the_stack_v2_python_sparse | Python3/Array/Permutations/Backtracking046.py | daviddwlee84/LeetCode | train | 14 | |
eac5417971633ce3a2982c832dd850dc619b8617 | [
"super().__init__(coordinator)\nself._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, f'{coordinator.latitude}-{coordinator.longitude}')}, manufacturer=MANUFACTURER, name=name, configuration_url=URL.format(latitude=coordinator.latitude, longitude=coordinator.longitude))\nself... | <|body_start_0|>
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, f'{coordinator.latitude}-{coordinator.longitude}')}, manufacturer=MANUFACTURER, name=name, configuration_url=URL.format(latitude=coordinator.latitude, longitude=co... | Define an Airly sensor. | AirlySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirlySensor:
"""Define an Airly sensor."""
def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def _handle_coordinator_update(self) -> None:
"""Handle updated data... | stack_v2_sparse_classes_75kplus_train_007168 | 7,989 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None"
},
{
"docstring": "Handle updated data from the coordinator.",
"name": "_handle_coordinator_update",
... | 2 | stack_v2_sparse_classes_30k_train_022814 | Implement the Python class `AirlySensor` described below.
Class description:
Define an Airly sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None: Initialize.
- def _handle_coordinator_update(self) -> None... | Implement the Python class `AirlySensor` described below.
Class description:
Define an Airly sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None: Initialize.
- def _handle_coordinator_update(self) -> None... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AirlySensor:
"""Define an Airly sensor."""
def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None:
"""Initialize."""
<|body_0|>
def _handle_coordinator_update(self) -> None:
"""Handle updated data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AirlySensor:
"""Define an Airly sensor."""
def __init__(self, coordinator: AirlyDataUpdateCoordinator, name: str, description: AirlySensorEntityDescription) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(entry_type=DeviceEntryType.SERV... | the_stack_v2_python_sparse | homeassistant/components/airly/sensor.py | home-assistant/core | train | 35,501 |
f6ecc30932191511adb31a71cfe95a6ff0bf2ec1 | [
"group_totals = dict()\nfor ocg in OffCycleCredits._offcycle_credit_groups:\n group_totals[ocg] = 0\ncost_cloud['cert_direct_offcycle_co2e_grams_per_mile'] = 0\ncost_cloud['cert_direct_offcycle_kwh_per_mile'] = 0\ncost_cloud['cert_indirect_offcycle_co2e_grams_per_mile'] = 0\nfor credit_column in OffCycleCredits.... | <|body_start_0|>
group_totals = dict()
for ocg in OffCycleCredits._offcycle_credit_groups:
group_totals[ocg] = 0
cost_cloud['cert_direct_offcycle_co2e_grams_per_mile'] = 0
cost_cloud['cert_direct_offcycle_kwh_per_mile'] = 0
cost_cloud['cert_indirect_offcycle_co2e_gram... | **Loads, stores and applies off-cycle credits to vehicle cost clouds** | OffCycleCredits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OffCycleCredits:
"""**Loads, stores and applies off-cycle credits to vehicle cost clouds**"""
def calc_off_cycle_credits(calendar_year, vehicle, cost_cloud):
"""Calculate vehicle off-cycle credits for the vehicle's cost cloud Args: calendar_year (int): the year to calculate credits f... | stack_v2_sparse_classes_75kplus_train_007169 | 11,371 | no_license | [
{
"docstring": "Calculate vehicle off-cycle credits for the vehicle's cost cloud Args: calendar_year (int): the year to calculate credits for, usually the vehicle model year vehicle (Vehicle): the vehicle to apply off-cycle credits to cost_cloud (DataFrame): destination data set for off-cycle credits Returns: c... | 2 | stack_v2_sparse_classes_30k_train_034026 | Implement the Python class `OffCycleCredits` described below.
Class description:
**Loads, stores and applies off-cycle credits to vehicle cost clouds**
Method signatures and docstrings:
- def calc_off_cycle_credits(calendar_year, vehicle, cost_cloud): Calculate vehicle off-cycle credits for the vehicle's cost cloud A... | Implement the Python class `OffCycleCredits` described below.
Class description:
**Loads, stores and applies off-cycle credits to vehicle cost clouds**
Method signatures and docstrings:
- def calc_off_cycle_credits(calendar_year, vehicle, cost_cloud): Calculate vehicle off-cycle credits for the vehicle's cost cloud A... | afe912c57383b9de90ef30820f7977c3367a30c4 | <|skeleton|>
class OffCycleCredits:
"""**Loads, stores and applies off-cycle credits to vehicle cost clouds**"""
def calc_off_cycle_credits(calendar_year, vehicle, cost_cloud):
"""Calculate vehicle off-cycle credits for the vehicle's cost cloud Args: calendar_year (int): the year to calculate credits f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OffCycleCredits:
"""**Loads, stores and applies off-cycle credits to vehicle cost clouds**"""
def calc_off_cycle_credits(calendar_year, vehicle, cost_cloud):
"""Calculate vehicle off-cycle credits for the vehicle's cost cloud Args: calendar_year (int): the year to calculate credits for, usually t... | the_stack_v2_python_sparse | omega_model/policy/offcycle_credits.py | USEPA/EPA_OMEGA_Model | train | 17 |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"super().__init__(*args, **kargs)\nself.set_field_from_dict('token')\nself.fields['token'].help_text = _('Authentication token provided by the external platform.')",
"form_data = super().clean()\nself.store_field_in_dict('token')\nreturn form_data"
] | <|body_start_0|>
super().__init__(*args, **kargs)
self.set_field_from_dict('token')
self.fields['token'].help_text = _('Authentication token provided by the external platform.')
<|end_body_0|>
<|body_start_1|>
form_data = super().clean()
self.store_field_in_dict('token')
... | Form to include a token field. | JSONTokenForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONTokenForm:
"""Form to include a token field."""
def __init__(self, *args, **kargs):
"""Modify the fields with the adequate information."""
<|body_0|>
def clean(self):
"""Verify form values."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sup... | stack_v2_sparse_classes_75kplus_train_007170 | 20,237 | permissive | [
{
"docstring": "Modify the fields with the adequate information.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Verify form values.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012141 | Implement the Python class `JSONTokenForm` described below.
Class description:
Form to include a token field.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Modify the fields with the adequate information.
- def clean(self): Verify form values. | Implement the Python class `JSONTokenForm` described below.
Class description:
Form to include a token field.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Modify the fields with the adequate information.
- def clean(self): Verify form values.
<|skeleton|>
class JSONTokenForm:
"""Form t... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class JSONTokenForm:
"""Form to include a token field."""
def __init__(self, *args, **kargs):
"""Modify the fields with the adequate information."""
<|body_0|>
def clean(self):
"""Verify form values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONTokenForm:
"""Form to include a token field."""
def __init__(self, *args, **kargs):
"""Modify the fields with the adequate information."""
super().__init__(*args, **kargs)
self.set_field_from_dict('token')
self.fields['token'].help_text = _('Authentication token provid... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
23012a8696036d95fa8afae3e4270e0eebb6d056 | [
"if 'doxylink-role' in self.options:\n doxylink_role = self.options['doxylink-role']\nelse:\n doxylink_role = self.env.config['documenteer_autocppapi_doxylink_role']\ntry:\n key = 'documenteer_autocppapi_symbolmaps'\n symbol_map: Union[doxylink.SymbolMap, None] = self.env.config[key][doxylink_role]\nexc... | <|body_start_0|>
if 'doxylink-role' in self.options:
doxylink_role = self.options['doxylink-role']
else:
doxylink_role = self.env.config['documenteer_autocppapi_doxylink_role']
try:
key = 'documenteer_autocppapi_symbolmaps'
symbol_map: Union[doxyli... | The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink. | AutoCppApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoCppApi:
"""The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink."""
def run(self) -> List[nodes.Node]:
"""Execute the directive."""
<|body_0|>
def _make_namespace_section(self, *, prefix: str, heading: str, symbol_map: doxylink... | stack_v2_sparse_classes_75kplus_train_007171 | 9,347 | permissive | [
{
"docstring": "Execute the directive.",
"name": "run",
"signature": "def run(self) -> List[nodes.Node]"
},
{
"docstring": "Create nodes for a section that lists links to APIs under a single C++ namespace (prefix). Parameters ---------- prefix : `str` The API refix to match to symbols. E.g. ``ls... | 3 | stack_v2_sparse_classes_30k_train_034783 | Implement the Python class `AutoCppApi` described below.
Class description:
The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink.
Method signatures and docstrings:
- def run(self) -> List[nodes.Node]: Execute the directive.
- def _make_namespace_section(self, *, prefix: str, he... | Implement the Python class `AutoCppApi` described below.
Class description:
The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink.
Method signatures and docstrings:
- def run(self) -> List[nodes.Node]: Execute the directive.
- def _make_namespace_section(self, *, prefix: str, he... | ae9d024902f85a18870ffa10240cd5f4ce2f1468 | <|skeleton|>
class AutoCppApi:
"""The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink."""
def run(self) -> List[nodes.Node]:
"""Execute the directive."""
<|body_0|>
def _make_namespace_section(self, *, prefix: str, heading: str, symbol_map: doxylink... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoCppApi:
"""The ``autocppapi`` directive that lists C++ APIs within a namespace, as detected by doxylink."""
def run(self) -> List[nodes.Node]:
"""Execute the directive."""
if 'doxylink-role' in self.options:
doxylink_role = self.options['doxylink-role']
else:
... | the_stack_v2_python_sparse | src/documenteer/ext/autocppapi.py | lsst-sqre/documenteer | train | 5 |
f118a02db607a03675f0aa31ebedeadbce0b314b | [
"self.session.login()\nself.session.write('\\r')\nr = self.session.expect_prompt()\nself.session.write('set session pager disabled timeout disabled')\nr = self.session.expect_prompt()\nself.session.write('\\r')\nr = self.session.expect_prompt()\nif r[0] < 0:\n print('CD Router login failed. session(%s)' % self.s... | <|body_start_0|>
self.session.login()
self.session.write('\r')
r = self.session.expect_prompt()
self.session.write('set session pager disabled timeout disabled')
r = self.session.expect_prompt()
self.session.write('\r')
r = self.session.expect_prompt()
if ... | APIs for CD Router. | CdrApiClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CdrApiClass:
"""APIs for CD Router."""
def login(self):
"""Description: login to CD Router"""
<|body_0|>
def _send(self, cmd='', timeout=3):
"""Description: (Internal use): Write a command to the object returning the response."""
<|body_1|>
def send(... | stack_v2_sparse_classes_75kplus_train_007172 | 3,815 | no_license | [
{
"docstring": "Description: login to CD Router",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "Description: (Internal use): Write a command to the object returning the response.",
"name": "_send",
"signature": "def _send(self, cmd='', timeout=3)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_005214 | Implement the Python class `CdrApiClass` described below.
Class description:
APIs for CD Router.
Method signatures and docstrings:
- def login(self): Description: login to CD Router
- def _send(self, cmd='', timeout=3): Description: (Internal use): Write a command to the object returning the response.
- def send(self... | Implement the Python class `CdrApiClass` described below.
Class description:
APIs for CD Router.
Method signatures and docstrings:
- def login(self): Description: login to CD Router
- def _send(self, cmd='', timeout=3): Description: (Internal use): Write a command to the object returning the response.
- def send(self... | 47efb2dfe13ace264f8943b59b701f39f23c4c17 | <|skeleton|>
class CdrApiClass:
"""APIs for CD Router."""
def login(self):
"""Description: login to CD Router"""
<|body_0|>
def _send(self, cmd='', timeout=3):
"""Description: (Internal use): Write a command to the object returning the response."""
<|body_1|>
def send(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CdrApiClass:
"""APIs for CD Router."""
def login(self):
"""Description: login to CD Router"""
self.session.login()
self.session.write('\r')
r = self.session.expect_prompt()
self.session.write('set session pager disabled timeout disabled')
r = self.session.e... | the_stack_v2_python_sparse | Gemtek/AutoTest/DropAP/WRTM-326ACN-DropAP2/equipment/cdrouter/cdrouter.py | DarcyChang/MyProjects | train | 0 |
f51c5574567a909cc25c05ffe5e0db3c3f726d46 | [
"super(Oauth20AuthenticationTestCase, self).setUp()\nself.user_logged_in = User.objects.create_user('username', 'user@example.com', 'userpass', last_login=dt.datetime.now())\nauthenticate(username='username', password='userpass')\nself.user_logged_out = User.objects.create_user('out', 'out@example.com', 'userpass')... | <|body_start_0|>
super(Oauth20AuthenticationTestCase, self).setUp()
self.user_logged_in = User.objects.create_user('username', 'user@example.com', 'userpass', last_login=dt.datetime.now())
authenticate(username='username', password='userpass')
self.user_logged_out = User.objects.create_u... | Checks if the oauth authentication class correctly detects users based on the authorization header. | Oauth20AuthenticationTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Oauth20AuthenticationTestCase:
"""Checks if the oauth authentication class correctly detects users based on the authorization header."""
def setUp(self):
"""Creates users and associations with access tokens in extra data. :return:"""
<|body_0|>
def test_authenticated(sel... | stack_v2_sparse_classes_75kplus_train_007173 | 7,826 | permissive | [
{
"docstring": "Creates users and associations with access tokens in extra data. :return:",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "The authentication class should return true when the user identified by the access token has a valid session.",
"name": "test_authent... | 6 | null | Implement the Python class `Oauth20AuthenticationTestCase` described below.
Class description:
Checks if the oauth authentication class correctly detects users based on the authorization header.
Method signatures and docstrings:
- def setUp(self): Creates users and associations with access tokens in extra data. :retu... | Implement the Python class `Oauth20AuthenticationTestCase` described below.
Class description:
Checks if the oauth authentication class correctly detects users based on the authorization header.
Method signatures and docstrings:
- def setUp(self): Creates users and associations with access tokens in extra data. :retu... | 10b5abcb8f5a47d4ba486b18991ffa13bcf60d8a | <|skeleton|>
class Oauth20AuthenticationTestCase:
"""Checks if the oauth authentication class correctly detects users based on the authorization header."""
def setUp(self):
"""Creates users and associations with access tokens in extra data. :return:"""
<|body_0|>
def test_authenticated(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Oauth20AuthenticationTestCase:
"""Checks if the oauth authentication class correctly detects users based on the authorization header."""
def setUp(self):
"""Creates users and associations with access tokens in extra data. :return:"""
super(Oauth20AuthenticationTestCase, self).setUp()
... | the_stack_v2_python_sparse | apps/mds_auth/tests.py | schocco/mds-web | train | 0 |
4801e77db8b0bbef6c5f9abbd3cf226706bc1bae | [
"executor_group = parser.add_argument_group(title='Task Graph Executor')\nexecutor_group.add_argument('-j', '--jobs', type=int, default=None, help='Number of jobs to run in parallel. Defaults to the number of processors on the machine')\nexecutor_group.add_argument('-N', '--dask-cluster-name', '--dcn', dest='dask_c... | <|body_start_0|>
executor_group = parser.add_argument_group(title='Task Graph Executor')
executor_group.add_argument('-j', '--jobs', type=int, default=None, help='Number of jobs to run in parallel. Defaults to the number of processors on the machine')
executor_group.add_argument('-N', '--dask-cl... | Takes care of creating a task graph executor and executing a graph. | TaskGraphCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."... | stack_v2_sparse_classes_75kplus_train_007174 | 6,088 | permissive | [
{
"docstring": "Add arguments needed to execute a task graph.",
"name": "add_arguments",
"signature": "def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None"
},
{
"docstring": "Create a task graph executo... | 3 | stack_v2_sparse_classes_30k_train_000720 | Implement the Python class `TaskGraphCli` described below.
Class description:
Takes care of creating a task graph executor and executing a graph.
Method signatures and docstrings:
- def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True... | Implement the Python class `TaskGraphCli` described below.
Class description:
Takes care of creating a task graph executor and executing a graph.
Method signatures and docstrings:
- def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True... | 21c8d4d32f632431704556f8bcb158f9bb686239 | <|skeleton|>
class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."""
ex... | the_stack_v2_python_sparse | dae/dae/task_graph/cli_tools.py | iossifovlab/gpf | train | 5 |
ac3c1446aef2ca741ba0ff5b3835280e9d31c734 | [
"self.id = nom\nself.comment = comment\nself.values = []",
"check_isinstance(nom_emh, str)\ncheck_isinstance(is_active, bool)\ncheck_isinstance(sens, [type(None), str])\nself.values.append([nom_emh, clim_tag, is_active, value, sens, typ_loi, param_loi, nom_fic])"
] | <|body_start_0|>
self.id = nom
self.comment = comment
self.values = []
<|end_body_0|>
<|body_start_1|>
check_isinstance(nom_emh, str)
check_isinstance(is_active, bool)
check_isinstance(sens, [type(None), str])
self.values.append([nom_emh, clim_tag, is_active, val... | Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une valeur (élément de `values`): * nom_emh * CLIM_TYPE_TO_TAG_VALUE.keys()[... | Calcul | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calcul:
"""Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une valeur (élément de `values`): * nom_em... | stack_v2_sparse_classes_75kplus_train_007175 | 6,361 | no_license | [
{
"docstring": ":param nom: nom du calcul :type nom: str :param comment: commentaire optionnel :type comment: str",
"name": "__init__",
"signature": "def __init__(self, nom, comment='')"
},
{
"docstring": "Ajouter une valeur (voir la définition de la classe pour plus de détails)",
"name": "a... | 2 | null | Implement the Python class `Calcul` described below.
Class description:
Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une... | Implement the Python class `Calcul` described below.
Class description:
Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une... | 59f9f57e62ab4897b74d5e97453ec7d44b02220f | <|skeleton|>
class Calcul:
"""Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une valeur (élément de `values`): * nom_em... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Calcul:
"""Classe abstraite pour les calculs :ivar id: nom du calcul :vartype id: str :ivar comment: commentaire du calcul :vartype comment: str :ivar values: paramètres du calcul (EMH, type et valeur/loi pour la CLimM...) :vartype values: list Contenu d'une valeur (élément de `values`): * nom_emh * CLIM_TYPE... | the_stack_v2_python_sparse | crue10/scenario/calcul.py | CNR-Engineering/Crue10_tools | train | 6 |
cdbad935ba9fa8c412bcc86a6d6b5ee9e7192e7f | [
"if len(s) == 0:\n return 0\ni = 0\nj = 0\nres = 0\nfor j in range(len(s)):\n if s[j] not in s[i:j]:\n res = max(j - i + 1, res)\n else:\n while s[i] != s[j] and i < j:\n i += 1\n i += 1\nreturn res",
"i = -1\nres = 0\ndic = {}\nfor j in range(len(s)):\n if s[j] in dic:... | <|body_start_0|>
if len(s) == 0:
return 0
i = 0
j = 0
res = 0
for j in range(len(s)):
if s[j] not in s[i:j]:
res = max(j - i + 1, res)
else:
while s[i] != s[j] and i < j:
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) == 0:
return 0
... | stack_v2_sparse_classes_75kplus_train_007176 | 952 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032146 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOf... | a3d7360bc336ea509c4bcc7eeea626551a4e49d9 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
if len(s) == 0:
return 0
i = 0
j = 0
res = 0
for j in range(len(s)):
if s[j] not in s[i:j]:
res = max(j - i + 1, res)
else:
... | the_stack_v2_python_sparse | 3.无重复字符的最长子串.py | cosJin/.leetcode | train | 0 | |
d998a62e14711782537ec5afce04bef78ef53293 | [
"self.num_simulation_steps = num_simulation_steps\nself.progress_bar = tqdm(total=self.num_simulation_steps)\nsuper().__init__(trigger_frequency)",
"if step == 0:\n num_update = 1\nelse:\n num_update = self.trigger_frequency\nself.progress_bar.update(num_update)"
] | <|body_start_0|>
self.num_simulation_steps = num_simulation_steps
self.progress_bar = tqdm(total=self.num_simulation_steps)
super().__init__(trigger_frequency)
<|end_body_0|>
<|body_start_1|>
if step == 0:
num_update = 1
else:
num_update = self.trigger_fr... | A Handler object that prints a progress bar, over the course of the simulation. | ProgressBarHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressBarHandler:
"""A Handler object that prints a progress bar, over the course of the simulation."""
def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1):
""":param num_simulation_steps: The number of simulation steps to run. :param trigger_frequency... | stack_v2_sparse_classes_75kplus_train_007177 | 13,619 | permissive | [
{
"docstring": ":param num_simulation_steps: The number of simulation steps to run. :param trigger_frequency: How often the handler actually performs the reporting update.",
"name": "__init__",
"signature": "def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_001457 | Implement the Python class `ProgressBarHandler` described below.
Class description:
A Handler object that prints a progress bar, over the course of the simulation.
Method signatures and docstrings:
- def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1): :param num_simulation_steps: The nu... | Implement the Python class `ProgressBarHandler` described below.
Class description:
A Handler object that prints a progress bar, over the course of the simulation.
Method signatures and docstrings:
- def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1): :param num_simulation_steps: The nu... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class ProgressBarHandler:
"""A Handler object that prints a progress bar, over the course of the simulation."""
def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1):
""":param num_simulation_steps: The number of simulation steps to run. :param trigger_frequency... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgressBarHandler:
"""A Handler object that prints a progress bar, over the course of the simulation."""
def __init__(self, num_simulation_steps: int, trigger_frequency: Optional[int]=1):
""":param num_simulation_steps: The number of simulation steps to run. :param trigger_frequency: How often t... | the_stack_v2_python_sparse | src/snc/simulation/plot/base_handlers.py | stochasticnetworkcontrol/snc | train | 9 |
5be9f48851d9ba03bd65aff1cef69ea64e663223 | [
"row, flags = self.HitTest((x, y))\ncol = bisect(self.col_locs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1\nreturn (row, col)",
"col_locs = self.col_locs\nx0 = col_locs[col]\nx1 = col_locs[col + 1]\nscrolloffset = self.GetScrollPos(wx.HORIZONTAL)\nif x1 - scrolloffset > self.GetSize()[0]:\n if wx.Platform == '_... | <|body_start_0|>
row, flags = self.HitTest((x, y))
col = bisect(self.col_locs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1
return (row, col)
<|end_body_0|>
<|body_start_1|>
col_locs = self.col_locs
x0 = col_locs[col]
x1 = col_locs[col + 1]
scrolloffset = self.GetSc... | Utility to transform window coordinates to row/col and vice versa. | ListCtrlUtil | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCtrlUtil:
"""Utility to transform window coordinates to row/col and vice versa."""
def GetCellId(self, x, y):
"""Transform window (x, y) position to logical (row, col) coords."""
<|body_0|>
def ViewCellRect(self, row, col):
"""Scroll the specified cell into p... | stack_v2_sparse_classes_75kplus_train_007178 | 24,506 | permissive | [
{
"docstring": "Transform window (x, y) position to logical (row, col) coords.",
"name": "GetCellId",
"signature": "def GetCellId(self, x, y)"
},
{
"docstring": "Scroll the specified cell into position if possible and return the (x0, y0, width, height) of the specified cell.",
"name": "ViewC... | 3 | stack_v2_sparse_classes_30k_val_000821 | Implement the Python class `ListCtrlUtil` described below.
Class description:
Utility to transform window coordinates to row/col and vice versa.
Method signatures and docstrings:
- def GetCellId(self, x, y): Transform window (x, y) position to logical (row, col) coords.
- def ViewCellRect(self, row, col): Scroll the ... | Implement the Python class `ListCtrlUtil` described below.
Class description:
Utility to transform window coordinates to row/col and vice versa.
Method signatures and docstrings:
- def GetCellId(self, x, y): Transform window (x, y) position to logical (row, col) coords.
- def ViewCellRect(self, row, col): Scroll the ... | 18241115b6c3c3ec8ba76c0ec10a894937ffc3c7 | <|skeleton|>
class ListCtrlUtil:
"""Utility to transform window coordinates to row/col and vice versa."""
def GetCellId(self, x, y):
"""Transform window (x, y) position to logical (row, col) coords."""
<|body_0|>
def ViewCellRect(self, row, col):
"""Scroll the specified cell into p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListCtrlUtil:
"""Utility to transform window coordinates to row/col and vice versa."""
def GetCellId(self, x, y):
"""Transform window (x, y) position to logical (row, col) coords."""
row, flags = self.HitTest((x, y))
col = bisect(self.col_locs, x + self.GetScrollPos(wx.HORIZONTAL)... | the_stack_v2_python_sparse | madgui/widget/listview.py | hibtc/madgui-old | train | 0 |
669321487c7e8da628aacbe3607a78982325e376 | [
"for model, trained_examples in trained_examples_by_model.items():\n if not trained_examples:\n continue\n if trained_examples[-1].span < max_span:\n return model\nraise exceptions.SkipSignal()",
"_validate_input_dict(input_dict)\nops_utils.validate_argument('wait_spans_before_eval', self.wait... | <|body_start_0|>
for model, trained_examples in trained_examples_by_model.items():
if not trained_examples:
continue
if trained_examples[-1].span < max_span:
return model
raise exceptions.SkipSignal()
<|end_body_0|>
<|body_start_1|>
_valid... | SpanDrivenEvaluatorInputs operator. | SpanDrivenEvaluatorInputs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_spa... | stack_v2_sparse_classes_75kplus_train_007179 | 7,595 | permissive | [
{
"docstring": "Finds the latest Model not trained on Examples with span max_span.",
"name": "_get_model_to_evaluate",
"signature": "def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_040835 | Implement the Python class `SpanDrivenEvaluatorInputs` described below.
Class description:
SpanDrivenEvaluatorInputs operator.
Method signatures and docstrings:
- def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]: Finds t... | Implement the Python class `SpanDrivenEvaluatorInputs` described below.
Class description:
SpanDrivenEvaluatorInputs operator.
Method signatures and docstrings:
- def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]: Finds t... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_spa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpanDrivenEvaluatorInputs:
"""SpanDrivenEvaluatorInputs operator."""
def _get_model_to_evaluate(self, trained_examples_by_model: Dict[types.Artifact, List[types.Artifact]], max_span: int) -> Optional[types.Artifact]:
"""Finds the latest Model not trained on Examples with span max_span."""
... | the_stack_v2_python_sparse | tfx/dsl/input_resolution/ops/span_driven_evaluator_inputs_op.py | tensorflow/tfx | train | 2,116 |
6f2d9ae8762d2525aad8895a88b6a2dd71e62528 | [
"print('-- create with check --')\nobj = self.filter(**field_check)\nif obj:\n obj = obj[0]\nelse:\n obj = self.create(**kwargs)\nreturn obj",
"print('-- delete with check --')\nif field_check:\n objs = self.filter(id__in=field_check)\nelse:\n objs = self.all()\nif hasattr(self.model, 'username'):\n ... | <|body_start_0|>
print('-- create with check --')
obj = self.filter(**field_check)
if obj:
obj = obj[0]
else:
obj = self.create(**kwargs)
return obj
<|end_body_0|>
<|body_start_1|>
print('-- delete with check --')
if field_check:
... | CRUDManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
<|body_0|>
def delete_with_field_check(self, field_check):
"""批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象"""
<|bo... | stack_v2_sparse_classes_75kplus_train_007180 | 1,985 | no_license | [
{
"docstring": "创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象",
"name": "create_with_field_check",
"signature": "def create_with_field_check(self, field_check, **kwargs)"
},
{
"docstring": "批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象",
"name": "delete_with_field_check"... | 2 | stack_v2_sparse_classes_30k_train_021199 | Implement the Python class `CRUDManager` described below.
Class description:
Implement the CRUDManager class.
Method signatures and docstrings:
- def create_with_field_check(self, field_check, **kwargs): 创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象
- def delete_with_field_check(self, field_check): 批量删除对象 Args... | Implement the Python class `CRUDManager` described below.
Class description:
Implement the CRUDManager class.
Method signatures and docstrings:
- def create_with_field_check(self, field_check, **kwargs): 创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象
- def delete_with_field_check(self, field_check): 批量删除对象 Args... | 6e5a498dd5b63117a6a20aa81ac67a1999d8ac21 | <|skeleton|>
class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
<|body_0|>
def delete_with_field_check(self, field_check):
"""批量删除对象 Args: field_check: 待删除对象的id列表 Returns: objs: 删除成功的对象"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CRUDManager:
def create_with_field_check(self, field_check, **kwargs):
"""创建对象 Args: field_check: 检查条件字典 Returns: obj: 创建成功的对象"""
print('-- create with check --')
obj = self.filter(**field_check)
if obj:
obj = obj[0]
else:
obj = self.create(**kwa... | the_stack_v2_python_sparse | career/core/managers.py | wyzane/skill-general | train | 0 | |
aa47fea00191988df92216098e43cab93958d3c8 | [
"self.name = name\nself.voc_size = voc_size\nself.emb_size = emb_size\nif is_tf_tensor(matrix):\n self.mat = matrix\nelse:\n with tf.variable_scope(name):\n self.mat = tf.get_variable('mat', shape=[voc_size, emb_size], initializer=matrix)",
"mat = self.mat + adv_eps if adv_eps is not None else self.m... | <|body_start_0|>
self.name = name
self.voc_size = voc_size
self.emb_size = emb_size
if is_tf_tensor(matrix):
self.mat = matrix
else:
with tf.variable_scope(name):
self.mat = tf.get_variable('mat', shape=[voc_size, emb_size], initializer=mat... | Embedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding:
def __init__(self, name, voc_size, emb_size, matrix=None, initializer=None):
"""Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at input :param emb_size: number of units :param matrix: tf tensor (to be used permanently) or tf in... | stack_v2_sparse_classes_75kplus_train_007181 | 14,497 | no_license | [
{
"docstring": "Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at input :param emb_size: number of units :param matrix: tf tensor (to be used permanently) or tf initializer (to be used at init) shape should be (inp_size, out_size) Stores weights as name/mat",
... | 2 | null | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, name, voc_size, emb_size, matrix=None, initializer=None): Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at... | Implement the Python class `Embedding` described below.
Class description:
Implement the Embedding class.
Method signatures and docstrings:
- def __init__(self, name, voc_size, emb_size, matrix=None, initializer=None): Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at... | 43c6a73dea76aa0b086c140ebd16c5bc2ea63bb0 | <|skeleton|>
class Embedding:
def __init__(self, name, voc_size, emb_size, matrix=None, initializer=None):
"""Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at input :param emb_size: number of units :param matrix: tf tensor (to be used permanently) or tf in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedding:
def __init__(self, name, voc_size, emb_size, matrix=None, initializer=None):
"""Embedding layer that actually creates all it's variables on init. :param voc_size: maximum index at input :param emb_size: number of units :param matrix: tf tensor (to be used permanently) or tf initializer (to ... | the_stack_v2_python_sparse | lib/layers.py | TIXFeniks/babelSolution | train | 1 | |
4d5413f29afbaa6f9654b5cbe2233b7401f1107d | [
"super().__init__(input_shape)\nself.body = body(input_shape=input_shape)\nself.shortcut = Identity(input_shape) if shortcut is None else shortcut(input_shape=input_shape)\nshortcut_out_shape = self.shortcut.output_shape\nif how == '.' and np.any(shortcut_out_shape[1:] != self.body.output_shape[1:]):\n raise Val... | <|body_start_0|>
super().__init__(input_shape)
self.body = body(input_shape=input_shape)
self.shortcut = Identity(input_shape) if shortcut is None else shortcut(input_shape=input_shape)
shortcut_out_shape = self.shortcut.output_shape
if how == '.' and np.any(shortcut_out_shape[1:... | BaseResBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseResBlock:
def __init__(self, input_shape, body, shortcut=None, head=None, how='+', **kwargs):
"""Build block with residual connection. Parameters ---------- input_shape : Tuple[int], List[int] or NDArray[int] shape of the input tensor. body : Module, ConvBlock, partially applied Conv... | stack_v2_sparse_classes_75kplus_train_007182 | 11,477 | no_license | [
{
"docstring": "Build block with residual connection. Parameters ---------- input_shape : Tuple[int], List[int] or NDArray[int] shape of the input tensor. body : Module, ConvBlock, partially applied ConvBlock or None module that will be used for building body part of block. The only parameter of constructor mus... | 3 | stack_v2_sparse_classes_30k_val_002302 | Implement the Python class `BaseResBlock` described below.
Class description:
Implement the BaseResBlock class.
Method signatures and docstrings:
- def __init__(self, input_shape, body, shortcut=None, head=None, how='+', **kwargs): Build block with residual connection. Parameters ---------- input_shape : Tuple[int], ... | Implement the Python class `BaseResBlock` described below.
Class description:
Implement the BaseResBlock class.
Method signatures and docstrings:
- def __init__(self, input_shape, body, shortcut=None, head=None, how='+', **kwargs): Build block with residual connection. Parameters ---------- input_shape : Tuple[int], ... | 9554e0f96703a37a9a41fc70dc8e70e45c6181a2 | <|skeleton|>
class BaseResBlock:
def __init__(self, input_shape, body, shortcut=None, head=None, how='+', **kwargs):
"""Build block with residual connection. Parameters ---------- input_shape : Tuple[int], List[int] or NDArray[int] shape of the input tensor. body : Module, ConvBlock, partially applied Conv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseResBlock:
def __init__(self, input_shape, body, shortcut=None, head=None, how='+', **kwargs):
"""Build block with residual connection. Parameters ---------- input_shape : Tuple[int], List[int] or NDArray[int] shape of the input tensor. body : Module, ConvBlock, partially applied ConvBlock or None ... | the_stack_v2_python_sparse | dnn_backend/radio_dep/models/models/pytorch/blocks/res_block.py | theVmagnificient/radiology_web | train | 0 | |
2f3a397abb79415922ead343d429dc1111c7d23a | [
"self._sensors = sensors\nself._const = const\nself.firmware = {}\nself.requested = {}\nself.started = {}\nself.unstarted = {}",
"fw_type = None\nfw_ver = None\nif not isinstance(updates, tuple):\n updates = (updates,)\nfor store in updates:\n fw_id = store.pop(msg.node_id, None)\n if fw_id is not None:\... | <|body_start_0|>
self._sensors = sensors
self._const = const
self.firmware = {}
self.requested = {}
self.started = {}
self.unstarted = {}
<|end_body_0|>
<|body_start_1|>
fw_type = None
fw_ver = None
if not isinstance(updates, tuple):
u... | Organize OTAFirmware updates. | OTAFirmware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTAFirmware:
"""Organize OTAFirmware updates."""
def __init__(self, sensors, const):
"""Set up OTA firmware instance."""
<|body_0|>
def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None):
"""Get firmware type, version and a dict holding binary data.""... | stack_v2_sparse_classes_75kplus_train_007183 | 6,845 | permissive | [
{
"docstring": "Set up OTA firmware instance.",
"name": "__init__",
"signature": "def __init__(self, sensors, const)"
},
{
"docstring": "Get firmware type, version and a dict holding binary data.",
"name": "_get_fw",
"signature": "def _get_fw(self, msg, updates, req_fw_type=None, req_fw_... | 5 | stack_v2_sparse_classes_30k_val_001990 | Implement the Python class `OTAFirmware` described below.
Class description:
Organize OTAFirmware updates.
Method signatures and docstrings:
- def __init__(self, sensors, const): Set up OTA firmware instance.
- def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): Get firmware type, version and a dict h... | Implement the Python class `OTAFirmware` described below.
Class description:
Organize OTAFirmware updates.
Method signatures and docstrings:
- def __init__(self, sensors, const): Set up OTA firmware instance.
- def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): Get firmware type, version and a dict h... | f7264321986a66193192a10f3261fe268eeb7601 | <|skeleton|>
class OTAFirmware:
"""Organize OTAFirmware updates."""
def __init__(self, sensors, const):
"""Set up OTA firmware instance."""
<|body_0|>
def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None):
"""Get firmware type, version and a dict holding binary data.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OTAFirmware:
"""Organize OTAFirmware updates."""
def __init__(self, sensors, const):
"""Set up OTA firmware instance."""
self._sensors = sensors
self._const = const
self.firmware = {}
self.requested = {}
self.started = {}
self.unstarted = {}
de... | the_stack_v2_python_sparse | mysensors/ota.py | theolind/pymysensors | train | 68 |
c022c0a0964612b399db096e3b1df9291ac074ce | [
"path = '/billing_request_flows'\nif params is not None:\n params = {self._envelope_key(): params}\nresponse = self._perform_request('POST', path, params, headers, retry_failures=True)\nreturn self._resource_for(response)",
"path = self._sub_url_params('/billing_request_flows/:identity/actions/initialise', {'i... | <|body_start_0|>
path = '/billing_request_flows'
if params is not None:
params = {self._envelope_key(): params}
response = self._perform_request('POST', path, params, headers, retry_failures=True)
return self._resource_for(response)
<|end_body_0|>
<|body_start_1|>
pa... | Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API. | BillingRequestFlowsService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BillingRequestFlowsService:
"""Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API."""
def create(self, params=None, headers=None):
"""Create a Billing Request Flow. Creates a new billing request flow. Args: params (dict, optional): Req... | stack_v2_sparse_classes_75kplus_train_007184 | 1,948 | permissive | [
{
"docstring": "Create a Billing Request Flow. Creates a new billing request flow. Args: params (dict, optional): Request body. Returns: BillingRequestFlow",
"name": "create",
"signature": "def create(self, params=None, headers=None)"
},
{
"docstring": "Initialise a Billing Request Flow. Returns... | 2 | stack_v2_sparse_classes_30k_test_001723 | Implement the Python class `BillingRequestFlowsService` described below.
Class description:
Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API.
Method signatures and docstrings:
- def create(self, params=None, headers=None): Create a Billing Request Flow. Creates a new... | Implement the Python class `BillingRequestFlowsService` described below.
Class description:
Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API.
Method signatures and docstrings:
- def create(self, params=None, headers=None): Create a Billing Request Flow. Creates a new... | ce6ef9064a2837ae4cebd7ca731fdef6c4ceca2d | <|skeleton|>
class BillingRequestFlowsService:
"""Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API."""
def create(self, params=None, headers=None):
"""Create a Billing Request Flow. Creates a new billing request flow. Args: params (dict, optional): Req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BillingRequestFlowsService:
"""Service class that provides access to the billing_request_flows endpoints of the GoCardless Pro API."""
def create(self, params=None, headers=None):
"""Create a Billing Request Flow. Creates a new billing request flow. Args: params (dict, optional): Request body. Re... | the_stack_v2_python_sparse | gocardless_pro/services/billing_request_flows_service.py | gocardless/gocardless-pro-python | train | 34 |
6f1eafa7b773b469f73243ad05d1acf3f8eeabf1 | [
"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... | kvstore.KVStore Key-Value键值存储服务 | KVStoreServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KVStoreServicer:
"""kvstore.KVStore Key-Value键值存储服务"""
def Put(self, request, context):
"""Put 创建kv键值对 若key已存在将更新value值"""
<|body_0|>
def Get(self, request, context):
"""Get 获取key的value 若key不存在则返回gRPC错误:NotFound"""
<|body_1|>
def GetPrefix(self, requ... | stack_v2_sparse_classes_75kplus_train_007185 | 8,051 | permissive | [
{
"docstring": "Put 创建kv键值对 若key已存在将更新value值",
"name": "Put",
"signature": "def Put(self, request, context)"
},
{
"docstring": "Get 获取key的value 若key不存在则返回gRPC错误:NotFound",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "GetPrefix 获取符合key_prefix的多个... | 5 | null | Implement the Python class `KVStoreServicer` described below.
Class description:
kvstore.KVStore Key-Value键值存储服务
Method signatures and docstrings:
- def Put(self, request, context): Put 创建kv键值对 若key已存在将更新value值
- def Get(self, request, context): Get 获取key的value 若key不存在则返回gRPC错误:NotFound
- def GetPrefix(self, request,... | Implement the Python class `KVStoreServicer` described below.
Class description:
kvstore.KVStore Key-Value键值存储服务
Method signatures and docstrings:
- def Put(self, request, context): Put 创建kv键值对 若key已存在将更新value值
- def Get(self, request, context): Get 获取key的value 若key不存在则返回gRPC错误:NotFound
- def GetPrefix(self, request,... | 4a0cb57aa5f318a3099fbfe6198620555b3a45af | <|skeleton|>
class KVStoreServicer:
"""kvstore.KVStore Key-Value键值存储服务"""
def Put(self, request, context):
"""Put 创建kv键值对 若key已存在将更新value值"""
<|body_0|>
def Get(self, request, context):
"""Get 获取key的value 若key不存在则返回gRPC错误:NotFound"""
<|body_1|>
def GetPrefix(self, requ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KVStoreServicer:
"""kvstore.KVStore Key-Value键值存储服务"""
def Put(self, request, context):
"""Put 创建kv键值对 若key已存在将更新value值"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
... | the_stack_v2_python_sparse | pythonsdk/kvstore/kvstore_pb2_grpc.py | jjrobotcn/andy4 | train | 0 |
c26faf27d043129e9d5beb6bf7dd9fe536beb4e6 | [
"hashmap = {}\nfor idx, val in enumerate(inorder):\n hashmap[val] = idx\n\ndef _buildTree(preorder_left: int, preorder_right: int, inorder_left: int, inorder_right: int) -> TreeNode:\n \"\"\"基于数组下标的递归遍历\n preorder_left: 左或右子树在前序数组的起始位置\n preorder_right: 左或右子树在前序数组的结束位置\n inord... | <|body_start_0|>
hashmap = {}
for idx, val in enumerate(inorder):
hashmap[val] = idx
def _buildTree(preorder_left: int, preorder_right: int, inorder_left: int, inorder_right: int) -> TreeNode:
"""基于数组下标的递归遍历
preorder_left: 左或右子树在前序数组的起始位置
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""递归"""
<|body_0|>
def buildTreeIteration(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""迭代法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hashmap... | stack_v2_sparse_classes_75kplus_train_007186 | 3,632 | no_license | [
{
"docstring": "递归",
"name": "buildTree",
"signature": "def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode"
},
{
"docstring": "迭代法",
"name": "buildTreeIteration",
"signature": "def buildTreeIteration(self, preorder: List[int], inorder: List[int]) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_test_002829 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 递归
- def buildTreeIteration(self, preorder: List[int], inorder: List[int]) -> TreeNode: 迭代法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 递归
- def buildTreeIteration(self, preorder: List[int], inorder: List[int]) -> TreeNode: 迭代法
<|skeleton|... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""递归"""
<|body_0|>
def buildTreeIteration(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""迭代法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""递归"""
hashmap = {}
for idx, val in enumerate(inorder):
hashmap[val] = idx
def _buildTree(preorder_left: int, preorder_right: int, inorder_left: int, inorder_right: int) -> TreeNo... | the_stack_v2_python_sparse | 105.从前序与中序遍历序列构造二叉树/solution.py | QtTao/daily_leetcode | train | 0 | |
5e13736ed45c850d8d571aea75f522516b4732a6 | [
"response = []\ntemplates = []\nintent_id = request.POST[INTENT_ID]\nintent = requests.get(API_URL + '/' + intent_id + '/' + API_URL_TAIL, headers=API_HEADER)\nintent_info = ''\nfor line in intent:\n intent_info += line\nintent_info_json = json.loads(intent_info)\nintent_name = intent_info_json['name']\nif 'resp... | <|body_start_0|>
response = []
templates = []
intent_id = request.POST[INTENT_ID]
intent = requests.get(API_URL + '/' + intent_id + '/' + API_URL_TAIL, headers=API_HEADER)
intent_info = ''
for line in intent:
intent_info += line
intent_info_json = json... | GetIntent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetIntent:
def post(self, request):
"""Standard post function."""
<|body_0|>
def get(self, request):
"""Standard get function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
response = []
templates = []
intent_id = request.POST[INTE... | stack_v2_sparse_classes_75kplus_train_007187 | 1,757 | no_license | [
{
"docstring": "Standard post function.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Standard get function.",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | null | Implement the Python class `GetIntent` described below.
Class description:
Implement the GetIntent class.
Method signatures and docstrings:
- def post(self, request): Standard post function.
- def get(self, request): Standard get function. | Implement the Python class `GetIntent` described below.
Class description:
Implement the GetIntent class.
Method signatures and docstrings:
- def post(self, request): Standard post function.
- def get(self, request): Standard get function.
<|skeleton|>
class GetIntent:
def post(self, request):
"""Standa... | b3ea44f442ebcd3e33aa98559243307a8529a15b | <|skeleton|>
class GetIntent:
def post(self, request):
"""Standard post function."""
<|body_0|>
def get(self, request):
"""Standard get function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetIntent:
def post(self, request):
"""Standard post function."""
response = []
templates = []
intent_id = request.POST[INTENT_ID]
intent = requests.get(API_URL + '/' + intent_id + '/' + API_URL_TAIL, headers=API_HEADER)
intent_info = ''
for line in inte... | the_stack_v2_python_sparse | ChatBot/views/intent_management/GetIntent.py | Fromalaska49/DunderMifflin-ChatBot | train | 0 | |
1421bf334400a24495fa248079662e20d281efb2 | [
"super(Data, self).__init__()\nself.gpu = gpu\nself.test_batch_size = test_batch_size\nself.weather_dataset = WeatherDataset(csv_file=csv_file)\nif category is not None:\n categorical_data = torch.zeros(len(self.weather_dataset), dtype=torch.int32)\n for i, data in enumerate(self.weather_dataset):\n ca... | <|body_start_0|>
super(Data, self).__init__()
self.gpu = gpu
self.test_batch_size = test_batch_size
self.weather_dataset = WeatherDataset(csv_file=csv_file)
if category is not None:
categorical_data = torch.zeros(len(self.weather_dataset), dtype=torch.int32)
... | Opens, splits and puts data in a dataloader | Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""Opens, splits and puts data in a dataloader"""
def __init__(self, csv_file, gpu=False, test_batch_size=100, train_percentage=0.8, category=None, one_hot_embedding_size=-1):
"""Args: csv_file (string): Relative path to the csv file gpu (bool, optional): If True use GPU's. Def... | stack_v2_sparse_classes_75kplus_train_007188 | 4,227 | no_license | [
{
"docstring": "Args: csv_file (string): Relative path to the csv file gpu (bool, optional): If True use GPU's. Defaults to False. test_batch_size (int, optional): Size of batches in the test set. Defaults to 100. train_percentage (float, optional): Percentage of dataset to be allocated for training. Defaults t... | 2 | stack_v2_sparse_classes_30k_train_051241 | Implement the Python class `Data` described below.
Class description:
Opens, splits and puts data in a dataloader
Method signatures and docstrings:
- def __init__(self, csv_file, gpu=False, test_batch_size=100, train_percentage=0.8, category=None, one_hot_embedding_size=-1): Args: csv_file (string): Relative path to ... | Implement the Python class `Data` described below.
Class description:
Opens, splits and puts data in a dataloader
Method signatures and docstrings:
- def __init__(self, csv_file, gpu=False, test_batch_size=100, train_percentage=0.8, category=None, one_hot_embedding_size=-1): Args: csv_file (string): Relative path to ... | 2a9be5364eab19d27c312ec50d38a38c397eaa1e | <|skeleton|>
class Data:
"""Opens, splits and puts data in a dataloader"""
def __init__(self, csv_file, gpu=False, test_batch_size=100, train_percentage=0.8, category=None, one_hot_embedding_size=-1):
"""Args: csv_file (string): Relative path to the csv file gpu (bool, optional): If True use GPU's. Def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Data:
"""Opens, splits and puts data in a dataloader"""
def __init__(self, csv_file, gpu=False, test_batch_size=100, train_percentage=0.8, category=None, one_hot_embedding_size=-1):
"""Args: csv_file (string): Relative path to the csv file gpu (bool, optional): If True use GPU's. Defaults to Fals... | the_stack_v2_python_sparse | data_setup.py | naddeok96/its_always_sunny | train | 0 |
612e22707e7b39a39551d31dd330cfaaea681298 | [
"program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')\noutputs, result = Computer(program, inputs=[]).run()\nassert program == outputs",
"program = parse_program('1102,34915192,34915192,7,4,7,99,0')\noutputs, result = Computer(program, inputs=[]).run()\nassert len(str(outputs[0])) ... | <|body_start_0|>
program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')
outputs, result = Computer(program, inputs=[]).run()
assert program == outputs
<|end_body_0|>
<|body_start_1|>
program = parse_program('1102,34915192,34915192,7,4,7,99,0')
outpu... | TestProblem09 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
<|body_0|>
def test_part1_example2(self):
"""1102,34915192,34915192,7,4,7,99,0 should output a 16-dig... | stack_v2_sparse_classes_75kplus_train_007189 | 5,550 | no_license | [
{
"docstring": "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.",
"name": "test_part1_example1",
"signature": "def test_part1_example1(self)"
},
{
"docstring": "1102,34915192,34915192,7,4,7,99,0 should output a 16-digit number.",
... | 4 | stack_v2_sparse_classes_30k_train_052050 | Implement the Python class `TestProblem09` described below.
Class description:
Implement the TestProblem09 class.
Method signatures and docstrings:
- def test_part1_example1(self): 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.
- def test_part1_exampl... | Implement the Python class `TestProblem09` described below.
Class description:
Implement the TestProblem09 class.
Method signatures and docstrings:
- def test_part1_example1(self): 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.
- def test_part1_exampl... | cd8d6c090496246d17b75dfc9f70175379aebeb8 | <|skeleton|>
class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
<|body_0|>
def test_part1_example2(self):
"""1102,34915192,34915192,7,4,7,99,0 should output a 16-dig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProblem09:
def test_part1_example1(self):
"""109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output."""
program = parse_program('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')
outputs, result = Computer(program,... | the_stack_v2_python_sparse | computer/test_computer.py | mattnworb/advent-of-code-2019 | train | 0 | |
0e352c78ca46c6854752a32f00b2a795c189e088 | [
"self.Vmatrix = np.array(Vmatrix).astype(float)\nself.sourcenames = sourcenames\nself.targetnames = targetnames",
"vals2Dout = {}\nzz = np.zeros(nn if nn is not None else (), dtype=float)\nif isinstance(vals2D, dict):\n xx = [vals2D.get(s, zz) for s in self.sourcenames]\n xx = [x.flatten() for x in xx]\n ... | <|body_start_0|>
self.Vmatrix = np.array(Vmatrix).astype(float)
self.sourcenames = sourcenames
self.targetnames = targetnames
<|end_body_0|>
<|body_start_1|>
vals2Dout = {}
zz = np.zeros(nn if nn is not None else (), dtype=float)
if isinstance(vals2D, dict):
... | GateTransform | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GateTransform:
def __init__(self, Vmatrix, sourcenames, targetnames):
"""Class to describe a linear transformation between source and target gates."""
<|body_0|>
def transformGateScan(self, vals2D, nn=None):
"""Get a list of parameter names and [c1 c2 c3 c4] 'corner'... | stack_v2_sparse_classes_75kplus_train_007190 | 28,215 | permissive | [
{
"docstring": "Class to describe a linear transformation between source and target gates.",
"name": "__init__",
"signature": "def __init__(self, Vmatrix, sourcenames, targetnames)"
},
{
"docstring": "Get a list of parameter names and [c1 c2 c3 c4] 'corner' values to generate dictionary self.val... | 2 | stack_v2_sparse_classes_30k_train_032558 | Implement the Python class `GateTransform` described below.
Class description:
Implement the GateTransform class.
Method signatures and docstrings:
- def __init__(self, Vmatrix, sourcenames, targetnames): Class to describe a linear transformation between source and target gates.
- def transformGateScan(self, vals2D, ... | Implement the Python class `GateTransform` described below.
Class description:
Implement the GateTransform class.
Method signatures and docstrings:
- def __init__(self, Vmatrix, sourcenames, targetnames): Class to describe a linear transformation between source and target gates.
- def transformGateScan(self, vals2D, ... | 208c9c53309e10484e9883d537b53282cb83a43d | <|skeleton|>
class GateTransform:
def __init__(self, Vmatrix, sourcenames, targetnames):
"""Class to describe a linear transformation between source and target gates."""
<|body_0|>
def transformGateScan(self, vals2D, nn=None):
"""Get a list of parameter names and [c1 c2 c3 c4] 'corner'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GateTransform:
def __init__(self, Vmatrix, sourcenames, targetnames):
"""Class to describe a linear transformation between source and target gates."""
self.Vmatrix = np.array(Vmatrix).astype(float)
self.sourcenames = sourcenames
self.targetnames = targetnames
def transform... | the_stack_v2_python_sparse | src/qtt/simulation/dotsystem.py | QuTech-Delft/qtt | train | 58 | |
27eaea1ca4774c852a79f6014ba75ee2512ff6f8 | [
"if amount == 0:\n return 1\nelif not coins:\n return 0\ndp = [[0] * (amount + 1) for _ in range(len(coins))]\nfor i in range(len(coins)):\n for j in range(amount + 1):\n if j == 0:\n dp[i][j] = 1\n elif j >= coins[i]:\n dp[i][j] = dp[i][j - coins[i]] + dp[i - 1][j]\n ... | <|body_start_0|>
if amount == 0:
return 1
elif not coins:
return 0
dp = [[0] * (amount + 1) for _ in range(len(coins))]
for i in range(len(coins)):
for j in range(amount + 1):
if j == 0:
dp[i][j] = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change__(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007191 | 1,306 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change__",
"signature": "def change__(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
}
] | 2 | stack_v2_sparse_classes_30k_test_003033 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change__(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change__(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
<... | b5c25f976866eefec33b96c638a4c5e127319e74 | <|skeleton|>
class Solution:
def change__(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def change__(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
if amount == 0:
return 1
elif not coins:
return 0
dp = [[0] * (amount + 1) for _ in range(len(coins))]
for i in range(len(coins)):
... | the_stack_v2_python_sparse | Python/518_Coin Change 2.py | Eddie02582/Leetcode | train | 1 | |
a882e928fcaa5be2d2cb6c128a9ae0b9099384ad | [
"self.HEADER_LENGTH = 9\nself.SizeBody = 0\nself.NumberPacket = 0\nself.Flag = 0\nif len(header_data) < self.HEADER_LENGTH:\n return None\nself.SizeBody = int(header_data[:4], 16)\nself.NumberPacket = int(header_data[4:8], 16)\nself.Flag = int(header_data[8], 16)",
"if len(header_data) < 9:\n return None\nr... | <|body_start_0|>
self.HEADER_LENGTH = 9
self.SizeBody = 0
self.NumberPacket = 0
self.Flag = 0
if len(header_data) < self.HEADER_LENGTH:
return None
self.SizeBody = int(header_data[:4], 16)
self.NumberPacket = int(header_data[4:8], 16)
self.Flag... | Class work with header of protocol | MTHeaderProtocol | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTHeaderProtocol:
"""Class work with header of protocol"""
def __init__(self, header_data):
"""length of header"""
<|body_0|>
def GetHeader(header_data):
"""Get header of response from MetaTrader 5 server @param string $header_data - package from server @return M... | stack_v2_sparse_classes_75kplus_train_007192 | 8,446 | permissive | [
{
"docstring": "length of header",
"name": "__init__",
"signature": "def __init__(self, header_data)"
},
{
"docstring": "Get header of response from MetaTrader 5 server @param string $header_data - package from server @return MTHeaderProtocol|None",
"name": "GetHeader",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_047375 | Implement the Python class `MTHeaderProtocol` described below.
Class description:
Class work with header of protocol
Method signatures and docstrings:
- def __init__(self, header_data): length of header
- def GetHeader(header_data): Get header of response from MetaTrader 5 server @param string $header_data - package ... | Implement the Python class `MTHeaderProtocol` described below.
Class description:
Class work with header of protocol
Method signatures and docstrings:
- def __init__(self, header_data): length of header
- def GetHeader(header_data): Get header of response from MetaTrader 5 server @param string $header_data - package ... | 1fadeecf31f1d25e258dc5d70c47a785f7b33961 | <|skeleton|>
class MTHeaderProtocol:
"""Class work with header of protocol"""
def __init__(self, header_data):
"""length of header"""
<|body_0|>
def GetHeader(header_data):
"""Get header of response from MetaTrader 5 server @param string $header_data - package from server @return M... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MTHeaderProtocol:
"""Class work with header of protocol"""
def __init__(self, header_data):
"""length of header"""
self.HEADER_LENGTH = 9
self.SizeBody = 0
self.NumberPacket = 0
self.Flag = 0
if len(header_data) < self.HEADER_LENGTH:
return None... | the_stack_v2_python_sparse | xwcrm/utils/mt5_protocol.py | MSUNorg/XWCRM | train | 0 |
78d1e9cc87ca03582cca80474a1fa00d6fae4e53 | [
"try:\n json_data = api.payload\n resp = User().register(json_data)\n return masked_json_template(resp, 200)\nexcept:\n abort(400, 'Input unrecognizable.')",
"try:\n try:\n get_args = {'filter': request.args.get('filter', default='', type=str), 'range': request.args.get('range', default='', ... | <|body_start_0|>
try:
json_data = api.payload
resp = User().register(json_data)
return masked_json_template(resp, 200)
except:
abort(400, 'Input unrecognizable.')
<|end_body_0|>
<|body_start_1|>
try:
try:
get_args = {'f... | UserRoute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRoute:
def post(self):
"""Add new user"""
<|body_0|>
def get(self):
"""Get all user data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
json_data = api.payload
resp = User().register(json_data)
return ma... | stack_v2_sparse_classes_75kplus_train_007193 | 5,083 | permissive | [
{
"docstring": "Add new user",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get all user data",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002450 | Implement the Python class `UserRoute` described below.
Class description:
Implement the UserRoute class.
Method signatures and docstrings:
- def post(self): Add new user
- def get(self): Get all user data | Implement the Python class `UserRoute` described below.
Class description:
Implement the UserRoute class.
Method signatures and docstrings:
- def post(self): Add new user
- def get(self): Get all user data
<|skeleton|>
class UserRoute:
def post(self):
"""Add new user"""
<|body_0|>
def get(s... | 100fca0d2dd9b0b2ab2fa5974d8126af35ddcfd1 | <|skeleton|>
class UserRoute:
def post(self):
"""Add new user"""
<|body_0|>
def get(self):
"""Get all user data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserRoute:
def post(self):
"""Add new user"""
try:
json_data = api.payload
resp = User().register(json_data)
return masked_json_template(resp, 200)
except:
abort(400, 'Input unrecognizable.')
def get(self):
"""Get all user da... | the_stack_v2_python_sparse | app/controllers/api/user/user.py | ardihikaru/api-dashboard-5g-dive | train | 0 | |
4e90b88434b2165ea0c4d1290f5753466515bd82 | [
"category_id = AdvertisingCategory.session.query(AdvertisingCategory.id).filter(AdvertisingCategory.name == category).scalar()\nnow_time = utime.timestamp(3)\nrows = Advertising.Q.filter(Advertising.category_id == category_id).filter(Advertising.start_at <= now_time).filter(or_(Advertising.end_at > now_time, Advert... | <|body_start_0|>
category_id = AdvertisingCategory.session.query(AdvertisingCategory.id).filter(AdvertisingCategory.name == category).scalar()
now_time = utime.timestamp(3)
rows = Advertising.Q.filter(Advertising.category_id == category_id).filter(Advertising.start_at <= now_time).filter(or_(Adv... | AdvertisingService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvertisingService:
def list_for_category(category, limit):
"""Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list"""
<|body_0|>
def get_for_category(category):
"""Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list"""
... | stack_v2_sparse_classes_75kplus_train_007194 | 2,150 | permissive | [
{
"docstring": "Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list",
"name": "list_for_category",
"signature": "def list_for_category(category, limit)"
},
{
"docstring": "Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list",
"name": "get_for_c... | 2 | stack_v2_sparse_classes_30k_train_034721 | Implement the Python class `AdvertisingService` described below.
Class description:
Implement the AdvertisingService class.
Method signatures and docstrings:
- def list_for_category(category, limit): Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list
- def get_for_category(category): Argument... | Implement the Python class `AdvertisingService` described below.
Class description:
Implement the AdvertisingService class.
Method signatures and docstrings:
- def list_for_category(category, limit): Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list
- def get_for_category(category): Argument... | 3300561c5686b674197ffc097cf781a931fd4787 | <|skeleton|>
class AdvertisingService:
def list_for_category(category, limit):
"""Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list"""
<|body_0|>
def get_for_category(category):
"""Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdvertisingService:
def list_for_category(category, limit):
"""Arguments: category string -- category 唯一标识 limit int -- 查询记录数 return: list"""
category_id = AdvertisingCategory.session.query(AdvertisingCategory.id).filter(AdvertisingCategory.name == category).scalar()
now_time = utime.t... | the_stack_v2_python_sparse | applications/huifeng/services/advertising.py | leeyisoft/py_admin | train | 17 | |
925e874c6ad06412b72283a89b837b318e2192f6 | [
"self.learning_rate = np.power(10, -3 * np.random.rand(7) - 1)\nself.weight_decay = np.power(10, -3 * np.random.rand(7) - 3)\nself.model = model",
"loss_min = np.inf\nbest_dict = {'learning_rate': None, 'weight_decay': None, 'acc': 0, 'loss': np.inf}\nhistory_dict = {}\nfor lr in self.learning_rate:\n for wd i... | <|body_start_0|>
self.learning_rate = np.power(10, -3 * np.random.rand(7) - 1)
self.weight_decay = np.power(10, -3 * np.random.rand(7) - 3)
self.model = model
<|end_body_0|>
<|body_start_1|>
loss_min = np.inf
best_dict = {'learning_rate': None, 'weight_decay': None, 'acc': 0, 'l... | Hyper-parameter search methods | RandomSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSearch:
"""Hyper-parameter search methods"""
def __init__(self, model):
"""Create a new GridSearch instance. :param model: the pre-trained keras model."""
<|body_0|>
def __call__(self, x, y, validation_data, batch_size):
"""Do the grid search evaluation :pa... | stack_v2_sparse_classes_75kplus_train_007195 | 2,501 | no_license | [
{
"docstring": "Create a new GridSearch instance. :param model: the pre-trained keras model.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Do the grid search evaluation :param x: the training set images. :param y: the ground truth labels. :param validation_dat... | 2 | stack_v2_sparse_classes_30k_train_004673 | Implement the Python class `RandomSearch` described below.
Class description:
Hyper-parameter search methods
Method signatures and docstrings:
- def __init__(self, model): Create a new GridSearch instance. :param model: the pre-trained keras model.
- def __call__(self, x, y, validation_data, batch_size): Do the grid ... | Implement the Python class `RandomSearch` described below.
Class description:
Hyper-parameter search methods
Method signatures and docstrings:
- def __init__(self, model): Create a new GridSearch instance. :param model: the pre-trained keras model.
- def __call__(self, x, y, validation_data, batch_size): Do the grid ... | b761a9e0e53eb99566769baac98ad5d9fd309a1d | <|skeleton|>
class RandomSearch:
"""Hyper-parameter search methods"""
def __init__(self, model):
"""Create a new GridSearch instance. :param model: the pre-trained keras model."""
<|body_0|>
def __call__(self, x, y, validation_data, batch_size):
"""Do the grid search evaluation :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomSearch:
"""Hyper-parameter search methods"""
def __init__(self, model):
"""Create a new GridSearch instance. :param model: the pre-trained keras model."""
self.learning_rate = np.power(10, -3 * np.random.rand(7) - 1)
self.weight_decay = np.power(10, -3 * np.random.rand(7) - ... | the_stack_v2_python_sparse | lib/hyper_search.py | heng-yuwen/MSc_Data_Reduction | train | 1 |
ab259044aa95d5bea931de2626b44d867c0570a6 | [
"n = len(a) + len(b)\nif n % 2 == 0:\n return (self._findKth(a, 0, b, 0, n // 2) + self._findKth(a, 0, b, 0, n // 2 + 1)) / 2.0\nelse:\n return self._findKth(a, 0, b, 0, n // 2 + 1)",
"assert k <= len(a) + len(b)\nif i >= len(a):\n return b[j + k - 1]\nelif j >= len(b):\n return a[i + k - 1]\nelif k =... | <|body_start_0|>
n = len(a) + len(b)
if n % 2 == 0:
return (self._findKth(a, 0, b, 0, n // 2) + self._findKth(a, 0, b, 0, n // 2 + 1)) / 2.0
else:
return self._findKth(a, 0, b, 0, n // 2 + 1)
<|end_body_0|>
<|body_start_1|>
assert k <= len(a) + len(b)
if ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, a, b):
"""Returns the median of two sorted arrays a and b."""
<|body_0|>
def _findKth(self, a, i, b, j, k):
"""Returns the kth element of two sorted sub-arrays a[i:] and b[j:]. The high level description of the algorithm is ... | stack_v2_sparse_classes_75kplus_train_007196 | 3,198 | permissive | [
{
"docstring": "Returns the median of two sorted arrays a and b.",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, a, b)"
},
{
"docstring": "Returns the kth element of two sorted sub-arrays a[i:] and b[j:]. The high level description of the algorithm is as follow... | 2 | stack_v2_sparse_classes_30k_train_022631 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, a, b): Returns the median of two sorted arrays a and b.
- def _findKth(self, a, i, b, j, k): Returns the kth element of two sorted sub-arrays a[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, a, b): Returns the median of two sorted arrays a and b.
- def _findKth(self, a, i, b, j, k): Returns the kth element of two sorted sub-arrays a[i... | 0e46cbaa3f2826b6ff9d4ebd150b5e2330e66859 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, a, b):
"""Returns the median of two sorted arrays a and b."""
<|body_0|>
def _findKth(self, a, i, b, j, k):
"""Returns the kth element of two sorted sub-arrays a[i:] and b[j:]. The high level description of the algorithm is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMedianSortedArrays(self, a, b):
"""Returns the median of two sorted arrays a and b."""
n = len(a) + len(b)
if n % 2 == 0:
return (self._findKth(a, 0, b, 0, n // 2) + self._findKth(a, 0, b, 0, n // 2 + 1)) / 2.0
else:
return self._findKt... | the_stack_v2_python_sparse | leetcode/algorithms/median-of-two-sorted-arrays/solution.py | i7sharath/algorithms-1 | train | 0 | |
5db5e17b69466853aa99f3c992602ba4c5517ef4 | [
"super().__init__()\nself.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=filter_size, stride=stride, padding=1)\nself.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=filter_size, padding=1)\nself.batch_norm = nn.BatchNorm2d(num_features=out_chann... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=filter_size, stride=stride, padding=1)
self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=filter_size, padding=1)
self.batch_nor... | Implementation of the ResBlock | ResBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
"""Implementation of the ResBlock"""
def __init__(self, in_channels, out_channels, stride, filter_size, activation_func):
""":param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel dimension of the output. :param stride (int): Stride for... | stack_v2_sparse_classes_75kplus_train_007197 | 11,846 | no_license | [
{
"docstring": ":param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel dimension of the output. :param stride (int): Stride for first Conv2D operation. :param filter_size (int): Filter/kernel size for the Conv2D-layers. :param activation_func (nn.Module): Activation functio... | 2 | stack_v2_sparse_classes_30k_train_008396 | Implement the Python class `ResBlock` described below.
Class description:
Implementation of the ResBlock
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride, filter_size, activation_func): :param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel... | Implement the Python class `ResBlock` described below.
Class description:
Implementation of the ResBlock
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, stride, filter_size, activation_func): :param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel... | 1d2d990c75bb7977d76430a50a31bd9ce31da37d | <|skeleton|>
class ResBlock:
"""Implementation of the ResBlock"""
def __init__(self, in_channels, out_channels, stride, filter_size, activation_func):
""":param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel dimension of the output. :param stride (int): Stride for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResBlock:
"""Implementation of the ResBlock"""
def __init__(self, in_channels, out_channels, stride, filter_size, activation_func):
""":param in_channels (int): Channel dimension of the input. :param out_channels (int): Channel dimension of the output. :param stride (int): Stride for first Conv2D... | the_stack_v2_python_sparse | Exercise 4/src_to_implement/model.py | StefanFischer/Deep-Learning-Framework | train | 0 |
e4ae778222bb15c9e49bab72928768f01a1880d3 | [
"super().__init__()\nself._sample_shape = torch.Size([num_samples])\nself.collapse_batch_dims = collapse_batch_dims\nself.resample = resample\nself.seed = seed if seed is not None else torch.randint(0, 1000000, (1,)).item()",
"if self.resample or not hasattr(self, 'base_samples') or self.base_samples.shape[-2:] !... | <|body_start_0|>
super().__init__()
self._sample_shape = torch.Size([num_samples])
self.collapse_batch_dims = collapse_batch_dims
self.resample = resample
self.seed = seed if seed is not None else torch.randint(0, 1000000, (1,)).item()
<|end_body_0|>
<|body_start_1|>
if ... | Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior) | IIDNormalSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IIDNormalSampler:
"""Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior)"""
def __init__(self, num_samples: int, resample: bool=False, seed: Optional[int]=None,... | stack_v2_sparse_classes_75kplus_train_007198 | 13,572 | permissive | [
{
"docstring": "Sampler for MC base samples using iid `N(0,1)` samples. Args: num_samples: The number of samples to use. resample: If `True`, re-draw samples in each `forward` evaluation - this results in stochastic acquisition functions (and thus should not be used with deterministic optimization algorithms). ... | 2 | null | Implement the Python class `IIDNormalSampler` described below.
Class description:
Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior)
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `IIDNormalSampler` described below.
Class description:
Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior)
Method signatures and docstrings:
- def __init__(sel... | af13f0a38b579ab504f49a01f1ced13532a3ad49 | <|skeleton|>
class IIDNormalSampler:
"""Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior)"""
def __init__(self, num_samples: int, resample: bool=False, seed: Optional[int]=None,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IIDNormalSampler:
"""Sampler for MC base samples using iid N(0,1) samples. Example: >>> sampler = IIDNormalSampler(1000, seed=1234) >>> posterior = model.posterior(test_X) >>> samples = sampler(posterior)"""
def __init__(self, num_samples: int, resample: bool=False, seed: Optional[int]=None, collapse_bat... | the_stack_v2_python_sparse | botorch/sampling/samplers.py | shalijiang/bo | train | 1 |
0bd1808eecfc0c246b65e26d8ac90132f0da6860 | [
"model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)\nid2property = {}\nfor model_property in model_properties:\n model_property.property_values = []\n t_name = model_property.name\n model_property.shot_name = t_name[:6] + '...' if len(t_name) > 6 els... | <|body_start_0|>
model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)
id2property = {}
for model_property in model_properties:
model_property.property_values = []
t_name = model_property.name
model_propert... | ModelPropertyList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
<|body_0|>
def api_get(request):
"""获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //full_id表示${property.id}:${value.id} name: "红", image: "" }, { id: 2, name... | stack_v2_sparse_classes_75kplus_train_007199 | 9,873 | no_license | [
{
"docstring": "商品规格列表页面.",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获取全部规格属性集合 Return json: Example: [{ id: 1, name: \"颜色\", type: \"text\", values: [{ id: 1, full_id: \"1:1\", //full_id表示${property.id}:${value.id} name: \"红\", image: \"\" }, { id: 2, name: \"白\" image:... | 2 | stack_v2_sparse_classes_30k_train_004896 | Implement the Python class `ModelPropertyList` described below.
Class description:
Implement the ModelPropertyList class.
Method signatures and docstrings:
- def get(request): 商品规格列表页面.
- def api_get(request): 获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //ful... | Implement the Python class `ModelPropertyList` described below.
Class description:
Implement the ModelPropertyList class.
Method signatures and docstrings:
- def get(request): 商品规格列表页面.
- def api_get(request): 获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //ful... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
<|body_0|>
def api_get(request):
"""获取全部规格属性集合 Return json: Example: [{ id: 1, name: "颜色", type: "text", values: [{ id: 1, full_id: "1:1", //full_id表示${property.id}:${value.id} name: "红", image: "" }, { id: 2, name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelPropertyList:
def get(request):
"""商品规格列表页面."""
model_properties = mall_models.ProductModelProperty.objects.filter(owner=request.manager, is_deleted=False)
id2property = {}
for model_property in model_properties:
model_property.property_values = []
... | the_stack_v2_python_sparse | weapp/mall/product/model_property.py | chengdg/weizoom | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.