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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ee4f17cefc72c91c70090d46481ca610980f42e | [
"code = Utils.code_to_symbol(code)\ncalc_date = Utils.to_date(calc_date)\nttm_fin_data = Utils.get_ttm_fin_basic_data(code, calc_date)\nif ttm_fin_data is None:\n return None\nreport_date = Utils.get_fin_report_date(calc_date)\nfin_basic_data = Utils.get_fin_basic_data(code, report_date)\nif fin_basic_data is No... | <|body_start_0|>
code = Utils.code_to_symbol(code)
calc_date = Utils.to_date(calc_date)
ttm_fin_data = Utils.get_ttm_fin_basic_data(code, calc_date)
if ttm_fin_data is None:
return None
report_date = Utils.get_fin_report_date(calc_date)
fin_basic_data = Utils.... | 价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) -------- | Value | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Value:
"""价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) --------"""
def _calc_factor_loading(cls, code, calc_date):
"""计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param code: str 个股代码:如600000或SH600000 :param calc_date: datetime... | stack_v2_sparse_classes_75kplus_train_008700 | 7,758 | no_license | [
{
"docstring": "计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param code: str 个股代码:如600000或SH600000 :param calc_date: datetime-like or str 计算日期,格式YYYY-MM-DD, YYYYMMDD :return: pd.Series -------- 价值类因子值 0. ep_ttm: TTM净利润/总市值 1. bp_lr: 净资产(最新财报)/总市值 2. ocf_ttm: TTM经营性现金流/总市值 若计算失败,返回None",
"... | 3 | null | Implement the Python class `Value` described below.
Class description:
价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) --------
Method signatures and docstrings:
- def _calc_factor_loading(cls, code, calc_date): 计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param c... | Implement the Python class `Value` described below.
Class description:
价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) --------
Method signatures and docstrings:
- def _calc_factor_loading(cls, code, calc_date): 计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param c... | c796951a7200af5ea247a505bbc7d456f43f9922 | <|skeleton|>
class Value:
"""价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) --------"""
def _calc_factor_loading(cls, code, calc_date):
"""计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param code: str 个股代码:如600000或SH600000 :param calc_date: datetime... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Value:
"""价值类因子 -------- 包含:ep_ttm(TTM净利润/总市值), bp_lr(净资产(最新财报)/总市值), ocf_ttm(TTM经营性现金流/总市值) --------"""
def _calc_factor_loading(cls, code, calc_date):
"""计算指定日期、指定个股的价值因子,包含ep_ttm, bp_lr, ocf_ttm Parameters: -------- :param code: str 个股代码:如600000或SH600000 :param calc_date: datetime-like or str ... | the_stack_v2_python_sparse | src/factors/Value.py | fan1018wen/MultiFactor | train | 0 |
6a9e6755df7dc1d2e15a9aa9f95f6b6bafcd687f | [
"count = 0\nfor i in range(len(nums)):\n total = 1\n for j in range(i, len(nums)):\n total *= nums[j]\n if total < k:\n count += 1\n else:\n break\nreturn count",
"if k <= 1:\n return 0\ncount, product, l = (0, 1, 0)\nfor r in range(len(nums)):\n product *= n... | <|body_start_0|>
count = 0
for i in range(len(nums)):
total = 1
for j in range(i, len(nums)):
total *= nums[j]
if total < k:
count += 1
else:
break
return count
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK_(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_008701 | 1,122 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK_",
"signature": "def numSubarrayProductLessThanK_(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_024713 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK_(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK_(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: i... | b5c25f976866eefec33b96c638a4c5e127319e74 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK_(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSubarrayProductLessThanK_(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
count = 0
for i in range(len(nums)):
total = 1
for j in range(i, len(nums)):
total *= nums[j]
if total < k:
... | the_stack_v2_python_sparse | Python/713_Subarray Product Less Than K.py | Eddie02582/Leetcode | train | 1 | |
52dc1724098928eb9c09b7f46de960d5d87b9879 | [
"super().__init__(*args, **kwargs)\nfor cog in cogs:\n try:\n self.load_extension(cog)\n except Exception as e:\n print('Failed to load extension ' + cog + '.')\n print(e)",
"if not hasattr(self, 'uptime'):\n self.uptime = datetime.datetime.now()\nprint('-' * 30)\nprint('Logged in as... | <|body_start_0|>
super().__init__(*args, **kwargs)
for cog in cogs:
try:
self.load_extension(cog)
except Exception as e:
print('Failed to load extension ' + cog + '.')
print(e)
<|end_body_0|>
<|body_start_1|>
if not hasattr... | DungeonBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
<|body_0|>
async def on_ready(self):
"""Function that runs when the bot starts."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
su... | stack_v2_sparse_classes_75kplus_train_008702 | 1,548 | no_license | [
{
"docstring": "Main bot object. This is used to play the game through discord.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Function that runs when the bot starts.",
"name": "on_ready",
"signature": "async def on_ready(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031691 | Implement the Python class `DungeonBot` described below.
Class description:
Implement the DungeonBot class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Main bot object. This is used to play the game through discord.
- async def on_ready(self): Function that runs when the bot starts. | Implement the Python class `DungeonBot` described below.
Class description:
Implement the DungeonBot class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Main bot object. This is used to play the game through discord.
- async def on_ready(self): Function that runs when the bot starts.
<|sk... | 0484df39ebd5eb0c2cbc8ad0e1863182751e5d72 | <|skeleton|>
class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
<|body_0|>
async def on_ready(self):
"""Function that runs when the bot starts."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DungeonBot:
def __init__(self, *args, **kwargs):
"""Main bot object. This is used to play the game through discord."""
super().__init__(*args, **kwargs)
for cog in cogs:
try:
self.load_extension(cog)
except Exception as e:
print('... | the_stack_v2_python_sparse | bot.py | emiipo/discord-and-dragons | train | 0 | |
2de5fbc0cc05cd99533f7e28c71a3bf2f9501eec | [
"try:\n if request.user.is_superuser:\n workspace_list = workspace_api.get_all()\n else:\n workspace_list = workspace_api.get_all_by_owner(request.user)\n serializer = WorkspaceSerializer(workspace_list, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Excep... | <|body_start_0|>
try:
if request.user.is_superuser:
workspace_list = workspace_api.get_all()
else:
workspace_list = workspace_api.get_all_by_owner(request.user)
serializer = WorkspaceSerializer(workspace_list, many=True)
return Resp... | List all user Workspace, or create a new one | WorkspaceList | [
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
<|body_0|>
def post(self, reques... | stack_v2_sparse_classes_75kplus_train_008703 | 23,285 | permissive | [
{
"docstring": "Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a Workspace Parameters: { \"title\": \"document_title\",... | 2 | stack_v2_sparse_classes_30k_test_002029 | Implement the Python class `WorkspaceList` described below.
Class description:
List all user Workspace, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal serv... | Implement the Python class `WorkspaceList` described below.
Class description:
List all user Workspace, or create a new one
Method signatures and docstrings:
- def get(self, request): Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal serv... | f032036d95076f92b164389fdbec7415567e7b0f | <|skeleton|>
class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
<|body_0|>
def post(self, reques... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkspaceList:
"""List all user Workspace, or create a new one"""
def get(self, request):
"""Get all user workspaces Args: request: HTTP request Returns: - code: 200 content: List of workspace - code: 500 content: Internal server error"""
try:
if request.user.is_superuser:
... | the_stack_v2_python_sparse | core_main_app/rest/workspace/views.py | usnistgov/core_main_app | train | 3 |
ad22a8c77b7b9f88efa12475982d45b9cd8e5838 | [
"if value is self.field.missing_value:\n return ['']\nif isinstance(value, six.string_types):\n return [util.toUnicode(value)]\nreturn [util.toUnicode(v) for v in value if v]",
"if self._strip_value and isinstance(value, six.string_types):\n value = [value.strip()]\nif value == u'' or value == []:\n r... | <|body_start_0|>
if value is self.field.missing_value:
return ['']
if isinstance(value, six.string_types):
return [util.toUnicode(value)]
return [util.toUnicode(v) for v in value if v]
<|end_body_0|>
<|body_start_1|>
if self._strip_value and isinstance(value, six... | MultiLineDataConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLineDataConverter:
def toWidgetValue(self, value):
"""See interfaces.IDataConverter"""
<|body_0|>
def toFieldValue(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is self.field.missing_val... | stack_v2_sparse_classes_75kplus_train_008704 | 1,400 | no_license | [
{
"docstring": "See interfaces.IDataConverter",
"name": "toWidgetValue",
"signature": "def toWidgetValue(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "toFieldValue",
"signature": "def toFieldValue(self, value)"
}
] | 2 | null | Implement the Python class `MultiLineDataConverter` described below.
Class description:
Implement the MultiLineDataConverter class.
Method signatures and docstrings:
- def toWidgetValue(self, value): See interfaces.IDataConverter
- def toFieldValue(self, value): See interfaces.IDataConverter | Implement the Python class `MultiLineDataConverter` described below.
Class description:
Implement the MultiLineDataConverter class.
Method signatures and docstrings:
- def toWidgetValue(self, value): See interfaces.IDataConverter
- def toFieldValue(self, value): See interfaces.IDataConverter
<|skeleton|>
class Multi... | 579dd77ae759f1834a908dee68999f5fb3d5ad0b | <|skeleton|>
class MultiLineDataConverter:
def toWidgetValue(self, value):
"""See interfaces.IDataConverter"""
<|body_0|>
def toFieldValue(self, value):
"""See interfaces.IDataConverter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLineDataConverter:
def toWidgetValue(self, value):
"""See interfaces.IDataConverter"""
if value is self.field.missing_value:
return ['']
if isinstance(value, six.string_types):
return [util.toUnicode(value)]
return [util.toUnicode(v) for v in value ... | the_stack_v2_python_sparse | cpskin/core/browser/widget.py | IMIO/cpskin.core | train | 1 | |
1c082998ba08fd6ca2b1ed03ab65d69c32dc29f6 | [
"Element.__init__(self)\nself.title = title\nself.subtitle = subtitle\nself.x = x\nself.y = y\nself.width = width\nself.height = height\nself.id = id\nself.classes = classes\nself.titleid = titleid\nself.titleclasses = titleclasses\nself.subtitleid = subtitleid\nself.subtitleclasses = subtitleclasses\nself.border =... | <|body_start_0|>
Element.__init__(self)
self.title = title
self.subtitle = subtitle
self.x = x
self.y = y
self.width = width
self.height = height
self.id = id
self.classes = classes
self.titleid = titleid
self.titleclasses = titlecl... | Element of a title and optional subtitle. | Title | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Title:
"""Element of a title and optional subtitle."""
def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(), border=False, borderid=u'', borderclasses=()):
"""@param ti... | stack_v2_sparse_classes_75kplus_train_008705 | 3,334 | permissive | [
{
"docstring": "@param title: The text of the title @type title: string @param subtitle: The text of the subtitle @type subtitle: string or None @param x: The x coordinate to draw the title element at @param y: The y coordinate to draw the title element at @param width: The width of the title element (used for ... | 2 | stack_v2_sparse_classes_30k_train_005564 | Implement the Python class `Title` described below.
Class description:
Element of a title and optional subtitle.
Method signatures and docstrings:
- def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(),... | Implement the Python class `Title` described below.
Class description:
Element of a title and optional subtitle.
Method signatures and docstrings:
- def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(),... | ff440f55f38d64658fcad3c60ded5236b1c0a401 | <|skeleton|>
class Title:
"""Element of a title and optional subtitle."""
def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(), border=False, borderid=u'', borderclasses=()):
"""@param ti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Title:
"""Element of a title and optional subtitle."""
def __init__(self, title=u'', subtitle=u'', x=0.0, y=0.0, width=100.0, height=50.0, id=u'', classes=(), titleid=u'', titleclasses=(), subtitleid=u'', subtitleclasses=(), border=False, borderid=u'', borderclasses=()):
"""@param title: The text... | the_stack_v2_python_sparse | lib/elements/Title.py | agold/svgchart | train | 1 |
7ca37ea93c618e49192bc0257509aae25dd2d999 | [
"event_key = headers.get('X-Event-Key')\nscm_type = payload.get('repository', {}).get('scm')\nif event_key not in BitBucketEventTypes.values():\n cls.event_notification_client.send_message_to_notification_center(CODE_JOB_CI_INVALID_EVENT_TYPE, detail={'event_type': event_key})\n raise UnrecognizableEventType(... | <|body_start_0|>
event_key = headers.get('X-Event-Key')
scm_type = payload.get('repository', {}).get('scm')
if event_key not in BitBucketEventTypes.values():
cls.event_notification_client.send_message_to_notification_center(CODE_JOB_CI_INVALID_EVENT_TYPE, detail={'event_type': event_... | BitBucket event translator. | BitBucketEventTranslator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitBucketEventTranslator:
"""BitBucket event translator."""
def translate(cls, payload, headers=None):
"""Translate event. :param payload: :param headers: :return:"""
<|body_0|>
def _translate_push(cls, payload):
"""Translate push event. BitBucket may put multipl... | stack_v2_sparse_classes_75kplus_train_008706 | 6,009 | permissive | [
{
"docstring": "Translate event. :param payload: :param headers: :return:",
"name": "translate",
"signature": "def translate(cls, payload, headers=None)"
},
{
"docstring": "Translate push event. BitBucket may put multiple pushes (i.e. when the developer uses push --all) into one event. :param pa... | 5 | stack_v2_sparse_classes_30k_train_004077 | Implement the Python class `BitBucketEventTranslator` described below.
Class description:
BitBucket event translator.
Method signatures and docstrings:
- def translate(cls, payload, headers=None): Translate event. :param payload: :param headers: :return:
- def _translate_push(cls, payload): Translate push event. BitB... | Implement the Python class `BitBucketEventTranslator` described below.
Class description:
BitBucket event translator.
Method signatures and docstrings:
- def translate(cls, payload, headers=None): Translate event. :param payload: :param headers: :return:
- def _translate_push(cls, payload): Translate push event. BitB... | 8601d652476cd30457961aaf9feac143fd437606 | <|skeleton|>
class BitBucketEventTranslator:
"""BitBucket event translator."""
def translate(cls, payload, headers=None):
"""Translate event. :param payload: :param headers: :return:"""
<|body_0|>
def _translate_push(cls, payload):
"""Translate push event. BitBucket may put multipl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BitBucketEventTranslator:
"""BitBucket event translator."""
def translate(cls, payload, headers=None):
"""Translate event. :param payload: :param headers: :return:"""
event_key = headers.get('X-Event-Key')
scm_type = payload.get('repository', {}).get('scm')
if event_key no... | the_stack_v2_python_sparse | devops/src/ax/devops/gateway/event_translators/bitbucket.py | durgeshsanagaram/argo | train | 1 |
80fb91db9f190acdf2c6a276281ce9252eb1f0d7 | [
"with session.begin(subtransactions=True):\n query = session.query(pnet_db.ProviderNet).filter_by(name=physical_network)\n return query.one()",
"ranges = {}\nwith session.begin(subtransactions=True):\n query = session.query(pnet_db.ProviderNetRange).join(pnet_db.ProviderNet).filter(pnet_db.ProviderNet.ty... | <|body_start_0|>
with session.begin(subtransactions=True):
query = session.query(pnet_db.ProviderNet).filter_by(name=physical_network)
return query.one()
<|end_body_0|>
<|body_start_1|>
ranges = {}
with session.begin(subtransactions=True):
query = session.que... | GenericProvidernetTypeDriverMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericProvidernetTypeDriverMixin:
def _get_providernet(self, session, physical_network):
"""A private function to query a provider network by name. This function is used rather than the get_providernet_by_name because we do not have access to the 'context' object from within this class.... | stack_v2_sparse_classes_75kplus_train_008707 | 15,649 | permissive | [
{
"docstring": "A private function to query a provider network by name. This function is used rather than the get_providernet_by_name because we do not have access to the 'context' object from within this class.",
"name": "_get_providernet",
"signature": "def _get_providernet(self, session, physical_net... | 3 | null | Implement the Python class `GenericProvidernetTypeDriverMixin` described below.
Class description:
Implement the GenericProvidernetTypeDriverMixin class.
Method signatures and docstrings:
- def _get_providernet(self, session, physical_network): A private function to query a provider network by name. This function is ... | Implement the Python class `GenericProvidernetTypeDriverMixin` described below.
Class description:
Implement the GenericProvidernetTypeDriverMixin class.
Method signatures and docstrings:
- def _get_providernet(self, session, physical_network): A private function to query a provider network by name. This function is ... | d4a8ad548c4afed73269575c48526a704dd09a9c | <|skeleton|>
class GenericProvidernetTypeDriverMixin:
def _get_providernet(self, session, physical_network):
"""A private function to query a provider network by name. This function is used rather than the get_providernet_by_name because we do not have access to the 'context' object from within this class.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericProvidernetTypeDriverMixin:
def _get_providernet(self, session, physical_network):
"""A private function to query a provider network by name. This function is used rather than the get_providernet_by_name because we do not have access to the 'context' object from within this class."""
wi... | the_stack_v2_python_sparse | neutron/plugins/wrs/drivers/type_generic.py | ericho/stx-neutron | train | 0 | |
8d25bafa1ffc970cdb8ffc6d89d802bfdef774fd | [
"self.string = xml.get('filterText')\nself.match_pre = xml.get('matchBefore')\nself.match_post = xml.get('matchAfter')\nif self.match_pre is None:\n self.match_pre = True\nelif self.match_pre == 'true':\n self.match_pre = True\nelif self.match_pre == 'false':\n self.match_pre = False\nelse:\n raise Valu... | <|body_start_0|>
self.string = xml.get('filterText')
self.match_pre = xml.get('matchBefore')
self.match_post = xml.get('matchAfter')
if self.match_pre is None:
self.match_pre = True
elif self.match_pre == 'true':
self.match_pre = True
elif self.mat... | BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, this implies that the filterText must appear at the end of a matched document. | BasicFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicFilter:
"""BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, this implies that the filterText must appe... | stack_v2_sparse_classes_75kplus_train_008708 | 3,468 | no_license | [
{
"docstring": "Builds the BasicFilter Must have three mandatory XML attributes specified: filterText: the string on which to filter matchBefore: See match_pre attribute matchAfter: See match_post attribute Args: xml: parsed lxml representation",
"name": "__init__",
"signature": "def __init__(self, xml)... | 3 | null | Implement the Python class `BasicFilter` described below.
Class description:
BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, thi... | Implement the Python class `BasicFilter` described below.
Class description:
BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, thi... | d48de55173e2d788c0ebc54d0bf85d92dd57ff26 | <|skeleton|>
class BasicFilter:
"""BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, this implies that the filterText must appe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicFilter:
"""BasicFilter deletes any documents which match the filterText Attributes: string: The string on which to filter match_pre: If False, this implies that the filterText must appear at the beginning of a matched document. match_post: If False, this implies that the filterText must appear at the end... | the_stack_v2_python_sparse | Actions/basic.py | Sentimentron/Nebraska-public | train | 0 |
1dc07b84136b64b2286beee367508042ac3d5d95 | [
"self.name = ''\nself.emojis = ['']\nself.activation = ''\nself.expected_pos = 0\nself.flags = Flag.Flag()\nself.handle = lambda x: 'Error'\nself.usage = lambda x: 'Error'",
"msg = ''\nmsg += self.emojis[0]\nmsg += ' ' + self.name + ' '\nmsg += self.emojis[(len(self.emojis) + 1) % 2]\nreturn msg"
] | <|body_start_0|>
self.name = ''
self.emojis = ['']
self.activation = ''
self.expected_pos = 0
self.flags = Flag.Flag()
self.handle = lambda x: 'Error'
self.usage = lambda x: 'Error'
<|end_body_0|>
<|body_start_1|>
msg = ''
msg += self.emojis[0]
... | This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py. | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py."""
def __init__(self):
"""Creates a new Command object."""
<|body_0|>
async def getHelpName(self):
"""Returns the name o... | stack_v2_sparse_classes_75kplus_train_008709 | 1,304 | permissive | [
{
"docstring": "Creates a new Command object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the name of the command with the set emojis. :return: A string representing the name of the command.",
"name": "getHelpName",
"signature": "async def getHelpNa... | 2 | stack_v2_sparse_classes_30k_train_051868 | Implement the Python class `Command` described below.
Class description:
This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py.
Method signatures and docstrings:
- def __init__(self): Creates a new Command object.
- async def getHelpName(self... | Implement the Python class `Command` described below.
Class description:
This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py.
Method signatures and docstrings:
- def __init__(self): Creates a new Command object.
- async def getHelpName(self... | fd41c8a065ac8adb29148a7a888b23f2ea1592da | <|skeleton|>
class Command:
"""This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py."""
def __init__(self):
"""Creates a new Command object."""
<|body_0|>
async def getHelpName(self):
"""Returns the name o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""This stores a command with all the important information in it. For more information on how to use it, refer to CommandExample.py."""
def __init__(self):
"""Creates a new Command object."""
self.name = ''
self.emojis = ['']
self.activation = ''
self.exp... | the_stack_v2_python_sparse | src/commands/Command.py | Leopounet/GeoGuessr | train | 8 |
a4ebc6de369f5d84d680afb4003e0ae70d97b2ae | [
"nx.Graph.__init__(self)\nself._TG = TG\nself._left = list()\nself._right = list()\nself._add_nodes()\nself._add_edges()",
"matching = nx.max_weight_matching(self, maxcardinality=True)\nelist = []\nfor key in matching:\n if key.count('left') > 0:\n l = int(key.replace('left_', ''))\n r = int(matc... | <|body_start_0|>
nx.Graph.__init__(self)
self._TG = TG
self._left = list()
self._right = list()
self._add_nodes()
self._add_edges()
<|end_body_0|>
<|body_start_1|>
matching = nx.max_weight_matching(self, maxcardinality=True)
elist = []
for key in ... | Flow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
<|body_0|>
def pathify(self):
"""compute maximum weight matching"""
<|body_1|>
def _add_edges(self):
"""adds edges between nodes"""
<|body_2|>
def _add_no... | stack_v2_sparse_classes_75kplus_train_008710 | 1,982 | no_license | [
{
"docstring": "creates bi-partite graph from directed one",
"name": "__init__",
"signature": "def __init__(self, TG)"
},
{
"docstring": "compute maximum weight matching",
"name": "pathify",
"signature": "def pathify(self)"
},
{
"docstring": "adds edges between nodes",
"name"... | 4 | stack_v2_sparse_classes_30k_train_048389 | Implement the Python class `Flow` described below.
Class description:
Implement the Flow class.
Method signatures and docstrings:
- def __init__(self, TG): creates bi-partite graph from directed one
- def pathify(self): compute maximum weight matching
- def _add_edges(self): adds edges between nodes
- def _add_nodes(... | Implement the Python class `Flow` described below.
Class description:
Implement the Flow class.
Method signatures and docstrings:
- def __init__(self, TG): creates bi-partite graph from directed one
- def pathify(self): compute maximum weight matching
- def _add_edges(self): adds edges between nodes
- def _add_nodes(... | 5a1e07abb07ed0fb99241b21af5b0ba045299d22 | <|skeleton|>
class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
<|body_0|>
def pathify(self):
"""compute maximum weight matching"""
<|body_1|>
def _add_edges(self):
"""adds edges between nodes"""
<|body_2|>
def _add_no... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
nx.Graph.__init__(self)
self._TG = TG
self._left = list()
self._right = list()
self._add_nodes()
self._add_edges()
def pathify(self):
"""compute maximum weight ma... | the_stack_v2_python_sparse | SINAH/scripts/graphs/Flow.py | jim-bo/SINAH | train | 0 | |
650a01d2bb406b8130ca3b47d07a5d55d6cef788 | [
"super(IntValidator, self).__init__(v, *args, **kw)\ntry:\n self.value = int(self.value, base)\nexcept (ValueError, TypeError):\n raise ValueError(msg)",
"if self.value < max:\n return self\nraise ValueError(msg % {'value': self.value, 'max': max})",
"if self.value <= max:\n return self\nraise Value... | <|body_start_0|>
super(IntValidator, self).__init__(v, *args, **kw)
try:
self.value = int(self.value, base)
except (ValueError, TypeError):
raise ValueError(msg)
<|end_body_0|>
<|body_start_1|>
if self.value < max:
return self
raise ValueError... | Conversion and validation of integers | IntValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntValidator:
"""Conversion and validation of integers"""
def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw):
"""Initialisation Check that the value is an integer In: - ``v`` -- value to validate"""
<|body_0|>
def lesser_than(self, max, msg=_L... | stack_v2_sparse_classes_75kplus_train_008711 | 11,080 | permissive | [
{
"docstring": "Initialisation Check that the value is an integer In: - ``v`` -- value to validate",
"name": "__init__",
"signature": "def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw)"
},
{
"docstring": "Check that the value is lesser than a limit In: - ``max`` -- t... | 5 | stack_v2_sparse_classes_30k_train_004691 | Implement the Python class `IntValidator` described below.
Class description:
Conversion and validation of integers
Method signatures and docstrings:
- def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw): Initialisation Check that the value is an integer In: - ``v`` -- value to validate
- d... | Implement the Python class `IntValidator` described below.
Class description:
Conversion and validation of integers
Method signatures and docstrings:
- def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw): Initialisation Check that the value is an integer In: - ``v`` -- value to validate
- d... | 9e251f053c4edeb46b59b46d22049b29d1498727 | <|skeleton|>
class IntValidator:
"""Conversion and validation of integers"""
def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw):
"""Initialisation Check that the value is an integer In: - ``v`` -- value to validate"""
<|body_0|>
def lesser_than(self, max, msg=_L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntValidator:
"""Conversion and validation of integers"""
def __init__(self, v, base=10, msg=i18n._L('Must be an integer'), *args, **kw):
"""Initialisation Check that the value is an integer In: - ``v`` -- value to validate"""
super(IntValidator, self).__init__(v, *args, **kw)
try... | the_stack_v2_python_sparse | cifrado/web/codigo/Python/virtualenv-15.1.0/NAGARE_HOME/Lib/site-packages/nagare-0.5.1-py2.7.egg/nagare/validator.py | SanchezRuizCarlosEduardo/disor | train | 0 |
0f76b35dc98c38a9c0559169a3544e943cb235a3 | [
"if connect_string is None:\n connect_string = config.get_database()\nif connect_string.startswith('sqlite:'):\n import sqlite3\n f_name = connect_string[7:]\n util.create_dir(os.path.dirname(f_name))\n con = sqlite3.connect(f_name, detect_types=sqlite3.PARSE_DECLTYPES)\n con.row_factory = sqlite3... | <|body_start_0|>
if connect_string is None:
connect_string = config.get_database()
if connect_string.startswith('sqlite:'):
import sqlite3
f_name = connect_string[7:]
util.create_dir(os.path.dirname(f_name))
con = sqlite3.connect(f_name, detect... | The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connection. | DatabaseDriver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseDriver:
"""The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connection."""
def connect(connect_string=... | stack_v2_sparse_classes_75kplus_train_008712 | 4,249 | permissive | [
{
"docstring": "Connect to the database management system. The connect string has two parts: dbms-identifier:connect-info The dbms-identifier is used to identify the database management system that is being used by the application. The driver currently supports two different systems: sqlite and postgres The con... | 3 | stack_v2_sparse_classes_30k_train_048047 | Implement the Python class `DatabaseDriver` described below.
Class description:
The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connecti... | Implement the Python class `DatabaseDriver` described below.
Class description:
The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connecti... | 7ee5a841c1de873e8cafe2f10da4a23652395f29 | <|skeleton|>
class DatabaseDriver:
"""The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connection."""
def connect(connect_string=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseDriver:
"""The database driver establishes a connection to the database system that is used by the application. The static connect method is a wrapper around the different implementations used by supported database systems for establishing a connection."""
def connect(connect_string=None):
... | the_stack_v2_python_sparse | benchengine/db.py | scailfin/benchmark-engine | train | 0 |
7b10209a761fb168faa81ef4820ff55b83a30253 | [
"super(Seq2Seq, self).__init__(name=name)\nself.encoder = encoder_net\nself.decoder = decoder_net\nself.threshold_net = threshold_net\nself.threshold_est = Dense(n_features, activation=None)\nself.score_fn = score_fn\nself.beta = beta",
"init_state = self.encoder(x)[1]\nx_recon, z, _ = self.decoder(x, init_state=... | <|body_start_0|>
super(Seq2Seq, self).__init__(name=name)
self.encoder = encoder_net
self.decoder = decoder_net
self.threshold_net = threshold_net
self.threshold_est = Dense(n_features, activation=None)
self.score_fn = score_fn
self.beta = beta
<|end_body_0|>
<|b... | Seq2Seq | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2Seq:
def __init__(self, encoder_net: EncoderLSTM, decoder_net: DecoderLSTM, threshold_net: tf.keras.Model, n_features: int, score_fn: Callable=tf.math.squared_difference, beta: float=1.0, name: str='seq2seq') -> None:
"""Sequence-to-sequence model. Parameters ---------- encoder_net E... | stack_v2_sparse_classes_75kplus_train_008713 | 14,709 | permissive | [
{
"docstring": "Sequence-to-sequence model. Parameters ---------- encoder_net Encoder network. decoder_net Decoder network. threshold_net Regression network used to estimate threshold. n_features Number of features. score_fn Function used for outlier score. beta Weight on the threshold estimation loss term. nam... | 3 | null | Implement the Python class `Seq2Seq` described below.
Class description:
Implement the Seq2Seq class.
Method signatures and docstrings:
- def __init__(self, encoder_net: EncoderLSTM, decoder_net: DecoderLSTM, threshold_net: tf.keras.Model, n_features: int, score_fn: Callable=tf.math.squared_difference, beta: float=1.... | Implement the Python class `Seq2Seq` described below.
Class description:
Implement the Seq2Seq class.
Method signatures and docstrings:
- def __init__(self, encoder_net: EncoderLSTM, decoder_net: DecoderLSTM, threshold_net: tf.keras.Model, n_features: int, score_fn: Callable=tf.math.squared_difference, beta: float=1.... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class Seq2Seq:
def __init__(self, encoder_net: EncoderLSTM, decoder_net: DecoderLSTM, threshold_net: tf.keras.Model, n_features: int, score_fn: Callable=tf.math.squared_difference, beta: float=1.0, name: str='seq2seq') -> None:
"""Sequence-to-sequence model. Parameters ---------- encoder_net E... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Seq2Seq:
def __init__(self, encoder_net: EncoderLSTM, decoder_net: DecoderLSTM, threshold_net: tf.keras.Model, n_features: int, score_fn: Callable=tf.math.squared_difference, beta: float=1.0, name: str='seq2seq') -> None:
"""Sequence-to-sequence model. Parameters ---------- encoder_net Encoder network... | the_stack_v2_python_sparse | alibi_detect/models/tensorflow/autoencoder.py | SeldonIO/alibi-detect | train | 1,922 | |
bf7705923713dd5348732ff520f97f8a79919311 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.independent_set = set()\nself.cardinality = 0\nself.source = None",
"used = dict(((node, False) fo... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise ValueError('a loop detected')
self.independent_set = set()
self.c... | Find a maximal independent set. | SmallestFirstIndependentSet2 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmallestFirstIndependentSet2:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_008714 | 13,747 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | null | Implement the Python class `SmallestFirstIndependentSet2` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `SmallestFirstIndependentSet2` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>
class SmallestFirstIndependentSe... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class SmallestFirstIndependentSet2:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmallestFirstIndependentSet2:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
... | the_stack_v2_python_sparse | graphtheory/independentsets/isetsf.py | kgashok/graphs-dict | train | 0 |
1060748d852c981d2ebb7586e2725fff7b4f96d2 | [
"warnings.warn('In following versions this function will become deprecated. Use deepattractornet_reconstructor.py instead', Warning)\nsuper(DeepattractorSoftmaxReconstructor, self).__init__(conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation)\nusedbins_names = conf['usedbins'].split(' ')\nusedbins_da... | <|body_start_0|>
warnings.warn('In following versions this function will become deprecated. Use deepattractornet_reconstructor.py instead', Warning)
super(DeepattractorSoftmaxReconstructor, self).__init__(conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation)
usedbins_names = conf['... | the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers | DeepattractorSoftmaxReconstructor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constr... | stack_v2_sparse_classes_75kplus_train_008715 | 3,997 | permissive | [
{
"docstring": "DeepclusteringReconstructor constructor Args: conf: the reconstructor configuration as a dictionary evalconf: the evaluator configuration as a ConfigParser dataconf: the database configuration rec_dir: the directory where the reconstructions will be stored task: task name",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_025025 | Implement the Python class `DeepattractorSoftmaxReconstructor` described below.
Class description:
the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers
Method signatures and docstrings:
- def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_fra... | Implement the Python class `DeepattractorSoftmaxReconstructor` described below.
Class description:
the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers
Method signatures and docstrings:
- def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_fra... | 5e862cbf846d45b8a317f87588533f3fde9f0726 | <|skeleton|>
class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeepattractorSoftmaxReconstructor:
"""the deepattractor softmax reconstructor class a reconstructor using deep attractor netwerk with softmax maskers"""
def __init__(self, conf, evalconf, dataconf, rec_dir, task, optimal_frame_permutation=False):
"""DeepclusteringReconstructor constructor Args: c... | the_stack_v2_python_sparse | nabu/postprocessing/reconstructors/deepattractornet_softmax_reconstructor.py | JeroenZegers/Nabu-MSSS | train | 19 |
3017b94c3ff2c21b446e881931f845e0f5b140ce | [
"def dist(p):\n return p[0] ** 2 + p[1] ** 2\n\ndef quick_select(arr, s, e, k, key=dist):\n if s == e:\n return s\n p = random.randint(s, e)\n arr[e], arr[p] = (arr[p], arr[e])\n v = key(arr[e])\n i = s\n j = e - 1\n while i <= j:\n if key(arr[i]) < v:\n i += 1\n ... | <|body_start_0|>
def dist(p):
return p[0] ** 2 + p[1] ** 2
def quick_select(arr, s, e, k, key=dist):
if s == e:
return s
p = random.randint(s, e)
arr[e], arr[p] = (arr[p], arr[e])
v = key(arr[e])
i = s
j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
<|body_0|>
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Heap Time complexity: O(nlogk) Space complexity: O(... | stack_v2_sparse_classes_75kplus_train_008716 | 3,121 | no_license | [
{
"docstring": "Quick selection TLE due to the worst case",
"name": "kClosest",
"signature": "def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]"
},
{
"docstring": "Heap Time complexity: O(nlogk) Space complexity: O(k)",
"name": "kClosest",
"signature": "def kClosest(... | 2 | stack_v2_sparse_classes_30k_train_045581 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: Quick selection TLE due to the worst case
- def kClosest(self, points: List[List[int]], k: int) -> List[Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: Quick selection TLE due to the worst case
- def kClosest(self, points: List[List[int]], k: int) -> List[Li... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
<|body_0|>
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Heap Time complexity: O(nlogk) Space complexity: O(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
"""Quick selection TLE due to the worst case"""
def dist(p):
return p[0] ** 2 + p[1] ** 2
def quick_select(arr, s, e, k, key=dist):
if s == e:
return s
... | the_stack_v2_python_sparse | leetcode/solved/1014_K_Closest_Points_to_Origin/solution.py | sungminoh/algorithms | train | 0 | |
b0d2055d169a5bf7574c85f95796ec283aadcdb7 | [
"super().__init__(name=name)\nif not isinstance(blocks_args, list):\n raise ValueError('blocks_args should be a list.')\nself._global_params = global_params\nself._blocks_args = blocks_args\nself.endpoints = None\nself._build()",
"self._blocks = []\nself._stem = Stem(self._blocks_args[0].input_filters, self._g... | <|body_start_0|>
super().__init__(name=name)
if not isinstance(blocks_args, list):
raise ValueError('blocks_args should be a list.')
self._global_params = global_params
self._blocks_args = blocks_args
self.endpoints = None
self._build()
<|end_body_0|>
<|body_... | A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626 | BackboneModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackboneModel:
"""A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626"""
def __init__(self, blocks_args=None, global_params=None, name=None):
"""Initializes an `Model` instance. Args: blocks_args: A list of BlockArgs to construct block modules. global_param... | stack_v2_sparse_classes_75kplus_train_008717 | 5,614 | no_license | [
{
"docstring": "Initializes an `Model` instance. Args: blocks_args: A list of BlockArgs to construct block modules. global_params: GlobalParams, a set of global parameters. name: A string of layer name. Raises: ValueError: when blocks_args is not specified as a list.",
"name": "__init__",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_008525 | Implement the Python class `BackboneModel` described below.
Class description:
A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626
Method signatures and docstrings:
- def __init__(self, blocks_args=None, global_params=None, name=None): Initializes an `Model` instance. Args: blocks_args: A l... | Implement the Python class `BackboneModel` described below.
Class description:
A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626
Method signatures and docstrings:
- def __init__(self, blocks_args=None, global_params=None, name=None): Initializes an `Model` instance. Args: blocks_args: A l... | b7549701b0b1a7e4cc2c8275df2bc6c7a3253d24 | <|skeleton|>
class BackboneModel:
"""A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626"""
def __init__(self, blocks_args=None, global_params=None, name=None):
"""Initializes an `Model` instance. Args: blocks_args: A list of BlockArgs to construct block modules. global_param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackboneModel:
"""A class implements tf.keras.Model. Reference: https://arxiv.org/abs/1807.11626"""
def __init__(self, blocks_args=None, global_params=None, name=None):
"""Initializes an `Model` instance. Args: blocks_args: A list of BlockArgs to construct block modules. global_params: GlobalPara... | the_stack_v2_python_sparse | AIServer/ai_api/ai_models/efficientnet/backbone_model.py | tfwcn/tensorflow2-machine-vision | train | 1 |
edf3e90b1b0882d0160e358ca9b9f7a3b2da8534 | [
"with open(self.file_path, mode='rt') as fid:\n all_lines = self._parse_file(fid)\nsta_codes = self._parse_stations(all_lines)\nnum_obs = self._parse_scans(all_lines)\nself.data = {STATION_NAME_MAP.get(sta_codes[k], sta_codes[k]): v for k, v in num_obs.items() if k in sta_codes}\nif not self.data:\n self.data... | <|body_start_0|>
with open(self.file_path, mode='rt') as fid:
all_lines = self._parse_file(fid)
sta_codes = self._parse_stations(all_lines)
num_obs = self._parse_scans(all_lines)
self.data = {STATION_NAME_MAP.get(sta_codes[k], sta_codes[k]): v for k, v in num_obs.items() if k... | A parser for reading VLBI schedule files produced by SKED. | VlbiSkdParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VlbiSkdParser:
"""A parser for reading VLBI schedule files produced by SKED."""
def read_data(self):
"""Reads the schedule file and stores the information in self.data"""
<|body_0|>
def _parse_file(self, fid):
"""Store each line in the file in a dictionary based ... | stack_v2_sparse_classes_75kplus_train_008718 | 3,431 | permissive | [
{
"docstring": "Reads the schedule file and stores the information in self.data",
"name": "read_data",
"signature": "def read_data(self)"
},
{
"docstring": "Store each line in the file in a dictionary based on blocks Each block is defined by with the \"$\" character and the name of the block. Re... | 4 | stack_v2_sparse_classes_30k_train_043407 | Implement the Python class `VlbiSkdParser` described below.
Class description:
A parser for reading VLBI schedule files produced by SKED.
Method signatures and docstrings:
- def read_data(self): Reads the schedule file and stores the information in self.data
- def _parse_file(self, fid): Store each line in the file i... | Implement the Python class `VlbiSkdParser` described below.
Class description:
A parser for reading VLBI schedule files produced by SKED.
Method signatures and docstrings:
- def read_data(self): Reads the schedule file and stores the information in self.data
- def _parse_file(self, fid): Store each line in the file i... | 0c8c5c68adca08f97e22cab1bce10e382a7fbf77 | <|skeleton|>
class VlbiSkdParser:
"""A parser for reading VLBI schedule files produced by SKED."""
def read_data(self):
"""Reads the schedule file and stores the information in self.data"""
<|body_0|>
def _parse_file(self, fid):
"""Store each line in the file in a dictionary based ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VlbiSkdParser:
"""A parser for reading VLBI schedule files produced by SKED."""
def read_data(self):
"""Reads the schedule file and stores the information in self.data"""
with open(self.file_path, mode='rt') as fid:
all_lines = self._parse_file(fid)
sta_codes = self._p... | the_stack_v2_python_sparse | where/parsers/vlbi_skd.py | kartverket/where | train | 21 |
47ac04cd5de60bdf85c5d26d2c6df88e70645ab0 | [
"fake_get_distribution.side_effect = [versions.DistributionNotFound()]\nv = versions.get_iiq_version()\nself.assertTrue(v is None)",
"fake_get_distribution.side_effect = [versions.DistributionNotFound()]\nv = versions.get_iiqtools_version()\nself.assertTrue(v is None)",
"fake_get_distribution.return_value = sel... | <|body_start_0|>
fake_get_distribution.side_effect = [versions.DistributionNotFound()]
v = versions.get_iiq_version()
self.assertTrue(v is None)
<|end_body_0|>
<|body_start_1|>
fake_get_distribution.side_effect = [versions.DistributionNotFound()]
v = versions.get_iiqtools_versio... | A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions | TestGetVersions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetVersions:
"""A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions"""
def test_get_iiq_version(self, fake_get_distribution):
"""None is returned if InsightIQ is not installed"""
<|body_0|>
def test_get_iiqtools_version(self, fake_get_... | stack_v2_sparse_classes_75kplus_train_008719 | 15,840 | permissive | [
{
"docstring": "None is returned if InsightIQ is not installed",
"name": "test_get_iiq_version",
"signature": "def test_get_iiq_version(self, fake_get_distribution)"
},
{
"docstring": "None is returned if IIQTools is not installed",
"name": "test_get_iiqtools_version",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_test_002762 | Implement the Python class `TestGetVersions` described below.
Class description:
A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions
Method signatures and docstrings:
- def test_get_iiq_version(self, fake_get_distribution): None is returned if InsightIQ is not installed
- def test_get_... | Implement the Python class `TestGetVersions` described below.
Class description:
A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions
Method signatures and docstrings:
- def test_get_iiq_version(self, fake_get_distribution): None is returned if InsightIQ is not installed
- def test_get_... | a44a8ee9a299c7711b3abd69d21c24f55f2ae84e | <|skeleton|>
class TestGetVersions:
"""A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions"""
def test_get_iiq_version(self, fake_get_distribution):
"""None is returned if InsightIQ is not installed"""
<|body_0|>
def test_get_iiqtools_version(self, fake_get_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGetVersions:
"""A suite of tests for the ``get_iiq_version`` and ``get_iiqtools_version`` functions"""
def test_get_iiq_version(self, fake_get_distribution):
"""None is returned if InsightIQ is not installed"""
fake_get_distribution.side_effect = [versions.DistributionNotFound()]
... | the_stack_v2_python_sparse | iiqtools_tests/utils/test_versions.py | willnx/iiqtools | train | 5 |
6aeabeb6179cb86fb2947996f1fbf77e9b453f8a | [
"super().__init__(embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal)\nself.adapters_1 = nn.ModuleList()\nself.adapters_2 = nn.ModuleList()\nfor _ in range(num_layers):\n self.adapters_1.append(nn.Sequential(nn.Linear(embed_dim, adapters_dim), nn.ReLU(), nn.Linear(ad... | <|body_start_0|>
super().__init__(embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal)
self.adapters_1 = nn.ModuleList()
self.adapters_2 = nn.ModuleList()
for _ in range(num_layers):
self.adapters_1.append(nn.Sequential(nn.Linear(e... | TransformerWithAdapters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerWithAdapters:
def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal):
"""Transformer with adapters (small bottleneck layers)"""
<|body_0|>
def forward(self, x, padding_mask=None):
... | stack_v2_sparse_classes_75kplus_train_008720 | 7,258 | no_license | [
{
"docstring": "Transformer with adapters (small bottleneck layers)",
"name": "__init__",
"signature": "def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal)"
},
{
"docstring": "x has shape [seq length, batch], padding_... | 2 | stack_v2_sparse_classes_30k_train_052614 | Implement the Python class `TransformerWithAdapters` described below.
Class description:
Implement the TransformerWithAdapters class.
Method signatures and docstrings:
- def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal): Transformer with... | Implement the Python class `TransformerWithAdapters` described below.
Class description:
Implement the TransformerWithAdapters class.
Method signatures and docstrings:
- def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal): Transformer with... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TransformerWithAdapters:
def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal):
"""Transformer with adapters (small bottleneck layers)"""
<|body_0|>
def forward(self, x, padding_mask=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerWithAdapters:
def __init__(self, adapters_dim, embed_dim, hidden_dim, num_embeddings, num_max_positions, num_heads, num_layers, dropout, causal):
"""Transformer with adapters (small bottleneck layers)"""
super().__init__(embed_dim, hidden_dim, num_embeddings, num_max_positions, num_... | the_stack_v2_python_sparse | generated/test_prrao87_fine_grained_sentiment.py | jansel/pytorch-jit-paritybench | train | 35 | |
b911e40a3f5d80d4cfcbace42b8d3795e1f7bdcf | [
"params['n_clusters'] = n_clusters\nself.km = Kmeans(**params)\nself.metric = self.km.metric",
"self.covmeans_ = []\nself.classes_ = numpy.unique(y)\nfor c in self.classes_:\n self.km.fit(X[y == c])\n self.covmeans_.extend(self.km.centroids())\nreturn self",
"mdm = MDM(metric=self.metric)\nmdm.covmeans_ =... | <|body_start_0|>
params['n_clusters'] = n_clusters
self.km = Kmeans(**params)
self.metric = self.km.metric
<|end_body_0|>
<|body_start_1|>
self.covmeans_ = []
self.classes_ = numpy.unique(y)
for c in self.classes_:
self.km.fit(X[y == c])
self.covm... | Run kmeans for each class. | KmeansPerClassTransform | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
<|body_0|>
def fit(self, X, y):
"""fit."""
<|body_1|>
def transform(self, X):
"""transform."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_008721 | 12,224 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, n_clusters=2, **params)"
},
{
"docstring": "fit.",
"name": "fit",
"signature": "def fit(self, X, y)"
},
{
"docstring": "transform.",
"name": "transform",
"signature": "def transform(self, X)"
}... | 3 | stack_v2_sparse_classes_30k_train_008298 | Implement the Python class `KmeansPerClassTransform` described below.
Class description:
Run kmeans for each class.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, **params): Init.
- def fit(self, X, y): fit.
- def transform(self, X): transform. | Implement the Python class `KmeansPerClassTransform` described below.
Class description:
Run kmeans for each class.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, **params): Init.
- def fit(self, X, y): fit.
- def transform(self, X): transform.
<|skeleton|>
class KmeansPerClassTransform:
""... | 26c2ebf5200b5a5cd268fa73ac3928d7257d08d3 | <|skeleton|>
class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
<|body_0|>
def fit(self, X, y):
"""fit."""
<|body_1|>
def transform(self, X):
"""transform."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KmeansPerClassTransform:
"""Run kmeans for each class."""
def __init__(self, n_clusters=2, **params):
"""Init."""
params['n_clusters'] = n_clusters
self.km = Kmeans(**params)
self.metric = self.km.metric
def fit(self, X, y):
"""fit."""
self.covmeans_ =... | the_stack_v2_python_sparse | externals/pyriemann/clustering.py | kingjr/decoding_challenge_cortana_2016_3rd | train | 10 |
fabe7a434ec485e953176a31b9c49f7aea655746 | [
"if node.op_type in OP_TYPES_WITH_PARAMS:\n if len(node.input) >= param_index + 1:\n param_name = node.input[param_index]\n for param in model.graph.initializer:\n if param.name == param_name:\n return param.dims\n assert 'Param not present in the node'\nelse:\n asse... | <|body_start_0|>
if node.op_type in OP_TYPES_WITH_PARAMS:
if len(node.input) >= param_index + 1:
param_name = node.input[param_index]
for param in model.graph.initializer:
if param.name == param_name:
return param.dims
... | Param utilities | ParamUtils | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_75kplus_train_008722 | 17,157 | permissive | [
{
"docstring": "Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param feeds to the ONNX node",
"name": "get_shape",
"signature": "def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProt... | 2 | stack_v2_sparse_classes_30k_train_031424 | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param fe... | the_stack_v2_python_sparse | TrainingExtensions/onnx/src/python/aimet_onnx/utils.py | quic/aimet | train | 1,676 |
8fe1c425f278624d587049bef4a50ca0e3859938 | [
"super().__init__()\nself._reauth_input: Mapping[str, Any] | None = None\nself._reauth_entry: config_entries.ConfigEntry | None = None",
"errors = {}\nif user_input is not None:\n controller = SmartTubController(self.hass)\n try:\n account = await controller.login(user_input[CONF_EMAIL], user_input[C... | <|body_start_0|>
super().__init__()
self._reauth_input: Mapping[str, Any] | None = None
self._reauth_entry: config_entries.ConfigEntry | None = None
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
controller = SmartTubController(self.hass)
... | SmartTub configuration flow. | SmartTubConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartTubConfigFlow:
"""SmartTub configuration flow."""
def __init__(self) -> None:
"""Instantiate config flow."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the user."""
<|body_1|>
async def async_step_... | stack_v2_sparse_classes_75kplus_train_008723 | 3,463 | permissive | [
{
"docstring": "Instantiate config flow.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Handle a flow initiated by the user.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Get new... | 4 | stack_v2_sparse_classes_30k_train_018917 | Implement the Python class `SmartTubConfigFlow` described below.
Class description:
SmartTub configuration flow.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate config flow.
- async def async_step_user(self, user_input=None): Handle a flow initiated by the user.
- async def async_step_reau... | Implement the Python class `SmartTubConfigFlow` described below.
Class description:
SmartTub configuration flow.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate config flow.
- async def async_step_user(self, user_input=None): Handle a flow initiated by the user.
- async def async_step_reau... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SmartTubConfigFlow:
"""SmartTub configuration flow."""
def __init__(self) -> None:
"""Instantiate config flow."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the user."""
<|body_1|>
async def async_step_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmartTubConfigFlow:
"""SmartTub configuration flow."""
def __init__(self) -> None:
"""Instantiate config flow."""
super().__init__()
self._reauth_input: Mapping[str, Any] | None = None
self._reauth_entry: config_entries.ConfigEntry | None = None
async def async_step_u... | the_stack_v2_python_sparse | homeassistant/components/smarttub/config_flow.py | home-assistant/core | train | 35,501 |
b20c00460141fc81d76a256422d452b0d28c57ea | [
"if not elements:\n elements = []\nUserList.__init__(self, elements)\nif not name:\n self.noname = 1\n name = 'XmlList'\ndom.Element.__init__(self, name)\nself.childNodes = elements\nself.__name = name",
"if not self:\n return ''\nelif self.noname:\n return self.childNodes[0].toxml()\nelse:\n re... | <|body_start_0|>
if not elements:
elements = []
UserList.__init__(self, elements)
if not name:
self.noname = 1
name = 'XmlList'
dom.Element.__init__(self, name)
self.childNodes = elements
self.__name = name
<|end_body_0|>
<|body_start_... | XmlList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlList:
def __init__(self, elements=None, name=None):
""":param elements: :param name:"""
<|body_0|>
def toxml(self):
""":return:"""
<|body_1|>
def __str__(self):
""":return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_75kplus_train_008724 | 3,652 | permissive | [
{
"docstring": ":param elements: :param name:",
"name": "__init__",
"signature": "def __init__(self, elements=None, name=None)"
},
{
"docstring": ":return:",
"name": "toxml",
"signature": "def toxml(self)"
},
{
"docstring": ":return:",
"name": "__str__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_052124 | Implement the Python class `XmlList` described below.
Class description:
Implement the XmlList class.
Method signatures and docstrings:
- def __init__(self, elements=None, name=None): :param elements: :param name:
- def toxml(self): :return:
- def __str__(self): :return: | Implement the Python class `XmlList` described below.
Class description:
Implement the XmlList class.
Method signatures and docstrings:
- def __init__(self, elements=None, name=None): :param elements: :param name:
- def toxml(self): :return:
- def __str__(self): :return:
<|skeleton|>
class XmlList:
def __init__... | d41ed17b3b2fd7f5ae2deb48243f530cf7f494ee | <|skeleton|>
class XmlList:
def __init__(self, elements=None, name=None):
""":param elements: :param name:"""
<|body_0|>
def toxml(self):
""":return:"""
<|body_1|>
def __str__(self):
""":return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XmlList:
def __init__(self, elements=None, name=None):
""":param elements: :param name:"""
if not elements:
elements = []
UserList.__init__(self, elements)
if not name:
self.noname = 1
name = 'XmlList'
dom.Element.__init__(self, name)... | the_stack_v2_python_sparse | adsrefpipe/refparsers/xmlFile.py | golnazads/ADSReferencePipeline | train | 1 | |
22d48a3fcc0244e3cecab342a8b964eeb18f9432 | [
"url = self.API_ROOT + '/oauth/authorize?'\nquery = {'response_type': 'code', 'client_id': self.app_info[0]}\nif scope:\n if not isinstance(scope, str):\n scope = ' '.join(scope)\n query['scope'] = scope\nif redirect:\n query['redirect_uri'] = redirect\nif state:\n query['state'] = state\nreturn ... | <|body_start_0|>
url = self.API_ROOT + '/oauth/authorize?'
query = {'response_type': 'code', 'client_id': self.app_info[0]}
if scope:
if not isinstance(scope, str):
scope = ' '.join(scope)
query['scope'] = scope
if redirect:
query['redi... | Implement helpers for the Authorization Code grant for OAuth2. | AuthorizationCodeMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorizationCodeMixin:
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect, state):
"""Get the url to direct a user to authenticate."""
<|body_0|>
def exchange_code(self, code, redirect):
"""Perform the exchang... | stack_v2_sparse_classes_75kplus_train_008725 | 1,347 | permissive | [
{
"docstring": "Get the url to direct a user to authenticate.",
"name": "auth_url",
"signature": "def auth_url(self, scope, redirect, state)"
},
{
"docstring": "Perform the exchange step for the code from the redirected user.",
"name": "exchange_code",
"signature": "def exchange_code(sel... | 2 | stack_v2_sparse_classes_30k_train_008796 | Implement the Python class `AuthorizationCodeMixin` described below.
Class description:
Implement helpers for the Authorization Code grant for OAuth2.
Method signatures and docstrings:
- def auth_url(self, scope, redirect, state): Get the url to direct a user to authenticate.
- def exchange_code(self, code, redirect)... | Implement the Python class `AuthorizationCodeMixin` described below.
Class description:
Implement helpers for the Authorization Code grant for OAuth2.
Method signatures and docstrings:
- def auth_url(self, scope, redirect, state): Get the url to direct a user to authenticate.
- def exchange_code(self, code, redirect)... | 90136302307b00286f830e1cffffe8f28171049d | <|skeleton|>
class AuthorizationCodeMixin:
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect, state):
"""Get the url to direct a user to authenticate."""
<|body_0|>
def exchange_code(self, code, redirect):
"""Perform the exchang... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthorizationCodeMixin:
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect, state):
"""Get the url to direct a user to authenticate."""
url = self.API_ROOT + '/oauth/authorize?'
query = {'response_type': 'code', 'client_id': sel... | the_stack_v2_python_sparse | resources/lib/vimeo/auth/authorization_code.py | jaylinski/kodi-addon-vimeo | train | 11 |
bfaeac640db9fdebd01ddbdaeb2712f3ed3cace9 | [
"if len(strs) == 0:\n return chr(258)\nreturn chr(257).join((x for x in strs))",
"if s == chr(258):\n return []\nreturn s.split(chr(257))"
] | <|body_start_0|>
if len(strs) == 0:
return chr(258)
return chr(257).join((x for x in strs))
<|end_body_0|>
<|body_start_1|>
if s == chr(258):
return []
return s.split(chr(257))
<|end_body_1|>
| Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_008726 | 4,315 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_031992 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
if len(strs) == 0:
return chr(258)
return chr(257).join((x for x in strs))
def decode(self, s):
"""Decodes a single string to a list of strings.... | the_stack_v2_python_sparse | leet/Design/encode_and_decode_strings.py | arsamigullin/problem_solving_python | train | 0 | |
a14947783ca31c007bfd549197f4e39264e1accb | [
"cur = head = ListNode(0)\nwhile l1 or l2:\n if not l1:\n cur.next = ListNode(l2.val)\n l2 = l2.next\n elif not l2:\n cur.next = ListNode(l1.val)\n l1 = l1.next\n elif l1.val < l2.val:\n cur.next = ListNode(l1.val)\n l1 = l1.next\n else:\n cur.next = List... | <|body_start_0|>
cur = head = ListNode(0)
while l1 or l2:
if not l1:
cur.next = ListNode(l2.val)
l2 = l2.next
elif not l2:
cur.next = ListNode(l1.val)
l1 = l1.next
elif l1.val < l2.val:
cu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个有序链表"""
<|body_0|>
def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个有序链表 优化后"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head = ListN... | stack_v2_sparse_classes_75kplus_train_008727 | 2,444 | no_license | [
{
"docstring": "合并两个有序链表",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "合并两个有序链表 优化后",
"name": "mergeTwoLists2",
"signature": "def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个有序链表
- def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个有序链表 优化后 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个有序链表
- def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个有序链表 优化后
<|skeleton|>
class Sol... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个有序链表"""
<|body_0|>
def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个有序链表 优化后"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个有序链表"""
cur = head = ListNode(0)
while l1 or l2:
if not l1:
cur.next = ListNode(l2.val)
l2 = l2.next
elif not l2:
cur.next = ListNod... | the_stack_v2_python_sparse | linked_list/021 Merge Two Sorted Lists.py | mofei952/leetcode_python | train | 0 | |
c3534b26e310b67407140712672adf0d2963268f | [
"if self.overwrite:\n raise ValueError('Overwrite does not work with downloading directories through wget. Please, remove the unwanted data manually')\ncommand = ['wget'] + wget_options + self.overwrite_options + [f'--directory-prefix={self.local_folder}', '--recursive', '--no-directories', f'{server_path}']\nlo... | <|body_start_0|>
if self.overwrite:
raise ValueError('Overwrite does not work with downloading directories through wget. Please, remove the unwanted data manually')
command = ['wget'] + wget_options + self.overwrite_options + [f'--directory-prefix={self.local_folder}', '--recursive', '--no-d... | Data downloader based on wget. | WGetDownloader | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
<|body_0|>
def download_file(self... | stack_v2_sparse_classes_75kplus_train_008728 | 3,289 | permissive | [
{
"docstring": "Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget",
"name": "download_folder",
"signature": "def download_folder(self, server_path, wget_options)"
},
{
"docstring": "Download file. Parameters ---------- se... | 3 | stack_v2_sparse_classes_30k_train_040398 | Implement the Python class `WGetDownloader` described below.
Class description:
Data downloader based on wget.
Method signatures and docstrings:
- def download_folder(self, server_path, wget_options): Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options f... | Implement the Python class `WGetDownloader` described below.
Class description:
Data downloader based on wget.
Method signatures and docstrings:
- def download_folder(self, server_path, wget_options): Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options f... | 0d2b68d6614c667141207affd7834cc49d34b203 | <|skeleton|>
class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
<|body_0|>
def download_file(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WGetDownloader:
"""Data downloader based on wget."""
def download_folder(self, server_path, wget_options):
"""Download folder. Parameters ---------- server_path: str Path to remote folder wget_options: list(str) Extra options for wget"""
if self.overwrite:
raise ValueError('Ov... | the_stack_v2_python_sparse | esmvaltool/cmorizers/data/downloaders/wget.py | ESMValGroup/ESMValTool | train | 196 |
e41c0887645cd935cee0f21c74aae3fd014699ab | [
"super(Attention, self).__init__()\nself.context_matrix = nn.Linear(input_dim, context_size)\nself.context_vector = nn.Linear(context_size, 1, bias=False)\nself.softmax = torch.nn.Softmax(dim=1)\nself.tanh = activation_functions[activation]()",
"batch_size, length, n_features = x.shape\nx_att = x.reshape(batch_si... | <|body_start_0|>
super(Attention, self).__init__()
self.context_matrix = nn.Linear(input_dim, context_size)
self.context_vector = nn.Linear(context_size, 1, bias=False)
self.softmax = torch.nn.Softmax(dim=1)
self.tanh = activation_functions[activation]()
<|end_body_0|>
<|body_st... | " Attention module similarly to Luong 2015 | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_008729 | 2,621 | permissive | [
{
"docstring": "input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context",
"name": "__init__",
"signature": "def __init__(self, input_dim, context_size=32, activation='tanh')"
},
{
"docstring": "x (tensor: batch_size,sequence len... | 2 | stack_v2_sparse_classes_30k_train_038029 | Implement the Python class `Attention` described below.
Class description:
" Attention module similarly to Luong 2015
Method signatures and docstrings:
- def __init__(self, input_dim, context_size=32, activation='tanh'): input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of d... | Implement the Python class `Attention` described below.
Class description:
" Attention module similarly to Luong 2015
Method signatures and docstrings:
- def __init__(self, input_dim, context_size=32, activation='tanh'): input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of d... | c8ff3f6f857299eb2bf2e9400483084d5ecd4106 | <|skeleton|>
class Attention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attention:
"""" Attention module similarly to Luong 2015"""
def __init__(self, input_dim, context_size=32, activation='tanh'):
"""input_dim (int): Dimensions of the input/ Number of features_data context_size (int): number of dim to use from the context"""
super(Attention, self).__init__(... | the_stack_v2_python_sparse | robust_sleep_net/models/modulo_net/modules/channels_attention.py | tmorshed/RobustSleepNet | train | 0 |
1ea7afcfa4ac51a45f01cc24b7186f7af6066141 | [
"pl = PageLogin(self.driver)\npl.quick_login()\nree = ReceiveEmail(self.driver)\nree.goto_inbox()\nself.driver.switch_to.frame('mainFrame')\nree.single_check(1)\nree.mark_as_read()\nsleep(2)\nassert self.driver.find_element_by_id('_ur_c').text == '24', '标记未读失败'",
"pl = PageLogin(self.driver)\npl.quick_login()\nre... | <|body_start_0|>
pl = PageLogin(self.driver)
pl.quick_login()
ree = ReceiveEmail(self.driver)
ree.goto_inbox()
self.driver.switch_to.frame('mainFrame')
ree.single_check(1)
ree.mark_as_read()
sleep(2)
assert self.driver.find_element_by_id('_ur_c').t... | 测试标记功能 | TestMark | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMark:
"""测试标记功能"""
def test1_mark_as_unread(self):
"""测试随机单个未读标记为已读"""
<|body_0|>
def test2_mark_as_unread(self):
"""测试随机批量未读标记为已读"""
<|body_1|>
def test3_mark_as_unread(self):
"""按发件人姓名标记为已读"""
<|body_2|>
def test4_mark_as_u... | stack_v2_sparse_classes_75kplus_train_008730 | 2,631 | no_license | [
{
"docstring": "测试随机单个未读标记为已读",
"name": "test1_mark_as_unread",
"signature": "def test1_mark_as_unread(self)"
},
{
"docstring": "测试随机批量未读标记为已读",
"name": "test2_mark_as_unread",
"signature": "def test2_mark_as_unread(self)"
},
{
"docstring": "按发件人姓名标记为已读",
"name": "test3_mark_... | 4 | stack_v2_sparse_classes_30k_train_048063 | Implement the Python class `TestMark` described below.
Class description:
测试标记功能
Method signatures and docstrings:
- def test1_mark_as_unread(self): 测试随机单个未读标记为已读
- def test2_mark_as_unread(self): 测试随机批量未读标记为已读
- def test3_mark_as_unread(self): 按发件人姓名标记为已读
- def test4_mark_as_unread(self): 测试页面全部未读标记为已读 | Implement the Python class `TestMark` described below.
Class description:
测试标记功能
Method signatures and docstrings:
- def test1_mark_as_unread(self): 测试随机单个未读标记为已读
- def test2_mark_as_unread(self): 测试随机批量未读标记为已读
- def test3_mark_as_unread(self): 按发件人姓名标记为已读
- def test4_mark_as_unread(self): 测试页面全部未读标记为已读
<|skeleton|>... | d6fb7c64903dfbf89f9b10f4bc3beb72e7c251f5 | <|skeleton|>
class TestMark:
"""测试标记功能"""
def test1_mark_as_unread(self):
"""测试随机单个未读标记为已读"""
<|body_0|>
def test2_mark_as_unread(self):
"""测试随机批量未读标记为已读"""
<|body_1|>
def test3_mark_as_unread(self):
"""按发件人姓名标记为已读"""
<|body_2|>
def test4_mark_as_u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMark:
"""测试标记功能"""
def test1_mark_as_unread(self):
"""测试随机单个未读标记为已读"""
pl = PageLogin(self.driver)
pl.quick_login()
ree = ReceiveEmail(self.driver)
ree.goto_inbox()
self.driver.switch_to.frame('mainFrame')
ree.single_check(1)
ree.mark_as... | the_stack_v2_python_sparse | QQ_mail_auto_test/mail_auto_test/test_case/testI_mark_as_read.py | jianghualuo/python_selenium | train | 0 |
0c9d3b202e065b18475a060706c950b1b397b5a1 | [
"destination = validate_branch_exists_in_city(data.get('destination'))\nbooking_station = validate_branch_exists_in_city(data.get('booking_station'))\nif not destination:\n raise serializers.ValidationError({'errors': {'destination': \"We don't have a branch in that city.\"}})\nelif not booking_station:\n rai... | <|body_start_0|>
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))
if not destination:
raise serializers.ValidationError({'errors': {'destination': "We don't have a branch in that city."... | Serializer to handle the Cargo serialization. | CargoSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_008731 | 2,171 | permissive | [
{
"docstring": "Ensure all passed data is valid.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Ensure that we create the Cargo using the correct method.",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038597 | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method. | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method.
<... | 60d034681da66771412fc73402d690a9fcaa5920 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))... | the_stack_v2_python_sparse | cargotracker/cargo/serializers.py | MandelaK/CargoTracker | train | 0 |
c8e933e1fe3279a9920c57dcfdbb4a10647773f1 | [
"data_loader = deepcopy(self)\ndata_loader.load_job_config.encoding = encoding\nreturn data_loader",
"data_loader = deepcopy(self)\ndata_loader.load_job_config.autodetect = active\nreturn data_loader"
] | <|body_start_0|>
data_loader = deepcopy(self)
data_loader.load_job_config.encoding = encoding
return data_loader
<|end_body_0|>
<|body_start_1|>
data_loader = deepcopy(self)
data_loader.load_job_config.autodetect = active
return data_loader
<|end_body_1|>
| This module provide features available for all raw file loader. | RawFileLoaderMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawFileLoaderMixin:
"""This module provide features available for all raw file loader."""
def with_encoding(self, encoding: str):
"""Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: return a new instance of the current type"""
<|bo... | stack_v2_sparse_classes_75kplus_train_008732 | 1,121 | permissive | [
{
"docstring": "Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: return a new instance of the current type",
"name": "with_encoding",
"signature": "def with_encoding(self, encoding: str)"
},
{
"docstring": "Autodetect schema from Args: active (bool, o... | 2 | stack_v2_sparse_classes_30k_train_029043 | Implement the Python class `RawFileLoaderMixin` described below.
Class description:
This module provide features available for all raw file loader.
Method signatures and docstrings:
- def with_encoding(self, encoding: str): Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: ... | Implement the Python class `RawFileLoaderMixin` described below.
Class description:
This module provide features available for all raw file loader.
Method signatures and docstrings:
- def with_encoding(self, encoding: str): Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: ... | ec5e3b79abf5334783cc93edbdeb0c586f65cdf9 | <|skeleton|>
class RawFileLoaderMixin:
"""This module provide features available for all raw file loader."""
def with_encoding(self, encoding: str):
"""Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: return a new instance of the current type"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RawFileLoaderMixin:
"""This module provide features available for all raw file loader."""
def with_encoding(self, encoding: str):
"""Set encoding of the file. Args: encoding (str): encoding of the file Returns: BaseDataLoader: return a new instance of the current type"""
data_loader = dee... | the_stack_v2_python_sparse | src/bq_test_kit/bq_dsl/bq_resources/data_loaders/mixins/raw_file_loader_mixin.py | tiboun/python-bigquery-test-kit | train | 47 |
81bc2620df61bf6ef4cce9c1ff5c164ab7a0a095 | [
"try:\n log = LogInfo({'user_id': user_id, 'client_ip': client_ip, 'action_cn': action_cn, 'action_en': action_en, 'result_cn': result_cn, 'result_en': result_en, 'reason': reason})\n db.session.add(log)\n db.session.commit()\nexcept Exception as ex:\n print(ex)",
"log_list = LogInfo.query.desc(LogInf... | <|body_start_0|>
try:
log = LogInfo({'user_id': user_id, 'client_ip': client_ip, 'action_cn': action_cn, 'action_en': action_en, 'result_cn': result_cn, 'result_en': result_en, 'reason': reason})
db.session.add(log)
db.session.commit()
except Exception as ex:
... | 用于操作日志 | LogService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogService:
"""用于操作日志"""
def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason=None, user_id=None):
"""写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :param result_cn: 结果中文 :param result_en: 结果英文 :param reaso... | stack_v2_sparse_classes_75kplus_train_008733 | 2,744 | no_license | [
{
"docstring": "写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :param result_cn: 结果中文 :param result_en: 结果英文 :param reason: 失败原因 :return:",
"name": "write_log",
"signature": "def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason... | 2 | stack_v2_sparse_classes_30k_train_008856 | Implement the Python class `LogService` described below.
Class description:
用于操作日志
Method signatures and docstrings:
- def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason=None, user_id=None): 写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :... | Implement the Python class `LogService` described below.
Class description:
用于操作日志
Method signatures and docstrings:
- def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason=None, user_id=None): 写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :... | efd7a533dc7702ac99f181e2d871f92213e6c067 | <|skeleton|>
class LogService:
"""用于操作日志"""
def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason=None, user_id=None):
"""写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :param result_cn: 结果中文 :param result_en: 结果英文 :param reaso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogService:
"""用于操作日志"""
def write_log(client_ip, action_cn, action_en, result_cn, result_en, reason=None, user_id=None):
"""写操作日志 :param user_id: 用户id :param client_ip: 客户端IP :param action_cn: 操作内容中文 :param action_en: 操作内容英文 :param result_cn: 结果中文 :param result_en: 结果英文 :param reason: 失败原因 :retu... | the_stack_v2_python_sparse | Src/services/service.py | AlexYangLong/NIA | train | 0 |
dd17a244039d1180e8a8e613423e485e554d39a1 | [
"global xml_meta, corpus_size_string\nstring_cand = 'id\\tl1\\tl2\\tf\\tf1\\tf2\\tN'\nxml_meta = meta\ncorpus_size_string = str(freq_value(xml_meta.corpus_sizes))\nself.add_string(string_cand, '\\n')",
"global surface_instead_lemmas\nglobal lemmapos\nstring_cand = ''\nif entity.id_number >= 0:\n string_cand +=... | <|body_start_0|>
global xml_meta, corpus_size_string
string_cand = 'id\tl1\tl2\tf\tf1\tf2\tN'
xml_meta = meta
corpus_size_string = str(freq_value(xml_meta.corpus_sizes))
self.add_string(string_cand, '\n')
<|end_body_0|>
<|body_start_1|>
global surface_instead_lemmas
... | UCSPrinter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UCSPrinter:
def handle_meta(self, meta, info={}):
"""Print the header for the UCS dataset file, and save the corpus size."""
<|body_0|>
def handle_candidate(self, entity, info={}):
"""Print each `Candidate` as a UCS data set entry line. @param entity: The `Candidate`... | stack_v2_sparse_classes_75kplus_train_008734 | 6,421 | no_license | [
{
"docstring": "Print the header for the UCS dataset file, and save the corpus size.",
"name": "handle_meta",
"signature": "def handle_meta(self, meta, info={})"
},
{
"docstring": "Print each `Candidate` as a UCS data set entry line. @param entity: The `Candidate` that is being read from the XML... | 2 | null | Implement the Python class `UCSPrinter` described below.
Class description:
Implement the UCSPrinter class.
Method signatures and docstrings:
- def handle_meta(self, meta, info={}): Print the header for the UCS dataset file, and save the corpus size.
- def handle_candidate(self, entity, info={}): Print each `Candidat... | Implement the Python class `UCSPrinter` described below.
Class description:
Implement the UCSPrinter class.
Method signatures and docstrings:
- def handle_meta(self, meta, info={}): Print the header for the UCS dataset file, and save the corpus size.
- def handle_candidate(self, entity, info={}): Print each `Candidat... | 6e074b9a95ba2efc88e49469a0e90a028681bd12 | <|skeleton|>
class UCSPrinter:
def handle_meta(self, meta, info={}):
"""Print the header for the UCS dataset file, and save the corpus size."""
<|body_0|>
def handle_candidate(self, entity, info={}):
"""Print each `Candidate` as a UCS data set entry line. @param entity: The `Candidate`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UCSPrinter:
def handle_meta(self, meta, info={}):
"""Print the header for the UCS dataset file, and save the corpus size."""
global xml_meta, corpus_size_string
string_cand = 'id\tl1\tl2\tf\tf1\tf2\tN'
xml_meta = meta
corpus_size_string = str(freq_value(xml_meta.corpus_... | the_stack_v2_python_sparse | LANGAGE_NATUREL/Nazim/TP1/bin/mwetoolkit/bin/xml2ucs.py | n4zim/Licence_3_Informatique | train | 0 | |
ddf40d602ae3172077c025667f1e625ecda56da6 | [
"args = ('2020-04-01', '1', '1', '1')\nq = self.generate_query('update_instructor', args)\nself.check_fail_test(q, 'Invalid arguments should throw an error', RaiseException)",
"self.manager_id = self._add_person('Manager', \"Array['Database']\")\nself.instructor_id = self._add_person('Instructor', \"Array['Databa... | <|body_start_0|>
args = ('2020-04-01', '1', '1', '1')
q = self.generate_query('update_instructor', args)
self.check_fail_test(q, 'Invalid arguments should throw an error', RaiseException)
<|end_body_0|>
<|body_start_1|>
self.manager_id = self._add_person('Manager', "Array['Database']")
... | ZUpdateInstructorTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZUpdateInstructorTest:
def test_invalid_args(self):
"""Call the function using invalid arguments"""
<|body_0|>
def setup_session(self):
"""Set up the sessions to be modified"""
<|body_1|>
def test_check_update_instructor(self):
"""Check if the up... | stack_v2_sparse_classes_75kplus_train_008735 | 2,519 | no_license | [
{
"docstring": "Call the function using invalid arguments",
"name": "test_invalid_args",
"signature": "def test_invalid_args(self)"
},
{
"docstring": "Set up the sessions to be modified",
"name": "setup_session",
"signature": "def setup_session(self)"
},
{
"docstring": "Check if ... | 3 | stack_v2_sparse_classes_30k_test_002658 | Implement the Python class `ZUpdateInstructorTest` described below.
Class description:
Implement the ZUpdateInstructorTest class.
Method signatures and docstrings:
- def test_invalid_args(self): Call the function using invalid arguments
- def setup_session(self): Set up the sessions to be modified
- def test_check_up... | Implement the Python class `ZUpdateInstructorTest` described below.
Class description:
Implement the ZUpdateInstructorTest class.
Method signatures and docstrings:
- def test_invalid_args(self): Call the function using invalid arguments
- def setup_session(self): Set up the sessions to be modified
- def test_check_up... | 318693b3168b3cc99129e890d31fd1da01085b69 | <|skeleton|>
class ZUpdateInstructorTest:
def test_invalid_args(self):
"""Call the function using invalid arguments"""
<|body_0|>
def setup_session(self):
"""Set up the sessions to be modified"""
<|body_1|>
def test_check_update_instructor(self):
"""Check if the up... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZUpdateInstructorTest:
def test_invalid_args(self):
"""Call the function using invalid arguments"""
args = ('2020-04-01', '1', '1', '1')
q = self.generate_query('update_instructor', args)
self.check_fail_test(q, 'Invalid arguments should throw an error', RaiseException)
de... | the_stack_v2_python_sparse | SQL/testfiles/testclass/update_instructor_test.py | Jh123x/cs2102-project | train | 2 | |
50d2821add2bf9e291ae263ca1f04ec11066e3f9 | [
"data = {'origin': request.query_params.get('origin', ''), 'destination': request.query_params.get('destination', ''), 'departure_date': request.query_params.get('departureDate', '')}\nflight = get_object_or_404(Flight.objects.all(), pk=kwargs['id'])\nserializer = self.serializer_class(flight)\nreturn success_respo... | <|body_start_0|>
data = {'origin': request.query_params.get('origin', ''), 'destination': request.query_params.get('destination', ''), 'departure_date': request.query_params.get('departureDate', '')}
flight = get_object_or_404(Flight.objects.all(), pk=kwargs['id'])
serializer = self.serializer_c... | FlightRetrieveUpdateDestroyAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlightRetrieveUpdateDestroyAPIView:
def get(self, request, *args, **kwargs):
"""Gets a single flight"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Updates a flight"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = {'origin': requ... | stack_v2_sparse_classes_75kplus_train_008736 | 4,045 | no_license | [
{
"docstring": "Gets a single flight",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Updates a flight",
"name": "update",
"signature": "def update(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034645 | Implement the Python class `FlightRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the FlightRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Gets a single flight
- def update(self, request, *args, **kwargs): Updates a flight | Implement the Python class `FlightRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the FlightRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Gets a single flight
- def update(self, request, *args, **kwargs): Updates a flight
... | 46247f93e7f9c83441c3f50eaca2f0d3eaeca96f | <|skeleton|>
class FlightRetrieveUpdateDestroyAPIView:
def get(self, request, *args, **kwargs):
"""Gets a single flight"""
<|body_0|>
def update(self, request, *args, **kwargs):
"""Updates a flight"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlightRetrieveUpdateDestroyAPIView:
def get(self, request, *args, **kwargs):
"""Gets a single flight"""
data = {'origin': request.query_params.get('origin', ''), 'destination': request.query_params.get('destination', ''), 'departure_date': request.query_params.get('departureDate', '')}
... | the_stack_v2_python_sparse | flight/views.py | SEUNAGBEYE/Flighty | train | 0 | |
09c7e88a95b36eb05082235f1861b9df7acf91e8 | [
"assert len(points) > 0, \"The length of 'points' must be at least 1.\"\nself._points = np.ascontiguousarray(points)\nif len(self._points) > 2:\n try:\n self._hull = _qhull._Qhull(points=self._points, options=b'', mode_option=b'i', required_options=b'Qt', furthest_site=False, incremental=False, interior_p... | <|body_start_0|>
assert len(points) > 0, "The length of 'points' must be at least 1."
self._points = np.ascontiguousarray(points)
if len(self._points) > 2:
try:
self._hull = _qhull._Qhull(points=self._points, options=b'', mode_option=b'i', required_options=b'Qt', furt... | TODO: Write documentation. | ConvexHull | [
"MIT",
"BSL-1.0",
"MPL-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvexHull:
"""TODO: Write documentation."""
def __init__(self, points: np.ndarray) -> None:
"""Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D array whose first dimension corresponds to the number of... | stack_v2_sparse_classes_75kplus_train_008737 | 7,957 | permissive | [
{
"docstring": "Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D array whose first dimension corresponds to the number of points, and the second to the N-D coordinates.",
"name": "__init__",
"signature": "def __init__(sel... | 4 | null | Implement the Python class `ConvexHull` described below.
Class description:
TODO: Write documentation.
Method signatures and docstrings:
- def __init__(self, points: np.ndarray) -> None: Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D... | Implement the Python class `ConvexHull` described below.
Class description:
TODO: Write documentation.
Method signatures and docstrings:
- def __init__(self, points: np.ndarray) -> None: Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D... | a3b244f0bcb21abe605544d1f5c4a31419946efd | <|skeleton|>
class ConvexHull:
"""TODO: Write documentation."""
def __init__(self, points: np.ndarray) -> None:
"""Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D array whose first dimension corresponds to the number of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvexHull:
"""TODO: Write documentation."""
def __init__(self, points: np.ndarray) -> None:
"""Compute the convex hull defined by a set of points. :param points: N-D points whose to computed the associated convex hull, as a 2D array whose first dimension corresponds to the number of points, and ... | the_stack_v2_python_sparse | python/gym_jiminy/toolbox/gym_jiminy/toolbox/math/qhull.py | duburcqa/jiminy | train | 108 |
3a2ab2a624617dc54a5a954bf54162fb7ab6897d | [
"super().__init__(header, raw_data)\nself.status, self.length, *self.values = unpack_from(f'<{self.header.params_count}I', raw_data)\nself.data = raw_data[8:8 + self.length] if self.length > 0 else b''",
"tag = ResponseTag.name(self.header.tag)\nstatus = StatusCode.get(self.status, f'Unknown[0x{self.status:08X}]'... | <|body_start_0|>
super().__init__(header, raw_data)
self.status, self.length, *self.values = unpack_from(f'<{self.header.params_count}I', raw_data)
self.data = raw_data[8:8 + self.length] if self.length > 0 else b''
<|end_body_0|>
<|body_start_1|>
tag = ResponseTag.name(self.header.tag)... | McuBoot flash read once response format class. | FlashReadOnceResponse | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_008738 | 14,747 | permissive | [
{
"docstring": "Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data",
"name": "__init__",
"signature": "def __init__(self, header: CmdHeader, raw_data: bytes) -> None"
},
{
"docstring": "Get object info.",
"name": "info",
... | 2 | stack_v2_sparse_classes_30k_train_003678 | Implement the Python class `FlashReadOnceResponse` described below.
Class description:
McuBoot flash read once response format class.
Method signatures and docstrings:
- def __init__(self, header: CmdHeader, raw_data: bytes) -> None: Initialize the Flash-Read-Once response object. :param header: Header for the respon... | Implement the Python class `FlashReadOnceResponse` described below.
Class description:
McuBoot flash read once response format class.
Method signatures and docstrings:
- def __init__(self, header: CmdHeader, raw_data: bytes) -> None: Initialize the Flash-Read-Once response object. :param header: Header for the respon... | 4a31fb091f95fb035bc66241ee4e02dabb580072 | <|skeleton|>
class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
super().__init__(header, ... | the_stack_v2_python_sparse | spsdk/mboot/commands.py | AdrianCano-01/spsdk | train | 0 |
3c1ae498137ca0bb073c5755c2674f823f34626c | [
"super().__init__(*args, category=CATEGORY_SENSOR)\nstate = self.hass.states.get(self.entity_id)\nserv_co2 = self.add_preload_service(SERV_CARBON_DIOXIDE_SENSOR, [CHAR_CARBON_DIOXIDE_LEVEL, CHAR_CARBON_DIOXIDE_PEAK_LEVEL])\nself.char_level = serv_co2.configure_char(CHAR_CARBON_DIOXIDE_LEVEL, value=0)\nself.char_pea... | <|body_start_0|>
super().__init__(*args, category=CATEGORY_SENSOR)
state = self.hass.states.get(self.entity_id)
serv_co2 = self.add_preload_service(SERV_CARBON_DIOXIDE_SENSOR, [CHAR_CARBON_DIOXIDE_LEVEL, CHAR_CARBON_DIOXIDE_PEAK_LEVEL])
self.char_level = serv_co2.configure_char(CHAR_CARB... | Generate a CarbonDioxideSensor accessory as CO2 sensor. | CarbonDioxideSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CarbonDioxideSensor:
"""Generate a CarbonDioxideSensor accessory as CO2 sensor."""
def __init__(self, *args):
"""Initialize a CarbonDioxideSensor accessory object."""
<|body_0|>
def async_update_state(self, new_state):
"""Update accessory after state change."""
... | stack_v2_sparse_classes_75kplus_train_008739 | 17,041 | permissive | [
{
"docstring": "Initialize a CarbonDioxideSensor accessory object.",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "Update accessory after state change.",
"name": "async_update_state",
"signature": "def async_update_state(self, new_state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004020 | Implement the Python class `CarbonDioxideSensor` described below.
Class description:
Generate a CarbonDioxideSensor accessory as CO2 sensor.
Method signatures and docstrings:
- def __init__(self, *args): Initialize a CarbonDioxideSensor accessory object.
- def async_update_state(self, new_state): Update accessory aft... | Implement the Python class `CarbonDioxideSensor` described below.
Class description:
Generate a CarbonDioxideSensor accessory as CO2 sensor.
Method signatures and docstrings:
- def __init__(self, *args): Initialize a CarbonDioxideSensor accessory object.
- def async_update_state(self, new_state): Update accessory aft... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class CarbonDioxideSensor:
"""Generate a CarbonDioxideSensor accessory as CO2 sensor."""
def __init__(self, *args):
"""Initialize a CarbonDioxideSensor accessory object."""
<|body_0|>
def async_update_state(self, new_state):
"""Update accessory after state change."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CarbonDioxideSensor:
"""Generate a CarbonDioxideSensor accessory as CO2 sensor."""
def __init__(self, *args):
"""Initialize a CarbonDioxideSensor accessory object."""
super().__init__(*args, category=CATEGORY_SENSOR)
state = self.hass.states.get(self.entity_id)
serv_co2 = ... | the_stack_v2_python_sparse | homeassistant/components/homekit/type_sensors.py | home-assistant/core | train | 35,501 |
c83e8df70834f713f1f51bbcaac6363520891375 | [
"n = int(request.data['quantity'])\nloc = request.data['location']\nrequest.data['location'] = 1\nitem_info = get_object_or_404(ItemModel, pk=int(request.data['item']))\nret = {}\nfor i in range(n):\n serializer = MyItemSerializer(data=request.data)\n if not serializer.is_valid(raise_exception=True):\n ... | <|body_start_0|>
n = int(request.data['quantity'])
loc = request.data['location']
request.data['location'] = 1
item_info = get_object_or_404(ItemModel, pk=int(request.data['item']))
ret = {}
for i in range(n):
serializer = MyItemSerializer(data=request.data)
... | Shop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shop:
def post(self, request):
"""buy"""
<|body_0|>
def delete(self, request):
"""sell"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = int(request.data['quantity'])
loc = request.data['location']
request.data['location'] = 1
... | stack_v2_sparse_classes_75kplus_train_008740 | 9,686 | no_license | [
{
"docstring": "buy",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "sell",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001169 | Implement the Python class `Shop` described below.
Class description:
Implement the Shop class.
Method signatures and docstrings:
- def post(self, request): buy
- def delete(self, request): sell | Implement the Python class `Shop` described below.
Class description:
Implement the Shop class.
Method signatures and docstrings:
- def post(self, request): buy
- def delete(self, request): sell
<|skeleton|>
class Shop:
def post(self, request):
"""buy"""
<|body_0|>
def delete(self, request)... | 291ec9e7304772769be7bf52ca8511791485bffe | <|skeleton|>
class Shop:
def post(self, request):
"""buy"""
<|body_0|>
def delete(self, request):
"""sell"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Shop:
def post(self, request):
"""buy"""
n = int(request.data['quantity'])
loc = request.data['location']
request.data['location'] = 1
item_info = get_object_or_404(ItemModel, pk=int(request.data['item']))
ret = {}
for i in range(n):
serializ... | the_stack_v2_python_sparse | backend/Django/accounts/views.py | starseek34/DailyTown | train | 0 | |
b39c2636ecc0a419bab3a42117f8392ed86c90ea | [
"nph = NumpyHist.getFromRoot(h)\nif np.isnan(nph.w).any():\n logging.warning('Warning : nan found in hist %s' % h.GetName())\n return None\nif not hasattr(self, 'ne'):\n raise RuntimeError('New bin edges have not been computed, is the rebin_method() not implemented ?')\nreturn nph.rebin(self.ne).fillHistog... | <|body_start_0|>
nph = NumpyHist.getFromRoot(h)
if np.isnan(nph.w).any():
logging.warning('Warning : nan found in hist %s' % h.GetName())
return None
if not hasattr(self, 'ne'):
raise RuntimeError('New bin edges have not been computed, is the rebin_method() no... | Base rebin method includes common methods to rebin, extract and fill histograms | Rebin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
<|body_0|>
def _processHist(h):
"""Input : h, can be - ROOT.TH1X - NumpyHist already - li... | stack_v2_sparse_classes_75kplus_train_008741 | 35,100 | no_license | [
{
"docstring": "input : initial histogram TH1 return : rebinned TH1",
"name": "__call__",
"signature": "def __call__(self, h)"
},
{
"docstring": "Input : h, can be - ROOT.TH1X - NumpyHist already - list of ROOT.TH1X or NumpyHist return : NumpyHist object",
"name": "_processHist",
"signat... | 2 | stack_v2_sparse_classes_30k_val_000393 | Implement the Python class `Rebin` described below.
Class description:
Base rebin method includes common methods to rebin, extract and fill histograms
Method signatures and docstrings:
- def __call__(self, h): input : initial histogram TH1 return : rebinned TH1
- def _processHist(h): Input : h, can be - ROOT.TH1X - N... | Implement the Python class `Rebin` described below.
Class description:
Base rebin method includes common methods to rebin, extract and fill histograms
Method signatures and docstrings:
- def __call__(self, h): input : initial histogram TH1 return : rebinned TH1
- def _processHist(h): Input : h, can be - ROOT.TH1X - N... | 30df434202df51017309b5bf88a1d9b94041b6ef | <|skeleton|>
class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
<|body_0|>
def _processHist(h):
"""Input : h, can be - ROOT.TH1X - NumpyHist already - li... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
nph = NumpyHist.getFromRoot(h)
if np.isnan(nph.w).any():
logging.warning('Warning : nan found i... | the_stack_v2_python_sparse | ZAStatAnalysis/Rebinning.py | kjaffel/ZA_FullAnalysis | train | 11 |
eec8041542744c7519553d07a72bb71ea42d34ed | [
"if not f:\n self.data_frame.insert({'date': d.strftime('%Y-%m-%d'), 'span_hours': 0.0, 'sensor': None, 'bname': None, 'fname': None})\n return\nm = re.match(self.pattern, f)\nif m:\n start = timestr_to_datetime(m.group('start'))\n stop = timestr_to_datetime(m.group('stop'))\n span_hours = (stop - st... | <|body_start_0|>
if not f:
self.data_frame.insert({'date': d.strftime('%Y-%m-%d'), 'span_hours': 0.0, 'sensor': None, 'bname': None, 'fname': None})
return
m = re.match(self.pattern, f)
if m:
start = timestr_to_datetime(m.group('start'))
stop = tim... | A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values. | CheapPadHoursGridWorker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheapPadHoursGridWorker:
"""A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values."""
def do_data_frame_insert(self, d, f):
"""Parse file basename to get dict and do data frame insert."""
<|body_0|>
def get_results(self):
"""Fill data f... | stack_v2_sparse_classes_75kplus_train_008742 | 7,697 | permissive | [
{
"docstring": "Parse file basename to get dict and do data frame insert.",
"name": "do_data_frame_insert",
"signature": "def do_data_frame_insert(self, d, f)"
},
{
"docstring": "Fill data frame, pivot, and show grid.",
"name": "get_results",
"signature": "def get_results(self)"
}
] | 2 | null | Implement the Python class `CheapPadHoursGridWorker` described below.
Class description:
A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values.
Method signatures and docstrings:
- def do_data_frame_insert(self, d, f): Parse file basename to get dict and do data frame insert.
- def get_resul... | Implement the Python class `CheapPadHoursGridWorker` described below.
Class description:
A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values.
Method signatures and docstrings:
- def do_data_frame_insert(self, d, f): Parse file basename to get dict and do data frame insert.
- def get_resul... | 5a07e02588b1b7c8ebf7458b10e81b8ecf84ad13 | <|skeleton|>
class CheapPadHoursGridWorker:
"""A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values."""
def do_data_frame_insert(self, d, f):
"""Parse file basename to get dict and do data frame insert."""
<|body_0|>
def get_results(self):
"""Fill data f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheapPadHoursGridWorker:
"""A grid with days as rows, sensors as columns, & "cheap" PAD hours as cell values."""
def do_data_frame_insert(self, d, f):
"""Parse file basename to get dict and do data frame insert."""
if not f:
self.data_frame.insert({'date': d.strftime('%Y-%m-%d... | the_stack_v2_python_sparse | utils/gridworkers.py | baluneboy/pims | train | 0 |
1646348048a6d86ba2c09fe12dcd69fc868de6bc | [
"client = mock_client()\nargs = {'scim': '{\"id\": \"1234\"}'}\nmock_result = mocker.patch('AWSILM.CommandResults')\nwith requests_mock.Mocker() as m:\n m.delete(f'{groupUri}1234', status_code=204, json={})\n delete_group_command(client, args)\nassert mock_result.call_args.kwargs['outputs']['id'] == '1234'",
... | <|body_start_0|>
client = mock_client()
args = {'scim': '{"id": "1234"}'}
mock_result = mocker.patch('AWSILM.CommandResults')
with requests_mock.Mocker() as m:
m.delete(f'{groupUri}1234', status_code=204, json={})
delete_group_command(client, args)
assert ... | TestDeleteGroupCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeleteGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-delete-group' Then: - Ensure the resulted 'CommandResults' object holds information about the deleted group."""... | stack_v2_sparse_classes_75kplus_train_008743 | 23,298 | permissive | [
{
"docstring": "Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-delete-group' Then: - Ensure the resulted 'CommandResults' object holds information about the deleted group.",
"name": "test_success",
"signature": "def test_success(self... | 3 | null | Implement the Python class `TestDeleteGroupCommand` described below.
Class description:
Implement the TestDeleteGroupCommand class.
Method signatures and docstrings:
- def test_success(self, mocker): Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-... | Implement the Python class `TestDeleteGroupCommand` described below.
Class description:
Implement the TestDeleteGroupCommand class.
Method signatures and docstrings:
- def test_success(self, mocker): Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestDeleteGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-delete-group' Then: - Ensure the resulted 'CommandResults' object holds information about the deleted group."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDeleteGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a group ID. When: - Calling the main function with 'iam-delete-group' Then: - Ensure the resulted 'CommandResults' object holds information about the deleted group."""
clien... | the_stack_v2_python_sparse | Packs/AWS-ILM/Integrations/AWSILM/AWSILM_test.py | demisto/content | train | 1,023 | |
57e1ae8aef85ac908f393073b994c1f04281c5f0 | [
"if _cfg.server_backend == 'cassandra':\n clear_graph()\nelse:\n Gremlin().gremlin_post('graph.truncateBackend();')\nInsertData(gremlin='gremlin_alg_03.txt').gremlin_graph()",
"body = {'depth': 10}\ncode, res = Algorithm().post_stress_centrality(body, auth=auth)\nid = res['task_id']\nif id > 0:\n result ... | <|body_start_0|>
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_03.txt').gremlin_graph()
<|end_body_0|>
<|body_start_1|>
body = {'depth': 10}
code, res = Algori... | stress_centrality 接口 | TestStressCentrality | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStressCentrality:
"""stress_centrality 接口"""
def setup(self):
"""case 开始"""
<|body_0|>
def test_stressCentrality_01(self):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if _cfg.server_backend == 'cassandra':
clear_g... | stack_v2_sparse_classes_75kplus_train_008744 | 1,635 | no_license | [
{
"docstring": "case 开始",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": ":return:",
"name": "test_stressCentrality_01",
"signature": "def test_stressCentrality_01(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047845 | Implement the Python class `TestStressCentrality` described below.
Class description:
stress_centrality 接口
Method signatures and docstrings:
- def setup(self): case 开始
- def test_stressCentrality_01(self): :return: | Implement the Python class `TestStressCentrality` described below.
Class description:
stress_centrality 接口
Method signatures and docstrings:
- def setup(self): case 开始
- def test_stressCentrality_01(self): :return:
<|skeleton|>
class TestStressCentrality:
"""stress_centrality 接口"""
def setup(self):
... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class TestStressCentrality:
"""stress_centrality 接口"""
def setup(self):
"""case 开始"""
<|body_0|>
def test_stressCentrality_01(self):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStressCentrality:
"""stress_centrality 接口"""
def setup(self):
"""case 开始"""
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_03.txt').gremlin_graph()
... | the_stack_v2_python_sparse | src/graph_function_test/server/algorithm_olap/test_stressCentrality.py | hugegraph/hugegraph-test | train | 1 |
db6e8bdb8d82b836c8a049dd6d528ae5162c29da | [
"d = dict()\neven_num = 0\nodd_num = 0\nfor i in s:\n count = d.get(i, 0)\n count = count + 1\n if count == 2:\n d[i] = 0\n even_num = even_num + 1\n odd_num = odd_num - 1\n else:\n d[i] = count\n odd_num = odd_num + 1\nif odd_num == 0:\n return even_num * 2\nelse:\... | <|body_start_0|>
d = dict()
even_num = 0
odd_num = 0
for i in s:
count = d.get(i, 0)
count = count + 1
if count == 2:
d[i] = 0
even_num = even_num + 1
odd_num = odd_num - 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = dict()
even_num = 0
odd_num = 0
... | stack_v2_sparse_classes_75kplus_train_008745 | 1,417 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024382 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome2(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 longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestPalindrome(self... | e3fa905ea46f03b56cde662d1d7a03c4af82773a | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome2(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 longestPalindrome(self, s):
""":type s: str :rtype: int"""
d = dict()
even_num = 0
odd_num = 0
for i in s:
count = d.get(i, 0)
count = count + 1
if count == 2:
d[i] = 0
even_num = even_num... | the_stack_v2_python_sparse | pyPractice/algoproblem/Longest_palindrome_409.py | bing1zhi2/algorithmPractice | train | 0 | |
c4f885879621d0ebffa352fe5ae3c16540bd66ca | [
"super().__init__(model=model)\nself.precomputed_distances = precomputed_distances\nself.object_clusters = object_clusters\nself._dataset = dataset\nself.max_top_number = max_top_number",
"if current_num_top_doc is None:\n current_num_top_doc = self.max_top_number\ntheta = self.model.get_theta(dataset=self._da... | <|body_start_0|>
super().__init__(model=model)
self.precomputed_distances = precomputed_distances
self.object_clusters = object_clusters
self._dataset = dataset
self.max_top_number = max_top_number
<|end_body_0|>
<|body_start_1|>
if current_num_top_doc is None:
... | TopDocumentsViewer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopDocumentsViewer:
def __init__(self, model, dataset=None, precomputed_distances=None, object_clusters=None, max_top_number=10):
"""The class provide information about top documents for the model topics from some collection. Parameters ---------- model : TopicModel a class of topic mode... | stack_v2_sparse_classes_75kplus_train_008746 | 10,666 | permissive | [
{
"docstring": "The class provide information about top documents for the model topics from some collection. Parameters ---------- model : TopicModel a class of topic model dataset : Dataset a class that stores information about the collection precomputed_distances : np.array array of shape (n_topics, n_objects... | 3 | null | Implement the Python class `TopDocumentsViewer` described below.
Class description:
Implement the TopDocumentsViewer class.
Method signatures and docstrings:
- def __init__(self, model, dataset=None, precomputed_distances=None, object_clusters=None, max_top_number=10): The class provide information about top document... | Implement the Python class `TopDocumentsViewer` described below.
Class description:
Implement the TopDocumentsViewer class.
Method signatures and docstrings:
- def __init__(self, model, dataset=None, precomputed_distances=None, object_clusters=None, max_top_number=10): The class provide information about top document... | 88963c16c65b90789739419ec1697843c9a97129 | <|skeleton|>
class TopDocumentsViewer:
def __init__(self, model, dataset=None, precomputed_distances=None, object_clusters=None, max_top_number=10):
"""The class provide information about top documents for the model topics from some collection. Parameters ---------- model : TopicModel a class of topic mode... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopDocumentsViewer:
def __init__(self, model, dataset=None, precomputed_distances=None, object_clusters=None, max_top_number=10):
"""The class provide information about top documents for the model topics from some collection. Parameters ---------- model : TopicModel a class of topic model dataset : Da... | the_stack_v2_python_sparse | topicnet/viewers/top_documents_viewer.py | machine-intelligence-laboratory/TopicNet | train | 141 | |
331b9928bfb76d7440534de8ff21cced416af93f | [
"self.m = np.zeros(shape, dtype=dtype)\nself.v = np.zeros(shape, dtype=dtype)\nself.t = 0\nself._beta1 = beta1\nself._beta2 = beta2\nself._learning_rate = learning_rate\nself._epsilon = epsilon",
"self.t += 1\nself.m = self._beta1 * self.m + (1 - self._beta1) * gradient\nself.v = self._beta2 * self.v + (1 - self.... | <|body_start_0|>
self.m = np.zeros(shape, dtype=dtype)
self.v = np.zeros(shape, dtype=dtype)
self.t = 0
self._beta1 = beta1
self._beta2 = beta2
self._learning_rate = learning_rate
self._epsilon = epsilon
<|end_body_0|>
<|body_start_1|>
self.t += 1
... | Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized | AdamOptimizer | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, dtype, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):
... | stack_v2_sparse_classes_75kplus_train_008747 | 2,767 | permissive | [
{
"docstring": "Updates internal parameters of the optimizer and returns the change that should be applied to the variable. Parameters ---------- shape : tuple the shape of the input dtype : data-type the data-type of the input learning_rate: float the learning rate in the current iteration beta1: float decay r... | 2 | null | Implement the Python class `AdamOptimizer` described below.
Class description:
Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized
Method signatures and docstrings:
- def __init__(self, shap... | Implement the Python class `AdamOptimizer` described below.
Class description:
Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized
Method signatures and docstrings:
- def __init__(self, shap... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, dtype, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdamOptimizer:
"""Basic Adam optimizer implementation that can minimize w.r.t. a single variable. Parameters ---------- shape : tuple shape of the variable w.r.t. which the loss should be minimized"""
def __init__(self, shape, dtype, learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-07):
"""Updat... | the_stack_v2_python_sparse | cnns/foolbox/foolbox_2_3_0/optimizers.py | adam-dziedzic/bandlimited-cnns | train | 17 |
b6b2ea977aa884529ea0af6a83cb3d35753ed872 | [
"super().__init__()\nself.u_dc, self.i_L = ([], [])\nself.i_dc, self.u_di, self.u_g, self.i_g = (0, 0, 0, 0)",
"super().save(mdl, sol)\nself.u_dc.extend(sol.y[4].real)\nself.i_L.extend(sol.y[5].real)",
"super().post_process(mdl)\nself.u_dc = np.asarray(self.u_dc)\nself.i_L = np.asarray(self.i_L)\nself.u_ss = md... | <|body_start_0|>
super().__init__()
self.u_dc, self.i_L = ([], [])
self.i_dc, self.u_di, self.u_g, self.i_g = (0, 0, 0, 0)
<|end_body_0|>
<|body_start_1|>
super().save(mdl, sol)
self.u_dc.extend(sol.y[4].real)
self.i_L.extend(sol.y[5].real)
<|end_body_1|>
<|body_start_2... | Extends the default data logger for the model with the DC-bus dynamics. | DataloggerExtended | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataloggerExtended:
"""Extends the default data logger for the model with the DC-bus dynamics."""
def __init__(self):
"""Initialize the attributes."""
<|body_0|>
def save(self, mdl, sol):
"""Extends the base class."""
<|body_1|>
def post_process(self... | stack_v2_sparse_classes_75kplus_train_008748 | 13,550 | permissive | [
{
"docstring": "Initialize the attributes.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Extends the base class.",
"name": "save",
"signature": "def save(self, mdl, sol)"
},
{
"docstring": "Extends the base class.",
"name": "post_process",
"si... | 3 | null | Implement the Python class `DataloggerExtended` described below.
Class description:
Extends the default data logger for the model with the DC-bus dynamics.
Method signatures and docstrings:
- def __init__(self): Initialize the attributes.
- def save(self, mdl, sol): Extends the base class.
- def post_process(self, md... | Implement the Python class `DataloggerExtended` described below.
Class description:
Extends the default data logger for the model with the DC-bus dynamics.
Method signatures and docstrings:
- def __init__(self): Initialize the attributes.
- def save(self, mdl, sol): Extends the base class.
- def post_process(self, md... | cc495858fa46267048583281df062a74de78574c | <|skeleton|>
class DataloggerExtended:
"""Extends the default data logger for the model with the DC-bus dynamics."""
def __init__(self):
"""Initialize the attributes."""
<|body_0|>
def save(self, mdl, sol):
"""Extends the base class."""
<|body_1|>
def post_process(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataloggerExtended:
"""Extends the default data logger for the model with the DC-bus dynamics."""
def __init__(self):
"""Initialize the attributes."""
super().__init__()
self.u_dc, self.i_L = ([], [])
self.i_dc, self.u_di, self.u_g, self.i_g = (0, 0, 0, 0)
def save(se... | the_stack_v2_python_sparse | model/im_drive.py | deepaksawIITD/motulator | train | 0 |
ca813c490d8b9b04f642140945bdb8fe6c8f1aeb | [
"content_type = ContentType.objects.get_for_model(instance.__class__)\nqueryset = super(RateManager, self).filter(content_type=content_type, object_id=instance.id)\nreturn queryset",
"try:\n my_avg = self.filter_by_model(instance).aggregate(Avg('rating'))\nexcept ZeroDivisionError:\n logging.error(error_han... | <|body_start_0|>
content_type = ContentType.objects.get_for_model(instance.__class__)
queryset = super(RateManager, self).filter(content_type=content_type, object_id=instance.id)
return queryset
<|end_body_0|>
<|body_start_1|>
try:
my_avg = self.filter_by_model(instance).agg... | RateManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateManager:
def filter_by_model(self, instance):
"""filter kardane content bar assasse model"""
<|body_0|>
def avg_rate(self, instance, avg=0):
"""emtiaz dehi be post bar assasse rate entekhab shude (az 1 ta 5) taghsim bar tedad e user haey ke be in post emtiaz dada... | stack_v2_sparse_classes_75kplus_train_008749 | 2,877 | permissive | [
{
"docstring": "filter kardane content bar assasse model",
"name": "filter_by_model",
"signature": "def filter_by_model(self, instance)"
},
{
"docstring": "emtiaz dehi be post bar assasse rate entekhab shude (az 1 ta 5) taghsim bar tedad e user haey ke be in post emtiaz dadan",
"name": "avg_... | 2 | stack_v2_sparse_classes_30k_train_052936 | Implement the Python class `RateManager` described below.
Class description:
Implement the RateManager class.
Method signatures and docstrings:
- def filter_by_model(self, instance): filter kardane content bar assasse model
- def avg_rate(self, instance, avg=0): emtiaz dehi be post bar assasse rate entekhab shude (az... | Implement the Python class `RateManager` described below.
Class description:
Implement the RateManager class.
Method signatures and docstrings:
- def filter_by_model(self, instance): filter kardane content bar assasse model
- def avg_rate(self, instance, avg=0): emtiaz dehi be post bar assasse rate entekhab shude (az... | aef47922fdd6488550881ed9d42bf30a0d33a32a | <|skeleton|>
class RateManager:
def filter_by_model(self, instance):
"""filter kardane content bar assasse model"""
<|body_0|>
def avg_rate(self, instance, avg=0):
"""emtiaz dehi be post bar assasse rate entekhab shude (az 1 ta 5) taghsim bar tedad e user haey ke be in post emtiaz dada... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RateManager:
def filter_by_model(self, instance):
"""filter kardane content bar assasse model"""
content_type = ContentType.objects.get_for_model(instance.__class__)
queryset = super(RateManager, self).filter(content_type=content_type, object_id=instance.id)
return queryset
... | the_stack_v2_python_sparse | src/rates/models.py | m3h-D/Myinfoblog | train | 0 | |
5d1d15bc365c7fbe007055020eac9e62c690077f | [
"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... | DataBusServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataBusServicer:
def Publish(self, request, context):
"""Declares the intention to write data to a topic, must be called once before any Write."""
<|body_0|>
def Subscribe(self, request, context):
"""Declares the intention to read data from a topic, must be called on... | stack_v2_sparse_classes_75kplus_train_008750 | 6,014 | no_license | [
{
"docstring": "Declares the intention to write data to a topic, must be called once before any Write.",
"name": "Publish",
"signature": "def Publish(self, request, context)"
},
{
"docstring": "Declares the intention to read data from a topic, must be called once before any Read.",
"name": "... | 6 | stack_v2_sparse_classes_30k_train_038117 | Implement the Python class `DataBusServicer` described below.
Class description:
Implement the DataBusServicer class.
Method signatures and docstrings:
- def Publish(self, request, context): Declares the intention to write data to a topic, must be called once before any Write.
- def Subscribe(self, request, context):... | Implement the Python class `DataBusServicer` described below.
Class description:
Implement the DataBusServicer class.
Method signatures and docstrings:
- def Publish(self, request, context): Declares the intention to write data to a topic, must be called once before any Write.
- def Subscribe(self, request, context):... | 090b9bd6af1fdf012afc4b7cc19c3c80e4651dba | <|skeleton|>
class DataBusServicer:
def Publish(self, request, context):
"""Declares the intention to write data to a topic, must be called once before any Write."""
<|body_0|>
def Subscribe(self, request, context):
"""Declares the intention to read data from a topic, must be called on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataBusServicer:
def Publish(self, request, context):
"""Declares the intention to write data to a topic, must be called once before any Write."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method no... | the_stack_v2_python_sparse | NativeAPI/Native-API/Tools/DataConversion/python/metamoto/services/data_bus_pb2_grpc.py | Huzefa-Kagalwala/OpenCAV-Metamoto | train | 0 | |
34120e69b241db7ecb9d0ff370d11129f8c865f1 | [
"if num < 1:\n return False\nwhile num % 2 == 0:\n num = num // 2\nwhile num % 3 == 0:\n num = num // 3\nwhile num % 5 == 0:\n num = num // 5\nreturn num != 1",
"a = list([1])\nx2 = 0\nx3 = 0\nx5 = 0\nwhile len(a) < n:\n t2 = a[x2] * 2\n t3 = a[x3] * 3\n t5 = a[x5] * 5\n t = min(t2, t3, t5... | <|body_start_0|>
if num < 1:
return False
while num % 2 == 0:
num = num // 2
while num % 3 == 0:
num = num // 3
while num % 5 == 0:
num = num // 5
return num != 1
<|end_body_0|>
<|body_start_1|>
a = list([1])
x2 = 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num < 1:
return False
while num % 2 == 0:
... | stack_v2_sparse_classes_75kplus_train_008751 | 834 | no_license | [
{
"docstring": ":type num: int :rtype: bool",
"name": "isUgly",
"signature": "def isUgly(self, num)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber",
"signature": "def nthUglyNumber(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006682 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthUglyNumber(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthUglyNumber(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def isUgly(self, num):
""":ty... | 113d052de41d85f366c9497fb132df91e619f13a | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
if num < 1:
return False
while num % 2 == 0:
num = num // 2
while num % 3 == 0:
num = num // 3
while num % 5 == 0:
num = num // 5
return num != 1
... | the_stack_v2_python_sparse | ugly-number.py | ding4it/leetcode | train | 1 | |
835926b36488f32eae9e38617b050ed6c348ef0e | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ajr10_chamathd_williami', 'ajr10_chamathd_williami')\nprint('Fetching Boston neighborhood geospatial data from City of Boston Data Portal')\ncolName = 'ajr10_chamathd_williami.neighborhood_area_boston'\n... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_chamathd_williami', 'ajr10_chamathd_williami')
print('Fetching Boston neighborhood geospatial data from City of Boston Data Portal')
colName... | fetch_neighborhood_area_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fetch_neighborhood_area_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening... | stack_v2_sparse_classes_75kplus_train_008752 | 6,226 | no_license | [
{
"docstring": "Retrieve some data sets for the MongoDB collection.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that i... | 2 | null | Implement the Python class `fetch_neighborhood_area_data` described below.
Class description:
Implement the fetch_neighborhood_area_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets for the MongoDB collection.
- def provenance(doc=prov.model.ProvDocument(), startTime=No... | Implement the Python class `fetch_neighborhood_area_data` described below.
Class description:
Implement the fetch_neighborhood_area_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets for the MongoDB collection.
- def provenance(doc=prov.model.ProvDocument(), startTime=No... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class fetch_neighborhood_area_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class fetch_neighborhood_area_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_chamathd_williami', 'ajr10_chamathd_willi... | the_stack_v2_python_sparse | ajr10_chamathd_williami/fetch_neighborhood_area_data.py | lingyigu/course-2017-spr-proj | train | 0 | |
91fdacb3c856743643ffced2e2963efbb77224da | [
"if not root:\n return None\nhead, tail = self.helper(root)\nreturn head",
"head, tail = (root, root)\nif root.left:\n left_head, left_tail = self.helper(root.left)\n left_tail.right = root\n root.left = left_tail\n head = left_head\nif root.right:\n right_head, right_tail = self.helper(root.rig... | <|body_start_0|>
if not root:
return None
head, tail = self.helper(root)
return head
<|end_body_0|>
<|body_start_1|>
head, tail = (root, root)
if root.left:
left_head, left_tail = self.helper(root.left)
left_tail.right = root
root.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
r... | stack_v2_sparse_classes_75kplus_train_008753 | 4,401 | no_license | [
{
"docstring": ":type root: Node :rtype: Node",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root)"
},
{
"docstring": "construct a doubly-linked list, return the head and tail",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033700 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): construct a doubly-linked list, return the head and tail | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): construct a doubly-linked list, return the head and tail
<|skeleton|>
class Solution:
... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
if not root:
return None
head, tail = self.helper(root)
return head
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
head, tail... | the_stack_v2_python_sparse | 426. Convert BST to Sorted Doubly Linked List.py | dundunmao/LeetCode2019 | train | 0 | |
5acfc60f596252a0c97856ada7d5a1bca1f03d35 | [
"super(TFN, self).__init__()\nself.audio_in = input_dims[0]\nself.video_in = input_dims[1]\nself.text_in = input_dims[2]\nself.audio_hidden = hidden_dims[0]\nself.video_hidden = hidden_dims[1]\nself.text_hidden = hidden_dims[2]\nself.text_out = text_out\nself.post_fusion_dim = post_fusion_dim\nself.audio_prob = dro... | <|body_start_0|>
super(TFN, self).__init__()
self.audio_in = input_dims[0]
self.video_in = input_dims[1]
self.text_in = input_dims[2]
self.audio_hidden = hidden_dims[0]
self.video_hidden = hidden_dims[1]
self.text_hidden = hidden_dims[2]
self.text_out = te... | Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral. | TFN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFN:
"""Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral."""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, post_fusion_dim):
"""... | stack_v2_sparse_classes_75kplus_train_008754 | 8,234 | no_license | [
{
"docstring": "Args: input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim) hidden_dims - another length-3 tuple, similar to input_dims text_out - int, specifying the resulting dimensions of the text subnetwork dropouts - a length-4 tuple, contains (audio_dropout, video_dropout, text_dropout,... | 2 | stack_v2_sparse_classes_30k_train_017238 | Implement the Python class `TFN` described below.
Class description:
Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral.
Method signatures and docstrings:
- def __init__(self, input_... | Implement the Python class `TFN` described below.
Class description:
Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral.
Method signatures and docstrings:
- def __init__(self, input_... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TFN:
"""Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral."""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, post_fusion_dim):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TFN:
"""Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in: Zadeh, Amir, et al. "Tensor fusion network for multimodal sentiment analysis." EMNLP 2017 Oral."""
def __init__(self, input_dims, hidden_dims, text_out, dropouts, post_fusion_dim):
"""Args: input_d... | the_stack_v2_python_sparse | generated/test_Justin1904_TensorFusionNetworks.py | jansel/pytorch-jit-paritybench | train | 35 |
7a446ed9876a6def0d6b04c7a501b3552253f473 | [
"total = self.quantity_total()\nhardware = self.hardware_resource()\nmost = self.quantity_most()\nreturn {'message': 'success', 'data': {'total': total, 'hardware': hardware, 'most': most}, 'code': 200}",
"deploys = databases.deploy.count_documents({})\ntimers = databases.timer.count_documents({})\nrecords = data... | <|body_start_0|>
total = self.quantity_total()
hardware = self.hardware_resource()
most = self.quantity_most()
return {'message': 'success', 'data': {'total': total, 'hardware': hardware, 'most': most}, 'code': 200}
<|end_body_0|>
<|body_start_1|>
deploys = databases.deploy.coun... | IndexHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexHandler:
def get(self):
"""* @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @apiSuccess {Int} jobs 任务总数 * @apiSuccess {Int} records 执行记录总数 * @apiSuccess {Int} timers 调度总数 * @apiS... | stack_v2_sparse_classes_75kplus_train_008755 | 5,480 | no_license | [
{
"docstring": "* @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @apiSuccess {Int} jobs 任务总数 * @apiSuccess {Int} records 执行记录总数 * @apiSuccess {Int} timers 调度总数 * @apiSuccess {Int} users 用户总数 * @apiSuccess {I... | 4 | stack_v2_sparse_classes_30k_train_046138 | Implement the Python class `IndexHandler` described below.
Class description:
Implement the IndexHandler class.
Method signatures and docstrings:
- def get(self): * @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @... | Implement the Python class `IndexHandler` described below.
Class description:
Implement the IndexHandler class.
Method signatures and docstrings:
- def get(self): * @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @... | b9734e9bae3703e328cacf1969d26e2b334b889a | <|skeleton|>
class IndexHandler:
def get(self):
"""* @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @apiSuccess {Int} jobs 任务总数 * @apiSuccess {Int} records 执行记录总数 * @apiSuccess {Int} timers 调度总数 * @apiS... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndexHandler:
def get(self):
"""* @api {get} /work 工作台信息 * @apiPermission Role.Other * @apiHeader (Header) {String} Authorization Authorization value. * @apiSuccess {Int} deploys 项目总数 * @apiSuccess {Int} jobs 任务总数 * @apiSuccess {Int} records 执行记录总数 * @apiSuccess {Int} timers 调度总数 * @apiSuccess {Int} u... | the_stack_v2_python_sparse | handler/index.py | 7ee3/sailboat | train | 0 | |
73dfd60aae18ce455bdc3908d8c3c58fa22f1d19 | [
"path = self.SUB_BASEURL + '/' + account + '/' + name\nurl = build_url(choice(self.list_hosts), path=path)\nif retroactive:\n raise NotImplementedError('Retroactive mode is not implemented')\nif filter_ and (not isinstance(filter_, dict)):\n raise TypeError('filter should be a dict')\nif replication_rules and... | <|body_start_0|>
path = self.SUB_BASEURL + '/' + account + '/' + name
url = build_url(choice(self.list_hosts), path=path)
if retroactive:
raise NotImplementedError('Retroactive mode is not implemented')
if filter_ and (not isinstance(filter_, dict)):
raise TypeErr... | SubscriptionClient class for working with subscriptions | SubscriptionClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_75kplus_train_008756 | 7,980 | permissive | [
{
"docstring": "Adds a new subscription which will be verified against every new added file and dataset :param name: Name of the subscription :type: String :param account: Account identifier :type account: String :param filter_: Dictionary of attributes by which the input data should be filtered **Example**: ``... | 4 | stack_v2_sparse_classes_30k_train_007137 | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added file and dataset... | the_stack_v2_python_sparse | lib/rucio/client/subscriptionclient.py | rucio/rucio | train | 232 |
7d11ffbca1b56700327d9bf296d078a445458f85 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('last_pk', type=int, default=0, location='args')\nfilter_parser.add_argument('limit_num', type=int, default=20, location='args')\nfilter_parser_args = filter_parser.parse_args()\ndata = get_fetch_result_limit_rows_by_last_id(**f... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('last_pk', type=int, default=0, location='args')
filter_parser.add_argument('limit_num', type=int, default=20, location='args')
filter_parser_args = filter_parser.parse_args()
d... | FetchResultListResource | FetchResultListResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0... | stack_v2_sparse_classes_75kplus_train_008757 | 11,580 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/news/fetch_results -H \"Content-Type: application/... | 2 | stack_v2_sparse_classes_30k_train_039096 | Implement the Python class `FetchResultListResource` described below.
Class description:
FetchResultListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Examp... | Implement the Python class `FetchResultListResource` described below.
Class description:
FetchResultListResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Examp... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetchResultListResource:
"""FetchResultListResource"""
def get(self):
"""Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.a... | the_stack_v2_python_sparse | web_api/news/resources/fetch_result.py | zhanghe06/flask_restful | train | 2 |
9184cb39bebd2bbbad3ad44212c6f27a74219ede | [
"fields = cls.IMPORT_FIELDS\nfor name, field in fields.items():\n base_field = None\n for f in cls._meta.fields:\n if f.name == name:\n base_field = f\n break\n if base_field:\n if 'label' not in field:\n field['label'] = base_field.verbose_name\n if 'h... | <|body_start_0|>
fields = cls.IMPORT_FIELDS
for name, field in fields.items():
base_field = None
for f in cls._meta.fields:
if f.name == name:
base_field = f
break
if base_field:
if 'label' not in... | Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import | DataImportMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a p... | stack_v2_sparse_classes_75kplus_train_008758 | 29,718 | permissive | [
{
"docstring": "Return all available import fields. Where information on a particular field is not explicitly provided, introspect the base model to (attempt to) find that information.",
"name": "get_import_fields",
"signature": "def get_import_fields(cls)"
},
{
"docstring": "Return all *require... | 2 | stack_v2_sparse_classes_30k_train_014928 | Implement the Python class `DataImportMixin` described below.
Class description:
Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import
Method signatures and docstrings:
- def get_import_fields(cls): Ret... | Implement the Python class `DataImportMixin` described below.
Class description:
Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import
Method signatures and docstrings:
- def get_import_fields(cls): Ret... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataImportMixin:
"""Model mixin class which provides support for 'data import' functionality. Models which implement this mixin should provide information on the fields available for import"""
def get_import_fields(cls):
"""Return all available import fields. Where information on a particular fie... | the_stack_v2_python_sparse | InvenTree/InvenTree/models.py | inventree/InvenTree | train | 3,077 |
c1aa2c79ec02ea2569d041088936be373b090142 | [
"s.dingding = dingding\ns.subscription_dictionary = d\ns.match_pattern = d['MatchPattern']\ns.xmlrpc_recv_url = d['XmlRpcRecvUrl']\ns.recv_password = d.get('RecvPassword', None)\ns.subscription_passwords = d.get('SubscriptionPasswords', [])\ns.who_can_see_this = d.get('WhoCanSeeThis', s.dingding.options.get_default... | <|body_start_0|>
s.dingding = dingding
s.subscription_dictionary = d
s.match_pattern = d['MatchPattern']
s.xmlrpc_recv_url = d['XmlRpcRecvUrl']
s.recv_password = d.get('RecvPassword', None)
s.subscription_passwords = d.get('SubscriptionPasswords', [])
s.who_can_se... | Subscription - augment a subscription dictionary | Subscription | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscription:
"""Subscription - augment a subscription dictionary"""
def __init__(s, d, dingding):
"""subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL for receiving Notify messages * RecvPassword (OPTIONAL - ... | stack_v2_sparse_classes_75kplus_train_008759 | 25,098 | permissive | [
{
"docstring": "subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL for receiving Notify messages * RecvPassword (OPTIONAL - used when posting a NOTIFY, also a legitimizing recipient password) * SubscriptionPasswords (OPTIONAL - group pass... | 2 | stack_v2_sparse_classes_30k_train_013202 | Implement the Python class `Subscription` described below.
Class description:
Subscription - augment a subscription dictionary
Method signatures and docstrings:
- def __init__(s, d, dingding): subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL ... | Implement the Python class `Subscription` described below.
Class description:
Subscription - augment a subscription dictionary
Method signatures and docstrings:
- def __init__(s, d, dingding): subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL ... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class Subscription:
"""Subscription - augment a subscription dictionary"""
def __init__(s, d, dingding):
"""subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL for receiving Notify messages * RecvPassword (OPTIONAL - ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Subscription:
"""Subscription - augment a subscription dictionary"""
def __init__(s, d, dingding):
"""subscription dictionary: * MatchPattern (*REQUIRED* - pattern of data matching out) * XmlRpcRecvUrl (REQUIRED) - XML-RPC URL for receiving Notify messages * RecvPassword (OPTIONAL - used when pos... | the_stack_v2_python_sparse | ancient/src/dingding/dingding.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
d5d778e5a37926f9cffd3e47b35bf56621573fe6 | [
"tmp = self.mkdtemp()\nret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('CC', GOANNA_WRAPPER), ('CFLAGS', '--license-server=%s' % GOANNA_LICENSE_SERVER)]))\nif ret != 0:\n self.fail('cmake failed:\\n%s\\n%s' % (stdout, stderr))\nret, stdout, s... | <|body_start_0|>
tmp = self.mkdtemp()
ret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('CC', GOANNA_WRAPPER), ('CFLAGS', '--license-server=%s' % GOANNA_LICENSE_SERVER)]))
if ret != 0:
self.fail('cmake failed:\n%s\n... | TestStaticAnalysis | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
<|body_0|>
def test_clang_static_analyser(self):
"""Run the Clang static analyser on the accelerator."""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_008760 | 4,207 | permissive | [
{
"docstring": "Test whether the Goanna static analyser can find any problems with the accelerator.",
"name": "test_goanna_compilation",
"signature": "def test_goanna_compilation(self)"
},
{
"docstring": "Run the Clang static analyser on the accelerator.",
"name": "test_clang_static_analyser... | 3 | stack_v2_sparse_classes_30k_train_002660 | Implement the Python class `TestStaticAnalysis` described below.
Class description:
Implement the TestStaticAnalysis class.
Method signatures and docstrings:
- def test_goanna_compilation(self): Test whether the Goanna static analyser can find any problems with the accelerator.
- def test_clang_static_analyser(self):... | Implement the Python class `TestStaticAnalysis` described below.
Class description:
Implement the TestStaticAnalysis class.
Method signatures and docstrings:
- def test_goanna_compilation(self): Test whether the Goanna static analyser can find any problems with the accelerator.
- def test_clang_static_analyser(self):... | 26bae4a3f000afca18bc7cf84a55e54f8fa9e4c2 | <|skeleton|>
class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
<|body_0|>
def test_clang_static_analyser(self):
"""Run the Clang static analyser on the accelerator."""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStaticAnalysis:
def test_goanna_compilation(self):
"""Test whether the Goanna static analyser can find any problems with the accelerator."""
tmp = self.mkdtemp()
ret, stdout, stderr = self.execute(['cmake', '-G', 'Unix Makefiles', MY_DIR], cwd=tmp, env=dict(os.environ.items() + [('... | the_stack_v2_python_sparse | tools/camkes/tools/accelerator/teststaticanalysis.py | ifscamkes/staticifs-camkes | train | 0 | |
8cc9a114f432e849366985487cbcfb8c4a5e4c6f | [
"try:\n pfolder_root = Extract.projects_folder_root(job_num)\nexcept ProjectsFolderRootError as error:\n msg = 'Make sure this job has a valid PROJECTS FOLDER and try again'\n error.message = '%s\\n%s.' % (error.message, msg)\n logging.warning(error)\n raise\ntry:\n rw_job_root = create_folder(os.... | <|body_start_0|>
try:
pfolder_root = Extract.projects_folder_root(job_num)
except ProjectsFolderRootError as error:
msg = 'Make sure this job has a valid PROJECTS FOLDER and try again'
error.message = '%s\n%s.' % (error.message, msg)
logging.warning(error)... | Project | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Project:
def folder(job_num, phase, subtype, nickname):
"""Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Returns ------- rw_project_folder : str Raises ------ ProjectsFolderRoot If the PROJECTS FOLDER root... | stack_v2_sparse_classes_75kplus_train_008761 | 3,829 | no_license | [
{
"docstring": "Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Returns ------- rw_project_folder : str Raises ------ ProjectsFolderRoot If the PROJECTS FOLDER root cannot be found. This path is used to help determine the ROTOWORKS... | 4 | stack_v2_sparse_classes_30k_train_023051 | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def folder(job_num, phase, subtype, nickname): Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Retu... | Implement the Python class `Project` described below.
Class description:
Implement the Project class.
Method signatures and docstrings:
- def folder(job_num, phase, subtype, nickname): Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Retu... | bde9efc64a00cf897649bab45094d13b2c4d4908 | <|skeleton|>
class Project:
def folder(job_num, phase, subtype, nickname):
"""Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Returns ------- rw_project_folder : str Raises ------ ProjectsFolderRoot If the PROJECTS FOLDER root... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Project:
def folder(job_num, phase, subtype, nickname):
"""Get the absolute path to a ROTOWORKS project folder. Parameters ---------- job_num : str phase : str subtype : str nickname: str Returns ------- rw_project_folder : str Raises ------ ProjectsFolderRoot If the PROJECTS FOLDER root cannot be fou... | the_stack_v2_python_sparse | rotoworks/project.py | brand-clear/rotoworks | train | 0 | |
727cb7eb753b0b002a471185216c0d716a45451c | [
"res = 0\nnumOfOdd = 0\nd = {}\nfor c in s:\n if c not in d:\n d[c] = 1\n else:\n d[c] += 1\nfor k in d:\n if d[k] % 2 == 1:\n numOfOdd += 1\nif numOfOdd > 1:\n res = len(s) - numOfOdd + 1\n return res\nelse:\n return len(s)",
"res = 0\nnumOfOdd = 0\nd = collections.Counter(... | <|body_start_0|>
res = 0
numOfOdd = 0
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
for k in d:
if d[k] % 2 == 1:
numOfOdd += 1
if numOfOdd > 1:
res = len(s) - num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
numOfOdd = 0
d = {}
for ... | stack_v2_sparse_classes_75kplus_train_008762 | 1,788 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome2(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 longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestPalindrome(self... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome2(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 longestPalindrome(self, s):
""":type s: str :rtype: int"""
res = 0
numOfOdd = 0
d = {}
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
for k in d:
if d[k] % 2 == 1:
... | the_stack_v2_python_sparse | 13.HASH MAP/409_longest_palindrome/solution.py | kimmyoo/python_leetcode | train | 1 | |
5df7f8e01ac13dd07c9e17d38515b15682ee2324 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nif is_teacher:\n TeacherProfile.objects.create(user=user)\nelse:\n StudentProfile.objects.create(user=user)\nreturn user",
"... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
if is_teacher:
TeacherProfile.objects.create(user=user)
e... | MyUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None, is_teacher=False):
"""Создание и сохранение пользователя"""
<|body_0|>
def create_superuser(self, email, password=None, is_teacher=False):
"""Creates and saves a superuser with the given email, date of birth ... | stack_v2_sparse_classes_75kplus_train_008763 | 2,969 | permissive | [
{
"docstring": "Создание и сохранение пользователя",
"name": "create_user",
"signature": "def create_user(self, email, password=None, is_teacher=False)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "create_superuser",
"signa... | 2 | stack_v2_sparse_classes_30k_train_013331 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, is_teacher=False): Создание и сохранение пользователя
- def create_superuser(self, email, password=None, is_teacher=False): ... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, is_teacher=False): Создание и сохранение пользователя
- def create_superuser(self, email, password=None, is_teacher=False): ... | 208cbc6d2b6d40c3043d35ce773a3433b377f671 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None, is_teacher=False):
"""Создание и сохранение пользователя"""
<|body_0|>
def create_superuser(self, email, password=None, is_teacher=False):
"""Creates and saves a superuser with the given email, date of birth ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
def create_user(self, email, password=None, is_teacher=False):
"""Создание и сохранение пользователя"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)... | the_stack_v2_python_sparse | students/K33401/Klishin_Nikita/Lr_3/peer_review_system/accounts/models.py | dEbAR38/ITMO_ICT_WebDevelopment_2020-2021 | train | 0 | |
1bfa9780d05241b6460fe90eaa4a6dcd3ce22ca2 | [
"query_string = request.query_string\nquery_params = dict(urlparse.parse_qsl(query_string))\nreturn query_params",
"query_params = self._parse_query_params(request=request)\nvalue = query_params.get(param_name, default_value)\nif param_type == 'bool' and isinstance(value, six.string_types):\n value = transform... | <|body_start_0|>
query_string = request.query_string
query_params = dict(urlparse.parse_qsl(query_string))
return query_params
<|end_body_0|>
<|body_start_1|>
query_params = self._parse_query_params(request=request)
value = query_params.get(param_name, default_value)
if ... | Base REST controller class which contains various utility functions. | BaseRestControllerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRestControllerMixin:
"""Base REST controller class which contains various utility functions."""
def _parse_query_params(self, request):
"""Parse query string for the provided request. :rtype: ``dict``"""
<|body_0|>
def _get_query_param_value(self, request, param_name... | stack_v2_sparse_classes_75kplus_train_008764 | 2,928 | permissive | [
{
"docstring": "Parse query string for the provided request. :rtype: ``dict``",
"name": "_parse_query_params",
"signature": "def _parse_query_params(self, request)"
},
{
"docstring": "Return a value for the provided query param and optionally cast it for boolean types. If the requested query par... | 3 | stack_v2_sparse_classes_30k_train_018567 | Implement the Python class `BaseRestControllerMixin` described below.
Class description:
Base REST controller class which contains various utility functions.
Method signatures and docstrings:
- def _parse_query_params(self, request): Parse query string for the provided request. :rtype: ``dict``
- def _get_query_param... | Implement the Python class `BaseRestControllerMixin` described below.
Class description:
Base REST controller class which contains various utility functions.
Method signatures and docstrings:
- def _parse_query_params(self, request): Parse query string for the provided request. :rtype: ``dict``
- def _get_query_param... | c3fc181981b141da95dcf6939d09c362556ca048 | <|skeleton|>
class BaseRestControllerMixin:
"""Base REST controller class which contains various utility functions."""
def _parse_query_params(self, request):
"""Parse query string for the provided request. :rtype: ``dict``"""
<|body_0|>
def _get_query_param_value(self, request, param_name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseRestControllerMixin:
"""Base REST controller class which contains various utility functions."""
def _parse_query_params(self, request):
"""Parse query string for the provided request. :rtype: ``dict``"""
query_string = request.query_string
query_params = dict(urlparse.parse_qs... | the_stack_v2_python_sparse | st2api/st2api/controllers/base.py | Plexxi/st2 | train | 3 |
372c2ad449be64e7b97db88b0cb6005f0ac139ce | [
"self.output_sz = output_sz\nself.scope = 'double_lstm_dense'\nself.keep_prob = keep_prob\nself.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lstm', 'encoder1')\nself.lstm_encoder2 = RNNEncoder(output_sz, keep_prob, 'gru', 'encoder2')",
"with vs.variable_scope(self.scope):\n lstm_1_out = self.lstm_encoder1... | <|body_start_0|>
self.output_sz = output_sz
self.scope = 'double_lstm_dense'
self.keep_prob = keep_prob
self.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lstm', 'encoder1')
self.lstm_encoder2 = RNNEncoder(output_sz, keep_prob, 'gru', 'encoder2')
<|end_body_0|>
<|body_start_... | base class for output representation | OutputDoubleLSTMDense | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputDoubleLSTMDense:
"""base class for output representation"""
def __init__(self, output_sz, keep_prob):
"""Args:"""
<|body_0|>
def build_graph(self, reps, context_mask):
"""Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, out... | stack_v2_sparse_classes_75kplus_train_008765 | 1,464 | no_license | [
{
"docstring": "Args:",
"name": "__init__",
"signature": "def __init__(self, output_sz, keep_prob)"
},
{
"docstring": "Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, output_sz]",
"name": "build_graph",
"signature": "def build_graph(self, reps, context_... | 2 | stack_v2_sparse_classes_30k_train_028293 | Implement the Python class `OutputDoubleLSTMDense` described below.
Class description:
base class for output representation
Method signatures and docstrings:
- def __init__(self, output_sz, keep_prob): Args:
- def build_graph(self, reps, context_mask): Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz... | Implement the Python class `OutputDoubleLSTMDense` described below.
Class description:
base class for output representation
Method signatures and docstrings:
- def __init__(self, output_sz, keep_prob): Args:
- def build_graph(self, reps, context_mask): Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz... | 66756a0019b294ec4e2e048473f10115bda45bde | <|skeleton|>
class OutputDoubleLSTMDense:
"""base class for output representation"""
def __init__(self, output_sz, keep_prob):
"""Args:"""
<|body_0|>
def build_graph(self, reps, context_mask):
"""Args: reps: [batch_sz, context_length, reps_sz] Return: [batch_sz, context_length, out... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutputDoubleLSTMDense:
"""base class for output representation"""
def __init__(self, output_sz, keep_prob):
"""Args:"""
self.output_sz = output_sz
self.scope = 'double_lstm_dense'
self.keep_prob = keep_prob
self.lstm_encoder1 = RNNEncoder(output_sz, keep_prob, 'lst... | the_stack_v2_python_sparse | src/code/modules/output_double_lstm_dense.py | dengl11/CS224N-Project-Machine-Reading | train | 2 |
4523a33d4629d310aadbbae6b094b3084fef8380 | [
"self.filepath = audio_filename\ntry:\n audio = EasyID3(audio_filename)\nexcept:\n raise ValueError\nelse:\n self.tags = {}\n self.tags['artist'] = audio.get('artist', 'Unknown')\n self.tags['title'] = audio.get('title', 'Unknown')\n self.tags['album'] = audio.get('album', 'Unknown')\n self.tag... | <|body_start_0|>
self.filepath = audio_filename
try:
audio = EasyID3(audio_filename)
except:
raise ValueError
else:
self.tags = {}
self.tags['artist'] = audio.get('artist', 'Unknown')
self.tags['title'] = audio.get('title', 'Unk... | Class for work with ID3 tags of Mp3 files | Tag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
<|body_0|>
def set_tags(self, **kwargs):
"""@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genr... | stack_v2_sparse_classes_75kplus_train_008766 | 2,305 | no_license | [
{
"docstring": "@type audio_filename str Init function of Tag class",
"name": "__init__",
"signature": "def __init__(self, audio_filename)"
},
{
"docstring": "@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genre, tracknumber) in mp3 files",
"name": "set_tags",
"signa... | 3 | stack_v2_sparse_classes_30k_train_017267 | Implement the Python class `Tag` described below.
Class description:
Class for work with ID3 tags of Mp3 files
Method signatures and docstrings:
- def __init__(self, audio_filename): @type audio_filename str Init function of Tag class
- def set_tags(self, **kwargs): @type **kwargs dict Set ID3 tags (artist, title, al... | Implement the Python class `Tag` described below.
Class description:
Class for work with ID3 tags of Mp3 files
Method signatures and docstrings:
- def __init__(self, audio_filename): @type audio_filename str Init function of Tag class
- def set_tags(self, **kwargs): @type **kwargs dict Set ID3 tags (artist, title, al... | a53bed4b95f2848ec64156e642b6166a1ca6a1e4 | <|skeleton|>
class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
<|body_0|>
def set_tags(self, **kwargs):
"""@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
self.filepath = audio_filename
try:
audio = EasyID3(audio_filename)
except:
raise ValueError
e... | the_stack_v2_python_sparse | src/tools/tags.py | Xkeeper/LastVK | train | 0 |
5196d4f4cbe8319c4799dd0f62e93dd3eb308f81 | [
"self._logger = logging.getLogger(__name__)\nself._logger.info(\"Setting up user input form's ROS node...\")\nself.ros_node = ros_node\nself.user_input_pub = rospy.Publisher('/rr/user_input', UserInput, queue_size=10)\nself._tega_pub = rospy.Publisher('/tega', TegaAction, queue_size=10)",
"if self.user_input_pub ... | <|body_start_0|>
self._logger = logging.getLogger(__name__)
self._logger.info("Setting up user input form's ROS node...")
self.ros_node = ros_node
self.user_input_pub = rospy.Publisher('/rr/user_input', UserInput, queue_size=10)
self._tega_pub = rospy.Publisher('/tega', TegaActio... | ROS functions for sending user input responses. | UserFormROS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFormROS:
"""ROS functions for sending user input responses."""
def __init__(self, ros_node):
"""Initialize ROS."""
<|body_0|>
def send_message(self, response_type, response):
"""Publish UserInput message."""
<|body_1|>
def send_tega_animation(sel... | stack_v2_sparse_classes_75kplus_train_008767 | 3,341 | permissive | [
{
"docstring": "Initialize ROS.",
"name": "__init__",
"signature": "def __init__(self, ros_node)"
},
{
"docstring": "Publish UserInput message.",
"name": "send_message",
"signature": "def send_message(self, response_type, response)"
},
{
"docstring": "Publish a Tega command messa... | 3 | stack_v2_sparse_classes_30k_train_007294 | Implement the Python class `UserFormROS` described below.
Class description:
ROS functions for sending user input responses.
Method signatures and docstrings:
- def __init__(self, ros_node): Initialize ROS.
- def send_message(self, response_type, response): Publish UserInput message.
- def send_tega_animation(self, m... | Implement the Python class `UserFormROS` described below.
Class description:
ROS functions for sending user input responses.
Method signatures and docstrings:
- def __init__(self, ros_node): Initialize ROS.
- def send_message(self, response_type, response): Publish UserInput message.
- def send_tega_animation(self, m... | 8bf3f928b442c2890dbbbff110fcde76846b2e16 | <|skeleton|>
class UserFormROS:
"""ROS functions for sending user input responses."""
def __init__(self, ros_node):
"""Initialize ROS."""
<|body_0|>
def send_message(self, response_type, response):
"""Publish UserInput message."""
<|body_1|>
def send_tega_animation(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserFormROS:
"""ROS functions for sending user input responses."""
def __init__(self, ros_node):
"""Initialize ROS."""
self._logger = logging.getLogger(__name__)
self._logger.info("Setting up user input form's ROS node...")
self.ros_node = ros_node
self.user_input_... | the_stack_v2_python_sparse | src/user_input_ros.py | mitmedialab/rr_interaction | train | 0 |
b266ae20180232ee336f9ffbed5f114a3fa8802c | [
"resource_creator_action_config = self.svc.get(system_id)\nif resource_creator_action_config is None:\n raise error_codes.VALIDATE_ERROR.format('system[{}] do not register resource_creator_actions config'.format(system_id))\nrac_beans = self._tiled_resource_creator_action(resource_creator_action_config.config)\n... | <|body_start_0|>
resource_creator_action_config = self.svc.get(system_id)
if resource_creator_action_config is None:
raise error_codes.VALIDATE_ERROR.format('system[{}] do not register resource_creator_actions config'.format(system_id))
rac_beans = self._tiled_resource_creator_action... | ResourceCreatorActionBiz | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceCreatorActionBiz:
def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]:
"""查询某个资源类型当其实例被创建时,创建者需要的操作权限"""
<|body_0|>
def _tiled_resource_creator_action(self, rca_config: List[ResourceCreatorActionConfigItem]) -> List[ResourceCreatorActionBean]... | stack_v2_sparse_classes_75kplus_train_008768 | 3,181 | permissive | [
{
"docstring": "查询某个资源类型当其实例被创建时,创建者需要的操作权限",
"name": "list_action_id",
"signature": "def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]"
},
{
"docstring": "将新建关联配置按照资源类型平铺",
"name": "_tiled_resource_creator_action",
"signature": "def _tiled_resource_creator_act... | 2 | stack_v2_sparse_classes_30k_train_004436 | Implement the Python class `ResourceCreatorActionBiz` described below.
Class description:
Implement the ResourceCreatorActionBiz class.
Method signatures and docstrings:
- def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]: 查询某个资源类型当其实例被创建时,创建者需要的操作权限
- def _tiled_resource_creator_action(sel... | Implement the Python class `ResourceCreatorActionBiz` described below.
Class description:
Implement the ResourceCreatorActionBiz class.
Method signatures and docstrings:
- def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]: 查询某个资源类型当其实例被创建时,创建者需要的操作权限
- def _tiled_resource_creator_action(sel... | 33c8f4ffe8697081abcfc5771b98a88c0578059f | <|skeleton|>
class ResourceCreatorActionBiz:
def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]:
"""查询某个资源类型当其实例被创建时,创建者需要的操作权限"""
<|body_0|>
def _tiled_resource_creator_action(self, rca_config: List[ResourceCreatorActionConfigItem]) -> List[ResourceCreatorActionBean]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceCreatorActionBiz:
def list_action_id(self, system_id: str, resource_type_id: str) -> List[str]:
"""查询某个资源类型当其实例被创建时,创建者需要的操作权限"""
resource_creator_action_config = self.svc.get(system_id)
if resource_creator_action_config is None:
raise error_codes.VALIDATE_ERROR.for... | the_stack_v2_python_sparse | saas/backend/biz/resource_creator_action.py | robert871126/bk-iam-saas | train | 0 | |
76b358129e6c21f15705f0fc8e976c50425dbe91 | [
"if self.developer_name == '':\n self._Warning('Please enter a develper name')\nelif self.developer_id == '':\n self._Warning('Please enter a develper ID')\nelif self.product_name == '':\n self._Warning('Please enter a product name')\nelif self.product_descr == '':\n self._Warning('Please enter a produc... | <|body_start_0|>
if self.developer_name == '':
self._Warning('Please enter a develper name')
elif self.developer_id == '':
self._Warning('Please enter a develper ID')
elif self.product_name == '':
self._Warning('Please enter a product name')
elif self.... | Product information wizard page | ProductInfoPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductInfoPage:
"""Product information wizard page"""
def onpage_changing(self, event):
"""Verify fields"""
<|body_0|>
def __init__(self, parent, developer_id=None, developer_name=None, product_id=None, product_name=None, product_descr=None, pwrdownmode=False):
... | stack_v2_sparse_classes_75kplus_train_008769 | 17,994 | no_license | [
{
"docstring": "Verify fields",
"name": "onpage_changing",
"signature": "def onpage_changing(self, event)"
},
{
"docstring": "Constructor @param parent: parent wizard @param developer_id: developer ID @param developer_nanme: developer name @param product_id: product ID @param product_nanme: prod... | 2 | null | Implement the Python class `ProductInfoPage` described below.
Class description:
Product information wizard page
Method signatures and docstrings:
- def onpage_changing(self, event): Verify fields
- def __init__(self, parent, developer_id=None, developer_name=None, product_id=None, product_name=None, product_descr=No... | Implement the Python class `ProductInfoPage` described below.
Class description:
Product information wizard page
Method signatures and docstrings:
- def onpage_changing(self, event): Verify fields
- def __init__(self, parent, developer_id=None, developer_name=None, product_id=None, product_name=None, product_descr=No... | 4c5b4ab455b62a9b1b0a1477121997ca8a495aef | <|skeleton|>
class ProductInfoPage:
"""Product information wizard page"""
def onpage_changing(self, event):
"""Verify fields"""
<|body_0|>
def __init__(self, parent, developer_id=None, developer_name=None, product_id=None, product_name=None, product_descr=None, pwrdownmode=False):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductInfoPage:
"""Product information wizard page"""
def onpage_changing(self, event):
"""Verify fields"""
if self.developer_name == '':
self._Warning('Please enter a develper name')
elif self.developer_id == '':
self._Warning('Please enter a develper ID'... | the_stack_v2_python_sparse | python/swapmaker/wizard.py | ntruchsess/panstamp | train | 3 |
1818d2ae5addf18bec4cba01ac6c8740a6679ca8 | [
"CG = CourseGroup.objects.get(id=request['id'])\nA = Announcement(title=request['title'], content=request['content'], courseGroup=CG, dateAndTime=datetime.datetime.now())\nA.save()\nreturn A",
"\"\"\" note: courseGroup, dateAndTime is not editable \"\"\"\nA = Announcement.objects.get(id=request['id'])\nA.title = ... | <|body_start_0|>
CG = CourseGroup.objects.get(id=request['id'])
A = Announcement(title=request['title'], content=request['content'], courseGroup=CG, dateAndTime=datetime.datetime.now())
A.save()
return A
<|end_body_0|>
<|body_start_1|>
""" note: courseGroup, dateAndTime is not e... | AnnouncementManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnouncementManager:
def addAnnouncement(self, request):
"""adds new announcement"""
<|body_0|>
def editAnnouncement(self, request):
"""edit an existing announcement"""
<|body_1|>
def deleteAnnouncement(self, request):
"""deletes an existing anno... | stack_v2_sparse_classes_75kplus_train_008770 | 1,588 | no_license | [
{
"docstring": "adds new announcement",
"name": "addAnnouncement",
"signature": "def addAnnouncement(self, request)"
},
{
"docstring": "edit an existing announcement",
"name": "editAnnouncement",
"signature": "def editAnnouncement(self, request)"
},
{
"docstring": "deletes an exi... | 3 | stack_v2_sparse_classes_30k_train_028855 | Implement the Python class `AnnouncementManager` described below.
Class description:
Implement the AnnouncementManager class.
Method signatures and docstrings:
- def addAnnouncement(self, request): adds new announcement
- def editAnnouncement(self, request): edit an existing announcement
- def deleteAnnouncement(self... | Implement the Python class `AnnouncementManager` described below.
Class description:
Implement the AnnouncementManager class.
Method signatures and docstrings:
- def addAnnouncement(self, request): adds new announcement
- def editAnnouncement(self, request): edit an existing announcement
- def deleteAnnouncement(self... | 8290c7f527cc953fb4837fa9f87c197a2734d9d7 | <|skeleton|>
class AnnouncementManager:
def addAnnouncement(self, request):
"""adds new announcement"""
<|body_0|>
def editAnnouncement(self, request):
"""edit an existing announcement"""
<|body_1|>
def deleteAnnouncement(self, request):
"""deletes an existing anno... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnnouncementManager:
def addAnnouncement(self, request):
"""adds new announcement"""
CG = CourseGroup.objects.get(id=request['id'])
A = Announcement(title=request['title'], content=request['content'], courseGroup=CG, dateAndTime=datetime.datetime.now())
A.save()
return ... | the_stack_v2_python_sparse | NewsFeed/models/Announcement.py | avijeet95/CMS | train | 2 | |
f5a3ebef506f78c66bbd38db36cc86b28c1598e3 | [
"self.hook = hook\nself.torch_modules = {'torch': torch, 'torch.functional': torch.functional, 'torch.nn.functional': torch.nn.functional}\nself._torch_functions = {f'{module_name}.{func_name}' for module_name, torch_module in self.torch_modules.items() for func_name in dir(torch_module)}\nself.exclude = ['as_tenso... | <|body_start_0|>
self.hook = hook
self.torch_modules = {'torch': torch, 'torch.functional': torch.functional, 'torch.nn.functional': torch.nn.functional}
self._torch_functions = {f'{module_name}.{func_name}' for module_name, torch_module in self.torch_modules.items() for func_name in dir(torch_m... | Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored here instead of attaching it directly to some other part of the global namespace. T... | TorchAttributes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TorchAttributes:
"""Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored here instead of attaching it directly to... | stack_v2_sparse_classes_75kplus_train_008771 | 5,349 | permissive | [
{
"docstring": "Initialization of the TorchAttributes class.",
"name": "__init__",
"signature": "def __init__(self, torch: ModuleType, hook: ModuleType) -> None"
},
{
"docstring": "Determine if a method is inplace or not. Check if the method ends by _ and is not a __xx__, then stash for constant... | 2 | stack_v2_sparse_classes_30k_train_051982 | Implement the Python class `TorchAttributes` described below.
Class description:
Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored h... | Implement the Python class `TorchAttributes` described below.
Class description:
Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored h... | cc4765bed880ad38a02505834f63df39e0815328 | <|skeleton|>
class TorchAttributes:
"""Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored here instead of attaching it directly to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TorchAttributes:
"""Adds torch module related custom attributes. TorchAttributes is a special class where all custom attributes related to the torch module can be added. Any global parameter, configuration, or reference relating to PyTorch should be stored here instead of attaching it directly to some other p... | the_stack_v2_python_sparse | syft/frameworks/torch/torch_attributes.py | tudorcebere/PySyft | train | 2 |
33e2ab16afdc779555e1cb14aa3d167332556b10 | [
"global dbu\nself.dt = dup.parse(inStr.split(',')[0])\nm = re.search('^.*\\\\sINFO\\\\s\\\\-\\\\srunning command\\\\:\\\\s(.*)$', inStr.strip())\nself.filename = m.group(1).split()[0]",
"outStr = '<tr>'\nfor attr in ['filename']:\n outStr += '<th>{0}</th>'.format(attr)\noutStr += '</tr>\\n'\nreturn outStr",
... | <|body_start_0|>
global dbu
self.dt = dup.parse(inStr.split(',')[0])
m = re.search('^.*\\sINFO\\s\\-\\srunning command\\:\\s(.*)$', inStr.strip())
self.filename = m.group(1).split()[0]
<|end_body_0|>
<|body_start_1|>
outStr = '<tr>'
for attr in ['filename']:
... | commandsRun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class commandsRun:
def __init__(self, inStr):
"""pass in the line and parse it grabbing what we need"""
<|body_0|>
def htmlheader(self):
"""return a string html header"""
<|body_1|>
def html(self, alt=False):
"""return a html string for this"""
... | stack_v2_sparse_classes_75kplus_train_008772 | 9,741 | no_license | [
{
"docstring": "pass in the line and parse it grabbing what we need",
"name": "__init__",
"signature": "def __init__(self, inStr)"
},
{
"docstring": "return a string html header",
"name": "htmlheader",
"signature": "def htmlheader(self)"
},
{
"docstring": "return a html string fo... | 3 | stack_v2_sparse_classes_30k_train_051378 | Implement the Python class `commandsRun` described below.
Class description:
Implement the commandsRun class.
Method signatures and docstrings:
- def __init__(self, inStr): pass in the line and parse it grabbing what we need
- def htmlheader(self): return a string html header
- def html(self, alt=False): return a htm... | Implement the Python class `commandsRun` described below.
Class description:
Implement the commandsRun class.
Method signatures and docstrings:
- def __init__(self, inStr): pass in the line and parse it grabbing what we need
- def htmlheader(self): return a string html header
- def html(self, alt=False): return a htm... | be29f149e93a66886dc988ea8aff1346e9174fe8 | <|skeleton|>
class commandsRun:
def __init__(self, inStr):
"""pass in the line and parse it grabbing what we need"""
<|body_0|>
def htmlheader(self):
"""return a string html header"""
<|body_1|>
def html(self, alt=False):
"""return a html string for this"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class commandsRun:
def __init__(self, inStr):
"""pass in the line and parse it grabbing what we need"""
global dbu
self.dt = dup.parse(inStr.split(',')[0])
m = re.search('^.*\\sINFO\\s\\-\\srunning command\\:\\s(.*)$', inStr.strip())
self.filename = m.group(1).split()[0]
... | the_stack_v2_python_sparse | dbprocessing/reports.py | lanl/dbprocessing | train | 0 | |
da0004ee9b3503274ab43705f1b5d14c2e8d6687 | [
"votes = self.votes.get(answer_no, 0)\nvotes = votes + 1\nself.votes[answer_no] = votes",
"data = {'question': self.content}\nanswers = []\ni = 0\ntotal = 0\nfor title in self.answers:\n votes = self.votes.get(str(i), 0)\n answer = {'title': title, 'votes': votes}\n total = total + votes\n answers.app... | <|body_start_0|>
votes = self.votes.get(answer_no, 0)
votes = votes + 1
self.votes[answer_no] = votes
<|end_body_0|>
<|body_start_1|>
data = {'question': self.content}
answers = []
i = 0
total = 0
for title in self.answers:
votes = self.votes.... | a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } There is an additional field ``voters`` which stores the list of all votin... | Poll | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poll:
"""a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } There is an additional field ``voters`` wh... | stack_v2_sparse_classes_75kplus_train_008773 | 2,548 | no_license | [
{
"docstring": "vote for answer number ``answer_no`` TODO: Check if answer_no is valid (number and in range)",
"name": "vote",
"signature": "def vote(self, answer_no)"
},
{
"docstring": "return all results of the poll in the following form:: 'question' : \"This is the question\", 'answers' :[ { ... | 2 | stack_v2_sparse_classes_30k_train_009186 | Implement the Python class `Poll` described below.
Class description:
a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } The... | Implement the Python class `Poll` described below.
Class description:
a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } The... | ce9854dc47e7a07c3b59a165c10ee8da61d05db4 | <|skeleton|>
class Poll:
"""a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } There is an additional field ``voters`` wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Poll:
"""a poll object. It stores the question as the main status message and the answers as a list of lines. It also stores votes in a vote dictionary. There's a list of userids for each answer:: votes = { 0 : [uid1, uid2, ...], 1 : [uid1, uid2, ...], } There is an additional field ``voters`` which stores th... | the_stack_v2_python_sparse | quantumlounge/content/poll.py | mrtopf/QuantumLounge | train | 0 |
fd684dbbb059174b17a5a6c311ac03cfda75c5a4 | [
"super().__init__()\nself.shared_net = nn.Sequential(nn.Linear(112, 128), nn.Tanh(), nn.Linear(128, 128), nn.Tanh(), nn.Linear(128, 64), nn.Tanh())\nself.pi = nn.Linear(64, num_actions)\nself.v = nn.Linear(64, 1)\nself.num_actions = num_actions\nself.apply(atari_initializer)\nself.pi.weight.data = ortho_weights(sel... | <|body_start_0|>
super().__init__()
self.shared_net = nn.Sequential(nn.Linear(112, 128), nn.Tanh(), nn.Linear(128, 128), nn.Tanh(), nn.Linear(128, 64), nn.Tanh())
self.pi = nn.Linear(64, num_actions)
self.v = nn.Linear(64, 1)
self.num_actions = num_actions
self.apply(atar... | A2CLarge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class A2CLarge:
def __init__(self, num_actions):
"""Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the number of available discrete actions"""
<|body_0|>
def forward(self, conv_in):
... | stack_v2_sparse_classes_75kplus_train_008774 | 7,848 | permissive | [
{
"docstring": "Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the number of available discrete actions",
"name": "__init__",
"signature": "def __init__(self, num_actions)"
},
{
"docstring": "Module fo... | 2 | stack_v2_sparse_classes_30k_train_012666 | Implement the Python class `A2CLarge` described below.
Class description:
Implement the A2CLarge class.
Method signatures and docstrings:
- def __init__(self, num_actions): Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the... | Implement the Python class `A2CLarge` described below.
Class description:
Implement the A2CLarge class.
Method signatures and docstrings:
- def __init__(self, num_actions): Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the... | bbe61592a3d85c00731e254edcd1108075c49b6f | <|skeleton|>
class A2CLarge:
def __init__(self, num_actions):
"""Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the number of available discrete actions"""
<|body_0|>
def forward(self, conv_in):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class A2CLarge:
def __init__(self, num_actions):
"""Basic convolutional actor-critic network for Atari 2600 games Equivalent to the network in the original DQN paper. Args: - num_actions (int): the number of available discrete actions"""
super().__init__()
self.shared_net = nn.Sequential(nn.... | the_stack_v2_python_sparse | a2c/models.py | WeiChengTseng/DL_final_project | train | 9 | |
403fc7c3e60b09c88e863c364b9e5d7ff28f549f | [
"super().__init__()\nself.chan = 3\nself.output_size = output_size\nself.hidden_dim = hidden_dim\nself.train_on_gpu = train_on_gpu\nself.dvc = device\nif mode == 'od':\n self.chan = 1\nself.encoder = nn.Linear(input_size, hidden_dim)\nself.l1 = nn.Linear(hidden_dim, hidden_dim // 2)\nself.l2 = nn.Linear(hidden_d... | <|body_start_0|>
super().__init__()
self.chan = 3
self.output_size = output_size
self.hidden_dim = hidden_dim
self.train_on_gpu = train_on_gpu
self.dvc = device
if mode == 'od':
self.chan = 1
self.encoder = nn.Linear(input_size, hidden_dim)
... | An autoencoder model, without any preprocessing to the inputs. | AutoEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoEncoder:
"""An autoencoder model, without any preprocessing to the inputs."""
def __init__(self, input_size, output_size, hidden_dim=512, mode='pnf', train_on_gpu=True, device='cuda:0'):
"""Auto encoder initialization. Args: input_size: dimention of state vector (flattened 3d ten... | stack_v2_sparse_classes_75kplus_train_008775 | 31,608 | permissive | [
{
"docstring": "Auto encoder initialization. Args: input_size: dimention of state vector (flattened 3d tensor) output_size: the same shape of input_size hidden_dim: hidden size train_on_gpu: whether use GPU or not device: where to put the model",
"name": "__init__",
"signature": "def __init__(self, inpu... | 2 | null | Implement the Python class `AutoEncoder` described below.
Class description:
An autoencoder model, without any preprocessing to the inputs.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_dim=512, mode='pnf', train_on_gpu=True, device='cuda:0'): Auto encoder initialization. Args... | Implement the Python class `AutoEncoder` described below.
Class description:
An autoencoder model, without any preprocessing to the inputs.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_dim=512, mode='pnf', train_on_gpu=True, device='cuda:0'): Auto encoder initialization. Args... | ff165de95ec0f258ba444ff343d18d812a066b8f | <|skeleton|>
class AutoEncoder:
"""An autoencoder model, without any preprocessing to the inputs."""
def __init__(self, input_size, output_size, hidden_dim=512, mode='pnf', train_on_gpu=True, device='cuda:0'):
"""Auto encoder initialization. Args: input_size: dimention of state vector (flattened 3d ten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoEncoder:
"""An autoencoder model, without any preprocessing to the inputs."""
def __init__(self, input_size, output_size, hidden_dim=512, mode='pnf', train_on_gpu=True, device='cuda:0'):
"""Auto encoder initialization. Args: input_size: dimention of state vector (flattened 3d tensor) output_s... | the_stack_v2_python_sparse | src/core/models.py | spencerzhang91/GSPNet | train | 0 |
738520414003b38a39ee6f782bec02851a6f7f6d | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"self.bttn1 = Button(self, text='Я ничего не делаю!')\nself.bttn1.grid()\nself.bttn2 = Button(self)\nself.bttn2.grid()\nself.bttn2.configure(text='И я тоже!')\nself.bttn3 = Button(self)\nself.bttn3.grid()\nself.bttn3['text'] = 'И я!'... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.bttn1 = Button(self, text='Я ничего не делаю!')
self.bttn1.grid()
self.bttn2 = Button(self)
self.bttn2.grid()
self.bttn2.conf... | GUI - приложение с тремя кнопками | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
<|body_0|>
def create_widgets(self):
"""Создает три бесполезные кнопки."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Applicatio... | stack_v2_sparse_classes_75kplus_train_008776 | 1,163 | no_license | [
{
"docstring": "Инициализирует рамку.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Создает три бесполезные кнопки.",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018425 | Implement the Python class `Application` described below.
Class description:
GUI - приложение с тремя кнопками
Method signatures and docstrings:
- def __init__(self, master): Инициализирует рамку.
- def create_widgets(self): Создает три бесполезные кнопки. | Implement the Python class `Application` described below.
Class description:
GUI - приложение с тремя кнопками
Method signatures and docstrings:
- def __init__(self, master): Инициализирует рамку.
- def create_widgets(self): Создает три бесполезные кнопки.
<|skeleton|>
class Application:
"""GUI - приложение с тр... | 0192a5a936aac4ebec18e6f6bb4988e1865942f0 | <|skeleton|>
class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
<|body_0|>
def create_widgets(self):
"""Создает три бесполезные кнопки."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""GUI - приложение с тремя кнопками"""
def __init__(self, master):
"""Инициализирует рамку."""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Создает три бесполезные кнопки."""
sel... | the_stack_v2_python_sparse | lessons/Chapter 10/10_02.py | a-abramow/MDawsonlessons | train | 0 |
8d4a981582b019644c6fc91736897948591cc89f | [
"if n % 2 != 0:\n LOGGER.warn(f'n should be a multiple of 2. Actual values = {n}')\nn = n // 2\nrng = np.random.default_rng(seed)\nbeta_baseline = rng.standard_t(dof_baseline) * scale_baseline\nsigma_state = np.abs(rng.standard_cauchy()) * scale_state\nsigma_district = np.abs(rng.standard_cauchy()) * scale_distr... | <|body_start_0|>
if n % 2 != 0:
LOGGER.warn(f'n should be a multiple of 2. Actual values = {n}')
n = n // 2
rng = np.random.default_rng(seed)
beta_baseline = rng.standard_t(dof_baseline) * scale_baseline
sigma_state = np.abs(rng.standard_cauchy()) * scale_state
... | N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school type. Hyper Parameters: n - total numb... | NSchools | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school ty... | stack_v2_sparse_classes_75kplus_train_008777 | 6,995 | permissive | [
{
"docstring": "See the class documentation for an explanation of the parameters. :param seed: random number generator seed",
"name": "generate_data",
"signature": "def generate_data(seed: int, n: int=2000, num_states: int=8, num_districts_per_state: int=5, num_types: int=5, dof_baseline: float=3.0, sca... | 2 | stack_v2_sparse_classes_30k_train_044188 | Implement the Python class `NSchools` described below.
Class description:
N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state... | Implement the Python class `NSchools` described below.
Class description:
N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state... | d69c652fc882ba50f56eb0cfaa3097d3ede295f9 | <|skeleton|>
class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NSchools:
"""N Schools This is a generalization of a classical 8 schools model to n schools. The model posits that the effect of a school on a student's performance can be explained by the a baseline effect of all schools plus an additive effect of the state, the school district and the school type. Hyper Par... | the_stack_v2_python_sparse | pplbench/models/n_schools.py | rambam613/pplbench | train | 0 |
9e288549dd3e5ad0fbc99c4ab1ba62f8de62a893 | [
"super(BaselineDNN, self).__init__()\nn_embeddings, self.embedding_size = np.shape(embeddings)\nself.embeddings = nn.Embedding(num_embeddings=n_embeddings, embedding_dim=self.embedding_size)\nself.embeddings.load_state_dict({'weight': torch.from_numpy(embeddings)})\nif not trainable_emb:\n self.embeddings.weight... | <|body_start_0|>
super(BaselineDNN, self).__init__()
n_embeddings, self.embedding_size = np.shape(embeddings)
self.embeddings = nn.Embedding(num_embeddings=n_embeddings, embedding_dim=self.embedding_size)
self.embeddings.load_state_dict({'weight': torch.from_numpy(embeddings)})
i... | 1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes. | BaselineDNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes."""
... | stack_v2_sparse_classes_75kplus_train_008778 | 3,429 | permissive | [
{
"docstring": "Args: output_size(int): the number of classes embeddings(bool): the 2D matrix with the pretrained embeddings trainable_emb(bool): train (finetune) or freeze the weights the embedding layer",
"name": "__init__",
"signature": "def __init__(self, output_size, embeddings, trainable_emb=False... | 2 | stack_v2_sparse_classes_30k_train_006017 | Implement the Python class `BaselineDNN` described below.
Class description:
1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the represent... | Implement the Python class `BaselineDNN` described below.
Class description:
1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the represent... | c7487c58bde54036b07df2b7ff9b4f2cd9776a15 | <|skeleton|>
class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaselineDNN:
"""1. We embed the words in the input texts using an embedding layer 2. We compute the min, mean, max of the word embeddings in each sample and use it as the feature representation of the sequence. 4. We project with a linear layer the representation to the number of classes."""
def __init__... | the_stack_v2_python_sparse | Lab3/Lab/models/BaselineDNN.py | PanosAntoniadis/slp-ntua | train | 11 |
13c9f9a257c267056da237e11200e487b5e27a93 | [
"self.model = model\nself.n_epochs = params.n_epochs\nself.optimizer = optimizer\nself.criterion = criterion\nself.batch_size = params.batch_size\nself.device = device\nself.dataset = dataset\nself.val_split = params.val_split\nself._init_dataloaders()\nself.current_epoch = 0\nself.train_loss = []\nself.test_loss =... | <|body_start_0|>
self.model = model
self.n_epochs = params.n_epochs
self.optimizer = optimizer
self.criterion = criterion
self.batch_size = params.batch_size
self.device = device
self.dataset = dataset
self.val_split = params.val_split
self._init_d... | class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader instance): loader handling training data test_loader (DataLoader instance):... | Trainer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader instance): loader handling training data... | stack_v2_sparse_classes_75kplus_train_008779 | 4,916 | permissive | [
{
"docstring": "initializes training from a parameter class object Args: model (nn.Module subclass instance): model to be training dataset (DataSet subclass instance): providing data criterion (nn.Loss instance): loss function optimizer (nn.optim instance): optimizer for model parameters params (params class in... | 5 | stack_v2_sparse_classes_30k_val_002827 | Implement the Python class `Trainer` described below.
Class description:
class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader i... | Implement the Python class `Trainer` described below.
Class description:
class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader i... | 62921423b787ad8b81b8e60e8de42a3f6e113d88 | <|skeleton|>
class Trainer:
"""class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader instance): loader handling training data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trainer:
"""class to provide framework for training a network. Attributes: TRAINING n_epochs (int): number of epochs of training model (nn.Module instance): model to be trained dataset (instance of DataSet subclass): to handle data train_loader (DataLoader instance): loader handling training data test_loader ... | the_stack_v2_python_sparse | utils/trainer.py | Bobby-Hua/birdsonearth | train | 0 |
c75a51c0f8c2d2ba01de02fb62064abc4dd002bd | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_dim=input_vocab, output_dim=dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(rate... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_dim=input_vocab, output_dim=dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in... | class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask):
... | stack_v2_sparse_classes_75kplus_train_008780 | 1,497 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1)"
},
{
"docstring": "Method that returns tensor of shape (batch, input_seq_len, dm)",
"name": "call",
"signature": "def call(self, x, trainin... | 2 | stack_v2_sparse_classes_30k_train_016302 | Implement the Python class `Encoder` described below.
Class description:
class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor
- def cal... | Implement the Python class `Encoder` described below.
Class description:
class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): Class constructor
- def cal... | c7b6ea4c37b7c5dc41e63cdb8142b3cdfb3e1d23 | <|skeleton|>
class Encoder:
"""class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
<|body_0|>
def call(self, x, training, mask):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""class Encoder that inherits from tensorflow.keras.layers.Layer to create the encoder for a transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""Class constructor"""
super().__init__()
self.N = N
self.dm = dm
s... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/9-transformer_encoder.py | linkjavier/holbertonschool-machine_learning | train | 0 |
65da4a0eb744703cbb2ec830096f8a30de801aee | [
"self.memory_capacity = capacity\nself.memory_size = 0\nself.memory_pointer_index = 0\nself.prioritize = prioritize\nself.total_priority_sum = 0.0\nif prioritize:\n self.priority_epsilon = priority_epsilon\n self.priority_alpha = priority_alpha\n self.priority_tree = PrioritizedSumTree(capacity)\nnew_state... | <|body_start_0|>
self.memory_capacity = capacity
self.memory_size = 0
self.memory_pointer_index = 0
self.prioritize = prioritize
self.total_priority_sum = 0.0
if prioritize:
self.priority_epsilon = priority_epsilon
self.priority_alpha = priority_al... | This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from each of the four (s,a,r,s,t) arrays. This sampling is done by using a prioritized su... | SarstReplayMemory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SarstReplayMemory:
"""This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from each of the four (s,a,r,s,t) arrays. Th... | stack_v2_sparse_classes_75kplus_train_008781 | 6,235 | no_license | [
{
"docstring": "Args: Capacity - int - How many samples to hold in the array. Samples all exist for exactly the same amount of time State_Size - numpy array shape tuple - specifying the dimensions of the input prioritize - Boolean, whether to use the prioritized sum tree or to just randomly pick priority epsilo... | 3 | stack_v2_sparse_classes_30k_train_036870 | Implement the Python class `SarstReplayMemory` described below.
Class description:
This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from ... | Implement the Python class `SarstReplayMemory` described below.
Class description:
This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from ... | a70f63ebab3163f299f7f9d860a98695c0a3f7d5 | <|skeleton|>
class SarstReplayMemory:
"""This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from each of the four (s,a,r,s,t) arrays. Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SarstReplayMemory:
"""This memory holds five numpy arrays, each of which store the state, action, reward, next_state, and is_terminal boolean for a series of observations in a reinforcement learner. It works by sampling a batch of corresponding indexes from each of the four (s,a,r,s,t) arrays. This sampling i... | the_stack_v2_python_sparse | DL/RL/RL_APP/DRL_FlappyBird_Mario/Super-Mario-Bros-DQN/SarstReplayMemory.py | Asher-1/AI | train | 7 |
42f403058a24f9aebf8858fed3d72445fb5957e4 | [
"self.num_dim = 3\nself.reflect_index = [1, 2, 3]\nsuper(SharpClawSolver3D, self).__init__(riemann_solver, claw_package)",
"if self.kernel_language == 'Fortran':\n self.fmod.workspace.dealloc_workspace(self.char_decomp)\n self.fmod.reconstruct.dealloc_recon_workspace(self.fmod.clawparams.lim_type, self.fmod... | <|body_start_0|>
self.num_dim = 3
self.reflect_index = [1, 2, 3]
super(SharpClawSolver3D, self).__init__(riemann_solver, claw_package)
<|end_body_0|>
<|body_start_1|>
if self.kernel_language == 'Fortran':
self.fmod.workspace.dealloc_workspace(self.char_decomp)
se... | Three Dimensional SharpClawSolver | SharpClawSolver3D | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharpClawSolver3D:
"""Three Dimensional SharpClawSolver"""
def __init__(self, riemann_solver=None, claw_package=None):
"""Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info."""
<|body_0|>
def teardown(self):
"""Deallocate F90 module arrays. A... | stack_v2_sparse_classes_75kplus_train_008782 | 38,052 | permissive | [
{
"docstring": "Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info.",
"name": "__init__",
"signature": "def __init__(self, riemann_solver=None, claw_package=None)"
},
{
"docstring": "Deallocate F90 module arrays. Also delete Fortran objects, which otherwise tend to persist i... | 3 | stack_v2_sparse_classes_30k_train_030144 | Implement the Python class `SharpClawSolver3D` described below.
Class description:
Three Dimensional SharpClawSolver
Method signatures and docstrings:
- def __init__(self, riemann_solver=None, claw_package=None): Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info.
- def teardown(self): Deallocate... | Implement the Python class `SharpClawSolver3D` described below.
Class description:
Three Dimensional SharpClawSolver
Method signatures and docstrings:
- def __init__(self, riemann_solver=None, claw_package=None): Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info.
- def teardown(self): Deallocate... | 6323b7295b80f33285b958b1a2144f88f51be4b1 | <|skeleton|>
class SharpClawSolver3D:
"""Three Dimensional SharpClawSolver"""
def __init__(self, riemann_solver=None, claw_package=None):
"""Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info."""
<|body_0|>
def teardown(self):
"""Deallocate F90 module arrays. A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SharpClawSolver3D:
"""Three Dimensional SharpClawSolver"""
def __init__(self, riemann_solver=None, claw_package=None):
"""Create 3D SharpClaw solver See :class:`SharpClawSolver3D` for more info."""
self.num_dim = 3
self.reflect_index = [1, 2, 3]
super(SharpClawSolver3D, se... | the_stack_v2_python_sparse | src/pyclaw/sharpclaw/solver.py | clawpack/pyclaw | train | 124 |
667d159440f043f5346a6ee126b7a0007bbd03a3 | [
"inputs = [x for x in sys_stdin]\na1 = [self.cast(x.strip()) for x in inputs[0].strip('[]\\n').split(',')]\no1 = TreeNode().convert(a1)\na2 = [self.cast(x.strip()) for x in inputs[0].strip('[]\\n').split(',')]\no2 = TreeNode().convert(a2)\nreturn (o1, o2)",
"if x.lower() == 'null':\n return None\nelse:\n re... | <|body_start_0|>
inputs = [x for x in sys_stdin]
a1 = [self.cast(x.strip()) for x in inputs[0].strip('[]\n').split(',')]
o1 = TreeNode().convert(a1)
a2 = [self.cast(x.strip()) for x in inputs[0].strip('[]\n').split(',')]
o2 = TreeNode().convert(a2)
return (o1, o2)
<|end_b... | Input | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None valu... | stack_v2_sparse_classes_75kplus_train_008783 | 6,319 | permissive | [
{
"docstring": "Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]",
"name": "stdin",
"signature": "def stdin(self, sys_stdin)"
},
{
"docstring": "Converts string values to integer or None values. :pa... | 2 | stack_v2_sparse_classes_30k_train_054018 | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]
- def cas... | Implement the Python class `Input` described below.
Class description:
Implement the Input class.
Method signatures and docstrings:
- def stdin(self, sys_stdin): Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]
- def cas... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]"""
<|body_0|>
def cast(self, x):
"""Converts string values to integer or None valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Input:
def stdin(self, sys_stdin):
"""Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: head nodes of two binary trees :rtype: tup[TreeNode, TreeNode]"""
inputs = [x for x in sys_stdin]
a1 = [self.cast(x.strip()) for x in inputs[0].strip('[]\n').split(... | the_stack_v2_python_sparse | 0951_flip_equivalent_binary_trees/python_source.py | arthurdysart/LeetCode | train | 0 | |
a40d244ef34a5736ac4679443ffdc007644687ea | [
"first = s[0]\nlast_first = 0\nfor c in s:\n if c == first:\n last_first += 1\n else:\n break\nret = s[last_first:]\nrecord_another = 0\nfor c in s[last_first:]:\n if c == str(1 - int(first)):\n record_another += 1\n if last_first == record_another:\n break\n else:... | <|body_start_0|>
first = s[0]
last_first = 0
for c in s:
if c == first:
last_first += 1
else:
break
ret = s[last_first:]
record_another = 0
for c in s[last_first:]:
if c == str(1 - int(first)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def forword_find(self, s):
""":type s: str"""
<|body_0|>
def back_find(self, s):
""":type s: str"""
<|body_1|>
def countBinarySubstrings1(self, s):
""":type s: str :rtype: int"""
<|body_2|>
def countBinarySubstrings2(self, ... | stack_v2_sparse_classes_75kplus_train_008784 | 3,891 | no_license | [
{
"docstring": ":type s: str",
"name": "forword_find",
"signature": "def forword_find(self, s)"
},
{
"docstring": ":type s: str",
"name": "back_find",
"signature": "def back_find(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countBinarySubstrings1",
"si... | 6 | stack_v2_sparse_classes_30k_train_021524 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def forword_find(self, s): :type s: str
- def back_find(self, s): :type s: str
- def countBinarySubstrings1(self, s): :type s: str :rtype: int
- def countBinarySubstrings2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def forword_find(self, s): :type s: str
- def back_find(self, s): :type s: str
- def countBinarySubstrings1(self, s): :type s: str :rtype: int
- def countBinarySubstrings2(self, ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def forword_find(self, s):
""":type s: str"""
<|body_0|>
def back_find(self, s):
""":type s: str"""
<|body_1|>
def countBinarySubstrings1(self, s):
""":type s: str :rtype: int"""
<|body_2|>
def countBinarySubstrings2(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def forword_find(self, s):
""":type s: str"""
first = s[0]
last_first = 0
for c in s:
if c == first:
last_first += 1
else:
break
ret = s[last_first:]
record_another = 0
for c in s[last_fir... | the_stack_v2_python_sparse | python/leetcode/696_Count_Binary_Substrings.py | bobcaoge/my-code | train | 0 | |
94d7e28a035a0c7030618228de8929d6766e0374 | [
"self.SERVER = config.db_server\nself.USER = config.db_user\nself.PASSWORD = config.db_password\nself.DATABASE_NAME = config.db_name\nself.conn = None",
"try:\n if self.conn is None:\n self.conn = pymssql.connect(server=self.SERVER, user=self.USER, password=self.PASSWORD, database=self.DATABASE_NAME)\n ... | <|body_start_0|>
self.SERVER = config.db_server
self.USER = config.db_user
self.PASSWORD = config.db_password
self.DATABASE_NAME = config.db_name
self.conn = None
<|end_body_0|>
<|body_start_1|>
try:
if self.conn is None:
self.conn = pymssql.c... | Database connection class | DMSDatabase | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DMSDatabase:
"""Database connection class"""
def __init__(self, config):
""":param config:"""
<|body_0|>
def open_connection(self):
"""Connection to DMS MS SQLserver."""
<|body_1|>
def run_query(self, query):
"""Execute SQL query. :param quer... | stack_v2_sparse_classes_75kplus_train_008785 | 1,691 | permissive | [
{
"docstring": ":param config:",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Connection to DMS MS SQLserver.",
"name": "open_connection",
"signature": "def open_connection(self)"
},
{
"docstring": "Execute SQL query. :param query: SQL query :r... | 3 | stack_v2_sparse_classes_30k_train_047848 | Implement the Python class `DMSDatabase` described below.
Class description:
Database connection class
Method signatures and docstrings:
- def __init__(self, config): :param config:
- def open_connection(self): Connection to DMS MS SQLserver.
- def run_query(self, query): Execute SQL query. :param query: SQL query :r... | Implement the Python class `DMSDatabase` described below.
Class description:
Database connection class
Method signatures and docstrings:
- def __init__(self, config): :param config:
- def open_connection(self): Connection to DMS MS SQLserver.
- def run_query(self, query): Execute SQL query. :param query: SQL query :r... | 519a8d79c04e979ba2599dbd8104eab39f8ac470 | <|skeleton|>
class DMSDatabase:
"""Database connection class"""
def __init__(self, config):
""":param config:"""
<|body_0|>
def open_connection(self):
"""Connection to DMS MS SQLserver."""
<|body_1|>
def run_query(self, query):
"""Execute SQL query. :param quer... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DMSDatabase:
"""Database connection class"""
def __init__(self, config):
""":param config:"""
self.SERVER = config.db_server
self.USER = config.db_user
self.PASSWORD = config.db_password
self.DATABASE_NAME = config.db_name
self.conn = None
def open_con... | the_stack_v2_python_sparse | src/prepare_input/download_raw/via_DMS/access/DMSDatabase.py | microbiomedata/metaPro | train | 10 |
d7c75bafb1d5c0abb87176fae6b674111413d1a0 | [
"mnem = ida_ua.print_insn_mnem(ea)\nif mnem == 'call':\n bgcolor = ctypes.cast(int(color), ctypes.POINTER(ctypes.c_int))\n bgcolor[0] = 14540253\n return 1\nelse:\n return 0",
"mnem = ctx.insn.get_canon_mnem()\nif mnem == 'call':\n ctx.out_custom_mnem('call')\n return 1\nelse:\n return 0"
] | <|body_start_0|>
mnem = ida_ua.print_insn_mnem(ea)
if mnem == 'call':
bgcolor = ctypes.cast(int(color), ctypes.POINTER(ctypes.c_int))
bgcolor[0] = 14540253
return 1
else:
return 0
<|end_body_0|>
<|body_start_1|>
mnem = ctx.insn.get_canon_m... | ColorHooks | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorHooks:
def ev_get_bg_color(self, color, ea):
"""Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef uint32 bgcolor_t; ``` ref: https://hex-rays.com/products/ida/support/sdkdoc/pro_8h.html#a3df504089... | stack_v2_sparse_classes_75kplus_train_008786 | 3,195 | permissive | [
{
"docstring": "Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef uint32 bgcolor_t; ``` ref: https://hex-rays.com/products/ida/support/sdkdoc/pro_8h.html#a3df5040891132e50157aee66affdf1de args: color: (bgcolor_t *), out ea: (... | 2 | stack_v2_sparse_classes_30k_train_040081 | Implement the Python class `ColorHooks` described below.
Class description:
Implement the ColorHooks class.
Method signatures and docstrings:
- def ev_get_bg_color(self, color, ea): Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef... | Implement the Python class `ColorHooks` described below.
Class description:
Implement the ColorHooks class.
Method signatures and docstrings:
- def ev_get_bg_color(self, color, ea): Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef... | 5e5c8055feb7c3ff4224d2ce1aab6a79f5e84c93 | <|skeleton|>
class ColorHooks:
def ev_get_bg_color(self, color, ea):
"""Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef uint32 bgcolor_t; ``` ref: https://hex-rays.com/products/ida/support/sdkdoc/pro_8h.html#a3df504089... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColorHooks:
def ev_get_bg_color(self, color, ea):
"""Get item background color. Plugins can hook this callback to color disassembly lines dynamically ```c // background color in RGB typedef uint32 bgcolor_t; ``` ref: https://hex-rays.com/products/ida/support/sdkdoc/pro_8h.html#a3df5040891132e50157aee6... | the_stack_v2_python_sparse | plugins/colors.py | williballenthin/idawilli | train | 113 | |
3bd5a9110174a406b2fb8a158292e2238a175b5f | [
"if not root:\n return\ncurrentLevel, nextLevel = (collections.deque([root]), collections.deque())\nwhile currentLevel:\n node = currentLevel.popleft()\n if node.left:\n nextLevel.append(node.left)\n if node.right:\n nextLevel.append(node.right)\n node.next = currentLevel[0] if currentL... | <|body_start_0|>
if not root:
return
currentLevel, nextLevel = (collections.deque([root]), collections.deque())
while currentLevel:
node = currentLevel.popleft()
if node.left:
nextLevel.append(node.left)
if node.right:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
<|body_0|>
def connect2(self, root):
"""把上面的bfs转换为常数空间 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
currentLevel, nex... | stack_v2_sparse_classes_75kplus_train_008787 | 3,639 | permissive | [
{
"docstring": "BFS :param root: :return:",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "把上面的bfs转换为常数空间 :param root: :return:",
"name": "connect2",
"signature": "def connect2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003102 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): BFS :param root: :return:
- def connect2(self, root): 把上面的bfs转换为常数空间 :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): BFS :param root: :return:
- def connect2(self, root): 把上面的bfs转换为常数空间 :param root: :return:
<|skeleton|>
class Solution:
def connect(self, root):
... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
<|body_0|>
def connect2(self, root):
"""把上面的bfs转换为常数空间 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def connect(self, root):
"""BFS :param root: :return:"""
if not root:
return
currentLevel, nextLevel = (collections.deque([root]), collections.deque())
while currentLevel:
node = currentLevel.popleft()
if node.left:
... | the_stack_v2_python_sparse | leetcode/hard/Populating_Next_Right_Pointers_in_Each_Node_II.py | shhuan/algorithms | train | 0 | |
d9807e1f9ca01f971e6ef85b3cffc89ccd0b6ce5 | [
"self.title = None\nself.title_font_size = 10\nself.plots = [PlotData(self)]\nself.columns = columns\nself.rows = rows",
"if self.title is not None:\n plt.title(self.title)\nfor index, cur_plot in enumerate(self.plots):\n plot = figure.add_subplot(self.rows, self.columns, index + 1)\n cur_plot.pyplot_vis... | <|body_start_0|>
self.title = None
self.title_font_size = 10
self.plots = [PlotData(self)]
self.columns = columns
self.rows = rows
<|end_body_0|>
<|body_start_1|>
if self.title is not None:
plt.title(self.title)
for index, cur_plot in enumerate(self.p... | Defines the complete data set of a figure consisting of one or more plots | FigureData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FigureData:
"""Defines the complete data set of a figure consisting of one or more plots"""
def __init__(self, columns=1, rows=1):
"""Initializer :param columns: The number of columns :param rows: The number of rows"""
<|body_0|>
def pyplot_visualize(self, figure):
... | stack_v2_sparse_classes_75kplus_train_008788 | 2,008 | permissive | [
{
"docstring": "Initializer :param columns: The number of columns :param rows: The number of rows",
"name": "__init__",
"signature": "def __init__(self, columns=1, rows=1)"
},
{
"docstring": "Visualizes the figure :param figure: The pyplot figure",
"name": "pyplot_visualize",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_002740 | Implement the Python class `FigureData` described below.
Class description:
Defines the complete data set of a figure consisting of one or more plots
Method signatures and docstrings:
- def __init__(self, columns=1, rows=1): Initializer :param columns: The number of columns :param rows: The number of rows
- def pyplo... | Implement the Python class `FigureData` described below.
Class description:
Defines the complete data set of a figure consisting of one or more plots
Method signatures and docstrings:
- def __init__(self, columns=1, rows=1): Initializer :param columns: The number of columns :param rows: The number of rows
- def pyplo... | e27b53e8e9eedc48abc99151f3adbb76f0a9b331 | <|skeleton|>
class FigureData:
"""Defines the complete data set of a figure consisting of one or more plots"""
def __init__(self, columns=1, rows=1):
"""Initializer :param columns: The number of columns :param rows: The number of rows"""
<|body_0|>
def pyplot_visualize(self, figure):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FigureData:
"""Defines the complete data set of a figure consisting of one or more plots"""
def __init__(self, columns=1, rows=1):
"""Initializer :param columns: The number of columns :param rows: The number of rows"""
self.title = None
self.title_font_size = 10
self.plots... | the_stack_v2_python_sparse | kaivy/plots/figure_data.py | team-kaivy/kaivy | train | 0 |
3bd75d6535f22e9c6ed1c3ccd5709aa440ba19e6 | [
"self.classifier = classifier\nself.threshold = to_threshold(threshold)\nself.use_total_counts = use_total_counts\nself.at_most_one = at_most_one",
"types = Datatypes(classifier=self.classifier, features=ResultFeatures.TOTAL if self.use_total_counts else ResultFeatures.DISTINCT, normalizer=divide_by_total).proces... | <|body_start_0|>
self.classifier = classifier
self.threshold = to_threshold(threshold)
self.use_total_counts = use_total_counts
self.at_most_one = at_most_one
<|end_body_0|>
<|body_start_1|>
types = Datatypes(classifier=self.classifier, features=ResultFeatures.TOTAL if self.use_... | Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a type may be defined based on the distinct values in the given list or the absolute val... | MajorityTypePicker | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityTypePicker:
"""Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a type may be defined based on the distinc... | stack_v2_sparse_classes_75kplus_train_008789 | 10,813 | permissive | [
{
"docstring": "Initialize the classifier for data type assignement. The optional threshold allows to further constrain the possible results by requiring a minimal frequency for the picked type. Parameters ---------- classifier: openclean.function.value.classifier.ValueClassifier , default=None Classifier that ... | 2 | null | Implement the Python class `MajorityTypePicker` described below.
Class description:
Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a t... | Implement the Python class `MajorityTypePicker` described below.
Class description:
Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a t... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class MajorityTypePicker:
"""Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a type may be defined based on the distinc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MajorityTypePicker:
"""Pick the most frequent type assigned by a given classifier to the values in a given list. Generates a dictionary containing the most frequent type(s) as key(s) and their normalized frequency as the associated value. The majority of a type may be defined based on the distinct values in t... | the_stack_v2_python_sparse | openclean/profiling/classifier/typepicker.py | Denisfench/openclean-core | train | 0 |
7c0f9be562305987c11aab3500d6f29784c9ecda | [
"self.queue = []\nself.d = {}\nself.size = 0",
"if self.size == 0:\n self.queue.append((timestamp, message))\n self.d[message] = timestamp\n self.size = 1\n return True\nelse:\n while self.size > 0 and self.queue[0][0] <= timestamp - 10:\n t, m = self.queue.pop(0)\n self.d.pop(m)\n ... | <|body_start_0|>
self.queue = []
self.d = {}
self.size = 0
<|end_body_0|>
<|body_start_1|>
if self.size == 0:
self.queue.append((timestamp, message))
self.d[message] = timestamp
self.size = 1
return True
else:
while sel... | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_75kplus_train_008790 | 4,690 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timest... | 2 | null | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp: int, message: str) -> bool: Returns true if the message should be printed in the gi... | 46caaf74aeab8af74861fb5b249eb4169baf8493 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
def __init__(self):
"""Initialize your data structure here."""
self.queue = []
self.d = {}
self.size = 0
def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
"""Returns true if the message should be printed in the given timestamp, otherwise r... | the_stack_v2_python_sparse | leetcode/Design/359. Logger Rate Limiter.py | yanshengjia/algorithm | train | 69 | |
43085f9355ed74c0e659a9fcb629329e36c4ea93 | [
"assert c2 < 1\nassert c1 < c2\nself.line_search = LineSearch(c1, c2, beta, tol)\nself.tad = TorchAutoDiff()\nself.f_all = []\nself.r = r\nself.tol = tol",
"y_k = grad_k_1 - grad_k\ns_k = x_k_1 - x_k\nif torch.abs(torch.t(y_k).matmul(s_k - H_k.matmul(y_k))) > self.r * torch.norm(y_k) * (s_k - H_k.matmul(y_k)) or ... | <|body_start_0|>
assert c2 < 1
assert c1 < c2
self.line_search = LineSearch(c1, c2, beta, tol)
self.tad = TorchAutoDiff()
self.f_all = []
self.r = r
self.tol = tol
<|end_body_0|>
<|body_start_1|>
y_k = grad_k_1 - grad_k
s_k = x_k_1 - x_k
i... | SR1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SR1:
def __init__(self, r, c1, c2, beta=None, tol=0.0001):
"""This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step selection. This method is advantageous in constrained optimization setting where the secant... | stack_v2_sparse_classes_75kplus_train_008791 | 6,380 | no_license | [
{
"docstring": "This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step selection. This method is advantageous in constrained optimization setting where the secant condition y_{k}^{T}s_{k} > 0 can not be satisfied. Input: c1 : parame... | 2 | stack_v2_sparse_classes_30k_train_045335 | Implement the Python class `SR1` described below.
Class description:
Implement the SR1 class.
Method signatures and docstrings:
- def __init__(self, r, c1, c2, beta=None, tol=0.0001): This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step... | Implement the Python class `SR1` described below.
Class description:
Implement the SR1 class.
Method signatures and docstrings:
- def __init__(self, r, c1, c2, beta=None, tol=0.0001): This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step... | 160f6bcef64d17c622fb9cb017bd4faa65afd858 | <|skeleton|>
class SR1:
def __init__(self, r, c1, c2, beta=None, tol=0.0001):
"""This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step selection. This method is advantageous in constrained optimization setting where the secant... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SR1:
def __init__(self, r, c1, c2, beta=None, tol=0.0001):
"""This is the implementation of the SR1 method. sec 6.2 Nocedal Line search is used to compute next step. To be Done : Trust region step selection. This method is advantageous in constrained optimization setting where the secant condition y_{... | the_stack_v2_python_sparse | python/py_solvers/unconstrained/quasi_newton.py | avadesh02/Non-Linear-Optimization-Solvers-Package | train | 4 | |
8575369963e45dc80448ce6c6477fc96c9d6be3b | [
"cafe_path = None\ntry:\n cafe_path = os.path.join(os.path.dirname(cafe.__file__), 'plugins')\nexcept AttributeError:\n cafe_path = os.path.join(cafe.__path__[0], 'plugins')\nreturn cafe_path",
"plugin_folders = os.walk(cls._plugin_dir()).next()[1]\nwrap = textwrap.TextWrapper(initial_indent=' ', subsequen... | <|body_start_0|>
cafe_path = None
try:
cafe_path = os.path.join(os.path.dirname(cafe.__file__), 'plugins')
except AttributeError:
cafe_path = os.path.join(cafe.__path__[0], 'plugins')
return cafe_path
<|end_body_0|>
<|body_start_1|>
plugin_folders = os.wa... | EnginePluginManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnginePluginManager:
def _plugin_dir(cls):
"""TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing a namespace package in it. This is a workaround/hack to get around the issue for now. Ideally, we should mo... | stack_v2_sparse_classes_75kplus_train_008792 | 24,517 | permissive | [
{
"docstring": "TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing a namespace package in it. This is a workaround/hack to get around the issue for now. Ideally, we should move all the plugins into pypi so that we don't have to ... | 4 | stack_v2_sparse_classes_30k_train_050392 | Implement the Python class `EnginePluginManager` described below.
Class description:
Implement the EnginePluginManager class.
Method signatures and docstrings:
- def _plugin_dir(cls): TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing... | Implement the Python class `EnginePluginManager` described below.
Class description:
Implement the EnginePluginManager class.
Method signatures and docstrings:
- def _plugin_dir(cls): TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing... | 67efb1615fc2d7c4f287878d3fe04b9faa598f10 | <|skeleton|>
class EnginePluginManager:
def _plugin_dir(cls):
"""TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing a namespace package in it. This is a workaround/hack to get around the issue for now. Ideally, we should mo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnginePluginManager:
def _plugin_dir(cls):
"""TODO: setuptools 31.0.0 introduced a bug that results in __file__ not existing for a namespace packages, in our case, after installing a namespace package in it. This is a workaround/hack to get around the issue for now. Ideally, we should move all the plu... | the_stack_v2_python_sparse | cafe/configurator/managers.py | CafeHub/opencafe | train | 0 | |
67df634a3a0f99574169ec946f9a51751f906cee | [
"self.dt, self.h = (dt, h)\nself.grid = c.shape[:]\nself.srcidx = srcidx[:]\nself.source = srcfunc()\nself.context = util.grabcontext(context)\nself.queue = cl.CommandQueue(self.context)\nt = Template(filename=self._kernel, output_encoding='ascii')\nself.fdcl = cl.Program(self.context, t.render(dim=self.grid, srcid... | <|body_start_0|>
self.dt, self.h = (dt, h)
self.grid = c.shape[:]
self.srcidx = srcidx[:]
self.source = srcfunc()
self.context = util.grabcontext(context)
self.queue = cl.CommandQueue(self.context)
t = Template(filename=self._kernel, output_encoding='ascii')
... | A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided. | Helmholtz | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initiali... | stack_v2_sparse_classes_75kplus_train_008793 | 24,055 | permissive | [
{
"docstring": "Initialize the sound-speed c, time step dt and spatial step h. The coroutine srcfunc should provide a time-dependent value that describes the incident pressure at index srcidx. The context, if provided, is a PyOpenCL context for a single device. If it is not provided, a default context will be c... | 4 | stack_v2_sparse_classes_30k_train_039389 | Implement the Python class `Helmholtz` described below.
Class description:
A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided.
Method signatures and docstrings:
- def __init__... | Implement the Python class `Helmholtz` described below.
Class description:
A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided.
Method signatures and docstrings:
- def __init__... | 5fabc9c1f410bf49b674bfb4427fe1f05ad251ed | <|skeleton|>
class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initiali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initialize the sound-... | the_stack_v2_python_sparse | pycwp/cltools/wavecl.py | ahesford/pycwp | train | 0 |
3f219301af76cb2f113ef3795e4b1710360899f3 | [
"result = []\nfor char in longUrl:\n result.append(str(ord(char)))\nreturn 'http://tinyurl.com/' + '#'.join(result)",
"tmp = shortUrl.split('/')[-1]\nresult = ''\nfor char in tmp.split('#'):\n result = result + chr(int(char))\nreturn result"
] | <|body_start_0|>
result = []
for char in longUrl:
result.append(str(ord(char)))
return 'http://tinyurl.com/' + '#'.join(result)
<|end_body_0|>
<|body_start_1|>
tmp = shortUrl.split('/')[-1]
result = ''
for char in tmp.split('#'):
result = result +... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
... | stack_v2_sparse_classes_75kplus_train_008794 | 750 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_047783 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
class Code... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
result = []
for char in longUrl:
result.append(str(ord(char)))
return 'http://tinyurl.com/' + '#'.join(result)
def decode(self, shortUrl: str) -> str:
"""Decodes a sho... | the_stack_v2_python_sparse | hashtable/tinyUrl.py | gsy/leetcode | train | 1 | |
365562a374cc42380530faec39ec73dd60ae3392 | [
"if e_sum_lim is None:\n e_sum_lim = [-10.0, 10.0]\nif out_lim is None:\n out_lim = [-50.0, 50.0]\nself.out_lim = out_lim\nself.p = float(p)\nself.i = float(i)\nself.d = float(d)\nself.e0 = 0.0\nself.e_sum = 0.0\nself.t0 = 0.0\nself.rate = rate\nself.e_sum_lim = e_sum_lim",
"if dt is None:\n dt = 1.0 / f... | <|body_start_0|>
if e_sum_lim is None:
e_sum_lim = [-10.0, 10.0]
if out_lim is None:
out_lim = [-50.0, 50.0]
self.out_lim = out_lim
self.p = float(p)
self.i = float(i)
self.d = float(d)
self.e0 = 0.0
self.e_sum = 0.0
self.t0... | PID | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PID:
def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None):
""":param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param e_sum_lim: maximum error sum value"""
<|body_0|>
def pass_value(self, r, m, dt=... | stack_v2_sparse_classes_75kplus_train_008795 | 4,500 | permissive | [
{
"docstring": ":param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param e_sum_lim: maximum error sum value",
"name": "__init__",
"signature": "def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None)"
},
{
"docstring": "ca... | 3 | null | Implement the Python class `PID` described below.
Class description:
Implement the PID class.
Method signatures and docstrings:
- def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None): :param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param ... | Implement the Python class `PID` described below.
Class description:
Implement the PID class.
Method signatures and docstrings:
- def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None): :param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param ... | 1171eed8d2894df6dcd84011a3c2521781709bd0 | <|skeleton|>
class PID:
def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None):
""":param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param e_sum_lim: maximum error sum value"""
<|body_0|>
def pass_value(self, r, m, dt=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PID:
def __init__(self, p, i, d, rate=20.0, out_lim=None, e_sum_lim=None):
""":param p: P gain :param i: I gain :param d: D gain :param rate: Rate in seconds :param out_lim: maximum output :param e_sum_lim: maximum error sum value"""
if e_sum_lim is None:
e_sum_lim = [-10.0, 10.0]
... | the_stack_v2_python_sparse | src/autodock_regulation/src/pid.py | VeslRuben/Autonomous-Inshore-Navigation-with-Lidar | train | 0 | |
53f36807f85cb5c6de0e623b2795c303145f83d3 | [
"super().__init__()\nself.hidden_dim = hidden_dim\nself.num_convs = num_convs\nself.short_cut = short_cut\nself.concat_hidden = concat_hidden\nself.node_emb = nn.Embedding(100, hidden_dim)\nif isinstance(activation, str):\n self.activation = getattr(F, activation)\nelse:\n self.activation = None\nself.convs =... | <|body_start_0|>
super().__init__()
self.hidden_dim = hidden_dim
self.num_convs = num_convs
self.short_cut = short_cut
self.concat_hidden = concat_hidden
self.node_emb = nn.Embedding(100, hidden_dim)
if isinstance(activation, str):
self.activation = ge... | GIN encoder. | GINEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activatio... | stack_v2_sparse_classes_75kplus_train_008796 | 15,380 | permissive | [
{
"docstring": "Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activation: activation function. short_cut: whether to use short cut. concat_hidden: whether to concatenate hidden.",
"name": "__init__",
"signature": "def __init__(self, hidden_dim: ... | 2 | stack_v2_sparse_classes_30k_train_004727 | Implement the Python class `GINEncoder` described below.
Class description:
GIN encoder.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None: Construct a GIN encoder. Args: hidden_dim: number of hidd... | Implement the Python class `GINEncoder` described below.
Class description:
GIN encoder.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None: Construct a GIN encoder. Args: hidden_dim: number of hidd... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GINEncoder:
"""GIN encoder."""
def __init__(self, hidden_dim: int, num_convs: int=3, activation: str='relu', short_cut: bool=True, concat_hidden: bool=False) -> None:
"""Construct a GIN encoder. Args: hidden_dim: number of hidden channels. num_convs: number of convolutions. activation: activation... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/diffusion/geodiff/model/layers.py | GT4SD/gt4sd-core | train | 239 |
e25fab7c14a8ec487c117e48e4a7c55e5b285c36 | [
"inSpec = super(FastFourierTransform, cls).getInputSpecification()\ninSpec.addSub(InputData.parameterInputFactory('target', contentType=InputTypes.StringListType, strictMode=True))\nreturn inSpec",
"super().__init__()\nself.dynamic = True\nself.targets = None\nself.indices = None",
"super()._handleInput(paramIn... | <|body_start_0|>
inSpec = super(FastFourierTransform, cls).getInputSpecification()
inSpec.addSub(InputData.parameterInputFactory('target', contentType=InputTypes.StringListType, strictMode=True))
return inSpec
<|end_body_0|>
<|body_start_1|>
super().__init__()
self.dynamic = Tru... | Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target | FastFourierTransform | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastFourierTransform:
"""Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the ... | stack_v2_sparse_classes_75kplus_train_008797 | 6,142 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 6 | stack_v2_sparse_classes_30k_train_051243 | Implement the Python class `FastFourierTransform` described below.
Class description:
Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class tha... | Implement the Python class `FastFourierTransform` described below.
Class description:
Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class tha... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class FastFourierTransform:
"""Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastFourierTransform:
"""Constructs fast-fourier transform data for a history Outputs are "frequency" for each index and "amplitude" for each target"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for whi... | the_stack_v2_python_sparse | ravenframework/Models/PostProcessors/FastFourierTransform.py | idaholab/raven | train | 201 |
d06d1f73e290d05221b70593a3bb9e1801a49564 | [
"time_zone_offset = self._GetValueFromStructure(structure, 'time_zone_offset')\ntry:\n time_zone_offset_hours = int(time_zone_offset[1:3], 10)\n time_zone_offset_minutes = int(time_zone_offset[3:5], 10)\nexcept (IndexError, TypeError, ValueError) as exception:\n raise ValueError('unable to parse time zone ... | <|body_start_0|>
time_zone_offset = self._GetValueFromStructure(structure, 'time_zone_offset')
try:
time_zone_offset_hours = int(time_zone_offset[1:3], 10)
time_zone_offset_minutes = int(time_zone_offset[3:5], 10)
except (IndexError, TypeError, ValueError) as exception:
... | Parses events from Google Drive Sync log files. | GoogleDriveSyncLogParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -08... | stack_v2_sparse_classes_75kplus_train_008798 | 8,303 | permissive | [
{
"docstring": "Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: \"2018-01-24 18:25:08,454 -0800\". Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file, that contains the time element... | 4 | stack_v2_sparse_classes_30k_val_002626 | Implement the Python class `GoogleDriveSyncLogParser` described below.
Class description:
Parses events from Google Drive Sync log files.
Method signatures and docstrings:
- def _GetISO8601String(self, structure): Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync... | Implement the Python class `GoogleDriveSyncLogParser` described below.
Class description:
Parses events from Google Drive Sync log files.
Method signatures and docstrings:
- def _GetISO8601String(self, structure): Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -08... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -0800". Args: st... | the_stack_v2_python_sparse | plaso/parsers/gdrive_synclog.py | cyb3rfox/plaso | train | 3 |
93fcea611e99e3137b1b6047c362ac72cb988275 | [
"row = g.db.query(Machine).get(machine_id)\nif not row:\n log.warning('Requested a non-existant machine: %s', machine_id)\n abort(http_client.NOT_FOUND, description='Machine not found')\nrecord = row.as_dict()\nrecord['url'] = url_for('machines.entry', machine_id=machine_id, _external=True)\nrecord['servers_u... | <|body_start_0|>
row = g.db.query(Machine).get(machine_id)
if not row:
log.warning('Requested a non-existant machine: %s', machine_id)
abort(http_client.NOT_FOUND, description='Machine not found')
record = row.as_dict()
record['url'] = url_for('machines.entry', ma... | Information about specific machines | MachineAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def put(self, machine_id):
"""Update machine Heartbeat and... | stack_v2_sparse_classes_75kplus_train_008799 | 8,672 | permissive | [
{
"docstring": "Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json",
"name": "get",
"signature": "def get(self, machine_id)"
},
{
"docstring": "Update machine Heartbeat and update the machine reference",
"name": "put",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_033570 | Implement the Python class `MachineAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def put(self, machine_id): Update ... | Implement the Python class `MachineAPI` described below.
Class description:
Information about specific machines
Method signatures and docstrings:
- def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json
- def put(self, machine_id): Update ... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
<|body_0|>
def put(self, machine_id):
"""Update machine Heartbeat and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MachineAPI:
"""Information about specific machines"""
def get(self, machine_id):
"""Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json"""
row = g.db.query(Machine).get(machine_id)
if not row:
log.warning('Requeste... | the_stack_v2_python_sparse | driftbase/api/machines.py | dgnorth/drift-base | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.