INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Prepend a metadata entry for symbol | def prepend(self, symbol, metadata, start_time=None):
"""
Prepend a metadata entry for `symbol`
Parameters
----------
symbol : `str`
symbol name for the item
metadata : `dict`
to be persisted
start_time : `datetime.datetime`
wh... |
Delete current metadata of symbol | def pop(self, symbol):
"""
Delete current metadata of `symbol`
Parameters
----------
symbol : `str`
symbol name to delete
Returns
-------
Deleted metadata
"""
last_metadata = self.find_one({'symbol': symbol}, sort=[('start_tim... |
Delete all metadata of symbol | def purge(self, symbol):
"""
Delete all metadata of `symbol`
Parameters
----------
symbol : `str`
symbol name to delete
"""
logger.warning("Deleting entire metadata history for %r from %r" % (symbol, self._arctic_lib.get_name()))
self.delete_m... |
Generic query method. | def query(self, *args, **kwargs):
"""
Generic query method.
In reality, your storage class would have its own query methods,
Performs a Mongo find on the Marketdata index metadata collection.
See:
http://api.mongodb.org/python/current/api/pymongo/collection.html
... |
Database usage statistics. Used by quota. | def stats(self):
"""
Database usage statistics. Used by quota.
"""
res = {}
db = self._collection.database
res['dbstats'] = db.command('dbstats')
res['data'] = db.command('collstats', self._collection.name)
res['totals'] = {'count': res['data']['count'],
... |
Simple persistence method | def store(self, thing):
"""
Simple persistence method
"""
to_store = {'field1': thing.field1,
'date_field': thing.date_field,
}
to_store['stuff'] = Binary(cPickle.dumps(thing.stuff))
# Respect any soft-quota on write - raises if sta... |
Read data for the named symbol. Returns a BitemporalItem object with a data and metdata element ( as passed into write ). | def read(self, symbol, as_of=None, raw=False, **kwargs):
# TODO: shall we block from_version from getting into super.read?
"""Read data for the named symbol. Returns a BitemporalItem object with
a data and metdata element (as passed into write).
Parameters
----------
sym... |
Append data under the specified symbol name to this library. | def update(self, symbol, data, metadata=None, upsert=True, as_of=None, **kwargs):
""" Append 'data' under the specified 'symbol' name to this library.
Parameters
----------
symbol : `str`
symbol name for the item
data : `pd.DataFrame`
to be persisted
... |
Convert a string to a DateRange type. If you put only one date it generates the relevant range for just that date or datetime till 24 hours later. You can optionally use mixtures of []/ () around the DateRange for OPEN/ CLOSED interval behaviour. | def string_to_daterange(str_range, delimiter='-', as_dates=False, interval=CLOSED_CLOSED):
"""
Convert a string to a DateRange type. If you put only one date, it generates the
relevant range for just that date or datetime till 24 hours later. You can optionally
use mixtures of []/() around the DateRange... |
Returns a non - naive datetime. datetime. | def to_dt(date, default_tz=None):
"""
Returns a non-naive datetime.datetime.
Interprets numbers as ms-since-epoch.
Parameters
----------
date : `int` or `datetime.datetime`
The datetime to convert
default_tz : tzinfo
The TimeZone to use if none is found. If not supplied, ... |
Pandas DateRange slicing is CLOSED - CLOSED inclusive at both ends. | def to_pandas_closed_closed(date_range, add_tz=True):
"""
Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends.
Parameters
----------
date_range : `DateRange` object
converted to CLOSED_CLOSED form for Pandas slicing
add_tz : `bool`
Adds a TimeZone to the daterange ... |
Convert a millisecond time value to an offset - aware Python datetime object. | def ms_to_datetime(ms, tzinfo=None):
"""Convert a millisecond time value to an offset-aware Python datetime object."""
if not isinstance(ms, (int, long)):
raise TypeError('expected integer, not %s' % type(ms))
if tzinfo is None:
tzinfo = mktz()
return datetime.datetime.fromtimestamp(ms... |
Convert a Python datetime object to a millisecond epoch ( UTC ) time value. | def datetime_to_ms(d):
"""Convert a Python datetime object to a millisecond epoch (UTC) time value."""
try:
millisecond = d.microsecond // 1000
return calendar.timegm(_add_tzone(d).utctimetuple()) * 1000 + millisecond
except AttributeError:
raise TypeError('expect Python datetime obj... |
Convert a UTC datetime to datetime in local timezone | def utc_dt_to_local_dt(dtm):
"""Convert a UTC datetime to datetime in local timezone"""
utc_zone = mktz("UTC")
if dtm.tzinfo is not None and dtm.tzinfo != utc_zone:
raise ValueError(
"Expected dtm without tzinfo or with UTC, not %r" % (
dtm.tzinfo
)
)
... |
Create a new DateRange representing the maximal range enclosed by this range and other | def intersection(self, other):
"""
Create a new DateRange representing the maximal range enclosed by this range and other
"""
startopen = other.startopen if self.start is None \
else self.startopen if other.start is None \
else other.startopen if self.start < othe... |
Create a new DateRange with the datetimes converted to dates and changing to CLOSED/ CLOSED. | def as_dates(self):
"""
Create a new DateRange with the datetimes converted to dates and changing to CLOSED/CLOSED.
"""
new_start = self.start.date() if self.start and isinstance(self.start, datetime.datetime) else self.start
new_end = self.end.date() if self.end and isinstance(s... |
Convert a DateRange into a MongoDb query string. FIXME: Mongo can only handle datetimes in queries so we should make this handle the case where start/ end are datetime. date and extend accordingly ( being careful about the interval logic ). | def mongo_query(self):
"""
Convert a DateRange into a MongoDb query string. FIXME: Mongo can only handle
datetimes in queries, so we should make this handle the case where start/end are
datetime.date and extend accordingly (being careful about the interval logic).
"""
com... |
Return the upper and lower bounds along with operators that are needed to do an in range test. Useful for SQL commands. | def get_date_bounds(self):
"""
Return the upper and lower bounds along
with operators that are needed to do an 'in range' test.
Useful for SQL commands.
Returns
-------
tuple: (`str`, `date`, `str`, `date`)
(date_gt, start, date_lt, end)
e... |
chunks the dataframe/ series by dates | def to_chunks(self, df, chunk_size='D', func=None, **kwargs):
"""
chunks the dataframe/series by dates
Parameters
----------
df: pandas dataframe or series
chunk_size: str
any valid Pandas frequency string
func: function
func will be appli... |
takes the range object used for this chunker type and converts it into a string that can be use for a mongo query that filters by the range | def to_mongo(self, range_obj):
"""
takes the range object used for this chunker type
and converts it into a string that can be use for a
mongo query that filters by the range
returns
-------
dict
"""
if isinstance(range_obj, (pd.DatetimeIndex, tup... |
ensures data is properly subset to the range in range_obj. ( Depending on how the chunking is implemented it might be possible to specify a chunk range that reads out more than the actual range eg: date range chunked monthly. read out 2016 - 01 - 01 to 2016 - 01 - 02. This will read ALL of January 2016 but it should be... | def filter(self, data, range_obj):
"""
ensures data is properly subset to the range in range_obj.
(Depending on how the chunking is implemented, it might be possible
to specify a chunk range that reads out more than the actual range
eg: date range, chunked monthly. read out 2016-... |
Removes data within the bounds of the range object ( inclusive ) | def exclude(self, data, range_obj):
"""
Removes data within the bounds of the range object (inclusive)
returns
-------
data, filtered by range_obj
"""
if isinstance(range_obj, (pd.DatetimeIndex, tuple)):
range_obj = DateRange(range_obj[0], range_obj[-... |
Enable sharding on a library | def enable_sharding(arctic, library_name, hashed=True, key='symbol'):
"""
Enable sharding on a library
Parameters:
-----------
arctic: `arctic.Arctic` Arctic class
library_name: `basestring` library name
hashed: `bool` if True, use hashed sharding, if False, use range sharding
... |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. insert_one | def insert_one(self, document, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
"""
self._arctic_lib.check_quota()
return self._collection.insert_one(document, **kwargs) |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. insert_many | def insert_many(self, documents, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many
"""
self._arctic_lib.check_quota()
return self._collection.insert_many(documents, **kwargs) |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. update_one | def update_one(self, filter, update, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
"""
self._arctic_lib.check_quota()
return self._collection.update_one(filter, update, **kwargs) |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. update_many | def update_many(self, filter, update, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many
"""
self._arctic_lib.check_quota()
return self._collection.update_many(filter, update, **kwargs) |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. replace_one | def replace_one(self, filter, replacement, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
"""
self._arctic_lib.check_quota()
return self._collection.replace_one(filter, replacement, **kwargs) |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. find_one_and_replace | def find_one_and_replace(self, filter, replacement, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace
"""
self._arctic_lib.check_quota()
return self._collection.find_one_and_replace(filter, repl... |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. find_one_and_update | def find_one_and_update(self, filter, update, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_update
"""
self._arctic_lib.check_quota()
return self._collection.find_one_and_update(filter, update, **kw... |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. bulk_write | def bulk_write(self, requests, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent.
... |
See http:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. count | def count(self, filter, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.count
"""
return mongo_count(self._collection, filter=filter, **kwargs) |
Return a new timezone ( tzinfo object ) based on the zone using the python - dateutil package. | def mktz(zone=None):
"""
Return a new timezone (tzinfo object) based on the zone using the python-dateutil
package.
The concise name 'mktz' is for convenient when using it on the
console.
Parameters
----------
zone : `String`
The zone for the timezone. This defaults to local... |
Ensure that symbol ( s ) have contiguous segment ids | def segment_id_repair(library, symbol=None):
"""
Ensure that symbol(s) have contiguous segment ids
Parameters
----------
library: arctic library
symbol: None, str, list of str
None: all symbols
str: single symbol
list: list of symbols
Returns
-------
list of... |
The database state created by this fixture is equivalent to the following operations using arctic 1. 40 or previous: | def multicolumn_store_with_uncompressed_write(mongo_server):
"""
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('... |
The database state created by this fixture is equivalent to the following operations using arctic 1. 40 or previous: | def ndarray_store_with_uncompressed_write(mongo_server):
"""
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('arct... |
Return the symbols in this library. | def list_symbols(self, all_symbols=False, snapshot=None, regex=None, **kwargs):
"""
Return the symbols in this library.
Parameters
----------
all_symbols : `bool`
If True returns all symbols under all snapshots, even if the symbol has been deleted
in the ... |
Return True if the symbol exists in this library AND the symbol isn t deleted in the specified as_of. | def has_symbol(self, symbol, as_of=None):
"""
Return True if the 'symbol' exists in this library AND the symbol
isn't deleted in the specified as_of.
It's possible for a deleted symbol to exist in older snapshots.
Parameters
----------
symbol : `str`
... |
Return the audit log associated with a given symbol | def read_audit_log(self, symbol=None, message=None):
"""
Return the audit log associated with a given symbol
Parameters
----------
symbol : `str`
symbol name for the item
"""
query = {}
if symbol:
if isinstance(symbol, six.string_t... |
Return a list of versions filtered by the passed in parameters. | def list_versions(self, symbol=None, snapshot=None, latest_only=False):
"""
Return a list of versions filtered by the passed in parameters.
Parameters
----------
symbol : `str`
Symbol to return versions for. If None returns versions across all
symbols in... |
Read data for the named symbol. Returns a VersionedItem object with a data and metdata element ( as passed into write ). | def read(self, symbol, as_of=None, date_range=None, from_version=None, allow_secondary=None, **kwargs):
"""
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
... |
Reads and returns information about the data stored for symbol | def get_info(self, symbol, as_of=None):
"""
Reads and returns information about the data stored for symbol
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of th... |
Return the numerical representation of the arctic version used to write the last ( or as_of ) version for the given symbol. | def get_arctic_version(self, symbol, as_of=None):
"""
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str`... |
Return the metadata saved for a symbol. This method is fast as it doesn t actually load the data. | def read_metadata(self, symbol, as_of=None, allow_secondary=None):
"""
Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or in... |
Append data under the specified symbol name to this library. The exact meaning of append is left up to the underlying store implementation. | def append(self, symbol, data, metadata=None, prune_previous_version=True, upsert=True, **kwargs):
"""
Append 'data' under the specified 'symbol' name to this library.
The exact meaning of 'append' is left up to the underlying store implementation.
Parameters
----------
... |
Write data under the specified symbol name to this library. | def write(self, symbol, data, metadata=None, prune_previous_version=True, **kwargs):
"""
Write 'data' under the specified 'symbol' name to this library.
Parameters
----------
symbol : `str`
symbol name for the item
data :
to be persisted
m... |
Write metadata under the specified symbol name to this library. The data will remain unchanged. A new version will be created. If the symbol is missing it causes a write with empty data ( None pickled can t append ) and the supplied metadata. Returns a VersionedItem object only with a metadata element. Fast operation: ... | def write_metadata(self, symbol, metadata, prune_previous_version=True, **kwargs):
"""
Write 'metadata' under the specified 'symbol' name to this library.
The data will remain unchanged. A new version will be created.
If the symbol is missing, it causes a write with empty data (None, pic... |
Restore the specified symbol data and metadata to the state of a given version/ snapshot/ date. Returns a VersionedItem object only with a metadata element. Fast operation: Zero data/ segment read/ write operations. | def restore_version(self, symbol, as_of, prune_previous_version=True):
"""
Restore the specified 'symbol' data and metadata to the state of a given version/snapshot/date.
Returns a VersionedItem object only with a metadata element.
Fast operation: Zero data/segment read/write operations.... |
Find all non - snapshotted versions of a symbol that are older than a version that s at least keep_mins minutes old. | def _find_prunable_version_ids(self, symbol, keep_mins):
"""
Find all non-snapshotted versions of a symbol that are older than a version that's at least keep_mins
minutes old.
Based on documents available on the secondary.
"""
read_preference = ReadPreference.SECONDARY_P... |
Return all base_version_ids for a symbol that are not bases of version_ids | def _find_base_version_ids(self, symbol, version_ids):
"""
Return all base_version_ids for a symbol that are not bases of version_ids
"""
cursor = self._versions.find({'symbol': symbol,
'_id': {'$nin': version_ids},
... |
Prune versions not pointed at by snapshots which are at least keep_mins old. Prune will never remove all versions. | def _prune_previous_versions(self, symbol, keep_mins=120, keep_version=None, new_version_shas=None):
"""
Prune versions, not pointed at by snapshots which are at least keep_mins old. Prune will never
remove all versions.
"""
new_version_shas = new_version_shas if new_version_shas... |
Delete the n th version of this symbol from the historical collection. | def _delete_version(self, symbol, version_num, do_cleanup=True):
"""
Delete the n'th version of this symbol from the historical collection.
"""
version = self._versions.find_one({'symbol': symbol, 'version': version_num})
if not version:
logger.error("Can't delete %s:... |
Delete all versions of the item from the current library which aren t currently part of some snapshot. | def delete(self, symbol):
"""
Delete all versions of the item from the current library which aren't
currently part of some snapshot.
Parameters
----------
symbol : `str`
symbol name to delete
"""
logger.info("Deleting data item: %r from %r" % ... |
Creates an audit entry which is much like a snapshot in that it references versions and provides some history of the changes made. | def _write_audit(self, user, message, changed_version):
"""
Creates an audit entry, which is much like a snapshot in that
it references versions and provides some history of the changes made.
"""
audit = {'_id': bson.ObjectId(),
'user': user,
'me... |
Snapshot versions of symbols in the library. Can be used like: | def snapshot(self, snap_name, metadata=None, skip_symbols=None, versions=None):
"""
Snapshot versions of symbols in the library. Can be used like:
Parameters
----------
snap_name : `str`
name of the snapshot
metadata : `dict`
an optional dictiona... |
Delete a named snapshot | def delete_snapshot(self, snap_name):
"""
Delete a named snapshot
Parameters
----------
symbol : `str`
The snapshot name to delete
"""
snapshot = self._snapshots.find_one({'name': snap_name})
if not snapshot:
raise NoDataFoundExcep... |
Return storage statistics about the library | def stats(self):
"""
Return storage statistics about the library
Returns
-------
dictionary of storage stats
"""
res = {}
db = self._collection.database
conn = db.connection
res['sharding'] = {}
try:
sharding = conn.co... |
Run a consistency check on this VersionStore library. | def _fsck(self, dry_run):
"""
Run a consistency check on this VersionStore library.
"""
# Cleanup Orphaned Chunks
self._cleanup_orphaned_chunks(dry_run)
# Cleanup unreachable SHAs (forward pointers)
self._cleanup_unreachable_shas(dry_run)
# Cleanup Orphane... |
Fixes any chunks who have parent pointers to missing versions. Removes the broken parent pointer and if there are no other parent pointers for the chunk removes the chunk. | def _cleanup_orphaned_chunks(self, dry_run):
"""
Fixes any chunks who have parent pointers to missing versions.
Removes the broken parent pointer and, if there are no other parent pointers for the chunk,
removes the chunk.
"""
lib = self
chunks_coll = lib._collect... |
Fixes any versions who have parent pointers to missing snapshots. Note doesn t delete the versions just removes the parent pointer if it no longer exists in snapshots. | def _cleanup_orphaned_versions(self, dry_run):
"""
Fixes any versions who have parent pointers to missing snapshots.
Note, doesn't delete the versions, just removes the parent pointer if it no longer
exists in snapshots.
"""
lib = self
versions_coll = lib._collect... |
Set the global multithread compression mode | def enable_parallel_lz4(mode):
"""
Set the global multithread compression mode
Parameters
----------
mode: `bool`
True: Use parallel compression. False: Use sequential compression
"""
global ENABLE_PARALLEL
ENABLE_PARALLEL = bool(mode)
logger.info("Setting parallelis... |
Set the size of the compression workers thread pool. If the pool is already created it waits until all jobs are finished and then proceeds with setting the new size. | def set_compression_pool_size(pool_size):
"""
Set the size of the compression workers thread pool.
If the pool is already created, it waits until all jobs are finished, and then proceeds with setting the new size.
Parameters
----------
pool_size : `int`
The size of the pool (mus... |
Compress an array of strings | def compress_array(str_list, withHC=LZ4_HIGH_COMPRESSION):
"""
Compress an array of strings
Parameters
----------
str_list: `list[str]`
The input list of strings which need to be compressed.
withHC: `bool`
This flag controls whether lz4HC will be used.
Retur... |
Decompress a list of strings | def decompress_array(str_list):
"""
Decompress a list of strings
"""
global _compress_thread_pool
if not str_list:
return str_list
if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL:
return [lz4_decompress(chunk) for chunk in str_list]
if _compress_thread_pool is No... |
Equivalent to numpy. split ( array_2d slices ) but avoids fancy indexing | def _split_arrs(array_2d, slices):
"""
Equivalent to numpy.split(array_2d, slices),
but avoids fancy indexing
"""
if len(array_2d) == 0:
return np.empty(0, dtype=np.object)
rtn = np.empty(len(slices) + 1, dtype=np.object)
start = 0
for i, s in enumerate(slices):
rtn[i] =... |
Checksum the passed in dictionary | def checksum(symbol, doc):
"""
Checksum the passed in dictionary
"""
sha = hashlib.sha1()
sha.update(symbol.encode('ascii'))
for k in sorted(iter(doc.keys()), reverse=True):
v = doc[k]
if isinstance(v, six.binary_type):
sha.update(doc[k])
else:
sha... |
Helper method for cleaning up chunks from a version store | def cleanup(arctic_lib, symbol, version_ids, versions_coll, shas_to_delete=None, pointers_cfgs=None):
"""
Helper method for cleaning up chunks from a version store
"""
pointers_cfgs = set(pointers_cfgs) if pointers_cfgs else set()
collection = arctic_lib.get_top_level_collection()
version_ids = ... |
Factory function to initialise the correct Pickle load function based on the Pandas version. | def _define_compat_pickle_load():
"""Factory function to initialise the correct Pickle load function based on
the Pandas version.
"""
if pd.__version__.startswith("0.14"):
return pickle.load
return functools.partial(pickle_compat.load, compat=True) |
This is a utility function to produce text output with details about the versions of a given symbol. It is useful for debugging corruption issues and to mark corrupted versions. Parameters ---------- l: arctic. store. version_store. VersionStore The VersionStore instance against which the analysis will be run. sym: str... | def analyze_symbol(l, sym, from_ver, to_ver, do_reads=False):
"""
This is a utility function to produce text output with details about the versions of a given symbol.
It is useful for debugging corruption issues and to mark corrupted versions.
Parameters
----------
l : `arctic.store.version_stor... |
This method hints whether the symbol/ version are safe for appending in two ways: 1. It verifies whether the symbol is already corrupted ( fast doesn t read the data ) 2. It verififes that the symbol is safe to append i. e. there are no subsequent appends or dangling segments from a failed append. Parameters ----------... | def is_safe_to_append(l, sym, input_v):
"""
This method hints whether the symbol/version are safe for appending in two ways:
1. It verifies whether the symbol is already corrupted (fast, doesn't read the data)
2. It verififes that the symbol is safe to append, i.e. there are no subsequent appends,
... |
This method can be used to check for a corrupted version. Will continue to a full read ( slower ) if the internally invoked fast - detection does not locate a corruption. | def is_corrupted(l, sym, input_v):
"""
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
... |
Converts object arrays of strings to numpy string arrays | def _convert_types(self, a):
"""
Converts object arrays of strings to numpy string arrays
"""
# No conversion for scalar type
if a.dtype != 'object':
return a, None
# We can't infer the type of an empty array, so just
# assume strings
if len(a... |
Convert a Pandas DataFrame to SON. | def docify(self, df):
"""
Convert a Pandas DataFrame to SON.
Parameters
----------
df: DataFrame
The Pandas DataFrame to encode
"""
dtypes = {}
masks = {}
lengths = {}
columns = []
data = Binary(b'')
start = 0
... |
Decode a Pymongo SON object into an Pandas DataFrame | def objify(self, doc, columns=None):
"""
Decode a Pymongo SON object into an Pandas DataFrame
"""
cols = columns or doc[METADATA][COLUMNS]
data = {}
for col in cols:
# if there is missing data in a chunk, we can default to NaN
# and pandas will au... |
Deserializes SON to a DataFrame | def deserialize(self, data, columns=None):
"""
Deserializes SON to a DataFrame
Parameters
----------
data: SON data
columns: None, or list of strings
optionally you can deserialize a subset of the data in the SON. Index
columns are ALWAYS deserial... |
Create and initialize the keybinding manager. | def _create_key_manager(self, get_match_fuzzy, set_match_fuzzy,
get_enable_vi_bindings, set_enable_vi_bindings,
get_show_completion_columns,
set_show_completion_columns,
get_show_help, set_show_help,
... |
Describe operation and args needed for server side completion. | def describe_autocomplete(self, service, operation, param):
"""Describe operation and args needed for server side completion.
:type service: str
:param service: The AWS service name.
:type operation: str
:param operation: The AWS operation name.
:type param: str
... |
Create a CompleterDescriber for a service. | def create_completer_query(self, service_name):
"""Create a CompleterDescriber for a service.
:type service_name: str
:param service_name: The name of the service, e.g. 'ec2'
:return: A CompleterDescriber object.
"""
if service_name not in self._describer_cache:
... |
Retrieve server side completions. | def retrieve_candidate_values(self, service, operation, param):
"""Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
used by the CLI (wor... |
Convert restructured text to basic text output. | def convert_rst_to_basic_text(contents):
"""Convert restructured text to basic text output.
This function removes most of the decorations added
in restructured text.
This function is used to generate documentation we
can show to users in a cross platform manner.
Basic indentation and list for... |
Read the config file if it exists else read the default config. | def load(self, config_template, config_file=None):
"""Read the config file if it exists, else read the default config.
Creates the user config file if it doesn't exist using the template.
:type config_template: str
:param config_template: The config template file name.
:type c... |
Load the config file if it exists else read the default config. | def _load_template_or_config(self, template_path, config_path):
"""Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file pa... |
Write the default config from a template. | def _copy_template_to_config(self, template_path,
config_path, overwrite=False):
"""Write the default config from a template.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path... |
Retrieve the specified pygments style. | def style_factory(self, style_name):
"""Retrieve the specified pygments style.
If the specified style is not found, the vim style is returned.
:type style_name: str
:param style_name: The pygments style name.
:rtype: :class:`pygments.style.StyleMeta`
:return: Pygments ... |
Change the profile used for server side completions. | def change_profile(self, profile_name):
"""Change the profile used for server side completions."""
self._server_side_completer = self._create_server_side_completer(
session=botocore.session.Session(profile=profile_name)) |
Given a line return a list of suggestions. | def autocomplete(self, line):
"""Given a line, return a list of suggestions."""
current_length = len(line)
self._current_line = line
if current_length == 1 and self._last_position > 1:
# Reset state. This is likely from a user completing
# a previous command.
... |
Open application s history buffer in an editor. | def run(self, command, application):
"""Open application's history buffer in an editor.
:type command: list
:param command: The dot command as a list split
on whitespace, e.g ``['.foo', 'arg1', 'arg2']``
:type application: AWSShell
:param application: The applicatio... |
Get or set the profile. | def run(self, command, application):
"""Get or set the profile.
If .profile is called with no args, the current profile
is displayed. If the .profile command is called with a
single arg, then the current profile for the application
will be set to the new value.
"""
... |
Handle running a given dot command from a user. | def handle_cmd(self, command, application):
"""Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application objec... |
Load the config from the config file or template. | def load_config(self):
"""Load the config from the config file or template."""
config = Config()
self.config_obj = config.load('awsshellrc')
self.config_section = self.config_obj['aws-shell']
self.model_completer.match_fuzzy = self.config_section.as_bool(
'match_fuzzy... |
Save the config to the config file. | def save_config(self):
"""Save the config to the config file."""
self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy
self.config_section['enable_vi_bindings'] = self.enable_vi_bindings
self.config_section['show_completion_columns'] = \
self.show_completion_c... |
Create the: class: KeyManager. | def create_key_manager(self):
"""Create the :class:`KeyManager`.
The inputs to KeyManager are expected to be callable, so we can't
use the standard @property and @attrib.setter for these attributes.
Lambdas cannot contain assignments so we're forced to define setters.
:rtype: :... |
Calculate how well the search string matches the word. | def calculate_score(search_string, word):
"""Calculate how well the search string matches the word."""
# See the module docstring for a high level description
# of what we're trying to do.
# * If the search string is larger than the word, we know
# immediately that this can't be a match.
if le... |
Find all matches in the collection for the specified word. | def substring_search(word, collection):
"""Find all matches in the `collection` for the specified `word`.
If `word` is empty, returns all items in `collection`.
:type word: str
:param word: The substring to search for.
:type collection: collection, usually a list
:param collection: A collecti... |
Create the toolbar handler. | def _create_toolbar_handler(self, get_match_fuzzy, get_enable_vi_bindings,
get_show_completion_columns, get_show_help):
"""Create the toolbar handler.
:type get_fuzzy_match: callable
:param fuzzy_match: Gets the fuzzy matching config.
:type get_enable_vi... |
Generate default layout. | def create_default_layout(app, message='',
lexer=None, is_password=False,
reserve_space_for_menu=False,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
display_completions_in_columns... |
Cross platform temporary file creation. | def temporary_file(mode):
"""Cross platform temporary file creation.
This is an alternative to ``tempfile.NamedTemporaryFile`` that
also works on windows and avoids the "file being used by
another process" error.
"""
tempdir = tempfile.gettempdir()
basename = 'tmpfile-%s' % (uuid.uuid4())
... |
Return the file for a given filename. | def file_contents(self, filename, binary=False):
"""Return the file for a given filename.
If you want binary content use ``mode='rb'``.
"""
if binary:
mode = 'rb'
else:
mode = 'r'
try:
with open(filename, mode) as f:
r... |
Load the completion index for a given CLI version. | def load_index(self, version_string):
"""Load the completion index for a given CLI version.
:type version_string: str
:param version_string: The AWS CLI version, e.g "1.9.2".
:raises: :class:`IndexLoadError <exceptions.IndexLoadError>`
"""
filename = self._filename_for_... |
Load completions from the completion index. | def load_completions(self):
"""Load completions from the completion index.
Updates the following attributes:
* commands
* subcommands
* global_opts
* args_opts
"""
try:
index_str = self.load_index(utils.AWSCLI_VERSION)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.