index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,077 | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/logutils.py | 16,17 | 6,27 | filter | FieldSkipLogFilter | 18,27 | 17,27 | class FieldSkipLogFilter(logging.Filter):
"""Filter field skip log messges.
At most, one message per field skipped per loop will be passed.
"""
def __init__(self, name=''):
super().__init__(name)
self.seen_msgs = set()
def filter(self, record):
FILL_FUNC_BODY | class FieldSkipLogFilter(logging.Filter):
"""Filter field skip log messges.
At most, one message per field skipped per loop will be passed.
"""
def __init__(self, name=''):
super().__init__(name)
self.seen_msgs = set()
def filter(self, record):
"""Pass record if not seen."... | msg = record.getMessage()
if msg.startswith("Skipping field"):
retval = msg not in self.seen_msgs
self.seen_msgs.add(msg)
return retval
else:
return 1
| """Pass record if not seen."""
msg = record.getMessage()
if msg.startswith("Skipping field"):
retval = msg not in self.seen_msgs
self.seen_msgs.add(msg)
return retval
else:
return 1
| 18 | 104 | 74 | 178 | """Logging helper classes."""
import logging
class FieldSkipLogFilter(logging.Filter):
"""Filter field skip log messges.
At most, one message per field skipped per loop will be passed.
"""
def __init__(self, name=''):
super().__init__(name)
self.seen_msgs = set()
def filter(sel... | """Logging helper classes."""
import logging
class FieldSkipLogFilter(logging.Filter):
"""Filter field skip log messges.
At most, one message per field skipped per loop will be passed.
"""
def __init__(self, name=''):
super().__init__(name)
self.seen_msgs = set()
def filter(sel... |
44,078 | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/rfc3339.py | 65,66 | 1,123 | parse_date | 77,89 | 66,89 | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... | match = re.search(pattern_date, text)
if match is None:
raise ValueError(f"Time data '{text}' does not match pattern")
g = group_accessor(match)
log.debug("Match groups: %s", match.groups())
return (
int(g.group(1)),
int(g.group(3)),
int(g.group(5)),
0, 0, 0, ... | """Given a date, returns a datetime tuple
Parameters
----------
text: string to be parsed
Returns
-------
(int, int , int, int, int, int, int, int):
datetime tuple: (year, month, day, hour, minute, second, microsecond, utcoffset in minutes or None)
"""
match = re.se... | 33 | 1,142 | 130 | 1,272 | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... | |
44,079 | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/rfc3339.py | 23,24 | 19,30 | group | group_accessor | 24,30 | 24,30 | class group_accessor:
def __init__(self, m):
self.match = m
def group(self, i):
FILL_FUNC_BODY | class group_accessor:
def __init__(self, m):
self.match = m
def group(self, i):
FILL_FUNC_BODY | try:
return self.match.group(i) or 0
except IndexError:
return 0
| try:
return self.match.group(i) or 0
except IndexError:
return 0
| 9 | 44 | 37 | 81 | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... | # Fiona's date and time is founded on RFC 3339.
#
# OGR knows 3 time "zones": GMT, "local time", amd "unknown". Fiona, when
# writing will convert times with a timezone offset to GMT (Z) and otherwise
# will write times with the unknown zone.
import logging
import re
log = logging.getLogger("Fiona")
pattern_date = r... |
44,080 | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona | /home/hieuvd/dung_repo/raw/stars_03/Toblerity_Fiona/Fiona/fiona/vfs.py | 38,39 | 1,88 | vsi_path | 39,53 | 39,53 | """Implementation of Apache VFS schemes and URLs."""
import sys
import re
from urllib.parse import urlparse
# Supported URI schemes and their mapping to GDAL's VSI suffix.
# TODO: extend for other cloud plaforms.
SCHEMES = {
'ftp': 'curl',
'gzip': 'gzip',
'http': 'curl',
'https': 'curl',
's3': 's... | """Implementation of Apache VFS schemes and URLs."""
import sys
import re
from urllib.parse import urlparse
# Supported URI schemes and their mapping to GDAL's VSI suffix.
# TODO: extend for other cloud plaforms.
SCHEMES = {
'ftp': 'curl',
'gzip': 'gzip',
'http': 'curl',
'https': 'curl',
's3': 's... | # If a VSI and archive file are specified, we convert the path to
# an OGR VSI path (see cpl_vsi.h).
if vsi:
prefix = '/'.join(f'vsi{SCHEMES[p]}' for p in vsi.split('+'))
if archive:
result = f'/{prefix}/{archive}{path}'
else:
result = f'/{prefix}/{path}'
... | # If a VSI and archive file are specified, we convert the path to
# an OGR VSI path (see cpl_vsi.h).
if vsi:
prefix = '/'.join(f'vsi{SCHEMES[p]}' for p in vsi.split('+'))
if archive:
result = f'/{prefix}/{archive}{path}'
else:
result = f'/{prefix}/{path}'
... | 45 | 715 | 139 | 854 | """Implementation of Apache VFS schemes and URLs."""
import sys
import re
from urllib.parse import urlparse
# Supported URI schemes and their mapping to GDAL's VSI suffix.
# TODO: extend for other cloud plaforms.
SCHEMES = {
'ftp': 'curl',
'gzip': 'gzip',
'http': 'curl',
'https': 'curl',
's3': 's... | """Implementation of Apache VFS schemes and URLs."""
import sys
import re
from urllib.parse import urlparse
# Supported URI schemes and their mapping to GDAL's VSI suffix.
# TODO: extend for other cloud plaforms.
SCHEMES = {
'ftp': 'curl',
'gzip': 'gzip',
'http': 'curl',
'https': 'curl',
's3': 's... | |
44,167 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/index.py | 5,6 | 1,18 | main_handler | 6,11 | 6,11 | from main import run
# Tencent SCF
def main_handler(event, context):
FILL_FUNC_BODYdef handler(event, context):
run()
return
if __name__ == '__main__':
run()
| from main import run
# Tencent SCF
def main_handler(event, context):
FILL_FUNC_BODYdef handler(event, context):
run()
return
if __name__ == '__main__':
run()
| run()
return
# Aliyun FC
| run()
return
# Aliyun FC
| 5 | 66 | 20 | 86 | from main import run
# Tencent SCF
def main_handler(event, context):
FILL_FUNC_BODYdef handler(event, context):
run()
return
if __name__ == '__main__':
run()
| from main import run
# Tencent SCF
def main_handler(event, context):
FILL_FUNC_BODYdef handler(event, context):
run()
return
if __name__ == '__main__':
run()
| |
44,168 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/bark.py | 29,40 | 10,52 | _prepare_data | Bark | 40,52 | 40,52 | class Bark(Provider):
name = 'bark'
base_url = 'https://api.day.app/{}'
site_url = 'https://apps.apple.com/us/app/bark-customed-notifications/id1403753865'
_params = {
'required': ['key'],
'optional': [
'title', 'content', 'sound', 'isarchive', 'icon', 'group', 'url', 'copy'... | class Bark(Provider):
name = 'bark'
base_url = 'https://api.day.app/{}'
site_url = 'https://apps.apple.com/us/app/bark-customed-notifications/id1403753865'
_params = {
'required': ['key'],
'optional': [
'title', 'content', 'sound', 'isarchive', 'icon', 'group', 'url', 'copy'... | self.data = {
'title': title,
'body': content,
'sound': sound,
'isArchive': 1 if isarchive else isarchive,
'icon': icon,
'group': group,
'url': url,
'copy': copy,
'autoCopy': 1 if autocopy else autocopy
... | self.data = {
'title': title,
'body': content,
'sound': sound,
'isArchive': 1 if isarchive else isarchive,
'icon': icon,
'group': group,
'url': url,
'copy': copy,
'autoCopy': 1 if autocopy else autocopy
... | 32 | 303 | 109 | 412 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Bark(Provider):
name = 'bark'
base_url = 'https://api.day.app/{}'
site_url = 'https://apps.apple.com/us/app/bark-customed-notifications/id1403753865'
_params = {
'required': ... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Bark(Provider):
name = 'bark'
base_url = 'https://api.day.app/{}'
site_url = 'https://apps.apple.com/us/app/bark-customed-notifications/id1403753865'
_params = {
'required': ... |
44,169 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/custom.py | 15,16 | 10,28 | _prepare_url | Custom | 16,19 | 16,19 | class Custom(Provider):
name = 'custom'
_params = {'required': ['url'], 'optional': ['method', 'datatype', 'data']}
async def _prepare_url(self, url: str, **kwargs):
FILL_FUNC_BODY async def _prepare_data(self,
method: str = 'post',
datatype: str = 'data',
... | class Custom(Provider):
name = 'custom'
_params = {'required': ['url'], 'optional': ['method', 'datatype', 'data']}
async def _prepare_url(self, url: str, **kwargs):
FILL_FUNC_BODY async def _prepare_data(self,
method: str = 'post',
datatype: str = 'data',
... | self.url = url
return self.url
| self.url = url
return self.url
| 5 | 144 | 17 | 161 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Custom(Provider):
name = 'custom'
_params = {'required': ['url'], 'optional': ['method', 'datatype', 'data']}
async def _prepare_url(self, url: str, **kwargs):
FILL_FUNC_BODY async d... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Custom(Provider):
name = 'custom'
_params = {'required': ['url'], 'optional': ['method', 'datatype', 'data']}
async def _prepare_url(self, url: str, **kwargs):
FILL_FUNC_BODY async d... |
44,170 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/dingtalk.py | 37,38 | 10,69 | _prepare_url | DingTalk | 38,48 | 38,48 | class DingTalk(Provider):
name = 'dingtalk'
base_url = 'https://oapi.dingtalk.com/robot/send?access_token={}'
site_url = 'https://developers.dingtalk.com/document/app/custom-robot-access'
_params = {
'required': ['token'],
'optional': ['title', 'content', 'secret', 'markdown']
}
... | class DingTalk(Provider):
name = 'dingtalk'
base_url = 'https://oapi.dingtalk.com/robot/send?access_token={}'
site_url = 'https://developers.dingtalk.com/document/app/custom-robot-access'
_params = {
'required': ['token'],
'optional': ['title', 'content', 'secret', 'markdown']
}
... | self.url = token
if 'https' not in token or 'http' not in token:
self.url = self.base_url.format(token)
if secret:
timestamp, sign = self.encrypt(secret)
self.url = self.url + '×tamp={}&sign={}'.format(
timestamp, sign)
return sel... | self.url = token
if 'https' not in token or 'http' not in token:
self.url = self.base_url.format(token)
if secret:
timestamp, sign = self.encrypt(secret)
self.url = self.url + '×tamp={}&sign={}'.format(
timestamp, sign)
return sel... | 31 | 520 | 104 | 624 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class DingTalk(Provider):
name = 'dingtalk'
base_url = 'https://oapi.dingtalk.com/robot/send?access_token={}'
site_url = 'https://developers.dingtalk.com/document/app/custom-robot-access'
... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class DingTalk(Provider):
name = 'dingtalk'
base_url = 'https://oapi.dingtalk.com/robot/send?access_token={}'
site_url = 'https://developers.dingtalk.com/document/app/custom-robot-access'
... |
44,171 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/discord.py | 41,42 | 10,43 | _send_message | Discord | 42,43 | 42,43 | class Discord(Provider):
name = 'discord'
site_url = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
_params = {
'required': ['webhook'],
'optional': ['title', 'content', 'username', 'avatar_url', 'color']
}
async def _prepare_url(self, webhook: str, **k... | class Discord(Provider):
name = 'discord'
site_url = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
_params = {
'required': ['webhook'],
'optional': ['title', 'content', 'username', 'avatar_url', 'color']
}
async def _prepare_url(self, webhook: str, **k... | return await self.request('post', self.url, json=self.data)
| return await self.request('post', self.url, json=self.data)
| 5 | 294 | 21 | 315 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Discord(Provider):
name = 'discord'
site_url = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
_params = {
'required': ['webhook'],
'optional'... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Discord(Provider):
name = 'discord'
site_url = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
_params = {
'required': ['webhook'],
'optional'... |
44,172 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/gocqhttp.py | 35,44 | 10,54 | _prepare_data | Gocqhttp | 44,54 | 44,54 | class Gocqhttp(Provider):
name = 'gocqhttp'
site_url = 'https://docs.go-cqhttp.org'
_params = {
'required': ['endpoint'],
'optional': [
'title', 'content', 'path', 'token', 'message_type', 'user_id',
'group_id', 'auto_escape'
]
}
def __init__(self):
... | class Gocqhttp(Provider):
name = 'gocqhttp'
site_url = 'https://docs.go-cqhttp.org'
_params = {
'required': ['endpoint'],
'optional': [
'title', 'content', 'path', 'token', 'message_type', 'user_id',
'group_id', 'auto_escape'
]
}
def __init__(self):
... | message = self.process_message(title, content)
self.data = {
'access_token': token,
'message_type': message_type,
'user_id': user_id,
'group_id': group_id,
'message': message,
'auto_escape': auto_escape
}
return self... | message = self.process_message(title, content)
self.data = {
'access_token': token,
'message_type': message_type,
'user_id': user_id,
'group_id': group_id,
'message': message,
'auto_escape': auto_escape
}
return self... | 22 | 304 | 99 | 403 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Gocqhttp(Provider):
name = 'gocqhttp'
site_url = 'https://docs.go-cqhttp.org'
_params = {
'required': ['endpoint'],
'optional': [
'title', 'content', 'path', ... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Gocqhttp(Provider):
name = 'gocqhttp'
site_url = 'https://docs.go-cqhttp.org'
_params = {
'required': ['endpoint'],
'optional': [
'title', 'content', 'path', ... |
44,173 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/lark.py | 18,19 | 9,39 | _prepare_url | Lark | 19,21 | 19,21 | class Lark(Provider):
name = 'lark'
def gen_sign(self, timestamp, secret):
string_to_sign = '{}\n{}'.format(timestamp, secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
sign = base64.b64encode(hmac_code).decode('utf-8')
return sign
... | class Lark(Provider):
name = 'lark'
def gen_sign(self, timestamp, secret):
string_to_sign = '{}\n{}'.format(timestamp, secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
sign = base64.b64encode(hmac_code).decode('utf-8')
return sign
... | self.url = webhook
| self.url = webhook
| 3 | 308 | 11 | 319 | from ..core import Provider
import hashlib
import base64
import hmac
import time
class Lark(Provider):
name = 'lark'
def gen_sign(self, timestamp, secret):
string_to_sign = '{}\n{}'.format(timestamp, secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).diges... | from ..core import Provider
import hashlib
import base64
import hmac
import time
class Lark(Provider):
name = 'lark'
def gen_sign(self, timestamp, secret):
string_to_sign = '{}\n{}'.format(timestamp, secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).diges... |
44,174 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/pushplus.py | 40,41 | 10,42 | _send_message | PushPlus | 41,42 | 41,42 | class PushPlus(Provider):
name = 'pushplus'
base_url = 'https://www.pushplus.plus/send'
site_url = 'https://www.pushplus.plus/doc'
_params = {
'required': ['token', 'content'],
'optional': ['title', 'topic', 'markdown']
}
async def _prepare_url(self, **kwargs):
self.url... | class PushPlus(Provider):
name = 'pushplus'
base_url = 'https://www.pushplus.plus/send'
site_url = 'https://www.pushplus.plus/doc'
_params = {
'required': ['token', 'content'],
'optional': ['title', 'topic', 'markdown']
}
async def _prepare_url(self, **kwargs):
self.url... | return await self.request('post', self.url, json=self.data)
| return await self.request('post', self.url, json=self.data)
| 5 | 257 | 21 | 278 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class PushPlus(Provider):
name = 'pushplus'
base_url = 'https://www.pushplus.plus/send'
site_url = 'https://www.pushplus.plus/doc'
_params = {
'required': ['token', 'content'],
... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class PushPlus(Provider):
name = 'pushplus'
base_url = 'https://www.pushplus.plus/send'
site_url = 'https://www.pushplus.plus/doc'
_params = {
'required': ['token', 'content'],
... |
44,175 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/qmsg.py | 24,29 | 10,32 | _prepare_data | Qmsg | 29,32 | 29,32 | class Qmsg(Provider):
name = 'qmsg'
base_url = 'https://qmsg.zendee.cn/{}/{}'
site_url = 'https://qmsg.zendee.cn/api.html'
_params = {
'required': ['key'],
'optional': ['title', 'content', 'mode', 'qq']
}
async def _prepare_url(self, key: str, mode: str = 'send', **kwargs):
... | class Qmsg(Provider):
name = 'qmsg'
base_url = 'https://qmsg.zendee.cn/{}/{}'
site_url = 'https://qmsg.zendee.cn/api.html'
_params = {
'required': ['key'],
'optional': ['title', 'content', 'mode', 'qq']
}
async def _prepare_url(self, key: str, mode: str = 'send', **kwargs):
... | message = self.process_message(title, content)
self.data = {'msg': message, 'qq': qq}
return self.data
| message = self.process_message(title, content)
self.data = {'msg': message, 'qq': qq}
return self.data
| 12 | 196 | 40 | 236 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Qmsg(Provider):
name = 'qmsg'
base_url = 'https://qmsg.zendee.cn/{}/{}'
site_url = 'https://qmsg.zendee.cn/api.html'
_params = {
'required': ['key'],
'optional': ['ti... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Qmsg(Provider):
name = 'qmsg'
base_url = 'https://qmsg.zendee.cn/{}/{}'
site_url = 'https://qmsg.zendee.cn/api.html'
_params = {
'required': ['key'],
'optional': ['ti... |
44,176 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/serverchan.py | 17,18 | 10,24 | _prepare_url | ServerChan | 18,21 | 18,21 | class ServerChan(Provider):
name = 'serverchan'
base_url = 'https://sc.ftqq.com/{}.send'
site_url = 'https://sc.ftqq.com/3.version'
_params = {'required': ['sckey', 'title'], 'optional': ['content']}
async def _prepare_url(self, sckey: str, **kwargs):
FILL_FUNC_BODY async def _prepare_data(self... | class ServerChan(Provider):
name = 'serverchan'
base_url = 'https://sc.ftqq.com/{}.send'
site_url = 'https://sc.ftqq.com/3.version'
_params = {'required': ['sckey', 'title'], 'optional': ['content']}
async def _prepare_url(self, sckey: str, **kwargs):
FILL_FUNC_BODY async def _prepare_data(self... | self.url = self.base_url.format(sckey)
return self.url
| self.url = self.base_url.format(sckey)
return self.url
| 5 | 155 | 27 | 182 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class ServerChan(Provider):
name = 'serverchan'
base_url = 'https://sc.ftqq.com/{}.send'
site_url = 'https://sc.ftqq.com/3.version'
_params = {'required': ['sckey', 'title'], 'optional': [... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class ServerChan(Provider):
name = 'serverchan'
base_url = 'https://sc.ftqq.com/{}.send'
site_url = 'https://sc.ftqq.com/3.version'
_params = {'required': ['sckey', 'title'], 'optional': [... |
44,177 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/serverchanturbo.py | 24,30 | 10,37 | _prepare_data | ServerChanTurbo | 30,37 | 30,37 | class ServerChanTurbo(Provider):
name = 'serverchanturbo'
base_url = 'https://sctapi.ftqq.com/{}.send'
site_url = 'https://sct.ftqq.com'
_params = {
'required': ['sctkey', 'title'],
'optional': ['content', 'channel', 'openid']
}
async def _prepare_url(self, sctkey: str, **kwarg... | class ServerChanTurbo(Provider):
name = 'serverchanturbo'
base_url = 'https://sctapi.ftqq.com/{}.send'
site_url = 'https://sct.ftqq.com'
_params = {
'required': ['sctkey', 'title'],
'optional': ['content', 'channel', 'openid']
}
async def _prepare_url(self, sctkey: str, **kwarg... | self.data = {
'text': title,
'desp': content,
'channel': channel,
'openid': openid
}
return self.data
| self.data = {
'text': title,
'desp': content,
'channel': channel,
'openid': openid
}
return self.data
| 14 | 200 | 53 | 253 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class ServerChanTurbo(Provider):
name = 'serverchanturbo'
base_url = 'https://sctapi.ftqq.com/{}.send'
site_url = 'https://sct.ftqq.com'
_params = {
'required': ['sctkey', 'title']... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class ServerChanTurbo(Provider):
name = 'serverchanturbo'
base_url = 'https://sctapi.ftqq.com/{}.send'
site_url = 'https://sct.ftqq.com'
_params = {
'required': ['sctkey', 'title']... |
44,178 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/telegram.py | 24,25 | 10,32 | _prepare_data | Telegram | 25,32 | 25,32 | class Telegram(Provider):
name = 'telegram'
base_url = 'https://{}/bot{}/sendMessage'
site_url = 'https://core.telegram.org/bots'
_params = {
'required': ['token', 'userid'],
'optional': ['title', 'content', 'api_url']
}
async def _prepare_url(self, token: str, api_url: str = '... | class Telegram(Provider):
name = 'telegram'
base_url = 'https://{}/bot{}/sendMessage'
site_url = 'https://core.telegram.org/bots'
_params = {
'required': ['token', 'userid'],
'optional': ['title', 'content', 'api_url']
}
async def _prepare_url(self, token: str, api_url: str = '... | message = self.process_message(title, content)
self.data = {
'chat_id': userid,
'text': message,
'disable_web_page_preview': True
}
return self.data
| message = self.process_message(title, content)
self.data = {
'chat_id': userid,
'text': message,
'disable_web_page_preview': True
}
return self.data
| 16 | 190 | 67 | 257 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Telegram(Provider):
name = 'telegram'
base_url = 'https://{}/bot{}/sendMessage'
site_url = 'https://core.telegram.org/bots'
_params = {
'required': ['token', 'userid'],
... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class Telegram(Provider):
name = 'telegram'
base_url = 'https://{}/bot{}/sendMessage'
site_url = 'https://core.telegram.org/bots'
_params = {
'required': ['token', 'userid'],
... |
44,179 | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper | /home/hieuvd/dung_repo/raw/stars_03/XiaoMiku01_fansMedalHelper/fansMedalHelper/onepush/providers/wechatworkbot.py | 20,21 | 10,41 | _prepare_url | WechatWorkBot | 21,26 | 21,26 | class WechatWorkBot(Provider):
name = 'wechatworkbot'
base_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'
site_url = 'https://work.weixin.qq.com/api/doc/90000/90136/91770'
_params = {
'required': ['key'],
'optional': ['title', 'content', 'markdown']
}
async def... | class WechatWorkBot(Provider):
name = 'wechatworkbot'
base_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'
site_url = 'https://work.weixin.qq.com/api/doc/90000/90136/91770'
_params = {
'required': ['key'],
'optional': ['title', 'content', 'markdown']
}
async def... | self.url = key
if 'https' not in key or 'http' not in key:
self.url = self.base_url.format(key)
return self.url
| self.url = key
if 'https' not in key or 'http' not in key:
self.url = self.base_url.format(key)
return self.url
| 18 | 295 | 52 | 347 | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class WechatWorkBot(Provider):
name = 'wechatworkbot'
base_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'
site_url = 'https://work.weixin.qq.com/api/doc/90000/90136/91770'
... | """
@Project : onepush
@Author : y1ndan
@Blog : https://www.yindan.me
"""
from ..core import Provider
class WechatWorkBot(Provider):
name = 'wechatworkbot'
base_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'
site_url = 'https://work.weixin.qq.com/api/doc/90000/90136/91770'
... |
44,182 | /home/hieuvd/dung_repo/raw/stars_03/abertsch72_unlimiformer/unlimiformer | /home/hieuvd/dung_repo/raw/stars_03/abertsch72_unlimiformer/unlimiformer/src/utils/config.py | 4,5 | 1,14 | handle_args_to_ignore | 5,14 | 5,14 | from typing import List
def handle_args_to_ignore(args: List[str]):
FILL_FUNC_BODY | from typing import List
def handle_args_to_ignore(args: List[str]):
FILL_FUNC_BODY | indices_to_remove = []
for i, arg in enumerate(args):
if "_ignore_" in arg:
indices_to_remove.append(i)
if not arg.startswith("-"):
indices_to_remove.append(i - 1)
for i in sorted(indices_to_remove, reverse=True):
del args[i]
| indices_to_remove = []
for i, arg in enumerate(args):
if "_ignore_" in arg:
indices_to_remove.append(i)
if not arg.startswith("-"):
indices_to_remove.append(i - 1)
for i in sorted(indices_to_remove, reverse=True):
del args[i]
| 26 | 34 | 104 | 138 | from typing import List
def handle_args_to_ignore(args: List[str]):
FILL_FUNC_BODY | from typing import List
def handle_args_to_ignore(args: List[str]):
FILL_FUNC_BODY | |
44,183 | /home/hieuvd/dung_repo/raw/stars_03/abertsch72_unlimiformer/unlimiformer | /home/hieuvd/dung_repo/raw/stars_03/abertsch72_unlimiformer/unlimiformer/src/utils/duplicates.py | 1,2 | 1,16 | drop_duplicates_in_input | 2,16 | 2,16 | def drop_duplicates_in_input(untokenized_dataset):
FILL_FUNC_BODY | def drop_duplicates_in_input(untokenized_dataset):
FILL_FUNC_BODY | indices_to_keep = []
id_to_idx = {}
outputs = []
for i, (id_, output) in enumerate(zip(untokenized_dataset["id"], untokenized_dataset["output"])):
if id_ in id_to_idx:
outputs[id_to_idx[id_]].append(output)
continue
indices_to_keep.append(i)
id_to_idx[id_]... | indices_to_keep = []
id_to_idx = {}
outputs = []
for i, (id_, output) in enumerate(zip(untokenized_dataset["id"], untokenized_dataset["output"])):
if id_ in id_to_idx:
outputs[id_to_idx[id_]].append(output)
continue
indices_to_keep.append(i)
id_to_idx[id_]... | 39 | 28 | 221 | 249 | def drop_duplicates_in_input(untokenized_dataset):
FILL_FUNC_BODY | def drop_duplicates_in_input(untokenized_dataset):
FILL_FUNC_BODY | |
44,184 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/backends/memory.py | 100,101 | 8,113 | __delete | SimpleMemoryBackend | 101,109 | 101,109 | class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
self._cache: Dict[str, object] = {}
self._handlers: ... | class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
self._cache: Dict[str, object] = {}
self._handlers: ... | if self._cache.pop(key, None) is not None:
handle = self._handlers.pop(key, None)
if handle:
handle.cancel()
return 1
return 0
| if self._cache.pop(key, None) is not None:
handle = self._handlers.pop(key, None)
if handle:
handle.cancel()
return 1
return 0
| 17 | 1,007 | 63 | 1,070 | import asyncio
from typing import Any, Dict, Optional
from aiocache.base import BaseCache
from aiocache.serializers import NullSerializer
class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
... | import asyncio
from typing import Any, Dict, Optional
from aiocache.base import BaseCache
from aiocache.serializers import NullSerializer
class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
... |
44,185 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/backends/memory.py | 134,136 | 113,137 | parse_uri_path | SimpleMemoryCache | 136,137 | 136,137 | class SimpleMemoryCache(SimpleMemoryBackend):
"""
Memory cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.NullSerializer`
- plugins: None
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseS... | class SimpleMemoryCache(SimpleMemoryBackend):
"""
Memory cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.NullSerializer`
- plugins: None
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseS... | return {}
| return {}
| 2 | 247 | 5 | 252 | import asyncio
from typing import Any, Dict, Optional
from aiocache.base import BaseCache
from aiocache.serializers import NullSerializer
class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
... | import asyncio
from typing import Any, Dict, Optional
from aiocache.base import BaseCache
from aiocache.serializers import NullSerializer
class SimpleMemoryBackend(BaseCache[str]):
"""
Wrapper around dict operations to use it as a cache backend
"""
# TODO(PY312): https://peps.python.org/pep-0692/
... |
44,186 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/backends/redis.py | 82,83 | 14,156 | _multi_set | RedisBackend | 83,94 | 83,94 | class RedisBackend(BaseCache[str]):
RELEASE_SCRIPT = (
"if redis.call('get',KEYS[1]) == ARGV[1] then"
" return redis.call('del',KEYS[1])"
" else"
" return 0"
" end"
)
CAS_SCRIPT = (
"if redis.call('get',KEYS[1]) == ARGV[2] then"
" if #ARGV == 4 then"... | class RedisBackend(BaseCache[str]):
RELEASE_SCRIPT = (
"if redis.call('get',KEYS[1]) == ARGV[1] then"
" return redis.call('del',KEYS[1])"
" else"
" return 0"
" end"
)
CAS_SCRIPT = (
"if redis.call('get',KEYS[1]) == ARGV[2] then"
" if #ARGV == 4 then"... | ttl = ttl or 0
flattened = list(itertools.chain.from_iterable((key, value) for key, value in pairs))
if ttl:
await self.__multi_set_ttl(flattened, ttl)
else:
await self.client.execute_command("MSET", *flattened)
return True
| ttl = ttl or 0
flattened = list(itertools.chain.from_iterable((key, value) for key, value in pairs))
if ttl:
await self.__multi_set_ttl(flattened, ttl)
else:
await self.client.execute_command("MSET", *flattened)
return True
| 25 | 1,611 | 106 | 1,717 | import itertools
from typing import Any, Callable, Optional, TYPE_CHECKING
import redis.asyncio as redis
from redis.exceptions import ResponseError as IncrbyException
from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer
if TYPE_CHECKING: # pragma: no cover
from aiocache.serializer... | import itertools
from typing import Any, Callable, Optional, TYPE_CHECKING
import redis.asyncio as redis
from redis.exceptions import ResponseError as IncrbyException
from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer
if TYPE_CHECKING: # pragma: no cover
from aiocache.serializer... |
44,187 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/backends/redis.py | 191,193 | 156,210 | parse_uri_path | RedisCache | 201,207 | 193,207 | class RedisCache(RedisBackend):
"""
Redis cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.JsonSerializer`
- plugins: []
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:... | class RedisCache(RedisBackend):
"""
Redis cache implementation with the following components as defaults:
- serializer: :class:`aiocache.serializers.JsonSerializer`
- plugins: []
Config options are:
:param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`.
:... | options = {}
db, *_ = path[1:].split("/")
if db:
options["db"] = db
return options
| """
Given a uri path, return the Redis specific configuration
options in that path string according to iana definition
http://www.iana.org/assignments/uri-schemes/prov/redis
:param path: string containing the path. Example: "/0"
:return: mapping containing the options. E... | 14 | 517 | 44 | 561 | import itertools
from typing import Any, Callable, Optional, TYPE_CHECKING
import redis.asyncio as redis
from redis.exceptions import ResponseError as IncrbyException
from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer
if TYPE_CHECKING: # pragma: no cover
from aiocache.serializer... | import itertools
from typing import Any, Callable, Optional, TYPE_CHECKING
import redis.asyncio as redis
from redis.exceptions import ResponseError as IncrbyException
from aiocache.base import BaseCache
from aiocache.serializers import JsonSerializer
if TYPE_CHECKING: # pragma: no cover
from aiocache.serializer... |
44,189 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/decorators.py | 154,155 | 13,161 | set_in_cache | cached | 155,161 | 155,161 | class cached:
"""
Caches the functions return value into a key generated with module_name, function_name
and args. The cache is available in the function object as ``<function_name>.cache``.
In some cases you will need to send more args to configure the cache object.
An example would be endpoint an... | class cached:
"""
Caches the functions return value into a key generated with module_name, function_name
and args. The cache is available in the function object as ``<function_name>.cache``.
In some cases you will need to send more args to configure the cache object.
An example would be endpoint an... | try:
await self.cache.set(key, value, ttl=self.ttl)
except Exception:
logger.exception("Couldn't set %s in key %s, unexpected error", value, key)
| try:
await self.cache.set(key, value, ttl=self.ttl)
except Exception:
logger.exception("Couldn't set %s in key %s, unexpected error", value, key)
| 17 | 1,549 | 63 | 1,612 | import asyncio
import functools
import inspect
import logging
from aiocache.base import SENTINEL
from aiocache.factory import Cache, caches
from aiocache.lock import RedLock
logger = logging.getLogger(__name__)
class cached:
"""
Caches the functions return value into a key generated with module_name, functi... | import asyncio
import functools
import inspect
import logging
from aiocache.base import SENTINEL
from aiocache.factory import Cache, caches
from aiocache.lock import RedLock
logger = logging.getLogger(__name__)
class cached:
"""
Caches the functions return value into a key generated with module_name, functi... |
44,190 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/decorators.py | 204,205 | 161,226 | decorator | cached_stampede | 205,226 | 205,226 | class cached_stampede(cached):
"""
Caches the functions return value into a key generated with module_name, function_name and args
while avoids for cache stampede effects.
In some cases you will need to send more args to configure the cache object.
An example would be endpoint and port for the Redi... | class cached_stampede(cached):
"""
Caches the functions return value into a key generated with module_name, function_name and args
while avoids for cache stampede effects.
In some cases you will need to send more args to configure the cache object.
An example would be endpoint and port for the Redi... | key = self.get_cache_key(f, args, kwargs)
value = await self.get_from_cache(key)
if value is not None:
return value
async with RedLock(self.cache, key, self.lease):
value = await self.get_from_cache(key)
if value is not None:
return v... | key = self.get_cache_key(f, args, kwargs)
value = await self.get_from_cache(key)
if value is not None:
return value
async with RedLock(self.cache, key, self.lease):
value = await self.get_from_cache(key)
if value is not None:
return v... | 46 | 661 | 168 | 829 | import asyncio
import functools
import inspect
import logging
from aiocache.base import SENTINEL
from aiocache.factory import Cache, caches
from aiocache.lock import RedLock
logger = logging.getLogger(__name__)
class cached:
"""
Caches the functions return value into a key generated with module_name, functi... | import asyncio
import functools
import inspect
import logging
from aiocache.base import SENTINEL
from aiocache.factory import Cache, caches
from aiocache.lock import RedLock
logger = logging.getLogger(__name__)
class cached:
"""
Caches the functions return value into a key generated with module_name, functi... |
44,193 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/factory.py | 96,98 | 50,144 | from_url | Cache | 119,144 | 98,144 | class Cache:
"""
This class is just a proxy to the specific cache implementations like
:class:`aiocache.SimpleMemoryCache`, :class:`aiocache.RedisCache` and
:class:`aiocache.MemcachedCache`. It is the preferred method of
instantiating new caches over using the backend specific classes.
You can ... | class Cache:
"""
This class is just a proxy to the specific cache implementations like
:class:`aiocache.SimpleMemoryCache`, :class:`aiocache.RedisCache` and
:class:`aiocache.MemcachedCache`. It is the preferred method of
instantiating new caches over using the backend specific classes.
You can ... | parsed_url = urllib.parse.urlparse(url)
kwargs = dict(urllib.parse.parse_qsl(parsed_url.query))
cache_class = Cache.get_scheme_class(parsed_url.scheme)
if parsed_url.path:
kwargs.update(cache_class.parse_uri_path(parsed_url.path))
if parsed_url.hostname:
... | """
Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
a more advanced ... | 50 | 741 | 293 | 1,034 | import logging
import urllib
from contextlib import suppress
from copy import deepcopy
from typing import Dict
from aiocache import AIOCACHE_CACHES
from aiocache.base import BaseCache
from aiocache.exceptions import InvalidCacheType
with suppress(ImportError):
import redis.asyncio as redis
logger = logging.getL... | import logging
import urllib
from contextlib import suppress
from copy import deepcopy
from typing import Dict
from aiocache import AIOCACHE_CACHES
from aiocache.base import BaseCache
from aiocache.exceptions import InvalidCacheType
with suppress(ImportError):
import redis.asyncio as redis
logger = logging.getL... |
44,194 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/factory.py | 173,174 | 144,274 | get | CacheHandler | 183,193 | 174,193 | class CacheHandler:
_config: Dict[str, Dict[str, object]] = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def add(self, alias: str, confi... | class CacheHandler:
_config: Dict[str, Dict[str, object]] = {
"default": {
"cache": "aiocache.SimpleMemoryCache",
"serializer": {"class": "aiocache.serializers.StringSerializer"},
}
}
def __init__(self):
self._caches = {}
def add(self, alias: str, confi... | try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache
| """
Retrieve cache identified by alias. Will return always the same instance
If the cache was not instantiated yet, it will do it lazily the first time
this is called.
:param alias: str cache alias
:return: cache instance
"""
try:
return self... | 17 | 989 | 79 | 1,068 | import logging
import urllib
from contextlib import suppress
from copy import deepcopy
from typing import Dict
from aiocache import AIOCACHE_CACHES
from aiocache.base import BaseCache
from aiocache.exceptions import InvalidCacheType
with suppress(ImportError):
import redis.asyncio as redis
logger = logging.getL... | import logging
import urllib
from contextlib import suppress
from copy import deepcopy
from typing import Dict
from aiocache import AIOCACHE_CACHES
from aiocache.base import BaseCache
from aiocache.exceptions import InvalidCacheType
with suppress(ImportError):
import redis.asyncio as redis
logger = logging.getL... |
44,195 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/lock.py | 152,153 | 99,166 | cas | OptimisticLock | 160,166 | 153,166 | class OptimisticLock(Generic[CacheKeyType]):
"""
Implementation of
`optimistic lock <https://en.wikipedia.org/wiki/Optimistic_concurrency_control>`_
Optimistic locking assumes multiple transactions can happen at the same time
and they will only fail if before finish, conflicting modifications with ... | class OptimisticLock(Generic[CacheKeyType]):
"""
Implementation of
`optimistic lock <https://en.wikipedia.org/wiki/Optimistic_concurrency_control>`_
Optimistic locking assumes multiple transactions can happen at the same time
and they will only fail if before finish, conflicting modifications with ... | success = await self.client.set(self.key, value, _cas_token=self._token, **kwargs)
if not success:
raise OptimisticLockError("Value has changed since the lock started")
return True
| """
Checks and sets the specified value for the locked key. If the value has changed
since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError`
exception.
:raises: :class:`aiocache.lock.OptimisticLockError`
"""
success = await self.cl... | 20 | 645 | 63 | 708 | import asyncio
import uuid
from typing import Any, Dict, Generic, Union
from aiocache.base import BaseCache, CacheKeyType
class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cac... | import asyncio
import uuid
from typing import Any, Dict, Generic, Union
from aiocache.base import BaseCache, CacheKeyType
class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cac... |
44,196 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/lock.py | 74,75 | 8,99 | _acquire | RedLock | 75,82 | 75,82 | class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cache.
This locking has some limitations and shouldn't be used in
situations where consistency is critical. Those locks... | class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cache.
This locking has some limitations and shouldn't be used in
situations where consistency is critical. Those locks... | self._value = str(uuid.uuid4())
try:
await self.client._add(self.key, self._value, ttl=self.lease)
RedLock._EVENTS[self.key] = asyncio.Event()
except ValueError:
await self._wait_for_release()
| self._value = str(uuid.uuid4())
try:
await self.client._add(self.key, self._value, ttl=self.lease)
RedLock._EVENTS[self.key] = asyncio.Event()
except ValueError:
await self._wait_for_release()
| 15 | 872 | 84 | 956 | import asyncio
import uuid
from typing import Any, Dict, Generic, Union
from aiocache.base import BaseCache, CacheKeyType
class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cac... | import asyncio
import uuid
from typing import Any, Dict, Generic, Union
from aiocache.base import BaseCache, CacheKeyType
class RedLock(Generic[CacheKeyType]):
"""
Implementation of `Redlock <https://redis.io/topics/distlock>`_
with a single instance because aiocache is focused on single
instance cac... |
44,197 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/plugins.py | 10,12 | 9,19 | add_hook | BasePlugin | 12,15 | 12,15 | class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
FILL_FUNC_BODY async def do_nothing(self, *args, **kwargs):
pass
| class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
FILL_FUNC_BODY async def do_nothing(self, *args, **kwargs):
pass
| for hook in hooks:
setattr(cls, hook, func)
| for hook in hooks:
setattr(cls, hook, func)
| 7 | 55 | 23 | 78 | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
FILL_FUNC_BODY async def do_nothing(self, *args, **kwa... | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
FILL_FUNC_BODY async def do_nothing(self, *args, **kwa... |
44,198 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/plugins.py | 71,72 | 63,99 | post_get | HitMissRatioPlugin | 72,85 | 72,85 | class HitMissRatioPlugin(BasePlugin):
"""
Calculates the ratio of hits the cache has. The data is saved in the cache class as a dict
attribute called ``hit_miss_ratio``. For example, to access the hit ratio of the cache,
you can do ``cache.hit_miss_ratio['hit_ratio']``. It also provides the "total" and ... | class HitMissRatioPlugin(BasePlugin):
"""
Calculates the ratio of hits the cache has. The data is saved in the cache class as a dict
attribute called ``hit_miss_ratio``. For example, to access the hit ratio of the cache,
you can do ``cache.hit_miss_ratio['hit_ratio']``. It also provides the "total" and ... | if not hasattr(client, "hit_miss_ratio"):
client.hit_miss_ratio = {}
client.hit_miss_ratio["total"] = 0
client.hit_miss_ratio["hits"] = 0
client.hit_miss_ratio["total"] += 1
if ret is not None:
client.hit_miss_ratio["hits"] += 1
client.hi... | if not hasattr(client, "hit_miss_ratio"):
client.hit_miss_ratio = {}
client.hit_miss_ratio["total"] = 0
client.hit_miss_ratio["hits"] = 0
client.hit_miss_ratio["total"] += 1
if ret is not None:
client.hit_miss_ratio["hits"] += 1
client.hi... | 31 | 325 | 163 | 488 | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
for hook in hooks:
setattr(cls, hook,... | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
for hook in hooks:
setattr(cls, hook,... |
44,199 | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache | /home/hieuvd/dung_repo/raw/stars_03/aio-libs_aiocache/aiocache/aiocache/plugins.py | 36,37 | 27,57 | do_save_time | TimingPlugin | 37,54 | 37,54 | class TimingPlugin(BasePlugin):
"""
Calculates average, min and max times each command takes. The data is saved
in the cache class as a dict attribute called ``profiling``. For example, to
access the average time of the operation get, you can do ``cache.profiling['get_avg']``
"""
@classmethod
... | class TimingPlugin(BasePlugin):
"""
Calculates average, min and max times each command takes. The data is saved
in the cache class as a dict attribute called ``profiling``. For example, to
access the average time of the operation get, you can do ``cache.profiling['get_avg']``
"""
@classmethod
... | if not hasattr(client, "profiling"):
client.profiling = {}
previous_total = client.profiling.get("{}_total".format(method), 0)
previous_avg = client.profiling.get("{}_avg".format(method), 0)
previous_max = client.profiling.get("{}_max".format(method), 0)
... | if not hasattr(client, "profiling"):
client.profiling = {}
previous_total = client.profiling.get("{}_total".format(method), 0)
previous_avg = client.profiling.get("{}_avg".format(method), 0)
previous_max = client.profiling.get("{}_max".format(method), 0)
... | 54 | 142 | 270 | 412 | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
for hook in hooks:
setattr(cls, hook,... | """
This module implements different plugins you can attach to your cache instance. They
are coded in a collaborative so you can use multiple inheritance.
"""
from aiocache.base import API
class BasePlugin:
@classmethod
def add_hook(cls, func, hooks):
for hook in hooks:
setattr(cls, hook,... |
44,200 | /home/hieuvd/dung_repo/raw/stars_03/alejandro-ao_ask-multiple-pdfs/ask-multiple-pdfs | /home/hieuvd/dung_repo/raw/stars_03/alejandro-ao_ask-multiple-pdfs/ask-multiple-pdfs/app.py | 67,68 | 1,105 | main | 68,103 | 68,103 | import streamlit as st
from dotenv import load_dotenv
from PyPDF2 import PdfReader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
from langchain.vectorstores import FAISS
from langchain.chat_models import ChatOpenAI
from langcha... | import streamlit as st
from dotenv import load_dotenv
from PyPDF2 import PdfReader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
from langchain.vectorstores import FAISS
from langchain.chat_models import ChatOpenAI
from langcha... | load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs",
page_icon=":books:")
st.write(css, unsafe_allow_html=True)
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.sess... | load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs",
page_icon=":books:")
st.write(css, unsafe_allow_html=True)
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.sess... | 90 | 718 | 382 | 1,100 | import streamlit as st
from dotenv import load_dotenv
from PyPDF2 import PdfReader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
from langchain.vectorstores import FAISS
from langchain.chat_models import ChatOpenAI
from langcha... | import streamlit as st
from dotenv import load_dotenv
from PyPDF2 import PdfReader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
from langchain.vectorstores import FAISS
from langchain.chat_models import ChatOpenAI
from langcha... | |
44,208 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/benchmarks/benchmark_funcs.py | 23,24 | 1,56 | benchmark_is_constant | 27,54 | 24,54 | # -*- coding: utf-8 -*-
#
# Benchmark various approaches to functions to speed things up.
# ... hopefully.
import numpy as np
import time
def _do_time(func, n_iter=10, *args, **kwargs):
times = []
for _ in range(n_iter):
start = time.time()
func(*args, **kwargs)
times.append(time.tim... | # -*- coding: utf-8 -*-
#
# Benchmark various approaches to functions to speed things up.
# ... hopefully.
import numpy as np
import time
def _do_time(func, n_iter=10, *args, **kwargs):
times = []
for _ in range(n_iter):
start = time.time()
func(*args, **kwargs)
times.append(time.tim... | # WINNER!
def is_const1(x):
"""This is the version in Pyramid 0.6.2.
Parameters
----------
x : np.ndarray
This is the array.
"""
return (x == x[0]).all()
def is_const2(x):
"""This should ostensibly only take O(N) rather than O(2N) like
... | """This benchmarks the "is_constant" function from ``pmdarima.arima.utils``
This was added in 0.6.2.
"""
# WINNER!
def is_const1(x):
"""This is the version in Pyramid 0.6.2.
Parameters
----------
x : np.ndarray
This is the array.
"""
retur... | 67 | 255 | 259 | 514 | # -*- coding: utf-8 -*-
#
# Benchmark various approaches to functions to speed things up.
# ... hopefully.
import numpy as np
import time
def _do_time(func, n_iter=10, *args, **kwargs):
times = []
for _ in range(n_iter):
start = time.time()
func(*args, **kwargs)
times.append(time.tim... | # -*- coding: utf-8 -*-
#
# Benchmark various approaches to functions to speed things up.
# ... hopefully.
import numpy as np
import time
def _do_time(func, n_iter=10, *args, **kwargs):
times = []
for _ in range(n_iter):
start = time.time()
func(*args, **kwargs)
times.append(time.tim... | |
44,209 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/build_tools/get_tag.py | 12,13 | 1,36 | get_version_from_tag | 14,18 | 13,18 | import os
from os.path import abspath, dirname
# This file assumes that our tags are always in this format: vX.X.X.
# In that case, we would only want to write X.X.X
TOP_LEVEL = abspath(dirname(dirname(__file__)))
OUT_FILE = os.path.join(TOP_LEVEL, 'pmdarima', 'VERSION')
DEFAULT_TAG = '0.0.0'
def get_version_from_t... | import os
from os.path import abspath, dirname
# This file assumes that our tags are always in this format: vX.X.X.
# In that case, we would only want to write X.X.X
TOP_LEVEL = abspath(dirname(dirname(__file__)))
OUT_FILE = os.path.join(TOP_LEVEL, 'pmdarima', 'VERSION')
DEFAULT_TAG = '0.0.0'
def get_version_from_t... | return tag[1:] if tag.startswith('v') else tag
# Circle is easy, since they give us the git tag
| """Handles 1.5.0 or v1.5.0"""
return tag[1:] if tag.startswith('v') else tag
# Circle is easy, since they give us the git tag
| 17 | 445 | 38 | 483 | import os
from os.path import abspath, dirname
# This file assumes that our tags are always in this format: vX.X.X.
# In that case, we would only want to write X.X.X
TOP_LEVEL = abspath(dirname(dirname(__file__)))
OUT_FILE = os.path.join(TOP_LEVEL, 'pmdarima', 'VERSION')
DEFAULT_TAG = '0.0.0'
def get_version_from_t... | import os
from os.path import abspath, dirname
# This file assumes that our tags are always in this format: vX.X.X.
# In that case, we would only want to write X.X.X
TOP_LEVEL = abspath(dirname(dirname(__file__)))
OUT_FILE = os.path.join(TOP_LEVEL, 'pmdarima', 'VERSION')
DEFAULT_TAG = '0.0.0'
def get_version_from_t... | |
44,210 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/build_tools/github/get_latest_dependencies.py | 12,13 | 1,43 | find_latest_dependencies | 25,39 | 13,39 | """This script reads our requirements.txt file and removes the pinned versions"""
import re
import os
from os.path import abspath, dirname
TOP_LEVEL = abspath(dirname(dirname(dirname(__file__))))
REQUIREMENTS = os.path.join(TOP_LEVEL, 'requirements.txt')
BUILD_REQUIREMENTS = os.path.join(TOP_LEVEL, 'build_tools', 'bu... | """This script reads our requirements.txt file and removes the pinned versions"""
import re
import os
from os.path import abspath, dirname
TOP_LEVEL = abspath(dirname(dirname(dirname(__file__))))
REQUIREMENTS = os.path.join(TOP_LEVEL, 'requirements.txt')
BUILD_REQUIREMENTS = os.path.join(TOP_LEVEL, 'build_tools', 'bu... | requirements = []
for requirements_file in requirements_files:
with open(requirements_file) as file:
for line in file:
requirement = line.strip()
if line.startswith('#'):
continue
match = re.match(r'^([A-Za-z\-0-9]+)', requi... | """Given one or more requirements.txt files, strip off any pinned versions
Parameters
----------
*requirements_files : str
One or more paths to requirements.txt files to parse
Returns
-------
requirements : list
List of parsed dependencies without their pinned versions
... | 33 | 283 | 136 | 419 | """This script reads our requirements.txt file and removes the pinned versions"""
import re
import os
from os.path import abspath, dirname
TOP_LEVEL = abspath(dirname(dirname(dirname(__file__))))
REQUIREMENTS = os.path.join(TOP_LEVEL, 'requirements.txt')
BUILD_REQUIREMENTS = os.path.join(TOP_LEVEL, 'build_tools', 'bu... | """This script reads our requirements.txt file and removes the pinned versions"""
import re
import os
from os.path import abspath, dirname
TOP_LEVEL = abspath(dirname(dirname(dirname(__file__))))
REQUIREMENTS = os.path.join(TOP_LEVEL, 'requirements.txt')
BUILD_REQUIREMENTS = os.path.join(TOP_LEVEL, 'build_tools', 'bu... | |
44,211 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/doc/sphinxext/github_link.py | 20,21 | 1,85 | _linkcode_resolve | 34,71 | 21,71 | from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except (subprocess.CalledProcessError, OSError... | from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except (subprocess.CalledProcessError, OSError... |
if revision is None:
return
if domain not in ('py', 'pyx'):
return
if not info.get('module') or not info.get('fullname'):
return
class_name = info['fullname'].split('.')[0]
if type(class_name) != str:
# Python 2 only
class_name = class_name.encode('utf-8')
... | """Determine a link to online source for a class/method/function
This is called by sphinx.ext.linkcode
An example with a long-untouched module that everyone has
>>> _linkcode_resolve('py', {'module': 'tty',
... 'fullname': 'setraw'},
... package='tty'... | 83 | 498 | 350 | 848 | from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except (subprocess.CalledProcessError, OSError... | from operator import attrgetter
import inspect
import subprocess
import os
import sys
from functools import partial
REVISION_CMD = 'git rev-parse --short HEAD'
def _get_git_revision():
try:
revision = subprocess.check_output(REVISION_CMD.split()).strip()
except (subprocess.CalledProcessError, OSError... | |
44,212 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/__check_build/_check_build.pyx | 1,2 | 1,3 | check_build | 2,3 | 2,3 | def check_build():
FILL_FUNC_BODY | def check_build():
FILL_FUNC_BODY | return
| return
| 1 | 16 | 4 | 20 | def check_build():
FILL_FUNC_BODY | def check_build():
FILL_FUNC_BODY | |
44,213 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/__check_build/setup.py | 8,9 | 1,21 | configuration | 9,18 | 9,18 | # Author: Virgile Fritsch <virgile.fritsch@inria.fr> (originally written
# for sklearn, adapted for pmdarima)
# License: BSD 3 clause
import numpy as np
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(t... | # Author: Virgile Fritsch <virgile.fritsch@inria.fr> (originally written
# for sklearn, adapted for pmdarima)
# License: BSD 3 clause
import numpy as np
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(t... | from numpy.distutils.misc_util import Configuration
config = Configuration('__check_build', parent_package, top_path)
config.add_extension('_check_build',
sources=['_check_build.pyx'],
include_dirs=[np.get_include()])
return config
| from numpy.distutils.misc_util import Configuration
config = Configuration('__check_build', parent_package, top_path)
config.add_extension('_check_build',
sources=['_check_build.pyx'],
include_dirs=[np.get_include()])
return config
| 14 | 125 | 91 | 216 | # Author: Virgile Fritsch <virgile.fritsch@inria.fr> (originally written
# for sklearn, adapted for pmdarima)
# License: BSD 3 clause
import numpy as np
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(t... | # Author: Virgile Fritsch <virgile.fritsch@inria.fr> (originally written
# for sklearn, adapted for pmdarima)
# License: BSD 3 clause
import numpy as np
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(t... | |
44,214 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/_build_utils/pre_build_helpers.py | 18,19 | 1,78 | compile_test_program | 20,68 | 19,68 | """
Helpers to check build environment before actual build of pmdarima
Adapted from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_build_utils/pre_build_helpers.py
""" # noqa
import os
import sys
import glob
import tempfile
import textwrap
import subprocess
from distutils.sysconfig import custom... | """
Helpers to check build environment before actual build of pmdarima
Adapted from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_build_utils/pre_build_helpers.py
""" # noqa
import os
import sys
import glob
import tempfile
import textwrap
import subprocess
from distutils.sysconfig import custom... | ccompiler = new_compiler()
customize_compiler(ccompiler)
# extra_(pre/post)args can be a callable to make it possible to get its
# value from the compiler
if callable(extra_preargs):
extra_preargs = extra_preargs(ccompiler)
if callable(extra_postargs):
extra_postargs = extra_pos... | """Check that some C code can be compiled and run"""
ccompiler = new_compiler()
customize_compiler(ccompiler)
# extra_(pre/post)args can be a callable to make it possible to get its
# value from the compiler
if callable(extra_preargs):
extra_preargs = extra_preargs(ccompiler)
if cal... | 118 | 243 | 489 | 732 | """
Helpers to check build environment before actual build of pmdarima
Adapted from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_build_utils/pre_build_helpers.py
""" # noqa
import os
import sys
import glob
import tempfile
import textwrap
import subprocess
from distutils.sysconfig import custom... | """
Helpers to check build environment before actual build of pmdarima
Adapted from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/_build_utils/pre_build_helpers.py
""" # noqa
import os
import sys
import glob
import tempfile
import textwrap
import subprocess
from distutils.sysconfig import custom... | |
44,216 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/_auto_solvers.py | 120,121 | 62,142 | solve | _RandomFitWrapper | 122,142 | 121,142 | class _RandomFitWrapper(_SolverMixin):
"""Searches for the best model using a random search"""
def __init__(self, y, X, fit_partial, d, D, m, max_order,
max_p, max_q, max_P, max_Q, random, random_state,
n_fits, n_jobs, seasonal, trace, with_intercept,
sarimax_... | class _RandomFitWrapper(_SolverMixin):
"""Searches for the best model using a random search"""
def __init__(self, y, X, fit_partial, d, D, m, max_order,
max_p, max_q, max_P, max_Q, random, random_state,
n_fits, n_jobs, seasonal, trace, with_intercept,
sarimax_... | fit_partial = self.fit_partial
n_jobs = self.n_jobs
gen = self.gen
# get results in parallel
all_res = Parallel(n_jobs=n_jobs)(
delayed(fit_partial)(
order=order,
seasonal_order=seasonal_order,
)
for order, seas... | """Do a random search"""
fit_partial = self.fit_partial
n_jobs = self.n_jobs
gen = self.gen
# get results in parallel
all_res = Parallel(n_jobs=n_jobs)(
delayed(fit_partial)(
order=order,
seasonal_order=seasonal_order,
... | 39 | 748 | 184 | 932 | # -*- coding: utf-8 -*-
#
# Methods for optimizing auto-arima
from numpy.linalg import LinAlgError
import numpy as np
from datetime import datetime
from joblib import Parallel, delayed
from sklearn.utils import check_random_state
import abc
import functools
import time
import warnings
import traceback
from .arima i... | # -*- coding: utf-8 -*-
#
# Methods for optimizing auto-arima
from numpy.linalg import LinAlgError
import numpy as np
from datetime import datetime
from joblib import Parallel, delayed
from sklearn.utils import check_random_state
import abc
import functools
import time
import warnings
import traceback
from .arima i... |
44,218 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/_context.py | 68,69 | 33,87 | values | AbstractContext | 69,71 | 69,71 | class AbstractContext(ABC):
"""An abstract context manager to store execution context.
A generic, re-entrant, reusable context manager to store
execution context. Has helper methods to iterate over the context info
and provide a string representation of the context info.
"""
def __init__(self, ... | class AbstractContext(ABC):
"""An abstract context manager to store execution context.
A generic, re-entrant, reusable context manager to store
execution context. Has helper methods to iterate over the context info
and provide a string representation of the context info.
"""
def __init__(self, ... | return self.props.values()
| return self.props.values()
| 2 | 451 | 12 | 463 | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... |
44,219 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/_context.py | 216,218 | 98,234 | _remove_context | ContextStore | 224,234 | 218,234 | class ContextStore:
"""A class to wrap access to the global context store
This class hosts static methods to wrap access to and encapsulate the
singleton content store instance
"""
@staticmethod
def get_context(context_type):
"""Returns most recently added instance of given Context Type... | class ContextStore:
"""A class to wrap access to the global context store
This class hosts static methods to wrap access to and encapsulate the
singleton content store instance
"""
@staticmethod
def get_context(context_type):
"""Returns most recently added instance of given Context Type... | if not isinstance(ctx, AbstractContext):
raise ValueError('ctx must be be an instance of AbstractContext')
context_type = ctx.get_type()
if context_type not in _ctx.store or \
len(_ctx.store[context_type]) == 0:
return
_ctx.store[context_type].p... | """Removes the most recently added context of given Context Type
This private member is only used by ``AbstractContext``
:param ctx:
:return: None
"""
if not isinstance(ctx, AbstractContext):
raise ValueError('ctx must be be an instance of AbstractContext')
... | 28 | 1,084 | 98 | 1,182 | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... |
44,220 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/_context.py | 93,94 | 87,98 | get_type | _emptyContext | 95,98 | 94,98 | class _emptyContext(AbstractContext):
"""An empty context for convenience use"""
def __init__(self):
super(_emptyContext, self).__init__()
def get_type(self):
FILL_FUNC_BODY | class _emptyContext(AbstractContext):
"""An empty context for convenience use"""
def __init__(self):
super(_emptyContext, self).__init__()
def get_type(self):
"""Indicates we are not in a context manager"""
FILL_FUNC_BODY | return ContextType.EMPTY
| """Indicates we are not in a context manager"""
return ContextType.EMPTY
| 2 | 75 | 14 | 89 | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... | # -*- coding: utf-8 -*-
#
# Author: Krishna Sunkara (kpsunkara)
#
# Re-entrant, reusable context manager to store execution context. Introduced
# in pmdarima 1.5.0 (see #221), redesigned not to use thread locals in #273
# (see #275 for context).
from abc import ABC, abstractmethod
from enum import Enum
import collecti... |
44,221 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/_validation.py | 106,107 | 1,155 | get_scoring_metric | 122,143 | 107,143 | # -*- coding: utf-8 -*-
"""
Arg validation for auto-arima calls. This allows us to test validation more
directly without having to fit numerous combinations of models.
"""
import numpy as np
import warnings
from sklearn import metrics
from pmdarima.warnings import ModelFitWarning
# The valid information criteria
VA... | # -*- coding: utf-8 -*-
"""
Arg validation for auto-arima calls. This allows us to test validation more
directly without having to fit numerous combinations of models.
"""
import numpy as np
import warnings
from sklearn import metrics
from pmdarima.warnings import ModelFitWarning
# The valid information criteria
VA... | if isinstance(metric, str):
# XXX: legacy support, remap mse/mae to their long versions
if metric == "mse":
return metrics.mean_squared_error
if metric == "mae":
return metrics.mean_absolute_error
try:
return getattr(metrics, metric)
exce... | """Get a scoring metric by name, or passthrough a callable
Parameters
----------
metric : str or callable
A name of a scoring metric, or a custom callable function. If it is a
callable, it must adhere to the signature::
def func(y_true, y_pred)
Note that the ARIMA ... | 70 | 1,321 | 199 | 1,520 | # -*- coding: utf-8 -*-
"""
Arg validation for auto-arima calls. This allows us to test validation more
directly without having to fit numerous combinations of models.
"""
import numpy as np
import warnings
from sklearn import metrics
from pmdarima.warnings import ModelFitWarning
# The valid information criteria
VA... | # -*- coding: utf-8 -*-
"""
Arg validation for auto-arima calls. This allows us to test validation more
directly without having to fit numerous combinations of models.
"""
import numpy as np
import warnings
from sklearn import metrics
from pmdarima.warnings import ModelFitWarning
# The valid information criteria
VA... | |
44,224 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/auto.py | 326,327 | 273,330 | get_type | StepwiseContext | 327,330 | 327,330 | class StepwiseContext(AbstractContext):
"""Context manager to capture runtime context for stepwise mode.
``StepwiseContext`` allows one to call :func:`auto_arima` in the context
of a runtime configuration that offers additional level of
control required in certain scenarios. Use cases that are either
... | class StepwiseContext(AbstractContext):
"""Context manager to capture runtime context for stepwise mode.
``StepwiseContext`` allows one to call :func:`auto_arima` in the context
of a runtime configuration that offers additional level of
control required in certain scenarios. Use cases that are either
... | return ContextType.STEPWISE
| return ContextType.STEPWISE
| 2 | 623 | 15 | 638 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Automatically find optimal parameters for an ARIMA
import numpy as np
from sklearn.linear_model import LinearRegression
import functools
import time
import warnings
from ..base import BaseARIMA
from . import _doc
from . import _vali... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Automatically find optimal parameters for an ARIMA
import numpy as np
from sklearn.linear_model import LinearRegression
import functools
import time
import warnings
from ..base import BaseARIMA
from . import _doc
from . import _vali... |
44,225 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/arima/setup.py | 11,12 | 1,41 | configuration | 12,38 | 12,38 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("arima", parent_package, top_path)
config.add_extension("_arima",
... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("arima", parent_package, top_path)
config.add_extension("_arima",
... | 51 | 116 | 274 | 390 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | |
44,227 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/base.py | 20,21 | 13,66 | fit_predict | BaseARIMA | 47,54 | 21,54 | class BaseARIMA(BaseEstimator, metaclass=ABCMeta):
"""A base ARIMA class"""
@abc.abstractmethod
def fit(self, y, X, **fit_args):
"""Fit an ARIMA model"""
def fit_predict(self, y, X=None, n_periods=10, **fit_args):
FILL_FUNC_BODY @abc.abstractmethod
def predict(self, n_periods, X, return... | class BaseARIMA(BaseEstimator, metaclass=ABCMeta):
"""A base ARIMA class"""
@abc.abstractmethod
def fit(self, y, X, **fit_args):
"""Fit an ARIMA model"""
def fit_predict(self, y, X=None, n_periods=10, **fit_args):
"""Fit an ARIMA to a vector, ``y``, of observations with an
opti... | self.fit(y, X, **fit_args)
# TODO: remove kwargs from call
return self.predict(n_periods=n_periods, X=X, **fit_args)
# TODO: remove kwargs from all of these
| """Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables, and then generate
predictions.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The time-series to which to fit the ``ARIMA`` estimator... | 21 | 559 | 75 | 634 | # -*- coding: utf-8 -*-
#
# Base classes and interfaces
import abc
from abc import ABCMeta
from sklearn.base import BaseEstimator
# TODO: change this to base TS model if we ever hope to support more
class BaseARIMA(BaseEstimator, metaclass=ABCMeta):
"""A base ARIMA class"""
@abc.abstractmethod
def fit... | # -*- coding: utf-8 -*-
#
# Base classes and interfaces
import abc
from abc import ABCMeta
from sklearn.base import BaseEstimator
# TODO: change this to base TS model if we ever hope to support more
class BaseARIMA(BaseEstimator, metaclass=ABCMeta):
"""A base ARIMA class"""
@abc.abstractmethod
def fit... |
44,228 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/compat/statsmodels.py | 37,38 | 1,66 | check_seasonal_order | 49,64 | 38,64 | # -*- coding: utf-8 -*-
#
# Handle inconsistencies in the statsmodels API versions
from collections.abc import Iterable
from packaging.version import Version
import statsmodels as sm
__all__ = [
'bind_df_model'
]
_sm_version = sm.__version__
def bind_df_model(model_fit, arima_results):
"""Set model degrees... | # -*- coding: utf-8 -*-
#
# Handle inconsistencies in the statsmodels API versions
from collections.abc import Iterable
from packaging.version import Version
import statsmodels as sm
__all__ = [
'bind_df_model'
]
_sm_version = sm.__version__
def bind_df_model(model_fit, arima_results):
"""Set model degrees... |
# If order[0] is an iterable, but not a string then we don't perform check.
# Otherwise we perform the check and override order if it satisfies check.
# See issue#370: https://github.com/alkaline-ml/pmdarima/issues/370
if isinstance(order[0], Iterable) and not isinstance(order[0], str):
return ... | """Check the seasonal order
Statsmodels 0.11.0 introduced a check for seasonal order == 1 that can
raise a ValueError, but some of our old defaults allow for m == 1 in an
otherwise null seasonal order.
Parameters
----------
order : tuple
The existing seasonal order
"""
# I... | 72 | 428 | 188 | 616 | # -*- coding: utf-8 -*-
#
# Handle inconsistencies in the statsmodels API versions
from collections.abc import Iterable
from packaging.version import Version
import statsmodels as sm
__all__ = [
'bind_df_model'
]
_sm_version = sm.__version__
def bind_df_model(model_fit, arima_results):
"""Set model degrees... | # -*- coding: utf-8 -*-
#
# Handle inconsistencies in the statsmodels API versions
from collections.abc import Iterable
from packaging.version import Version
import statsmodels as sm
__all__ = [
'bind_df_model'
]
_sm_version = sm.__version__
def bind_df_model(model_fit, arima_results):
"""Set model degrees... | |
44,229 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/context_managers.py | 8,10 | 1,40 | except_and_reraise | 27,40 | 10,40 | # -*- coding: utf-8 -*-
import contextlib
__all__ = ['except_and_reraise']
@contextlib.contextmanager
def except_and_reraise(*except_errs, raise_err=None, raise_msg=None):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import contextlib
__all__ = ['except_and_reraise']
@contextlib.contextmanager
def except_and_reraise(*except_errs, raise_err=None, raise_msg=None):
"""Catch a lower-level error and re-raise with a more meaningful message
In some cases, Numpy linalg errors can be raised in perplexing... | if raise_err is None:
raise TypeError("raise_err must be used as a key-word arg")
if raise_msg is None:
raise TypeError("raise_msg must be used as a key-word arg")
try:
yield
except except_errs as e:
message = "%s (raised from %s: %s)" \
% (raise_msg,
... | """Catch a lower-level error and re-raise with a more meaningful message
In some cases, Numpy linalg errors can be raised in perplexing spots. This
allows us to catch the lower-level errors in spots where we are aware of
them so that we may raise with a more meaningful message.
Parameters
----... | 46 | 218 | 137 | 355 | # -*- coding: utf-8 -*-
import contextlib
__all__ = ['except_and_reraise']
@contextlib.contextmanager
def except_and_reraise(*except_errs, raise_err=None, raise_msg=None):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import contextlib
__all__ = ['except_and_reraise']
@contextlib.contextmanager
def except_and_reraise(*except_errs, raise_err=None, raise_msg=None):
"""Catch a lower-level error and re-raise with a more meaningful message
In some cases, Numpy linalg errors can be raised in perplexing... | |
44,230 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/_base.py | 70,71 | 1,86 | _load_tarfile | 72,79 | 71,79 | # -*- coding: utf-8 -*-
import os
from os.path import abspath, dirname, join, expanduser
import numpy as np
import pandas as pd
import urllib3
import tarfile
from ..compat.numpy import DTYPE
# caches anything read from disk to avoid re-reads
_cache = {}
http = urllib3.PoolManager()
def get_data_path():
"""Get ... | # -*- coding: utf-8 -*-
import os
from os.path import abspath, dirname, join, expanduser
import numpy as np
import pandas as pd
import urllib3
import tarfile
from ..compat.numpy import DTYPE
# caches anything read from disk to avoid re-reads
_cache = {}
http = urllib3.PoolManager()
def get_data_path():
"""Get ... | base_path = abspath(dirname(__file__))
file_path = join(base_path, "data", key)
with tarfile.open(file_path, "r:*") as tar:
csv_path = tar.getnames()[0] # there is only one file per tar
return pd.read_csv(tar.extractfile(csv_path), header=0)
| """Internal method for loading a tar file"""
base_path = abspath(dirname(__file__))
file_path = join(base_path, "data", key)
with tarfile.open(file_path, "r:*") as tar:
csv_path = tar.getnames()[0] # there is only one file per tar
return pd.read_csv(tar.extractfile(csv_path), header=0)
... | 27 | 705 | 110 | 815 | # -*- coding: utf-8 -*-
import os
from os.path import abspath, dirname, join, expanduser
import numpy as np
import pandas as pd
import urllib3
import tarfile
from ..compat.numpy import DTYPE
# caches anything read from disk to avoid re-reads
_cache = {}
http = urllib3.PoolManager()
def get_data_path():
"""Get ... | # -*- coding: utf-8 -*-
import os
from os.path import abspath, dirname, join, expanduser
import numpy as np
import pandas as pd
import urllib3
import tarfile
from ..compat.numpy import DTYPE
# caches anything read from disk to avoid re-reads
_cache = {}
http = urllib3.PoolManager()
def get_data_path():
"""Get ... | |
44,231 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/airpassengers.py | 13,14 | 1,89 | load_airpassengers | 71,89 | 14,89 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_airpassengers'
]
def load_airpassengers(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_airpassengers'
]
def load_airpassengers(as_series=False, dtype=DTYPE):
"""Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passenge... | rslt = np.array([
112, 118, 132, 129, 121, 135, 148, 148, 136, 119, 104, 118,
115, 126, 141, 135, 125, 149, 170, 170, 158, 133, 114, 140,
145, 150, 178, 163, 172, 178, 199, 199, 184, 162, 146, 166,
171, 180, 193, 181, 183, 218, 230, 242, 209, 191, 172, 194,
196, 196, 236, 235... | """Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passengers, 1949 to 1960.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If False, will return a 1d
numpy array.
... | 154 | 1,221 | 794 | 2,015 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_airpassengers'
]
def load_airpassengers(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_airpassengers'
]
def load_airpassengers(as_series=False, dtype=DTYPE):
"""Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passenge... | |
44,234 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/gasoline.py | 15,16 | 1,71 | load_gasoline | 65,71 | 16,71 | # -*- coding: utf-8 -*-
import pandas as pd
from ..compat.numpy import DTYPE
from ._base import fetch_from_web_or_disk
__all__ = [
'load_gasoline'
]
url = 'http://alkaline-ml.com/datasets/gasoline.csv'
def load_gasoline(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import pandas as pd
from ..compat.numpy import DTYPE
from ._base import fetch_from_web_or_disk
__all__ = [
'load_gasoline'
]
url = 'http://alkaline-ml.com/datasets/gasoline.csv'
def load_gasoline(as_series=False, dtype=DTYPE):
"""Weekly US finished motor gasoline products
A we... | """ # noqa
rslt = fetch_from_web_or_disk(url, 'gasoline', cache=True).astype(dtype)
if not as_series:
return rslt
return pd.Series(rslt)
| """Weekly US finished motor gasoline products
A weekly time series of US finished motor gasoline products supplied (in
thousands of barrels per day) from February 1991 to May 2005.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If Tr... | 15 | 690 | 72 | 762 | # -*- coding: utf-8 -*-
import pandas as pd
from ..compat.numpy import DTYPE
from ._base import fetch_from_web_or_disk
__all__ = [
'load_gasoline'
]
url = 'http://alkaline-ml.com/datasets/gasoline.csv'
def load_gasoline(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import pandas as pd
from ..compat.numpy import DTYPE
from ._base import fetch_from_web_or_disk
__all__ = [
'load_gasoline'
]
url = 'http://alkaline-ml.com/datasets/gasoline.csv'
def load_gasoline(as_series=False, dtype=DTYPE):
"""Weekly US finished motor gasoline products
A we... | |
44,236 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/lynx.py | 17,18 | 1,94 | load_lynx | 75,94 | 18,94 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the lynx dataset found in R.
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_lynx'
]
def load_lynx(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the lynx dataset found in R.
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_lynx'
]
def load_lynx(as_series=False, dtype=DTYPE):
"""Annual numbers of lynx trappings for 1821–1934... | """ # noqa: E501
rslt = np.array([269, 321, 585, 871, 1475, 2821, 3928, 5943, 4950,
2577, 523, 98, 184, 279, 409, 2285, 2685, 3409,
1824, 409, 151, 45, 68, 213, 546, 1033, 2129,
2536, 957, 361, 377, 225, 360, 731, 1638, 2725,
2... | """Annual numbers of lynx trappings for 1821–1934 in Canada.
This time-series records the number of skins of predators (lynx) that were
collected over several years by the Hudson's Bay Company. The dataset was
taken from Brockwell & Davis (1991) and appears to be the series
considered by Campbell &... | 134 | 1,240 | 722 | 1,962 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the lynx dataset found in R.
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_lynx'
]
def load_lynx(as_series=False, dtype=DTYPE):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the lynx dataset found in R.
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_lynx'
]
def load_lynx(as_series=False, dtype=DTYPE):
"""Annual numbers of lynx trappings for 1821–1934... | |
44,237 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/setup.py | 4,5 | 1,16 | configuration | 5,13 | 5,13 | # -*- coding: utf-8 -*-
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| # -*- coding: utf-8 -*-
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| from numpy.distutils.misc_util import Configuration
config = Configuration('datasets', parent_package, top_path)
config.add_data_dir('data')
config.add_subpackage('tests')
return config
| from numpy.distutils.misc_util import Configuration
config = Configuration('datasets', parent_package, top_path)
config.add_data_dir('data')
config.add_subpackage('tests')
return config
| 13 | 80 | 71 | 151 | # -*- coding: utf-8 -*-
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| # -*- coding: utf-8 -*-
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| |
44,238 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/stocks.py | 8,9 | 1,33 | load_msft | 31,33 | 9,33 | # -*- coding: utf-8 -*-
from ._base import _load_tarfile
__all__ = ['load_msft']
def load_msft():
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
from ._base import _load_tarfile
__all__ = ['load_msft']
def load_msft():
"""Load the microsoft stock data
Financial data for the MSFT stock between the dates of Mar 13, 1986 and
Nov 10, 2017. This data is part of the Kaggle stock dataset [1]. Features
are as follows:
... | """ # noqa:E501
return _load_tarfile("msft.tar.gz")
| """Load the microsoft stock data
Financial data for the MSFT stock between the dates of Mar 13, 1986 and
Nov 10, 2017. This data is part of the Kaggle stock dataset [1]. Features
are as follows:
* Date : datetime
* Open : float32
* High : float32
* Low : float32
... | 5 | 267 | 31 | 298 | # -*- coding: utf-8 -*-
from ._base import _load_tarfile
__all__ = ['load_msft']
def load_msft():
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
from ._base import _load_tarfile
__all__ = ['load_msft']
def load_msft():
"""Load the microsoft stock data
Financial data for the MSFT stock between the dates of Mar 13, 1986 and
Nov 10, 2017. This data is part of the Kaggle stock dataset [1]. Features
are as follows:
... | |
44,239 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/datasets/sunspots.py | 21,22 | 1,86 | load_sunspots | 65,86 | 22,86 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the sunspots dataset found in R.
import numpy as np
import pandas as pd
from os.path import join
import calendar
from ..compat import DTYPE
from . import _base as base
__all__ = [
'load_sunspots'
]
def load_sunspots(as... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the sunspots dataset found in R.
import numpy as np
import pandas as pd
from os.path import join
import calendar
from ..compat import DTYPE
from . import _base as base
__all__ = [
'load_sunspots'
]
def load_sunspots(as... | """ # noqa: E501
rslt = base._cache.get('sunspots', None)
if rslt is None:
data_path = join(base.get_data_path(), 'sunspots.txt.gz')
rslt = np.loadtxt(data_path).ravel()
base._cache['sunspots'] = rslt
# don't want to cache type conversion
rslt = rslt.astype(dtype)
if n... | """Monthly Sunspot Numbers, 1749 - 1983
Monthly mean relative sunspot numbers from 1749 to 1983. Collected at Swiss
Federal Observatory, Zurich until 1960, then Tokyo Astronomical
Observatory.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pand... | 73 | 615 | 252 | 867 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the sunspots dataset found in R.
import numpy as np
import pandas as pd
from os.path import join
import calendar
from ..compat import DTYPE
from . import _base as base
__all__ = [
'load_sunspots'
]
def load_sunspots(as... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the sunspots dataset found in R.
import numpy as np
import pandas as pd
from os.path import join
import calendar
from ..compat import DTYPE
from . import _base as base
__all__ = [
'load_sunspots'
]
def load_sunspots(as... | |
44,243 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/decorators.py | 9,10 | 1,44 | deprecated | 23,44 | 10,44 | # -*- coding: utf-8 -*-
import functools
import warnings
__all__ = ['deprecated']
def deprecated(use_instead, notes=None):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import functools
import warnings
__all__ = ['deprecated']
def deprecated(use_instead, notes=None):
"""Mark functions as deprecated.
This decorator will result in a warning being emitted when the decorated
function is used.
Parameters
----------
use_instead : str
... | if notes is None:
notes = ""
else:
notes = " " + notes
def wrapped_func(func):
@functools.wraps(func)
def _inner(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # un-filter
msg = ("{0} is deprecated and will be removed in a futu... | """Mark functions as deprecated.
This decorator will result in a warning being emitted when the decorated
function is used.
Parameters
----------
use_instead : str
The name of the function to use instead.
notes : str, optional (default=None)
Additional notes to add to the ... | 61 | 142 | 218 | 360 | # -*- coding: utf-8 -*-
import functools
import warnings
__all__ = ['deprecated']
def deprecated(use_instead, notes=None):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
import functools
import warnings
__all__ = ['deprecated']
def deprecated(use_instead, notes=None):
"""Mark functions as deprecated.
This decorator will result in a warning being emitted when the decorated
function is used.
Parameters
----------
use_instead : str
... | |
44,244 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/metrics.py | 9,10 | 1,60 | smape | 10,60 | 10,60 | # -*- coding: utf-8 -*-
from .utils import check_endog
import numpy as np
__all__ = ['smape']
def smape(y_true, y_pred):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
from .utils import check_endog
import numpy as np
__all__ = ['smape']
def smape(y_true, y_pred):
FILL_FUNC_BODY | r"""Compute the Symmetric Mean Absolute Percentage Error.
The symmetric mean absolute percentage error (SMAPE) is an accuracy measure
based on percentage (or relative) errors. Defined as follows:
:math:`\frac{100\%}{n}\sum_{t=1}^{n}{\frac{|F_{t}-A_{t}|}{
(|A_{t}|+|F_{t}|)/2}}`
Where a... | r"""Compute the Symmetric Mean Absolute Percentage Error.
The symmetric mean absolute percentage error (SMAPE) is an accuracy measure
based on percentage (or relative) errors. Defined as follows:
:math:`\frac{100\%}{n}\sum_{t=1}^{n}{\frac{|F_{t}-A_{t}|}{
(|A_{t}|+|F_{t}|)/2}}`
Where a... | 147 | 64 | 656 | 720 | # -*- coding: utf-8 -*-
from .utils import check_endog
import numpy as np
__all__ = ['smape']
def smape(y_true, y_pred):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
from .utils import check_endog
import numpy as np
__all__ = ['smape']
def smape(y_true, y_pred):
FILL_FUNC_BODY | |
44,246 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/model_selection/_split.py | 92,93 | 72,133 | split | BaseTSCrossValidator | 111,118 | 93,118 | class BaseTSCrossValidator(BaseEstimator, metaclass=abc.ABCMeta):
"""Base class for time series cross validators
Based on the scikit-learn base cross-validator with alterations to fit the
time series interface.
"""
def __init__(self, h, step):
if h < 1:
raise ValueError("h must ... | class BaseTSCrossValidator(BaseEstimator, metaclass=abc.ABCMeta):
"""Base class for time series cross validators
Based on the scikit-learn base cross-validator with alterations to fit the
time series interface.
"""
def __init__(self, h, step):
if h < 1:
raise ValueError("h must ... | y, X = indexable(y, X)
indices = np.arange(y.shape[0])
for train_index, test_index in self._iter_train_test_masks(y, X):
train_index = indices[train_index]
test_index = indices[test_index]
yield train_index, test_index
| """Generate indices to split data into training and test sets
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The time-series array.
X : array-like, shape=[n_obs, n_vars], optional (default=None)
An optional 2-d array of exogenous va... | 23 | 504 | 96 | 600 | # -*- coding: utf-8 -*-
import abc
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import indexable
from sklearn.model_selection import train_test_split as tts
__all__ = [
'check_cv',
'train_test_split',
'RollingForecastCV',
'SlidingWindowForecastCV'
]
def tr... | # -*- coding: utf-8 -*-
import abc
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import indexable
from sklearn.model_selection import train_test_split as tts
__all__ = [
'check_cv',
'train_test_split',
'RollingForecastCV',
'SlidingWindowForecastCV'
]
def tr... |
44,248 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/model_selection/_split.py | 320,321 | 253,353 | _iter_train_test_indices | SlidingWindowForecastCV | 322,353 | 321,353 | class SlidingWindowForecastCV(BaseTSCrossValidator):
"""Use a sliding window to perform cross validation
This approach to CV slides a window over the training samples while using
several future samples as a test set. While similar to the
:class:`RollingForecastCV`, it differs in that the train set does... | class SlidingWindowForecastCV(BaseTSCrossValidator):
"""Use a sliding window to perform cross validation
This approach to CV slides a window over the training samples while using
several future samples as a test set. While similar to the
:class:`RollingForecastCV`, it differs in that the train set does... | n_samples = y.shape[0]
window_size = self.window_size
step = self.step
h = self.h
if window_size is not None:
if window_size + h > n_samples:
raise ValueError("The window_size + forecasting "
"horizon would exceed the ... | """Yields the train/test indices"""
n_samples = y.shape[0]
window_size = self.window_size
step = self.step
h = self.h
if window_size is not None:
if window_size + h > n_samples:
raise ValueError("The window_size + forecasting "
... | 101 | 1,068 | 306 | 1,374 | # -*- coding: utf-8 -*-
import abc
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import indexable
from sklearn.model_selection import train_test_split as tts
__all__ = [
'check_cv',
'train_test_split',
'RollingForecastCV',
'SlidingWindowForecastCV'
]
def tr... | # -*- coding: utf-8 -*-
import abc
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import indexable
from sklearn.model_selection import train_test_split as tts
__all__ = [
'check_cv',
'train_test_split',
'RollingForecastCV',
'SlidingWindowForecastCV'
]
def tr... |
44,252 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/base.py | 31,33 | 17,124 | _check_y_X | BaseTransformer | 34,53 | 33,53 | class BaseTransformer(BaseEstimator, TransformerMixin, metaclass=abc.ABCMeta):
"""A base pre-processing transformer
A subclass of the scikit-learn ``TransformerMixin``, the purpose of the
``BaseTransformer`` is to learn characteristics from the training set and
apply them in a transformation to the tes... | class BaseTransformer(BaseEstimator, TransformerMixin, metaclass=abc.ABCMeta):
"""A base pre-processing transformer
A subclass of the scikit-learn ``TransformerMixin``, the purpose of the
``BaseTransformer`` is to learn characteristics from the training set and
apply them in a transformation to the tes... | # Do not force finite, since a transformer's goal may be imputation.
if y is not None:
y = check_endog(
y,
dtype=DTYPE,
copy=True,
force_all_finite=False,
preserve_series=False,
)
if X is not... | """Validate input"""
# Do not force finite, since a transformer's goal may be imputation.
if y is not None:
y = check_endog(
y,
dtype=DTYPE,
copy=True,
force_all_finite=False,
preserve_series=False,
... | 42 | 806 | 150 | 956 | # -*- coding: utf-8 -*-
#
# Base ARIMA pre-processing classes. Don't import this in __init__, or we'll
# potentially get circular imports in sub-classes
from sklearn.base import BaseEstimator, TransformerMixin
import abc
from ..compat.numpy import DTYPE
from ..utils import check_exog, check_endog
__all__ = [
"Ba... | # -*- coding: utf-8 -*-
#
# Base ARIMA pre-processing classes. Don't import this in __init__, or we'll
# potentially get circular imports in sub-classes
from sklearn.base import BaseEstimator, TransformerMixin
import abc
from ..compat.numpy import DTYPE
from ..utils import check_exog, check_endog
__all__ = [
"Ba... |
44,253 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/base.py | 127,128 | 124,147 | _check_endog | UpdatableMixin | 128,133 | 128,133 | class UpdatableMixin:
"""Transformers that may update their params, like ARIMAs"""
def _check_endog(self, y):
FILL_FUNC_BODY def update_and_transform(self, y, X=None, **kwargs):
"""Update the params and return the transformed arrays
Parameters
----------
y : array-like or No... | class UpdatableMixin:
"""Transformers that may update their params, like ARIMAs"""
def _check_endog(self, y):
FILL_FUNC_BODY def update_and_transform(self, y, X=None, **kwargs):
"""Update the params and return the transformed arrays
Parameters
----------
y : array-like or No... | if y is None:
raise ValueError("endog array cannot be None when updating")
# TODO: remove default None value for X when we remove kwargs
| if y is None:
raise ValueError("endog array cannot be None when updating")
# TODO: remove default None value for X when we remove kwargs
| 24 | 176 | 46 | 222 | # -*- coding: utf-8 -*-
#
# Base ARIMA pre-processing classes. Don't import this in __init__, or we'll
# potentially get circular imports in sub-classes
from sklearn.base import BaseEstimator, TransformerMixin
import abc
from ..compat.numpy import DTYPE
from ..utils import check_exog, check_endog
__all__ = [
"Ba... | # -*- coding: utf-8 -*-
#
# Base ARIMA pre-processing classes. Don't import this in __init__, or we'll
# potentially get circular imports in sub-classes
from sklearn.base import BaseEstimator, TransformerMixin
import abc
from ..compat.numpy import DTYPE
from ..utils import check_exog, check_endog
__all__ = [
"Ba... |
44,254 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/endog/base.py | 11,12 | 8,42 | _check_y_X | BaseEndogTransformer | 13,18 | 12,18 | class BaseEndogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for endogenous array transformers"""
def _check_y_X(self, y, X):
FILL_FUNC_BODY @abc.abstractmethod
def inverse_transform(self, y, X=None):
"""Inverse transform a transformed array
Inverse the transforma... | class BaseEndogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for endogenous array transformers"""
def _check_y_X(self, y, X):
"""Check the endog and exog arrays"""
FILL_FUNC_BODY @abc.abstractmethod
def inverse_transform(self, y, X=None):
"""Inverse transform a tra... | y, X = super(BaseEndogTransformer, self)._check_y_X(y, X)
if y is None:
raise ValueError("y must be non-None for endogenous transformers")
return y, X
| """Check the endog and exog arrays"""
y, X = super(BaseEndogTransformer, self)._check_y_X(y, X)
if y is None:
raise ValueError("y must be non-None for endogenous transformers")
return y, X
| 21 | 276 | 65 | 341 | # -*- coding: utf-8 -*-
import abc
from ..base import BaseTransformer
class BaseEndogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for endogenous array transformers"""
def _check_y_X(self, y, X):
FILL_FUNC_BODY @abc.abstractmethod
def inverse_transform(self, y, X=None):
... | # -*- coding: utf-8 -*-
import abc
from ..base import BaseTransformer
class BaseEndogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for endogenous array transformers"""
def _check_y_X(self, y, X):
"""Check the endog and exog arrays"""
FILL_FUNC_BODY @abc.abstractmethod
... |
44,255 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/endog/boxcox.py | 82,83 | 14,167 | transform | BoxCoxEndogTransformer | 106,128 | 83,128 | class BoxCoxEndogTransformer(BaseEndogTransformer):
r"""Apply the Box-Cox transformation to an endogenous array
The Box-Cox transformation is applied to non-normal data to coerce it more
towards a normal distribution. It's specified as::
(((y + lam2) ** lam1) - 1) / lam1, if lmbda != 0, else
... | class BoxCoxEndogTransformer(BaseEndogTransformer):
r"""Apply the Box-Cox transformation to an endogenous array
The Box-Cox transformation is applied to non-normal data to coerce it more
towards a normal distribution. It's specified as::
(((y + lam2) ** lam1) - 1) / lam1, if lmbda != 0, else
... | check_is_fitted(self, "lam1_")
lam1 = self.lam1_
lam2 = self.lam2_
y, exog = self._check_y_X(y, X)
y += lam2
neg_mask = y <= 0.
if neg_mask.any():
action = self.neg_action
msg = "Negative or zero values present in y"
if actio... | """Transform the new array
Apply the Box-Cox transformation to the array after learning the
lambda parameter.
Parameters
----------
y : array-like or None, shape=(n_samples,)
The endogenous (time-series) array.
X : array-like or None, shape=(n_sampl... | 66 | 1,365 | 220 | 1,585 | # -*- coding: utf-8 -*-
from scipy import stats
import numpy as np
import warnings
from ...compat import check_is_fitted
from .base import BaseEndogTransformer
__all__ = ['BoxCoxEndogTransformer']
class BoxCoxEndogTransformer(BaseEndogTransformer):
r"""Apply the Box-Cox transformation to an endogenous array
... | # -*- coding: utf-8 -*-
from scipy import stats
import numpy as np
import warnings
from ...compat import check_is_fitted
from .base import BaseEndogTransformer
__all__ = ['BoxCoxEndogTransformer']
class BoxCoxEndogTransformer(BaseEndogTransformer):
r"""Apply the Box-Cox transformation to an endogenous array
... |
44,256 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/endog/log.py | 109,110 | 8,131 | get_params | LogEndogTransformer | 123,131 | 110,131 | class LogEndogTransformer(BoxCoxEndogTransformer):
"""Apply a log transformation to an endogenous array
When ``y`` is your endogenous array, the log transform is
``log(y + lmbda)``
Parameters
----------
lmbda : float, optional (default=0.)
The value to add to ``y`` to make it non-nega... | class LogEndogTransformer(BoxCoxEndogTransformer):
"""Apply a log transformation to an endogenous array
When ``y`` is your endogenous array, the log transform is
``log(y + lmbda)``
Parameters
----------
lmbda : float, optional (default=0.)
The value to add to ``y`` to make it non-nega... | # this method is shadowed because we shadow the the lmbda parameter
# name. Instead of setting lmbda, this transformer stores the parameter
# as lmbda2
# See: https://github.com/alkaline-ml/pmdarima/issues/407
# Thanks to @jseabold
params = super().get_params(deep=deep)
... | """Get parameters for this estimator.
Parameters
----------
deep : bool, default=True
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
... | 41 | 1,117 | 119 | 1,236 | # -*- coding: utf-8 -*-
from .boxcox import BoxCoxEndogTransformer
__all__ = ['LogEndogTransformer']
class LogEndogTransformer(BoxCoxEndogTransformer):
"""Apply a log transformation to an endogenous array
When ``y`` is your endogenous array, the log transform is
``log(y + lmbda)``
Parameters
-... | # -*- coding: utf-8 -*-
from .boxcox import BoxCoxEndogTransformer
__all__ = ['LogEndogTransformer']
class LogEndogTransformer(BoxCoxEndogTransformer):
"""Apply a log transformation to an endogenous array
When ``y`` is your endogenous array, the log transform is
``log(y + lmbda)``
Parameters
-... |
44,257 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/exog/base.py | 40,41 | 21,94 | _safe_hstack | BaseExogFeaturizer | 42,61 | 41,61 | class BaseExogFeaturizer(BaseExogTransformer, metaclass=abc.ABCMeta):
"""Transformers that create new exog features from the endog or exog array
Parameters
----------
prefix : str or None, optional (default=None)
The feature prefix
"""
def __init__(self, prefix=None):
self.prefi... | class BaseExogFeaturizer(BaseExogTransformer, metaclass=abc.ABCMeta):
"""Transformers that create new exog features from the endog or exog array
Parameters
----------
prefix : str or None, optional (default=None)
The feature prefix
"""
def __init__(self, prefix=None):
self.prefi... | if X is None or isinstance(X, pd.DataFrame):
# the features we're adding may be np.ndarray
if not isinstance(features, pd.DataFrame):
features = pd.DataFrame.from_records(features)
# subclass may override this
features.columns = self._get_feature_... | """H-stack dataframes or np.ndarrays"""
if X is None or isinstance(X, pd.DataFrame):
# the features we're adding may be np.ndarray
if not isinstance(features, pd.DataFrame):
features = pd.DataFrame.from_records(features)
# subclass may override this
... | 83 | 525 | 251 | 776 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import abc
from ..base import BaseTransformer
class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
"""Check the endog and ... | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import abc
from ..base import BaseTransformer
class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
"""Check the endog and ... |
44,258 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/exog/base.py | 13,14 | 10,21 | _check_y_X | BaseExogTransformer | 15,21 | 14,21 | class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
FILL_FUNC_BODY | class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
"""Check the endog and exog arrays"""
FILL_FUNC_BODY | y, X = super(BaseExogTransformer, self)._check_y_X(y, X)
if X is None and not null_allowed:
raise ValueError("X must be non-None for exog transformers")
return y, X
| """Check the endog and exog arrays"""
y, X = super(BaseExogTransformer, self)._check_y_X(y, X)
if X is None and not null_allowed:
raise ValueError("X must be non-None for exog transformers")
return y, X
| 24 | 81 | 71 | 152 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import abc
from ..base import BaseTransformer
class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
FILL_FUNC_BODYclass BaseExogFea... | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import abc
from ..base import BaseTransformer
class BaseExogTransformer(BaseTransformer, metaclass=abc.ABCMeta):
"""A base class for exogenous array transformers"""
def _check_y_X(self, y, X, null_allowed=False):
"""Check the endog and ... |
44,260 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/exog/dates.py | 130,131 | 23,201 | fit | DateFeaturizer | 142,156 | 131,156 | class DateFeaturizer(BaseExogFeaturizer):
"""Create exogenous date features
Given an exogenous feature of dtype TimeStamp, creates a set of dummy and
ordinal variables indicating:
* Day of the week
Particular days of the week may align with quasi-seasonal trends.
* Day of the month
... | class DateFeaturizer(BaseExogFeaturizer):
"""Create exogenous date features
Given an exogenous feature of dtype TimeStamp, creates a set of dummy and
ordinal variables indicating:
* Day of the week
Particular days of the week may align with quasi-seasonal trends.
* Day of the month
... | y, X = self._check_y_X(y, X, null_allowed=False)
# enforce pd.DataFrame
self._check_X(X)
# we don't _technically_ need to do this, but it seems like a nice bit
# of friendly validation to make sure that at least _something_ will
# happen in this transformer.
if ... | """Fit the transformer
Parameters
----------
y : array-like or None, shape=(n_samples,)
The endogenous (time-series) array.
X : array-like, shape=(n_samples, n_features)
The exogenous array of additional covariates. Must include the
``column_... | 58 | 1,885 | 158 | 2,043 | # -*- coding: utf-8 -*-
from .base import BaseExogFeaturizer
import numpy as np
import pandas as pd
import warnings
__all__ = [
"DateFeaturizer"
]
# TODO: future usecases might include with_hour_of_day
def _safe_hstack_numpy(left, right):
if left is None:
return right
return np.hstack([left, ... | # -*- coding: utf-8 -*-
from .base import BaseExogFeaturizer
import numpy as np
import pandas as pd
import warnings
__all__ = [
"DateFeaturizer"
]
# TODO: future usecases might include with_hour_of_day
def _safe_hstack_numpy(left, right):
if left is None:
return right
return np.hstack([left, ... |
44,261 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/exog/setup.py | 11,12 | 1,38 | configuration | 12,35 | 12,35 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("exog", parent_package, top_path)
config.add_extension("_fourier",
... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("exog", parent_package, top_path)
config.add_extension("_fourier",
... | 43 | 116 | 237 | 353 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | |
44,262 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/preprocessing/setup.py | 10,11 | 1,31 | configuration | 11,28 | 11,28 | # -*- coding: utf-8 -*-
import os
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
| # -*- coding: utf-8 -*-
import os
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
| cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("preprocessing", parent_package, top_path)
config.add_subpackage('end... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("preprocessing", parent_package, top_path)
config.add_subpackage('end... | 43 | 112 | 167 | 279 | # -*- coding: utf-8 -*-
import os
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
| # -*- coding: utf-8 -*-
import os
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
| |
44,263 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/setup.py | 14,15 | 1,55 | configuration | 15,52 | 15,52 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup for submodules of pmdarima
import os
import sys
from pmdarima._build_utils import cythonize_extensions
# DEFINE CONFIG
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from nump... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup for submodules of pmdarima
import os
import sys
from pmdarima._build_utils import cythonize_extensions
# DEFINE CONFIG
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from nump... | from numpy.distutils.misc_util import Configuration
libs = []
if os.name == 'posix':
libs.append('m')
config = Configuration('pmdarima', parent_package, top_path)
# build utilities
config.add_subpackage('__check_build')
config.add_subpackage('_build_utils')
# submodules that ... | from numpy.distutils.misc_util import Configuration
libs = []
if os.name == 'posix':
libs.append('m')
config = Configuration('pmdarima', parent_package, top_path)
# build utilities
config.add_subpackage('__check_build')
config.add_subpackage('_build_utils')
# submodules that ... | 97 | 147 | 383 | 530 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup for submodules of pmdarima
import os
import sys
from pmdarima._build_utils import cythonize_extensions
# DEFINE CONFIG
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from nump... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup for submodules of pmdarima
import os
import sys
from pmdarima._build_utils import cythonize_extensions
# DEFINE CONFIG
def configuration(parent_package='', top_path=None):
FILL_FUNC_BODYif __name__ == '__main__':
from nump... | |
44,264 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/utils/_show_versions.py | 52,53 | 1,104 | _get_deps_info | 60,92 | 53,92 | """
Utility methods to print system info for debugging
adapted from ``pandas.show_versions``
adapted from ``sklearn.show_versions``
"""
# License: BSD 3 clause
import platform
import sys
_pmdarima_deps = (
# setuptools needs to be before pip: https://github.com/pypa/setuptools/issues/3044#issuecomment-1024972548... | """
Utility methods to print system info for debugging
adapted from ``pandas.show_versions``
adapted from ``sklearn.show_versions``
"""
# License: BSD 3 clause
import platform
import sys
_pmdarima_deps = (
# setuptools needs to be before pip: https://github.com/pypa/setuptools/issues/3044#issuecomment-1024972548... | def get_version(module):
return module.__version__
deps_info = {}
# TODO: We can get rid of this when we deprecate 3.7
if sys.version_info.minor <= 7:
import importlib
for modname in deps:
try:
if modname in sys.modules:
mod = sy... | """Overview of the installed version of main dependencies
Returns
-------
deps_info: dict
version information on relevant Python libraries
"""
def get_version(module):
return module.__version__
deps_info = {}
# TODO: We can get rid of this when we deprecate 3.7
if ... | 76 | 539 | 286 | 825 | """
Utility methods to print system info for debugging
adapted from ``pandas.show_versions``
adapted from ``sklearn.show_versions``
"""
# License: BSD 3 clause
import platform
import sys
_pmdarima_deps = (
# setuptools needs to be before pip: https://github.com/pypa/setuptools/issues/3044#issuecomment-1024972548... | """
Utility methods to print system info for debugging
adapted from ``pandas.show_versions``
adapted from ``sklearn.show_versions``
"""
# License: BSD 3 clause
import platform
import sys
_pmdarima_deps = (
# setuptools needs to be before pip: https://github.com/pypa/setuptools/issues/3044#issuecomment-1024972548... | |
44,265 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/utils/metaestimators.py | 59,60 | 1,99 | if_has_delegate | 93,99 | 60,99 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Metaestimators for the ARIMA class. These classes are derived from the
# sklearn metaestimators, but adapted for more specific use with pmdarima.
from operator import attrgetter
from functools import update_wrapper
__all__ = [
'if... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Metaestimators for the ARIMA class. These classes are derived from the
# sklearn metaestimators, but adapted for more specific use with pmdarima.
from operator import attrgetter
from functools import update_wrapper
__all__ = [
'if... | if isinstance(delegate, list):
delegate = tuple(delegate)
if not isinstance(delegate, tuple):
delegate = (delegate,)
return lambda fn: _IffHasDelegate(fn, delegate)
| """Wrap a delegated instance attribute function.
Creates a decorator for methods that are delegated in the presence of a
results wrapper. This enables duck-typing by ``hasattr`` returning True
according to the sub-estimator.
This function was adapted from scikit-learn, which defines
``if_deleg... | 18 | 910 | 68 | 978 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Metaestimators for the ARIMA class. These classes are derived from the
# sklearn metaestimators, but adapted for more specific use with pmdarima.
from operator import attrgetter
from functools import update_wrapper
__all__ = [
'if... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Metaestimators for the ARIMA class. These classes are derived from the
# sklearn metaestimators, but adapted for more specific use with pmdarima.
from operator import attrgetter
from functools import update_wrapper
__all__ = [
'if... | |
44,266 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/utils/setup.py | 11,12 | 1,38 | configuration | 12,35 | 12,35 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("utils", parent_package, top_path)
config.add_extension("_array",
... | cblas_libs, blas_info = get_blas_info()
# Use this rather than cblas_libs so we don't fail on Windows
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration("utils", parent_package, top_path)
config.add_extension("_array",
... | 43 | 116 | 232 | 348 | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | # -*- coding: utf-8 -*-
import os
import numpy
from numpy.distutils.misc_util import Configuration
from pmdarima._build_utils import get_blas_info
def configuration(parent_package="", top_path=None):
FILL_FUNC_BODYif __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().tod... | |
44,267 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/pmdarima/utils/wrapped.py | 56,66 | 1,97 | acf | 66,77 | 66,77 | # -*- coding: utf-8 -*-
#
# Taylor G Smith <taylor.smith@alkaline.ml>
#
# Wrapped functions
from functools import wraps
import warnings
from statsmodels.tsa.stattools import acf as sm_acf, pacf as sm_pacf
__all__ = [
'acf',
'pacf'
]
# TODO: remove all explicit args/kwargs, making them *args, **kwargs
def i... | # -*- coding: utf-8 -*-
#
# Taylor G Smith <taylor.smith@alkaline.ml>
#
# Wrapped functions
from functools import wraps
import warnings
from statsmodels.tsa.stattools import acf as sm_acf, pacf as sm_pacf
__all__ = [
'acf',
'pacf'
]
# TODO: remove all explicit args/kwargs, making them *args, **kwargs
def i... | return sm_acf(
x=x,
nlags=nlags,
qstat=qstat,
fft=fft,
alpha=alpha,
missing=missing,
adjusted=adjusted,
)
| return sm_acf(
x=x,
nlags=nlags,
qstat=qstat,
fft=fft,
alpha=alpha,
missing=missing,
adjusted=adjusted,
)
| 10 | 715 | 76 | 791 | # -*- coding: utf-8 -*-
#
# Taylor G Smith <taylor.smith@alkaline.ml>
#
# Wrapped functions
from functools import wraps
import warnings
from statsmodels.tsa.stattools import acf as sm_acf, pacf as sm_pacf
__all__ = [
'acf',
'pacf'
]
# TODO: remove all explicit args/kwargs, making them *args, **kwargs
def i... | # -*- coding: utf-8 -*-
#
# Taylor G Smith <taylor.smith@alkaline.ml>
#
# Wrapped functions
from functools import wraps
import warnings
from statsmodels.tsa.stattools import acf as sm_acf, pacf as sm_pacf
__all__ = [
'acf',
'pacf'
]
# TODO: remove all explicit args/kwargs, making them *args, **kwargs
def i... | |
44,269 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/setup.py | 101,102 | 97,129 | run | CleanCommand | 102,129 | 102,129 | class CleanCommand(Clean):
description = "Remove build artifacts from the source tree"
# this is mostly in case we ever add a Cython module to SMRT
def run(self):
FILL_FUNC_BODY | class CleanCommand(Clean):
description = "Remove build artifacts from the source tree"
# this is mostly in case we ever add a Cython module to SMRT
def run(self):
FILL_FUNC_BODY | Clean.run(self)
# Remove c files if we are not within a sdist package
cwd = os.path.abspath(os.path.dirname(__file__))
remove_c_files = not os.path.exists(os.path.join(cwd, 'PKG-INFO'))
if remove_c_files:
print('Will remove generated .c files')
if os.path.exis... | Clean.run(self)
# Remove c files if we are not within a sdist package
cwd = os.path.abspath(os.path.dirname(__file__))
remove_c_files = not os.path.exists(os.path.join(cwd, 'PKG-INFO'))
if remove_c_files:
print('Will remove generated .c files')
if os.path.exis... | 92 | 57 | 408 | 465 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup the pmdarima module. This is heavily adapted from the scikit-learn
# setup.py, since they have a similar package structure and build similar
# Cython + C modules.
import sys
import os
import platform
import shutil
from distutils... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup the pmdarima module. This is heavily adapted from the scikit-learn
# setup.py, since they have a similar package structure and build similar
# Cython + C modules.
import sys
import os
import platform
import shutil
from distutils... |
44,270 | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima | /home/hieuvd/dung_repo/raw/stars_03/alkaline-ml_pmdarima/pmdarima/setup.py | 143,144 | 142,146 | build_extensions | build_ext_subclass | 144,146 | 144,146 | class build_ext_subclass(build_ext):
def build_extensions(self):
FILL_FUNC_BODY | class build_ext_subclass(build_ext):
def build_extensions(self):
FILL_FUNC_BODY | build_ext.build_extensions(self)
| build_ext.build_extensions(self)
| 1 | 33 | 15 | 48 | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup the pmdarima module. This is heavily adapted from the scikit-learn
# setup.py, since they have a similar package structure and build similar
# Cython + C modules.
import sys
import os
import platform
import shutil
from distutils... | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# Setup the pmdarima module. This is heavily adapted from the scikit-learn
# setup.py, since they have a similar package structure and build similar
# Cython + C modules.
import sys
import os
import platform
import shutil
from distutils... |
44,319 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/base.py | 61,62 | 31,72 | wrapped | requires | 63,69 | 62,69 | class requires: # pylint: disable=invalid-name
"""Decorator to return None if an object does not have the required attribute.
If the decorator is called various times on the same function with different
attributes, it will return None if one of them is missing. If instead a list
of attributes is passe... | class requires: # pylint: disable=invalid-name
"""Decorator to return None if an object does not have the required attribute.
If the decorator is called various times on the same function with different
attributes, it will return None if one of them is missing. If instead a list
of attributes is passe... | for prop in self.props:
prop = [prop] if isinstance(prop, str) else prop
if all((getattr(cls, prop_i) is None for prop_i in prop)):
return None
return func(cls)
| """Return None if not all props are available."""
for prop in self.props:
prop = [prop] if isinstance(prop, str) else prop
if all((getattr(cls, prop_i) is None for prop_i in prop)):
return None
return func(cls)
| 25 | 532 | 68 | 600 | """Low level converters usually used by other functions."""
import datetime
import functools
import importlib
import re
import warnings
from copy import deepcopy
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
import numpy as np
import tree
import xarray as xr
try:
import ujson as j... | """Low level converters usually used by other functions."""
import datetime
import functools
import importlib
import re
import warnings
from copy import deepcopy
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
import numpy as np
import tree
import xarray as xr
try:
import ujson as j... |
44,321 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/datasets.py | 76,77 | 1,162 | _sha256 | 78,89 | 77,89 | """Base IO code for all datasets. Heavily influenced by scikit-learn's implementation."""
import hashlib
import itertools
import json
import os
import shutil
from collections import namedtuple
from urllib.request import urlretrieve
from ..rcparams import rcParams
from .io_netcdf import from_netcdf
LocalFileMetadata ... | """Base IO code for all datasets. Heavily influenced by scikit-learn's implementation."""
import hashlib
import itertools
import json
import os
import shutil
from collections import namedtuple
from urllib.request import urlretrieve
from ..rcparams import rcParams
from .io_netcdf import from_netcdf
LocalFileMetadata ... | sha256hash = hashlib.sha256()
chunk_size = 8192
with open(path, "rb") as buff:
while True:
buffer = buff.read(chunk_size)
if not buffer:
break
sha256hash.update(buffer)
return sha256hash.hexdigest()
| """Calculate the sha256 hash of the file at path."""
sha256hash = hashlib.sha256()
chunk_size = 8192
with open(path, "rb") as buff:
while True:
buffer = buff.read(chunk_size)
if not buffer:
break
sha256hash.update(buffer)
return sha256hash.... | 23 | 1,589 | 104 | 1,693 | """Base IO code for all datasets. Heavily influenced by scikit-learn's implementation."""
import hashlib
import itertools
import json
import os
import shutil
from collections import namedtuple
from urllib.request import urlretrieve
from ..rcparams import rcParams
from .io_netcdf import from_netcdf
LocalFileMetadata ... | """Base IO code for all datasets. Heavily influenced by scikit-learn's implementation."""
import hashlib
import itertools
import json
import os
import shutil
from collections import namedtuple
from urllib.request import urlretrieve
from ..rcparams import rcParams
from .io_netcdf import from_netcdf
LocalFileMetadata ... | |
44,322 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_beanmachine.py | 82,88 | 1,113 | from_beanmachine | 108,113 | 88,113 | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... | return BMConverter(
sampler=sampler,
coords=coords,
dims=dims,
).to_inference_data()
| """Convert Bean Machine MonteCarloSamples object into an InferenceData object.
For a usage example read the
:ref:`Creating InferenceData section on from_beanmachine <creating_InferenceData>`
Parameters
----------
sampler : bm.MonteCarloSamples
Fitted MonteCarloSamples object from Bean... | 6 | 1,124 | 46 | 1,170 | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... | |
44,323 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_beanmachine.py | 45,47 | 7,82 | posterior_to_xarray | BMConverter | 48,51 | 47,51 | class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> None:
self.sampler = sampler
self.coords = coords
self.dims = dims
import beanmachine.ppl as bm # pyl... | class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> None:
self.sampler = sampler
self.coords = coords
self.dims = dims
import beanmachine.ppl as bm # pyl... | data = {k: v.detach().cpu().numpy() for k, v in self.posterior.items()}
return dict_to_dataset(data, library=self.beanm, coords=self.coords, dims=self.dims)
| """Convert the posterior to an xarray dataset."""
data = {k: v.detach().cpu().numpy() for k, v in self.posterior.items()}
return dict_to_dataset(data, library=self.beanm, coords=self.coords, dims=self.dims)
| 14 | 807 | 69 | 876 | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... | """beanmachine-specific conversion code."""
from .inference_data import InferenceData
from .base import dict_to_dataset, requires
class BMConverter:
"""Encapsulate Bean Machine specific logic."""
def __init__(
self,
*,
sampler=None,
coords=None,
dims=None,
) -> No... |
44,324 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_datatree.py | 6,7 | 1,24 | to_datatree | 13,16 | 7,16 | """Conversion between InferenceData and DataTree."""
from .inference_data import InferenceData
def to_datatree(data):
FILL_FUNC_BODYdef from_datatree(datatree):
"""Create an InferenceData object from a :class:`~datatree.DataTree`.
Parameters
----------
datatree : DataTree
"""
return Inferenc... | """Conversion between InferenceData and DataTree."""
from .inference_data import InferenceData
def to_datatree(data):
"""Convert InferenceData object to a :class:`~datatree.DataTree`.
Parameters
----------
data : InferenceData
"""
FILL_FUNC_BODYdef from_datatree(datatree):
"""Create an Infer... | return data.to_datatree()
| """Convert InferenceData object to a :class:`~datatree.DataTree`.
Parameters
----------
data : InferenceData
"""
return data.to_datatree()
| 2 | 161 | 16 | 177 | """Conversion between InferenceData and DataTree."""
from .inference_data import InferenceData
def to_datatree(data):
FILL_FUNC_BODYdef from_datatree(datatree):
"""Create an InferenceData object from a :class:`~datatree.DataTree`.
Parameters
----------
datatree : DataTree
"""
return Inferenc... | """Conversion between InferenceData and DataTree."""
from .inference_data import InferenceData
def to_datatree(data):
"""Convert InferenceData object to a :class:`~datatree.DataTree`.
Parameters
----------
data : InferenceData
"""
FILL_FUNC_BODYdef from_datatree(datatree):
"""Create an Infer... | |
44,327 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_json.py | 14,15 | 1,55 | from_json | 28,34 | 15,34 | """Input and output support for data."""
from .io_dict import from_dict
try:
import ujson as json
except ImportError:
# Can't find ujson using json
# mypy struggles with conditional imports expressed as catching ImportError:
# https://github.com/python/mypy/issues/1153
import json # type: ignore
... | """Input and output support for data."""
from .io_dict import from_dict
try:
import ujson as json
except ImportError:
# Can't find ujson using json
# mypy struggles with conditional imports expressed as catching ImportError:
# https://github.com/python/mypy/issues/1153
import json # type: ignore
... | with open(filename, "rb") as file:
idata_dict = json.load(file)
return from_dict(**idata_dict, save_warmup=True)
| """Initialize object from a json file.
Will use the faster `ujson` (https://github.com/ultrajson/ultrajson) if it is available.
Parameters
----------
filename : str
location of json file
Returns
-------
InferenceData object
"""
with open(filename, "rb") as file:
... | 11 | 345 | 56 | 401 | """Input and output support for data."""
from .io_dict import from_dict
try:
import ujson as json
except ImportError:
# Can't find ujson using json
# mypy struggles with conditional imports expressed as catching ImportError:
# https://github.com/python/mypy/issues/1153
import json # type: ignore
... | """Input and output support for data."""
from .io_dict import from_dict
try:
import ujson as json
except ImportError:
# Can't find ujson using json
# mypy struggles with conditional imports expressed as catching ImportError:
# https://github.com/python/mypy/issues/1153
import json # type: ignore
... | |
44,328 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_netcdf.py | 41,42 | 1,69 | to_netcdf | 66,69 | 42,69 | """Input and output support for data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_netcdf(filename, *, engine="h5netcdf", group_kwargs=None, regex=False):
"""Load netcdf file back into an arviz.InferenceData.
Parameters
----------
filename :... | """Input and output support for data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_netcdf(filename, *, engine="h5netcdf", group_kwargs=None, regex=False):
"""Load netcdf file back into an arviz.InferenceData.
Parameters
----------
filename :... | inference_data = convert_to_inference_data(data, group=group, coords=coords, dims=dims)
file_name = inference_data.to_netcdf(filename, engine=engine)
return file_name
| """Save dataset as a netcdf file.
WARNING: Only idempotent in case `data` is InferenceData
Parameters
----------
data : InferenceData, or any object accepted by `convert_to_inference_data`
Object to be saved
filename : str
name or path of the file to load trace
group : str ... | 12 | 640 | 64 | 704 | """Input and output support for data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_netcdf(filename, *, engine="h5netcdf", group_kwargs=None, regex=False):
"""Load netcdf file back into an arviz.InferenceData.
Parameters
----------
filename :... | """Input and output support for data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_netcdf(filename, *, engine="h5netcdf", group_kwargs=None, regex=False):
"""Load netcdf file back into an arviz.InferenceData.
Parameters
----------
filename :... | |
44,330 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_pyjags.py | 93,94 | 16,117 | log_likelihood_to_xarray | PyJAGSConverter | 95,100 | 94,100 | class PyJAGSConverter:
"""Encapsulate PyJAGS specific logic."""
def __init__(
self,
*,
posterior: tp.Optional[tp.Mapping[str, np.ndarray]] = None,
prior: tp.Optional[tp.Mapping[str, np.ndarray]] = None,
log_likelihood: tp.Optional[
tp.Union[str, tp.List[str],... | class PyJAGSConverter:
"""Encapsulate PyJAGS specific logic."""
def __init__(
self,
*,
posterior: tp.Optional[tp.Mapping[str, np.ndarray]] = None,
prior: tp.Optional[tp.Mapping[str, np.ndarray]] = None,
log_likelihood: tp.Optional[
tp.Union[str, tp.List[str],... | if self.log_likelihood is None:
return None
return self._pyjags_samples_to_xarray(self.log_likelihood)
| """Extract log likelihood samples from fit."""
if self.log_likelihood is None:
return None
return self._pyjags_samples_to_xarray(self.log_likelihood)
| 8 | 1,181 | 47 | 1,228 | """Convert PyJAGS sample dictionaries to ArviZ inference data objects."""
import typing as tp
from collections import OrderedDict
from collections.abc import Iterable
import numpy as np
import xarray
from .inference_data import InferenceData
from ..rcparams import rcParams
from .base import dict_to_dataset
class ... | """Convert PyJAGS sample dictionaries to ArviZ inference data objects."""
import typing as tp
from collections import OrderedDict
from collections.abc import Iterable
import numpy as np
import xarray
from .inference_data import InferenceData
from ..rcparams import rcParams
from .base import dict_to_dataset
class ... |
44,331 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/io_zarr.py | 14,15 | 1,47 | to_zarr | 44,47 | 15,47 | """Input and output support for zarr data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_zarr(store):
return InferenceData.from_zarr(store)
from_zarr.__doc__ = InferenceData.from_zarr.__doc__
def to_zarr(data, store=None, **kwargs):
FILL_FUNC_BODY | """Input and output support for zarr data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_zarr(store):
return InferenceData.from_zarr(store)
from_zarr.__doc__ = InferenceData.from_zarr.__doc__
def to_zarr(data, store=None, **kwargs):
"""
Conver... | inference_data = convert_to_inference_data(data, **kwargs)
zarr_group = inference_data.to_zarr(store=store)
return zarr_group
| """
Convert data to zarr, optionally saving to disk if ``store`` is provided.
The zarr storage is using the same group names as the InferenceData.
Parameters
----------
store : zarr.storage, MutableMapping or str, optional
Zarr storage class or path to desired DirectoryStore.
D... | 9 | 317 | 50 | 367 | """Input and output support for zarr data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_zarr(store):
return InferenceData.from_zarr(store)
from_zarr.__doc__ = InferenceData.from_zarr.__doc__
def to_zarr(data, store=None, **kwargs):
FILL_FUNC_BODY | """Input and output support for zarr data."""
from .converters import convert_to_inference_data
from .inference_data import InferenceData
def from_zarr(store):
return InferenceData.from_zarr(store)
from_zarr.__doc__ = InferenceData.from_zarr.__doc__
def to_zarr(data, store=None, **kwargs):
"""
Conver... | |
44,332 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/data/utils.py | 41,51 | 1,140 | extract | 110,140 | 51,140 | """Data specific utilities."""
import warnings
import numpy as np
from ..utils import _var_names
from .converters import convert_to_dataset
def extract_dataset(
data,
group="posterior",
combined=True,
var_names=None,
filter_vars=None,
num_samples=None,
rng=None,
):
"""Extract an Infe... | """Data specific utilities."""
import warnings
import numpy as np
from ..utils import _var_names
from .converters import convert_to_dataset
def extract_dataset(
data,
group="posterior",
combined=True,
var_names=None,
filter_vars=None,
num_samples=None,
rng=None,
):
"""Extract an Infe... | if num_samples is not None and not combined:
raise ValueError("num_samples is only compatible with combined=True")
if rng is None:
rng = num_samples is not None
if rng is not False and not combined:
raise ValueError("rng is only compatible with combined=True")
data = convert_to_d... | """Extract an InferenceData group or subset of it.
Parameters
----------
idata : InferenceData or InferenceData_like
InferenceData from which to extract the data.
group : str, optional
Which InferenceData data group to extract data from.
combined : bool, optional
Combine... | 160 | 983 | 440 | 1,423 | """Data specific utilities."""
import warnings
import numpy as np
from ..utils import _var_names
from .converters import convert_to_dataset
def extract_dataset(
data,
group="posterior",
combined=True,
var_names=None,
filter_vars=None,
num_samples=None,
rng=None,
):
"""Extract an Infe... | """Data specific utilities."""
import warnings
import numpy as np
from ..utils import _var_names
from .converters import convert_to_dataset
def extract_dataset(
data,
group="posterior",
combined=True,
var_names=None,
filter_vars=None,
num_samples=None,
rng=None,
):
"""Extract an Infe... | |
44,334 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 99,100 | 77,146 | var_pp_to_str | BaseLabeller | 101,107 | 100,107 | class BaseLabeller:
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
"""WIP."""
return f"{coord_val}"
def sel_to_str(self, sel: dict, isel: dict):
"""WIP."""
if sel:
return ", ".join(
[
self.dim_coord_to_str(d... | class BaseLabeller:
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
"""WIP."""
return f"{coord_val}"
def sel_to_str(self, sel: dict, isel: dict):
"""WIP."""
if sel:
return ", ".join(
[
self.dim_coord_to_str(d... | var_name_str = self.var_name_to_str(var_name)
pp_var_name_str = self.var_name_to_str(pp_var_name)
if var_name_str == pp_var_name_str:
return f"{var_name_str}"
return f"{var_name_str} / {pp_var_name_str}"
| """WIP."""
var_name_str = self.var_name_to_str(var_name)
pp_var_name_str = self.var_name_to_str(pp_var_name)
if var_name_str == pp_var_name_str:
return f"{var_name_str}"
return f"{var_name_str} / {pp_var_name_str}"
| 16 | 701 | 106 | 807 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,335 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 149,150 | 146,154 | dim_coord_to_str | DimCoordLabeller | 151,154 | 150,154 | class DimCoordLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
FILL_FUNC_BODY | class DimCoordLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
"""WIP."""
FILL_FUNC_BODY | return f"{dim}: {coord_val}"
| """WIP."""
return f"{dim}: {coord_val}"
| 3 | 59 | 19 | 78 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,336 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 165,166 | 162,170 | dim_coord_to_str | DimIdxLabeller | 167,170 | 166,170 | class DimIdxLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
FILL_FUNC_BODY | class DimIdxLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
"""WIP."""
FILL_FUNC_BODY | return f"{dim}#{coord_idx}"
| """WIP."""
return f"{dim}#{coord_idx}"
| 2 | 59 | 20 | 79 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,337 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 157,158 | 154,162 | dim_coord_to_str | IdxLabeller | 159,162 | 158,162 | class IdxLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
FILL_FUNC_BODY | class IdxLabeller(BaseLabeller):
"""WIP."""
def dim_coord_to_str(self, dim, coord_val, coord_idx):
"""WIP."""
FILL_FUNC_BODY | return f"{coord_idx}"
| """WIP."""
return f"{coord_idx}"
| 2 | 58 | 16 | 74 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,338 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 180,181 | 170,197 | dim_coord_to_str | MapLabeller | 182,186 | 181,186 | class MapLabeller(BaseLabeller):
"""WIP."""
def __init__(self, var_name_map=None, dim_map=None, coord_map=None, model_name_map=None):
"""WIP."""
self.var_name_map = {} if var_name_map is None else var_name_map
self.dim_map = {} if dim_map is None else dim_map
self.coord_map = {}... | class MapLabeller(BaseLabeller):
"""WIP."""
def __init__(self, var_name_map=None, dim_map=None, coord_map=None, model_name_map=None):
"""WIP."""
self.var_name_map = {} if var_name_map is None else var_name_map
self.dim_map = {} if dim_map is None else dim_map
self.coord_map = {}... | dim_str = self.dim_map.get(dim, dim)
coord_str = self.coord_map.get(dim, {}).get(coord_val, coord_val)
return super().dim_coord_to_str(dim_str, coord_str, coord_idx)
| """WIP."""
dim_str = self.dim_map.get(dim, dim)
coord_str = self.coord_map.get(dim, {}).get(coord_val, coord_val)
return super().dim_coord_to_str(dim_str, coord_str, coord_idx)
| 13 | 328 | 79 | 407 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,339 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 208,209 | 205,211 | make_model_label | NoModelLabeller | 210,211 | 209,211 | class NoModelLabeller(BaseLabeller):
"""WIP."""
def make_model_label(self, model_name, label):
FILL_FUNC_BODY | class NoModelLabeller(BaseLabeller):
"""WIP."""
def make_model_label(self, model_name, label):
"""WIP."""
FILL_FUNC_BODY | return label
| """WIP."""
return label
| 2 | 51 | 5 | 56 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,340 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/labels.py | 200,201 | 197,205 | var_name_to_str | NoVarLabeller | 202,205 | 201,205 | class NoVarLabeller(BaseLabeller):
"""WIP."""
def var_name_to_str(self, var_name):
FILL_FUNC_BODY | class NoVarLabeller(BaseLabeller):
"""WIP."""
def var_name_to_str(self, var_name):
"""WIP."""
FILL_FUNC_BODY | return None
| """WIP."""
return None
| 2 | 51 | 9 | 60 | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... | # pylint: disable=unused-argument
"""Utilities to generate labels from xarray objects."""
from typing import Union
__all__ = [
"mix_labellers",
"BaseLabeller",
"DimCoordLabeller",
"DimIdxLabeller",
"MapLabeller",
"NoVarLabeller",
"NoModelLabeller",
]
def mix_labellers(labellers, class_nam... |
44,341 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/autocorrplot.py | 11,27 | 1,162 | plot_autocorr | 27,162 | 27,162 | """Autocorrelation plot of data."""
from ..data import convert_to_dataset
from ..labels import BaseLabeller
from ..sel_utils import xarray_var_iter
from ..rcparams import rcParams
from ..utils import _var_names
from .plot_utils import default_grid, filter_plotters_list, get_plotting_function
def plot_autocorr(
d... | """Autocorrelation plot of data."""
from ..data import convert_to_dataset
from ..labels import BaseLabeller
from ..sel_utils import xarray_var_iter
from ..rcparams import rcParams
from ..utils import _var_names
from .plot_utils import default_grid, filter_plotters_list, get_plotting_function
def plot_autocorr(
d... | r"""Bar plot of the autocorrelation function (ACF) for a sequence of data.
The ACF plots are helpful as a convergence diagnostic for posteriors from MCMC
samples which display autocorrelation.
Parameters
----------
data : InferenceData
Any object that can be converted to an :class:`arv... | r"""Bar plot of the autocorrelation function (ACF) for a sequence of data.
The ACF plots are helpful as a convergence diagnostic for posteriors from MCMC
samples which display autocorrelation.
Parameters
----------
data : InferenceData
Any object that can be converted to an :class:`arv... | 579 | 202 | 1,627 | 1,829 | """Autocorrelation plot of data."""
from ..data import convert_to_dataset
from ..labels import BaseLabeller
from ..sel_utils import xarray_var_iter
from ..rcparams import rcParams
from ..utils import _var_names
from .plot_utils import default_grid, filter_plotters_list, get_plotting_function
def plot_autocorr(
d... | """Autocorrelation plot of data."""
from ..data import convert_to_dataset
from ..labels import BaseLabeller
from ..sel_utils import xarray_var_iter
from ..rcparams import rcParams
from ..utils import _var_names
from .plot_utils import default_grid, filter_plotters_list, get_plotting_function
def plot_autocorr(
d... | |
44,342 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/bfplot.py | 4,20 | 1,24 | plot_bf | 21,24 | 20,24 | """Bokeh Bayes Factor plot."""
def plot_bf(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
FILL_FUNC_BODY | """Bokeh Bayes Factor plot."""
def plot_bf(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
"""Bokeh Bayes Factor plot."""
FILL_FUNC_BODY | raise NotImplementedError(
"The bokeh backend is still under development. Use matplotlib backend."
)
| """Bokeh Bayes Factor plot."""
raise NotImplementedError(
"The bokeh backend is still under development. Use matplotlib backend."
)
| 13 | 116 | 34 | 150 | """Bokeh Bayes Factor plot."""
def plot_bf(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
FILL_FUNC_BODY | """Bokeh Bayes Factor plot."""
def plot_bf(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
"""Bokeh Bayes Factor plot."""
FILL_FUNC_BODY | |
44,343 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/distcomparisonplot.py | 4,20 | 1,24 | plot_dist_comparison | 21,24 | 20,24 | """Bokeh Density Comparison plot."""
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
FILL_FUNC_BODY | """Bokeh Density Comparison plot."""
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
"""Bokeh Density Comparison plot."""
FILL_F... | raise NotImplementedError(
"The bokeh backend is still under development. Use matplotlib backend."
)
| """Bokeh Density Comparison plot."""
raise NotImplementedError(
"The bokeh backend is still under development. Use matplotlib backend."
)
| 13 | 119 | 34 | 153 | """Bokeh Density Comparison plot."""
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
FILL_FUNC_BODY | """Bokeh Density Comparison plot."""
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
legend,
groups,
textsize,
labeller,
prior_kwargs,
posterior_kwargs,
observed_kwargs,
backend_kwargs,
show,
):
"""Bokeh Density Comparison plot."""
FILL_F... | |
44,344 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/distplot.py | 126,127 | 1,184 | _histplot_bokeh_op | 128,184 | 127,184 | """Bokeh Distplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import get_bins, histogram
from ...kdeplot import plot_kde
from ...plot_utils import (
_scale_fig_size,
set_bokeh_circular_ticks_labels,
vectorized_to_hex,
_init_kwargs_dict,
)
from .. import show_lay... | """Bokeh Distplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import get_bins, histogram
from ...kdeplot import plot_kde
from ...plot_utils import (
_scale_fig_size,
set_bokeh_circular_ticks_labels,
vectorized_to_hex,
_init_kwargs_dict,
)
from .. import show_lay... | if values2 is not None:
raise NotImplementedError("Insert hexbin plot here")
color = hist_kwargs.pop("color", False)
if color:
hist_kwargs["fill_color"] = color
hist_kwargs["line_color"] = color
bins = hist_kwargs.pop("bins", None)
if bins is None:
bins = get_bins(v... | """Add a histogram for the data to the axes."""
if values2 is not None:
raise NotImplementedError("Insert hexbin plot here")
color = hist_kwargs.pop("color", False)
if color:
hist_kwargs["fill_color"] = color
hist_kwargs["line_color"] = color
bins = hist_kwargs.pop("bins", ... | 134 | 1,042 | 643 | 1,685 | """Bokeh Distplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import get_bins, histogram
from ...kdeplot import plot_kde
from ...plot_utils import (
_scale_fig_size,
set_bokeh_circular_ticks_labels,
vectorized_to_hex,
_init_kwargs_dict,
)
from .. import show_lay... | """Bokeh Distplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import get_bins, histogram
from ...kdeplot import plot_kde
from ...plot_utils import (
_scale_fig_size,
set_bokeh_circular_ticks_labels,
vectorized_to_hex,
_init_kwargs_dict,
)
from .. import show_lay... | |
44,345 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/dotplot.py | 14,37 | 1,111 | plot_dot | 38,111 | 37,111 | """Bokeh dotplot."""
import math
import warnings
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import create_axes_grid
from ...plot_utils import plot_point_interval
from ...dotplot import wilkinson_algorithm, layout_stacks
def plot_dot(
values,... | """Bokeh dotplot."""
import math
import warnings
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import create_axes_grid
from ...plot_utils import plot_point_interval
from ...dotplot import wilkinson_algorithm, layout_stacks
def plot_dot(
values,... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs.setdefault("match_aspect", True)
(figsize, _, _, _, auto_linewidth, auto_markersize) = _scale_fig_size(figsize, None)
dotcolor = vectorized_to_hex(dotcolor)
intervalcolor = vectorized_to_hex(intervalcolor)
markercolor = vect... | """Bokeh dotplot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs.setdefault("match_aspect", True)
(figsize, _, _, _, auto_linewidth, auto_markersize) = _scale_fig_size(figsize, None)
dotcolor = vectorized_to_hex(dotcolor)
intervalcolor = vectorized_to_hex(intervalcolo... | 192 | 227 | 783 | 1,010 | """Bokeh dotplot."""
import math
import warnings
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import create_axes_grid
from ...plot_utils import plot_point_interval
from ...dotplot import wilkinson_algorithm, layout_stacks
def plot_dot(
values,... | """Bokeh dotplot."""
import math
import warnings
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import create_axes_grid
from ...plot_utils import plot_point_interval
from ...dotplot import wilkinson_algorithm, layout_stacks
def plot_dot(
values,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.