code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Given an FSM and a multiplier, return the multiplied FSM.
'''
if multiplier < 0:
raise Exception("Can't multiply an FSM by " + repr(multiplier))
alphabet = self.alphabet
# metastate is a set of iterations+states
initial = {(self.initial, 0)}
def final(state):
'''If the initial state is fin... | def times(self, multiplier) | Given an FSM and a multiplier, return the multiplied FSM. | 4.809729 | 4.496314 | 1.069705 |
'''
Return a finite state machine which will accept any string NOT
accepted by self, and will not accept any string accepted by self.
This is more complicated if there are missing transitions, because the
missing "dead" state must now be reified.
'''
alphabet = self.alphabet
initial = {0 : self.ini... | def everythingbut(self) | Return a finite state machine which will accept any string NOT
accepted by self, and will not accept any string accepted by self.
This is more complicated if there are missing transitions, because the
missing "dead" state must now be reified. | 6.280563 | 2.949206 | 2.129577 |
'''
Return a new FSM such that for every string that self accepts (e.g.
"beer", the new FSM accepts the reversed string ("reeb").
'''
alphabet = self.alphabet
# Start from a composite "state-set" consisting of all final states.
# If there are no final states, this set is empty and we'll find that
# n... | def reversed(self) | Return a new FSM such that for every string that self accepts (e.g.
"beer", the new FSM accepts the reversed string ("reeb"). | 7.096805 | 4.868345 | 1.457745 |
'''A state is "live" if a final state can be reached from it.'''
reachable = [state]
i = 0
while i < len(reachable):
current = reachable[i]
if current in self.finals:
return True
if current in self.map:
for symbol in self.map[current]:
next = self.map[current][symbol]
if next not in r... | def islive(self, state) | A state is "live" if a final state can be reached from it. | 2.498192 | 2.057833 | 1.213992 |
'''
Generate strings (lists of symbols) that this FSM accepts. Since there may
be infinitely many of these we use a generator instead of constructing a
static list. Strings will be sorted in order of length and then lexically.
This procedure uses arbitrary amounts of memory but is very fast. There
may ... | def strings(self) | Generate strings (lists of symbols) that this FSM accepts. Since there may
be infinitely many of these we use a generator instead of constructing a
static list. Strings will be sorted in order of length and then lexically.
This procedure uses arbitrary amounts of memory but is very fast. There
may be more e... | 4.910528 | 2.918118 | 1.682772 |
'''
Consider the FSM as a set of strings and return the cardinality of that
set, or raise an OverflowError if there are infinitely many
'''
num_strings = {}
def get_num_strings(state):
# Many FSMs have at least one oblivion state
if self.islive(state):
if state in num_strings:
if num_string... | def cardinality(self) | Consider the FSM as a set of strings and return the cardinality of that
set, or raise an OverflowError if there are infinitely many | 3.974552 | 3.095526 | 1.283967 |
'''
For completeness only, since `set.copy()` also exists. FSM objects are
immutable, so I can see only very odd reasons to need this.
'''
return fsm(
alphabet = self.alphabet,
states = self.states,
initial = self.initial,
finals = self.finals,
map = self.map,
) | def copy(self) | For completeness only, since `set.copy()` also exists. FSM objects are
immutable, so I can see only very odd reasons to need this. | 7.277059 | 2.076032 | 3.505274 |
'''
Compute the Brzozowski derivative of this FSM with respect to the input
string of symbols. <https://en.wikipedia.org/wiki/Brzozowski_derivative>
If any of the symbols are not members of the alphabet, that's a KeyError.
If you fall into oblivion, then the derivative is an FSM accepting no
strings.
... | def derive(self, input) | Compute the Brzozowski derivative of this FSM with respect to the input
string of symbols. <https://en.wikipedia.org/wiki/Brzozowski_derivative>
If any of the symbols are not members of the alphabet, that's a KeyError.
If you fall into oblivion, then the derivative is an FSM accepting no
strings. | 4.884939 | 2.800274 | 1.74445 |
if self.url_prefix:
url = '{prefix}{url}'.format(prefix=self.url_prefix, url=endpoint.url)
else:
url = endpoint.url
self.add_url_rule(
url,
view_func=endpoint.as_view(endpoint.get_name()),
) | def add_endpoint(self, endpoint) | Register an :class:`.Endpoint` aginst this resource.
:param endpoint: :class:`.Endpoint` API Endpoint class
Usage::
foo_resource = Resource('example', __name__)
class MyEndpoint(Endpoint):
url = '/example'
name = 'myendpoint'
foo_r... | 2.801992 | 2.872587 | 0.975425 |
'''reduce() the result of this method call (unless you already reduced it).'''
def new_method(self, *args, **kwargs):
result = method(self, *args, **kwargs)
if result == self:
return result
return result.reduce()
return new_method | def reduce_after(method) | reduce() the result of this method call (unless you already reduced it). | 4.399828 | 3.058843 | 1.438396 |
'''
Take a method which acts on 0 or more regular expression objects... return a
new method which simply converts them all to FSMs, calls the FSM method
on them instead, then converts the result back to a regular expression.
We do this for several of the more annoying operations.
'''
fsm_method = getattr(fsm... | def call_fsm(method) | Take a method which acts on 0 or more regular expression objects... return a
new method which simply converts them all to FSMs, calls the FSM method
on them instead, then converts the result back to a regular expression.
We do this for several of the more annoying operations. | 6.993196 | 2.26703 | 3.08474 |
'''
Parse the entire supplied string as an instance of the present class.
Mainly for internal use in unit tests because it drops through to match()
in a convenient way.
'''
obj, i = cls.match(string, 0)
if i != len(string):
raise Exception("Could not parse '" + string + "' beyond index " + str(i))
... | def parse(cls, string) | Parse the entire supplied string as an instance of the present class.
Mainly for internal use in unit tests because it drops through to match()
in a convenient way. | 6.970455 | 2.3675 | 2.944226 |
'''
Each time next() is called on this iterator, a new string is returned
which will the present lego piece can match. StopIteration is raised once
all such strings have been returned, although a regex with a * in may
match infinitely many strings.
'''
# In the case of a regex like "[^abc]", there ar... | def strings(self, otherchar=None) | Each time next() is called on this iterator, a new string is returned
which will the present lego piece can match. StopIteration is raised once
all such strings have been returned, although a regex with a * in may
match infinitely many strings. | 9.932012 | 5.149224 | 1.928837 |
'''
Multiplication is not well-defined for all pairs of multipliers because
the resulting possibilities do not necessarily form a continuous range.
For example:
{0,x} * {0,y} = {0,x*y}
{2} * {3} = {6}
{2} * {1,2} = ERROR
The proof isn't simple but suffice it to say that {p,p+q} * {r,r+s} is
... | def canmultiplyby(self, other) | Multiplication is not well-defined for all pairs of multipliers because
the resulting possibilities do not necessarily form a continuous range.
For example:
{0,x} * {0,y} = {0,x*y}
{2} * {3} = {6}
{2} * {1,2} = ERROR
The proof isn't simple but suffice it to say that {p,p+q} * {r,r+s} is
equal t... | 10.365919 | 1.707423 | 6.071089 |
'''
Intersection is not well-defined for all pairs of multipliers.
For example:
{2,3} & {3,4} = {3}
{2,} & {1,7} = {2,7}
{2} & {5} = ERROR
'''
return not (self.max < other.min or other.max < self.min) | def canintersect(self, other) | Intersection is not well-defined for all pairs of multipliers.
For example:
{2,3} & {3,4} = {3}
{2,} & {1,7} = {2,7}
{2} & {5} = ERROR | 5.060441 | 1.66865 | 3.032655 |
'''Union is not defined for all pairs of multipliers. e.g. {0,1} | {3,4}'''
return not (self.max + bound(1) < other.min or other.max + bound(1) < self.min) | def canunion(self, other) | Union is not defined for all pairs of multipliers. e.g. {0,1} | {3,4} | 7.822034 | 3.54139 | 2.208747 |
'''
Find the shared part of two multipliers. This is the largest multiplier
which can be safely subtracted from both the originals. This may
return the "zero" multiplier.
'''
mandatory = min(self.mandatory, other.mandatory)
optional = min(self.optional, other.optional)
return multiplier(mandatory, ma... | def common(self, other) | Find the shared part of two multipliers. This is the largest multiplier
which can be safely subtracted from both the originals. This may
return the "zero" multiplier. | 6.817889 | 2.351487 | 2.899395 |
'''
"Dock" another mult from this one (i.e. remove part of the tail) and
return the result. The reverse of concatenation. This is a lot trickier.
e.g. a{4,5} - a{3} = a{1,2}
'''
if other.multiplicand != self.multiplicand:
raise Exception("Can't subtract " + repr(other) + " from " + repr(self))
retur... | def dock(self, other) | "Dock" another mult from this one (i.e. remove part of the tail) and
return the result. The reverse of concatenation. This is a lot trickier.
e.g. a{4,5} - a{3} = a{1,2} | 6.399021 | 1.939736 | 3.298914 |
'''
Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree.
'''
if self.multiplicand == other.multiplicand:
return mult(self.m... | def common(self, other) | Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree. | 6.216348 | 2.237873 | 2.777793 |
'''
Return the common prefix of these two concs; that is, the largest conc
which can be safely beheaded() from the front of both.
The result could be emptystring.
"ZYAA, ZYBB" -> "ZY"
"CZ, CZ" -> "CZ"
"YC, ZC" -> ""
With the "suffix" flag set, works from the end. E.g.:
"AAZY, BBZY" -> "ZY"
... | def common(self, other, suffix=False) | Return the common prefix of these two concs; that is, the largest conc
which can be safely beheaded() from the front of both.
The result could be emptystring.
"ZYAA, ZYBB" -> "ZY"
"CZ, CZ" -> "CZ"
"YC, ZC" -> ""
With the "suffix" flag set, works from the end. E.g.:
"AAZY, BBZY" -> "ZY"
"CZ, CZ"... | 4.873902 | 2.467895 | 1.974923 |
'''
Subtract another conc from this one.
This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF,
then logically ABCDEF - DEF = ABC.
'''
# e.g. self has mults at indices [0, 1, 2, 3, 4, 5, 6] len=7
# e.g. other has mults at indices [0, 1, 2] len=3
new = list(self.mults)
for i in ... | def dock(self, other) | Subtract another conc from this one.
This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF,
then logically ABCDEF - DEF = ABC. | 5.456419 | 4.19175 | 1.301704 |
'''
The opposite of concatenation. Remove a common suffix from the present
pattern; that is, from each of its constituent concs.
AYZ|BYZ|CYZ - YZ = A|B|C.
'''
return pattern(*[c.dock(other) for c in self.concs]) | def dock(self, other) | The opposite of concatenation. Remove a common suffix from the present
pattern; that is, from each of its constituent concs.
AYZ|BYZ|CYZ - YZ = A|B|C. | 18.485912 | 2.271767 | 8.137241 |
'''
Like dock() but the other way around. Remove a common prefix from the
present pattern; that is, from each of its constituent concs.
ZA|ZB|ZC.behead(Z) = A|B|C
'''
return pattern(*[c.behead(other) for c in self.concs]) | def behead(self, other) | Like dock() but the other way around. Remove a common prefix from the
present pattern; that is, from each of its constituent concs.
ZA|ZB|ZC.behead(Z) = A|B|C | 15.273121 | 2.101367 | 7.268183 |
'''
Find the longest conc which acts as prefix to every conc in this pattern.
This could be the empty string. Return the common prefix along with all
the leftovers after truncating that common prefix from each conc.
"ZA|ZB|ZC" -> "Z", "(A|B|C)"
"ZA|ZB|ZC|Z" -> "Z", "(A|B|C|)"
"CZ|CZ" -> "CZ", "()"
... | def _commonconc(self, suffix=False) | Find the longest conc which acts as prefix to every conc in this pattern.
This could be the empty string. Return the common prefix along with all
the leftovers after truncating that common prefix from each conc.
"ZA|ZB|ZC" -> "Z", "(A|B|C)"
"ZA|ZB|ZC|Z" -> "Z", "(A|B|C|)"
"CZ|CZ" -> "CZ", "()"
If "su... | 5.343563 | 1.629715 | 3.278833 |
''' This function don't use the plugin. '''
session = create_session()
try:
user = session.query(User).filter_by(name=name).first()
session.delete(user)
session.commit()
except SQLAlchemyError, e:
session.rollback()
raise bottle.HTTPError(500, "Database Error", e)... | def delete_name(name) | This function don't use the plugin. | 3.479029 | 2.806621 | 1.239579 |
''' Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available.'''
for other in app.plugins:
if not isinstance(other, SQLAlchemyPlugin):
continue
if other.keyword == self.keyword:
ra... | def setup(self, app) | Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available. | 9.02348 | 5.261705 | 1.714935 |
self.__in_send_multipart = True
try:
msg = super(GreenSocket, self).send_multipart(*args, **kwargs)
finally:
self.__in_send_multipart = False
self.__state_changed()
return msg | def send_multipart(self, *args, **kwargs) | wrap send_multipart to prevent state_changed on each partial send | 3.665802 | 2.809468 | 1.304803 |
self.__in_recv_multipart = True
try:
msg = super(GreenSocket, self).recv_multipart(*args, **kwargs)
finally:
self.__in_recv_multipart = False
self.__state_changed()
return msg | def recv_multipart(self, *args, **kwargs) | wrap recv_multipart to prevent state_changed on each partial recv | 3.635674 | 2.776999 | 1.30921 |
ext_file = os.path.abspath(str(ext_file))
F = pd.read_table(
ext_file,
header=[0, 1],
index_col=list(range(index_col)),
sep=sep)
F.columns.names = ['region', 'sector']
if index_col == 1:
F.index.names = ['stressor']
elif index_col == 2:
F.ind... | def parse_exio12_ext(ext_file, index_col, name, drop_compartment=True,
version=None, year=None, iosystem=None, sep=',') | Parse an EXIOBASE version 1 or 2 like extension file into pymrio.Extension
EXIOBASE like extensions files are assumed to have two
rows which are used as columns multiindex (region and sector)
and up to three columns for the row index (see Parameters).
For EXIOBASE 3 - extension can be loaded directly ... | 2.442121 | 1.966424 | 1.24191 |
try:
ver_match = re.search(r'(\d+\w*(\.|\-|\_))*\d+\w*', filename)
version = ver_match.string[ver_match.start():ver_match.end()]
if re.search('\_\d\d\d\d', version[-5:]):
version = version[:-5]
except AttributeError:
version = None
return version | def get_exiobase12_version(filename) | Returns the EXIOBASE version for the given filename,
None if not found | 3.838233 | 3.978773 | 0.964678 |
path = os.path.normpath(str(path))
if coefficients:
exio_core_regex = dict(
# don’t match file if starting with _
A=re.compile('(?<!\_)mrIot.*txt'),
Y=re.compile('(?<!\_)mrFinalDemand.*txt'),
S_factor_inputs=re.compile('(?<!\_)mrFactorInputs.*txt'),
... | def get_exiobase_files(path, coefficients=True) | Gets the EXIOBASE files in path (which can be a zip file)
Parameters
----------
path: str or pathlib.Path
Path to exiobase files or zip file
coefficients: boolean, optional
If True (default), considers the mrIot file as A matrix,
and the extensions as S matrices. Otherwise as Z ... | 2.749621 | 2.635972 | 1.043115 |
ispxp = True if re.search('pxp', path, flags=re.IGNORECASE) else False
isixi = True if re.search('ixi', path, flags=re.IGNORECASE) else False
if ispxp == isixi:
system = None
else:
system = 'pxp' if ispxp else 'ixi'
return system | def _get_MRIO_system(path) | Extract system information (ixi, pxp) from file path.
Returns 'ixi' or 'pxp', None in undetermined | 2.948079 | 2.350095 | 1.254451 |
path = os.path.abspath(os.path.normpath(str(path)))
exio_files = get_exiobase_files(path)
if len(exio_files) == 0:
raise ParserError("No EXIOBASE files found at {}".format(path))
system = _get_MRIO_system(path)
if not system:
logging.warning("Could not determine system (pxp or... | def parse_exiobase1(path) | Parse the exiobase1 raw data files.
This function works with
- pxp_ita_44_regions_coeff_txt
- ixi_fpa_44_regions_coeff_txt
- pxp_ita_44_regions_coeff_src_txt
- ixi_fpa_44_regions_coeff_src_txt
which can be found on www.exiobase.eu
The parser works with the compressed (zip) files as well ... | 6.513347 | 5.555137 | 1.172491 |
io = load_all(path)
# need to rename the final demand satellite,
# wrong name in the standard distribution
try:
io.satellite.FY = io.satellite.F_hh.copy()
del io.satellite.F_hh
except AttributeError:
pass
# some ixi in the exiobase 3.4 official distribution
# ha... | def parse_exiobase3(path) | Parses the public EXIOBASE 3 system
This parser works with either the compressed zip
archive as downloaded or the extracted system.
Note
----
The exiobase 3 parser does so far not include
population and characterization data.
Parameters
----------
path : string or pathlib.Path
... | 2.578382 | 2.622417 | 0.983208 |
sea_ext = '.xlsx'
sea_start = 'WIOD_SEA'
_SEA_folder = os.path.join(root_path, 'SEA')
if not os.path.exists(_SEA_folder):
_SEA_folder = root_path
sea_folder_content = [ff for ff in os.listdir(_SEA_folder)
if os.path.splitext(ff)[-1] == sea_ext and
... | def __get_WIOD_SEA_extension(root_path, year, data_sheet='DATA') | Utility function to get the extension data from the SEA file in WIOD
This function is based on the structure in the WIOD_SEA_July14 file.
Missing values are set to zero.
The function works if the SEA file is either in path or in a subfolder
named 'SEA'.
Parameters
----------
root_path : s... | 3.655887 | 3.742366 | 0.976892 |
meta_string = "{time} - {etype} - {entry}".format(
time=self._time(),
etype=entry_type.upper(),
entry=entry)
self._content['history'].insert(0, meta_string)
self.logger(meta_string) | def _add_history(self, entry_type, entry) | Generic method to add entry as entry_type to the history | 5.695344 | 5.346391 | 1.065269 |
if not new_value:
return
para = para.lower()
if para == 'history':
raise ValueError(
'History can only be extended - use method "note"')
old_value = self._content.get(para, None)
if new_value == old_value:
return
... | def change_meta(self, para, new_value, log=True) | Changes the meta data
This function does nothing if None is passed as new_value.
To set a certain value to None pass the str 'None'
Parameters
----------
para: str
Meta data entry to change
new_value: str
New value
log: boolean, optiona... | 3.873816 | 4.38262 | 0.883904 |
if self._path_in_arc:
with zipfile.ZipFile(file=str(self._metadata_file)) as zf:
self._content = json.loads(
zf.read(self._path_in_arc).decode('utf-8'),
object_pairs_hook=OrderedDict)
else:
with self._metadata_file.... | def _read_content(self) | Reads metadata from location (and path_in_arc if archive)
This function is called during the init process and
should not be used in isolation: it overwrites
unsafed metadata. | 2.824835 | 2.314905 | 1.220281 |
if location:
location = Path(location)
if os.path.splitext(str(location))[1] == '':
self._metadata_file = location / DEFAULT_FILE_NAMES['metadata']
else:
self._metadata_file = location
if self._metadata_file:
with ... | def save(self, location=None) | Saves the current status of the metadata
This saves the metadata at the location of the previously loaded
metadata or at the file/path given in location.
Specify a location if the metadata should be stored in a different
location or was never stored before. Subsequent saves will use th... | 3.401207 | 3.202421 | 1.062074 |
x = np.reshape(np.sum(np.hstack((Z, Y)), 1), (-1, 1))
if type(Z) is pd.DataFrame:
x = pd.DataFrame(x, index=Z.index, columns=['indout'])
if type(x) is pd.Series:
x = pd.DataFrame(x)
if type(x) is pd.DataFrame:
x.columns = ['indout']
return x | def calc_x(Z, Y) | Calculate the industry output x from the Z and Y matrix
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
Y : pandas.DataFrame or numpy.array
final demand with categories (1.order) for each country (2.order)
Returns
-------
panda... | 2.728836 | 3.133611 | 0.870828 |
x = L.dot(y)
if type(x) is pd.Series:
x = pd.DataFrame(x)
if type(x) is pd.DataFrame:
x.columns = ['indout']
return x | def calc_x_from_L(L, y) | Calculate the industry output x from L and a y vector
Parameters
----------
L : pandas.DataFrame or numpy.array
Symmetric input output Leontief table
y : pandas.DataFrame or numpy.array
a column vector of the total final demand
Returns
-------
pandas.DataFrame or numpy.arra... | 4.345253 | 4.723167 | 0.919987 |
if (type(x) is pd.DataFrame) or (type(x) is pd.Series):
x = x.values
x = x.reshape((1, -1)) # use numpy broadcasting - much faster
# (but has to ensure that x is a row vector)
# old mathematical form:
# return A.dot(np.diagflat(x))
if type(A) is pd.DataFrame:
return pd.Dat... | def calc_Z(A, x) | calculate the Z matrix (flows) from A and x
Parameters
----------
A : pandas.DataFrame or numpy.array
Symmetric input output table (coefficients)
x : pandas.DataFrame or numpy.array
Industry output column vector
Returns
-------
pandas.DataFrame or numpy.array
Symmet... | 4.913734 | 5.602151 | 0.877116 |
if (type(x) is pd.DataFrame) or (type(x) is pd.Series):
x = x.values
if (type(x) is not np.ndarray) and (x == 0):
recix = 0
else:
with warnings.catch_warnings():
# catch the divide by zero warning
# we deal wit that by setting to 0 afterwards
... | def calc_A(Z, x) | Calculate the A matrix (coefficients) from Z and x
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
x : pandas.DataFrame or numpy.array
Industry output column vector
Returns
-------
pandas.DataFrame or numpy.array
Symmet... | 4.473062 | 5.04419 | 0.886775 |
I = np.eye(A.shape[0]) # noqa
if type(A) is pd.DataFrame:
return pd.DataFrame(np.linalg.inv(I-A),
index=A.index, columns=A.columns)
else:
return np.linalg.inv(I-A) | def calc_L(A) | Calculate the Leontief L from A
Parameters
----------
A : pandas.DataFrame or numpy.array
Symmetric input output table (coefficients)
Returns
-------
pandas.DataFrame or numpy.array
Leontief input output table L
The type is determined by the type of A.
If DataFr... | 2.655099 | 3.086918 | 0.860113 |
Y_diag = ioutil.diagonalize_blocks(Y.values, blocksize=nr_sectors)
Y_inv = np.linalg.inv(Y_diag)
M = D_cba.dot(Y_inv)
if type(D_cba) is pd.DataFrame:
M.columns = D_cba.columns
M.index = D_cba.index
return M | def recalc_M(S, D_cba, Y, nr_sectors) | Calculate Multipliers based on footprints.
Parameters
----------
D_cba : pandas.DataFrame or numpy array
Footprint per sector and country
Y : pandas.DataFrame or numpy array
Final demand: aggregated across categories or just one category, one
column per country. This will be dia... | 3.969727 | 3.992249 | 0.994359 |
# diagonalize each sector block per country
# this results in a disaggregated y with final demand per country per
# sector in one column
Y_diag = ioutil.diagonalize_blocks(Y.values, blocksize=nr_sectors)
x_diag = L.dot(Y_diag)
x_tot = x_diag.values.sum(1)
del Y_diag
D_cba = pd.Data... | def calc_accounts(S, L, Y, nr_sectors) | Calculate sector specific cba and pba based accounts, imp and exp accounts
The total industry output x for the calculation
is recalculated from L and y
Parameters
----------
L : pandas.DataFrame
Leontief input output table L
S : pandas.DataFrame
Direct impact coefficients
Y... | 4.199969 | 3.53553 | 1.187932 |
# Use post here - NB: get could be necessary for some other pages
# but currently works for wiod and eora
returnvalue = namedtuple('url_content',
['raw_text', 'data_urls'])
url_text = requests.post(url_db_view, cookies=access_cookie).text
data_urls = [url_db_content... | def _get_url_datafiles(url_db_view, url_db_content,
mrio_regex, access_cookie=None) | Urls of mrio files by parsing url content for mrio_regex
Parameters
----------
url_db_view: url str
Url which shows the list of mrios in the db
url_db_content: url str
Url which needs to be appended before the url parsed from the
url_db_view to get a valid download link
m... | 7.237755 | 7.077549 | 1.022636 |
for url in url_list:
filename = os.path.basename(url)
if not overwrite_existing and filename in os.listdir(storage_folder):
continue
storage_file = os.path.join(storage_folder, filename)
# Using requests here - tried with aiohttp but was actually slower
# Al... | def _download_urls(url_list, storage_folder, overwrite_existing,
meta_handler, access_cookie=None) | Save url from url_list to storage_folder
Parameters
----------
url_list: list of str
Valid url to download
storage_folder: str, valid path
Location to store the download, folder will be created if
not existing. If the file is already present in the folder,
the download ... | 4.686969 | 5.295656 | 0.885059 |
try:
os.makedirs(storage_folder)
except FileExistsError:
pass
if type(years) is int or type(years) is str:
years = [years]
years = years if years else range(1995, 2012)
years = [str(yy).zfill(2)[-2:] for yy in years]
wiod_web_content = _get_url_datafiles(
... | def download_wiod2013(storage_folder, years=None, overwrite_existing=False,
satellite_urls=WIOD_CONFIG['satellite_urls']) | Downloads the 2013 wiod release
Note
----
Currently, pymrio only works with the 2013 release of the wiod tables. The
more recent 2016 release so far (October 2017) lacks the environmental and
social extensions.
Parameters
----------
storage_folder: str, valid path
Location to ... | 5.179879 | 5.004388 | 1.035067 |
s = '%.6f' % time.time()
whole, frac = map(int, s.split('.'))
res = '%d%d' % (whole, frac)
return res[:length] | def get_timestamp(length) | Get a timestamp of `length` in string | 4.578208 | 4.23881 | 1.080069 |
if PY3:
return os.makedirs(path, exist_ok=True)
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | def mkdir_p(path) | mkdir -p path | 1.765566 | 1.782433 | 0.990537 |
ozmq = __import__('zmq')
ozmq.Socket = zmq.Socket
ozmq.Context = zmq.Context
ozmq.Poller = zmq.Poller
ioloop = __import__('zmq.eventloop.ioloop')
ioloop.Poller = zmq.Poller | def monkey_patch() | Monkey patches `zmq.Context` and `zmq.Socket`
If test_suite is True, the pyzmq test suite will be patched for
compatibility as well. | 3.556066 | 3.647326 | 0.974979 |
# Attriubtes to keep must be defined in the init: __basic__
strwarn = None
for df in self.__basic__:
if (getattr(self, df)) is None:
if force:
strwarn = ("Reset system warning - Recalculation after "
"reset n... | def reset_full(self, force=False, _meta=None) | Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
_meta: MRIOMetaData, optional
Metadata handler for ... | 9.868936 | 9.55399 | 1.032965 |
# Development note: The attributes which should be removed are
# defined in self.__non_agg_attributes__
strwarn = None
for df in self.__basic__:
if (getattr(self, df)) is None:
if force:
strwarn = ("Reset system warning - Recalcula... | def reset_to_flows(self, force=False, _meta=None) | Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. D... | 8.939805 | 8.140778 | 1.098151 |
# Development note: The coefficient attributes are
# defined in self.__coefficients__
[setattr(self, key, None)
for key in self.get_DataFrame(
data=False,
with_unit=False,
with_population=False)
if key not in self.__coefficients__... | def reset_to_coefficients(self) | Keeps only the coefficient.
This can be used to recalculate the IO tables for a new finald demand.
Note
-----
The system can not be reconstructed after this steps
because all absolute data is removed. Save the Y data in case
a reconstruction might be necessary. | 10.005669 | 11.986589 | 0.834739 |
_tmp = copy.deepcopy(self)
if not new_name:
new_name = self.name + '_copy'
if str(type(self)) == "<class 'pymrio.core.mriosystem.IOSystem'>":
_tmp.meta.note('IOSystem copy {new} based on {old}'.format(
new=new_name, old=self.meta.name))
... | def copy(self, new_name=None) | Returns a deep copy of the system
Parameters
-----------
new_name: str, optional
Set a new meta name parameter.
Default: <old_name>_copy | 4.971914 | 4.830913 | 1.029187 |
possible_dataframes = ['Y', 'FY']
for df in possible_dataframes:
if (df in self.__dict__) and (getattr(self, df) is not None):
try:
ind = getattr(self, df).columns.get_level_values(
'category').unique()
exc... | def get_Y_categories(self, entries=None) | Returns names of y cat. of the IOSystem as unique names in order
Parameters
----------
entries : List, optional
If given, retuns an list with None for all values not in entries.
Returns
-------
Index
List of categories, None if no attribute to de... | 3.897225 | 3.853076 | 1.011458 |
possible_dataframes = ['A', 'L', 'Z', 'Y', 'F', 'FY', 'M', 'S',
'D_cba', 'D_pba', 'D_imp', 'D_exp',
'D_cba_reg', 'D_pba_reg',
'D_imp_reg', 'D_exp_reg',
'D_cba_cap', 'D_pba_cap',... | def get_index(self, as_dict=False, grouping_pattern=None) | Returns the index of the DataFrames in the system
Parameters
----------
as_dict: boolean, optional
If True, returns a 1:1 key-value matching for further processing
prior to groupby functions. Otherwise (default) the index
is returned as pandas index.
... | 3.16188 | 3.107037 | 1.017651 |
for df in self.get_DataFrame(data=True, with_population=False):
df.index = index | def set_index(self, index) | Sets the pd dataframe index of all dataframes in the system to index | 14.512142 | 11.633889 | 1.247402 |
for key in self.__dict__:
if (key is 'unit') and not with_unit:
continue
if (key is 'population') and not with_population:
continue
if type(self.__dict__[key]) is pd.DataFrame:
if data:
yield getatt... | def get_DataFrame(self, data=False, with_unit=True, with_population=True) | Yields all panda.DataFrames or there names
Notes
-----
For IOSystem this does not include the DataFrames in the extensions.
Parameters
----------
data : boolean, optional
If True, returns a generator which yields the DataFrames.
If False, returns... | 2.461757 | 2.450471 | 1.004606 |
if type(path) is str:
path = path.rstrip('\\')
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
para_file_path = path / DEFAULT_FILE_NAMES['filepara']
file_para = dict()
file_para['files'] = dict()
if table_format in ['text', ... | def save(self, path, table_format='txt', sep='\t',
table_ext=None, float_format='%.12g') | Saving the system to path
Parameters
----------
path : pathlib.Path or string
path for the saved data (will be created if necessary, data
within will be overwritten).
table_format : string
Format to save the DataFrames:
- 'pkl' : Bi... | 2.590286 | 2.550145 | 1.015741 |
if type(regions) is list:
regions = {old: new for old, new in
zip(self.get_regions(), regions)}
for df in self.get_DataFrame(data=True):
df.rename(index=regions, columns=regions, inplace=True)
try:
for ext in self.get_extensi... | def rename_regions(self, regions) | Sets new names for the regions
Parameters
----------
regions : list or dict
In case of dict: {'old_name' : 'new_name'} with a
entry for each old_name which should be renamed
In case of list: List of new names in order and complete
without... | 3.779451 | 3.890427 | 0.971475 |
if type(sectors) is list:
sectors = {old: new for old, new in
zip(self.get_sectors(), sectors)}
for df in self.get_DataFrame(data=True):
df.rename(index=sectors, columns=sectors, inplace=True)
try:
for ext in self.get_extensi... | def rename_sectors(self, sectors) | Sets new names for the sectors
Parameters
----------
sectors : list or dict
In case of dict: {'old_name' : 'new_name'} with an
entry for each old_name which should be renamed
In case of list: List of new names in order and
complete withou... | 3.342457 | 3.423836 | 0.976232 |
if type(Y_categories) is list:
Y_categories = {old: new for old, new in
zip(self.get_Y_categories(), Y_categories)}
for df in self.get_DataFrame(data=True):
df.rename(index=Y_categories, columns=Y_categories, inplace=True)
try:
... | def rename_Y_categories(self, Y_categories) | Sets new names for the Y_categories
Parameters
----------
Y_categories : list or dict
In case of dict: {'old_name' : 'new_name'} with an
entry for each old_name which should be renamed
In case of list: List of new names in order and
compl... | 3.182742 | 3.305863 | 0.962757 |
possible_dataframes = ['F', 'FY', 'M', 'S',
'D_cba', 'D_pba', 'D_imp', 'D_exp',
'D_cba_reg', 'D_pba_reg',
'D_imp_reg', 'D_exp_reg',
'D_cba_cap', 'D_pba_cap',
... | def get_rows(self) | Returns the name of the rows of the extension | 4.236165 | 3.989152 | 1.061921 |
retdict = {}
for rowname, data in zip(self.get_DataFrame(),
self.get_DataFrame(data=True)):
retdict[rowname] = pd.DataFrame(data.ix[row])
if name:
retdict['name'] = name
return retdict | def get_row_data(self, row, name=None) | Returns a dict with all available data for a row in the extension
Parameters
----------
row : tuple, list, string
A valid index for the extension DataFrames
name : string, optional
If given, adds a key 'name' with the given value to the dict. In
that ... | 4.572218 | 4.7759 | 0.957352 |
if type(stressor) is int:
stressor = self.F.index[stressor]
if len(stressor) == 1:
stressor = stressor[0]
if not name:
if type(stressor) is str:
name = stressor
else:
name = '_'.join(stressor) + '_diag'
... | def diag_stressor(self, stressor, name=None) | Diagonalize one row of the stressor matrix for a flow analysis.
This method takes one row of the F matrix and diagonalize
to the full region/sector format. Footprints calculation based
on this matrix show the flow of embodied stressors from the source
region/sector (row index) to the fi... | 3.071768 | 2.858664 | 1.074547 |
# Possible cases:
# 1) Z given, rest can be None and calculated
# 2) A and x given, rest can be calculated
# 3) A and Y , calc L (if not given) - calc x and the rest
# this catches case 3
if self.x is None and self.Z is None:
# in that case we need ... | def calc_system(self) | Calculates the missing part of the core IOSystem
The method checks Z, x, A, L and calculates all which are None | 4.455092 | 3.97296 | 1.121354 |
ext_list = list(self.get_extensions(data=False))
extensions = extensions or ext_list
if type(extensions) == str:
extensions = [extensions]
for ext_name in extensions:
self.meta._add_modify(
'Calculating accounts for extension {}'.format(... | def calc_extensions(self, extensions=None, Y_agg=None) | Calculates the extension and their accounts
For the calculation, y is aggregated across specified y categories
The method calls .calc_system of each extension (or these given in the
extensions parameter)
Parameters
----------
extensions : list of strings, optional
... | 4.894117 | 4.689147 | 1.043712 |
for ext in self.get_extensions(data=True):
ext.report_accounts(path=path,
per_region=per_region,
per_capita=per_capita,
pic_size=pic_size,
format=format,
... | def report_accounts(self, path, per_region=True,
per_capita=False, pic_size=1000,
format='rst', **kwargs) | Generates a report to the given path for all extension
This method calls .report_accounts for all extensions
Notes
-----
This looks prettier with the seaborn module (import seaborn before
calling this method)
Parameters
----------
path : string
... | 2.229424 | 2.284874 | 0.975732 |
ext_list = [key for key in
self.__dict__ if type(self.__dict__[key]) is Extension]
for key in ext_list:
if data:
yield getattr(self, key)
else:
yield key | def get_extensions(self, data=False) | Yields the extensions or their names
Parameters
----------
data : boolean, optional
If True, returns a generator which yields the extensions.
If False, returns a generator which yields the names of
the extensions (default)
Returns
-------
... | 3.627363 | 3.802001 | 0.954067 |
super().reset_full(force=force, _meta=self.meta)
return self | def reset_full(self, force=False) | Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False | 9.267924 | 14.507744 | 0.638826 |
self.reset_full()
[ee.reset_full() for ee in self.get_extensions(data=True)]
self.meta._add_modify("Reset all calculated data")
return self | def reset_all_full(self, force=False) | Removes all accounts that can be recalculated (IOSystem and extensions)
This calls reset_full for the core system and all extension.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: Fal... | 15.502797 | 16.725517 | 0.926895 |
super().reset_to_flows(force=force, _meta=self.meta)
return self | def reset_to_flows(self, force=False) | Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. D... | 7.694775 | 14.872345 | 0.517388 |
self.reset_to_flows(force=force)
[ee.reset_to_flows(force=force)
for ee in self.get_extensions(data=True)]
self.meta._add_modify("Reset full system to absolute flows")
return self | def reset_all_to_flows(self, force=False) | Resets the IOSystem and all extensions to absolute flows
This method calls reset_to_flows for the IOSystem and for
all Extensions in the system.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalc... | 10.089065 | 9.137995 | 1.104079 |
self.reset_to_coefficients()
[ee.reset_to_coefficients() for ee in self.get_extensions(data=True)]
self.meta._add_modify("Reset full system to coefficients")
return self | def reset_all_to_coefficients(self) | Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
because all absolute data is removed. Save the Y data i... | 10.497519 | 9.524316 | 1.102181 |
if type(path) is str:
path = path.rstrip('\\')
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
self.save(path=path,
table_format=table_format,
sep=sep,
table_ext=table_ext,
float... | def save_all(self, path, table_format='txt', sep='\t',
table_ext=None, float_format='%.12g') | Saves the system and all extensions
Extensions are saved in separate folders (names based on extension)
Parameters are passed to the .save methods of the IOSystem and
Extensions. See parameters description there. | 2.197171 | 2.108382 | 1.042112 |
if ext is None:
ext = list(self.get_extensions())
if type(ext) is str:
ext = [ext]
for ee in ext:
try:
del self.__dict__[ee]
except KeyError:
for exinstancename, exdata in zip(
self.... | def remove_extension(self, ext=None) | Remove extension from IOSystem
For single Extensions the same can be achieved with del
IOSystem_name.Extension_name
Parameters
----------
ext : string or list, optional
The extension to remove, this can be given as the name of the
instance or of Extensio... | 4.100125 | 3.755125 | 1.091875 |
inp = np.asarray(inp)
nr_dim = np.ndim(inp)
if nr_dim == 1:
return True
elif (nr_dim == 2) and (1 in inp.shape):
return True
else:
return False | def is_vector(inp) | Returns true if the input can be interpreted as a 'true' vector
Note
----
Does only check dimensions, not if type is numeric
Parameters
----------
inp : numpy.ndarray or something that can be converted into ndarray
Returns
-------
Boolean
True for vectors: ndim = 1 or ndim... | 2.497269 | 3.145548 | 0.793906 |
path = Path(path)
if zipfile.is_zipfile(str(path)):
with zipfile.ZipFile(str(path)) as zz:
filelist = [info.filename for info in zz.infolist()]
iszip = True
else:
iszip = False
filelist = [str(f) for f in path.glob('**/*') if f.is_file()]
return namedtup... | def get_repo_content(path) | List of files in a repo (path or zip)
Parameters
----------
path: string or pathlib.Path
Returns
-------
Returns a namedtuple with .iszip and .filelist
The path in filelist are pure strings. | 2.6664 | 2.152183 | 1.238928 |
if type(path) is str:
path = Path(path.rstrip('\\'))
if zipfile.is_zipfile(str(path)):
para_file_folder = str(path_in_arc)
with zipfile.ZipFile(file=str(path)) as zf:
files = zf.namelist()
else:
para_file_folder = str(path)
files = [str(f) for f in p... | def get_file_para(path, path_in_arc='') | Generic method to read the file parameter file
Helper function to consistently read the file parameter file, which can
either be uncompressed or included in a zip archive. By default, the file
name is to be expected as set in DEFAULT_FILE_NAMES['filepara'] (currently
file_parameters.json), but can def... | 2.145385 | 1.873938 | 1.144854 |
if isinstance(agg_vector, np.ndarray):
agg_vector = agg_vector.flatten().tolist()
if type(agg_vector[0]) == str:
str_vector = agg_vector
agg_vector = np.zeros(len(str_vector))
if pos_dict:
if len(pos_dict.keys()) != len(set(str_vector)):
raise Va... | def build_agg_matrix(agg_vector, pos_dict=None) | Agg. matrix based on mapping given in input as numerical or str vector.
The aggregation matrix has the from nxm with
-n new classificaction
-m old classification
Parameters
----------
agg_vector : list or vector like numpy ndarray
This can be row or column vector.
... | 2.568204 | 2.633969 | 0.975032 |
nr_col = arr.shape[1]
nr_row = arr.shape[0]
if np.mod(nr_row, blocksize):
raise ValueError(
'Number of rows of input array must be a multiple of blocksize')
arr_diag = np.zeros((nr_row, blocksize*nr_col))
for col_ind, col_val in enumerate(arr.T):
col_start = col_... | def diagonalize_blocks(arr, blocksize) | Diagonalize sections of columns of an array for the whole array
Parameters
----------
arr : numpy array
Input array
blocksize : int
number of rows/colums forming one block
Returns
-------
numpy ndarray with shape (columns 'arr' * blocksize,
c... | 2.356679 | 2.432216 | 0.968943 |
nr_col = arr.shape[1]
nr_row = arr.shape[0]
nr_col_block = arr_block.shape[1]
nr_row_block = arr_block.shape[0]
if np.mod(nr_row, nr_row_block) or np.mod(nr_col, nr_col_block):
raise ValueError('Number of rows/columns of the input array '
'must be a multiple o... | def set_block(arr, arr_block) | Sets the diagonal blocks of an array to an given array
Parameters
----------
arr : numpy ndarray
the original array
block_arr : numpy ndarray
the block array for the new diagonal
Returns
-------
numpy ndarray (the modified array) | 2.153008 | 2.172856 | 0.990866 |
seen = {}
result = []
for item in ll:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result | def unique_element(ll) | returns unique elements from a list preserving the original order | 2.079761 | 1.953131 | 1.064835 |
for nr, entry in enumerate(ll):
try:
float(entry)
except (ValueError, TypeError) as e:
pass
else:
return nr
return None | def find_first_number(ll) | Returns nr of first entry parseable to float in ll, None otherwise | 4.059216 | 2.492769 | 1.628397 |
def read_first_lines(filehandle):
lines = []
for i in range(max_test_lines):
line = ff.readline()
if line == '':
break
try:
line = line.decode('utf-8')
except AttributeError:
pass
lines.... | def sniff_csv_format(csv_file,
potential_sep=['\t', ',', ';', '|', '-', '_'],
max_test_lines=10,
zip_file=None) | Tries to get the separator, nr of index cols and header rows in a csv file
Parameters
----------
csv_file: str
Path to a csv file
potential_sep: list, optional
List of potential separators (delimiters) to test.
Default: '\t', ',', ';', '|', '-', '_'
max_test_lines: int, o... | 2.254467 | 2.104145 | 1.071441 |
rlist = []
wlist = []
xlist = []
for socket, flags in self.sockets.items():
if isinstance(socket, zmq.Socket):
rlist.append(socket.getsockopt(zmq.FD))
continue
elif isinstance(socket, int):
fd = socket
... | def _get_descriptors(self) | Returns three elements tuple with socket descriptors ready
for gevent.select.select | 2.63343 | 2.340781 | 1.125022 |
if timeout is None:
timeout = -1
if timeout < 0:
timeout = -1
rlist = None
wlist = None
xlist = None
if timeout > 0:
tout = gevent.Timeout.start_new(timeout/1000.0)
try:
# Loop until timeout or events a... | def poll(self, timeout=-1) | Overridden method to ensure that the green version of
Poller is used.
Behaves the same as :meth:`zmq.core.Poller.poll` | 4.042084 | 3.632162 | 1.112859 |
file_id = kwargs['file_id']
kwargs['file_id'] = file_id if str(file_id).strip() else None
kwargs['cid'] = kwargs['file_id'] or None
kwargs['rate_download'] = kwargs['rateDownload']
kwargs['percent_done'] = kwargs['percentDone']
kwargs['add_time'] = get_utcdatetime(kwargs['add_time'])
kw... | def _instantiate_task(api, kwargs) | Create a Task object from raw kwargs | 3.455542 | 3.38128 | 1.021963 |
r = self.session.get(url, params=params)
return self._response_parser(r, expect_json=False) | def get(self, url, params=None) | Initiate a GET request | 4.365252 | 4.710257 | 0.926755 |
r = self.session.post(url, data=data, params=params)
return self._response_parser(r, expect_json=False) | def post(self, url, data, params=None) | Initiate a POST request | 3.65593 | 4.039637 | 0.905015 |
r = self.session.request(method=request.method,
url=request.url,
params=request.params,
data=request.data,
files=request.files,
headers=re... | def send(self, request, expect_json=True, ignore_content=False) | Send a formatted API request
:param request: a formatted request object
:type request: :class:`.Request`
:param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if
response is not in JSON format
:param bool ignore_content: whether to ignore setting content of the
... | 2.280971 | 2.612687 | 0.873037 |
if r.ok:
try:
j = r.json()
return Response(j.get('state'), j)
except ValueError:
# No JSON-encoded data returned
if expect_json:
logger = logging.getLogger(conf.LOGGING_API_LOGGER)
... | def _response_parser(self, r, expect_json=True, ignore_content=False) | :param :class:`requests.Response` r: a response object of the Requests
library
:param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if
response is not in JSON format
:param bool ignore_content: whether to ignore setting content of the
Response object | 4.307644 | 3.958281 | 1.088261 |
self._init_cookies()
if os.path.exists(self.cookies.filename):
self.cookies.load(ignore_discard=ignore_discard,
ignore_expires=ignore_expires)
self._reset_cache() | def load_cookies(self, ignore_discard=True, ignore_expires=True) | Load cookies from the file :attr:`.API.cookies_filename` | 3.211503 | 3.050335 | 1.052836 |
if not isinstance(self.cookies, cookielib.FileCookieJar):
m = 'Cookies must be a cookielib.FileCookieJar object to be saved.'
raise APIError(m)
self.cookies.save(ignore_discard=ignore_discard,
ignore_expires=ignore_expires) | def save_cookies(self, ignore_discard=True, ignore_expires=True) | Save cookies to the file :attr:`.API.cookies_filename` | 3.0543 | 2.89833 | 1.053814 |
if self.has_logged_in:
return True
if username is None or password is None:
credential = conf.get_credential(section)
username = credential['username']
password = credential['password']
passport = Passport(username, password)
r = ... | def login(self, username=None, password=None,
section='default') | Created the passport with ``username`` and ``password`` and log in.
If either ``username`` or ``password`` is None or omitted, the
credentials file will be parsed.
:param str username: username to login (email, phone number or user ID)
:param str password: password
:param str se... | 3.721547 | 3.685889 | 1.009674 |
if self._user_id is None:
if self.has_logged_in:
self._user_id = self._req_get_user_aq()['data']['uid']
else:
raise AuthenticationError('Not logged in.')
return self._user_id | def user_id(self) | User id of the current API user | 6.009076 | 5.341576 | 1.124963 |
if self._username is None:
if self.has_logged_in:
self._username = self._get_username()
else:
raise AuthenticationError('Not logged in.')
return self._username | def username(self) | Username of the current API user | 3.573343 | 3.540927 | 1.009155 |
r = self.http.get(CHECKPOINT_URL)
if r.state is False:
return True
# If logged out, flush cache
self._reset_cache()
return False | def has_logged_in(self) | Check whether the API has logged in | 12.072679 | 10.248111 | 1.178039 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.