code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with open(RELEASE_README_FILE, "r") as file_obj:
template = file_obj.read()
contents = template.format(
version=version,
circleci_build=circleci_build,
appveyor_build=appveyor_build,
coveralls_build=coveralls_build,
travis_build=travis_build,
)
with o... | def populate_readme(
version, circleci_build, appveyor_build, coveralls_build, travis_build
) | Populates ``README.rst`` with release-specific data.
This is because ``README.rst`` is used on PyPI.
Args:
version (str): The current version.
circleci_build (Union[str, int]): The CircleCI build ID corresponding
to the release.
appveyor_build (str): The AppVeyor build ID c... | 1.779924 | 1.978828 | 0.899484 |
with open(RELEASE_INDEX_FILE, "r") as file_obj:
template = file_obj.read()
contents = template.format(
version=version,
circleci_build=circleci_build,
appveyor_build=appveyor_build,
coveralls_build=coveralls_build,
travis_build=travis_build,
)
with op... | def populate_index(
version, circleci_build, appveyor_build, coveralls_build, travis_build
) | Populates ``docs/index.rst`` with release-specific data.
Args:
version (str): The current version.
circleci_build (Union[str, int]): The CircleCI build ID corresponding
to the release.
appveyor_build (str): The AppVeyor build ID corresponding to the
release.
... | 1.841391 | 1.953782 | 0.942475 |
with open(BINARY_EXT_TEMPLATE, "r") as file_obj:
template = file_obj.read()
contents = template.format(revision=version)
with open(BINARY_EXT_FILE, "w") as file_obj:
file_obj.write(contents) | def populate_native_libraries(version) | Populates ``binary-extension.rst`` with release-specific data.
Args:
version (str): The current version. | 3.163545 | 3.004645 | 1.052885 |
with open(DEVELOPMENT_TEMPLATE, "r") as file_obj:
template = file_obj.read()
contents = template.format(revision=version, rtd_version=version)
with open(DEVELOPMENT_FILE, "w") as file_obj:
file_obj.write(contents) | def populate_development(version) | Populates ``DEVELOPMENT.rst`` with release-specific data.
This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation.
Args:
version (str): The current version. | 2.700518 | 3.021725 | 0.893701 |
version = get_version()
circleci_build = six.moves.input("CircleCI Build ID: ")
appveyor_build = six.moves.input("AppVeyor Build ID: ")
coveralls_build = six.moves.input("Coveralls Build ID: ")
travis_build = six.moves.input("Travis Build ID: ")
populate_readme(
version, circleci_bu... | def main() | Populate the templates with release-specific fields.
Requires user input for the CircleCI, AppVeyor, Coveralls.io and Travis
build IDs. | 2.755873 | 2.203789 | 1.250516 |
left = np.zeros((degree + 1, degree + 1), order="F")
right = np.zeros((degree + 1, degree + 1), order="F")
left[0, 0] = 1.0
right[-1, -1] = 1.0
for col in six.moves.xrange(1, degree + 1):
half_prev = 0.5 * left[:col, col - 1]
left[:col, col] = half_prev
left[1 : col + 1,... | def make_subdivision_matrices(degree) | Make the matrix used to subdivide a curve.
.. note::
This is a helper for :func:`_subdivide_nodes`. It does not have a
Fortran speedup because it is **only** used by a function which has
a Fortran speedup.
Args:
degree (int): The degree of the curve.
Returns:
Tupl... | 3.817903 | 4.108505 | 0.929268 |
_, num_nodes = np.shape(nodes)
if num_nodes == 2:
left_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_LEFT)
right_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_RIGHT)
elif num_nodes == 3:
left_nodes = _helpers.matrix_product(nodes, _QUADRATIC_SUBDIVIDE_LEFT)... | def _subdivide_nodes(nodes) | Subdivide a curve into two sub-curves.
Does so by taking the unit interval (i.e. the domain of the surface) and
splitting it into two sub-intervals by splitting down the middle.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Ar... | 1.796728 | 1.803616 | 0.996181 |
r
# NOTE: We assume but don't check that lambda2 has the same shape.
num_vals, = lambda1.shape
dimension, num_nodes = nodes.shape
degree = num_nodes - 1
# Resize as row vectors for broadcast multiplying with
# columns of ``nodes``.
lambda1 = lambda1[np.newaxis, :]
lambda2 = lambda2[n... | def _evaluate_multi_barycentric(nodes, lambda1, lambda2) | r"""Evaluates a B |eacute| zier type-function.
Of the form
.. math::
B(\lambda_1, \lambda_2) = \sum_j \binom{n}{j}
\lambda_1^{n - j} \lambda_2^j \cdot v_j
for some set of vectors :math:`v_j` given by ``nodes``.
Does so via a modified Horner's method for each pair of values
in ... | 4.26095 | 4.418647 | 0.964311 |
r
result_vec = evaluate_multi(nodes, np.asfortranarray([s_val]))
# NOTE: We convert to 1D to make sure NumPy uses vector norm.
return np.linalg.norm(result_vec[:, 0], ord=2) | def vec_size(nodes, s_val) | r"""Compute :math:`\|B(s)\|_2`.
.. note::
This is a helper for :func:`_compute_length` and does not have
a Fortran speedup.
Intended to be used with ``functools.partial`` to fill in the
value of ``nodes`` and create a callable that only accepts ``s_val``.
Args:
nodes (numpy.n... | 11.158185 | 12.806906 | 0.871263 |
r
_, num_nodes = np.shape(nodes)
# NOTE: We somewhat replicate code in ``evaluate_hodograph()``
# here. This is so we don't re-compute the nodes for the first
# derivative every time it is evaluated.
first_deriv = (num_nodes - 1) * (nodes[:, 1:] - nodes[:, :-1])
if num_nodes == 2... | def _compute_length(nodes) | r"""Approximately compute the length of a curve.
.. _QUADPACK: https://en.wikipedia.org/wiki/QUADPACK
If ``degree`` is :math:`n`, then the Hodograph curve
:math:`B'(s)` is degree :math:`d = n - 1`. Using this curve, we
approximate the integral:
.. math::
\int_{B\left(\left[0, 1\right]\rig... | 7.052205 | 6.086174 | 1.158725 |
r
dimension, num_nodes = np.shape(nodes)
new_nodes = np.empty((dimension, num_nodes + 1), order="F")
multipliers = np.arange(1, num_nodes, dtype=_FLOAT64)[np.newaxis, :]
denominator = float(num_nodes)
new_nodes[:, 1:-1] = (
multipliers * nodes[:, :-1]
+ (denominator - multipliers... | def _elevate_nodes(nodes) | r"""Degree-elevate a B |eacute| zier curves.
Does this by converting the current nodes :math:`v_0, \ldots, v_n`
to new nodes :math:`w_0, \ldots, w_{n + 1}` where
.. math::
\begin{align*}
w_0 &= v_0 \\
w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\
w_{n + 1} ... | 4.379085 | 4.970809 | 0.88096 |
return np.asfortranarray(lambda1 * nodes[:, :-1] + lambda2 * nodes[:, 1:]) | def de_casteljau_one_round(nodes, lambda1, lambda2) | Perform one round of de Casteljau's algorithm.
.. note::
This is a helper for :func:`_specialize_curve`. It does not have a
Fortran speedup because it is **only** used by a function which has
a Fortran speedup.
The weights are assumed to sum to one.
Args:
nodes (numpy.nda... | 4.784986 | 10.508158 | 0.455359 |
# NOTE: There is no corresponding "enable", but the disable only applies
# in this lexical scope.
# pylint: disable=too-many-locals
_, num_nodes = np.shape(nodes)
# Uses start-->0, end-->1 to represent the specialization used.
weights = ((1.0 - start, start), (1.0 - end, end))
par... | def _specialize_curve(nodes, start, end) | Specialize a curve to a re-parameterization
.. note::
This assumes the curve is degree 1 or greater but doesn't check.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): Control points for a... | 4.151061 | 4.187039 | 0.991407 |
r
_, num_nodes = np.shape(nodes)
first_deriv = nodes[:, 1:] - nodes[:, :-1]
return (num_nodes - 1) * evaluate_multi(
first_deriv, np.asfortranarray([s])
) | def _evaluate_hodograph(s, nodes) | r"""Evaluate the Hodograph curve at a point :math:`s`.
The Hodograph (first derivative) of a B |eacute| zier curve
degree :math:`d = n - 1` and is given by
.. math::
B'(s) = n \sum_{j = 0}^{d} \binom{d}{j} s^j
(1 - s)^{d - j} \cdot \Delta v_j
where each forward difference is given by
... | 8.398364 | 7.750232 | 1.083627 |
r
_, num_nodes = np.shape(nodes)
if num_nodes == 2: # Lines have no curvature.
return 0.0
# NOTE: We somewhat replicate code in ``evaluate_hodograph()`` here.
first_deriv = nodes[:, 1:] - nodes[:, :-1]
second_deriv = first_deriv[:, 1:] - first_deriv[:, :-1]
concavity = (
(n... | def _get_curvature(nodes, tangent_vec, s) | r"""Compute the signed curvature of a curve at :math:`s`.
Computed via
.. math::
\frac{B'(s) \times B''(s)}{\left\lVert B'(s) \right\rVert_2^3}
.. image:: ../images/get_curvature.png
:align: center
.. testsetup:: get-curvature
import numpy as np
import bezier
fro... | 5.055627 | 4.721849 | 1.070688 |
r
candidates = [(0.0, 1.0, nodes)]
for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1):
next_candidates = []
for start, end, candidate in candidates:
if _helpers.contains_nd(candidate, point.ravel(order="F")):
midpoint = 0.5 * (start + end)
lef... | def _locate_point(nodes, point) | r"""Locate a point on a curve.
Does so by recursively subdividing the curve and rejecting
sub-curves with bounding boxes that don't contain the point.
After the sub-curves are sufficiently small, uses Newton's
method to zoom in on the parameter value.
.. note::
This assumes, but does not c... | 4.752717 | 4.265183 | 1.114305 |
_, num_nodes = np.shape(nodes)
if num_nodes == 2:
reduction = _REDUCTION0
denom = _REDUCTION_DENOM0
elif num_nodes == 3:
reduction = _REDUCTION1
denom = _REDUCTION_DENOM1
elif num_nodes == 4:
reduction = _REDUCTION2
denom = _REDUCTION_DENOM2
elif ... | def _reduce_pseudo_inverse(nodes) | Performs degree-reduction for a B |eacute| zier curve.
Does so by using the pseudo-inverse of the degree elevation
operator (which is overdetermined).
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.nd... | 2.824755 | 2.422632 | 1.165986 |
relative_err = np.linalg.norm(nodes - projected, ord="fro")
if relative_err != 0.0:
relative_err /= np.linalg.norm(nodes, ord="fro")
return relative_err | def projection_error(nodes, projected) | Compute the error between ``nodes`` and the projected nodes.
.. note::
This is a helper for :func:`maybe_reduce`, which is in turn a helper
for :func:`_full_reduce`. Hence there is no corresponding Fortran
speedup.
For now, just compute the relative error in the Frobenius norm. But,
... | 2.764199 | 3.523811 | 0.784434 |
r
_, num_nodes = nodes.shape
if num_nodes < 2:
return False, nodes
elif num_nodes == 2:
projection = _PROJECTION0
denom = _PROJ_DENOM0
elif num_nodes == 3:
projection = _PROJECTION1
denom = _PROJ_DENOM1
elif num_nodes == 4:
projection = _PROJECTIO... | def maybe_reduce(nodes) | r"""Reduce nodes in a curve if they are degree-elevated.
.. note::
This is a helper for :func:`_full_reduce`. Hence there is no
corresponding Fortran speedup.
We check if the nodes are degree-elevated by projecting onto the
space of degree-elevated curves of the same degree, then comparin... | 3.331056 | 2.8208 | 1.18089 |
was_reduced, nodes = maybe_reduce(nodes)
while was_reduced:
was_reduced, nodes = maybe_reduce(nodes)
return nodes | def _full_reduce(nodes) | Apply degree reduction to ``nodes`` until it can no longer be reduced.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): The nodes in the curve.
Returns:
numpy.ndarray: The fully degree-red... | 4.288129 | 5.732576 | 0.748028 |
if bezier is None:
return []
local_members = []
all_members = set()
for name in dir(bezier):
# Filter out non-public.
if name.startswith("_") and name not in SPECIAL_MEMBERS:
continue
value = getattr(bezier, name)
# Filter out imported modules.
... | def get_public_members() | Get public members in :mod:`bezier` package.
Also validates the contents of ``bezier.__all__``.
Returns:
list: List of all public members **defined** in the
main package (i.e. in ``__init__.py``).
Raises:
ValueError: If ``__all__`` has repeated elements.
ValueError: If the... | 3.891806 | 3.436876 | 1.132367 |
public_members = get_public_members()
if public_members:
members = "\n :members: {}".format(", ".join(public_members))
else:
members = ""
return DESIRED_TEMPLATE.format(members=members) | def get_desired() | Populate ``DESIRED_TEMPLATE`` with public members.
If there are no members, does nothing.
Returns:
str: The "desired" contents of ``bezier.rst``. | 4.317268 | 2.972813 | 1.45225 |
with open(FILENAME, "r") as file_obj:
contents = file_obj.read()
desired = get_desired()
if contents == EXPECTED:
with open(FILENAME, "w") as file_obj:
file_obj.write(desired)
elif contents != desired:
raise ValueError("Unexpected contents", contents, "Expected",... | def main() | Main entry point to replace autogenerated contents.
Raises:
ValueError: If the file doesn't contain the expected or
desired contents. | 3.987246 | 3.635023 | 1.096897 |
if not build_ext_cmd.inplace:
return
bezier_dir = os.path.join("src", "bezier")
shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir)
shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir) | def run_cleanup(build_ext_cmd) | Cleanup after ``BuildFortranThenExt.run``.
For in-place builds, moves the built shared library into the source
directory. | 3.190378 | 3.129944 | 1.019308 |
# NOTE: NumPy may not be installed, but we don't want **this** module to
# cause an import failure.
from numpy.distutils.fcompiler import gnu
# Only Windows.
if os.name != "nt":
return
# Only ``gfortran``.
if not isinstance(f90_compiler, gnu.Gnu95FCompiler):
retu... | def patch_f90_compiler(f90_compiler) | Patch up ``f90_compiler.library_dirs``.
Updates flags in ``gfortran`` and ignores other compilers. The only
modification is the removal of ``-fPIC`` since it is not used on Windows
and the build flags turn warnings into errors.
Args:
f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortra... | 3.703745 | 3.591838 | 1.031156 |
clean_dirs = (
get_path(".cache"),
get_path(".coverage"),
get_path(".pytest_cache"),
get_path("__pycache__"),
get_path("build"),
get_path("dist"),
get_path("docs", "__pycache__"),
get_path("docs", "build"),
get_path("scripts", "macos", "__... | def clean(session) | Clean up build files.
Cleans up all artifacts that might get created during
other ``nox`` sessions.
There is no need for the session to create a ``virtualenv``
here (we are just pretending to be ``make``). | 2.217558 | 2.226339 | 0.996056 |
def _hook_add(func):
if name not in _hooks:
logger.debug("Creating new hook %s" % name)
_hooks[name] = []
logger.debug('Registering hook %s for function %s' % (name, fn))
_hooks[name].append(func)
if fn is None:
# Behave like a decorator
def... | def register(name, fn=None) | Decorator to register a function as a hook
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
:param name: str Nam... | 2.808805 | 2.968968 | 0.946054 |
for name, module in get_app_modules():
if module_has_submodule(module, module_name):
yield name, import_module('{0}.{1}'.format(name, module_name)) | def get_app_submodules(module_name) | Get a specific sub module of the app
:param module_name: module name to get
:return: name, module tuple | 3.522888 | 3.876101 | 0.908874 |
global _all_hooks_registered
if not _all_hooks_registered:
logger.debug("Searching for hooks")
hooks = list(get_app_submodules('auth_hooks'))
logger.debug("Got %s hooks" % len(hooks))
_all_hooks_registered = True | def register_all_hooks() | Register all hooks found in 'auth_hooks' sub modules
:return: | 4.236517 | 3.669003 | 1.154678 |
try:
endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint)
headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'}
logger.debug(headers)
logger.debug(endpoint)
ret = getattr(requests, func)(endpoint, headers=headers... | def exec_request(endpoint, func, raise_for_status=False, **kwargs) | Send an https api request | 3.442679 | 3.433567 | 1.002654 |
sanitized = str(cls.__sanitize_username(username))
logger.debug("Adding user to SeAT with username %s" % sanitized)
password = cls.__generate_random_pass()
ret = cls.exec_request('user', 'post', username=sanitized, email=str(email), password=password)
logger.debug(ret)
... | def add_user(cls, username, email) | Add user to service | 4.275544 | 4.239599 | 1.008478 |
ret = cls.exec_request('user/{}'.format(username), 'delete')
logger.debug(ret)
if cls._response_ok(ret):
logger.info("Deleted SeAT user with username %s" % username)
return username
return None | def delete_user(cls, username) | Delete user | 7.308626 | 7.292924 | 1.002153 |
ret = cls.exec_request('user/{}'.format(username), 'put', account_status=1)
logger.debug(ret)
if cls._response_ok(ret):
logger.info("Enabled SeAT user with username %s" % username)
return username
logger.info("Failed to enabled SeAT user with username %s"... | def enable_user(cls, username) | Enable user | 5.942171 | 5.900557 | 1.007053 |
cls.update_roles(username, [])
ret = cls.exec_request('user/{}'.format(username), 'put', account_status=0)
logger.debug(ret)
if cls._response_ok(ret):
logger.info("Disabled SeAT user with username %s" % username)
return username
logger.info("Faile... | def disable_user(cls, username) | Disable user | 5.957577 | 5.796453 | 1.027797 |
ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True)
return ret['email'] != email | def _check_email_changed(cls, username, email) | Compares email to one set on SeAT | 7.730853 | 7.00381 | 1.103807 |
if cls._check_email_changed(username, email):
# if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error
logger.debug("Updating SeAT username %s with email %s and password" % (username, email))
ret = cls.exec_request('user/{}'.format(usern... | def update_user(cls, username, email, password) | Edit user info | 3.605229 | 3.641447 | 0.990054 |
format_data = self.get_format_data()
return Formatter().vformat(self.string_formatter, args=[], kwargs=format_data) | def format_name(self) | :return: str Generated name | 10.231368 | 9.59334 | 1.066507 |
kwargs = super(AddUpdateMixin, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs | def get_form_kwargs(self) | Inject the request user into the kwargs passed to the form | 3.084883 | 2.679385 | 1.15134 |
if queryset is None:
queryset = self.get_queryset()
try:
return queryset.get(user__pk=self.request.user.pk)
except ObjectDoesNotExist:
raise Http404 | def get_object(self, queryset=None) | Returns the object the view is displaying. | 2.206638 | 2.224515 | 0.991964 |
if user.is_authenticated:
return cls.has_management_permission(user) or user.leads_groups.all()
return False | def can_manage_groups(cls, user) | For use with user_passes_test decorator.
Check if the user can manage groups. Either has the
auth.group_management permission or is a leader of at least one group
and is also a Member.
:param user: django.contrib.auth.models.User for the request
:return: bool True if user can man... | 7.61496 | 6.077308 | 1.253015 |
if user.is_authenticated:
return cls.has_management_permission(user) or user.leads_groups.filter(group=group).exists()
return False | def can_manage_group(cls, user, group) | Check user has permission to manage the given group
:param user: User object to test permission of
:param group: Group object the user is attempting to manage
:return: True if the user can manage the group | 5.507357 | 7.60041 | 0.724613 |
if created:
AuthGroup.objects.create(group=instance) | def create_auth_group(sender, instance, created, **kwargs) | Creates the AuthGroup model when a group is created | 3.696776 | 3.095121 | 1.194388 |
cstr = [command]
# Add the keys and values, escape as needed
if keys:
for key in keys:
if isinstance(keys[key], list):
ncstr = []
for nest in keys[key]:
ncstr.append("%s=%s" % (key, self._escap... | def construct_command(self, command, keys=None, opts=None) | Constructs a TS3 formatted command string
Keys can have a single nested list to construct a nested parameter
@param command: Command list
@type command: string
@param keys: Key/Value pairs
@type keys: dict
@param opts: Options
@type opts: list | 2.620331 | 2.56405 | 1.02195 |
if len(commandstr.split('|')) > 1:
vals = []
for cmd in commandstr.split('|'):
vals.append(self.parse_command(cmd))
return vals
cmdlist = commandstr.strip().split(' ')
command = None
keys = {}
opts = []
for k... | def parse_command(self, commandstr) | Parses a TS3 command string into command/keys/opts tuple
@param commandstr: Command string
@type commandstr: string | 3.326656 | 3.012574 | 1.104257 |
if isinstance(value, int):
return "%d" % value
value = value.replace("\\", r'\\')
for i, j in ts3_escape.items():
value = value.replace(i, j)
return value | def _escape_str(value) | Escape a value into a TS3 compatible string
@param value: Value
@type value: string/int | 5.26935 | 4.173961 | 1.262434 |
if isinstance(value, int):
return "%d" % value
value = value.replace(r"\\", "\\")
for i, j in ts3_escape.items():
value = value.replace(j, i)
return value | def _unescape_str(value) | Unescape a TS3 compatible string into a normal string
@param value: Value
@type value: string/int | 4.792237 | 3.641893 | 1.315864 |
d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': password})
if d == 0:
self._log.info('Login Successful')
return True
return False | def login(self, username, password) | Login to the TS3 Server
@param username: Username
@type username: str
@param password: Password
@type password: str | 5.188754 | 4.296611 | 1.207639 |
if self._connected and id > 0:
self.send_command('use', keys={'sid': id}) | def use(self, id) | Use a particular Virtual Server instance
@param id: Virtual Server ID
@type id: int | 14.548416 | 13.943136 | 1.043411 |
urls = self.Urls()
urls.auth_activate = 'auth_example_activate'
urls.auth_deactivate = 'auth_example_deactivate'
urls.auth_reset_password = 'auth_example_reset_password'
urls.auth_set_password = 'auth_example_set_password'
return render_to_string(self.service_ctr... | def render_services_ctrl(self, request) | Example for rendering the service control panel row
You can override the default template and create a
custom one if you wish.
:param request:
:return: | 3.291594 | 3.171437 | 1.037887 |
if self.alliance_id is None:
return None
return EveAllianceInfo.objects.get(alliance_id=self.alliance_id) | def alliance(self) -> Union[EveAllianceInfo, None] | Pseudo foreign key from alliance_id to EveAllianceInfo
:raises: EveAllianceInfo.DoesNotExist
:return: EveAllianceInfo or None | 2.336222 | 2.065364 | 1.131143 |
logger.debug("Received pre_save from {}".format(instance))
if not instance.pk:
# new model being created
return
try:
old_instance = AutogroupsConfig.objects.get(pk=instance.pk)
# Check if enable was toggled, delete groups?
if old_instance.alliance_groups is True... | def pre_save_config(sender, instance, *args, **kwargs) | Checks if enable was toggled on group config and
deletes groups if necessary. | 4.177051 | 3.604696 | 1.15878 |
AutogroupsConfig.objects.update_groups_for_user(instance.user) | def check_groups_on_profile_update(sender, instance, created, *args, **kwargs) | Trigger check when main character or state changes. | 10.979692 | 11.335203 | 0.968636 |
if action.startswith('post_'):
for pk in pk_set:
try:
state = State.objects.get(pk=pk)
instance.update_group_membership_for_state(state)
except State.DoesNotExist:
# Deleted States handled by the profile state change
... | def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs) | Trigger group membership update when a state is added or removed from
an autogroup config. | 4.716846 | 4.632987 | 1.018101 |
def update_service_groups(modeladmin, request, queryset):
for user in queryset: # queryset filtering doesn't work here?
service.update_groups(user)
update_service_groups.__name__ = str('update_{}_groups'.format(slugify(service.name)))
update_service_groups.short_description = "Syn... | def make_service_hooks_update_groups_action(service) | Make a admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to update services groups for the selected users | 4.656258 | 4.261796 | 1.092557 |
def sync_nickname(modeladmin, request, queryset):
for user in queryset: # queryset filtering doesn't work here?
service.sync_nickname(user)
sync_nickname.__name__ = str('sync_{}_nickname'.format(slugify(service.name)))
sync_nickname.short_description = "Sync nicknames for selected... | def make_service_hooks_sync_nickname_action(service) | Make a sync_nickname admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to sync nickname for the selected users | 4.322968 | 4.225004 | 1.023187 |
if re.search(pattern, request.path):
return getattr(settings, "NAVHELPER_ACTIVE_CLASS", "active")
return getattr(settings, "NAVHELPER_NOT_ACTIVE_CLASS", "") | def renavactive(request, pattern) | {% renavactive request "^/a_regex" %} | 4.298444 | 3.836467 | 1.120417 |
url_list = set(urls.split())
resolved = resolve(request.path)
resolved_urls = set()
if resolved.url_name:
resolved_urls.add(resolved.url_name)
if resolved.namespaces:
resolved_urls = resolved_urls.union(["{}:{}".format(namespace, resolved.url_name) for namespace in resolved.nam... | def navactive(request, urls) | {% navactive request "view_name another_view_name" %} | 1.985577 | 1.942836 | 1.021999 |
users = get_users_for_state(state)
for config in self.filter(states=state):
logger.debug("in state loop")
for user in users:
logger.debug("in user loop for {}".format(user))
config.update_group_membership_for_user(user) | def update_groups_for_state(self, state: State) | Update all the Group memberships for the users
who have State
:param state: State to update for
:return: | 5.538179 | 4.886252 | 1.133421 |
if state is None:
state = user.profile.state
for config in self.filter(states=state):
# grant user new groups for their state
config.update_group_membership_for_user(user)
for config in self.exclude(states=state):
# ensure user does not ha... | def update_groups_for_user(self, user: User, state: State = None) | Update the Group memberships for the given users state
:param user: User to update for
:param state: State to update user for
:return: | 5.422327 | 5.402898 | 1.003596 |
if self.replace_spaces:
return name.strip().replace(' ', str(self.replace_spaces_with))
return name | def _replace_spaces(self, name: str) -> str | Replace the spaces in the given name based on the config
:param name: name to replace spaces in
:return: name with spaces replaced with the configured character(s) or unchanged if configured | 6.190591 | 5.783391 | 1.070408 |
class PerformBackoff(Exception):
def __init__(self, retry_after, retry_datetime, global_ratelimit):
super(Exception, self).__init__()
self.retry_after = int(retry_after)
self.retry_datetime = retry_datetime
self.global_ratelimit = global_ratelimit
@... | def api_backoff(func) | Decorator, Handles HTTP 429 "Too Many Requests" messages from the Discord API
If blocking=True is specified, this function will block and retry
the function up to max_retries=n times, or 3 if retries is not specified.
If the API call still recieves a backoff timer this function will raise
a <DiscordApiT... | 2.749205 | 2.612954 | 1.052144 |
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-", "") # Remove the UUID '-'.
return random[0:string_length] | def random_string(string_length=10) | Returns a random string of length string_length. | 2.988971 | 2.772726 | 1.07799 |
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(Genome_Raba)
names = []
for g in f.iterRun() :
names.append(g.name)
return names | def getGenomeList() | Return the names of all imported genomes | 9.732755 | 8.934948 | 1.089291 |
for i in range(len(self.cDNA)/3) :
yield self.getCodon(i) | def iterCodons(self) | iterates through the codons | 5.593584 | 5.081376 | 1.100801 |
f = open(inFileName)
legend = f.readline()
data = ''
h = {}
h[legend] = 0
lines = f.readlines()
for l in lines :
if not h.has_key(l) :
h[l] = 0
data += l
f.flush()
f.close()
f = open(outFileName, 'w')
f.write(legend+data)
f.flush()
f.close() | def removeDuplicates(inFileName, outFileName) | removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName | 2.56823 | 2.566867 | 1.000531 |
strCmd = r %(folder, ouputFileName)
os.system(strCmd)
if removeDups :
removeDuplicates(ouputFileName, ouputFileName) | def catCSVs(folder, ouputFileName, removeDups = False) | Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems | 4.671824 | 4.402649 | 1.061139 |
res = ''
legend = []
csvs = []
for f in csvFilePaths :
c = CSVFile()
c.parse(f)
csvs.append(c)
legend.append(separator.join(c.legend.keys()))
legend = separator.join(legend)
lines = []
for i in range(len(csvs[0])) :
val = csvs[0].get(i, column)
line = separator.join(csvs[0][i])
for c in csv... | def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') | csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName' | 2.35185 | 2.300069 | 1.022513 |
if field.lower() in self.legend :
raise ValueError("%s is already in the legend" % field.lower())
self.legend[field.lower()] = len(self.legend)
if len(self.strLegend) > 0 :
self.strLegend += self.separator + field
else :
self.strLegend += field | def addField(self, field) | add a filed to the legend | 3.423125 | 2.931908 | 1.167542 |
self.filename = filePath
f = open(filePath)
if lineSeparator == '\n' :
lines = f.readlines()
else :
lines = f.read().split(lineSeparator)
f.flush()
f.close()
lines = lines[skipLines:]
self.lines = []
self.comments = []
for l in lines :
# print l
if len(l) != 0 and l[0] != "#" :
... | def parse(self, filePath, skipLines=0, separator = ',', stringSeparator = '"', lineSeparator = '\n') | Loads a CSV file | 2.413202 | 2.415834 | 0.99891 |
if len(self.legend) < 1 :
raise ValueError("There's no legend defined")
try :
os.remove(filename)
except :
pass
self.streamFile = open(filename, "a")
self.writeRate = writeRate
self.streamBuffer = []
self.keepInMemory = keepInMemory
self.streamFile.write(self.strLegend + "\n") | def streamToFile(self, filename, keepInMemory = False, writeRate = 1) | Starts a stream to a file. Every line must be committed (l.commit()) to be appended in to the file.
If keepInMemory is set to True, the parser will keep a version of the whole CSV in memory, writeRate is the number
of lines that must be committed before an automatic save is triggered. | 3.438807 | 3.43779 | 1.000296 |
if self.streamBuffer is None :
raise ValueError("Commit lines is only for when you are streaming to a file")
self.streamBuffer.append(line)
if len(self.streamBuffer) % self.writeRate == 0 :
for i in xrange(len(self.streamBuffer)) :
self.streamBuffer[i] = str(self.streamBuffer[i])
self.streamFile.... | def commitLine(self, line) | Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError | 3.044263 | 2.61015 | 1.166317 |
if self.streamBuffer is None :
raise ValueError("Commit lines is only for when you are streaming to a file")
for i in xrange(len(self.streamBuffer)) :
self.streamBuffer[i] = str(self.streamBuffer[i])
self.streamFile.write('\n'.join(self.streamBuffer))
self.streamFile.close()
self.streamFile = None
... | def closeStreamToFile(self) | Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError | 4.072113 | 3.63605 | 1.119927 |
l = CSVEntry(self)
if self.keepInMemory :
self.lines.append(l)
return l | def newLine(self) | Appends an empty line at the end of the CSV and returns it | 11.440671 | 9.057858 | 1.263066 |
self.data.insert(i, CSVEntry(self))
return self.lines[i] | def insertLine(self, i) | Inserts an empty line at position i and returns it | 10.273903 | 9.307454 | 1.103836 |
self.filename = filePath
f = open(filePath, 'w')
f.write(self.toStr())
f.flush()
f.close() | def save(self, filePath) | save the CSV to a file | 2.816359 | 2.679452 | 1.051095 |
s = [self.strLegend]
for l in self.lines :
s.append(l.toStr())
return self.lineSeparator.join(s) | def toStr(self) | returns a string version of the CSV | 5.516726 | 5.217902 | 1.057269 |
return self._makeLoadQuery(objectType, *args, **coolArgs).count() | def count(self, objectType, *args, **coolArgs) | Returns the number of elements satisfying the query | 7.862287 | 7.849032 | 1.001689 |
ret = []
for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() :
if issubclass(objectType, pyGenoRabaObjectWrapper) :
ret.append(objectType(wrapped_object_and_bag = (e, self.bagKey)))
else :
ret.append(e)
return ret | def get(self, objectType, *args, **coolArgs) | Raba Magic inside. This is th function that you use for
querying pyGeno's DB.
Usage examples:
* myGenome.get("Gene", name = 'TPST2')
* myGene.get(Protein, id = 'ENSID...')
* myGenome.get(Transcript, {'start >' : x, 'end <' : y}) | 8.139893 | 6.746462 | 1.206542 |
for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() :
if issubclass(objectType, pyGenoRabaObjectWrapper) :
yield objectType(wrapped_object_and_bag = (e, self.bagKey))
else :
yield e | def iterGet(self, objectType, *args, **coolArgs) | Same as get. But retuns the elements one by one, much more efficient for large outputs | 11.255542 | 10.179405 | 1.105717 |
printf("Importing polymorphism set: %s... (This may take a while)" % packageFile)
isDir = False
if not os.path.isdir(packageFile) :
packageDir = _decompressPackage(packageFile)
else :
isDir = True
packageDir = packageFile
fpMan = os.path.normpath(packageDir+'/manifest.ini')
if not os.path.isfile(fpMan)... | def importSNPs(packageFile) | The big wrapper, this function should detect the SNP type by the package manifest and then launch the corresponding function.
Here's an example of a SNP manifest file for Casava SNPs::
[package_infos]
description = Casava SNPs for testing purposes
maintainer = Tariq Daouda
maintainer_contact = tariq.daouda [a... | 3.327077 | 3.010322 | 1.105223 |
con = conf.db
try :
SMaster = SNPMaster(setName = setName)
con.beginTransaction()
SNPType = SMaster.SNPType
con.delete(SNPType, 'setName = ?', (setName,))
SMaster.delete()
con.endTransaction()
except KeyError :
raise KeyError("Can't delete the setName %s because i can't find it in SNPMaster, maybe th... | def deleteSNPs(setName) | deletes a set of polymorphisms | 5.729385 | 5.445598 | 1.052113 |
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno wil interpret all positions as 0 based"
printf('importing SNP set %s for species %s...' % (setName, species))
snpData = CSVFile()
snpData.parse(snpsFile, separator = "\t")
AgnosticSNP.dropIndex(('start', 'chromosomeNum... | def _importSNPs_AgnosticSNP(setName, species, genomeSource, snpsFile) | This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno wil interpret all positions as 0 based | 4.188679 | 3.216027 | 1.302439 |
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
printf('importing SNP set %s for species %s...' % (setName, species))
snpData = SNPsTxtFile(snpsFile)
CasavaSNP.dropIndex(('start', 'chromosomeNumber', 'setName'))
conf.db.beginTransaction()
... | def _importSNPs_CasavaSNP(setName, species, genomeSource, snpsFile) | This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based | 4.705103 | 3.661463 | 1.285034 |
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
snpData = VCFFile(snpsFile, gziped = True, stream = True)
dbSNPSNP.dropIndex(('start', 'chromosomeNumber', 'setName'))
conf.db.beginTransaction()
pBar = ProgressBar()
pLabel = ''
for snpEntry in ... | def _importSNPs_dbSNPSNP(setName, species, genomeSource, snpsFile) | This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based | 4.441158 | 3.435451 | 1.292744 |
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(SNPMaster)
names = []
for g in f.iterRun() :
names.append(g.setName)
return names | def getSNPSetsList() | Return the names of all imported snp sets | 12.951627 | 11.667324 | 1.110077 |
'print + sys.stdout.flush()'
for e in s[:-1] :
print e,
print s[-1]
sys.stdout.flush() | def printf(*s) | print + sys.stdout.flush() | 5.672881 | 4.534475 | 1.251056 |
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
if p.shape != q.shape :
raise ValueError("p and q must be of the same dimensions")
return np.sum(np.where(p > 0, np.log(p / q) * p, 0)) | def kullback_leibler(p, q) | Discrete Kullback-Leibler divergence D(P||Q) | 2.164988 | 2.092281 | 1.03475 |
f = open(fil)
self.parseStr(f.read())
f.close() | def parseFile(self, fil) | Opens a file and parses it | 3.730283 | 3.462564 | 1.077318 |
if header[0] != '>' :
self.data.append(('>'+header, data))
else :
self.data.append((header, data)) | def add(self, header, data) | appends a new entry to the file | 3.918578 | 3.583336 | 1.093556 |
h = haystack
res = []
f = haystack.find(needle)
offset = 0
while (f >= 0) :
#print h, needle, f, offset
res.append(f+offset)
offset += f+len(needle)
h = h[f+len(needle):]
f = h.find(needle)
return res | def findAll(haystack, needle) | returns a list of all occurances of needle in haystack | 2.80138 | 2.72342 | 1.028626 |
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M',
'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't',
'c': 'g', 'g': 'c', 't': 'a', 'r': 'y', 'y': 'r', 'm': 'k', 'k': 'm', 'w': 'w',
's'... | def complementTab(seq=[]) | returns a list of complementary sequence without inversing it | 2.366114 | 2.351672 | 1.006141 |
trans = (
translateDNA(sequence, 'f1'),
translateDNA(sequence, 'f2'),
translateDNA(sequence, 'f3'),
translateDNA(sequence, 'r1'),
translateDNA(sequence, 'r2'),
translateDNA(sequence, 'r3'),
)
return trans | def translateDNA_6Frames(sequence) | returns 6 translation of sequence. One for each reading frame | 2.531078 | 2.350869 | 1.076656 |
protein = ""
if frame == 'f1' :
dna = sequence
elif frame == 'f2':
dna = sequence[1:]
elif frame == 'f3' :
dna = sequence[2:]
elif frame == 'r1' :
dna = reverseComplement(sequence)
elif frame == 'r2' :
dna = reverseComplement(sequence)
dna = dna[1:]
elif frame == 'r3' :
dna = reverseComplement(... | def translateDNA(sequence, frame = 'f1', translTable_id='default') | Translates DNA code, frame : fwd1, fwd2, fwd3, rev1, rev2, rev3 | 2.782206 | 2.613169 | 1.064687 |
if type(polymorphipolymorphicDnaSeqSeq) is not types.ListType :
seq = list(polymorphipolymorphicDnaSeqSeq)
else :
seq = polymorphipolymorphicDnaSeqSeq
if pos >= len(seq) :
return [''.join(seq)]
variants = []
if seq[pos] in polymorphicNucleotides :
chars = decodePolymorphicNucleotide(seq[pos])
else :
... | def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) | Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield | 2.479884 | 2.406809 | 1.030362 |
if type(polySeq) is types.StringType :
if polySeq.find("/") < 0 :
sseq = list(polySeq)
else :
sseq = polySeq.split('/')
else :
sseq = polySeq
seq = []
for n in sseq :
try :
for n2 in polymorphicNucleotides[n] :
seq.append(n2)
except KeyError :
seq.append(n)
seq = set(seq)
i... | def encodePolymorphicNucleotide(polySeq) | returns a single character encoding all nucletides of polySeq
in a single character. PolySeq must have one of the following forms:
['A', 'T', 'G'], 'ATG', 'A/T/G | 1.882479 | 1.907028 | 0.987127 |
if nuc in polymorphicNucleotides :
return polymorphicNucleotides[nuc]
if nuc in nucleotides :
return nuc
raise ValueError('nuc: %s, is not a valid nucleotide' % nuc) | def decodePolymorphicNucleotide(nuc) | the opposite of encodePolymorphicNucleotide, from 'R' to ['A', 'G'] | 3.31328 | 3.042757 | 1.088907 |
if x1 < 0 or x1 >= len(sequence) :
return None
p = x1%3
if p == 0 :
return (sequence[x1: x1+3], 0)
elif p ==1 :
return (sequence[x1-1: x1+2], 1)
elif p == 2 :
return (sequence[x1-2: x1+1], 2) | def getNucleotideCodon(sequence, x1) | Returns the entire codon of the nucleotide at pos x1 in sequence,
and the position of that nocleotide in the codon in a tuple | 2.054661 | 1.886106 | 1.089367 |
ret = []
for i in range(max(len(seq1), len(seq2))) :
if i >= len(seq1) :
c1 = '#'
else :
c1 = seq1[i]
if i >= len(seq2) :
c2 = '#'
else :
c2 = seq2[i]
if c1 != c2 :
ret.append('%s|%s' % (c1, c2))
else :
ret.append('-')
return ''.join(ret) | def showDifferences(seq1, seq2) | Returns a string highligthing differences between seq1 and seq2:
* Matches by '-'
* Differences : 'A|T'
* Exceeded length : '#' | 1.850551 | 1.687979 | 1.096312 |
seq = list(sequence)
print x1, x2-1, len(seq)
seq[x1] = start + seq[x1]
seq[x2-1] = seq[x2-1] + stop
return ''.join(seq) | def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') | returns a sequence where the subsequence in [x1, x2[ is placed
in bewteen 'start' and 'stop | 2.84575 | 2.679906 | 1.061884 |
st = time.ctime().replace(' ', '_')
fn = conf.pyGeno_RABA_DBFILE.replace('.db', '_%s-bck.db' % st)
shutil.copy2(conf.pyGeno_RABA_DBFILE, fn)
return fn | def backUpDB() | backup the current database version. automatically called by importGenome(). Returns the filename of the backup | 7.472717 | 6.581628 | 1.13539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.