code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
path = self._library_path()
logger.info("Loading library from path {}".format(path))
library_dir = os.path.dirname(path)
if platform.system() == 'Windows':
import win32api
olddir = os.getcwd()
os.chdir(library_dir)
win32api.SetDllD... | def _load_library(self) | Return the fortran library, loaded with | 2.902081 | 2.889417 | 1.004383 |
if configfile is not None:
self.configfile = configfile
try:
self.configfile
except AttributeError:
raise ValueError("Specify configfile during construction or during initialize")
abs_name = os.path.abspath(self.configfile)
os.chdir(o... | def initialize(self, configfile=None) | Initialize and load the Fortran library (and model, if applicable).
The Fortran library is loaded and ctypes is used to annotate functions
inside the library. The Fortran library's initialization is called.
Normally a path to an ``*.ini`` model file is passed to the
:meth:`__init__`. I... | 4.860905 | 4.502065 | 1.079706 |
self.library.finalize.argtypes = []
self.library.finalize.restype = c_int
ierr = wrap(self.library.finalize)()
# always go back to previous directory
logger.info('cd {}'.format(self.original_dir))
# This one doesn't work.
os.chdir(self.original_dir)
... | def finalize(self) | Shutdown the library and clean up the model.
Note that the Fortran library's cleanup code is not up to snuff yet,
so the cleanup is not perfect. Note also that the working directory is
changed back to the original one. | 5.663915 | 4.977996 | 1.13779 |
self.library.update.argtypes = [c_double]
self.library.update.restype = c_int
if dt == -1:
# use default timestep
dt = self.get_time_step()
result = wrap(self.library.update)(dt)
return result | def update(self, dt=-1) | Return type string, compatible with numpy. | 4.008245 | 3.613533 | 1.109231 |
n = c_int()
self.library.get_var_count.argtypes = [POINTER(c_int)]
self.library.get_var_count(byref(n))
return n.value | def get_var_count(self) | Return number of variables | 2.875573 | 2.468608 | 1.164856 |
i = c_int(i)
name = create_string_buffer(MAXSTRLEN)
self.library.get_var_name.argtypes = [c_int, c_char_p]
self.library.get_var_name(i, name)
return name.value | def get_var_name(self, i) | Return variable name | 2.601683 | 2.289728 | 1.136241 |
name = create_string_buffer(name)
type_ = create_string_buffer(MAXSTRLEN)
self.library.get_var_type.argtypes = [c_char_p, c_char_p]
self.library.get_var_type(name, type_)
return type_.value | def get_var_type(self, name) | Return type string, compatible with numpy. | 3.036201 | 2.628987 | 1.154894 |
name = create_string_buffer(name)
self.library.inq_compound.argtypes = [c_char_p, POINTER(c_int)]
self.library.inq_compound.restype = None
nfields = c_int()
self.library.inq_compound(name, byref(nfields))
return nfields.value | def inq_compound(self, name) | Return the number of fields and size (not yet) of a compound type. | 2.365894 | 1.970766 | 1.200495 |
typename = create_string_buffer(name)
index = c_int(index + 1)
fieldname = create_string_buffer(MAXSTRLEN)
fieldtype = create_string_buffer(MAXSTRLEN)
rank = c_int()
arraytype = ndpointer(dtype='int32',
ndim=1,
... | def inq_compound_field(self, name, index) | Lookup the type,rank and shape of a compound field | 2.494299 | 2.29512 | 1.086784 |
# look up the type name
compoundname = self.get_var_type(varname)
nfields = self.inq_compound(compoundname)
# for all the fields look up the type, rank and shape
fields = []
for i in range(nfields):
(fieldname, fieldtype,
fieldrank, fiel... | def make_compound_ctype(self, varname) | Create a ctypes type that corresponds to a compound type in memory. | 3.97782 | 3.783246 | 1.05143 |
name = create_string_buffer(name)
rank = c_int()
self.library.get_var_rank.argtypes = [c_char_p, POINTER(c_int)]
self.library.get_var_rank.restype = None
self.library.get_var_rank(name, byref(rank))
return rank.value | def get_var_rank(self, name) | Return array rank or 0 for scalar. | 2.117071 | 1.869026 | 1.132714 |
rank = self.get_var_rank(name)
name = create_string_buffer(name)
arraytype = ndpointer(dtype='int32',
ndim=1,
shape=(MAXDIMS, ),
flags='F')
shape = np.empty((MAXDIMS, ), dtype='int32', orde... | def get_var_shape(self, name) | Return shape of the array. | 3.394676 | 3.158175 | 1.074885 |
start_time = c_double()
self.library.get_start_time.argtypes = [POINTER(c_double)]
self.library.get_start_time.restype = None
self.library.get_start_time(byref(start_time))
return start_time.value | def get_start_time(self) | returns start time | 2.129775 | 1.94492 | 1.095045 |
end_time = c_double()
self.library.get_end_time.argtypes = [POINTER(c_double)]
self.library.get_end_time.restype = None
self.library.get_end_time(byref(end_time))
return end_time.value | def get_end_time(self) | returns end time of simulation | 2.151803 | 1.950166 | 1.103395 |
current_time = c_double()
self.library.get_current_time.argtypes = [POINTER(c_double)]
self.library.get_current_time.restype = None
self.library.get_current_time(byref(current_time))
return current_time.value | def get_current_time(self) | returns current time of simulation | 2.148024 | 1.935194 | 1.109979 |
time_step = c_double()
self.library.get_time_step.argtypes = [POINTER(c_double)]
self.library.get_time_step.restype = None
self.library.get_time_step(byref(time_step))
return time_step.value | def get_time_step(self) | returns current time step of simulation | 2.121674 | 1.926525 | 1.101296 |
# How many dimensions.
rank = self.get_var_rank(name)
# The shape array is fixed size
shape = np.empty((MAXDIMS, ), dtype='int32', order='F')
shape = self.get_var_shape(name)
# there should be nothing here...
assert sum(shape[rank:]) == 0
# variab... | def get_var(self, name) | Return an nd array from model library | 5.948175 | 5.870067 | 1.013306 |
# we don't expect anything back
try:
self.library.set_logger.restype = None
except AttributeError:
logger.warn("Tried to set logger but method is not implemented in %s", self.engine)
return
# as an argument we need a pointer to a fortran log ... | def set_logger(self, logger) | subscribe to fortran log messages | 8.112925 | 7.131314 | 1.137648 |
current_time = c_double(current_time)
try:
self.library.set_current_time.argtypes = [POINTER(c_double)]
self.library.set_current_time.restype = None
self.library.set_current_time(byref(current_time))
except AttributeError:
logger.warn("Tri... | def set_current_time(self, current_time) | sets current time of simulation | 2.705081 | 2.69082 | 1.0053 |
'''
This does not only accept/refuse a book. It also returns an ENHANCED
version of body, with (mostly fts-related) additional fields.
This function is idempotent.
'''
if '_language' not in body:
raise ValueError('language needed')
if len(body['_language']) > 2:
raise ValueE... | def validate_book(body) | This does not only accept/refuse a book. It also returns an ENHANCED
version of body, with (mostly fts-related) additional fields.
This function is idempotent. | 7.719414 | 3.254474 | 2.371939 |
''' Create and configure index
If `wait_for_ready` is True, this function will block until
status for `self.index_name` will be `yellow`
'''
if self.es.indices.exists(self.index_name):
try:
self.update_mappings()
except MappingsEx... | def setup_db(self, wait_for_ready=True) | Create and configure index
If `wait_for_ready` is True, this function will block until
status for `self.index_name` will be `yellow` | 4.389273 | 3.358781 | 1.306805 |
''' Create the index
Create the index with given configuration.
If `indexname` is provided it will be used as the new index name
instead of the class one (:py:attr:`DB.index_name`)
:param index_conf: configuration to be used in index creation. If this
... | def create_index(self, indexname=None, index_conf=None) | Create the index
Create the index with given configuration.
If `indexname` is provided it will be used as the new index name
instead of the class one (:py:attr:`DB.index_name`)
:param index_conf: configuration to be used in index creation. If this
... | 3.445569 | 1.888503 | 1.824498 |
'''Clone current index
All entries of the current index will be copied into the newly
created one named `new_indexname`
:param index_conf: Configuration to be used in the new index creation.
This param will be passed directly to :py:func:`DB.creat... | def clone_index(self, new_indexname, index_conf=None) | Clone current index
All entries of the current index will be copied into the newly
created one named `new_indexname`
:param index_conf: Configuration to be used in the new index creation.
This param will be passed directly to :py:func:`DB.create_index` | 4.520921 | 1.982141 | 2.280827 |
'''Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is built in such a way that you can continue to use the old index name,
... | def reindex(self, new_index=None, index_conf=None) | Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is built in such a way that you can continue to use the old index name,
thi... | 3.354917 | 1.771757 | 1.893554 |
'''
High-level method to do "more like this".
Its exact implementation can vary.
'''
query = {
'query': {'more_like_this': {
'like': {'_id': _id},
'min_term_freq': 1,
'min_doc_freq': 1,
}}... | def mlt(self, _id) | High-level method to do "more like this".
Its exact implementation can vary. | 4.752884 | 3.069956 | 1.548193 |
'''return true if at least one book has
file with the given url as attachment
'''
body = self._get_search_field('_attachments.url', url)
return self.es.count(index=self.index_name, body=body)['count'] > 0 | def file_is_attached(self, url) | return true if at least one book has
file with the given url as attachment | 9.342038 | 4.73079 | 1.974731 |
'''
Call it like this:
db.add_book(doc_type='book',
body={'title': 'foobar', '_language': 'it'})
'''
body = validate_book(body)
body['_insertion_date'] = current_time_millisec()
return self.es.index(index=self.index_name, doc_type=doc_type, body=bo... | def add_book(self, body, doc_type='book') | Call it like this:
db.add_book(doc_type='book',
body={'title': 'foobar', '_language': 'it'}) | 5.556968 | 2.792117 | 1.990234 |
'''Delete all books from the index'''
def delete_action_gen():
scanner = scan(self.es,
index=self.index_name,
query={'query': {'match_all':{}}})
for v in scanner:
yield { '_op_type': 'delete',
... | def delete_all(self) | Delete all books from the index | 4.490924 | 3.969031 | 1.131491 |
''' Update a book
The "body" is merged with the current one.
Yes, it is NOT overwritten.
In case of concurrency conflict
this function could raise `elasticsearch.ConflictError`
'''
# note that we are NOT overwriting all the _source, just merging
... | def update_book(self, id, body, doc_type='book') | Update a book
The "body" is merged with the current one.
Yes, it is NOT overwritten.
In case of concurrency conflict
this function could raise `elasticsearch.ConflictError` | 6.446995 | 3.027609 | 2.129401 |
''' replace the entire book body
Instead of `update_book` this function
will overwrite the book content with param body
If param `version` is given, it will be checked that the
changes are applied upon that document version.
If the document version p... | def modify_book(self, id, body, doc_type='book', version=None) | replace the entire book body
Instead of `update_book` this function
will overwrite the book content with param body
If param `version` is given, it will be checked that the
changes are applied upon that document version.
If the document version provided is d... | 6.63856 | 2.043099 | 3.249261 |
'''
Increment the download counter of a specific file
'''
body = self.es.get(index=self.index_name, id=id, doc_type='book', _source_include='_attachments')['_source']
for attachment in body['_attachments']:
if attachment['id'] == attachmentID:
attachm... | def increment_download_count(self, id, attachmentID, doc_type='book') | Increment the download counter of a specific file | 2.905211 | 2.697226 | 1.077111 |
typed_conf = {}
for s in raw_conf.keys():
typed_conf[s] = {}
for option in raw_conf[s]:
val = raw_conf[s][option]
if len(val) > 1 and (val[0] == '"' and val[-1] == '"'):
# It is a string
typed_conf... | def __add_types(self, raw_conf) | Convert to int, boolean, list, None types config items | 2.008634 | 1.952858 | 1.028561 |
check_version = kwargs.pop('check_version', True)
es = Elasticsearch_official(*args, **kwargs)
if check_version:
es_version = es.info()['version']['number'].split('.')
if(int(es_version[0]) != int(es_pylib_version[0])):
raise RuntimeError("The Elasticsearch python library ve... | def Elasticsearch(*args, **kwargs) | Elasticsearch wrapper function
Wrapper function around the official Elasticsearch class that adds
a simple version check upon initialization.
In particular it checks if the major version of the library in use
match the one of the cluster that we are tring to interact with.
The check can be skipped ... | 3.743268 | 3.352328 | 1.116617 |
conf = {}
if environ is None:
environ = os.environ
if prefix is None and envvars is None:
raise RuntimeError('Must either give prefix or envvars argument')
# if it's a list, convert to dict
if isinstance(envvars, list):
envvars = {k: k for k in envvars}
if not envv... | def from_envvars(prefix=None, environ=None, envvars=None, as_json=True) | Load environment variables in a dictionary
Values are parsed as JSON. If parsing fails with a ValueError,
values are instead used as verbatim strings.
:param prefix: If ``None`` is passed as envvars, all variables from
``environ`` starting with this prefix are imported. The
... | 2.145312 | 2.067117 | 1.037828 |
'''Load configuration
The following steps will be undertake:
* It will attempt to load configs from file:
if `path` is provided, it will be used, otherwise the path
will be taken from envvar `envvar_prefix` + "SETTINGS".
* all envvars starting with `envvar_prefix` will be lo... | def load_configs(envvar_prefix, path=None) | Load configuration
The following steps will be undertake:
* It will attempt to load configs from file:
if `path` is provided, it will be used, otherwise the path
will be taken from envvar `envvar_prefix` + "SETTINGS".
* all envvars starting with `envvar_prefix` will be loaded. | 5.047878 | 2.092989 | 2.411803 |
last = timeseries['value'][len(timeseries['value']) - 1]
prev = timeseries['value'][len(timeseries['value']) - 2]
trend = last - prev
trend_percentage = None
if last == 0:
if prev > 0:
trend_percentage = -100
else:
trend_percentage = 0
else:
... | def get_trend(timeseries) | Using the values returned by get_timeseries(), compare the current
Metric value with it's previous period's value
:param timeseries: data returned from the get_timeseries() method
:returns: the last period value and relative change | 2.51724 | 2.38206 | 1.056749 |
if sorted(closed.keys()) != sorted(submitted.keys()):
raise AttributeError("The buckets supplied are not congruent!")
dates = closed.index.values
closed_values = closed['value']
submitted_values = submitted['value']
ratios = []
for x, y in zip(closed_values, submitted_values):
... | def calculate_bmi(closed, submitted) | BMI is the ratio of the number of closed items to the number of total items
submitted in a particular period of analysis. The items can be issues, pull
requests and such
:param closed: dataframe returned from get_timeseries() containing closed items
:param submitted: dataframe returned from get_timeser... | 3.438439 | 2.99957 | 1.146311 |
cleaned_buckets = []
for item in buckets:
if type(item) == str:
return item
temp = {}
for key, val in item.items():
try:
temp[key] = val['value']
except Exception as e:
temp[key] = val
cleaned_buckets.appe... | def buckets_to_df(buckets) | Takes in aggregation buckets and converts them into a pandas dataframe
after cleaning the buckets. If a DateTime field is present(usually having the name:
"key_as_string") parses it to datetime object and then it uses it as key
:param buckets: elasticsearch aggregation buckets to be converted to a DataFram... | 2.594953 | 2.445976 | 1.060907 |
q = Q("match", **key_val)
self.search = self.search.query(q)
return self | def add_query(self, key_val={}) | Add an es_dsl query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods | 4.685009 | 5.276127 | 0.887964 |
q = Q("match", **key_val)
self.search = self.search.query(~q)
return self | def add_inverse_query(self, key_val={}) | Add an es_dsl inverse query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods | 5.853067 | 6.764318 | 0.865286 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("sum", field=field)
self.aggregations['sum_' + field] = agg
return self | def get_sum(self, field=None) | Create a sum aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 8.272882 | 6.69695 | 1.235321 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("avg", field=field)
self.aggregations['avg_' + field] = agg
return self | def get_average(self, field=None) | Create an avg aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 8.176358 | 6.441799 | 1.269266 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
if not percents:
percents = [1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]
agg = A("percentiles", field=field, percents=percents)
self.aggregations['percentiles_' + field] = a... | def get_percentiles(self, field=None, percents=None) | Create a percentile aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:param percents: the specific percentiles to be calculated
default: [1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]
:returns: self, w... | 2.801208 | 2.460402 | 1.138517 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("terms", field=field, size=self.size, order={"_count": "desc"})
self.aggregations['terms_' + field] = agg
return self | def get_terms(self, field=None) | Create a terms aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 5.490259 | 4.512063 | 1.216796 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("min", field=field)
self.aggregations['min_' + field] = agg
return self | def get_min(self, field=None) | Create a min aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 8.487512 | 6.626224 | 1.280897 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("max", field=field)
self.aggregations['max_' + field] = agg
return self | def get_max(self, field=None) | Create a max aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 8.144015 | 6.546421 | 1.244041 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("cardinality", field=field, precision_threshold=self.precision_threshold)
self.aggregations['cardinality_' + field] = agg
return self | def get_cardinality(self, field=None) | Create a cardinality aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 6.014623 | 5.123417 | 1.173948 |
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("extended_stats", field=field)
self.aggregations['extended_stats_' + field] = agg
return self | def get_extended_stats(self, field=None) | Create an extended_stats aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods | 7.191932 | 5.629855 | 1.277463 |
agg_name = name if name else 'custom_agg'
self.aggregations[agg_name] = agg
return self | def add_custom_aggregation(self, agg, name=None) | Takes in an es_dsl Aggregation object and adds it to the aggregation dict.
Can be used to add custom aggregations such as moving averages
:param agg: aggregation to be added to the es_dsl search object
:param name: name of the aggregation object (optional)
:returns: self, which allows t... | 3.941561 | 4.724635 | 0.834257 |
if not field:
field = "grimoire_creation_date"
self.start_date = start
date_dict = {field: {"gte": "{}".format(self.start_date.isoformat())}}
self.search = self.search.filter("range", **date_dict)
return self | def since(self, start, field=None) | Add the start date to query data starting from that date
sets the default start date for each query
:param start: date to start looking at the fields (from date)
:param field: specific field for the start date in range filter
for the Search object
:returns: self, w... | 4.821407 | 4.031046 | 1.196069 |
if not field:
field = "grimoire_creation_date"
self.end_date = end
date_dict = {field: {"lte": "{}".format(self.end_date.isoformat())}}
self.search = self.search.filter("range", **date_dict)
return self | def until(self, end, field=None) | Add the end date to query data upto that date
sets the default end date for each query
:param end: date to stop looking at the fields (to date)
:param field: specific field for the end date in range filter
for the Search object
:returns: self, which allows the meth... | 5.000166 | 4.202008 | 1.189947 |
# this functions is currently only for issues and PRs
agg_field = field if field else "author_org_name"
agg_key = "terms_" + agg_field
if agg_key in self.aggregations.keys():
agg = self.aggregations[agg_key]
else:
agg = A("terms", field=agg_field... | def by_organizations(self, field=None) | Used to seggregate the data acording to organizations. This method
pops the latest aggregation from the self.aggregations dict and
adds it as a nested aggregation under itself
:param field: the field to create the parent agg (optional)
default: author_org_name
:ret... | 4.824724 | 3.89994 | 1.237128 |
hist_period = period if period else self.interval_
time_zone = timezone if timezone else "UTC"
start_ = start if start else self.start_date
end_ = end if end else self.end_date
bounds = self.get_bounds(start_, end_)
date_field = field if field else "grimoire_c... | def by_period(self, field=None, period=None, timezone=None, start=None, end=None) | Create a date histogram aggregation using the last added aggregation for the
current object. Add this date_histogram aggregation into self.aggregations
:param field: the index field to create the histogram from
:param period: the interval which elasticsearch supports, ex: "month", "week" and su... | 3.101577 | 2.930259 | 1.058465 |
bounds = {}
if start or end:
# Extend bounds so we have data until start and end
start_ts = None
end_ts = None
if start:
start = start.replace(microsecond=0)
start_ts = start.replace(tzinfo=timezone.utc).timestamp... | def get_bounds(self, start=None, end=None) | Get bounds for the date_histogram method
:param start: start date to set the extended_bounds min field
:param end: end date to set the extended_bounds max field
:returns bounds: a dictionary containing the min and max fields
required to set the bounds in date_histogram ... | 2.378104 | 2.242131 | 1.060645 |
temp_search = self.search.to_dict()
if 'aggs' in temp_search.keys():
del temp_search['aggs']
self.search.from_dict(temp_search)
self.parent_agg_counter = 0
self.child_agg_counter = 0
self.child_agg_counter_dict = defaultdict(int) | def reset_aggregations(self) | Remove all aggregations added to the search object | 3.58112 | 3.078939 | 1.163102 |
self.reset_aggregations()
for key, val in self.aggregations.items():
self.search.aggs.bucket(self.parent_agg_counter, val)
self.parent_agg_counter += 1
self.search = self.search.extra(size=0)
response = self.search.execute()
self.flush_aggregat... | def fetch_aggregation_results(self) | Loops though the self.aggregations dict and adds them to the Search object
in order in which they were created. Queries elasticsearch and returns a dict
containing the results
:returns: a dictionary containing the response from elasticsearch | 3.582505 | 3.198871 | 1.119928 |
if not fields:
raise AttributeError("Please provide the fields to get from elasticsearch!")
self.reset_aggregations()
self.search = self.search.extra(_source=fields)
self.search = self.search.extra(size=self.size)
response = self.search.execute()
h... | def fetch_results_from_source(self, *fields, dataframe=False) | Get values for specific fields in the elasticsearch index, from source
:param fields: a list of fields that have to be retrieved from the index
:param dataframe: if true, will return the data in the form of a pandas.DataFrame
:returns: a list of dicts(key_val pairs) containing the values for th... | 3.327854 | 3.338274 | 0.996879 |
res = self.fetch_aggregation_results()
ts = {"date": [], "value": [], "unixtime": []}
if 'buckets' not in res['aggregations'][str(self.parent_agg_counter - 1)]:
raise RuntimeError("Aggregation results have no buckets in time series results.")
for bucket in res['a... | def get_timeseries(self, child_agg_count=0, dataframe=False) | Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataFrame object
:returns: dictionary containing "date", "value" a... | 3.308217 | 3.140154 | 1.053521 |
res = self.fetch_aggregation_results()
if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]:
try:
agg = res['aggregations'][str(self.parent_agg_counter - 1)]['values']["50.0"]
if agg == 'NaN':
... | def get_aggs(self) | Compute the values for single valued aggregations
:returns: the single aggregation value | 3.719811 | 3.57288 | 1.041124 |
res = self.fetch_aggregation_results()
keys = []
values = []
for bucket in res['aggregations'][str(self.parent_agg_counter - 1)]['buckets']:
keys.append(bucket['key'])
values.append(bucket['doc_count'])
result = {"keys": keys, "values": values}
... | def get_list(self, dataframe=False) | Compute the value for multi-valued aggregations
:returns: a dict containing 'keys' and their corresponding 'values' | 3.626884 | 3.293207 | 1.101323 |
'''
Upgrade libreant database.
This command can be used after an update of libreant
in order to upgrade the database and make it aligned with the new version.
'''
from utils.es import Elasticsearch
from libreantdb import DB, migration
from libreantdb.exceptions import MappingsException
... | def upgrade(check_only, yes) | Upgrade libreant database.
This command can be used after an update of libreant
in order to upgrade the database and make it aligned with the new version. | 4.946118 | 4.055337 | 1.219657 |
'''Import volumes
SOURCE must be a json file and must follow the same structure used in `libreant-db export`.
Pass - to read from standard input.
'''
volumes = json.load(source)
tot = len(volumes)
if not yes:
click.confirm("Are you sure you want to import {} volumes into index '{}'"... | def import_volumes(source, ignore_conflicts, yes) | Import volumes
SOURCE must be a json file and must follow the same structure used in `libreant-db export`.
Pass - to read from standard input. | 5.192733 | 3.493659 | 1.486331 |
'''
Add a new volume to libreant.
The metadata of the volume are taken from a json file whose path must be
passed as argument. Passing "-" as argument will read the file from stdin.
language is an exception, because it must be set using --language
For every attachment you must add a --file AND... | def insert_volume(language, filepath, notes, metadata) | Add a new volume to libreant.
The metadata of the volume are taken from a json file whose path must be
passed as argument. Passing "-" as argument will read the file from stdin.
language is an exception, because it must be set using --language
For every attachment you must add a --file AND a --notes.
... | 8.31025 | 1.652817 | 5.02793 |
'''
all the arguments are lists
returns a list of dictionaries; each dictionary "represent" an attachment
'''
assert type(filepaths) in (list, tuple)
assert type(notes) in (list, tuple)
# this if clause means "if those lists are not of the same length"
if len(filepaths) != len(notes):
... | def attach_list(filepaths, notes) | all the arguments are lists
returns a list of dictionaries; each dictionary "represent" an attachment | 3.499864 | 2.692274 | 1.299966 |
if fields is None:
return
if type(fields) in [list, set, frozenset, tuple]:
fields = {x: True for x in fields}
if type(fields) == dict:
fields.setdefault("_id", False)
kwargs["projection"] = fields | def _param_fields(kwargs, fields) | Normalize the "fields" argument to most find methods | 4.668251 | 4.030554 | 1.158216 |
def wrapped(*args, **kwargs):
# Normalize the fields argument if passed as a positional param.
if len(args) == 3 and func.__name__ in ("find", "find_one", "find_by_id", "find_by_ids"):
_param_fields(kwargs, args[2])
args = (args[0], args[1])
elif "fields" in kwargs:
_param_fields(kwa... | def find_method(func) | Decorator that manages smart defaults or transforms for common find methods:
- fields/projection: list of fields to be returned. Contrary to pymongo, _id won't be added automatically
- json: performs a json_clone on the results. Beware of performance!
- timeout
- return_document | 2.738481 | 2.441821 | 1.121491 |
if type(batch_size) == int:
cursor.batch_size(batch_size)
if limit is not None:
cursor.limit(limit)
if sort is not None:
cursor.sort(sort)
if skip is not None:
cursor.skip(skip) | def patch_cursor(cursor, batch_size=None, limit=None, skip=None, sort=None, **kwargs) | Adds batch_size, limit, sort parameters to a DB cursor | 1.940658 | 1.979511 | 0.980372 |
return bool(self.find(query, **args).limit(1).count()) | def exists(self, query, **args) | Returns True if the search matches at least one document | 6.209482 | 5.253637 | 1.18194 |
# class DocumentClassWithFields(self.document_class):
# _fetched_fields = kwargs.get("projection")
# mongokat_collection = self
read_preference = kwargs.get("read_preference") or getattr(self.collection, "read_preference", None) or ReadPreference.PRIMARY
if "r... | def _collection_with_options(self, kwargs) | Returns a copy of the pymongo collection with various options set up | 2.798359 | 2.755142 | 1.015686 |
doc = self._collection_with_options(kwargs).find_one(*args, **kwargs)
if doc is None:
return None
return doc | def find_one(self, *args, **kwargs) | Get a single document from the database. | 5.25688 | 4.465086 | 1.17733 |
if type(_id) == dict and _id.get("_id"):
return self.find_one({"_id": ObjectId(_id["_id"])}, **kwargs)
return self.find_one({"_id": ObjectId(_id)}, **kwargs) | def find_by_id(self, _id, **kwargs) | Pass me anything that looks like an _id : str, ObjectId, {"_id": str}, {"_id": ObjectId} | 2.523934 | 2.28948 | 1.102405 |
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return [] # FIXME : this should be an empty cursor !
# Optimized path when only fetching the _id field.
# Be mindful this might not filter missing documents that may not have been returned, had we done ... | def find_by_ids(self, _ids, projection=None, **kwargs) | Does a big _id:$in query on any iterator | 6.876047 | 6.508648 | 1.056448 |
return self.find_one({"_id": ObjectId(base64.b64decode(_id))}, **kwargs) | def find_by_b64id(self, _id, **kwargs) | Pass me a base64-encoded ObjectId | 3.831714 | 3.381931 | 1.132996 |
return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **kwargs) | def find_by_b64ids(self, _ids, **kwargs) | Pass me a list of base64-encoded ObjectId | 4.00284 | 3.445366 | 1.161804 |
find_kwargs = {
"projection": {"_id": False}
}
find_kwargs["projection"][field] = True
cursor = self._collection_with_options(kwargs).find(query, **find_kwargs) # We only want 1 field: bypass the ORM
patch_cursor(cursor, **kwargs)
return (dotdict(... | def iter_column(self, query=None, field="_id", **kwargs) | Return one field as an iterator.
Beware that if your query returns records where the field is not set, it will raise a KeyError. | 8.474718 | 8.406475 | 1.008118 |
import random
max = self.count(**kwargs)
if max:
num = random.randint(0, max - 1)
return next(self.find(**kwargs).skip(num)) | def find_random(self, **kwargs) | return one random document from the collection | 4.58064 | 3.625537 | 1.263438 |
obj = self(data) # pylint: disable=E1102
obj.save()
if return_object:
return obj
else:
return obj["_id"] | def insert(self, data, return_object=False) | Inserts the data as a new document. | 4.371796 | 3.923644 | 1.114218 |
if not self.has_trigger(event):
return
if documents is not None:
pass
elif ids is not None:
documents = self.find_by_ids(ids, read_use="primary")
elif filter is not None:
documents = self.find(filter, read_use="primary")
... | def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None) | Trigger the after_save hook on documents, if present. | 3.26999 | 3.212289 | 1.017963 |
if spec is None:
spec = {}
for key in self.structure:
if key in spec:
if isinstance(spec[key], dict):
spec[key].update({'$exists': True})
else:
spec[key] = {'$exists': True}
return self.find(spec, *a... | def fetch(self, spec=None, *args, **kwargs) | return all document which match the structure of the object
`fetch()` takes the same arguments than the the pymongo.collection.find method.
The query is launch against the db and collection of the object. | 2.611517 | 2.204454 | 1.184655 |
bson_obj = self.fetch(*args, **kwargs)
count = bson_obj.count()
if count > 1:
raise MultipleResultsFound("%s results found" % count)
elif count == 1:
# return self(bson_obj.next(), fetched_fields=kwargs.get("projection"))
return next(bson_obj) | def fetch_one(self, *args, **kwargs) | return one document which match the structure of the object
`fetch_one()` takes the same arguments than the the pymongo.collection.find method.
If multiple documents are found, raise a MultipleResultsFound exception.
If no document is found, return None
The query is launch against the db... | 5.249451 | 4.899776 | 1.071366 |
print >> sys.stderr, __doc__
if msg:
print >> sys.stderr, msg
sys.exit(ecode) | def usage(ecode, msg='') | Print usage and msg and exit with given code. | 2.588561 | 2.374394 | 1.090198 |
global MESSAGES
if not fuzzy and transtr and not transtr.startswith('\0'):
MESSAGES[msgid] = transtr | def add(msgid, transtr, fuzzy) | Add a non-fuzzy translation to the dictionary. | 7.566465 | 7.344189 | 1.030266 |
global MESSAGES
keys = MESSAGES.keys()
# the keys are sorted in the .mo file
keys.sort()
offsets = []
ids = strs = ''
for _id in keys:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL does not count into the size.
offsets... | def generate() | Return the generated output. | 4.529102 | 4.455783 | 1.016455 |
'''Get the requirements string for elasticsearch-py library
Returns a suitable requirements string for the elsaticsearch-py library
according to the elasticsearch version to be supported (es_version)'''
# accepts version range in the form `2.x`
es_version = es_version.replace('x', '0')
es_vers... | def get_es_requirements(es_version) | Get the requirements string for elasticsearch-py library
Returns a suitable requirements string for the elsaticsearch-py library
according to the elasticsearch version to be supported (es_version) | 3.142652 | 2.057571 | 1.52736 |
# thanks to deluge guys ;)
po_dir = os.path.join(os.path.dirname(__file__), 'webant', 'translations')
print('Compiling po files from "{}"...'.format(po_dir))
for lang in os.listdir(po_dir):
sys.stdout.write("\tCompiling {}... ".format(lang))
sys.stdout.fl... | def run(self) | Compile all message catalogs .po files into .mo files.
Skips not changed file based on source mtime. | 2.811216 | 2.638459 | 1.065476 |
if not self.dict_response[key1][key2]:
l = self.response
for i, orig in enumerate(self.origins):
self.dict_response[key1][key2][orig] = {}
for j, dest in enumerate(self.destinations):
if l[i]['elements'][j]['status'] == 'OK':
... | def __get_response_element_data(self, key1, key2) | For each origin an elements object is created in the ouput.
For each destination, an object is created inside elements object. For example, if there are
2 origins and 1 destination, 2 element objects with 1 object each are created. If there are
2 origins and 2 destinations, 2 element objects wit... | 2.342621 | 2.09847 | 1.116347 |
if not self.dict_response['distance']['value']:
self.get_distance_values()
if origin_raw:
origin = copy.deepcopy(self.dict_response['distance']['value'][origin_raw])
else:
origin = copy.deepcopy(self.dict_response['distance']['value'][self.origins[or... | def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None) | Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance. | 3.582152 | 3.448257 | 1.03883 |
node_map_dict = {}
# map each node to its new name (e.g. "a1")
for i in range(0, len(self.nodes)):
node_map_dict[self.nodes[i]] = prefix + str(i)
# update node name
for i, v in enumerate(self.nodes):
self.nodes[i] = node_map_dict[v]
# upda... | def rename_node(self, prefix) | Rename AMR graph nodes to prefix + node_index to avoid nodes with the same name in two different AMRs. | 2.738464 | 2.56677 | 1.066891 |
instance_triple = []
relation_triple = []
attribute_triple = []
for i in range(len(self.nodes)):
instance_triple.append(("instance", self.nodes[i], self.node_values[i]))
# l[0] is relation name
# l[1] is the other node this node has relation w... | def get_triples(self) | Get the triples in three lists.
instance_triple: a triple representing an instance. E.g. instance(w, want-01)
attribute triple: relation of attributes, e.g. polarity(w, - )
and relation triple, e.g. arg0 (w, b) | 2.466461 | 2.186556 | 1.128012 |
cur_amr = []
has_content = False
for line in input_f:
line = line.strip()
if line == "":
if not has_content:
# empty lines before current AMR
continue
else:
# end of curre... | def get_amr_line(input_f) | Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid | 3.147494 | 3.232613 | 0.973669 |
if not data_sources:
# For testing
data_sources = ["gerrit", "git", "github_issues", "mls"]
# In new_config a dict with all the metrics for all data sources is created
new_config = {}
for ds in data_sources:
ds_config = self.ds2class[ds].get... | def __get_config(self, data_sources=None) | Build a dictionary with the Report configuration with the data sources and metrics to be included
in each section of the report
:param data_sources: list of data sources to be included in the report
:return: a dict with the data sources and metrics to be included in the report | 3.281469 | 3.202926 | 1.024522 |
if not ts:
return ts
ts_clean = [val if val else 0 for val in ts]
return ts_clean | def __convert_none_to_zero(self, ts) | Convert None values to 0 so the data works with Matplotlib
:param ts:
:return: a list with 0s where Nones existed | 5.651509 | 4.85472 | 1.164127 |
colors = ["orange", "grey"]
data1 = self.__convert_none_to_zero(data1)
data2 = self.__convert_none_to_zero(data2)
data3 = self.__convert_none_to_zero(data3)
fig, ax = plt.subplots(1)
xpos = np.arange(len(data1))
width = 0.28
plt.title(title)
... | def bar3_chart(self, title, labels, data1, file_name, data2, data3, legend=["", ""]) | Generate a bar plot with three columns in each x position and save it to file_name
:param title: title to be used in the chart
:param labels: list of labels for the x axis
:param data1: values for the first columns
:param file_name: name of the file in which to save the chart
:p... | 2.481068 | 2.528504 | 0.98124 |
ds = self.class2ds[metric_cls.ds]
if self.index_dict[ds]:
index_name = self.index_dict[ds]
else:
index_name = self.ds2index[metric_cls.ds]
return index_name | def get_metric_index(self, metric_cls) | Get the index name with the data for a metric class
:param metric_cls: a metric class
:return: the name of the index with the data for the metric | 4.2339 | 4.237054 | 0.999255 |
metrics = self.config['overview']['activity_metrics']
file_name = self.config['overview']['activity_file_csv']
data_path = os.path.join(self.data_dir, "data")
file_name = os.path.join(data_path, file_name)
logger.debug("CSV file %s generation in progress", fi... | def sec_overview(self) | Generate the data for the Overview section in the report
:return: | 3.206891 | 3.184649 | 1.006984 |
metrics = self.config['com_channels']['activity_metrics']
metrics += self.config['com_channels']['author_metrics']
for metric in metrics:
csv_labels = 'labels,' + metric.id
file_label = metric.ds.name + "_" + metric.id
title_label = metric.name + " p... | def sec_com_channels(self) | Generate the data for the Communication Channels section in the report
:return: | 7.820119 | 7.669242 | 1.019673 |
logger.debug("CSV file %s generation in progress", file_label)
esfilters = None
csv_labels = csv_labels.replace("_", "") # LaTeX not supports
if project and project != self.GLOBAL_PROJECT:
esfilters = {"project": project}
m1 = metric1(self.es_url, self.ge... | def __create_csv_eps(self, metric1, metric2, csv_labels, file_label,
title_label, project=None) | Generate the CSV data and EPS figs files for two metrics
:param metric1: first metric class
:param metric2: second metric class
:param csv_labels: labels to be used in the CSV file
:param file_label: shared filename token to be included in csv and eps files
:param title_label: ti... | 2.177096 | 2.17156 | 1.002549 |
def create_data(metrics, project):
csv_labels = "labels" + ',' + metrics[0].id + "," + metrics[1].id
file_label = metrics[0].ds.name + "_" + metrics[0].id + "_"
file_label += metrics[1].ds.name + "_" + metrics[1].id
title_label = metrics[0].name + ", " +... | def sec_project_activity(self, project=None) | Generate the data for the Activity section in the report
:return: | 4.716282 | 4.781875 | 0.986283 |
def create_csv(metric1, csv_labels, file_label):
esfilters = None
csv_labels = csv_labels.replace("_", "") # LaTeX not supports "_"
if project != self.GLOBAL_PROJECT:
esfilters = {"project": project}
data_path = os.path.join(self.data_d... | def sec_project_community(self, project=None) | Generate the data for the Communication section in a Project report
:return: | 4.177626 | 4.246261 | 0.983836 |
logger.info("Process data for: %s", project)
for i in range(0, len(self.config['project_process']['bmi_metrics'])):
metric = self.config['project_process']['bmi_metrics'][i]
csv_labels = "labels" + "," + metric.id
file_label = metric.ds.name + "_" ... | def sec_project_process(self, project=None) | Generate the data for the Process section in a Project report
:return: | 2.057061 | 2.061569 | 0.997814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.