_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8400 | IrcObject.from_config | train | def from_config(cls, cfg, **kwargs):
"""return an instance configured with the ``cfg`` dict"""
cfg = dict(cfg, **kwargs)
pythonpath = cfg.get('pythonpath', [])
if 'here' in cfg:
pythonpath.append(cfg['here'])
for path in pythonpath:
sys.path.append(os.path.expanduser(path))
prog = cls.server and 'irc3d' or 'irc3'
if cfg.get('debug'):
cls.venusian_categories.append(prog + '.debug')
if cfg.get('interactive'): # pragma: no cover
import irc3.testing
| python | {
"resource": ""
} |
q8401 | AsyncLibrary.async_run | train | def async_run(self, keyword, *args, **kwargs):
''' Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get '''
handle = self._last_thread_handle
| python | {
"resource": ""
} |
q8402 | AsyncLibrary.async_get | train | def async_get(self, handle):
''' Blocks until the thread created by async_run returns '''
assert handle in | python | {
"resource": ""
} |
q8403 | AsyncLibrary._get_handler_from_keyword | train | def _get_handler_from_keyword(self, keyword):
''' Gets the Robot Framework handler associated with the given keyword '''
if EXECUTION_CONTEXTS.current is None:
| python | {
"resource": ""
} |
q8404 | PMMail._set_attachments | train | def _set_attachments(self, value):
'''
A special set function to ensure
we're setting with a list
'''
if value is None:
setattr(self, '_PMMail__attachments', [])
elif isinstance(value, list):
| python | {
"resource": ""
} |
q8405 | PMMail._check_values | train | def _check_values(self):
'''
Make sure all values are of the appropriate
type and are not missing.
'''
if not self.__api_key:
raise PMMailMissingValueException('Cannot send an e-mail without a Postmark API Key')
elif not self.__sender:
raise PMMailMissingValueException('Cannot send an e-mail without a sender (.sender field)')
elif not self.__to:
raise PMMailMissingValueException('Cannot send an e-mail without at least one recipient (.to field)')
elif (self.__template_id or self.__template_model) and not all([self.__template_id, self.__template_model]):
raise PMMailMissingValueException(
'Cannot send a template e-mail without a both template_id and template_model set')
elif not any([self.__template_id, self.__template_model, self.__subject]):
| python | {
"resource": ""
} |
q8406 | PMMail.send | train | def send(self, test=None):
'''
Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark
'''
self._check_values()
# Set up message dictionary
json_message = self.to_json_message()
# if (self.__html_body and not self.__text_body) and self.__multipart:
# # TODO: Set up regex to strip html
# pass
# If test is not specified, attempt to read the Django setting
if test is None:
try:
from django.conf import settings as django_settings
test = getattr(django_settings, "POSTMARK_TEST_MODE", None)
except ImportError:
pass
# If this is a test, just print the message
if test:
print('JSON message is:\n%s' % json.dumps(json_message, cls=PMJSONEncoder))
return
if self.__template_id:
endpoint_url = __POSTMARK_URL__ + 'email/withTemplate/'
else:
endpoint_url = __POSTMARK_URL__ + 'email'
# Set up the url Request
req = Request(
endpoint_url,
json.dumps(json_message, cls=PMJSONEncoder).encode('utf8'),
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': self.__api_key,
'User-agent': self.__user_agent
}
)
# Attempt send
try:
# print 'sending request to postmark: %s' % json_message
result = urlopen(req)
jsontxt = result.read().decode('utf8')
result.close()
if result.code == 200:
self.message_id = json.loads(jsontxt).get('MessageID', None)
return True
else:
raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))
except HTTPError as err:
if err.code == 401:
raise PMMailUnauthorizedException('Sending Unauthorized - incorrect API key.', err)
elif err.code == 422:
| python | {
"resource": ""
} |
q8407 | PMBatchMail.remove_message | train | def remove_message(self, message):
'''
Remove a message from the batch
'''
| python | {
"resource": ""
} |
q8408 | PMBounceManager.delivery_stats | train | def delivery_stats(self):
'''
Returns a summary of inactive emails and bounces by type.
'''
self._check_values()
req = Request(
__POSTMARK_URL__ + 'deliverystats',
None,
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': self.__api_key,
'User-agent': self.__user_agent
}
)
# Attempt send
try:
| python | {
"resource": ""
} |
q8409 | PMBounceManager.get_all | train | def get_all(self, inactive='', email_filter='', tag='', count=25, offset=0):
'''
Fetches a portion of bounces according to the specified input criteria. The count and offset
parameters are mandatory. You should never retrieve all bounces as that could be excessively
slow for your application. To know how many bounces you have, you need to request a portion
first, usually the first page, and the service will return the count in the TotalCount property
of the response.
'''
self._check_values()
params = '?inactive=' + inactive + '&emailFilter=' + email_filter +'&tag=' + tag
params += '&count=' + str(count) + '&offset=' + str(offset)
req = Request(
__POSTMARK_URL__ + 'bounces' + params,
None,
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Postmark-Server-Token': self.__api_key,
| python | {
"resource": ""
} |
q8410 | PMBounceManager.activate | train | def activate(self, bounce_id):
'''
Activates a deactivated bounce.
'''
self._check_values()
req_url = '/bounces/' + str(bounce_id) + '/activate'
# print req_url
h1 = HTTPConnection('api.postmarkapp.com')
dta = urlencode({"data": "blank"}).encode('utf8')
req = h1.request(
'PUT',
req_url,
dta,
{
| python | {
"resource": ""
} |
q8411 | EmailBackend._build_message | train | def _build_message(self, message):
"""A helper method to convert a PMEmailMessage to a PMMail"""
if not message.recipients():
return False
recipients = ','.join(message.to)
recipients_cc = ','.join(message.cc)
recipients_bcc = ','.join(message.bcc)
text_body = message.body
html_body = None
if isinstance(message, EmailMultiAlternatives):
for alt in message.alternatives:
if alt[1] == "text/html":
html_body = alt[0]
break
elif getattr(message, 'content_subtype', None) == 'html':
# Don't send html content as plain text
text_body = None
html_body = message.body
reply_to = ','.join(message.reply_to)
custom_headers = {}
if message.extra_headers and isinstance(message.extra_headers, dict):
if 'Reply-To' in message.extra_headers:
reply_to = message.extra_headers.pop('Reply-To')
if len(message.extra_headers):
custom_headers = message.extra_headers
attachments = []
if message.attachments and isinstance(message.attachments, list):
if len(message.attachments):
for item in message.attachments:
if isinstance(item, tuple):
(f, content, m) = item
content = base64.b64encode(content)
# b64decode returns bytes on Python 3. PMMail needs a
# str (for JSON serialization). Convert on Python 3
# only to avoid a useless performance hit on Python 2.
if not isinstance(content, str):
| python | {
"resource": ""
} |
q8412 | Nature.handle_starttag | train | def handle_starttag(self, tag, attrs):
'''
PDF link handler; never gets explicitly called by user
'''
if tag == 'a' and ( ('class', 'download-pdf') in attrs or ('id', 'download-pdf') in attrs ):
| python | {
"resource": ""
} |
q8413 | genpass | train | def genpass(pattern=r'[\w]{32}'):
"""generates a password with random chararcters
"""
try:
| python | {
"resource": ""
} |
q8414 | CStruct.unpack | train | def unpack(self, string):
"""
Unpack the string containing packed C structure data
"""
if string is None:
string = CHAR_ZERO * self.__size__
data = struct.unpack(self.__fmt__, string)
i = 0
for field in self.__fields__:
(vtype, vlen) = self.__fields_types__[field]
if vtype == 'char': # string
setattr(self, field, data[i])
i = i + 1
elif isinstance(vtype, CStructMeta):
num = int(vlen / vtype.size)
if num == 1: # single struct
sub_struct = vtype()
sub_struct.unpack(EMPTY_BYTES_STRING.join(data[i:i+sub_struct.size]))
setattr(self, field, sub_struct)
i = i + sub_struct.size
else: # multiple struct
sub_structs = []
| python | {
"resource": ""
} |
q8415 | CStruct.pack | train | def pack(self):
"""
Pack the structure data into a string
"""
data = []
for field in self.__fields__:
(vtype, vlen) = self.__fields_types__[field]
if vtype == 'char': # string
data.append(getattr(self, field))
elif isinstance(vtype, CStructMeta):
num = int(vlen / vtype.size)
if num == 1: # single struct
v = getattr(self, field, vtype())
v = v.pack()
if sys.version_info >= (3, 0):
| python | {
"resource": ""
} |
q8416 | get_all | train | def get_all():
"""Get all subclasses of BaseImporter from module and return and generator
"""
_import_all_importer_files()
for module in (value for key, value in globals().items()
if key in __all__):
for klass_name, klass in inspect.getmembers(module, | python | {
"resource": ""
} |
q8417 | list_database | train | def list_database(db):
"""Print credential as a table"""
credentials = db.credentials()
if credentials:
table = Table(
db.config['headers'],
table_format=db.config['table_format'],
colors=db.config['colors'],
| python | {
"resource": ""
} |
q8418 | check_config | train | def check_config(db, level):
"""Show current configuration for shell"""
if level == 'global':
configuration = config.read(config.HOMEDIR, '.passpierc')
| python | {
"resource": ""
} |
q8419 | RequestHandler.process | train | def process(self, data=None):
"""Fetch incoming data from the Flask request object when no data is supplied
to the process method. By default, the RequestHandler expects the
incoming data | python | {
"resource": ""
} |
q8420 | DBMixin.save | train | def save(self, obj):
"""Add ``obj`` to the SQLAlchemy session and commit the changes back to
the database.
:param obj: SQLAlchemy | python | {
"resource": ""
} |
q8421 | DBObjectMixin.filter_by_id | train | def filter_by_id(self, query):
"""Apply the primary key filter to query to filter the results for a specific
instance by id.
The filter applied by the this method by default can be controlled using the
url_id_param
:param query: SQLAlchemy Query
| python | {
"resource": ""
} |
q8422 | DBObjectMixin.delete_object | train | def delete_object(self, obj):
"""Deletes an object from the session by calling session.delete and then commits
the changes to the | python | {
"resource": ""
} |
q8423 | ArrestedAPI.init_app | train | def init_app(self, app):
"""Initialise the ArrestedAPI object by storing a pointer to a Flask app object.
This method is typically used when initialisation is deferred.
:param app: Flask application object
Usage::
| python | {
"resource": ""
} |
q8424 | Endpoint.dispatch_request | train | def dispatch_request(self, *args, **kwargs):
"""Dispatch the incoming HTTP request to the appropriate handler.
"""
self.args = args
self.kwargs = kwargs
self.meth = request.method.lower()
self.resource = current_app.blueprints.get(request.blueprint, None)
if not any([self.meth in self.methods, self.meth.upper() in self.methods]):
return self.return_error(405)
| python | {
"resource": ""
} |
q8425 | Endpoint.return_error | train | def return_error(self, status, payload=None):
"""Error handler called by request handlers when an error occurs and the request
should be aborted.
Usage::
def handle_post_request(self, *args, **kwargs):
self.request_handler = self.get_request_handler()
try:
self.request_handler.process(self.get_data())
except SomeException as e:
self.return_error(400, payload=self.request_handler.errors)
return self.return_create_response()
| python | {
"resource": ""
} |
q8426 | KimResponseHandler.handle | train | def handle(self, data, **kwargs):
"""Run serialization for the specified mapper_class.
Supports both .serialize and .many().serialize Kim interfaces.
:param data: Objects to be serialized.
:returns: Serialized data according to mapper configuration
"""
if self.many:
| python | {
"resource": ""
} |
q8427 | KimRequestHandler.handle_error | train | def handle_error(self, exp):
"""Called if a Mapper returns MappingInvalid. Should handle the error
and return it in the appropriate format, can be overridden in order
to change the error format.
:param exp: MappingInvalid exception raised
"""
payload | python | {
"resource": ""
} |
q8428 | KimRequestHandler.handle | train | def handle(self, data, **kwargs):
"""Run marshalling for the specified mapper_class.
Supports both .marshal and .many().marshal Kim interfaces. Handles errors raised
during marshalling and automatically returns a HTTP error response.
:param data: Data to be marshaled.
:returns: Marshaled object according to mapper configuration
:raises: :class:`werkzeug.exceptions.UnprocessableEntity`
"""
try:
if self.many:
return self.mapper.many(raw=self.raw, **self.mapper_kwargs).marshal(
| python | {
"resource": ""
} |
q8429 | KimEndpoint.get_response_handler_params | train | def get_response_handler_params(self, **params):
"""Return a config object that will be used to configure the KimResponseHandler
:returns: a dictionary of config options
:rtype: dict
"""
params = super(KimEndpoint, self).get_response_handler_params(**params)
params['mapper_class'] = self.mapper_class
params['role'] = self.serialize_role
# After a successfull attempt to marshal an object has been made, a response
# is generated using the RepsonseHandler. Rather than taking the class level
# setting for many by default, pull it from the request handler params config to
| python | {
"resource": ""
} |
q8430 | KimEndpoint.get_request_handler_params | train | def get_request_handler_params(self, **params):
"""Return a config object that will be used to configure the KimRequestHandler
:returns: a dictionary of config options
:rtype: dict
"""
params = super(KimEndpoint, self).get_request_handler_params(**params)
params['mapper_class'] = self.mapper_class
params['role'] = self.marshal_role
params['many'] = False
| python | {
"resource": ""
} |
q8431 | GetListMixin.list_response | train | def list_response(self, status=200):
"""Pull the processed data from the response_handler and return a response.
:param status: The HTTP status code returned with the response
.. seealso:
:meth:`Endpoint.make_response`
| python | {
"resource": ""
} |
q8432 | CreateMixin.create_response | train | def create_response(self, status=201):
"""Generate a Response object for a POST request. By default, the newly created
object will be passed to the specified ResponseHandler and will be serialized
as the response body.
"""
self.response = | python | {
"resource": ""
} |
q8433 | fsm.concatenate | train | def concatenate(*fsms):
'''
Concatenate arbitrarily many finite state machines together.
'''
alphabet = set().union(*[fsm.alphabet for fsm in fsms])
def connect_all(i, substate):
'''
Take a state in the numbered FSM and return a set containing it, plus
(if it's final) the first state from the next FSM, plus (if that's
final) the first state from the next but one FSM, plus...
'''
result = {(i, substate)}
while i < len(fsms) - 1 and substate in fsms[i].finals:
i += 1
substate = fsms[i].initial
result.add((i, substate))
return result
# Use a superset containing states from all FSMs at once.
# We start at the start of the first FSM. If this state is final in the
# first FSM, then we are also at the start of the second FSM. And so on.
initial = set()
if len(fsms) > 0:
initial.update(connect_all(0, fsms[0].initial))
initial = frozenset(initial)
def final(state):
'''If you're in a final state of the final FSM, it's final'''
for | python | {
"resource": ""
} |
q8434 | fsm.times | train | def times(self, multiplier):
'''
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 final then multiplying doesn't alter that'''
for (substate, iteration) in state:
if substate == self.initial \
and (self.initial in self.finals or iteration == multiplier):
return True
return False
def follow(current, symbol):
next = []
for (substate, iteration) in current:
if iteration < multiplier \
and substate in self.map \
and symbol in self.map[substate]: | python | {
"resource": ""
} |
q8435 | fsm.everythingbut | train | 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.
'''
alphabet = self.alphabet
initial = {0 : self.initial}
def follow(current, symbol):
next = {}
if 0 in current and | python | {
"resource": ""
} |
q8436 | fsm.islive | train | def islive(self, state):
'''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 | python | {
"resource": ""
} |
q8437 | fsm.cardinality | train | 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
'''
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_strings[state] is None: # "computing..." | python | {
"resource": ""
} |
q8438 | call_fsm | train | 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.
| python | {
"resource": ""
} |
q8439 | from_fsm | train | def from_fsm(f):
'''
Turn the supplied finite state machine into a `lego` object. This is
accomplished using the Brzozowski algebraic method.
'''
# Make sure the supplied alphabet is kosher. It must contain only single-
# character strings or `fsm.anything_else`.
for symbol in f.alphabet:
if symbol == fsm.anything_else:
continue
if isinstance(symbol, str) and len(symbol) == 1:
continue
raise Exception("Symbol " + repr(symbol) + " cannot be used in a regular expression")
# We need a new state not already used
outside = object()
# The set of strings that would be accepted by this FSM if you started
# at state i is represented by the regex R_i.
# If state i has a sole transition "a" to state j, then we know R_i = a R_j.
# If state i is final, then the empty string is also accepted by this regex.
# And so on...
# From this we can build a set of simultaneous equations in len(f.states)
# variables. This system is easily solved for all variables, but we only
# need one: R_a, where a is the starting state.
# The first thing we need to do is organise the states into order of depth,
# so that when we perform our back-substitutions, we can start with the
# last (deepest) state and therefore finish with R_a.
states = [f.initial]
i = 0
while i < len(states):
current = states[i]
if current in f.map:
for symbol in sorted(f.map[current], key=fsm.key):
next = f.map[current][symbol]
if next not in states:
states.append(next)
i += 1
# Our system of equations is represented like so:
brz = {}
for a in f.states:
brz[a] = {}
for b in f.states | {outside}:
brz[a][b] = nothing
# Populate it with some initial data.
for a in f.map:
for symbol in f.map[a]:
b = f.map[a][symbol]
if symbol == fsm.anything_else:
| python | {
"resource": ""
} |
q8440 | multiplier.common | train | 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.
'''
mandatory = | python | {
"resource": ""
} |
q8441 | conc.dock | train | 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.
'''
# 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 reversed(range(len(other.mults))): # [2, 1, 0]
# e.g. i = 1, j = 7 - 3 + 1 = 5
j = len(self.mults) - len(other.mults) + i
new[j] = new[j].dock(other.mults[i])
if new[j].multiplier == zero:
# omit that mult entirely since it has been factored out
del new[j]
# If the subtraction is incomplete but there is more to
| python | {
"resource": ""
} |
q8442 | pattern.dock | train | def dock(self, other):
'''
The opposite of concatenation. Remove a common suffix from the present
| python | {
"resource": ""
} |
q8443 | delete_name | train | def delete_name(name):
''' This function don't use the plugin. '''
session = create_session()
try:
user = session.query(User).filter_by(name=name).first()
| python | {
"resource": ""
} |
q8444 | SQLAlchemyPlugin.setup | train | def setup(self, app):
''' 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:
raise bottle.PluginError("Found another SQLAlchemy plugin with "\
"conflicting settings (non-unique keyword).")
| python | {
"resource": ""
} |
q8445 | GreenSocket.send_multipart | train | def send_multipart(self, *args, **kwargs):
"""wrap send_multipart to prevent state_changed on each partial send"""
self.__in_send_multipart = True | python | {
"resource": ""
} |
q8446 | GreenSocket.recv_multipart | train | def recv_multipart(self, *args, **kwargs):
"""wrap recv_multipart to prevent state_changed on each partial recv"""
self.__in_recv_multipart = True | python | {
"resource": ""
} |
q8447 | archive | train | def archive(source, archive, path_in_arc=None, remove_source=False,
compression=zipfile.ZIP_DEFLATED, compresslevel=-1):
"""Archives a MRIO database as zip file
This function is a wrapper around zipfile.write,
to ease the writing of an archive and removing the source data.
Note
----
In contrast to zipfile.write, this function raises an
error if the data (path + filename) are identical in the zip archive.
Background: the zip standard allows that files with the same name and path
are stored side by side in a zip file. This becomes an issue when unpacking
this files as they overwrite each other upon extraction.
Parameters
----------
source: str or pathlib.Path or list of these
Location of the mrio data (folder).
If not all data should be archived, pass a list of
all files which should be included in the archive (absolute path)
archive: str or pathlib.Path
Full path with filename for the archive.
path_in_arc: string, optional
Path within the archive zip file where data should be stored.
'path_in_arc' must be given without leading dot and slash.
Thus to point to the data in the root of the compressed file pass '',
for data in e.g. the folder 'mrio_v1' pass 'mrio_v1/'.
If None (default) data will be stored in the root of the archive.
remove_source: boolean, optional
If True, deletes the source file from the disk (all files
specified in 'source' or the specified directory, depending if a
list of files or directory was passed). If False, leaves the
original files on disk. Also removes all empty directories
in source including source.
compression: ZIP compression method, optional
This is passed to zipfile.write. By default it is set to ZIP_DEFLATED.
NB: This is different from the zipfile default (ZIP_STORED) which would
not give any compression. See
https://docs.python.org/3/library/zipfile.html#zipfile-objects for
further information. Depending on the value given here additional
modules might be necessary (e.g. zlib for ZIP_DEFLATED). Futher
information on this can also be found in the zipfile python docs.
compresslevel: int, optional
This is passed to zipfile.write and specifies the compression level.
Acceptable values depend on the method specified at the parameter
'compression'. By default, it is set to -1 which gives a compromise
between speed and size for the ZIP_DEFLATED compression (this is
internally interpreted as 6 as described here:
https://docs.python.org/3/library/zlib.html#zlib.compressobj )
NB: This is only used if python version >= 3.7
Raises
------
FileExistsError: In case a file to be archived already present in the
archive.
"""
archive = Path(archive)
if type(source) is not list:
source_root = str(source)
source_files = [f for f in Path(source).glob('**/*') if f.is_file()]
else:
| python | {
"resource": ""
} |
q8448 | parse_exio12_ext | train | 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 with pymrio.load
Notes
-----
So far this only parses factor of production extensions F (not
final demand extensions FY nor coeffiecents S).
Parameters
----------
ext_file : string or pathlib.Path
File to parse
index_col : int
The number of columns (1 to 3) at the beginning of the file
to use as the index. The order of the index_col must be
- 1 index column: ['stressor']
- 2 index columns: ['stressor', 'unit']
- 3 index columns: ['stressor', 'compartment', 'unit']
- > 3: everything up to three index columns will be removed
name : string
Name of the extension
drop_compartment : boolean, optional
If | python | {
"resource": ""
} |
q8449 | get_exiobase12_version | train | def get_exiobase12_version(filename):
""" Returns the EXIOBASE version for the given filename,
None if not found
"""
try:
ver_match = re.search(r'(\d+\w*(\.|\-|\_))*\d+\w*', filename)
version = ver_match.string[ver_match.start():ver_match.end()]
| python | {
"resource": ""
} |
q8450 | parse_exiobase1 | train | 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 as the unpacked
files.
Parameters
----------
path : pathlib.Path or string
Path of the exiobase 1 data
Returns
-------
pymrio.IOSystem with exio1 data
"""
path = os.path.abspath(os.path.normpath(str(path)))
exio_files = get_exiobase_files(path)
if len(exio_files) == 0:
| python | {
"resource": ""
} |
q8451 | parse_exiobase3 | train | 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
Path to the folder with the EXIOBASE files
or the compressed archive.
Returns
-------
IOSystem
A IOSystem with the parsed exiobase 3 data
"""
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
# have a country name mixup. Clean | python | {
"resource": ""
} |
q8452 | __get_WIOD_SEA_extension | train | 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 : string
Path to the WIOD data or the path with the SEA data.
year : str or int
Year to return for the extension
sea_data_sheet : string, optional
Worksheet with the SEA data in the excel file
Returns
-------
SEA data as extension for the WIOD MRIO
"""
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
ff[:8] == sea_start]
if sea_folder_content:
# read data
sea_file = os.path.join(_SEA_folder, sorted(sea_folder_content)[0])
df_sea = pd.read_excel(sea_file,
sheet_name=data_sheet,
header=0,
index_col=[0, 1, 2, 3])
# fix years
ic_sea = df_sea.columns.tolist()
ic_sea = [yystr.lstrip('_') for yystr in ic_sea]
df_sea.columns = ic_sea
try:
ds_sea = df_sea[str(year)]
except KeyError:
warnings.warn(
'SEA extension does not include data for the '
'year {} - SEA-Extension not included'.format(year),
ParserWarning)
return None, None
# get useful data (employment)
mt_sea = ['EMP', 'EMPE', 'H_EMP', 'H_EMPE']
ds_use_sea = pd.concat(
[ds_sea.xs(key=vari, level='Variable', drop_level=False)
for vari in mt_sea])
ds_use_sea.drop(labels='TOT', level='Code', inplace=True)
ds_use_sea.reset_index('Description', drop=True, inplace=True)
# RoW not included in SEA but needed to get it consistent for
# all countries. Just add a dummy with 0 for all accounts.
if 'RoW' | python | {
"resource": ""
} |
q8453 | MRIOMetaData._add_history | train | def _add_history(self, entry_type, entry):
""" Generic method to add entry as entry_type to the history """
meta_string = "{time} - {etype} - {entry}".format(
time=self._time(),
etype=entry_type.upper(),
| python | {
"resource": ""
} |
q8454 | MRIOMetaData.change_meta | train | 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, optional
If True (default) records the meta data change
in the history
"""
if not new_value:
| python | {
"resource": ""
} |
q8455 | MRIOMetaData.save | train | 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 the
location set here.
Parameters
----------
location: str, optional
Path or file for saving the metadata.
| python | {
"resource": ""
} |
q8456 | calc_x | train | 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 | python | {
"resource": ""
} |
q8457 | calc_x_from_L | train | 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.array
Industry output | python | {
"resource": ""
} |
q8458 | calc_L | train | 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
| python | {
"resource": ""
} |
q8459 | recalc_M | train | 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 diagonalized per country block.
The diagonolized form must be invertable for this method to work.
nr_sectors : int
Number of sectors in the MRIO
Returns
-------
pandas.DataFrame or numpy.array
Multipliers M
| python | {
"resource": ""
} |
q8460 | calc_accounts | train | 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 : pandas.DataFrame
Final demand: aggregated across categories or just one category, one
column per country
nr_sectors : int
Number of sectors in the MRIO
Returns
-------
Tuple
(D_cba, D_pba, D_imp, D_exp)
Format: D_row x L_col (=nr_countries*nr_sectors)
- D_cba Footprint per sector and country
- D_pba Total factur use per sector and country
- D_imp Total global factor use to satisfy total final demand in
the country per sector
- D_exp Total factor use in one country to satisfy final demand
in all other countries (per sector)
"""
# 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.DataFrame(S.values.dot(x_diag),
| python | {
"resource": ""
} |
q8461 | _get_url_datafiles | train | 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
mrio_regex: regex str
Regex to parse the mrio datafile from url_db_view
access_cookie: dict, optional
If needed, cookie to access the database
Returns
-------
Named tuple:
.raw_text: content of url_db_view for later use
.data_urls: list of url
"""
| python | {
"resource": ""
} |
q8462 | _download_urls | train | 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 depends on the setting in 'overwrite_existing'.
overwrite_existing: boolean, optional
If False, skip download of file already existing in
| python | {
"resource": ""
} |
q8463 | download_wiod2013 | train | 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 store the download, folder will be created if
not existing. If the file is already present in the folder,
the download of the specific file will be skipped.
years: list of int or str, optional
If years is given only downloads the specific years. This
only applies to the IO tables because extensions are stored
by country and not per year.
The years can be given in 2 or 4 digits.
overwrite_existing: boolean, optional
If False, skip download of file already existing in
the storage folder (default). Set to True to replace
files.
satellite_urls : list of str (urls), optional
Which satellite accounts to download. Default: satellite urls defined
in WIOD_CONFIG - list of all available urls Remove items from this list
to only download a subset of extensions
"""
try:
os.makedirs(storage_folder)
except FileExistsError:
pass
if type(years) is int or type(years) is str:
years = [years]
| python | {
"resource": ""
} |
q8464 | get_timestamp | train | def get_timestamp(length):
"""Get a timestamp of `length` in string"""
s = '%.6f' % time.time()
whole, | python | {
"resource": ""
} |
q8465 | mkdir_p | train | def mkdir_p(path):
"""mkdir -p path"""
if PY3:
return os.makedirs(path, exist_ok=True)
try:
os.makedirs(path)
except OSError as exc:
| python | {
"resource": ""
} |
q8466 | monkey_patch | train | 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.
"""
ozmq = __import__('zmq')
| python | {
"resource": ""
} |
q8467 | CoreSystem.reset_to_coefficients | train | 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 | python | {
"resource": ""
} |
q8468 | CoreSystem.copy | train | 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
"""
_tmp = copy.deepcopy(self)
if not new_name:
new_name = self.name + '_copy'
| python | {
"resource": ""
} |
q8469 | CoreSystem.get_Y_categories | train | 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 determine
list is available
"""
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()
except (AssertionError, KeyError):
ind = getattr(self, df).columns.get_level_values(
| python | {
"resource": ""
} |
q8470 | CoreSystem.get_index | train | 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.
grouping_pattern: dict, optional
Dictionary with keys being regex patterns matching index and
values the name for the grouping. If the index is a pandas
multiindex, the keys must be tuples of length levels in the
multiindex, with a valid regex expression at each position.
Otherwise, the keys need to be strings.
Only relevant if as_dict is True.
"""
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',
'D_imp_cap', 'D_exp_cap', ]
for df in possible_dataframes:
if (df in self.__dict__) and (getattr(self, df) is not None):
orig_idx = getattr(self, df).index
break
else:
logging.warn("No attributes available to get index")
return None
| python | {
"resource": ""
} |
q8471 | CoreSystem.set_index | train | def set_index(self, index):
""" Sets the pd dataframe index of all dataframes in the system to index
"""
| python | {
"resource": ""
} |
q8472 | CoreSystem.get_DataFrame | train | 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 a generator which
yields only the names of the DataFrames
with_unit: boolean, optional
If True, includes the 'unit' DataFrame
| python | {
"resource": ""
} |
q8473 | CoreSystem.save | train | 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' : Binary pickle files,
alias: 'pickle', 'bin', 'binary'
- 'txt' : Text files (default), alias: 'text', 'csv'
table_ext : string, optional
File extension,
default depends on table_format(.pkl for pickle, .txt for text)
sep : string, optional
Field delimiter for the output file, only for txt files.
Default: tab ('\t')
float_format : string, optional
Format for saving the DataFrames,
default = '%.12g', only for txt files
"""
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', 'csv', 'txt']:
table_format = 'txt'
elif table_format in ['pickle', 'bin', 'binary', 'pkl']:
table_format = 'pkl'
else:
raise ValueError('Unknown table format "{}" - '
'must be "txt" or "pkl"'.format(table_format))
return None
if not table_ext:
if table_format == 'txt':
table_ext = '.txt'
if table_format == 'pkl':
table_ext = '.pkl'
if str(type(self)) == "<class 'pymrio.core.mriosystem.IOSystem'>":
file_para['systemtype'] = GENERIC_NAMES['iosys']
elif str(type(self)) == "<class 'pymrio.core.mriosystem.Extension'>":
file_para['systemtype'] = GENERIC_NAMES['ext']
file_para['name'] = self.name
else:
logging.warn('Unknown system type {} - set to "undef"'.format(
str(type(self))))
file_para['systemtype'] = 'undef'
for df, df_name in zip(self.get_DataFrame(data=True),
| python | {
"resource": ""
} |
q8474 | CoreSystem.rename_regions | train | 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 repetition
"""
if type(regions) is list:
regions = {old: new for old, new in
zip(self.get_regions(), regions)}
for | python | {
"resource": ""
} |
q8475 | CoreSystem.rename_sectors | train | 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 without repetition
"""
if type(sectors) is list:
sectors = {old: new for old, new in
zip(self.get_sectors(), sectors)}
| python | {
"resource": ""
} |
q8476 | CoreSystem.rename_Y_categories | train | 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
complete without repetition
"""
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):
| python | {
"resource": ""
} |
q8477 | Extension.get_rows | train | def get_rows(self):
""" Returns the name of the rows of the extension"""
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',
'D_imp_cap', 'D_exp_cap', ] | python | {
"resource": ""
} |
q8478 | Extension.get_row_data | train | 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 case the dict can be
used directly to build a new extension.
Returns
-------
dict object with the data | python | {
"resource": ""
} |
q8479 | Extension.diag_stressor | train | 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 final consumer (column index).
Note
----
Since the type of analysis based on the disaggregated matrix is based
on flow, direct household emissions (FY) are not included.
Parameters
----------
stressor : str or int - valid index for one row of the F matrix
This must be a tuple for a multiindex, a string otherwise.
The stressor to diagonalize.
name : string (optional)
The new name for the extension,
if None (default): string based on the given stressor (row name)
Returns
-------
Extension
"""
if type(stressor) is int:
stressor = self.F.index[stressor]
if len(stressor) == | python | {
"resource": ""
} |
q8480 | IOSystem.calc_system | train | 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
"""
# 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 L or at least A to calculate it
if self.L is None:
self.L = calc_L(self.A)
| python | {
"resource": ""
} |
q8481 | IOSystem.calc_extensions | train | 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
A list of key names of extensions which shall be calculated.
Default: all dictionaries of IOSystem are assumed to be extensions
Y_agg : pandas.DataFrame or np.array, optional
| python | {
"resource": ""
} |
q8482 | IOSystem.report_accounts | train | 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
Root path for the report
per_region : boolean, optional
If true, reports the accounts per region
per_capita : boolean, optional
If true, reports the accounts per capita
If per_capita and per_region are False, nothing will be done
pic_size : int, optional
size for the figures in px, 1000 by default
format : string, optional
file format of the report:
'rst'(default), 'html', 'latex', ...
except for rst all depend on the module docutils (all writer_name
from docutils can be used as format)
ffname : string, optional
root file | python | {
"resource": ""
} |
q8483 | IOSystem.get_extensions | train | 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
-------
Generator for Extension or string
"""
ext_list = [key | python | {
"resource": ""
} |
q8484 | IOSystem.reset_all_to_flows | train | 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
----------
| python | {
"resource": ""
} |
q8485 | IOSystem.reset_all_to_coefficients | train | 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 in case
| python | {
"resource": ""
} |
q8486 | IOSystem.save_all | train | 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.
"""
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,
| python | {
"resource": ""
} |
q8487 | IOSystem.remove_extension | train | 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 Extension.name (the latter will be checked if no
instance was found)
If ext is None (default) all Extensions will be removed
"""
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:
| python | {
"resource": ""
} |
q8488 | is_vector | train | 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
| python | {
"resource": ""
} |
q8489 | get_file_para | train | 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 defined otherwise by including the file
name of the parameter file in the parameter path.
Parameters
----------
path: pathlib.Path or string
Path or path with para file name for the data to load.
This must either point to the directory containing the uncompressed
data or the location of a compressed zip file with the data. In the
later case the parameter 'path_in_arc' needs to be specific to
further indicate the location of the data in the compressed file.
path_in_arc: string, optional
Path to the data in the zip file (where the fileparameters file is
located). path_in_arc must be given without leading dot and slash;
thus to point to the data in the root of the compressed file pass ''
(default), for data in e.g. the folder 'emissions' pass 'emissions/'.
Only used if parameter 'path' points to an | python | {
"resource": ""
} |
q8490 | build_agg_matrix | train | 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.
Length m with position given for n and -1 if values
should not be included
or
length m with id_string for the aggregation
pos_dict : dictionary
(only possible if agg_vector is given as string)
output order for the new matrix
must be given as dict with
'string in agg_vector' = pos
(as int, -1 if value should not be included in the aggregation)
Example 1:
input vector: np.array([0, 1, 1, 2]) or ['a', 'b', 'b', 'c']
agg matrix:
m0 m1 m2 m3
n0 1 0 0 0
n1 0 1 1 0
n2 0 0 0 1
Example 2:
input vector: np.array([1, 0, 0, 2]) or
(['b', 'a', 'a', 'c'], dict(a=0,b=1,c=2))
agg matrix:
m0 m1 m2 m3
n0 0 1 1 0
n1 1 0 0 0
n2 0 0 0 1
"""
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)):
| python | {
"resource": ""
} |
q8491 | diagonalize_blocks | train | 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,
columns 'arr' * blocksize)
Example
--------
arr: output: (blocksize = 3)
3 1 3 0 0 1 0 0
4 2 0 4 0 0 2 0
5 3 0 0 5 0 0 3
6 9 6 0 0 9 0 0
7 6 0 7 0 0 6 0
8 4 0 0 8 0 0 4
"""
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 | python | {
"resource": ""
} |
q8492 | set_block | train | 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)
"""
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 of block shape')
if nr_row/nr_row_block != nr_col/nr_col_block:
raise ValueError('Block array can | python | {
"resource": ""
} |
q8493 | unique_element | train | def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in seen:
| python | {
"resource": ""
} |
q8494 | build_agg_vec | train | def build_agg_vec(agg_vec, **source):
""" Builds an combined aggregation vector based on various classifications
This function build an aggregation vector based on the order in agg_vec.
The naming and actual mapping is given in source, either explicitly or by
pointing to a folder with the mapping.
>>> build_agg_vec(['EU', 'OECD'], path = 'test')
['EU', 'EU', 'EU', 'OECD', 'REST', 'REST']
>>> build_agg_vec(['OECD', 'EU'], path = 'test', miss='RoW')
['OECD', 'EU', 'OECD', 'OECD', 'RoW', 'RoW']
>>> build_agg_vec(['EU', 'orig_regions'], path = 'test')
['EU', 'EU', 'EU', 'reg4', 'reg5', 'reg6']
>>> build_agg_vec(['supreg1', 'other'], path = 'test',
>>> other = [None, None, 'other1', 'other1', 'other2', 'other2'])
['supreg1', 'supreg1', 'other1', 'other1', 'other2', 'other2']
Parameters
----------
agg_vec : list
A list of sector or regions to which the IOSystem shall be aggregated.
The order in agg_vec is important:
If a string was assigned to one specific entry it will not be
overwritten if it is given in the next vector, e.g. ['EU', 'OECD']
would aggregate first into EU and the remaining one into OECD, whereas
['OECD', 'EU'] would first aggregate all countries into OECD and than
the remaining countries into EU.
source : list or string
Definition of the vectors in agg_vec. The input vectors (either in the
file or given as list for the entries in agg_vec) must be as long as
the desired output with a string for every position which should be
aggregated and None for position which should not be used.
Special keywords:
- path : Path to a folder with concordance matrices.
The files in the folder can have any extension but must be
in text format (tab separated) | python | {
"resource": ""
} |
q8495 | find_first_number | train | def find_first_number(ll):
""" Returns nr of first entry parseable to float in ll, None otherwise"""
for nr, entry in | python | {
"resource": ""
} |
q8496 | sniff_csv_format | train | 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, optional
How many lines to test, default: 10 or available lines in csv_file
zip_file: str, optional
Path to a zip file containing the csv file (if any, default: None).
If a zip file is given, the path given at 'csv_file' is assumed
to be the path to the file within the zip_file.
Returns
-------
dict with
sep: string (separator)
nr_index_col: int
nr_header_row: int
Entries are set to None if inconsistent information in the file
"""
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.append(line[:-1])
return lines
if zip_file:
with zipfile.ZipFile(zip_file, 'r') as zz:
with zz.open(csv_file, 'r') as ff:
test_lines = read_first_lines(ff)
else:
with open(csv_file, 'r') as ff:
test_lines = read_first_lines(ff)
sep_aly_lines = [sorted([(line.count(sep), sep)
| python | {
"resource": ""
} |
q8497 | GreenPoller._get_descriptors | train | def _get_descriptors(self):
"""Returns three elements tuple with socket descriptors ready
for gevent.select.select
"""
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
elif hasattr(socket, 'fileno'):
try:
fd = int(socket.fileno())
except:
raise ValueError('fileno() must return an valid integer fd')
else:
raise TypeError('Socket must be a 0MQ socket, an integer | python | {
"resource": ""
} |
q8498 | GreenPoller.poll | train | 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`
"""
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 available
rlist, wlist, xlist = self._get_descriptors()
while True:
| python | {
"resource": ""
} |
q8499 | _instantiate_task | train | def _instantiate_task(api, kwargs):
"""Create a Task object from raw kwargs"""
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'])
kwargs['last_update'] = get_utcdatetime(kwargs['last_update'])
is_transferred = (kwargs['status'] == 2 and kwargs['move'] == 1)
if is_transferred:
kwargs['pid'] = | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.