signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def path_lookup(data_obj, xj_path, create_dict_path=False):
|
if not xj_path or xj_path == '<STR_LIT:.>':<EOL><INDENT>return data_obj, True<EOL><DEDENT>res = list(split(xj_path, '<STR_LIT:.>', maxsplit=<NUM_LIT:1>))<EOL>top_key = res[<NUM_LIT:0>]<EOL>leftover = res[<NUM_LIT:1>] if len(res) > <NUM_LIT:1> else None<EOL>if top_key == '<STR_LIT:*>':<EOL><INDENT>return _full_sub_array(data_obj, leftover, create_dict_path)<EOL><DEDENT>elif top_key.startswith('<STR_LIT:@>'):<EOL><INDENT>return _single_array_element(data_obj, leftover, top_key,<EOL>create_dict_path)<EOL><DEDENT>else:<EOL><INDENT>val_type, top_key = _clean_key_type(top_key)<EOL>top_key = unescape(top_key)<EOL>if top_key in data_obj:<EOL><INDENT>value = data_obj[top_key]<EOL>if val_type is not None and not isinstance(value, val_type):<EOL><INDENT>raise XJPathError(<EOL>'<STR_LIT>' %<EOL>(top_key, val_type.__name__, type(value).__name__))<EOL><DEDENT>if leftover:<EOL><INDENT>return path_lookup(value, leftover, create_dict_path)<EOL><DEDENT>else:<EOL><INDENT>return value, True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if val_type is not None:<EOL><INDENT>if not isinstance(data_obj, dict):<EOL><INDENT>raise XJPathError('<STR_LIT>'<EOL>'<STR_LIT>' % top_key)<EOL><DEDENT>if create_dict_path:<EOL><INDENT>data_obj[top_key] = val_type()<EOL><DEDENT>else:<EOL><INDENT>return None, False<EOL><DEDENT>if leftover:<EOL><INDENT>return path_lookup(data_obj[top_key], leftover,<EOL>create_dict_path)<EOL><DEDENT>else:<EOL><INDENT>return data_obj[top_key], True<EOL><DEDENT><DEDENT>return None, False<EOL><DEDENT><DEDENT>
|
Looks up a xj path in the data_obj.
:param dict|list data_obj: An object to look into.
:param str xj_path: A path to extract data from.
:param bool create_dict_path: Create an element if type is specified.
:return: A tuple where 0 value is an extracted value and a second
field that tells if value either was found or not found.
|
f8812:m8
|
def strict_path_lookup(data_obj, xj_path, force_type=None):
|
value, exists = path_lookup(data_obj, xj_path)<EOL>if exists:<EOL><INDENT>if force_type is not None:<EOL><INDENT>if not isinstance(value, force_type):<EOL><INDENT>raise XJPathError('<STR_LIT>',<EOL>(xj_path, force_type))<EOL><DEDENT><DEDENT>return value<EOL><DEDENT>else:<EOL><INDENT>raise XJPathError('<STR_LIT>', (xj_path,))<EOL><DEDENT>
|
Looks up a xj path in the data_obj.
:param dict|list data_obj: An object to look into.
:param str xj_path: A path to extract data from.
:param type force_type: A type that excepted to be.
:return: Returns result or throws an exception if value is not found.
|
f8812:m9
|
def is_text_string(obj):
|
if PY2:<EOL><INDENT>return isinstance(obj, basestring)<EOL><DEDENT>else:<EOL><INDENT>return isinstance(obj, str)<EOL><DEDENT>
|
Return True if `obj` is a text string, False if it is anything else,
like binary data (Python 3) or QString (Python 2, PyQt API #1)
|
f8816:m0
|
def is_binary_string(obj):
|
if PY2:<EOL><INDENT>return isinstance(obj, str)<EOL><DEDENT>else:<EOL><INDENT>return isinstance(obj, bytes)<EOL><DEDENT>
|
Return True if `obj` is a binary string, False if it is anything else
|
f8816:m1
|
def is_string(obj):
|
return is_text_string(obj) or is_binary_string(obj)<EOL>
|
Return True if `obj` is a text or binary Python string object,
False if it is anything else, like a QString (Python 2, PyQt API #1)
|
f8816:m2
|
def is_unicode(obj):
|
if PY2:<EOL><INDENT>return isinstance(obj, unicode)<EOL><DEDENT>else:<EOL><INDENT>return isinstance(obj, str)<EOL><DEDENT>
|
Return True if `obj` is unicode
|
f8816:m3
|
def to_text_string(obj, encoding=None):
|
if PY2:<EOL><INDENT>if encoding is None:<EOL><INDENT>return unicode(obj)<EOL><DEDENT>else:<EOL><INDENT>return unicode(obj, encoding)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if encoding is None:<EOL><INDENT>return str(obj)<EOL><DEDENT>elif isinstance(obj, str):<EOL><INDENT>return obj<EOL><DEDENT>else:<EOL><INDENT>return str(obj, encoding)<EOL><DEDENT><DEDENT>
|
Convert `obj` to (unicode) text string
|
f8816:m4
|
def to_binary_string(obj, encoding=None):
|
if PY2:<EOL><INDENT>if encoding is None:<EOL><INDENT>return str(obj)<EOL><DEDENT>else:<EOL><INDENT>return obj.encode(encoding)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return bytes(obj, '<STR_LIT:utf-8>' if encoding is None else encoding)<EOL><DEDENT>
|
Convert `obj` to binary string (bytes in Python 3, str in Python 2)
|
f8816:m5
|
def get_func_code(func):
|
if PY2:<EOL><INDENT>return func.func_code<EOL><DEDENT>else:<EOL><INDENT>return func.__code__<EOL><DEDENT>
|
Return function code object
|
f8816:m6
|
def get_func_name(func):
|
if PY2:<EOL><INDENT>return func.func_name<EOL><DEDENT>else:<EOL><INDENT>return func.__name__<EOL><DEDENT>
|
Return function name
|
f8816:m7
|
def get_func_defaults(func):
|
if PY2:<EOL><INDENT>return func.func_defaults<EOL><DEDENT>else:<EOL><INDENT>return func.__defaults__<EOL><DEDENT>
|
Return function default argument values
|
f8816:m8
|
def get_meth_func(obj):
|
if PY2:<EOL><INDENT>return obj.im_func<EOL><DEDENT>else:<EOL><INDENT>return obj.__func__<EOL><DEDENT>
|
Return method function object
|
f8816:m9
|
def get_meth_class_inst(obj):
|
if PY2:<EOL><INDENT>return obj.im_self<EOL><DEDENT>else:<EOL><INDENT>return obj.__self__<EOL><DEDENT>
|
Return method class instance
|
f8816:m10
|
def get_meth_class(obj):
|
if PY2:<EOL><INDENT>return obj.im_class<EOL><DEDENT>else:<EOL><INDENT>return obj.__self__.__class__<EOL><DEDENT>
|
Return method class
|
f8816:m11
|
def qbytearray_to_str(qba):
|
return str(bytes(qba.toHex().data()).decode())<EOL>
|
Convert QByteArray object to str in a way compatible with Python 2/3
|
f8816:m12
|
@contextlib.contextmanager<EOL>def enabled_qcombobox_subclass(tmpdir):
|
with open(tmpdir.join('<STR_LIT>').strpath, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(QCOMBOBOX_SUBCLASS)<EOL><DEDENT>sys.path.insert(<NUM_LIT:0>, tmpdir.strpath)<EOL>yield<EOL>sys.path.pop(<NUM_LIT:0>)<EOL>
|
Context manager that sets up a temporary module with a QComboBox subclass
and then removes it once we are done.
|
f8823:m0
|
def get_qapp(icon_path=None):
|
qapp = QtWidgets.QApplication.instance()<EOL>if qapp is None:<EOL><INDENT>qapp = QtWidgets.QApplication(['<STR_LIT>'])<EOL><DEDENT>return qapp<EOL>
|
Helper function to return a QApplication instance
|
f8823:m1
|
def assert_pyside():
|
import PySide<EOL>assert QtCore.QEvent is PySide.QtCore.QEvent<EOL>assert QtGui.QPainter is PySide.QtGui.QPainter<EOL>assert QtWidgets.QWidget is PySide.QtGui.QWidget<EOL>assert QtWebEngineWidgets.QWebEnginePage is PySide.QtWebKit.QWebPage<EOL>
|
Make sure that we are using PySide
|
f8832:m0
|
def assert_pyside2():
|
import PySide2<EOL>assert QtCore.QEvent is PySide2.QtCore.QEvent<EOL>assert QtGui.QPainter is PySide2.QtGui.QPainter<EOL>assert QtWidgets.QWidget is PySide2.QtWidgets.QWidget<EOL>assert QtWebEngineWidgets.QWebEnginePage is PySide2.QtWebEngineWidgets.QWebEnginePage<EOL>
|
Make sure that we are using PySide
|
f8832:m1
|
def assert_pyqt4():
|
import PyQt4<EOL>assert QtCore.QEvent is PyQt4.QtCore.QEvent<EOL>assert QtGui.QPainter is PyQt4.QtGui.QPainter<EOL>assert QtWidgets.QWidget is PyQt4.QtGui.QWidget<EOL>assert QtWebEngineWidgets.QWebEnginePage is PyQt4.QtWebKit.QWebPage<EOL>
|
Make sure that we are using PyQt4
|
f8832:m2
|
def assert_pyqt5():
|
import PyQt5<EOL>assert QtCore.QEvent is PyQt5.QtCore.QEvent<EOL>assert QtGui.QPainter is PyQt5.QtGui.QPainter<EOL>assert QtWidgets.QWidget is PyQt5.QtWidgets.QWidget<EOL>if QtWebEngineWidgets.WEBENGINE:<EOL><INDENT>assert QtWebEngineWidgets.QWebEnginePage is PyQt5.QtWebEngineWidgets.QWebEnginePage<EOL><DEDENT>else:<EOL><INDENT>assert QtWebEngineWidgets.QWebEnginePage is PyQt5.QtWebKitWidgets.QWebPage<EOL><DEDENT>
|
Make sure that we are using PyQt5
|
f8832:m3
|
def main():
|
errno = pytest.main(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>sys.exit(errno)<EOL>
|
Run pytest tests.
|
f8833:m0
|
def getexistingdirectory(parent=None, caption='<STR_LIT>', basedir='<STR_LIT>',<EOL>options=QFileDialog.ShowDirsOnly):
|
<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>_temp1, _temp2 = sys.stdout, sys.stderr<EOL>sys.stdout, sys.stderr = None, None<EOL><DEDENT>try:<EOL><INDENT>result = QFileDialog.getExistingDirectory(parent, caption, basedir,<EOL>options)<EOL><DEDENT>finally:<EOL><INDENT>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>sys.stdout, sys.stderr = _temp1, _temp2<EOL><DEDENT><DEDENT>if not is_text_string(result):<EOL><INDENT>result = to_text_string(result)<EOL><DEDENT>return result<EOL>
|
Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
|
f8850:m0
|
def getopenfilename(parent=None, caption='<STR_LIT>', basedir='<STR_LIT>', filters='<STR_LIT>',<EOL>selectedfilter='<STR_LIT>', options=None):
|
return _qfiledialog_wrapper('<STR_LIT>', parent=parent,<EOL>caption=caption, basedir=basedir,<EOL>filters=filters, selectedfilter=selectedfilter,<EOL>options=options)<EOL>
|
Wrapper around QtGui.QFileDialog.getOpenFileName static method
Returns a tuple (filename, selectedfilter) -- when dialog box is canceled,
returns a tuple of empty strings
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
|
f8850:m2
|
def getopenfilenames(parent=None, caption='<STR_LIT>', basedir='<STR_LIT>', filters='<STR_LIT>',<EOL>selectedfilter='<STR_LIT>', options=None):
|
return _qfiledialog_wrapper('<STR_LIT>', parent=parent,<EOL>caption=caption, basedir=basedir,<EOL>filters=filters, selectedfilter=selectedfilter,<EOL>options=options)<EOL>
|
Wrapper around QtGui.QFileDialog.getOpenFileNames static method
Returns a tuple (filenames, selectedfilter) -- when dialog box is canceled,
returns a tuple (empty list, empty string)
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
|
f8850:m3
|
def getsavefilename(parent=None, caption='<STR_LIT>', basedir='<STR_LIT>', filters='<STR_LIT>',<EOL>selectedfilter='<STR_LIT>', options=None):
|
return _qfiledialog_wrapper('<STR_LIT>', parent=parent,<EOL>caption=caption, basedir=basedir,<EOL>filters=filters, selectedfilter=selectedfilter,<EOL>options=options)<EOL>
|
Wrapper around QtGui.QFileDialog.getSaveFileName static method
Returns a tuple (filename, selectedfilter) -- when dialog box is canceled,
returns a tuple of empty strings
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0
|
f8850:m4
|
def patch_qcombobox(QComboBox):
|
from ..QtGui import QIcon<EOL>from ..QtCore import Qt, QObject<EOL>class userDataWrapper():<EOL><INDENT>"""<STR_LIT>"""<EOL>def __init__(self, data):<EOL><INDENT>self.data = data<EOL><DEDENT><DEDENT>_addItem = QComboBox.addItem<EOL>def addItem(self, *args, **kwargs):<EOL><INDENT>if len(args) == <NUM_LIT:3> or (not isinstance(args[<NUM_LIT:0>], QIcon)<EOL>and len(args) == <NUM_LIT:2>):<EOL><INDENT>args, kwargs['<STR_LIT>'] = args[:-<NUM_LIT:1>], args[-<NUM_LIT:1>]<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = userDataWrapper(kwargs['<STR_LIT>'])<EOL><DEDENT>_addItem(self, *args, **kwargs)<EOL><DEDENT>_insertItem = QComboBox.insertItem<EOL>def insertItem(self, *args, **kwargs):<EOL><INDENT>if len(args) == <NUM_LIT:4> or (not isinstance(args[<NUM_LIT:1>], QIcon)<EOL>and len(args) == <NUM_LIT:3>):<EOL><INDENT>args, kwargs['<STR_LIT>'] = args[:-<NUM_LIT:1>], args[-<NUM_LIT:1>]<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = userDataWrapper(kwargs['<STR_LIT>'])<EOL><DEDENT>_insertItem(self, *args, **kwargs)<EOL><DEDENT>_setItemData = QComboBox.setItemData<EOL>def setItemData(self, index, value, role=Qt.UserRole):<EOL><INDENT>value = userDataWrapper(value)<EOL>_setItemData(self, index, value, role=role)<EOL><DEDENT>_itemData = QComboBox.itemData<EOL>def itemData(self, index, role=Qt.UserRole):<EOL><INDENT>userData = _itemData(self, index, role=role)<EOL>if isinstance(userData, userDataWrapper):<EOL><INDENT>userData = userData.data<EOL><DEDENT>return userData<EOL><DEDENT>def findData(self, value):<EOL><INDENT>for i in range(self.count()):<EOL><INDENT>if self.itemData(i) == value:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return -<NUM_LIT:1><EOL><DEDENT>QComboBox.addItem = addItem<EOL>QComboBox.insertItem = insertItem<EOL>QComboBox.setItemData = setItemData<EOL>QComboBox.itemData = itemData<EOL>QComboBox.findData = findData<EOL>
|
In PySide, using Python objects as userData in QComboBox causes
Segmentation faults under certain conditions. Even in cases where it
doesn't, findData does not work correctly. Likewise, findData also does not
work correctly with Python objects when using PyQt4. On the other hand,
PyQt5 deals with this case correctly. We therefore patch QComboBox when
using PyQt4 and PySide to avoid issues.
|
f8857:m0
|
def __init__(self, api_key, custom_handler_chain=None, **kwargs):
|
if custom_handler_chain is None:<EOL><INDENT>custom_handler_chain = [<EOL>JsonifyHandler(),<EOL>ThrowOnErrorHandler(),<EOL>TypeCorrectorHandler(),<EOL>RateLimitHandler(),<EOL>]<EOL><DEDENT>self._base_api = BaseApi(api_key, custom_handler_chain)<EOL>self._champion = ChampionApiV3(self._base_api)<EOL>self._lol_status = LolStatusApiV3(self._base_api)<EOL>self._data_dragon = DataDragonApi(self._base_api)<EOL>self._champion_mastery = ChampionMasteryApiV4(self._base_api)<EOL>self._league = LeagueApiV4(self._base_api)<EOL>self._match = MatchApiV4(self._base_api)<EOL>self._spectator = SpectatorApiV4(self._base_api)<EOL>self._summoner = SummonerApiV4(self._base_api)<EOL>self._third_party_code = ThirdPartyCodeApiV4(self._base_api)<EOL>
|
Initialize a new instance of the RiotWatcher class.
:param string api_key: the API key to use for this instance
:param List[RequestHandler] custom_handler_chain:
RequestHandler chain to pass to the created BaseApi object.
This chain is called in order before any calls to the API, and called in
reverse order after any calls to the API.
If preview_request returns data, the rest of the call short circuits,
preventing any call to the real API and calling any handlers that have already
been run in reverse order.
This should allow for dynamic tiered caching of data.
If after_request returns data, that is the data that is fed to the next handler
in the chain.
Default chain is:
[
JsonifyHandler,
ThrowOnErrorHandler,
TypeCorrector,
RateLimitHandler
]
|
f8895:c0:m0
|
@property<EOL><INDENT>def champion_mastery(self):<DEDENT>
|
return self._champion_mastery<EOL>
|
Interface to the ChampionMastery Endpoint
:rtype: ChampionMasteryApiV4
|
f8895:c0:m1
|
@property<EOL><INDENT>def champion(self):<DEDENT>
|
return self._champion<EOL>
|
Interface to the Champion Endpoint
:rtype: ChampionApiV3
|
f8895:c0:m2
|
@property<EOL><INDENT>def league(self):<DEDENT>
|
return self._league<EOL>
|
Interface to the League Endpoint
:rtype: LeagueApiV4
|
f8895:c0:m3
|
@property<EOL><INDENT>def lol_status(self):<DEDENT>
|
return self._lol_status<EOL>
|
Interface to the LoLStatus Endpoint
:rtype: LolStatusApiV3
|
f8895:c0:m4
|
@property<EOL><INDENT>def match(self):<DEDENT>
|
return self._match<EOL>
|
Interface to the Match Endpoint
:rtype: MatchApiV4
|
f8895:c0:m5
|
@property<EOL><INDENT>def spectator(self):<DEDENT>
|
return self._spectator<EOL>
|
Interface to the Spectator Endpoint
:rtype: SpectatorApiV4
|
f8895:c0:m6
|
@property<EOL><INDENT>def data_dragon(self):<DEDENT>
|
return self._data_dragon<EOL>
|
Interface to the DataDragon Endpoint
:rtype: DataDragonApi
|
f8895:c0:m7
|
@property<EOL><INDENT>def summoner(self):<DEDENT>
|
return self._summoner<EOL>
|
Interface to the Summoner Endpoint
:rtype: SummonerApiV4
|
f8895:c0:m8
|
@property<EOL><INDENT>def third_party_code(self):<DEDENT>
|
return self._third_party_code<EOL>
|
Interface to the Third Party Code Endpoint
:rtype: ThirdPartyCodeApiV4
|
f8895:c0:m9
|
def preview_request(self, region, endpoint_name, method_name, url, query_params):
|
if query_params is not None:<EOL><INDENT>for key, value in query_params.items():<EOL><INDENT>if isinstance(value, bool):<EOL><INDENT>query_params[key] = str(value).lower()<EOL><DEDENT>if (<EOL>not hasattr(value, "<STR_LIT>")<EOL>and hasattr(value, "<STR_LIT>")<EOL>or hasattr(value, "<STR_LIT>")<EOL>):<EOL><INDENT>for idx, val in enumerate(value):<EOL><INDENT>if isinstance(val, bool):<EOL><INDENT>value[idx] = str(val).lower()<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>
|
called before a request is processed.
:param string endpoint_name: the name of the endpoint being requested
:param string method_name: the name of the method being requested
:param url: the URL that is being requested.
:param query_params: dict: the parameters to the url that is being queried,
e.g. ?key1=val&key2=val2
|
f8896:c0:m0
|
def preview_request(self, region, endpoint_name, method_name, url, query_params):
|
wait_until = max(<EOL>[<EOL>(<EOL>limiter.wait_until(region, endpoint_name, method_name),<EOL>limiter.friendly_name,<EOL>)<EOL>for limiter in self._limiters<EOL>],<EOL>key=lambda lim_pair: lim_pair[<NUM_LIT:0>]<EOL>if lim_pair[<NUM_LIT:0>]<EOL>else datetime.datetime(datetime.MINYEAR, <NUM_LIT:1>, <NUM_LIT:1>),<EOL>)<EOL>if wait_until[<NUM_LIT:0>] is not None and wait_until[<NUM_LIT:0>] > datetime.datetime.now():<EOL><INDENT>to_wait = wait_until[<NUM_LIT:0>] - datetime.datetime.now()<EOL>logging.info(<EOL>"<STR_LIT>",<EOL>to_wait.total_seconds(),<EOL>wait_until[<NUM_LIT:1>],<EOL>)<EOL>time.sleep(to_wait.total_seconds())<EOL><DEDENT>
|
called before a request is processed.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint being requested
:param string method_name: the name of the method being requested
:param url: the URL that is being requested.
:param query_params: dict: the parameters to the url that is being queried,
e.g. ?key1=val&key2=val2
|
f8900:c0:m1
|
def after_request(self, region, endpoint_name, method_name, url, response):
|
for limiter in self._limiters:<EOL><INDENT>limiter.update_limiter(region, endpoint_name, method_name, response)<EOL><DEDENT>return response<EOL>
|
Called after a response is received and before it is returned to the user.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint that was requested
:param string method_name: the name of the method that was requested
:param url: The url that was requested
:param response: the response received. This is a response from the Requests library
|
f8900:c0:m2
|
def preview_request(self, region, endpoint_name, method_name, url, query_params):
|
pass<EOL>
|
called before a request is processed.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint being requested
:param string method_name: the name of the method being requested
:param url: the URL that is being requested.
:param query_params: dict: the parameters to the url that is being queried,
e.g. ?key1=val&key2=val2
|
f8904:c0:m1
|
def after_request(self, region, endpoint_name, method_name, url, response):
|
pass<EOL>
|
Called after a response is received and before it is returned to the user.
:param string region: the region of this request
:param string endpoint_name: the name of the endpoint that was requested
:param string method_name: the name of the method that was requested
:param url: The url that was requested
:param response: the response received. This is a response from the Requests library
|
f8904:c0:m2
|
def preview_static_request(self, url, query_params):
|
pass<EOL>
|
Called before a request to DataDragon is processed
:param url: The url that was requested
|
f8904:c0:m3
|
def after_static_request(self, url, response):
|
pass<EOL>
|
Called after a response is received and before it is returned to the user.
:param url: The url that was requested
:param response: the response received. This is a response from the Requests library
|
f8904:c0:m4
|
def __init__(self, base_api, endpoint_name):
|
self._base_api = base_api<EOL>self._endpoint_name = endpoint_name<EOL>
|
Initialize a new NamedEndpoint which uses the provided base_api and
injects the provided endpoint_name into calls to _request
:param BaseApi base_api: the root API object to use for making all requests.
:param string endpoint_name: the name of the child endpoint
|
f8910:c0:m0
|
def _raw_request(self, method_name, region, url, query_params):
|
return self._base_api.raw_request(<EOL>self._endpoint_name, method_name, region, url, query_params<EOL>)<EOL>
|
Sends a request through the BaseApi instance provided, injecting the provided endpoint_name
into the method call, so the caller doesn't have to.
:param string method_name: The name of the calling method
:param string region: The region to execute this request on
:param string url: The full URL to the method being requested.
:param dict query_params: Query parameters to be provided in the HTTP request
|
f8910:c0:m1
|
def __init__(self, base_api):
|
super(MatchApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new MatchApiV4 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8911:c0:m0
|
def by_id(self, region, match_id):
|
url, query = MatchApiV4Urls.by_id(region=region, match_id=match_id)<EOL>return self._raw_request(self.by_id.__name__, region, url, query)<EOL>
|
Get match by match ID
:param string region: The region to execute this request on
:param long match_id: The match ID.
:returns: MatchDto
|
f8911:c0:m1
|
def matchlist_by_account(<EOL>self,<EOL>region,<EOL>encrypted_account_id,<EOL>queue=None,<EOL>begin_time=None,<EOL>end_time=None,<EOL>begin_index=None,<EOL>end_index=None,<EOL>season=None,<EOL>champion=None,<EOL>):
|
url, query = MatchApiV4Urls.matchlist_by_account(<EOL>region=region,<EOL>encrypted_account_id=encrypted_account_id,<EOL>queue=queue,<EOL>beginTime=begin_time,<EOL>endTime=end_time,<EOL>beginIndex=begin_index,<EOL>endIndex=end_index,<EOL>season=season,<EOL>champion=champion,<EOL>)<EOL>return self._raw_request(self.matchlist_by_account.__name__, region, url, query)<EOL>
|
Get matchlist for ranked games played on given account ID and platform ID
and filtered using given filter parameters, if any
A number of optional parameters are provided for filtering. It is up to the caller to
ensure that the combination of filter parameters provided is valid for the requested
account, otherwise, no matches may be returned.
Note that if either beginIndex or endIndex are specified, then both must be specified and
endIndex must be greater than beginIndex.
If endTime is specified, but not beginTime, then beginTime is effectively the start of the
account's match history.
If beginTime is specified, but not endTime, then endTime is effectively the current time.
Note that endTime should be greater than beginTime if both are specified, although there is
no maximum limit on their range.
:param string region: The region to execute this request on
:param string encrypted_account_id: The account ID.
:param Set[int] queue: Set of queue IDs for which to filtering matchlist.
:param long begin_time: The begin time to use for filtering matchlist specified as
epoch milliseconds.
:param long end_time: The end time to use for filtering matchlist specified as epoch
milliseconds.
:param int begin_index: The begin index to use for filtering matchlist.
:param int end_index: The end index to use for filtering matchlist.
:param Set[int] season: Set of season IDs for which to filtering matchlist.
:param Set[int] champion: Set of champion IDs for which to filtering matchlist.
:returns: MatchlistDto
|
f8911:c0:m2
|
def timeline_by_match(self, region, match_id):
|
url, query = MatchApiV4Urls.timeline_by_match(region=region, match_id=match_id)<EOL>return self._raw_request(self.timeline_by_match.__name__, region, url, query)<EOL>
|
Get match timeline by match ID.
Not all matches have timeline data.
:param string region: The region to execute this request on
:param long match_id: The match ID.
:returns: MatchTimelineDto
|
f8911:c0:m3
|
def __init__(self, base_api):
|
super(ChampionMasteryApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new ChampionMasteryApiV4 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8912:c0:m0
|
def by_summoner(self, region, encrypted_summoner_id):
|
url, query = ChampionMasteryApiV4Urls.by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.by_summoner.__name__, region, url, query)<EOL>
|
Get all champion mastery entries.
:param string region: the region to execute this request on
:param string encrypted_summoner_id: Summoner ID associated with the player
:returns: List[ChampionMasteryDTO]: This object contains a list of Champion Mastery
information for player and champion combination.
|
f8912:c0:m1
|
def by_summoner_by_champion(self, region, encrypted_summoner_id, champion_id):
|
url, query = ChampionMasteryApiV4Urls.by_summoner_by_champion(<EOL>region=region,<EOL>encrypted_summoner_id=encrypted_summoner_id,<EOL>champion_id=champion_id,<EOL>)<EOL>return self._raw_request(<EOL>self.by_summoner_by_champion.__name__, region, url, query<EOL>)<EOL>
|
Get a champion mastery by player ID and champion ID.
:param string region: the region to execute this request on
:param string encrypted_summoner_id: Summoner ID associated with the player
:param long champion_id: Champion ID to retrieve Champion Mastery for
:returns: ChampionMasteryDTO: This object contains single Champion Mastery information for
player and champion combination.
|
f8912:c0:m2
|
def scores_by_summoner(self, region, encrypted_summoner_id):
|
url, query = ChampionMasteryApiV4Urls.scores_by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.scores_by_summoner.__name__, region, url, query)<EOL>
|
Get a player's total champion mastery score, which is the sum of individual champion
mastery levels
:param string region: the region to execute this request on
:param string encrypted_summoner_id: Summoner ID associated with the player
:returns: int
|
f8912:c0:m3
|
def __init__(self, base_api):
|
super(SummonerApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new SummonerApiV4 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8913:c0:m0
|
def by_account(self, region, encrypted_account_id):
|
url, query = SummonerApiV4Urls.by_account(<EOL>region=region, encrypted_account_id=encrypted_account_id<EOL>)<EOL>return self._raw_request(self.by_account.__name__, region, url, query)<EOL>
|
Get a summoner by account ID.
:param string region: The region to execute this request on
:param string encrypted_account_id: The account ID.
:returns: SummonerDTO: represents a summoner
|
f8913:c0:m1
|
def by_name(self, region, summoner_name):
|
url, query = SummonerApiV4Urls.by_name(<EOL>region=region, summoner_name=summoner_name<EOL>)<EOL>return self._raw_request(self.by_name.__name__, region, url, query)<EOL>
|
Get a summoner by summoner name
:param string region: The region to execute this request on
:param string summoner_name: Summoner Name
:returns: SummonerDTO: represents a summoner
|
f8913:c0:m2
|
def by_puuid(self, region, encrypted_puuid):
|
url, query = SummonerApiV4Urls.by_puuid(<EOL>region=region, encrypted_puuid=encrypted_puuid<EOL>)<EOL>return self._raw_request(self.by_puuid.__name__, region, url, query)<EOL>
|
Get a summoner by PUUID.
:param string region: The region to execute this request on
:param string encrypted_puuid: PUUID
:returns: SummonerDTO: represents a summoner
|
f8913:c0:m3
|
def by_id(self, region, encrypted_summoner_id):
|
url, query = SummonerApiV4Urls.by_id(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.by_id.__name__, region, url, query)<EOL>
|
Get a summoner by summoner ID.
:param string region: The region to execute this request on
:param string encrypted_summoner_id: Summoner ID
:returns: SummonerDTO: represents a summoner
|
f8913:c0:m4
|
def __init__(self, base_api):
|
super(ChampionApiV3, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new ChampionApiV3 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8914:c0:m0
|
def rotations(self, region):
|
url, query = ChampionApiV3Urls.rotations(region=region)<EOL>return self._raw_request(self.rotations.__name__, region, url, query)<EOL>
|
Returns champion rotations, including free-to-play and low-level free-to-play rotations.
:returns: ChampionInfo
|
f8914:c0:m1
|
def __init__(self, base_api):
|
super(ThirdPartyCodeApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new ThirdPartyCodeApiV4 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8915:c0:m0
|
def by_summoner(self, region, encrypted_summoner_id):
|
url, query = ThirdPartyCodeApiV4Urls.by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.by_summoner.__name__, region, url, query)<EOL>
|
FOR KR SUMMONERS, A 404 WILL ALWAYS BE RETURNED.
Valid codes must be no longer than 256 characters and only use
valid characters: 0-9, a-z, A-Z, and -
:param string region: the region to execute this request on
:param string encrypted_summoner_id: Summoner ID
:returns: string
|
f8915:c0:m1
|
def __init__(self, base_api):
|
super(LeagueApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new LeagueApiV4 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8916:c0:m0
|
def challenger_by_queue(self, region, queue):
|
url, query = LeagueApiV4Urls.challenger_by_queue(region=region, queue=queue)<EOL>return self._raw_request(self.challenger_by_queue.__name__, region, url, query)<EOL>
|
Get the challenger league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the challenger players for
:returns: LeagueListDTO
|
f8916:c0:m1
|
def grandmaster_by_queue(self, region, queue):
|
url, query = LeagueApiV4Urls.grandmaster_by_queue(region=region, queue=queue)<EOL>return self._raw_request(self.grandmaster_by_queue.__name__, region, url, query)<EOL>
|
Get the grandmaster league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the grandmaster players for
:returns: LeagueListDTO
|
f8916:c0:m2
|
def masters_by_queue(self, region, queue):
|
url, query = LeagueApiV4Urls.master_by_queue(region=region, queue=queue)<EOL>return self._raw_request(self.masters_by_queue.__name__, region, url, query)<EOL>
|
Get the master league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the master players for
:returns: LeagueListDTO
|
f8916:c0:m3
|
def by_id(self, region, league_id):
|
url, query = LeagueApiV4Urls.by_id(region=region, league_id=league_id)<EOL>return self._raw_request(self.by_id.__name__, region, url, query)<EOL>
|
Get league with given ID, including inactive entries
:param string region: the region to execute this request on
:param string league_id: the league ID to query
:returns: LeagueListDTO
|
f8916:c0:m4
|
def by_summoner(self, region, encrypted_summoner_id):
|
url, query = LeagueApiV4Urls.by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.by_summoner.__name__, region, url, query)<EOL>
|
Get league entries in all queues for a given summoner ID
:param string region: the region to execute this request on
:param string encrypted_summoner_id: the summoner ID to query
:returns: Set[LeagueEntryDTO]
|
f8916:c0:m5
|
def entries(self, region, queue, tier, division):
|
url, query = LeagueApiV4Urls.entries(<EOL>region=region, queue=queue, tier=tier, division=division<EOL>)<EOL>return self._raw_request(self.entries.__name__, region, url, query)<EOL>
|
Get all the league entries
:param string region: the region to execute this request on
:param string queue: the queue to query, i.e. RANKED_SOLO_5x5
:param string tier: the tier to query, i.e. DIAMOND
:param string division: the division to query, i.e. III
:returns: Set[LeagueEntryDTO]
|
f8916:c0:m6
|
def positions_by_summoner(self, region, encrypted_summoner_id):
|
url, query = LeagueApiV4Urls.positions_by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(<EOL>self.positions_by_summoner.__name__, region, url, query<EOL>)<EOL>
|
DEPRECATED
Get league positions in all queues for a given summoner ID
:param string region: the region to execute this request on
:param string encrypted_summoner_id: the summoner ID to query
:returns: Set[LeaguePositionDTO]
|
f8916:c0:m7
|
def __init__(self, base_api):
|
super(LolStatusApiV3, self).__init__(base_api, LolStatusApiV3.__name__)<EOL>
|
Initialize a new LolStatusApiV3 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8920:c0:m0
|
def shard_data(self, region):
|
url, query = LolStatusApiV3Urls.shard_data(region=region)<EOL>return self._raw_request(self.shard_data.__name__, region, url, query)<EOL>
|
Get League of Legends status for the given shard.
Requests to this API are not counted against the application Rate Limits.
:param string region: the region to execute this request on
:returns: ShardStatus
|
f8920:c0:m1
|
def __init__(self, base_api):
|
super(SpectatorApiV4, self).__init__(base_api, self.__class__.__name__)<EOL>
|
Initialize a new SpectatorApiV3 which uses the provided base_api
:param BaseApi base_api: the root API object to use for making all requests.
|
f8921:c0:m0
|
def by_summoner(self, region, encrypted_summoner_id):
|
url, query = SpectatorApiV4Urls.by_summoner(<EOL>region=region, encrypted_summoner_id=encrypted_summoner_id<EOL>)<EOL>return self._raw_request(self.by_summoner.__name__, region, url, query)<EOL>
|
Get current game information for the given summoner ID
:param string region: The region to execute this request on
:param string encrypted_summoner_id: The ID of the summoner.
:returns: CurrentGameInfo
|
f8921:c0:m1
|
def featured_games(self, region):
|
url, query = SpectatorApiV4Urls.featured_games(region=region)<EOL>return self._raw_request(self.featured_games.__name__, region, url, query)<EOL>
|
Get list of featured games.
:param string region: The region to execute this request on
:returns: FeaturedGames
|
f8921:c0:m2
|
def apply(filter):
|
def decorator(callable):<EOL><INDENT>return lambda *args, **kwargs: filter(callable(*args, **kwargs))<EOL><DEDENT>return decorator<EOL>
|
Manufacture decorator that filters return value with given function.
``filter``:
Callable that takes a single parameter.
|
f8936:m0
|
def format_outpat(outpat, xn):
|
return outpat.format(<EOL>year=str(xn.date.year),<EOL>month='<STR_LIT>'.format(xn.date.month),<EOL>fy=str(xn.date.year if xn.date.month < <NUM_LIT:7> else xn.date.year + <NUM_LIT:1>),<EOL>date=xn.date<EOL>)<EOL>
|
Format an outpat for the given transaction.
Format the given output filename pattern. The pattern should
be a format string with any combination of the following named
fields:
``year``
The year of the transaction.
``month``
The month of the transaction, with leading zero for
single-digit months.
``fy``
The financial year of the transaction (being the year in
which the financial year of the transaction *ends*).
A financial year runs from 1 July to 30 June.
``date``
The date object itself. The format string may specify
any attribute of the date object, e.g. ``{date.day}``.
This field is deprecated.
|
f8936:m1
|
def __init__(self, path='<STR_LIT>', text=None):
|
if text is None:<EOL><INDENT>path = os.path.expanduser(path)<EOL>if os.path.isfile(path):<EOL><INDENT>with open(path) as fh:<EOL><INDENT>self.data = json.load(fh)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.data = {} <EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.data = json.load(StringIO.StringIO(text))<EOL><DEDENT>
|
Initialise a Config object.
``path``
The path to the config file. Defaults to ``'~/.ltconfig'``.
User expansion is performed on the value.
``text``
JSON string that will be used for configuration. If supplied,
takes precedence over ``path``.
|
f8936:c0:m0
|
def get(self, name, acc=None, default=None):
|
if acc in self.data['<STR_LIT>'] and name in self.data['<STR_LIT>'][acc]:<EOL><INDENT>return self.data['<STR_LIT>'][acc][name]<EOL><DEDENT>if name in self.data:<EOL><INDENT>return self.data[name]<EOL><DEDENT>return default<EOL>
|
Return the named config for the given account.
If an account is given, first checks the account space for the name.
If no account given, or if the name not found in the account space,
look for the name in the global config space. If still not found,
return the default, if given, otherwise ``None``.
|
f8936:c0:m1
|
@apply(os.path.normpath)<EOL><INDENT>def outdir(self, acc=None):<DEDENT>
|
rootdir = self.rootdir()<EOL>outdir = self.get('<STR_LIT>', acc=acc)<EOL>dir = os.path.join(rootdir, outdir) if rootdir and outdir else None<EOL>if not os.path.exists(dir):<EOL><INDENT>os.makedirs(dir)<EOL><DEDENT>return dir<EOL>
|
Return the outdir for the given account.
Attempts to create the directory if it does not exist.
|
f8936:c0:m3
|
def outpat(self, acc=None):
|
outdir = self.outdir(acc)<EOL>outpat = self.get('<STR_LIT>', acc=acc)<EOL>return os.path.join(outdir, outpat) if outdir and outpat else None<EOL>
|
Determine the full outfile pattern for the given account.
Return None if not specified.
|
f8936:c0:m4
|
@apply(os.path.normpath)<EOL><INDENT>def rulesdir(self, acc=None):<DEDENT>
|
rootdir = self.rootdir()<EOL>rulesdir = self.get('<STR_LIT>', acc=acc, default=[])<EOL>return os.path.join(rootdir, rulesdir)if rootdir and rulesdir else None<EOL>
|
Determine the rulesdir for the given account.
Return None if not specified.
|
f8936:c0:m5
|
def rulefiles(self, acc=None):
|
rulesdir = self.rulesdir(acc)<EOL>rules = [os.path.join(rulesdir, x) for x in self.get('<STR_LIT>', acc, [])]<EOL>if acc is not None:<EOL><INDENT>rules += self.rulefiles(acc=None)<EOL><DEDENT>return rules<EOL>
|
Return a list of rulefiles for the given account.
Returns an empty list if none specified.
|
f8936:c0:m6
|
def __init__(self, *args, **kwargs):
|
super(AccountCondition, self).__init__(*args, **kwargs)<EOL>pattern = self.value.replace('<STR_LIT>', '<STR_LIT>')<EOL>if pattern[<NUM_LIT:0>] != '<STR_LIT::>':<EOL><INDENT>pattern = '<STR_LIT>' + pattern<EOL><DEDENT>if pattern[-<NUM_LIT:1>] != '<STR_LIT::>':<EOL><INDENT>pattern = pattern + '<STR_LIT:$>'<EOL><DEDENT>self.re = re.compile(pattern)<EOL>
|
Any '::' expands to 1+ intermediate fragments.
No ':' at start anchors fragment at beginning.
No ':' at end anchors fragment at end.
|
f8938:c2:m0
|
def __init__(self, *args):
|
super(Rule, self).__init__()<EOL>self.conditions = []<EOL>self.outcomes = []<EOL>for condition_or_outcome in args:<EOL><INDENT>if isinstance(condition_or_outcome, Condition):<EOL><INDENT>self.conditions.append(condition_or_outcome)<EOL><DEDENT>elif isinstance(condition_or_outcome, Outcome):<EOL><INDENT>self.outcomes.append(condition_or_outcome)<EOL><DEDENT>elif condition_or_outcome is not None:<EOL><INDENT>raise Exception<EOL><DEDENT><DEDENT>
|
Initialise the rule
|
f8938:c14:m0
|
def match(self, xn):
|
if all(map(lambda x: x.match(xn), self.conditions)):<EOL><INDENT>return self.outcomes<EOL><DEDENT>return None<EOL>
|
Processes a transaction against this rule
If all conditions are satisfied, a list of outcomes is returned.
If any condition is unsatisifed, None is returned.
|
f8938:c14:m1
|
def balance_to_ringchart_items(balance, account='<STR_LIT>', show=SHOW_CREDIT):
|
show = show if show else SHOW_CREDIT <EOL>rcis = []<EOL>for item in balance:<EOL><INDENT>subaccount = item['<STR_LIT>'] if not accountelse '<STR_LIT::>'.join((account, item['<STR_LIT>']))<EOL>ch = balance_to_ringchart_items(item['<STR_LIT>'], subaccount, show)<EOL>amount = item['<STR_LIT>'] if show == SHOW_CREDIT else -item['<STR_LIT>']<EOL>if amount < <NUM_LIT:0>:<EOL><INDENT>continue <EOL><DEDENT>wedge_amount = max(amount, sum(map(float, ch)))<EOL>rci = gtkchartlib.ringchart.RingChartItem(<EOL>wedge_amount,<EOL>tooltip='<STR_LIT>'.format(subaccount, wedge_amount),<EOL>items=ch<EOL>)<EOL>rcis.append(rci)<EOL><DEDENT>return rcis<EOL>
|
Convert a balance data structure into RingChartItem objects.
|
f8939:m0
|
def __init__(<EOL>self,<EOL>fieldnames=None,<EOL>fieldremap=None,<EOL>date_format=None,<EOL>**kwargs):
|
if '<STR_LIT>' not in kwargs:<EOL><INDENT>raise reader.DataError('<STR_LIT>')<EOL><DEDENT>self.account = kwargs.pop('<STR_LIT>')<EOL>super(Reader, self).__init__(**kwargs)<EOL>self.csvreader = csv.DictReader(self.file, fieldnames=fieldnames)<EOL>self.remap = fieldremap<EOL>self.date_format = date_format<EOL>
|
Takes an account argument which indicates the account that was
transacted upon.
The fieldnames argument, if supplied, is passed to the underlying
csv.DictReader object, and is required if the first line of the
CSV file does not specify the field names.
|
f8941:c1:m0
|
def __next__(self):
|
try:<EOL><INDENT>return self.dict_to_xn(next(self.csvreader))<EOL><DEDENT>except MetadataException:<EOL><INDENT>return next(self)<EOL><DEDENT>
|
Return the next transaction object.
StopIteration will be propagated from self.csvreader.next()
|
f8941:c1:m1
|
def parse_date(self, date):
|
if self.date_format is not None:<EOL><INDENT>return datetime.datetime.strptime(date, self.date_format).date()<EOL><DEDENT>if re.match('<STR_LIT>', date):<EOL><INDENT>return datetime.date(*list(map(int, (date[:<NUM_LIT:4>], date[<NUM_LIT:4>:<NUM_LIT:6>], date[<NUM_LIT:6>:]))))<EOL><DEDENT>try:<EOL><INDENT>parts = date_delim.split(date, <NUM_LIT:2>) <EOL>if len(parts) == <NUM_LIT:3>:<EOL><INDENT>if len(parts[<NUM_LIT:0>]) == <NUM_LIT:4>:<EOL><INDENT>return datetime.date(*list(map(int, parts)))<EOL><DEDENT>elif len(parts[<NUM_LIT:2>]) == <NUM_LIT:4>:<EOL><INDENT>return datetime.date(*list(map(int, reversed(parts))))<EOL><DEDENT><DEDENT><DEDENT>except TypeError as ValueError:<EOL><INDENT>raise reader.DataError('<STR_LIT>'.format(date))<EOL><DEDENT>
|
Parse the date and return a datetime object
The heuristic for determining the date is:
- if ``date_format`` is set, parse using strptime
- if one field of 8 digits, YYYYMMDD
- split by '-' or '/'
- (TODO: substitute string months with their numbers)
- if (2, 2, 4), DD-MM-YYYY (not the peculiar US order)
- if (4, 2, 2), YYYY-MM-DD
- ka-boom!
The issue of reliably discerning between DD-MM-YYYY (sane) vs.
MM-DD-YYYY (absurd, but Big In America), without being told what's
being used, is intractable.
Return a datetime.date object.
|
f8941:c1:m2
|
def match_to_dict(match):
|
balance, indent, account_fragment = match.group(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>)<EOL>return {<EOL>'<STR_LIT>': decimal.Decimal(balance),<EOL>'<STR_LIT>': len(indent),<EOL>'<STR_LIT>': account_fragment,<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': [],<EOL>}<EOL>
|
Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
|
f8943:m0
|
def balance(output):
|
lines = map(pattern.search, output.splitlines())<EOL>stack = []<EOL>top = []<EOL>for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):<EOL><INDENT>while stack and item['<STR_LIT>'] <= stack[-<NUM_LIT:1>]['<STR_LIT>']:<EOL><INDENT>stack.pop()<EOL><DEDENT>if not stack:<EOL><INDENT>stack.append(item)<EOL>top.append(item)<EOL><DEDENT>else:<EOL><INDENT>item['<STR_LIT>'] = stack[-<NUM_LIT:1>]<EOL>stack[-<NUM_LIT:1>]['<STR_LIT>'].append(item)<EOL>stack.append(item)<EOL><DEDENT><DEDENT>return top<EOL>
|
Convert `ledger balance` output into an hierarchical data structure.
|
f8943:m1
|
def __iter__(self):
|
return self<EOL>
|
Return an iterator for the Reader
|
f8944:c2:m1
|
def next(self):
|
raise NotImplementedError<EOL>
|
Return the next item.
Must raise StopIteration when the file has no more transactions
|
f8944:c2:m2
|
def number(items):
|
n = len(items)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return items<EOL><DEDENT>places = str(int(math.log10(n) // <NUM_LIT:1> + <NUM_LIT:1>))<EOL>format = '<STR_LIT>' + str(int(places)) + '<STR_LIT>'<EOL>return [format.format(x) for x in enumerate(items)]<EOL>
|
Maps numbering onto given values
|
f8946:m0
|
def filter_yn(string, default=None):
|
if string.startswith(('<STR_LIT:Y>', '<STR_LIT:y>')):<EOL><INDENT>return True<EOL><DEDENT>elif string.startswith(('<STR_LIT:N>', '<STR_LIT:n>')):<EOL><INDENT>return False<EOL><DEDENT>elif not string and default is not None:<EOL><INDENT>return True if default else False<EOL><DEDENT>raise InvalidInputError<EOL>
|
Return True if yes, False if no, or the default.
|
f8946:m1
|
def filter_int(string, default=None, start=None, stop=None):
|
try:<EOL><INDENT>i = int(string)<EOL>if start is not None and i < start:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>if stop is not None and i >= stop:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>return i<EOL><DEDENT>except ValueError:<EOL><INDENT>if not string and default is not None:<EOL><INDENT>return default<EOL><DEDENT>else:<EOL><INDENT>raise InvalidInputError<EOL><DEDENT><DEDENT>
|
Return the input integer, or the default.
|
f8946:m2
|
def filter_decimal(string, default=None, lower=None, upper=None):
|
try:<EOL><INDENT>d = decimal.Decimal(string)<EOL>if lower is not None and d < lower:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>if upper is not None and d >= upper:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>return d<EOL><DEDENT>except decimal.InvalidOperation:<EOL><INDENT>if not string and default is not None:<EOL><INDENT>return default<EOL><DEDENT>else:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT><DEDENT>
|
Return the input decimal number, or the default.
|
f8946:m3
|
def filter_pastdate(string, default=None):
|
if not string and default is not None:<EOL><INDENT>return default<EOL><DEDENT>today = datetime.date.today()<EOL>try:<EOL><INDENT>parts = list(map(int, re.split('<STR_LIT>', string))) <EOL><DEDENT>except ValueError:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>if len(parts) < <NUM_LIT:1> or len(parts) > <NUM_LIT:3>:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>if len(parts) == <NUM_LIT:1>:<EOL><INDENT>parts.append(today.month - <NUM_LIT:1> if parts[<NUM_LIT:0>] > today.day else today.month)<EOL>if parts[<NUM_LIT:1>] < <NUM_LIT:1>:<EOL><INDENT>parts[<NUM_LIT:1>] = <NUM_LIT:12><EOL><DEDENT><DEDENT>if len(parts) == <NUM_LIT:2>:<EOL><INDENT>if parts[<NUM_LIT:1>] > today.monthor parts[<NUM_LIT:1>] == today.month and parts[<NUM_LIT:0>] > today.day:<EOL><INDENT>parts.append(today.year - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>parts.append(today.year)<EOL><DEDENT><DEDENT>parts.reverse()<EOL>try:<EOL><INDENT>date = datetime.date(*parts)<EOL>if date > today:<EOL><INDENT>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>return date<EOL><DEDENT>except ValueError:<EOL><INDENT>print(parts)<EOL>raise InvalidInputError("<STR_LIT>")<EOL><DEDENT>
|
Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the current year
if the given date has passed (or is today), otherwise the previous
year.
|
f8946:m5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.