code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = PermissionsForm()
users = []
uids = db.hgetall('users').values()
if request.method == 'POST':
if not... | def acp_users_permissions() | Change user permissions. | 3.503048 | 3.485156 | 1.005134 |
if path is not None:
file_ = open(path, 'rb')
elif file_ is not None:
assert hasattr(file_, 'read')
elif url is not None:
file_ = urllib2.urlopen(url)
if mime_type is None:
mime_type = file_.headers.gettype()
elif data is not None:
file_ = cString... | def openXmlDocument(path=None, file_=None, data=None, url=None, mime_type=None) | **Factory function**
Will guess what document type is best suited and return the appropriate
document type.
User must provide either ``path``, ``file_``, ``data`` or ``url`` parameter.
:param path: file path in the local filesystem to a document.
:param file_: a file (like) object to a document (m... | 2.529589 | 2.512631 | 1.006749 |
# type: () -> bool
try:
# noinspection PyUnresolvedReferences
from ccurl import Curl as CCurl
except ImportError:
return False
else:
# noinspection PyUnresolvedReferences
from iota.crypto import Curl
return issubclass(Curl, CCurl) | def is_installed() | Returns whether the C extension is installed correctly. | 4.942787 | 5.272713 | 0.937428 |
"Map a key name to a specific comparison function"
if '__' not in key:
# If no __ exists, default to doing an "exact" comparison
key, comp = key, 'exact'
else:
key, comp = key.rsplit('__', 1)
# Check if comp is valid
if hasattr(Compare, comp):
return getattr(Compare, ... | def make_compare(key, value, obj) | Map a key name to a specific comparison function | 5.158957 | 4.279711 | 1.205445 |
if not hasattr(self, '_array'): self._array = self.load_data()
return self._array | def array(self) | Data as a [`numpy.ndarray`][1] in the form
#!python
[
[ x1, x2, x3, ... ],
[ y1, y2, y3, ...]
]
By default, if unset, this will be set on first access
by calling `scipy_data_fitting.Data.load_data`.
When loaded from file, the... | 5.381318 | 5.601595 | 0.960676 |
if not hasattr(self, '_error'):
if any(v is not None for v in self.error_columns):
self._error = self.load_error()
else:
return (None, None)
return self._error | def error(self) | Error associated with the data as a two element tuple of the form `(x_error, y_error)`.
Both `x_error` and `y_error` is a [`numpy.ndarray`][1] or `None`.
The array dimensions depend on how the error is specified:
1. Symmetric constant error is a zero dimensional array: `error`.
2. Asy... | 4.657493 | 3.838646 | 1.213316 |
if not hasattr(self, '_genfromtxt_args_error'):
self._genfromtxt_args_error = self.genfromtxt_args.copy()
return self._genfromtxt_args_error | def genfromtxt_args_error(self) | Passed as keyword arguments to [`numpy.genfromtxt`][1]
when called by `scipy_data_fitting.Data.load_error`.
Even if defined here, the `usecols` value will always be reset based
on `scipy_data_fitting.Data.error_columns` before being passed to [`numpy.genfromtxt`][1].
If not set, this d... | 2.216235 | 2.142444 | 1.034443 |
array = numpy.genfromtxt(self.path, **self.genfromtxt_args)
for n, scale in enumerate(self.scale): array[n,:] *= self.scale[n]
return array | def load_data(self) | Loads data from `scipy_data_fitting.Data.path` using [`numpy.genfromtxt`][1]
and returns a [`numpy.ndarray`][2].
Data is scaled according to `scipy_data_fitting.Data.scale`.
Arguments to [`numpy.genfromtxt`][1] are controlled
by `scipy_data_fitting.Data.genfromtxt_args`.
[1]: ... | 7.031844 | 3.603837 | 1.95121 |
usecols = []
for v in self.error_columns:
if v is None:
pass
elif isinstance(v, int):
usecols.append(v)
elif len(v) is 2:
for n in v: usecols.append(n)
self.genfromtxt_args_error['usecols'] = tuple(useco... | def load_error(self) | Loads error values from `scipy_data_fitting.Data.path` using [`numpy.genfromtxt`][1]
and returns a two element tuple where each element is of a form described by
cases 3 and 4 in `scipy_data_fitting.Data.error`.
The columns to import are set by `scipy_data_fitting.Data.error_columns`.
... | 2.768739 | 2.279811 | 1.21446 |
self.path.extend(args)
self.qs.update(kwargs)
return self | def mock_attr(self, *args, **kwargs) | Empty method to call to slurp up args and kwargs.
`args` get pushed onto the url path.
`kwargs` are converted to a query string and appended to the URL. | 8.062308 | 5.069612 | 1.590321 |
for i in my_xrange(self._column_query_pos, self.pos):
if self.text[i] == '\t':
self._column += self.tab_size
self._column -= self._column % self.tab_size
else:
self._column += 1
self._column_query_pos = self.pos
ret... | def column(self) | Returns the zero based column number based on the
current position of the parser. | 4.090277 | 3.477208 | 1.176311 |
pos = self.pos + offset
if pos >= self.end:
return None
return self.text[pos] | def peek(self, offset=0) | Looking forward in the input text without actually stepping the current position.
returns None if the current position is at the end of the input. | 4.096869 | 2.981929 | 1.373899 |
if self.peek() != c:
self.error('Expected "%c"' % (c,))
self.skip_char() | def expect(self, c) | If the current position doesn't hold the specified c character then it raises an
exception, otherwise it skips the specified character (moves the current position forward). | 5.708813 | 4.626812 | 1.233854 |
listener.begin_parsing(self)
try:
self.init_text_parser(json_text)
self.listener = listener
c = self._skip_spaces_and_peek()
if c == '{':
if self.params.root_is_array:
self.error('The root of the json is expect... | def parse(self, json_text, listener) | Parses the specified json_text and emits parser events to the listener.
If root_is_array then the root element of the json has to be an array/list,
otherwise the expected root is a json object/dict.
In case of python2 the json_text can be either an utf8 encoded string
or a unicode objec... | 3.397694 | 3.115746 | 1.090491 |
while 1:
# skipping spaces
self.skip_chars(self.end, lambda x: x in self.spaces)
c = self.peek()
if not self.params.allow_comments:
return c
if c != '/':
return c
d = self.peek(1)
if d ==... | def _skip_spaces_and_peek(self) | Skips all spaces and comments.
:return: The first character that follows the skipped spaces and comments or
None if the end of the json string has been reached. | 3.354151 | 3.544789 | 0.94622 |
begin = self.pos
for end in my_xrange(self.pos, self.end):
if self.text[end] in self.spaces_and_special_chars:
break
else:
end = self.end
if begin == end:
self.error('Expected a scalar here.')
return self.text[begin:end... | def _parse_and_return_unquoted_string(self) | Parses a string that has no quotation marks so it doesn't
contain any special characters and we don't have to interpret
any escape sequences.
:return: (string, quoted=False, end_of_string_pos) | 5.412873 | 4.815223 | 1.124117 |
result = []
pos = self.pos + 1
segment_begin = pos
my_chr = my_unichr if isinstance(self.text, my_unicode) else utf8chr
while pos < self.end:
c = self.text[pos]
if c < ' ' and c != '\t':
self.skip_to(pos)
self.error... | def _parse_and_return_quoted_string(self) | Parses a string that has quotation marks so it may contain
special characters and escape sequences.
:return: (unescaped_string, quoted=True, end_of_string_pos) | 2.839511 | 2.740065 | 1.036293 |
if default:
default_q = ' [{0}]'.format(default)
else:
default_q = ''
if sys.version_info[0] == 3:
inp = input("{query}{default_q}: ".format(
query=query, default_q=default_q)).strip()
else:
inp = raw_input("{query}{default_q}: ".format(
query... | def ask(query, default=None) | Ask a question. | 2.030342 | 2.028899 | 1.000712 |
if default is None:
default_q = ' [y/n]'
elif default is True:
default_q = ' [Y/n]'
elif default is False:
default_q = ' [y/N]'
if sys.version_info[0] == 3:
inp = raw_input("{query}{default_q} ".format(
query=query, default_q=default_q)).strip()
else:... | def ask_yesno(query, default=None) | Ask a yes/no question. | 2.063298 | 2.051735 | 1.005635 |
rev = int(self.db.get('site:rev'))
if rev != self.revision and self.db.exists('site:rev'):
timeline = self.db.lrange('site:timeline', 0, -1)
self._timeline = []
for data in timeline:
data = json.loads(data.decode('utf-8'))
self... | def reload_site(self) | Reload the site from the database. | 3.779626 | 3.709453 | 1.018917 |
setattr(self, '_' + name, [self._timeline[int(i)] for i in
self.db.lrange('site:{0}'.format(name), 0,
-1)]) | def _read_indexlist(self, name) | Read a list of indexes. | 9.612585 | 8.787317 | 1.093916 |
d = [self._site.timeline.index(p) for p in getattr(self._site, name)]
self.db.delete('site:{0}'.format(name))
if d:
self.db.rpush('site:{0}'.format(name), *d) | def _write_indexlist(self, name) | Write a list of indexes. | 5.1212 | 4.947505 | 1.035108 |
while (self.db.exists('site:lock') and
int(self.db.get('site:lock')) != 0):
self.logger.info("Waiting for DB lock...")
time.sleep(0.5)
self.db.incr('site:lock')
self.logger.info("Lock acquired.")
self.logger.info("Scanning site...")
... | def scan_posts(self, really=True, ignore_quit=False, quiet=True) | Rescan the site. | 3.647538 | 3.550115 | 1.027442 |
rev = int(self.db.get('site:rev'))
if rev != self.revision:
self.reload_site()
return self._timeline | def timeline(self) | Get timeline, reloading the site if needed. | 12.320647 | 6.926638 | 1.778734 |
rev = int(self.db.get('site:rev'))
if rev != self.revision:
self.reload_site()
return self._posts | def posts(self) | Get posts, reloading the site if needed. | 10.896027 | 6.752952 | 1.613521 |
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._all_posts | def all_posts(self) | Get all_posts, reloading the site if needed. | 10.220495 | 6.254524 | 1.634096 |
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._pages | def pages(self) | Get pages, reloading the site if needed. | 10.589274 | 6.748424 | 1.569148 |
parser = JSONParser(parser_params)
listener = ObjectBuilderParserListener(object_builder_params)
parser.parse(s, listener)
return listener.result | def loads(s,
parser_params=JSONParserParams(),
object_builder_params=PythonObjectBuilderParams()) | Loads a json string as a python object hierarchy just like the standard json.loads(). Unlike
the standard json.loads() this function uses OrderedDict instances to represent json objects
but the class of the dictionary to be used is configurable.
:param s: The json string to load.
:params parser_params: ... | 3.566454 | 3.18823 | 1.118631 |
parser = JSONParser(parser_params)
object_builder_params = ConfigObjectBuilderParams(string_to_scalar_converter=string_to_scalar_converter)
listener = ObjectBuilderParserListener(object_builder_params)
parser.parse(s, listener)
return listener.result | def loads_config(s,
parser_params=JSONParserParams(),
string_to_scalar_converter=DefaultStringToScalarConverter()) | Works similar to the loads() function but this one returns a json object hierarchy
that wraps all json objects, arrays and scalars to provide a nice config query syntax.
For example:
my_config = loads_config(json_string)
ip_address = my_config.servers.reverse_proxy.ip_address()
port = my_config.serv... | 3.677586 | 4.994444 | 0.736335 |
json_str = load_utf_text_file(
file_,
default_encoding=kwargs.pop('default_encoding', 'UTF-8'),
use_utf8_strings=kwargs.pop('use_utf8_strings', True),
)
return loads(json_str, *args, **kwargs) | def load(file_, *args, **kwargs) | Does exactly the same as loads() but instead of a json string this function
receives the path to a file containing the json string or a file like object with a read()
method.
:param file_: Filename or a file like object with read() method.
:param default_encoding: The encoding to be used if the file doe... | 3.441916 | 3.216647 | 1.070032 |
json_str = load_utf_text_file(
file_,
default_encoding=kwargs.pop('default_encoding', 'UTF-8'),
use_utf8_strings=kwargs.pop('use_utf8_strings', True),
)
return loads_config(json_str, *args, **kwargs) | def load_config(file_, *args, **kwargs) | Does exactly the same as loads_config() but instead of a json string this function
receives the path to a file containing the json string or a file like object with a read()
method.
:param file_: Filename or a file like object with read() method.
:param default_encoding: The encoding to be used if the f... | 3.760474 | 3.210399 | 1.171342 |
if not hasattr(self, '_options'):
self._options = {
'fit_function': scipy.optimize.curve_fit,
'maxfev': 1000,
}
return self._options | def options(self) | Dictionary of options which affect the curve fitting algorithm.
Must contain the key `fit_function` which must be set to
the function that will perform the fit.
All other options are passed as keyword arguments to the `fit_function`.
The default options use `scipy.optimize.curve_fit`.... | 3.673865 | 2.68686 | 1.367345 |
if not hasattr(self, '_limits'):
xmax = max(abs(self.data.array[0]))
xmin = min(self.data.array[0])
x_error = self.data.error[0]
if isinstance(x_error, numpy.ndarray):
if x_error.ndim == 0: xmax = xmax + x_error
if xmin < 0:
... | def limits(self) | Limits to use for the independent variable whenever
creating a linespace, plot, etc.
Defaults to `(-x, x)` where `x` is the largest absolute value
of the data corresponding to the independent variable.
If no such values are negative, defaults to `(0, x)` instead. | 3.581002 | 3.172712 | 1.128688 |
variables = []
variables.extend(self.free_variables)
variables.append(self.independent['symbol'])
variables.extend([ param['symbol'] for param in self.fitting_parameters ])
variables.extend([ param['symbol'] for param in self.fixed_parameters ])
variables.extend(... | def all_variables(self) | A flat tuple of all symbols taken in order from the following:
1. `scipy_data_fitting.Fit.free_variables`
2. `scipy_data_fitting.Fit.independent`
3. `scipy_data_fitting.Fit.fitting_parameters`
4. `scipy_data_fitting.Fit.fixed_parameters`
5. `scipy_data_fitting.Fit.constants` | 3.00719 | 2.093266 | 1.436602 |
values = []
values.extend([ prefix_factor(param) * param['value'] for param in self.fixed_parameters ])
values.extend([ prefix_factor(const) * get_constant(const['value']) for const in self.constants ])
return tuple(values) | def fixed_values(self) | A flat tuple of all values corresponding to `scipy_data_fitting.Fit.fixed_parameters`
and `scipy_data_fitting.Fit.constants` after applying any prefixes.
The values mimic the order of those lists. | 6.370225 | 4.093456 | 1.556197 |
if not hasattr(self,'_function'):
function = self.model.lambdify(self.expression, self.all_variables, **self.lambdify_options)
self._function = lambda *x: function(*(x + self.fixed_values))
return self._function | def function(self) | The function passed to the `fit_function` specified in `scipy_data_fitting.Fit.options`,
and used by `scipy_data_fitting.Fit.pointspace` to generate plots, etc.
Its number of arguments and their order is determined by items 1, 2, and 3
as listed in `scipy_data_fitting.Fit.all_variables`.
... | 4.87152 | 3.6434 | 1.337081 |
p0 = []
for param in self.fitting_parameters:
opts = param['lmfit'].copy() if 'lmfit' in param else {}
if 'min' in opts: opts['min'] = prefix_factor(param) * opts['min']
if 'max' in opts: opts['max'] = prefix_factor(param) * opts['max']
p0.append(... | def lmfit_parameters(self) | A [`lmfit.Parameters`][1] object built from `scipy_data_fitting.Fit.fitting_parameters`,
see `scipy_data_fitting.Fit.parameters`.
Each parameters is assigned a key of the form `p_00000`, `p_00001`, `p_00002`, etc.
Thus, `sorted(self.lmfit_parameters)` will give the keys in the same
orde... | 3.600482 | 3.118124 | 1.154695 |
return lambda params, x, data, error: self.function(x, *self.lmfit_parameter_values(params)) - data | def lmfit_fcn2min(self) | The function to minimize when using [lmfit][1].
If overriding this, the replacement function must accept the following
non-keyword arguments in this order (even if unused):
1. A [`lmfit.Parameters`][2] object.
The value of each parameter must be passed appropriately to `scipy_data_f... | 9.567209 | 2.502372 | 3.823256 |
if not hasattr(self,'_curve_fit'):
options = self.options.copy()
fit_function = options.pop('fit_function')
independent_values = self.data.array[0]
dependent_values = self.data.array[1]
if fit_function == 'lmfit':
self._curve_... | def curve_fit(self) | Fits `scipy_data_fitting.Fit.function` to the data and returns
the output from the specified curve fit function.
See `scipy_data_fitting.Fit.options` for details on how to control
or override the the curve fitting algorithm. | 3.66905 | 3.647148 | 1.006005 |
if hasattr(self,'_fitted_parameters'): return self._fitted_parameters
if not self.fitting_parameters: return tuple()
if self.options['fit_function'] == 'lmfit':
return tuple( self.curve_fit.params[key].value for key in sorted(self.curve_fit.params) )
else:
... | def fitted_parameters(self) | A tuple of fitted values for the `scipy_data_fitting.Fit.fitting_parameters`.
The values in this tuple are not scaled by the prefix,
as they are passed back to `scipy_data_fitting.Fit.function`,
e.g. in most standard use cases these would be the SI values.
If no fitting parameters were... | 3.947461 | 3.570907 | 1.105451 |
function = self.function
fitted_parameters = self.fitted_parameters
return lambda x: function(x, *fitted_parameters) | def fitted_function(self) | A function of the single independent variable after
partially evaluating `scipy_data_fitting.Fit.function` at
the `scipy_data_fitting.Fit.fitted_parameters`. | 4.059777 | 3.440492 | 1.179999 |
quantity = quantity.copy()
expression = self.model.replace(quantity.pop('expression'), self.replacements)
variables = self.all_variables[len(self.free_variables) + 1:]
function = self.model.lambdify(expression, variables, **self.lambdify_options)
quantity['value'] = func... | def compute_quantity(self, quantity) | Processes a single quantity as described and used
in `scipy_data_fitting.Fit.computed_quantities`. | 7.60181 | 7.333424 | 1.036598 |
fitted_parameters = []
for (i, v) in enumerate(self.fitting_parameters):
param = v.copy()
param['value'] = self.fitted_parameters[i] * prefix_factor(param)**(-1)
fitted_parameters.append(param)
return fitted_parameters | def computed_fitting_parameters(self) | A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`,
but in each dictionary, the key `value` is added with the fitted value of the quantity.
The reported value is scaled by the inverse prefix. | 4.970454 | 3.595963 | 1.382232 |
return {
'name': self.name,
'description': self.description,
'independent': self.independent,
'dependent': self.dependent,
'quantities': self.computed_quantities,
'fixed_parameters': self.fixed_parameters,
'fitted_parameters': self.c... | def metadata(self) | A dictionary which summarizes the results of the fit:
#!python
{
'name': self.name,
'description': self.description,
'independent': self.independent,
'dependent': self.dependent,
'quantities': self.computed_quantiti... | 4.140913 | 1.428339 | 2.89911 |
scale_array = numpy.array([
[prefix_factor(self.independent)**(-1)],
[prefix_factor(self.dependent)**(-1)]
])
linspace = numpy.linspace(self.limits[0], self.limits[1], **kwargs)
return {
'data': self.data.array * scale_array,
'fit': n... | def pointspace(self, **kwargs) | Returns a dictionary with the keys `data` and `fit`.
`data` is just `scipy_data_fitting.Data.array`.
`fit` is a two row [`numpy.ndarray`][1], the first row values correspond
to the independent variable and are generated using [`numpy.linspace`][2].
The second row are the values of `sci... | 6.476193 | 4.161074 | 1.556376 |
pointspace = self.pointspace(num=points)
fit_points = numpy.dstack(pointspace['fit'])[0]
data_points = numpy.dstack(pointspace['data'])[0]
fit = [ [ point[0], point[1] ] for point in fit_points ]
data = [ [ point[0], point[1] ] for point in data_points ]
obj ... | def to_json(self, path, points=50, meta=None) | Write the results of the fit to a json file at `path`.
`points` will define the length of the `fit` array.
If `meta` is given, a `meta` key be added with the given value.
The json object has the form
#!text
{
'data': [ [x1, y1], [x2, y2], ... ],
... | 2.811602 | 2.825565 | 0.995058 |
return tuple( params[key].value for key in sorted(params) ) | def lmfit_parameter_values(self, params) | `params` is a [`lmfit.Parameters`][1] object.
Returns a tuple containing the values of the parameters in `params`.
The order is determined by sorting the parameter keys alphabetically.
[1]: http://lmfit.github.io/lmfit-py/parameters.html#the-parameters-class | 10.060405 | 9.482064 | 1.060993 |
new_cells = []
for cell in nb.worksheets[0].cells:
# Remove the pylab inline line.
if "input" in cell and cell["input"].strip() == "%pylab inline":
continue
# Remove output resulting from the stream/trace method chaining.
if "outputs" in cell:
outputs... | def clean_for_doc(nb) | Cleans the notebook to be suitable for inclusion in the docs. | 4.791188 | 4.591712 | 1.043443 |
for cell in nb.worksheets[0].cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | def strip_output(nb) | strip the outputs from a notebook object | 2.104686 | 1.905613 | 1.104467 |
self.timer.add_callback(func)
self.timer.start() | def set_call_back(self, func) | sets callback function for updating the plot.
in the callback function implement the logic of reading of serial input
also the further processing of the signal if necessary has to be done
in this
callbak function. | 6.592471 | 5.770927 | 1.142359 |
def func_wrapper():
func()
try:
self.manager.canvas.draw()
except ValueError as ve:
print(ve)
pass
except RuntimeError as RtE:
print(RtE)
pass
except Excep... | def plot_self(self, func) | define your callback function with the decorator @plotter.plot_self.
in the callback function set the data of lines
in the plot using self.lines[i][j].set_data(your data) | 4.43889 | 4.126735 | 1.075642 |
if not hasattr(cls, '_cache'):
cls._cache = cls._all()
return cls._cache | def all(cls) | Wrapper around _all() to cache and return all results of something
>>> ec2.instances.all()
[ ... ] | 4.179591 | 5.386119 | 0.775993 |
things = cls.filter(**kwargs)
if len(things) > 1:
# Raise an exception if more than one object is matched
raise cls.MultipleObjectsReturned
elif len(things) == 0:
# Rase an exception if no objects were matched
raise cls.DoesNotExist
... | def get(cls, **kwargs) | Generic get() for one item only
>>> ec2.instances.get(name='production-web-01')
<Instance: ...> | 3.568073 | 4.251877 | 0.839176 |
qs = cls.all()
for key in kwargs:
qs = filter(lambda i: make_compare(key, kwargs[key], i), qs)
return qs | def filter(cls, **kwargs) | The meat. Filtering using Django model style syntax.
All kwargs are translated into attributes on the underlying objects.
If the attribute is not found, it looks for a similar key
in the tags.
There are a couple comparisons to check against as well:
exact: check strict equa... | 6.406511 | 8.759947 | 0.731341 |
'''Reconnect to redis.
:return: Redis client instance
:rettype: redis.Redis
'''
if self.shared_client and Storage.storage:
return Storage.storage
storage = Redis(
port=self.context.config.REDIS_RESULT_STORAGE_SERVER_PORT,
host=self.c... | def reconnect_redis(self) | Reconnect to redis.
:return: Redis client instance
:rettype: redis.Redis | 3.517193 | 2.911028 | 1.208231 |
'''Return a key for the current request url.
:return: The storage key for the current url
:rettype: string
'''
path = "result:%s" % self.context.request.url
if self.is_auto_webp():
path += '/webp'
return path | def get_key_from_request(self) | Return a key for the current request url.
:return: The storage key for the current url
:rettype: string | 11.827308 | 5.691858 | 2.077934 |
'''Return the TTL of the current request.
:returns: The TTL value for the current request.
:rtype: int
'''
default_ttl = self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS
if self.context.request.max_age == 0:
return self.context.request.max_age
... | def get_max_age(self) | Return the TTL of the current request.
:returns: The TTL value for the current request.
:rtype: int | 5.790079 | 4.09276 | 1.414713 |
'''Save to redis
:param bytes: Bytes to write to the storage.
:return: Redis key for the current url
:rettype: string
'''
key = self.get_key_from_request()
result_ttl = self.get_max_age()
logger.debug(
"[REDIS_RESULT_STORAGE] putting `{key}`... | def put(self, bytes) | Save to redis
:param bytes: Bytes to write to the storage.
:return: Redis key for the current url
:rettype: string | 4.713166 | 2.961911 | 1.591258 |
'''Get the item from redis.'''
key = self.get_key_from_request()
result = self.get_storage().get(key)
return result if result else None | def get(self) | Get the item from redis. | 7.72146 | 6.143857 | 1.256777 |
'''Return the last_updated time of the current request item
:return: A DateTime object
:rettype: datetetime.datetime
'''
key = self.get_key_from_request()
max_age = self.get_max_age()
if max_age == 0:
return datetime.fromtimestamp(Storage.start_time... | def last_updated(self) | Return the last_updated time of the current request item
:return: A DateTime object
:rettype: datetetime.datetime | 5.962811 | 4.253479 | 1.401867 |
d = {}
for key, val in l:
d.setdefault(key, []).append(val)
return d | def list_of_lists_to_dict(l) | Convert list of key,value lists to dict
[['id', 1], ['id', 2], ['id', 3], ['foo': 4]]
{'id': [1, 2, 3], 'foo': [4]} | 2.782417 | 2.788777 | 0.997719 |
params = {}
''' m2m_request:
{u'company[]': [u'["id", 1]'],
u'professions[]': [u'["id", 2]', u'["id", 3]']}
'''
m2m_request = {k: v for k, v in list(request.items()) if k.endswith('[]')}
for k, v in list(m2m_request.items()):
key = k[:-2]
relation = getattr(obj... | def get_m2m_value(session, request, obj) | Set m2m value for model obj from request params like "group[]"
:Parameters:
- `session`: SQLAlchemy DBSession
- `request`: request as dict
- `obj`: model instance | 3.300804 | 3.471114 | 0.950935 |
if not isinstance(number, integer_types):
raise TypeError('number must be an integer')
if number < 0:
return '-' + dumps(-number)
value = ''
while number != 0:
number, index = divmod(number, len(alphabet))
value = alphabet[index] + value
return value or '0' | def dumps(number) | Dumps an integer into a base36 string.
:param number: the 10-based integer.
:returns: the base36 string. | 2.489009 | 2.505924 | 0.99325 |
async def _acl_middleware_factory(app, handler):
async def _middleware_handler(request):
# Save the policy in the request
request[GROUPS_KEY] = callback
# Call the next handler in the chain
return await handler(request)
return _middleware_handl... | def acl_middleware(callback) | Returns a aiohttp_auth.acl middleware factory for use by the aiohttp
application object.
Args:
callback: This is a callable which takes a user_id (as returned from
the auth.get_auth function), and expects a sequence of permitted ACL
groups to be returned. This can be a empty tup... | 4.79646 | 5.048565 | 0.950064 |
acl_callback = request.get(GROUPS_KEY)
if acl_callback is None:
raise RuntimeError('acl_middleware not installed')
user_id = await get_auth(request)
groups = await acl_callback(user_id)
if groups is None:
return None
user_groups = (Group.AuthenticatedUser, user_id) if user... | async def get_user_groups(request) | Returns the groups that the user in this request has access to.
This function gets the user id from the auth.get_auth function, and passes
it to the ACL callback function to get the groups.
Args:
request: aiohttp Request object
Returns:
If the ACL callback function returns None, this ... | 5.254612 | 3.529382 | 1.488819 |
groups = await get_user_groups(request)
if groups is None:
return False
for action, group, permissions in context:
if group in groups:
if permission in permissions:
return action == Permission.Allow
return False | async def get_permitted(request, permission, context) | Returns true if the one of the groups in the request has the requested
permission.
The function takes a request, a permission to check for and a context. A
context is a sequence of ACL tuples which consist of a Allow/Deny action,
a group, and a sequence of permissions for that ACL group. For example::
... | 5.947579 | 3.419304 | 1.739412 |
output = []
for item in input_list:
if item not in output:
output.append(item)
return output | def unique(input_list) | Return a list of unique items (similar to set functionality).
Parameters
----------
input_list : list
A list containg some items that can occur more than once.
Returns
-------
list
A list with only unique occurances of an item. | 2.015963 | 3.124814 | 0.645146 |
return (np.array([atomic_mass[i.upper()] for i in elements]).sum()) | def molecular_weight(elements) | Return molecular weight of a molecule.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
Returns
-------
numpy.float64
A molecular weight of a molecule. | 7.039754 | 14.395792 | 0.489015 |
mass = molecular_weight(elements)
mass_array = np.array([[atomic_mass[i.upper()]] * 3 for i in elements])
mass_coordinates = coordinates * mass_array
return (np.sum(mass_coordinates, axis=0) / np.array([mass, mass, mass])) | def center_of_mass(elements, coordinates) | Return the centre of mass (COM).
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
Returns
-------
numpy.ndarray
An 1d array with coordinates of... | 4.032262 | 4.753267 | 0.848314 |
if len(args) == 2:
atom_list = [[
i[0],
round(float(i[1]), 8),
round(float(i[2]), 8),
round(float(i[3]), 8),
] for i in np.concatenate(
(args[0].reshape(-1, 1), args[1]), axis=1)]
elif len(args) == 3:
atom_list = [
... | def compose_atom_list(*args) | Return an `atom list` from elements and/or atom ids and coordinates.
An `atom list` is a special object that some pywindowfunctions uses.
It is a nested list of lists with each individual list containing:
1. [[element, coordinates (x, y, z)], ...]
2. [[element, atom key, coordinates (x, y, z)... | 2.055309 | 1.921501 | 1.069637 |
transpose = list(zip(*atom_list))
if len(transpose) == 4:
elements = np.array(transpose[0])
array_a = np.array(transpose[1]).reshape(-1, 1)
array_b = np.array(transpose[2]).reshape(-1, 1)
array_c = np.array(transpose[3]).reshape(-1, 1)
array_ab = np.concatenate((arra... | def decompose_atom_list(atom_list) | Return elements and/or atom ids and coordinates from an `atom list`.
Depending on input type of an atom list (version 1 or 2)
1. [[element, coordinates (x, y, z)], ...]
2. [[element, atom key, coordinates (x, y, z)], ...]
the function reverses what pywindow.utilities.compose_atom_list() do.
... | 1.833637 | 1.839981 | 0.996552 |
split = list(atom_key)
element = ''
number = False
count = 0
while number is False:
element = "".join((element, split[count]))
count += 1
if is_number(split[count]) is True:
number = True
# In case of for example Material Studio output, integers can also ... | def dlf_notation(atom_key) | Return element for atom key using DL_F notation. | 10.079147 | 9.0164 | 1.117868 |
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
"For how to solve this issue see the manual or "
"MolecularSyst... | def opls_notation(atom_key) | Return element for OPLS forcefield atom key. | 6.53443 | 6.131941 | 1.065638 |
load_funcs = {
'DLF': dlf_notation,
'DL_F': dlf_notation,
'OPLS': opls_notation,
'OPLSAA': opls_notation,
'OPLS2005': opls_notation,
'OPLS3': opls_notation,
}
if forcefield.upper() in load_funcs.keys():
return load_funcs[forcefield.upper()](atom_k... | def decipher_atom_key(atom_key, forcefield) | Return element for deciphered atom key.
This functions checks if the forcfield specified by user is supported
and passes the atom key to the appropriate function for deciphering.
Parameters
----------
atom_key : str
The atom key which is to be deciphered.
forcefield : str
The ... | 4.621008 | 4.748203 | 0.973212 |
com = center_of_mass(elements, coordinates)
com = np.array([com - com_adjust] * coordinates.shape[0])
return coordinates - com | def shift_com(elements, coordinates, com_adjust=np.zeros(3)) | Return coordinates translated by some vector.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
com_adjust : numpy.ndarray (default = [0, 0, 0])
Returns
... | 3.702427 | 6.006846 | 0.616368 |
atom_vdw_vertical = np.matrix(
[[atomic_vdw_radius[i.upper()]] for i in elements])
atom_vdw_horizontal = np.matrix(
[atomic_vdw_radius[i.upper()] for i in elements])
dist_matrix = euclidean_distances(coordinates, coordinates)
vdw_matrix = atom_vdw_vertical + atom_vdw_horizontal
... | def max_dim(elements, coordinates) | Return the maximum diameter of a molecule.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
Returns
------- | 3.019057 | 3.122333 | 0.966923 |
if com is None:
com = center_of_mass(elements, coordinates)
atom_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
dist_matrix = euclidean_distances(coordinates, com.reshape(1, -1))
re_dist_matrix = dist_matrix - atom_vdw
index = np.argmin(re_dist_matrix)
pored = re... | def pore_diameter(elements, coordinates, com=None) | Return pore diameter of a molecule. | 3.592694 | 3.439841 | 1.044436 |
elements, coordinates = params
return (-pore_diameter(elements, coordinates, com)[0]) | def correct_pore_diameter(com, *params) | Return negative of a pore diameter. (optimisation function). | 20.919163 | 13.717692 | 1.524977 |
args = elements, coordinates
if com is not None:
pass
else:
com = center_of_mass(elements, coordinates)
if bounds is None:
pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2
bounds = (
(com[0]-pore_r, com[0]+pore_r),
(com[1]-pore_r,... | def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs) | Return optimised pore diameter and it's COM. | 2.378059 | 2.269156 | 1.047993 |
# First calculate COM for correction.
com = centre_of_mass(elements, coordinates)
# Correct the coordinates for the COM.
coordinates = coordinates - com
# Calculate diagonal and then other values of the matrix.
diag = np.sum(coordinates**2, axis=0)
xy = np.sum(coordinates[:, 0] * coordi... | def get_gyration_tensor(elements, coordinates) | Return the gyration tensor of a molecule.
The gyration tensor should be invariant to the molecule's position.
The known formulas for the gyration tensor have the correction for the
centre of mass of the molecule, therefore, the coordinates are first
corrected for the centre of mass and essentially shif... | 2.944653 | 2.73561 | 1.076416 |
pow2 = coordinates**2
molecular_weight = np.array(
[[atomic_mass[e.upper()]] for e in elements])
diag_1 = np.sum(molecular_weight * (pow2[:, 1] + pow2[:, 2]))
diag_2 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 2]))
diag_3 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 1]))
... | def get_inertia_tensor(elements, coordinates) | Return the tensor of inertia a molecule.
Parameters
----------
elements : numpy.ndarray
The array containing the molecule's elemental data.
coordinates : numpy.ndarray
The array containing the Cartesian coordinates of the molecule.
Returns
-------
numpy.ndarray
Th... | 2.056049 | 2.175195 | 0.945225 |
v = np.divide(vector, np.linalg.norm(vector))
return np.round(v, decimals=4) | def normalize_vector(vector) | Normalize a vector.
A new vector is returned, the original vector is not modified.
Parameters
----------
vector : np.array
The vector to be normalized.
Returns
-------
np.array
The normalized vector. | 3.569183 | 4.937957 | 0.722806 |
axis = normalize_vector(axis)
a = np.cos(angle / 2)
b, c, d = axis * np.sin(angle / 2)
e11 = np.square(a) + np.square(b) - np.square(c) - np.square(d)
e12 = 2 * (b * c - a * d)
e13 = 2 * (b * d + a * c)
e21 = 2 * (b * c + a * d)
e22 = np.square(a) + np.square(c) - np.square(b) - ... | def rotation_matrix_arbitrary_axis(angle, axis) | Return a rotation matrix of `angle` radians about `axis`.
Parameters
----------
angle : int or float
The size of the rotation in radians.
axis : numpy.array
A 3 element aray which represents a vector. The vector is the
axis about which the rotation is carried out.
Returns
... | 1.266095 | 1.377502 | 0.919124 |
a_, b_, c_, alpha, beta, gamma = cryst
# Convert angles from degrees to radians.
r_alpha = np.deg2rad(alpha)
r_beta = np.deg2rad(beta)
r_gamma = np.deg2rad(gamma)
# Calculate unit cell volume that is neccessary.
volume = a_ * b_ * c_ * (
1 - np.cos(r_alpha)**2 - np.cos(r_beta)**... | def unit_cell_to_lattice_array(cryst) | Return parallelpiped unit cell lattice matrix. | 1.930017 | 1.875504 | 1.029066 |
cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0))
gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1])
beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2])
alpha_r = np.arccos(
lattice_array[1][2] * np.sin(gamma_r) / cell_lengths[2]
+ np.cos(beta_r) * np.cos(gamma_... | def lattice_array_to_unit_cell(lattice_array) | Return crystallographic param. from unit cell lattice matrix. | 1.935904 | 1.897689 | 1.020138 |
deorthogonalisation_M = np.matrix(np.linalg.inv(lattice_array))
fractional = deorthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(fractional.reshape(1, -1)) | def fractional_from_cartesian(coordinate, lattice_array) | Return a fractional coordinate from a cartesian one. | 4.187594 | 3.92104 | 1.06798 |
orthogonalisation_M = np.matrix(lattice_array)
orthogonal = orthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(orthogonal.reshape(1, -1)) | def cartisian_from_fractional(coordinate, lattice_array) | Return cartesian coordinate from a fractional one. | 4.65563 | 4.535588 | 1.026467 |
frac_coordinates = deepcopy(coordinates)
for coord in range(frac_coordinates.shape[0]):
frac_coordinates[coord] = fractional_from_cartesian(
frac_coordinates[coord], lattice_array)
return frac_coordinates | def cart2frac_all(coordinates, lattice_array) | Convert all cartesian coordinates to fractional. | 2.707821 | 2.562112 | 1.056871 |
coordinates = deepcopy(frac_coordinates)
for coord in range(coordinates.shape[0]):
coordinates[coord] = cartisian_from_fractional(coordinates[coord],
lattice_array)
return coordinates | def frac2cart_all(frac_coordinates, lattice_array) | Convert all fractional coordinates to cartesian. | 3.942191 | 3.651528 | 1.0796 |
if 'lattice' not in system.keys():
matrix = unit_cell_to_lattice_array(system['unit_cell'])
else:
matrix = system['lattice']
coordinates = deepcopy(system['coordinates'])
multiplication_matrices = []
for a_ in range(supercell[0][0], supercell[0][1] + 1):
for b_ in range(... | def create_supercell(system, supercell=[[-1, 1], [-1, 1], [-1, 1]]) | Create a supercell. | 2.360439 | 2.366441 | 0.997464 |
first_step = abs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]) / (
np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) *
np.sqrt(y[0]**2 + y[1]**2 + y[2]**2))
second_step = np.arccos(first_step)
return (second_step) | def angle_between_vectors(x, y) | Calculate the angle between two vectors x and y. | 2.008904 | 1.944549 | 1.033095 |
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector / chunks
# Calculate set of points on vector's path every increment.
vector_pathway = np.array([chunk * i for i in range(chunks + ... | def vector_analysis(vector, coordinates, elements_vdw, increment=1.0) | Analyse a sampling vector's path for window analysis purpose. | 5.109656 | 5.003337 | 1.02125 |
z, elements, coordinates = args
window_com = np.array([xy[0], xy[1], z])
return -pore_diameter(elements, coordinates, com=window_com)[0] | def optimise_xy(xy, *args) | Return negative pore diameter for x and y coordinates optimisation. | 14.057564 | 8.300316 | 1.693618 |
x, y, elements, coordinates = args
window_com = np.array([x, y, z])
return pore_diameter(elements, coordinates, com=window_com)[0] | def optimise_z(z, *args) | Return pore diameter for coordinates optimisation in z direction. | 13.720163 | 8.075612 | 1.698963 |
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)... | def find_average_diameter(elements, coordinates, adjust=1, increment=0.1,
processes=None, **kwargs) | Return average diameter for a molecule. | 5.171729 | 5.067446 | 1.020579 |
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array([0, 0, 0])
# Initial center of mass to reverse translation at the end
initial_com = center_of_mass(elements, coordinates)... | def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs) | Return average diameter for a molecule. | 7.163045 | 7.034848 | 1.018223 |
res = p * (p - 1.0) / 4.0 * log(pi)
for ii in range(1, p+1):
res += gammaln(a + (1.0 - ii) / 2.0)
return res | def lpgamma(p, a) | Multidimensional gamma / partial gamma function
Parameters
----------
p : int
something....
a : float
something....
Returns
-------
Multidimensional gamma / partial gamma function | 4.35124 | 5.714073 | 0.761495 |
if n == 1:
return self._rand1()
else:
out = np.empty((n, self._p, self._p))
for i in range(n):
out[i] = self._rand1()
return out | def rand(self, n=1) | Generate random samples from the distribution
Parameters
----------
n : int, optional(default=1)
The number of samples to generate
Returns
-------
out : array_like
The generated samples | 2.7823 | 3.52403 | 0.789522 |
"the logarithm of normalizing constant in pdf"
h_df = self.df / 2
p, S = self._p, self.S
return h_df * (logdet(S) + p * logtwo) + lpgamma(p, h_df) | def _c0(self) | the logarithm of normalizing constant in pdf | 13.843915 | 8.087407 | 1.711787 |
p, df = self._p, self.df
A = np.zeros((p, p))
for i in range(p):
A[i, i] = sqrt(st.chi2.rvs(df - i))
for j in range(p-1):
for i in range(j+1, p):
A[i, j] = np.random.randn()
return A | def _genA(self) | Generate the matrix A in the Bartlett decomposition
A is a lower triangular matrix, with
A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j
~ Normal() when i > j | 3.309389 | 2.66656 | 1.241071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.