uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b7128c8499eaff42e1c464b | train | class | class DBSetupTest(TestCase):
trip_id = "t1"
service_id = "s1"
route_id = "r1"
shape_id = "shape1"
stop_id = "stop1"
def setUp(self):
insert_service(self.service_id, '20180910', '20180912', 1, 0, 1, 0, 1, 1, 1)
insert_route(self.route_id, "short route", "long route")
in... | class DBSetupTest(TestCase):
| trip_id = "t1"
service_id = "s1"
route_id = "r1"
shape_id = "shape1"
stop_id = "stop1"
def setUp(self):
insert_service(self.service_id, '20180910', '20180912', 1, 0, 1, 0, 1, 1, 1)
insert_route(self.route_id, "short route", "long route")
insert_shape(self.shape_id, "31.... | 173569&lon=-114.118553&datetime=2018-04-29_18:47:05')
#
# # Test my_view() as if it were deployed at /customer/details
# response = query(request)
# self.assertEqual(response.status_code, 200)
class DBSetupTest(TestCase):
| 69 | 69 | 233 | 7 | 62 | hazelement/OneBus | api/tests.py | Python | DBSetupTest | DBSetupTest | 24 | 46 | 24 | 25 | ad2347b20c555524029add0742b34b69ba232317 | bigcode/the-stack | train |
c6b3f0ba9c61333f25a209eb | train | class | class TestETCI2021:
@pytest.fixture(params=["train", "val", "test"])
def dataset(
self,
monkeypatch: Generator[MonkeyPatch, None, None],
tmp_path: Path,
request: SubRequest,
) -> ETCI2021:
monkeypatch.setattr( # type: ignore[attr-defined]
torchgeo.dataset... | class TestETCI2021:
@pytest.fixture(params=["train", "val", "test"])
| def dataset(
self,
monkeypatch: Generator[MonkeyPatch, None, None],
tmp_path: Path,
request: SubRequest,
) -> ETCI2021:
monkeypatch.setattr( # type: ignore[attr-defined]
torchgeo.datasets.utils, "download_url", download_url
)
data_dir = os.pat... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import shutil
from pathlib import Path
from typing import Generator
import pytest
import torch
from _pytest.fixtures import SubRequest
from _pytest.monkeypatch import MonkeyPatch
import torchgeo.datasets.utils
fro... | 130 | 192 | 641 | 21 | 109 | Z-Zheng/torchgeo | tests/datasets/test_etci2021.py | Python | TestETCI2021 | TestETCI2021 | 23 | 86 | 23 | 24 | 061afa6bb5779210485f1caad723d807e7c591c7 | bigcode/the-stack | train |
236a8f11627d2fb2d78b7c9f | train | function | def download_url(url: str, root: str, *args: str) -> None:
shutil.copy(url, root)
| def download_url(url: str, root: str, *args: str) -> None:
| shutil.copy(url, root)
| import torch
from _pytest.fixtures import SubRequest
from _pytest.monkeypatch import MonkeyPatch
import torchgeo.datasets.utils
from torchgeo.datasets import ETCI2021
from torchgeo.transforms import Identity
def download_url(url: str, root: str, *args: str) -> None:
| 64 | 64 | 26 | 19 | 44 | Z-Zheng/torchgeo | tests/datasets/test_etci2021.py | Python | download_url | download_url | 19 | 20 | 19 | 19 | b430b6cc8556d99f374fde16fec5b0072c387258 | bigcode/the-stack | train |
044945ab00296929aa9a56ff | train | class | class BomItemResource(ModelResource):
""" Class for managing BomItem data import/export """
level = Field(attribute='level', readonly=True)
bom_id = Field(attribute='pk')
parent_part_id = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
parent_part_name = Field(attribute='part__ful... | class BomItemResource(ModelResource):
| """ Class for managing BomItem data import/export """
level = Field(attribute='level', readonly=True)
bom_id = Field(attribute='pk')
parent_part_id = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
parent_part_name = Field(attribute='part__full_name', readonly=True)
sub_part_... | .ModelAdmin):
list_display = ('part', 'attachment', 'comment')
class PartStarAdmin(admin.ModelAdmin):
list_display = ('part', 'user')
class PartTestTemplateAdmin(admin.ModelAdmin):
list_display = ('part', 'test_name', 'required')
class BomItemResource(ModelResource):
| 64 | 64 | 181 | 7 | 57 | gpauriyal/inventree-python | part/admin.py | Python | BomItemResource | BomItemResource | 135 | 163 | 135 | 135 | 7486f91aa5f672a657b2272dd8ef3c253e55730b | bigcode/the-stack | train |
9cc1427ff4bf20af5b7f80f6 | train | class | class PartResource(ModelResource):
""" Class for managing Part data import/export """
# ForeignKey fields
category = Field(attribute='category', widget=widgets.ForeignKeyWidget(PartCategory))
default_location = Field(attribute='default_location', widget=widgets.ForeignKeyWidget(StockLocation))
... | class PartResource(ModelResource):
| """ Class for managing Part data import/export """
# ForeignKey fields
category = Field(attribute='category', widget=widgets.ForeignKeyWidget(PartCategory))
default_location = Field(attribute='default_location', widget=widgets.ForeignKeyWidget(StockLocation))
default_supplier = Field(attribut... | unicode_literals
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export.resources import ModelResource
from import_export.fields import Field
import import_export.widgets as widgets
from .models import PartCategory, Part
from .models import PartAttachment, PartSta... | 106 | 106 | 355 | 6 | 99 | gpauriyal/inventree-python | part/admin.py | Python | PartResource | PartResource | 21 | 69 | 21 | 21 | 88efb246eb8de379836bc287402b5e543ef62af7 | bigcode/the-stack | train |
c9b52e18c4a921622453aecc | train | class | class PartCategoryResource(ModelResource):
""" Class for managing PartCategory data import/export """
parent = Field(attribute='parent', widget=widgets.ForeignKeyWidget(PartCategory))
parent_name = Field(attribute='parent__name', readonly=True)
default_location = Field(attribute='default_location', w... | class PartCategoryResource(ModelResource):
| """ Class for managing PartCategory data import/export """
parent = Field(attribute='parent', widget=widgets.ForeignKeyWidget(PartCategory))
parent_name = Field(attribute='parent__name', readonly=True)
default_location = Field(attribute='default_location', widget=widgets.ForeignKeyWidget(StockLocatio... | _display = ('full_name', 'description', 'total_stock', 'category')
list_filter = ('active', 'assembly', 'is_template', 'virtual')
search_fields = ('name', 'description', 'category__name', 'category__description', 'IPN')
class PartCategoryResource(ModelResource):
| 64 | 64 | 189 | 7 | 57 | gpauriyal/inventree-python | part/admin.py | Python | PartCategoryResource | PartCategoryResource | 83 | 108 | 83 | 83 | 8b6eab2ea01c862b9d4e7d9ddc5ae1f74db5f2d8 | bigcode/the-stack | train |
16b9704131dd5ed98def4895 | train | class | class PartStarAdmin(admin.ModelAdmin):
list_display = ('part', 'user')
| class PartStarAdmin(admin.ModelAdmin):
| list_display = ('part', 'user')
| ModelAdmin):
resource_class = PartCategoryResource
list_display = ('name', 'pathstring', 'description')
search_fields = ('name', 'description')
class PartAttachmentAdmin(admin.ModelAdmin):
list_display = ('part', 'attachment', 'comment')
class PartStarAdmin(admin.ModelAdmin):
| 64 | 64 | 18 | 8 | 56 | gpauriyal/inventree-python | part/admin.py | Python | PartStarAdmin | PartStarAdmin | 125 | 127 | 125 | 126 | ff921891a0211fb7129a1803c8f4e2b04ecbc986 | bigcode/the-stack | train |
76da9d87d458b72bff98a3ed | train | class | class ParameterAdmin(ImportExportModelAdmin):
resource_class = ParameterResource
list_display = ('part', 'template', 'data')
| class ParameterAdmin(ImportExportModelAdmin):
| resource_class = ParameterResource
list_display = ('part', 'template', 'data')
| widgets.ForeignKeyWidget(PartParameterTemplate))
template_name = Field(attribute='template__name', readonly=True)
class Meta:
model = PartParameter
skip_unchanged = True
report_skipped = False
clean_model_instance = True
class ParameterAdmin(ImportExportModelAdmin):
| 64 | 64 | 29 | 9 | 54 | gpauriyal/inventree-python | part/admin.py | Python | ParameterAdmin | ParameterAdmin | 197 | 201 | 197 | 198 | c2e8bf20d5c7bcb094ee7187b73e43a620665e75 | bigcode/the-stack | train |
39173ac021af1cc75d6a2643 | train | class | class BomItemAdmin(ImportExportModelAdmin):
resource_class = BomItemResource
list_display = ('part', 'sub_part', 'quantity')
search_fields = ('part__name', 'part__description', 'sub_part__name', 'sub_part__description')
| class BomItemAdmin(ImportExportModelAdmin):
| resource_class = BomItemResource
list_display = ('part', 'sub_part', 'quantity')
search_fields = ('part__name', 'part__description', 'sub_part__name', 'sub_part__description')
| Meta:
model = BomItem
skip_unchanged = True
report_skipped = False
clean_model_instances = True
exclude = [
'checksum',
'id',
'part',
'sub_part',
]
class BomItemAdmin(ImportExportModelAdmin):
| 63 | 64 | 58 | 10 | 53 | gpauriyal/inventree-python | part/admin.py | Python | BomItemAdmin | BomItemAdmin | 166 | 172 | 166 | 167 | ae3d212d3c79963b066b02e4f25c403e8f5a5106 | bigcode/the-stack | train |
016084c48bec9719b8cc70f9 | train | class | class ParameterResource(ModelResource):
""" Class for managing PartParameter data import/export """
part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
part_name = Field(attribute='part__name', readonly=True)
template = Field(attribute='template', widget=widgets.ForeignKeyWidget(Par... | class ParameterResource(ModelResource):
| """ Class for managing PartParameter data import/export """
part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
part_name = Field(attribute='part__name', readonly=True)
template = Field(attribute='template', widget=widgets.ForeignKeyWidget(PartParameterTemplate))
template_name ... | _display = ('part', 'sub_part', 'quantity')
search_fields = ('part__name', 'part__description', 'sub_part__name', 'sub_part__description')
class ParameterTemplateAdmin(ImportExportModelAdmin):
list_display = ('name', 'units')
class ParameterResource(ModelResource):
| 64 | 64 | 113 | 6 | 58 | gpauriyal/inventree-python | part/admin.py | Python | ParameterResource | ParameterResource | 179 | 194 | 179 | 179 | a91109c756520facd9b27c4022a91d57b760c6ba | bigcode/the-stack | train |
a3a16d6acb73a3f03cad8506 | train | class | class PartAttachmentAdmin(admin.ModelAdmin):
list_display = ('part', 'attachment', 'comment')
| class PartAttachmentAdmin(admin.ModelAdmin):
| list_display = ('part', 'attachment', 'comment')
| build the PartCategory tree(s)
PartCategory.objects.rebuild()
class PartCategoryAdmin(ImportExportModelAdmin):
resource_class = PartCategoryResource
list_display = ('name', 'pathstring', 'description')
search_fields = ('name', 'description')
class PartAttachmentAdmin(admin.ModelAdmin):
| 64 | 64 | 21 | 8 | 56 | gpauriyal/inventree-python | part/admin.py | Python | PartAttachmentAdmin | PartAttachmentAdmin | 120 | 122 | 120 | 121 | b16ccace42291b5746efa95520b872899005f09b | bigcode/the-stack | train |
687397015d590b430ed0118d | train | class | class PartAdmin(ImportExportModelAdmin):
resource_class = PartResource
list_display = ('full_name', 'description', 'total_stock', 'category')
list_filter = ('active', 'assembly', 'is_template', 'virtual')
search_fields = ('name', 'description', 'category__name', 'category__description', 'IPN')
| class PartAdmin(ImportExportModelAdmin):
| resource_class = PartResource
list_display = ('full_name', 'description', 'total_stock', 'category')
list_filter = ('active', 'assembly', 'is_template', 'virtual')
search_fields = ('name', 'description', 'category__name', 'category__description', 'IPN')
| query = super().get_queryset()
query = query.prefetch_related(
'category',
'used_in',
'builds',
'supplier_parts__purchase_order_line_items',
'stock_items__allocations'
)
return query
class PartAdmin(ImportExportModelAdmin):
... | 64 | 64 | 76 | 10 | 53 | gpauriyal/inventree-python | part/admin.py | Python | PartAdmin | PartAdmin | 72 | 80 | 72 | 73 | 423299986819df32ef79508527c03df238a1821b | bigcode/the-stack | train |
75636eb2f89d4d5d8df05df1 | train | class | class PartTestTemplateAdmin(admin.ModelAdmin):
list_display = ('part', 'test_name', 'required')
| class PartTestTemplateAdmin(admin.ModelAdmin):
| list_display = ('part', 'test_name', 'required')
| pathstring', 'description')
search_fields = ('name', 'description')
class PartAttachmentAdmin(admin.ModelAdmin):
list_display = ('part', 'attachment', 'comment')
class PartStarAdmin(admin.ModelAdmin):
list_display = ('part', 'user')
class PartTestTemplateAdmin(admin.ModelAdmin):
| 64 | 64 | 23 | 9 | 55 | gpauriyal/inventree-python | part/admin.py | Python | PartTestTemplateAdmin | PartTestTemplateAdmin | 130 | 132 | 130 | 131 | 800b85979fa59ef2e4fb19d366842a04bf1ceec5 | bigcode/the-stack | train |
908983f73dab32e3b55cc1d3 | train | class | class ParameterTemplateAdmin(ImportExportModelAdmin):
list_display = ('name', 'units')
| class ParameterTemplateAdmin(ImportExportModelAdmin):
| list_display = ('name', 'units')
| (ImportExportModelAdmin):
resource_class = BomItemResource
list_display = ('part', 'sub_part', 'quantity')
search_fields = ('part__name', 'part__description', 'sub_part__name', 'sub_part__description')
class ParameterTemplateAdmin(ImportExportModelAdmin):
| 64 | 64 | 20 | 10 | 54 | gpauriyal/inventree-python | part/admin.py | Python | ParameterTemplateAdmin | ParameterTemplateAdmin | 175 | 176 | 175 | 175 | e58f5aa9919d68d1fbf35764424ec809e30b6b9c | bigcode/the-stack | train |
444551cf0eb7611a8477c97d | train | class | class PartCategoryAdmin(ImportExportModelAdmin):
resource_class = PartCategoryResource
list_display = ('name', 'pathstring', 'description')
search_fields = ('name', 'description')
| class PartCategoryAdmin(ImportExportModelAdmin):
| resource_class = PartCategoryResource
list_display = ('name', 'pathstring', 'description')
search_fields = ('name', 'description')
| def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
super().after_import(dataset, result, using_transactions, dry_run, **kwargs)
# Rebuild the PartCategory tree(s)
PartCategory.objects.rebuild()
class PartCategoryAdmin(ImportExportModelAdmin):
| 64 | 64 | 42 | 10 | 54 | gpauriyal/inventree-python | part/admin.py | Python | PartCategoryAdmin | PartCategoryAdmin | 111 | 117 | 111 | 112 | 6861f572ea8678a0c569c6a922a65043a44d16d9 | bigcode/the-stack | train |
d37b386bae347af705ed4f62 | train | function | def get_session_identity_keys():
return ["default_wallet_index"]
| def get_session_identity_keys():
| return ["default_wallet_index"]
| to a required ledger nano s device for signing using a given wallet\n"
" index)\n"
" - 'trezor' (yields to a required trezor device for signing using a given wallet index)\n"
"\n")
exit(1)
def get_session_identity_keys():
| 64 | 64 | 13 | 6 | 58 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | get_session_identity_keys | get_session_identity_keys | 225 | 226 | 225 | 225 | aabba65c70edea857b67b2b4cf1d802446a6dea4 | bigcode/the-stack | train |
d489653b0085473f9f0a36cb | train | function | def get_session_keys():
return get_session_network_keys() + get_session_identity_keys() + ["default_ipfs_endpoint"]
| def get_session_keys():
| return get_session_network_keys() + get_session_identity_keys() + ["default_ipfs_endpoint"]
| crow_at", "current_singularitynettoken_at",
"default_eth_rpc_endpoint"]
def get_session_network_keys_removable():
return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at"]
def get_session_keys():
| 63 | 64 | 25 | 5 | 58 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | get_session_keys | get_session_keys | 238 | 239 | 238 | 238 | c88f41dca0142a2beff707236280db8ba8ef7659 | bigcode/the-stack | train |
e85642a90b42a229cb342a9d | train | class | class Config(ConfigParser):
def __init__(self, _snet_folder=default_snet_folder):
super(Config, self).__init__(interpolation=ExtendedInterpolation(), delimiters=("=",))
self._config_file = _snet_folder.joinpath("config")
if (self._config_file.exists()):
with open(self._config_fil... | class Config(ConfigParser):
| def __init__(self, _snet_folder=default_snet_folder):
super(Config, self).__init__(interpolation=ExtendedInterpolation(), delimiters=("=",))
self._config_file = _snet_folder.joinpath("config")
if (self._config_file.exists()):
with open(self._config_file) as f:
sel... | from configparser import ConfigParser, ExtendedInterpolation
from pathlib import Path
default_snet_folder = Path("~").expanduser().joinpath(".snet")
class Config(ConfigParser):
| 38 | 256 | 2,184 | 5 | 33 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | Config | Config | 7 | 207 | 7 | 7 | 80bcedb43f7b695335abd004eb152dfb671b9ddc | bigcode/the-stack | train |
302b8d08d486e00865605ec2 | train | function | def first_identity_message_and_exit():
print("\nPlease create your first identity by running 'snet identity create'.\n\n"
"The available identity types are:\n"
" - 'rpc' (yields to a required ethereum json-rpc endpoint for signing using a given wallet\n"
" index)\n"
... | def first_identity_message_and_exit():
| print("\nPlease create your first identity by running 'snet identity create'.\n\n"
"The available identity types are:\n"
" - 'rpc' (yields to a required ethereum json-rpc endpoint for signing using a given wallet\n"
" index)\n"
" - 'mnemonic' (uses a required b... | not in self):
raise Exception("Config error, section %s is absent" % s)
def _persist(self):
with open(self._config_file, "w") as f:
self.write(f)
self._config_file.chmod(0o600)
def first_identity_message_and_exit():
| 64 | 64 | 196 | 7 | 57 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | first_identity_message_and_exit | first_identity_message_and_exit | 210 | 222 | 210 | 210 | d75cdecee5b6c667689b7322079dc906547751b5 | bigcode/the-stack | train |
9e94464567ee3a99eb731beb | train | function | def get_session_network_keys_removable():
return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at"]
| def get_session_network_keys_removable():
| return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at"]
| _session_identity_keys():
return ["default_wallet_index"]
def get_session_network_keys():
return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at",
"default_eth_rpc_endpoint"]
def get_session_network_keys_removable():
| 63 | 64 | 38 | 8 | 55 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | get_session_network_keys_removable | get_session_network_keys_removable | 234 | 235 | 234 | 234 | 0ea865d37b7a8b122d194a4d6f96a26ae3f9bfb5 | bigcode/the-stack | train |
ece7e01c143c9d7183d394d7 | train | function | def get_session_network_keys():
return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at",
"default_eth_rpc_endpoint"]
| def get_session_network_keys():
| return ["default_gas_price", "current_registry_at", "current_multipartyescrow_at", "current_singularitynettoken_at",
"default_eth_rpc_endpoint"]
| "
" index)\n"
" - 'trezor' (yields to a required trezor device for signing using a given wallet index)\n"
"\n")
exit(1)
def get_session_identity_keys():
return ["default_wallet_index"]
def get_session_network_keys():
| 63 | 64 | 43 | 6 | 57 | dhruvshettty/snet-cli | packages/snet_cli/snet_cli/config.py | Python | get_session_network_keys | get_session_network_keys | 229 | 231 | 229 | 229 | 885d62a0d4948ec663efe7742388dd404a86a94a | bigcode/the-stack | train |
5f94bae1e3b0942088e7dc30 | train | function | def get_naver_blog_user_id(naver_blog_link):
u = re.search(r'^http://blog.naver.com/(.*)', naver_blog_link)
if u is None:
print(naver_blog_link)
return None
return u.group(1)
| def get_naver_blog_user_id(naver_blog_link):
| u = re.search(r'^http://blog.naver.com/(.*)', naver_blog_link)
if u is None:
print(naver_blog_link)
return None
return u.group(1)
| _blog_link, title, post_date,
'NAVER', '블로그')
return
def get_naver_blog_page_num(naver_blog_inner_link):
temp_link = naver_blog_inner_link.split('=')
return temp_link[-1]
def get_naver_blog_user_id(naver_blog_link):
| 64 | 64 | 57 | 12 | 52 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_naver_blog_user_id | get_naver_blog_user_id | 332 | 337 | 332 | 332 | 05bfe4ea32df5896af92c6da07d648f6e616316e | bigcode/the-stack | train |
e685d55248a2fd8a4ca84e94 | train | function | def month_converter(month):
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months.index(month) + 1
| def month_converter(month):
| months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months.index(month) + 1
| e)
def get_twitter_post_date(date_str):
split_date = date_str.split()
post_date = '%s-%02d-%02d' % (split_date[5],
month_converter(split_date[1]),
int(split_date[2]))
return post_date
def month_converter(month):
| 64 | 64 | 54 | 5 | 58 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | month_converter | month_converter | 498 | 500 | 498 | 498 | c017fe0a33dcb37b76b62fdd3615b91543a98b47 | bigcode/the-stack | train |
4cb39507400c8d786f68b596 | train | function | def get_naver_blog_post_date(post_date): # 20170323 -> 2017-03-23
return '-'.join([post_date[:4], post_date[4:6], post_date[6:]])
| def get_naver_blog_post_date(post_date): # 20170323 -> 2017-03-23
| return '-'.join([post_date[:4], post_date[4:6], post_date[6:]])
| '^http://blog.naver.com/(.*)', naver_blog_link)
if u is None:
print(naver_blog_link)
return None
return u.group(1)
def get_naver_blog_post_date(post_date): # 20170323 -> 2017-03-23
| 64 | 64 | 49 | 25 | 39 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_naver_blog_post_date | get_naver_blog_post_date | 340 | 341 | 340 | 340 | 94df24f9de4ba0e6888148a60dd3355c2ffda39b | bigcode/the-stack | train |
9cb4014d8ba908d18ada308f | train | function | def search_webs(s):
for key in s.keys:
get_daum(s, key)
# get_daum_agora(s, key) # pretty shit...
get_naver(s, key)
get_today_humor(s, key)
get_nate_pann(s, key)
get_twitter_search(s, key)
get_dcinside(s, key)
get_ilbe(s, key)
get_bobedream(s,... | def search_webs(s):
| for key in s.keys:
get_daum(s, key)
# get_daum_agora(s, key) # pretty shit...
get_naver(s, key)
get_today_humor(s, key)
get_nate_pann(s, key)
get_twitter_search(s, key)
get_dcinside(s, key)
get_ilbe(s, key)
get_bobedream(s, key)
get_in... | # -*- coding: utf-8 -*-
import json
import urllib.request
import re
import sys
from bs4 import BeautifulSoup
from requests import get, codes
from twython import TwythonError
from searcher.google_sheet import append_google_sheet
def search_webs(s):
| 59 | 64 | 116 | 6 | 52 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | search_webs | search_webs | 13 | 25 | 13 | 13 | 0d19a9cb072944bfacbe1e49fe59f1841945093f | bigcode/the-stack | train |
e7e7ab53588b8e61982012a4 | train | function | def parse_tistory_page(s, daum_blog_link):
r = get(daum_blog_link)
soup = BeautifulSoup(r.text, 'html.parser')
rows = None
for a in soup.find_all(s.match_soup_class(['article'])):
rows = a.findChildren(['th', 'tr'])
if rows is None:
return None, None
for row in rows:
ce... | def parse_tistory_page(s, daum_blog_link):
| r = get(daum_blog_link)
soup = BeautifulSoup(r.text, 'html.parser')
rows = None
for a in soup.find_all(s.match_soup_class(['article'])):
rows = a.findChildren(['th', 'tr'])
if rows is None:
return None, None
for row in rows:
cells = row.findChildren('td')
for ce... | _id.group(1), daum_blog_link, title, post_date,
'DAUM', '블로그')
continue
else:
s.logger.info('[drop] %s', daum_blog_link) # drop
return
def parse_tistory_page(s, daum_blog_link):
| 64 | 64 | 131 | 12 | 51 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | parse_tistory_page | parse_tistory_page | 402 | 417 | 402 | 402 | 11bb202c29c1c7bebddf40035458543547fa33ad | bigcode/the-stack | train |
e5f84253b972bfd72f0f51aa | train | function | def get_today_humor(s, key):
url = 'http://www.todayhumor.co.kr/board/list.php?kind=search&keyfield=subject&keyword=%s&Submit.x=0&Submit.y=0&Submit=검색' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[TodayHumor] request error')
return None
soup = BeautifulSoup(r.text, ... | def get_today_humor(s, key):
| url = 'http://www.todayhumor.co.kr/board/list.php?kind=search&keyfield=subject&keyword=%s&Submit.x=0&Submit.y=0&Submit=검색' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[TodayHumor] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for l in s... | = re.search('(.*)-(.*)-(.*) ', date) # 아이디17-03-23
user_id_year = (u2.group(1)) # 아이디17
user_id = user_id_year[:-2] # 아이디
year = user_id_year[-2:] # 17
post_date = '20%s-%s-%s' % (year, u2.group(2), u2.group(3))
return user_id, post_date
return None,... | 122 | 122 | 408 | 10 | 111 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_today_humor | get_today_humor | 234 | 275 | 234 | 234 | 3bae75e73782ebe6d1284f629239029d614d9ebc | bigcode/the-stack | train |
71e19096242af06a96be759d | train | function | def get_ppomppu(s, key):
url = 'http://www.ppomppu.co.kr/search_bbs.php?keyword=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[Oh_U] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
# soup = BeautifulSoup(r.content.decode('utf-8r', 'repla... | def get_ppomppu(s, key):
| url = 'http://www.ppomppu.co.kr/search_bbs.php?keyword=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[Oh_U] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
# soup = BeautifulSoup(r.content.decode('utf-8r', 'replace'), 'html.parser')
... | m[0]
append_google_sheet(s, user_id, url, title, post_date, '오늘의 유머')
user_id, url, title, post_date = None, None, None, None
temp_url = None
return None
def get_ppomppu(s, key):
| 64 | 64 | 124 | 9 | 54 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_ppomppu | get_ppomppu | 278 | 287 | 278 | 278 | 4c16afbc9572bb22c8f1aee3fe931756c04d1074 | bigcode/the-stack | train |
80ed64cffc261b7fe17d821e | train | function | def get_clien(s, key):
date_regex = re.compile(r'^\d+:\d+')
for i in range(1, 10): # 10 page search
url = 'http://www.clien.net/cs2/bbs/board.php?bo_table=kin&page=%d' % i
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[CLIEN] request error')
return N... | def get_clien(s, key):
| date_regex = re.compile(r'^\d+:\d+')
for i in range(1, 10): # 10 page search
url = 'http://www.clien.net/cs2/bbs/board.php?bo_table=kin&page=%d' % i
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[CLIEN] request error')
return None
soup = Bea... | s(s):
for key in s.keys:
get_daum(s, key)
# get_daum_agora(s, key) # pretty shit...
get_naver(s, key)
get_today_humor(s, key)
get_nate_pann(s, key)
get_twitter_search(s, key)
get_dcinside(s, key)
get_ilbe(s, key)
get_bobedream(s, key)
... | 138 | 138 | 462 | 8 | 129 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_clien | get_clien | 29 | 71 | 29 | 29 | 9ca49e285abb9fb55bc8a55562afa89bec7ffe77 | bigcode/the-stack | train |
202eb39a67d5115381a0d4da | train | function | def get_daum(s, key, mode='date'):
# https://apis.daum.net/search/blog?apikey={apikey}&q=다음&output=json
url = 'https://apis.daum.net/search/blog?apikey=%s&q=' % (s.daum_app_key)
encText = urllib.parse.quote(key)
options = '&result=20&sort=%s&output=json' % mode
req_url = url + encText + options
... | def get_daum(s, key, mode='date'):
# https://apis.daum.net/search/blog?apikey={apikey}&q=다음&output=json
| url = 'https://apis.daum.net/search/blog?apikey=%s&q=' % (s.daum_app_key)
encText = urllib.parse.quote(key)
options = '&result=20&sort=%s&output=json' % mode
req_url = url + encText + options
request = urllib.request.Request(req_url)
try:
response = urllib.request.urlopen(request)
ex... | NAVER', '블로그')
return
def get_naver_blog_page_num(naver_blog_inner_link):
temp_link = naver_blog_inner_link.split('=')
return temp_link[-1]
def get_naver_blog_user_id(naver_blog_link):
u = re.search(r'^http://blog.naver.com/(.*)', naver_blog_link)
if u is None:
print(naver_blog_link)
... | 184 | 185 | 617 | 36 | 148 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_daum | get_daum | 344 | 399 | 344 | 346 | a849ba1f187a76e5f7a3df27531221290f33d596 | bigcode/the-stack | train |
952d117523c38d2fbf3d0d41 | train | function | def get_insoya(s, key):
for i in range(1, 5): # 5 page search
url = 'http://www.insoya.com/bbs/zboard.php?id=talkmaple&page=%d&divpage=15' % i
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[INSOYA] request error')
return None
soup = BeautifulSo... | def get_insoya(s, key):
| for i in range(1, 5): # 5 page search
url = 'http://www.insoya.com/bbs/zboard.php?id=talkmaple&page=%d&divpage=15' % i
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[INSOYA] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser'... | .text)
elif span.text == '12-31': # TODO : need to better way
post_date = '%s-%s' % (s.last_year, span.text)
else:
post_date = '%s-%s' % (s.this_year, span.text)
if url is not None:
... | 112 | 112 | 376 | 9 | 102 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_insoya | get_insoya | 74 | 110 | 74 | 74 | fb861d5b282e00293730931ce79c7787496955d4 | bigcode/the-stack | train |
97fab4c757dec1ea424b229d | train | function | def get_twitter_post_date(date_str):
split_date = date_str.split()
post_date = '%s-%02d-%02d' % (split_date[5],
month_converter(split_date[1]),
int(split_date[2]))
return post_date
| def get_twitter_post_date(date_str):
| split_date = date_str.split()
post_date = '%s-%02d-%02d' % (split_date[5],
month_converter(split_date[1]),
int(split_date[2]))
return post_date
| i['text'], post_url, 'No title', post_date,
'TWITTER')
# print('[USER_CREATED_AT]', i['user']['created_at'])
except TwythonError as e:
s.logger.error('TwythonError %s', e)
def get_twitter_post_date(date_str):
| 64 | 64 | 57 | 9 | 55 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_twitter_post_date | get_twitter_post_date | 490 | 495 | 490 | 490 | 84cd8bab76c5581327d9c62d7e642e3940678205 | bigcode/the-stack | train |
5b5877a055f1b64c64019ec3 | train | function | def get_title_and_user_id(s, message, blog_type=None):
if blog_type == 'tistory':
temp = message.split()
p = re.compile(r'^\d+:\d+:\d+')
m = p.match(temp[-1])
if m is None: # ok 'YYYY-MM-DD'
return' '.join(temp[:-2]), temp[-1].replace('.', '-')
else:
... | def get_title_and_user_id(s, message, blog_type=None):
| if blog_type == 'tistory':
temp = message.split()
p = re.compile(r'^\d+:\d+:\d+')
m = p.match(temp[-1])
if m is None: # ok 'YYYY-MM-DD'
return' '.join(temp[:-2]), temp[-1].replace('.', '-')
else:
return' '.join(temp[:-2]), s.today
else:
s.... | html.parser')
for a in soup.find_all('meta', property="ks:richscrap"):
res = json.loads(a['content'])
return (res['header']['title'], res['header']['date'].replace('.', '-'))
def get_title_and_user_id(s, message, blog_type=None):
| 63 | 64 | 125 | 14 | 49 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_title_and_user_id | get_title_and_user_id | 428 | 439 | 428 | 428 | 8bfc420945debeedba6e6c3177ec8ac4f00fb4a2 | bigcode/the-stack | train |
cae66f6a98ce7aa664bdd494 | train | function | def get_naver(s, key, mode='blog'):
url = 'https://openapi.naver.com/v1/search/%s?query=' % mode
encText = urllib.parse.quote(key)
options = '&display=20&sort=date'
req_url = url + encText + options
request = urllib.request.Request(req_url)
request.add_header('X-Naver-Client-Id', s.naver_client_... | def get_naver(s, key, mode='blog'):
| url = 'https://openapi.naver.com/v1/search/%s?query=' % mode
encText = urllib.parse.quote(key)
options = '&display=20&sort=date'
req_url = url + encText + options
request = urllib.request.Request(req_url)
request.add_header('X-Naver-Client-Id', s.naver_client_id)
request.add_header('X-Naver-... | ://www.ppomppu.co.kr/search_bbs.php?keyword=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[Oh_U] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
# soup = BeautifulSoup(r.content.decode('utf-8r', 'replace'), 'html.parser')
# soup = Beauti... | 122 | 122 | 409 | 12 | 110 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_naver | get_naver | 290 | 324 | 290 | 290 | e087f33f0f4bd248e17a4615711863478139bc90 | bigcode/the-stack | train |
1916e973cdb659e634fecb52 | train | function | def parse_brunch_page(daum_blog_link):
r = get(daum_blog_link)
soup = BeautifulSoup(r.text, 'html.parser')
for a in soup.find_all('meta', property="ks:richscrap"):
res = json.loads(a['content'])
return (res['header']['title'], res['header']['date'].replace('.', '-'))
| def parse_brunch_page(daum_blog_link):
| r = get(daum_blog_link)
soup = BeautifulSoup(r.text, 'html.parser')
for a in soup.find_all('meta', property="ks:richscrap"):
res = json.loads(a['content'])
return (res['header']['title'], res['header']['date'].replace('.', '-'))
|
for row in rows:
cells = row.findChildren('td')
for cell in cells:
message = row.text.strip()
return get_title_and_user_id(s, message.strip('\n'), 'tistory')
return None, None
def parse_brunch_page(daum_blog_link):
| 64 | 64 | 79 | 11 | 52 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | parse_brunch_page | parse_brunch_page | 420 | 425 | 420 | 420 | 6dd90ff1725e25c59b21e95abd3e41fc1d229d40 | bigcode/the-stack | train |
41960ebecf5c0d8c05dc54a3 | train | function | def get_bobedream(s, key):
for i in range(1, 10): # 5 page search
url = 'http://www.bobaedream.co.kr/list?code=freeb&s_cate=&maker_no=&model_no=&or_gu=10&or_se=desc&s_selday=&pagescale=30&info3=¬iceShow=&s_select=&s_key=&level_no=&vdate=&type=list&page=%d' % i
r = get(url)
if r.status_c... | def get_bobedream(s, key):
| for i in range(1, 10): # 5 page search
url = 'http://www.bobaedream.co.kr/list?code=freeb&s_cate=&maker_no=&model_no=&or_gu=10&or_se=desc&s_selday=&pagescale=30&info3=¬iceShow=&s_select=&s_key=&level_no=&vdate=&type=list&page=%d' % i
r = get(url)
if r.status_code != codes.ok:
... | ('span', attrs={'class': 'memberSelect'})
for span in spans:
if url is None:
break
user_id = span.string
# print(user_id)
txt = str(td)
if txt.startswith('<td class="eng w_date">'):
... | 157 | 157 | 526 | 9 | 147 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_bobedream | get_bobedream | 113 | 152 | 113 | 113 | 72bed46f824f920a6029d8d3dfc30713465dcc51 | bigcode/the-stack | train |
e6847cd8bb0e7dec70094e39 | train | function | def get_daum_agora(s, key):
url = 'http://agora.media.daum.net/nsearch/total?query=%s' % '사람'
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[DAUM AGORA] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for sre in soup.find_all(s.match_soup_class(... | def get_daum_agora(s, key):
| url = 'http://agora.media.daum.net/nsearch/total?query=%s' % '사람'
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[DAUM AGORA] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for sre in soup.find_all(s.match_soup_class(['sResult'])):
rows =... | ])
if m is None: # ok 'YYYY-MM-DD'
return' '.join(temp[:-2]), temp[-1].replace('.', '-')
else:
return' '.join(temp[:-2]), s.today
else:
s.logger.error('invalid blog_type: %s', blog_type)
return None, None
def get_daum_agora(s, key):
| 81 | 81 | 270 | 10 | 70 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_daum_agora | get_daum_agora | 442 | 467 | 442 | 443 | 7df94b7218bb5ac853422a50c660e622c1d13c18 | bigcode/the-stack | train |
f499ac27d67e61c4174c5a4f | train | function | def get_ilbe(s, key):
url = 'https://www.ilbe.com/?act=IS&where=document&is_keyword=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[ILGANBEST] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for sre in soup.find_all(s.match_soup_class(['... | def get_ilbe(s, key):
| url = 'https://www.ilbe.com/?act=IS&where=document&is_keyword=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[ILGANBEST] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for sre in soup.find_all(s.match_soup_class(['searchResult'])):
... | 보배드림')
url, user_id, post_date, title = None, None, None, None
else:
spans = td.find_all('span', attrs={'class': 'author'})
for span in spans:
user_id = span.string
def get_ilbe(s, key):
| 64 | 64 | 180 | 8 | 55 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_ilbe | get_ilbe | 155 | 169 | 155 | 155 | 868d99d08eb10860244eb5319c5a00235f37fe01 | bigcode/the-stack | train |
ab00edc77232ea4f1233f7d6 | train | function | def get_nate_id_and_date(date, user_info):
if len(date) == len('17-03-23'):
post_date = '20%s' % date
return user_info, post_date
else:
u1 = re.search('(.*)이야기(.*) ', date)
if u1 is not None: # 10대 이야기I__D17-03-23 02:18
u2 = re.search('(.*)-(.*)-(.*)', u1.group(2)) ... | def get_nate_id_and_date(date, user_info):
| if len(date) == len('17-03-23'):
post_date = '20%s' % date
return user_info, post_date
else:
u1 = re.search('(.*)이야기(.*) ', date)
if u1 is not None: # 10대 이야기I__D17-03-23 02:18
u2 = re.search('(.*)-(.*)-(.*)', u1.group(2)) # I__D17-03-23
user_id_year = (... | info = row.text.strip().split('\n')
title = info[0]
date = info[-1].replace('.', '-')
user_id, post_date = get_nate_id_and_date(date, info[-2])
if user_id is None or post_date is None:
continue
append_goo... | 102 | 102 | 340 | 12 | 90 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_nate_id_and_date | get_nate_id_and_date | 211 | 231 | 211 | 211 | f75697587f5cb032d176cd19845126b80113442f | bigcode/the-stack | train |
75c0e12e049a2f11f086e4d0 | train | function | def get_twitter_search(s, key):
try:
timeline = s.twitter.search(
q=key, result_type='popular', count=20)
dump_tl = json.dumps(timeline) # dict -> json
tl = json.loads(dump_tl)
for i in tl['statuses']:
for url in i['entities']['urls']:
post_u... | def get_twitter_search(s, key):
| try:
timeline = s.twitter.search(
q=key, result_type='popular', count=20)
dump_tl = json.dumps(timeline) # dict -> json
tl = json.loads(dump_tl)
for i in tl['statuses']:
for url in i['entities']['urls']:
post_url = url['url']
... | # title
# #print(row.a['href']) # url
# print(user_id.strip())
append_google_sheet(s, user_id.strip(), row.a['href'], 'No title', post_date,
'DAUM', '아고라')
def get_twitter_search(s, key):
| 64 | 64 | 170 | 9 | 55 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_twitter_search | get_twitter_search | 470 | 487 | 470 | 470 | 4f6c92c71f6c4131a04fc27046b68487942f41b1 | bigcode/the-stack | train |
da3a8c05cd8c1a9c2e30f767 | train | function | def get_nate_pann(s, key):
url = 'http://pann.nate.com/search?searchType=A&q=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[Nate] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for srch in soup.find_all(s.match_soup_class(['srch_list']... | def get_nate_pann(s, key):
| url = 'http://pann.nate.com/search?searchType=A&q=%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[Nate] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for srch in soup.find_all(s.match_soup_class(['srch_list'])):
rows = srch.fin... | (['thumb_txt'])):
post_date = thumb_txt.span.string.split()
append_google_sheet(s, '직접채워야함', thumb_txt.a['href'],
'no title', post_date[0].replace('.', '-'),
'DCINSIDE')
def get_nate_pann(s, key):
| 65 | 65 | 218 | 10 | 55 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_nate_pann | get_nate_pann | 188 | 208 | 188 | 188 | 39ba6e834e2995db823dc071dd609eb88391686a | bigcode/the-stack | train |
3746a72671497737e204af2e | train | function | def get_naver_blog_page_num(naver_blog_inner_link):
temp_link = naver_blog_inner_link.split('=')
return temp_link[-1]
| def get_naver_blog_page_num(naver_blog_inner_link):
| temp_link = naver_blog_inner_link.split('=')
return temp_link[-1]
| print(js["items"][i]["description"])
title = js["items"][i]["title"]
append_google_sheet(s, user_id, naver_blog_link, title, post_date,
'NAVER', '블로그')
return
def get_naver_blog_page_num(naver_blog_inner_link):
| 64 | 64 | 32 | 13 | 50 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_naver_blog_page_num | get_naver_blog_page_num | 327 | 329 | 327 | 327 | c77bf7347097ac94b227160914a7484ca8155daa | bigcode/the-stack | train |
3009dddf7c13977e0b73b879 | train | function | def get_dcinside(s, key):
url = 'http://search.dcinside.com/post/q/%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[DCINSIDE] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for thumb in soup.find_all(s.match_soup_class(['thumb_list'])):
... | def get_dcinside(s, key):
| url = 'http://search.dcinside.com/post/q/%s' % key
r = get(url)
if r.status_code != codes.ok:
s.logger.error('[DCINSIDE] request error')
return None
soup = BeautifulSoup(r.text, 'html.parser')
for thumb in soup.find_all(s.match_soup_class(['thumb_list'])):
for thumb_txt in t... | [0])
# print('post_date: ', ilbe[1].split()[0])
append_google_sheet(s, ilbe[0], li.a['href'], 'no title',
ilbe[1].split()[0], '일간베스트')
def get_dcinside(s, key):
| 64 | 64 | 154 | 8 | 56 | byung-u/GranXiSearch | blogging/TEST/web.py | Python | get_dcinside | get_dcinside | 172 | 185 | 172 | 172 | e73967e2ecef4c2b093ff13d3b5eb9f4ef76e97a | bigcode/the-stack | train |
a8ac101f4b64cd7640975f13 | train | class | class EMCVMAXUtils(object):
"""Utility class for SMI-S based EMC volume drivers.
This Utility class is for EMC volume drivers based on SMI-S.
It supports VMAX arrays.
"""
SLO = 'storagetype:slo'
WORKLOAD = 'storagetype:workload'
POOL = 'storagetype:pool'
def __init__(self, prtcl):
... | class EMCVMAXUtils(object):
| """Utility class for SMI-S based EMC volume drivers.
This Utility class is for EMC volume drivers based on SMI-S.
It supports VMAX arrays.
"""
SLO = 'storagetype:slo'
WORKLOAD = 'storagetype:workload'
POOL = 'storagetype:pool'
def __init__(self, prtcl):
if not pywbemAvailable:
... | LI, _LW
from cinder.volume import volume_types
LOG = logging.getLogger(__name__)
try:
import pywbem
pywbemAvailable = True
except ImportError:
pywbemAvailable = False
STORAGEGROUPTYPE = 4
POSTGROUPTYPE = 3
CLONE_REPLICATION_TYPE = 10
SYNC_SNAPSHOT_LOCAL = 6
ASYNC_SNAPSHOT_LOCAL = 7
MAX_POOL_LENGTH = 16
... | 256 | 256 | 22,801 | 7 | 248 | aarunsai81/netapp | cinder/volume/drivers/emc/emc_vmax_utils.py | Python | EMCVMAXUtils | EMCVMAXUtils | 67 | 2,830 | 67 | 67 | 2c97ed1e8a94f7b6aca956895f4508a6f5b92d1c | bigcode/the-stack | train |
dfae0d3cb088487814cbe5b6 | train | class | class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
| class Point:
| def __init__(self, x=0, y=0):
self.x = x
self.y = y
| class Point:
| 3 | 64 | 30 | 3 | 0 | ethansaxenian/RosettaDecode | lang/Python/compound-data-type-2.py | Python | Point | Point | 1 | 4 | 1 | 1 | 0a594c33ecbca1ce6c40dddfe3ceccf668a92548 | bigcode/the-stack | train |
64ab94e9e13e05053091364c | train | class | class MicrosoftgraphspecialFolder(Model):
"""specialFolder.
:param name:
:type name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(self, name=None):
super(MicrosoftgraphspecialFolder, self).__init__()
self.name = name
| class MicrosoftgraphspecialFolder(Model):
| """specialFolder.
:param name:
:type name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(self, name=None):
super(MicrosoftgraphspecialFolder, self).__init__()
self.name = name
| # coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... | 57 | 64 | 78 | 7 | 49 | peombwa/Sample-Graph-Python-Client | src/users/models/microsoftgraphspecial_folder.py | Python | MicrosoftgraphspecialFolder | MicrosoftgraphspecialFolder | 11 | 24 | 11 | 11 | 65f0dfbbe4677292d69d58bc844dfd549a2e4eab | bigcode/the-stack | train |
37346973c8b768dbcdc78566 | train | class | class SampleReference:
"""Reference implementation of generic sample manager
For simplicity, built on top of a list of dicts.
This is primarily a reference implementation / for testing but can be
used in production for very small numbers of samples.
"""
def __init__(self, sample_dict=None):
... | class SampleReference:
| """Reference implementation of generic sample manager
For simplicity, built on top of a list of dicts.
This is primarily a reference implementation / for testing but can be
used in production for very small numbers of samples.
"""
def __init__(self, sample_dict=None):
if sample_dict i... | import jsonschema
import json
from doct import Document
from uuid import uuid4
def look_up_schema(schema):
raise NotImplemented()
class SampleReference:
| 33 | 247 | 824 | 4 | 29 | tacaswell/samplez | amostra/basic.py | Python | SampleReference | SampleReference | 11 | 137 | 11 | 11 | b74f9930fd5e83963b88bab1cd1c3eec413c2385 | bigcode/the-stack | train |
8dd7301245eb437f453ca8e5 | train | function | def look_up_schema(schema):
raise NotImplemented()
| def look_up_schema(schema):
| raise NotImplemented()
| import jsonschema
import json
from doct import Document
from uuid import uuid4
def look_up_schema(schema):
| 24 | 64 | 11 | 6 | 17 | tacaswell/samplez | amostra/basic.py | Python | look_up_schema | look_up_schema | 7 | 8 | 7 | 7 | 4efcbfaba4ba264bb55479eb77872bd04174561b | bigcode/the-stack | train |
cc682e50d7c5423312e0358e | train | class | class FaceGANLoader(data.Dataset):
def __init__(self, root_dir=None, json_path=None, aug_transform=None, img_transform=None, configer=None):
super(FaceGANLoader, self).__init__()
self.configer = configer
self.aug_transform=aug_transform
self.img_transform = img_transform
sel... | class FaceGANLoader(data.Dataset):
| def __init__(self, root_dir=None, json_path=None, aug_transform=None, img_transform=None, configer=None):
super(FaceGANLoader, self).__init__()
self.configer = configer
self.aug_transform=aug_transform
self.img_transform = img_transform
self.item_list = self.__read_json(root_... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You(youansheng@gmail.com)
# Single Shot Detector data loader
import os
import torch.utils.data as data
from extensions.tools.parallel import DataContainer
from utils.helpers.json_helper import JsonHelper
from utils.helpers.image_helper import ImageHelper
f... | 85 | 130 | 435 | 7 | 77 | raviv/torchcv | datasets/test/loader/facegan_loader.py | Python | FaceGANLoader | FaceGANLoader | 16 | 65 | 16 | 17 | f611755b9176d3239129e991f95ab8cabb797223 | bigcode/the-stack | train |
21bafbd75ddaab261eeb4593 | train | function | def test_transition_matrix():
# k_regimes = 2
endog = np.ones(10)
mod = markov_switching.MarkovSwitching(endog, k_regimes=2)
params = np.r_[0., 0., 1.]
transition_matrix = np.zeros((2, 2, 1))
transition_matrix[1, :] = 1.
assert_allclose(mod.regime_transition_matrix(params), transition_matrix... | def test_transition_matrix():
# k_regimes = 2
| endog = np.ones(10)
mod = markov_switching.MarkovSwitching(endog, k_regimes=2)
params = np.r_[0., 0., 1.]
transition_matrix = np.zeros((2, 2, 1))
transition_matrix[1, :] = 1.
assert_allclose(mod.regime_transition_matrix(params), transition_matrix)
# k_regimes = 3
endog = np.ones(10)
... | _regimes=1)
# Invalid: multiple endog columns
endog = np.ones((10, 2))
assert_raises(ValueError, markov_switching.MarkovSwitching, endog,
k_regimes=2)
def test_init_exog_tvtp():
endog = np.ones(10)
exog_tvtp = np.c_[np.ones((10, 1)), (np.arange(10) + 1)[:, np.newaxis]]
mod =... | 256 | 256 | 963 | 14 | 242 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_transition_matrix | test_transition_matrix | 109 | 178 | 109 | 110 | 7708ec709bdfd221350865ad13e60175016ad422 | bigcode/the-stack | train |
bdc59adc74df5e3a9e1a4b51 | train | function | def test_params():
def check_transtion_2(params):
assert_equal(params['regime_transition'], np.s_[0:2])
assert_equal(params[0, 'regime_transition'], [0])
assert_equal(params[1, 'regime_transition'], [1])
assert_equal(params['regime_transition', 0], [0])
assert_equal(params['r... | def test_params():
| def check_transtion_2(params):
assert_equal(params['regime_transition'], np.s_[0:2])
assert_equal(params[0, 'regime_transition'], [0])
assert_equal(params[1, 'regime_transition'], [1])
assert_equal(params['regime_transition', 0], [0])
assert_equal(params['regime_transition', ... | """
General tests for Markov switching models
Author: Chad Fulton
License: BSD-3
"""
import numpy as np
from numpy.testing import assert_equal, assert_allclose, assert_raises
import pandas as pd
from statsmodels.tools.numdiff import approx_fprime_cs
from statsmodels.tsa.regime_switching import markov_switching
def t... | 77 | 194 | 649 | 4 | 72 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_params | test_params | 16 | 66 | 16 | 16 | bb279f281d70f06abe7bf854880b22a366f81884 | bigcode/the-stack | train |
679f13599a2f50b4cf7cc1de | train | function | def test_init_exog_tvtp():
endog = np.ones(10)
exog_tvtp = np.c_[np.ones((10, 1)), (np.arange(10) + 1)[:, np.newaxis]]
mod = markov_switching.MarkovSwitching(endog, k_regimes=2,
exog_tvtp=exog_tvtp)
assert_equal(mod.tvtp, True)
assert_equal(mod.k_tvtp, 2)
... | def test_init_exog_tvtp():
| endog = np.ones(10)
exog_tvtp = np.c_[np.ones((10, 1)), (np.arange(10) + 1)[:, np.newaxis]]
mod = markov_switching.MarkovSwitching(endog, k_regimes=2,
exog_tvtp=exog_tvtp)
assert_equal(mod.tvtp, True)
assert_equal(mod.k_tvtp, 2)
# Invalid exog_tvtp (to... | ,
k_regimes=1)
# Invalid: multiple endog columns
endog = np.ones((10, 2))
assert_raises(ValueError, markov_switching.MarkovSwitching, endog,
k_regimes=2)
def test_init_exog_tvtp():
| 64 | 64 | 190 | 9 | 55 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_init_exog_tvtp | test_init_exog_tvtp | 95 | 106 | 95 | 95 | e369b28b18b8da54a143b212baa853c8a9140878 | bigcode/the-stack | train |
da62294693dfc10ab1c35f53 | train | function | def test_partials_logistic():
# Here we compare to analytic derivatives and to finite-difference
# approximations
logistic = markov_switching._logistic
partials_logistic = markov_switching._partials_logistic
# For a number, logistic(x) = np.exp(x) / (1 + np.exp(x))
# Then d/dx = logistix(x) - l... | def test_partials_logistic():
# Here we compare to analytic derivatives and to finite-difference
# approximations
| logistic = markov_switching._logistic
partials_logistic = markov_switching._partials_logistic
# For a number, logistic(x) = np.exp(x) / (1 + np.exp(x))
# Then d/dx = logistix(x) - logistic(x)**2
cases = [0, 10., -4]
for x in cases:
assert_allclose(partials_logistic(x), logistic(x) - log... | 0, 1 and t=0
case = [[0], [1.]]
actual = logistic(case)
desired = [np.exp(i) / (1 + np.sum(np.exp(case))) for i in case]
assert_allclose(actual, desired)
# Here, np.array(case) is 1x2, so it is interpreted as i=0 and t=0, 1
case = [[0, 1.]]
actual = logistic(case)
desired = np.exp(case)... | 255 | 256 | 865 | 26 | 229 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_partials_logistic | test_partials_logistic | 254 | 317 | 254 | 256 | cb495f46533bb03e46e87764c87d46221e416a97 | bigcode/the-stack | train |
4c0c49ba89b26c2629d1d524 | train | function | def test_init_endog():
index = pd.date_range(start='1950-01-01', periods=10, freq='D')
endog = [
np.ones(10), pd.Series(np.ones(10), index=index), np.ones((10, 1)),
pd.DataFrame(np.ones((10, 1)), index=index)
]
for _endog in endog:
mod = markov_switching.MarkovSwitching(_endog, k... | def test_init_endog():
| index = pd.date_range(start='1950-01-01', periods=10, freq='D')
endog = [
np.ones(10), pd.Series(np.ones(10), index=index), np.ones((10, 1)),
pd.DataFrame(np.ones((10, 1)), index=index)
]
for _endog in endog:
mod = markov_switching.MarkovSwitching(_endog, k_regimes=2)
ass... | selection
assert_raises(IndexError, params.__getitem__, None)
assert_raises(IndexError, params.__getitem__, (0, 0))
assert_raises(IndexError, params.__getitem__, ('exog', 'exog'))
assert_raises(IndexError, params.__getitem__, ('exog', 0, 1))
def test_init_endog():
| 78 | 78 | 263 | 6 | 72 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_init_endog | test_init_endog | 69 | 92 | 69 | 69 | d8e4e50f637e9b98ba7eacad6068a1ddc65df2b7 | bigcode/the-stack | train |
ee24501b27add17d757ab121 | train | function | def test_logistic():
logistic = markov_switching._logistic
# For a number, logistic(x) = np.exp(x) / (1 + np.exp(x))
cases = [0, 10., -4]
for x in cases:
# Have to use allclose b/c logistic() actually uses logsumexp, so
# they're not equal
assert_allclose(logistic(x), np.exp(x) ... | def test_logistic():
| logistic = markov_switching._logistic
# For a number, logistic(x) = np.exp(x) / (1 + np.exp(x))
cases = [0, 10., -4]
for x in cases:
# Have to use allclose b/c logistic() actually uses logsumexp, so
# they're not equal
assert_allclose(logistic(x), np.exp(x) / (1 + np.exp(x)))
... | elements)
assert_raises(ValueError, mod.initialize_known, [0.2, 0.2, 0.6])
# Invalid known initial probabilities (does not sum to 1)
assert_raises(ValueError, mod.initialize_known, [0.2, 0.2])
# Valid steady-state probabilities
mod.initialize_steady_state()
assert_allclose(mod.initial_probabi... | 165 | 165 | 553 | 5 | 160 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_logistic | test_logistic | 206 | 251 | 206 | 206 | 0e4acf0b14ead615c7962f046ad0cc731cbef690 | bigcode/the-stack | train |
a2a3dca74f97579794a7e0b7 | train | function | def test_initial_probabilities():
endog = np.ones(10)
mod = markov_switching.MarkovSwitching(endog, k_regimes=2)
params = np.r_[0.5, 0.5, 1.]
# Valid known initial probabilities
mod.initialize_known([0.2, 0.8])
assert_allclose(mod.initial_probabilities(params), [0.2, 0.8])
# Invalid known ... | def test_initial_probabilities():
| endog = np.ones(10)
mod = markov_switching.MarkovSwitching(endog, k_regimes=2)
params = np.r_[0.5, 0.5, 1.]
# Valid known initial probabilities
mod.initialize_known([0.2, 0.8])
assert_allclose(mod.initial_probabilities(params), [0.2, 0.8])
# Invalid known initial probabilities (too many el... | (tmp, axis=0))
transition_matrix[2, 0, :] = (
1 - np.sum(transition_matrix[:2, 0, :], axis=0))
assert_allclose(mod.regime_transition_matrix(params)[:, 0, :],
transition_matrix[:, 0, :], atol=1e-10)
def test_initial_probabilities():
| 78 | 78 | 263 | 6 | 72 | EkremBayar/bayar | venv/Lib/site-packages/statsmodels/tsa/regime_switching/tests/test_markov_switching.py | Python | test_initial_probabilities | test_initial_probabilities | 181 | 203 | 181 | 181 | e1331030d1c7253f6f6ceee99fc7744917ce1c32 | bigcode/the-stack | train |
61be9f5d86bf817226979aa8 | train | class | class VariationalSamplingAlgorithm(SamplingAlgorithm):
"""
The base class for the sampling algorithms that are applied to the models with variational approximation.
:param model: the definition of the probabilistic model
:type model: Model
:param posterior: the definition of the variational posteri... | class VariationalSamplingAlgorithm(SamplingAlgorithm):
| """
The base class for the sampling algorithms that are applied to the models with variational approximation.
:param model: the definition of the probabilistic model
:type model: Model
:param posterior: the definition of the variational posterior of the probabilistic model
:param posterior: Pos... | model, posterior, observed):
super(VariationalInference, self).__init__(
model=model, observed=observed, extra_graphs=[posterior])
@property
def posterior(self):
"""
return the variational posterior.
"""
return self._extra_graphs[0]
class VariationalSampling... | 72 | 72 | 241 | 9 | 63 | tdiethe/MXFusion | mxfusion/inference/variational.py | Python | VariationalSamplingAlgorithm | VariationalSamplingAlgorithm | 30 | 57 | 30 | 30 | dfcaf5d25833f99a84ad2c9dfdcf54342c45f89c | bigcode/the-stack | train |
7fde7365fece7a8c997012d1 | train | class | class VariationalInference(InferenceAlgorithm):
"""
The class of the Stochastic Variational Inference (SVI) algorithm.
:param num_samples: the number of samples used in estimating the variational lower bound
:type num_samples: int
:param model: the definition of the probabilistic model
:type mo... | class VariationalInference(InferenceAlgorithm):
| """
The class of the Stochastic Variational Inference (SVI) algorithm.
:param num_samples: the number of samples used in estimating the variational lower bound
:type num_samples: int
:param model: the definition of the probabilistic model
:type model: Model
:param posterior: the definition ... | from .inference_alg import InferenceAlgorithm, SamplingAlgorithm
class VariationalInference(InferenceAlgorithm):
| 21 | 64 | 191 | 8 | 12 | tdiethe/MXFusion | mxfusion/inference/variational.py | Python | VariationalInference | VariationalInference | 4 | 27 | 4 | 4 | 0f7ecc37f37cf3804d6c67a0d3a482332d5d68b6 | bigcode/the-stack | train |
c5c85087c27303bee3193483 | train | class | class StochasticVariationalInference(VariationalInference):
"""
The class of the Stochastic Variational Inference (SVI) algorithm.
:param num_samples: the number of samples used in estimating the variational lower bound
:type num_samples: int
:param model: the definition of the probabilistic model
... | class StochasticVariationalInference(VariationalInference):
| """
The class of the Stochastic Variational Inference (SVI) algorithm.
:param num_samples: the number of samples used in estimating the variational lower bound
:type num_samples: int
:param model: the definition of the probabilistic model
:type model: Model
:param posterior: the definition ... | UUID]
"""
def __init__(self, model, posterior, observed, num_samples=1,
target_variables=None):
super(VariationalSamplingAlgorithm, self).__init__(
model=model, observed=observed, num_samples=num_samples,
target_variables=target_variables, extra_graphs=[posterio... | 108 | 108 | 362 | 11 | 97 | tdiethe/MXFusion | mxfusion/inference/variational.py | Python | StochasticVariationalInference | StochasticVariationalInference | 60 | 95 | 60 | 60 | 7ccf21ab2f9ec3060874109893e41e042a98d454 | bigcode/the-stack | train |
9ee7d7b3eec094d05aa02a04 | train | function | def time_elapsed(quit_date, use_days=False):
date = datetime_from_date(quit_date)
delta = today() - date
years = delta.days / 365
months = (delta.days % 365) / 30
days = delta.days % 365 % 30
if use_days:
return '%d %s' % (delta.days, day_string(delta.days))
if years >= 1 and del... | def time_elapsed(quit_date, use_days=False):
| date = datetime_from_date(quit_date)
delta = today() - date
years = delta.days / 365
months = (delta.days % 365) / 30
days = delta.days % 365 % 30
if use_days:
return '%d %s' % (delta.days, day_string(delta.days))
if years >= 1 and delta.days % 365 == 0:
return '%d %s' % ... | return unit_string('year', quantity)
def day_string(quantity):
return unit_string('day', quantity)
def month_from_date(date):
return datetime_from_date(date).strftime('%B')
def datetime_from_date(date):
return datetime.datetime.strptime(date, '%m/%d/%Y')
def today():
return datetime.datetime.now... | 98 | 98 | 329 | 11 | 87 | Donohue/nonsmoker | src/index.py | Python | time_elapsed | time_elapsed | 201 | 223 | 201 | 201 | 6d1974af23de9cf7dc8e491a7b78f101d972ec83 | bigcode/the-stack | train |
ff2574d1ae77c0b2e7e16c21 | train | function | def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('nonsmoker')
user_id = ses... | def on_intent(intent_request, session):
| """ Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('nonsmoker')
user_id = session['user']['userId']
intent = inte... | Id=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
user_id = session['user']['userId']
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('nonsmoker')
return get_time_intent(table, user_id)
def on_intent(intent_requ... | 86 | 86 | 289 | 9 | 77 | Donohue/nonsmoker | src/index.py | Python | on_intent | on_intent | 41 | 70 | 41 | 41 | 2951f33d8b0a3ec6abf79999cc73dd4b5998e991 | bigcode/the-stack | train |
c6c32205246e5251a77d2649 | train | function | def build_speechlet_response(output, card_title=None, card_content=None,
reprompt='', should_end_session=True):
response = {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'reprompt': {
'outputSpeech': {
... | def build_speechlet_response(output, card_title=None, card_content=None,
reprompt='', should_end_session=True):
| response = {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt
}
},
'shouldEndSession': should_end_session
}
... | return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(output, card_title=None, card_content=None,
reprompt='', should_end_session=True):
| 64 | 64 | 137 | 25 | 39 | Donohue/nonsmoker | src/index.py | Python | build_speechlet_response | build_speechlet_response | 236 | 259 | 236 | 237 | 23faa0586948afa21fbf92ce1121a747c4508220 | bigcode/the-stack | train |
9bc234b3dda0e1e771a6468a | train | function | def on_session_ended(session_ended_request, session):
print("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
| def on_session_ended(session_ended_request, session):
| print("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
| event['session'])
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
def on_session_ended(session_ended_request, session):
| 64 | 64 | 43 | 12 | 52 | Donohue/nonsmoker | src/index.py | Python | on_session_ended | on_session_ended | 31 | 33 | 31 | 31 | b94dc9af953fa7d46f3af8e310cc622a6b22a57a | bigcode/the-stack | train |
4767752b10c0988b52547ab0 | train | function | def random_encouragement():
encouragement = [
'Good work!',
'Nice job!',
'Keep it up!',
'Congrats!'
]
return random.choice(encouragement)
| def random_encouragement():
| encouragement = [
'Good work!',
'Nice job!',
'Keep it up!',
'Congrats!'
]
return random.choice(encouragement)
| -bye")
)
def help_response():
return build_response(
{},
build_speechlet_response(
"You can ask how long it has been since you stopped smoking or set your stop date. How can I help?",
should_end_session=False
)
)
def random_encouragement():
| 64 | 64 | 40 | 6 | 58 | Donohue/nonsmoker | src/index.py | Python | random_encouragement | random_encouragement | 165 | 172 | 165 | 165 | eabb98aa3babe5b8d31ce861a02993a90ee664a6 | bigcode/the-stack | train |
6b8a6099cae960430fa13191 | train | function | def on_launch(launch_request, session):
user_id = session['user']['userId']
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('nonsmoker')
return get_time_intent(table, user_id)
| def on_launch(launch_request, session):
| user_id = session['user']['userId']
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('nonsmoker')
return get_time_intent(table, user_id)
| + ", sessionId=" + session['sessionId'])
def on_session_ended(session_ended_request, session):
print("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
| 64 | 64 | 54 | 9 | 55 | Donohue/nonsmoker | src/index.py | Python | on_launch | on_launch | 35 | 39 | 35 | 35 | 32c5b03dbdb40e0f97476b082b172d53e2030124 | bigcode/the-stack | train |
2af843f618e953d7ce103fdd | train | function | def unit_string(string, quantity):
return string if quantity == 1 else string + 's'
| def unit_string(string, quantity):
| return string if quantity == 1 else string + 's'
| journey of a thousand miles begins with a single step. Congratulations on becoming a nonsmoker."
else:
return "It has been %s since you stopped smoking. %s" % (time_elapsed(quit_date, use_days=use_days), random_encouragement())
def unit_string(string, quantity):
| 64 | 64 | 21 | 7 | 57 | Donohue/nonsmoker | src/index.py | Python | unit_string | unit_string | 180 | 181 | 180 | 180 | d5daacfdd797a6fb609d85a380c32473523afbd2 | bigcode/the-stack | train |
23a1d10ee611c53815879ada | train | function | def datetime_from_date(date):
return datetime.datetime.strptime(date, '%m/%d/%Y')
| def datetime_from_date(date):
| return datetime.datetime.strptime(date, '%m/%d/%Y')
| month_string(quantity):
return unit_string('month', quantity)
def year_string(quantity):
return unit_string('year', quantity)
def day_string(quantity):
return unit_string('day', quantity)
def month_from_date(date):
return datetime_from_date(date).strftime('%B')
def datetime_from_date(date):
| 64 | 64 | 20 | 6 | 58 | Donohue/nonsmoker | src/index.py | Python | datetime_from_date | datetime_from_date | 195 | 196 | 195 | 195 | 12aed855e097e09fade62c35f324f941da89fb42 | bigcode/the-stack | train |
49d81650905a9ac629ea945a | train | function | def bye_response():
return build_response(
{},
build_speechlet_response("Good-bye")
)
| def bye_response():
| return build_response(
{},
build_speechlet_response("Good-bye")
)
| return build_response(
{},
build_speechlet_response(
"Your stop date has been set to %s %s, %s. %s" % (month_from_date(quit_date), day_date_string(day), year, time_response(quit_date))
)
)
def bye_response():
| 64 | 64 | 24 | 4 | 60 | Donohue/nonsmoker | src/index.py | Python | bye_response | bye_response | 150 | 154 | 150 | 150 | 9dafa8a08a7463588b786206b4e662e1f6c72060 | bigcode/the-stack | train |
ca02f5d191ad65e0e0c9afaf | train | function | def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
| def build_response(session_attributes, speechlet_response):
| return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
| 'shouldEndSession': should_end_session
}
if card_title and card_content:
response['card'] = {
'type': 'Simple',
'title': card_title,
'content': card_content
}
return response
def build_response(session_attributes, speechlet_response):
| 64 | 64 | 40 | 10 | 53 | Donohue/nonsmoker | src/index.py | Python | build_response | build_response | 261 | 266 | 261 | 261 | a6cc9984027a298d4f07eaa99f2d0cb443eada25 | bigcode/the-stack | train |
f584b306bdc8b9e61e5372e4 | train | function | def time_response(quit_date, use_days=False):
if datetime_from_date(quit_date) == today():
return "Today is the first day you stopped smoking. Lao Tzu once said, the journey of a thousand miles begins with a single step. Congratulations on becoming a nonsmoker."
else:
return "It has been %s sinc... | def time_response(quit_date, use_days=False):
| if datetime_from_date(quit_date) == today():
return "Today is the first day you stopped smoking. Lao Tzu once said, the journey of a thousand miles begins with a single step. Congratulations on becoming a nonsmoker."
else:
return "It has been %s since you stopped smoking. %s" % (time_elapsed(qui... | I help?",
should_end_session=False
)
)
def random_encouragement():
encouragement = [
'Good work!',
'Nice job!',
'Keep it up!',
'Congrats!'
]
return random.choice(encouragement)
def time_response(quit_date, use_days=False):
| 64 | 64 | 99 | 11 | 53 | Donohue/nonsmoker | src/index.py | Python | time_response | time_response | 174 | 178 | 174 | 174 | 74ff9e5a1d9ee669485626ad3de845047b38efbe | bigcode/the-stack | train |
04efd3a801f95af6358be18b | train | function | def year_string(quantity):
return unit_string('year', quantity)
| def year_string(quantity):
| return unit_string('year', quantity)
| smoking. %s" % (time_elapsed(quit_date, use_days=use_days), random_encouragement())
def unit_string(string, quantity):
return string if quantity == 1 else string + 's'
def month_string(quantity):
return unit_string('month', quantity)
def year_string(quantity):
| 64 | 64 | 14 | 5 | 59 | Donohue/nonsmoker | src/index.py | Python | year_string | year_string | 186 | 187 | 186 | 186 | 1645e3b86e24a16bb6faa37c0e572d666d036f92 | bigcode/the-stack | train |
aa5388a985deaeda80fffdd9 | train | function | def day_date_string(day):
return '%d%s' % (day, day_suffix(day))
| def day_date_string(day):
| return '%d%s' % (day, day_suffix(day))
| , month_string(months))
elif months >= 1:
return '%d %s and %d %s' % (months, month_string(months), days, day_string(days))
else:
return '%d %s' % (days, day_string(days))
def day_date_string(day):
| 64 | 64 | 20 | 6 | 58 | Donohue/nonsmoker | src/index.py | Python | day_date_string | day_date_string | 225 | 226 | 225 | 225 | e53346f1d96172fd61b869f74504f0653a39430b | bigcode/the-stack | train |
5a80266c23af51e16d456a01 | train | function | def today():
return datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
| def today():
| return datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
| ):
return unit_string('year', quantity)
def day_string(quantity):
return unit_string('day', quantity)
def month_from_date(date):
return datetime_from_date(date).strftime('%B')
def datetime_from_date(date):
return datetime.datetime.strptime(date, '%m/%d/%Y')
def today():
| 64 | 64 | 27 | 3 | 61 | Donohue/nonsmoker | src/index.py | Python | today | today | 198 | 199 | 198 | 198 | a0e9ec7797a33b59caecf64b6cd2f4f0fe869f55 | bigcode/the-stack | train |
a1e64021cb4814ef65c65059 | train | function | def help_response():
return build_response(
{},
build_speechlet_response(
"You can ask how long it has been since you stopped smoking or set your stop date. How can I help?",
should_end_session=False
)
)
| def help_response():
| return build_response(
{},
build_speechlet_response(
"You can ask how long it has been since you stopped smoking or set your stop date. How can I help?",
should_end_session=False
)
)
| s %s, %s. %s" % (month_from_date(quit_date), day_date_string(day), year, time_response(quit_date))
)
)
def bye_response():
return build_response(
{},
build_speechlet_response("Good-bye")
)
def help_response():
| 64 | 64 | 53 | 4 | 60 | Donohue/nonsmoker | src/index.py | Python | help_response | help_response | 156 | 163 | 156 | 156 | 61c7a7b9140bab3faca7eb0110917cae7ad1e515 | bigcode/the-stack | train |
832dd86f07421cefd66e320a | train | function | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
#... | def lambda_handler(event, context):
| """ Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
#if (event['session']['application'][... | from __future__ import print_function
import boto3
import datetime
import dateutil.parser
import random
def lambda_handler(event, context):
| 30 | 64 | 185 | 7 | 22 | Donohue/nonsmoker | src/index.py | Python | lambda_handler | lambda_handler | 7 | 23 | 7 | 7 | 92e22ec633a76be11ea65f74ef2c197b4fb633cb | bigcode/the-stack | train |
61311e4d9c5d88d42bf7c5ed | train | function | def set_year_intent(table, user_id, session, intent):
try:
month = session['attributes']['month']
day = session['attributes']['day']
except KeyError:
return set_time_intent()
year = intent['slots']['year']['value']
quit_date = '%s/%s/%s' % (month, day, year)
if datetime_from... | def set_year_intent(table, user_id, session, intent):
| try:
month = session['attributes']['month']
day = session['attributes']['day']
except KeyError:
return set_time_intent()
year = intent['slots']['year']['value']
quit_date = '%s/%s/%s' % (month, day, year)
if datetime_from_date(quit_date) > today():
return build_respo... | .month, 'day': date.day},
build_speechlet_response(
"Great, you stopped smoking on %s %s. Which year did you stop smoking?" % (date.strftime('%B'), day_date_string(date.day)),
should_end_session=False
)
)
def set_year_intent(table, user_id, session, intent):
| 72 | 72 | 242 | 14 | 58 | Donohue/nonsmoker | src/index.py | Python | set_year_intent | set_year_intent | 120 | 148 | 120 | 120 | dd6480caca2cccf6861330714f3fd9d75b32baa7 | bigcode/the-stack | train |
5090ada307909d536ec850de | train | function | def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
| def on_session_started(session_started_request, session):
| """ Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
| elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_session_ended(event['request'], event['session'])
def on_session_started(session_started_request, session):
| 63 | 64 | 47 | 10 | 53 | Donohue/nonsmoker | src/index.py | Python | on_session_started | on_session_started | 26 | 29 | 26 | 26 | 4b7b206b8e9ab0d8a7eb96adff50f43af5ea8630 | bigcode/the-stack | train |
9dd4dc8f97b0248b8afa2e39 | train | function | def set_time_intent():
return build_response(
{},
build_speechlet_response(
"What month and day did you stop smoking?",
should_end_session=False
)
)
| def set_time_intent():
| return build_response(
{},
build_speechlet_response(
"What month and day did you stop smoking?",
should_end_session=False
)
)
| _id}
)
try:
quit_date = response['Item']['quit_date']
except KeyError:
return set_time_intent()
return build_response(
{},
build_speechlet_response(time_response(quit_date, use_days=use_days))
)
def set_time_intent():
| 64 | 64 | 41 | 6 | 58 | Donohue/nonsmoker | src/index.py | Python | set_time_intent | set_time_intent | 89 | 96 | 89 | 89 | 613e2e30868c2aa866923e652d7ce5a0860ed9a1 | bigcode/the-stack | train |
7c1d05819d605efc4fc555f4 | train | function | def day_string(quantity):
return unit_string('day', quantity)
| def day_string(quantity):
| return unit_string('day', quantity)
| _days=use_days), random_encouragement())
def unit_string(string, quantity):
return string if quantity == 1 else string + 's'
def month_string(quantity):
return unit_string('month', quantity)
def year_string(quantity):
return unit_string('year', quantity)
def day_string(quantity):
| 64 | 64 | 14 | 5 | 59 | Donohue/nonsmoker | src/index.py | Python | day_string | day_string | 189 | 190 | 189 | 189 | 15c6ae96dd8de7db2ef99d557fc7140bc7599802 | bigcode/the-stack | train |
298a1463475ac3c84e81b547 | train | function | def day_suffix(day):
if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
| def day_suffix(day):
| if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
| and %d %s' % (months, month_string(months), days, day_string(days))
else:
return '%d %s' % (days, day_string(days))
def day_date_string(day):
return '%d%s' % (day, day_suffix(day))
def day_suffix(day):
| 64 | 64 | 50 | 5 | 59 | Donohue/nonsmoker | src/index.py | Python | day_suffix | day_suffix | 228 | 232 | 228 | 228 | 606ad400000bcfd6062e8205c1123d2c9105c271 | bigcode/the-stack | train |
4f59379da917f0f7eab9bb14 | train | function | def month_from_date(date):
return datetime_from_date(date).strftime('%B')
| def month_from_date(date):
| return datetime_from_date(date).strftime('%B')
| quantity):
return string if quantity == 1 else string + 's'
def month_string(quantity):
return unit_string('month', quantity)
def year_string(quantity):
return unit_string('year', quantity)
def day_string(quantity):
return unit_string('day', quantity)
def month_from_date(date):
| 64 | 64 | 17 | 6 | 58 | Donohue/nonsmoker | src/index.py | Python | month_from_date | month_from_date | 192 | 193 | 192 | 192 | a5f2bc08f453260e39af525a63645ceaa4adc944 | bigcode/the-stack | train |
bcf86f401b233d08fd8bdec7 | train | function | def month_string(quantity):
return unit_string('month', quantity)
| def month_string(quantity):
| return unit_string('month', quantity)
| else:
return "It has been %s since you stopped smoking. %s" % (time_elapsed(quit_date, use_days=use_days), random_encouragement())
def unit_string(string, quantity):
return string if quantity == 1 else string + 's'
def month_string(quantity):
| 64 | 64 | 14 | 5 | 59 | Donohue/nonsmoker | src/index.py | Python | month_string | month_string | 183 | 184 | 183 | 183 | d71a2dbb4072cfd1c42f39bea63f50362ce9a671 | bigcode/the-stack | train |
e6bd970d7aac514664b1a623 | train | function | def set_day_month_intent(table, user_id, intent):
day_month = intent['slots']['day_month']['value']
try:
date = dateutil.parser.parse(day_month)
except Exception as e:
print("There was an error parsing %s: %s" % (day_month, str(e)))
return build_response(
{},
... | def set_day_month_intent(table, user_id, intent):
| day_month = intent['slots']['day_month']['value']
try:
date = dateutil.parser.parse(day_month)
except Exception as e:
print("There was an error parsing %s: %s" % (day_month, str(e)))
return build_response(
{},
build_speechlet_response(
"Sorry I... | _date, use_days=use_days))
)
def set_time_intent():
return build_response(
{},
build_speechlet_response(
"What month and day did you stop smoking?",
should_end_session=False
)
)
def set_day_month_intent(table, user_id, intent):
| 64 | 64 | 176 | 13 | 51 | Donohue/nonsmoker | src/index.py | Python | set_day_month_intent | set_day_month_intent | 98 | 118 | 98 | 98 | 9b05cd9d4bf697b13690125ada348fc83d2cc927 | bigcode/the-stack | train |
24d2aa2deab41427e6172995 | train | function | def get_time_intent(table, user_id, use_days=False):
response = table.get_item(
Key={"user_id": user_id}
)
try:
quit_date = response['Item']['quit_date']
except KeyError:
return set_time_intent()
return build_response(
{},
build_speechlet_response(time_r... | def get_time_intent(table, user_id, use_days=False):
| response = table.get_item(
Key={"user_id": user_id}
)
try:
quit_date = response['Item']['quit_date']
except KeyError:
return set_time_intent()
return build_response(
{},
build_speechlet_response(time_response(quit_date, use_days=use_days))
)
| ON.CancelIntent" or intent_name == "AMAZON.StopIntent":
return bye_response()
else:
raise ValueError("Invalid intent: %s" % intent_name)
# --------------- Functions that control the skill's behavior ------------------
def get_time_intent(table, user_id, use_days=False):
| 64 | 64 | 86 | 14 | 50 | Donohue/nonsmoker | src/index.py | Python | get_time_intent | get_time_intent | 74 | 87 | 74 | 74 | c3bd15f78fe7c90325f6b0a7521c0c4105c6ef16 | bigcode/the-stack | train |
afbe483366f79a1bcaae127b | train | class | @pytest.mark.enable_bookmark_creation
class RegistrationWithChildNodesRetractionModelTestCase(OsfTestCase):
def setUp(self):
super(RegistrationWithChildNodesRetractionModelTestCase, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(... | @pytest.mark.enable_bookmark_creation
class RegistrationWithChildNodesRetractionModelTestCase(OsfTestCase):
| def setUp(self):
super(RegistrationWithChildNodesRetractionModelTestCase, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(is_public=True, creator=self.user)
self.component = NodeFactory(
creator=self.user,
... | (self.user, rejection_token)
# Logs: Created, registered, retraction initiated, retraction cancelled
assert_equal(self.registration.registered_from.logs.count(), initial_project_logs + 2)
def test__on_complete_makes_project_and_components_public(self):
project_admin = UserFactory()
... | 256 | 256 | 1,324 | 23 | 233 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | RegistrationWithChildNodesRetractionModelTestCase | RegistrationWithChildNodesRetractionModelTestCase | 403 | 561 | 403 | 404 | 911b93e5733d4862e41d986ab85d035c8d74b273 | bigcode/the-stack | train |
28a2cb6a0ee6ebaee1df9214 | train | class | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionShareHook(OsfTestCase):
def setUp(self):
super(RegistrationRetractionShareHook, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(is_public=True, creator=self.user)
... | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionShareHook(OsfTestCase):
| def setUp(self):
super(RegistrationRetractionShareHook, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(is_public=True, creator=self.user)
self.registration = RegistrationFactory(project=self.project, is_public=True)
... | (node.embargo_end_date)
# Approve parent registration's retraction
approval_token = self.registration.retraction.approval_state[self.user._id]['approval_token']
self.registration.retraction.approve_retraction(self.user, approval_token)
assert_true(self.registration.is_retracted)
... | 120 | 120 | 400 | 19 | 100 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | RegistrationRetractionShareHook | RegistrationRetractionShareHook | 563 | 601 | 563 | 564 | f8c0e83c92e61c56c7f35dd9a89fa30c60e95603 | bigcode/the-stack | train |
5da0767044d8af9bcfa19b7b | train | class | @pytest.mark.enable_bookmark_creation
class ComponentRegistrationRetractionViewsTestCase(OsfTestCase):
def setUp(self):
super(ComponentRegistrationRetractionViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(is_public=T... | @pytest.mark.enable_bookmark_creation
class ComponentRegistrationRetractionViewsTestCase(OsfTestCase):
| def setUp(self):
super(ComponentRegistrationRetractionViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.auth = self.user.auth
self.project = ProjectFactory(is_public=True, creator=self.user)
self.component = NodeFactory(
is_public=True,
c... | _equal(res.status_code, http_status.HTTP_400_BAD_REQUEST)
def test_GET_disapprove_with_valid_token_returns_redirect(self):
res = self.app.get(
self.registration.web_url_for('token_action', token=self.rejection_token),
auth=self.user.auth,
)
self.registration.retracti... | 129 | 129 | 432 | 21 | 108 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | ComponentRegistrationRetractionViewsTestCase | ComponentRegistrationRetractionViewsTestCase | 716 | 768 | 716 | 717 | fe0e79dfa943ef7f1c17a14daa7b67404e606af0 | bigcode/the-stack | train |
2d8a003a5c7e24f402e32210 | train | class | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionApprovalDisapprovalViewsTestCase(OsfTestCase):
def setUp(self):
super(RegistrationRetractionApprovalDisapprovalViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.registered_from = ProjectFactory(is_public=True, c... | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionApprovalDisapprovalViewsTestCase(OsfTestCase):
| def setUp(self):
super(RegistrationRetractionApprovalDisapprovalViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.registered_from = ProjectFactory(is_public=True, creator=self.user)
self.registration = RegistrationFactory(is_public=True, project=self.registered_from)
... | _share):
# Initiate retraction for parent registration
self.registration.retract_registration(self.user)
self.registration.save()
# Approve parent registration's retraction
approval_token = self.registration.retraction.approval_state[self.user._id]['approval_token']
self... | 256 | 256 | 985 | 23 | 232 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | RegistrationRetractionApprovalDisapprovalViewsTestCase | RegistrationRetractionApprovalDisapprovalViewsTestCase | 604 | 713 | 604 | 605 | 3c88759a72ffc182222622749c2d521bfee3d408 | bigcode/the-stack | train |
502bf76375780fd9bc1fa686 | train | class | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionModelsTestCase(OsfTestCase):
def setUp(self):
super(RegistrationRetractionModelsTestCase, self).setUp()
self.user = UserFactory()
self.registration = RegistrationFactory(creator=self.user, is_public=True)
self.valid_j... | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionModelsTestCase(OsfTestCase):
| def setUp(self):
super(RegistrationRetractionModelsTestCase, self).setUp()
self.user = UserFactory()
self.registration = RegistrationFactory(creator=self.user, is_public=True)
self.valid_justification = fake.sentence()
self.invalid_justification = fake.text(max_nb_chars=3000... | """Tests related to retraction of public registrations"""
import datetime
from rest_framework import status as http_status
import mock
import pytest
from django.utils import timezone
from django.db import DataError
from nose.tools import * # noqa
from framework.auth import Auth
from framework.exceptions import Perm... | 187 | 256 | 3,495 | 20 | 166 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | RegistrationRetractionModelsTestCase | RegistrationRetractionModelsTestCase | 29 | 400 | 29 | 30 | c332e5701c35e55d76bb0a373ee63dfe5b5858df | bigcode/the-stack | train |
4b569e9b1f5e9f1406d98ced | train | class | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionViewsTestCase(OsfTestCase):
def setUp(self):
super(RegistrationRetractionViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.registered_from = ProjectFactory(creator=self.user, is_public=True)
self.registr... | @pytest.mark.enable_bookmark_creation
class RegistrationRetractionViewsTestCase(OsfTestCase):
| def setUp(self):
super(RegistrationRetractionViewsTestCase, self).setUp()
self.user = AuthUserFactory()
self.registered_from = ProjectFactory(creator=self.user, is_public=True)
self.registration = RegistrationFactory(project=self.registered_from, is_public=True)
self.retrac... | self.subproject_registration = list(self.registration._nodes.order_by('created'))[1]
self.subproject_component_registration = self.subproject_registration._nodes.order_by('created').first()
def test_POST_retraction_to_component_returns_HTTPError_BAD_REQUEST(self):
res = self.app.post_json(
... | 256 | 256 | 1,673 | 20 | 236 | RCOSDP/osf.io | tests/test_registrations/test_retractions.py | Python | RegistrationRetractionViewsTestCase | RegistrationRetractionViewsTestCase | 770 | 966 | 770 | 771 | e38d76ef167e81c9e13fe89702d3b3b4b545843c | bigcode/the-stack | train |
5ce7b552b7923f77b6da3b4e | train | function | def dataload(row):
dt = np.loadtxt('PhDData_500n_1rep40000n_img.csv', delimiter=',')
dt = dt[row, 0:1024]
np.save("data", dt)
return dt
| def dataload(row):
| dt = np.loadtxt('PhDData_500n_1rep40000n_img.csv', delimiter=',')
dt = dt[row, 0:1024]
np.save("data", dt)
return dt
| import pandas as pd
import numpy as np
from PIL import Image
import cv2
# load data
def dataload(row):
| 28 | 64 | 54 | 5 | 22 | whizzkid-ox/neuron-image | image_show.py | Python | dataload | dataload | 7 | 11 | 7 | 7 | 2fabaec07abe87a062f77bb1dd9ac629070e5f39 | bigcode/the-stack | train |
e6e8694baf6d7507e373c167 | train | class | class Migration(migrations.Migration):
dependencies = [
('home', '0002_create_homepage'),
]
operations = [
migrations.AddField(
model_name='homepage',
name='body',
field=wagtail.core.fields.RichTextField(blank=True),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('home', '0002_create_homepage'),
]
operations = [
migrations.AddField(
model_name='homepage',
name='body',
field=wagtail.core.fields.RichTextField(blank=True),
),
]
| # Generated by Django 2.0.5 on 2018-05-11 07:21
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
| 42 | 64 | 61 | 7 | 34 | Parbhat/wagtail-amp | home/migrations/0003_homepage_body.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | 7743546e77183513c6fcc26e5d5e8750530d6881 | bigcode/the-stack | train |
72d079ba9228758e8b3d9bf8 | train | function | def fizz_buzz(number):
output = []
conversions = {
'3': 'fizz',
'5': 'buzz',
}
deluxe = False
for key in list(conversions.keys()):
criteria_count = 0
if number % int(key) == 0:
criteria_count += 1
if key in str(number):
criteria_count +... | def fizz_buzz(number):
| output = []
conversions = {
'3': 'fizz',
'5': 'buzz',
}
deluxe = False
for key in list(conversions.keys()):
criteria_count = 0
if number % int(key) == 0:
criteria_count += 1
if key in str(number):
criteria_count += 1
if criteria... | # noinspection PyUnusedLocal
def fizz_buzz(number):
| 13 | 64 | 158 | 6 | 6 | DPNT-Sourcecode/FIZ-dixe01 | lib/solutions/FIZ/fizz_buzz_solution.py | Python | fizz_buzz | fizz_buzz | 2 | 25 | 2 | 2 | 477a2ceb0d48d269525d0420e23ff6488bf37da3 | bigcode/the-stack | train |
926b5cdbfab20d354ed8e42b | train | function | def _correct_rotational_difference(points, target_dir):
"""
Rotates all points in `points` around the z-axis according to an angle computed such that the first forward
vector of the root is rotated onto the `target_dir` vector.
:param points: an np array of size (nr_points, 3, nr_frames), the first poin... | def _correct_rotational_difference(points, target_dir):
| """
Rotates all points in `points` around the z-axis according to an angle computed such that the first forward
vector of the root is rotated onto the `target_dir` vector.
:param points: an np array of size (nr_points, 3, nr_frames), the first point in the first frame is considered root
:param targe... | ].diffuse *
gl_FrontMaterial.diffuse *
lambertTerm1;
vec3 E = normalize(eyeVec);
vec3 R = reflect(-L1, N);
float specular = pow( max(dot(R, E), 0.0),
gl_FrontMaterial.shininess );
final_color += gl_LightSource[1].spe... | 118 | 118 | 394 | 11 | 107 | eth-ait/motion-infilling | tbase/skeleton.py | Python | _correct_rotational_difference | _correct_rotational_difference | 78 | 107 | 78 | 78 | 97cf9e34840985f1462488fd30d33e1425e3dcc2 | bigcode/the-stack | train |
0d99f38745aebd06c7d77ec9 | train | function | def to_global_batched(points, override_trajectory=None, override_root=None):
"""
:param points: A np array of shape (batch_size, dof, seq_lenth) where dof is assumed to contain the trajectory
in the last three dimensions.
:param override_trajectory: A np array of shape (batch_size, 3, seq_lenth) if th... | def to_global_batched(points, override_trajectory=None, override_root=None):
| """
:param points: A np array of shape (batch_size, dof, seq_lenth) where dof is assumed to contain the trajectory
in the last three dimensions.
:param override_trajectory: A np array of shape (batch_size, 3, seq_lenth) if the trajectory of `point` is
to be overriden with this value.
"""
... | j_corrected, axis=-1), [points.shape[0], points.shape[2], 3])
proj_corrected = np.transpose(proj_corrected, [0, 2, 1])
# restore the old z-values
proj_corrected[:, 2:3, :] = ori_z
return proj_corrected
def to_global_batched(points, override_trajectory=None, override_root=None):
| 88 | 88 | 296 | 16 | 71 | eth-ait/motion-infilling | tbase/skeleton.py | Python | to_global_batched | to_global_batched | 110 | 134 | 110 | 110 | 5d622a1baa3339f1e594a851cf40ab281821f01e | bigcode/the-stack | train |
ce5071e58419af45c2cf0091 | train | class | class Skeleton(object):
"""
Defines a skeleton.
"""
# Making joint indices explicit
ALL_JOINTS = list(range(0, 22))
ROOT, HIP, RIGHT_GROIN, RIGHT_KNEE, RIGHT_HEEL, RIGHT_TOE, \
LEFT_GROIN, LEFT_KNEE, LEFT_HEEL, LEFT_TOE, \
LOWER_BODY, UPPER_BODY, NECK, HEAD, \
RIGHT_SHOULDER, RIGHT_E... | class Skeleton(object):
| """
Defines a skeleton.
"""
# Making joint indices explicit
ALL_JOINTS = list(range(0, 22))
ROOT, HIP, RIGHT_GROIN, RIGHT_KNEE, RIGHT_HEEL, RIGHT_TOE, \
LEFT_GROIN, LEFT_KNEE, LEFT_HEEL, LEFT_TOE, \
LOWER_BODY, UPPER_BODY, NECK, HEAD, \
RIGHT_SHOULDER, RIGHT_ELBOW, RIGHT_WRIST, RIGHT... | 3, seq_lenth) if the trajectory of `point` is
to be overriden with this value.
"""
n = points.shape[0]
seq_len = points.shape[-1]
body_dim = len(Skeleton.ALL_JOINTS)*3
body_joints = points[:, :body_dim].reshape([n, -1, 3, seq_len]) # (N, n_joints, 3, seq_len)
trajectory = points[:, body_d... | 227 | 227 | 758 | 4 | 223 | eth-ait/motion-infilling | tbase/skeleton.py | Python | Skeleton | Skeleton | 137 | 185 | 137 | 137 | 3d41af94dce41e9a5b89cb4800a5a1e122c45a71 | bigcode/the-stack | train |
623dfddeaa3ca33274608f27 | train | class | class SkeletonSequence(object):
"""
An animated skeleton, i.e. a sequence of skeletons over time.
"""
_counter = 0
def __init__(self, sequence, x_offset=None, offsets=None, target_dir=None, name=None, color=None, interp=None,
static_frames=None):
"""
Constructor
... | class SkeletonSequence(object):
| """
An animated skeleton, i.e. a sequence of skeletons over time.
"""
_counter = 0
def __init__(self, sequence, x_offset=None, offsets=None, target_dir=None, name=None, color=None, interp=None,
static_frames=None):
"""
Constructor
:param sequence: an np arra... | 62])
# Indices pointing to the feet. Note that those indices are only valid if the data is NOT flattened, i.e. it is
# e.g. in the form (nr_joints, 3). Also note that the order in the `FEET` vector is chosen such that it is the same
# as the foot contact states encoded in the training data.
FEET = np.a... | 256 | 256 | 3,504 | 5 | 251 | eth-ait/motion-infilling | tbase/skeleton.py | Python | SkeletonSequence | SkeletonSequence | 188 | 570 | 188 | 188 | 1cdb87af327d6b8a23626602a11caabab9048c77 | bigcode/the-stack | train |
84accd333703abba5a57e382 | train | class | class FlatBlockAdmin(admin.ModelAdmin):
ordering = ['slug', ]
list_display = ('slug', 'content')
search_fields = ('slug', 'content')
| class FlatBlockAdmin(admin.ModelAdmin):
| ordering = ['slug', ]
list_display = ('slug', 'content')
search_fields = ('slug', 'content')
| .site.register(ConservationFeature)
admin.site.register(PlanningUnit)
admin.site.register(Cost)
admin.site.register(PuVsCf)
admin.site.register(PuVsCost)
admin.site.register(Scenario)
# Override flatblock admin
from flatblocks.models import FlatBlock
class FlatBlockAdmin(admin.ModelAdmin):
| 64 | 64 | 35 | 8 | 55 | Ecotrust/cogs-priorities | priorities/seak/admin.py | Python | FlatBlockAdmin | FlatBlockAdmin | 14 | 17 | 14 | 14 | 34e09192a12e27b02887e6d1140f735d6787d985 | bigcode/the-stack | train |
26a1ffc9ca3f2dad864db05c | train | function | def addPadding(data):
length = 8 - (len(data) % 8)
data += "\x00" * (length)
return data
| def addPadding(data):
| length = 8 - (len(data) % 8)
data += "\x00" * (length)
return data
| 45678'
plaintext = 'AAAABBBBCCCC'
def encrypt(data,key, mode):
encobj = DES.new(key,mode)
return(encobj.encrypt(data))
def decrypt(ciphertext,key, mode):
encobj = DES.new(key,mode)
return(encobj.decrypt(ciphertext))
def addPadding(data):
| 64 | 64 | 35 | 5 | 59 | neilpelow/Security-Labs | padding.py | Python | addPadding | addPadding | 17 | 20 | 17 | 17 | a288cd6d3f63162849350272047debdf201f6766 | bigcode/the-stack | train |
33be42bf37adb2eb8d4f3512 | train | function | def removePadding(data):
return data
| def removePadding(data):
| return data
| (ciphertext,key, mode):
encobj = DES.new(key,mode)
return(encobj.decrypt(ciphertext))
def addPadding(data):
length = 8 - (len(data) % 8)
data += "\x00" * (length)
return data
def removePadding(data):
| 64 | 64 | 10 | 6 | 57 | neilpelow/Security-Labs | padding.py | Python | removePadding | removePadding | 22 | 24 | 22 | 23 | f31fbc6997e2e0e16a19c461554c7ff073664097 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.