code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
thread = StoppableThread(target=monitor, args=(seconds_frozen,
test_interval))
thread.daemon = True
thread.start()
return thread | def start_monitoring(seconds_frozen=SECONDS_FROZEN,
test_interval=TEST_INTERVAL) | Start monitoring for hanging threads.
seconds_frozen - How much time should thread hang to activate
printing stack trace - default(10)
tests_interval - Sleep time of monitoring thread (in milliseconds)
- default(100) | 2.997407 | 3.558666 | 0.842284 |
current_thread = threading.current_thread()
hanging_threads = set()
old_threads = {} # Threads found on previous iteration.
while not current_thread.is_stopped():
new_threads = get_current_frames()
# Report died threads.
for thread_id in old_threads.keys():
if... | def monitor(seconds_frozen, test_interval) | Monitoring thread function.
Checks if thread is hanging for time defined by
``seconds_frozen`` parameter every ``test_interval`` milliseconds. | 2.891332 | 2.844639 | 1.016414 |
return dict(
(thread_id, {'frame': thread2list(frame), 'time': None})
for thread_id, frame in sys._current_frames().items()
) | def get_current_frames() | Return current threads prepared for
further processing. | 6.483224 | 5.609593 | 1.155739 |
lineno = frame.f_lineno # or f_lasti
co = frame.f_code
filename = co.co_filename
name = co.co_name
s = '\tFile "{0}", line {1}, in {2}'.format(filename, lineno, name)
line = linecache.getline(filename, lineno, frame.f_globals).lstrip()
return s + '\n\t\t' + line | def frame2string(frame) | Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number | 2.554717 | 2.490748 | 1.025683 |
l = []
while frame:
l.insert(0, frame2string(frame))
frame = frame.f_back
return l | def thread2list(frame) | Return list with string frame representation of each frame of
thread. | 3.639603 | 3.101375 | 1.173545 |
sys.stderr.write(''.join([
title.center(40).center(60, '-'), '\n', message
])) | def write_log(title, message='') | Write formatted log message to stderr. | 8.978413 | 6.909733 | 1.299386 |
def get_user(username):
try:
return User.objects.get(username=username)
except ObjectDoesNotExist as e:
raise CommandError("This user doesn't exist in the database")
def add_permissions(user_field_permissions, content_type, name):
... | def handle(self, *args, **options) | dump fields permissions for a user | 2.716711 | 2.529561 | 1.073985 |
source = self.get_model()
if not source:
return [], {}
argspec = inspect.getargspec(source)
kk = list(zip(*[reversed(l) for l in (argspec.args, argspec.defaults or [])]))
kk.reverse()
kwargs = OrderedDict(kk)
args = [x for x in argsp... | def get_model_args_kwargs(self) | Inspect the model (or view in the case of no model) and return the args
and kwargs. This functin is necessary because argspec returns in a silly format
by default. | 3.767761 | 3.401953 | 1.107529 |
start_request = request
# either 'http' or 'cmd' or 'irc'
controller_name = "".join(controller.get_controller_name().split('-')[:1])
middlewares = list(self.pre_input_middleware) + list(self.input_middleware)
for m in middlewares:
to_execute = getattr(m(contr... | def execute_input_middleware_stream(self, request, controller) | Request comes from the controller. Returned is a request.
controller arg is the name of the controller. | 6.887089 | 6.807388 | 1.011708 |
tag_match = lambda program: set(program.controllers) & set(controllers or [])
urls = set()
for key, value in self.manifest.items():
path = "%s/%s" % (prefix_path, key)
if path.endswith('/') and prefix_path:
path = path[:-1]
if hasa... | def get_urls(self, controllers=None, prefix_path='') | Return a list of all valid urls (minus args and kwargs, just the program paths)
for this manifest. If a single program has two urls, both will be returned. | 5.64871 | 5.223638 | 1.081375 |
keys = self.manifest.keys()
words = []
for key in keys:
if isinstance(self.manifest[key], Manifest):
# if this key is another manifest, append a slash to the
# suggestion so the user knows theres more items under this key
... | def _get_suggestions(self, filter_word=None) | This only gets caled internally from the get_suggestion method. | 4.323179 | 4.210853 | 1.026675 |
if '/' in front_path:
# transverse the manifest, return the new manifest, then
# get those suggestions with the remaining word
splitted = front_path.split('/')
new_manifest = self.manifest
pre_path = ''
for item in splitted:
... | def get_suggestion(self, front_path) | Returns suggestions for a path. Used in tab completion from the command
line. | 5.199683 | 5.010486 | 1.03776 |
if not program_path or program_path[0] != '/':
raise ValueError("program_path must be a full path with leading slash")
items = program_path[1:].split('/')
result = self
for item in items:
result = result[item]
if hasattr(result, "lower"):
... | def get_program(self, program_path, controller=None) | Find the program within this manifest. If key is found, and it contains
a list, iterate over the list and return the program that matches
the controller tag. NOTICE: program_path must have a leading slash. | 5.313664 | 4.646489 | 1.143587 |
if invocation.endswith('/'):
invocation = invocation[:-1]
if not invocation.startswith('/'):
invocation = '/' + invocation
if invocation == '':
invocation = '/'
all_programs = self.get_urls(controllers=[controller_tag])
matching_path... | def parse_invocation(self, invocation, controller_tag) | Given an invocation string, determine which part is the path, the program,
and the args. | 2.872985 | 2.819719 | 1.018891 |
out = type(self)(
name=self.__name,
field=self.__field,
display=self.__display,
flags=self.__flags,
default=self.__default,
defaultOrder=self.__defaultOrder,
getter=self.__gettermethod,
setter=self.__setterm... | def copy(self) | Returns a new instance copy of this column.
:return: <orb.Column> | 4.32253 | 4.503111 | 0.959898 |
# restore translatable column
if self.testFlag(self.Flags.I18n):
if isinstance(db_value, (str, unicode)):
if db_value.startswith('{'):
try:
value = projex.text.safe_eval(db_value)
except StandardError:
... | def dbRestore(self, db_value, context=None) | Converts a stored database value to Python.
:param typ: <str>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | 4.062438 | 4.440373 | 0.914887 |
ops = orb.Query.Math(op)
format = self.MathMap.get(typ, {}).get(ops) or self.MathMap.get('Default').get(ops) or '{field}'
return format.format(field=field, value=value) | def dbMath(self, typ, field, op, value) | Performs some database math on the given field. This will be database specific
implementations and should return the resulting database operation.
:param field: <str>
:param op: <orb.Query.Math>
:param target: <variant>
:param context: <orb.Context> || None
:return: <s... | 8.41487 | 6.857918 | 1.22703 |
# convert base types to work in the database
if isinstance(py_value, (list, tuple, set)):
py_value = tuple((self.dbStore(x) for x in py_value))
elif isinstance(py_value, orb.Collection):
py_value = py_value.ids()
elif isinstance(py_value, orb.Model):
... | def dbStore(self, typ, py_value) | Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> | 3.52667 | 3.341911 | 1.055285 |
return self.TypeMap.get(typ, self.TypeMap.get('Default')) | def dbType(self, typ) | Returns the database object type based on the given connection type.
:param typ: <str>
:return: <str> | 10.029893 | 13.647491 | 0.734926 |
if isinstance(self.__default, (str, unicode)):
return self.valueFromString(self.__default)
else:
return self.__default | def default(self) | Returns the default value for this column to return
when generating new instances.
:return <variant> | 5.56109 | 4.657449 | 1.194021 |
if not self.__field:
default_field = inflection.underscore(self.__name)
if isinstance(self, orb.ReferenceColumn):
default_field += '_id'
self.__field = default_field
return self.__field or default_field | def field(self) | Returns the field name that this column will have inside the database.
:return <str> | 6.054874 | 5.708607 | 1.060657 |
for schema in schemas:
if schema.hasColumn(self):
return schema
return self.schema() | def firstMemberSchema(self, schemas) | Returns the first schema within the list that this column is a member
of.
:param schemas | [<orb.TableSchema>, ..]
:return <orb.TableSchema> || None | 7.261151 | 6.918484 | 1.049529 |
if type(schemas) not in (tuple, list, set):
schemas = (schemas,)
for schema in schemas:
if schema.hasColumn(self):
return True
return False | def isMemberOf(self, schemas) | Returns whether or not this column is a member of any of the given
schemas.
:param schemas | [<orb.TableSchema>, ..] || <orb.TableSchema>
:return <bool> | 3.852639 | 3.82624 | 1.006899 |
# required params
self.__name = jdata['name']
self.__field = jdata['field']
# optional fields
self.__display = jdata.get('display') or self.__display
self.__flags = jdata.get('flags') or self.__flags
self.__defaultOrder = jdata.get('defaultOrder') or sel... | def loadJSON(self, jdata) | Initializes the information for this class from the given JSON data blob.
:param jdata: <dict> | 2.873395 | 3.039834 | 0.945247 |
context = context or orb.Context()
# check to see if this column is translatable before restoring
if self.testFlag(self.Flags.I18n):
locales = context.locale.split(',')
if not isinstance(value, dict):
default_locale = locales[0]
... | def restore(self, value, context=None, inflated=True) | Restores the value from a table cache for usage.
:param value | <variant>
context | <orb.Context> || None | 4.244427 | 4.213204 | 1.007411 |
if isinstance(value, (str, unicode)):
value = self.valueFromString(value)
# store the internationalized property
if self.testFlag(self.Flags.I18n):
if not isinstance(value, dict):
context = context or orb.Context()
return {context... | def store(self, value, context=None) | Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant> | 6.362932 | 6.836469 | 0.930734 |
if state:
self.__flags |= flag
else:
self.__flags &= ~flag | def setFlag(self, flag, state=True) | Sets whether or not this flag should be on.
:param flag | <Column.Flags>
state | <bool> | 3.255737 | 4.729143 | 0.688441 |
# check for the required flag
if self.testFlag(self.Flags.Required) and not self.testFlag(self.Flags.AutoAssign):
if self.isNull(value):
msg = '{0} is a required column.'.format(self.name())
raise orb.errors.ColumnValidationError(self, msg)
#... | def validate(self, value) | Validates the inputted value against this columns rules. If the inputted value does not pass, then
a validation error will be raised. Override this method in column sub-classes for more
specialized validation.
:param value | <variant>
:return <bool> success | 7.344301 | 6.345549 | 1.157394 |
cls_type = jdata.get('type')
col_cls = cls.byName(cls_type)
if not col_cls:
raise orb.errors.ColumnTypeNotFound(cls_type)
else:
col = col_cls()
col.loadJSON(jdata)
return col | def fromJSON(cls, jdata) | Generates a new column from the given json data. This should
be already loaded into a Python dictionary, not a JSON string.
:param jdata | <dict>
:return <orb.Column> || None | 4.742691 | 4.061227 | 1.167798 |
if not self.inherits():
return []
schema = orb.system.schema(self.inherits())
if not schema:
return []
return schema.ancestry() + [schema] | def ancestry(self) | Returns the different inherited schemas for this instance.
:return [<TableSchema>, ..] | 7.843699 | 5.52117 | 1.420659 |
column.setSchema(self)
self.__columns[column.name()] = column | def addColumn(self, column) | Adds the inputted column to this table schema.
:param column | <orb.Column> | 8.275832 | 10.410741 | 0.794932 |
index.setSchema(self)
self.__indexes[index.name()] = index | def addIndex(self, index) | Adds the inputted index to this table schema.
:param index | <orb.Index> | 8.023382 | 11.782549 | 0.680955 |
collector.setSchema(self)
self.__collectors[collector.name()] = collector | def addCollector(self, collector) | Adds the inputted collector reference to this table schema.
:param collector | <orb.Collector> | 6.606438 | 8.536315 | 0.773922 |
return self.collectors(recurse=recurse).get(name) | def collector(self, name, recurse=True) | Returns the collector that matches the inputted name.
:return <orb.Collector> || None | 9.13354 | 8.670142 | 1.053448 |
output = {}
if recurse and self.inherits():
schema = orb.system.schema(self.inherits())
if not schema:
raise orb.errors.ModelNotFound(schema=self.inherits())
else:
iflags = (flags & ~orb.Collector.Flags.Virtual) if flags else ~... | def collectors(self, recurse=True, flags=0) | Returns a list of the collectors for this instance.
:return {<str> name: <orb.Collector>, ..} | 5.228678 | 4.630047 | 1.129293 |
if isinstance(key, orb.Column):
return key
else:
cache_key = (key, recurse, flags)
try:
last_column = self.__cache[cache_key]
except KeyError:
parts = key.split('.')
schema = self
la... | def column(self, key, recurse=True, flags=0, raise_=True) | Returns the column instance based on its name.
If error reporting is on, then the ColumnNotFound
error will be thrown the key inputted is not a valid
column name.
:param key | <str> || <orb.Column> || <list>
recurse | <bool>
fla... | 3.124247 | 2.976387 | 1.049678 |
key = (recurse, flags)
try:
return self.__cache[key]
except KeyError:
output = odict()
if recurse:
inherits = self.inherits()
if inherits:
schema = orb.system.schema(inherits)
i... | def columns(self, recurse=True, flags=0) | Returns the list of column instances that are defined
for this table schema instance.
:param recurse | <bool>
flags | <orb.Column.Flags>
kind | <orb.Column.Kind>
:return {<str> column name: <orb.Column>, ..} | 4.10141 | 3.961412 | 1.03534 |
return column in self.columns(recurse=recurse, flags=flags) | def hasColumn(self, column, recurse=True, flags=0) | Returns whether or not this column exists within the list of columns
for this schema.
:return <bool> | 4.844057 | 7.409742 | 0.653742 |
output = self.__indexes.copy()
if recurse and self.inherits():
schema = orb.system.schema(self.inherits())
if not schema:
raise orb.errors.ModelNotFound(schema=self.inherits())
else:
output.update(schema.indexes(recurse=recurse... | def indexes(self, recurse=True) | Returns the list of indexes that are associated with this schema.
:return [<orb.Index>, ..] | 4.997811 | 4.489201 | 1.113296 |
inherits = self.inherits()
while inherits:
ischema = orb.system.schema(inherits)
if not ischema:
raise orb.errors.ModelNotFound(schema=inherits)
yield ischema
inherits = ischema.inherits() | def inheritanceTree(self) | Returns the inheritance tree for this schema, traversing up the hierarchy for the inherited schema instances.
:return: <generator> | 7.319237 | 5.912344 | 1.237959 |
if self.__model is None and autoGenerate:
self.__model = orb.system.generateModel(self)
self.setModel(self.__model)
return self.__model | def model(self, autoGenerate=False) | Returns the default Table class that is associated with this \
schema instance.
:param autoGenerate | <bool>
:return <subclass of Table> | 5.73826 | 7.147256 | 0.802862 |
context = orb.Context(**context)
if context.forceNamespace:
return context.namespace or self.__namespace
else:
return self.__namespace or context.namespace | def namespace(self, **context) | Returns the namespace that should be used for this schema, when specified.
:return: <str> | 8.278549 | 9.825228 | 0.842581 |
if callable(item) and hasattr(item, '__orb__'):
item = item.__orb__
key = item.name()
model = self.__model
# create class methods for indexes
if isinstance(item, orb.Index):
self.__indexes[key] = item
item.setSchema(self)
... | def register(self, item) | Registers a new orb object to this schema. This could be a column, index, or collector -- including
a virtual object defined through the orb.virtual decorator.
:param item: <variant>
:return: | 3.144207 | 2.588466 | 1.214699 |
self.__columns = {}
for name, column in columns.items():
self.__columns[name] = column
column.setSchema(self) | def setColumns(self, columns) | Sets the columns that this schema uses.
:param columns | [<orb.Column>, ..] | 3.668412 | 3.934892 | 0.932278 |
self.__indexes = {}
for name, index in indexes.items():
self.__indexes[name] = index
index.setSchema(self) | def setIndexes(self, indexes) | Sets the list of indexed lookups for this schema to the inputted list.
:param indexes | [<orb.Index>, ..] | 3.577425 | 4.292635 | 0.833387 |
self.__collectors = {}
for name, collector in collectors.items():
self.__collectors[name] = collector
collector.setSchema(self) | def setCollectors(self, collectors) | Sets the collector methods that will be used for this schema.
:param collectors | [<orb.Collectors>, ..] | 3.349883 | 3.608812 | 0.928251 |
d = defaultdict(list)
for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in kwargs)):
d[k].append(v)
ret = {}
for k, v in d.items():
# replace single item lists with just the item.
if len(v) == 1 and type(v) is list:
ret[k] = v[0]
else:
... | def parse_kwargs(kwargs) | Convert a list of kwargs into a dictionary. Duplicates of the same keyword
get added to an list within the dictionary.
>>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']
{'var1': [1, 3], 'var2': 2} | 2.72453 | 2.774465 | 0.982002 |
out = ["<ul>"]
for item in items:
out.append("<li>" + htmlize(item) + "</li>")
out.append("</ul>")
return "\n".join(out) | def htmlize_list(items) | Turn a python list into an html list. | 1.886042 | 1.841602 | 1.024131 |
if type(obj) is dict:
new_dict = {}
for key, value in obj.items():
new_dict[key] = pre_process_json(value)
return new_dict
elif type(obj) is list:
new_list = []
for item in obj:
new_list.append(pre_process_json(item))
return new_list
... | def pre_process_json(obj) | Preprocess items in a dictionary or list and prepare them to be json serialized. | 1.684809 | 1.616752 | 1.042095 |
from giotto.views import get_jinja_template
if 'json' in mimetype:
return json.dumps({
'code': code,
'exception': exc.__class__.__name__,
'message': str(exc),
})
et = get_config('error_template')
if not et:
return "%s %s\n%s" % (code, st... | def render_error_page(code, exc, mimetype='text/html', traceback='') | Render the error page | 2.813825 | 2.790542 | 1.008344 |
if six.PY3:
value = str(value)
else:
value = unicode(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = to_remove.sub('', value).strip().lower()
return remove_dup.sub('-', value) | def slugify(value) | Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace. | 2.918641 | 3.002679 | 0.972012 |
import giotto
from giotto.utils import random_string, switchout_keyvalue
from django.conf import settings
setattr(giotto, '_config', GiottoSettings())
if not module_name:
# For testing. No settings will be set.
return
project_module = importlib.import_module(module_name)
... | def initialize(module_name=None) | Build the giotto settings object. This function gets called
at the very begining of every request cycle. | 2.731219 | 2.656926 | 1.027962 |
import giotto
return getattr(giotto._config, item, default) or default | def get_config(item, default=None) | Use this function to get values from the config object. | 14.791362 | 13.37048 | 1.10627 |
def get_user(username):
try:
return User.objects.get(username=username)
except ObjectDoesNotExist as e:
raise CommandError("This user doesn't exist in the database")
def get_fields_permissions(user):
try:
retu... | def handle(self, *args, **options) | dump fields permissions for a user | 3.132588 | 2.845351 | 1.10095 |
user = request.user
if not user.is_superuser and not user.is_anonymous():
valid = False
try:
ct = ContentType.objects.get_for_model(obj)
fpm = FilterPermissionModel.objects.get(user=user,
... | def has_object_permission(self, request, view, obj) | check filter permissions | 3.809846 | 3.586331 | 1.062324 |
self.outputStream.write(self.linter.help())
sys.exit(32) | def displayHelp(self) | Output help message of twistedchecker. | 17.415289 | 13.186089 | 1.320732 |
# We patch the default pylint format checker.
patch_pylint_format.patch()
# register checkers
allowedMessages = list(self.allowedMessagesFromPylint)
for strChecker in self.checkers:
modname, classname = strChecker.split(".")
strModule = "twistedc... | def registerCheckers(self) | Register all checkers of TwistedChecker to C{PyLinter}.
@return: a list of allowed messages | 5.935513 | 5.062676 | 1.172406 |
self.linter._checkers[checker.name].remove(checker)
if checker in self.linter._reports:
del self.linter._reports[checker]
if checker in self.linter.options_providers:
self.linter.options_providers.remove(checker) | def unregisterChecker(self, checker) | Remove a checker from the list of registered checkers.
@param checker: the checker to remove | 3.772563 | 4.329163 | 0.87143 |
uselessCheckers = []
for checkerName in self.linter._checkers:
for checker in list(self.linter._checkers[checkerName]):
messagesOfChecker = set(checker.msgs)
if not messagesOfChecker.intersection(allowedMessages):
uselessCheckers.a... | def findUselessCheckers(self, allowedMessages) | Find checkers which generate no allowed messages.
@param allowedMessages: allowed messages
@return: useless checkers, remove them from pylint | 3.078642 | 3.197131 | 0.962939 |
uselessCheckers = self.findUselessCheckers(allowedMessages)
# Unregister these checkers
for checker in uselessCheckers:
self.unregisterChecker(checker) | def restrictCheckers(self, allowedMessages) | Unregister useless checkers to speed up twistedchecker.
@param allowedMessages: output messages allowed in twistedchecker | 5.308774 | 5.121546 | 1.036557 |
for checker in sum(list(self.linter._checkers.values()), []):
if isinstance(checker, checkerType):
return checker
return None | def getCheckerByName(self, checkerType) | Get checker by given name.
@checkerType: type of the checker | 5.659204 | 7.493448 | 0.75522 |
cfgParser = self.linter.cfgfile_parser
nameChecker = self.getCheckerByName(NameChecker)
if not nameChecker:
return
if patternsFunc:
regexFuncAdd = "|((%s).+)$" % "|".join(patternsFunc)
else:
regexFuncAdd = ""
if patternsClass:
... | def allowPatternsForNameChecking(self, patternsFunc, patternsClass) | Allow name exceptions by given patterns.
@param patternsFunc: patterns of special function names
@param patternsClass: patterns of special class names | 2.576331 | 2.55024 | 1.010231 |
pathList = []
for fileOrMod in filesOrModules:
if not os.path.exists(fileOrMod):
# May be given module is not not a path,
# then transform it to a path.
try:
filepath = file_from_modpath(fileOrMod.split('.'))
... | def getPathList(self, filesOrModules) | Transform a list of modules to path.
@param filesOrModules: a list of modules (may be foo/bar.py or
foo.bar) | 3.49785 | 3.418031 | 1.023352 |
pathList = self.getPathList(filesOrModules)
for path in pathList:
patternsFunc, patternsClass = findAllExceptions(path)
self.allowPatternsForNameChecking(patternsFunc, patternsClass) | def setNameExceptions(self, filesOrModules) | Find name exceptions in codes and allow them to be ignored
in checking.
@param filesOrModules: a list of modules (may be foo/bar.py or
foo.bar) | 10.200696 | 10.578557 | 0.96428 |
# set output stream.
if self.outputStream:
self.linter.reporter.set_output(self.outputStream)
try:
args = self.linter.load_command_line_configuration(args)
except SystemExit as exc:
if exc.code == 2: # bad options
exc.code = 3... | def run(self, args) | Setup the environment, and run pylint.
@param args: arguments will be passed to pylint
@type args: list of string | 5.410079 | 5.194113 | 1.041579 |
self.streamForDiff = NativeStringIO()
self.linter.reporter.set_output(self.streamForDiff) | def prepareDiff(self) | Prepare to run the checker and get diff results. | 14.12157 | 10.984745 | 1.285562 |
try:
oldWarnings = self.parseWarnings(self._readDiffFile())
except:
sys.stderr.write(self.errorResultRead % self.diffOption)
return 1
newWarnings = self.parseWarnings(self.streamForDiff.getvalue())
diffWarnings = self.generateDiff(oldWarning... | def showDiffResults(self) | Show results when diff option on. | 5.017379 | 4.770885 | 1.051666 |
with open(self.diffOption) as f:
content = f.read()
return content | def _readDiffFile(self) | Read content of diff file.
This is here to help with testing.
@return: File content.
@rtype: c{str} | 6.771525 | 8.396458 | 0.806474 |
diffWarnings = {}
for modulename in newWarnings:
diffInModule = (
newWarnings[modulename] -
oldWarnings.get(modulename, set()))
if diffInModule:
diffWarnings[modulename] = diffInModule
return diffWarnings | def generateDiff(self, oldWarnings, newWarnings) | Generate diff between given two lists of warnings.
@param oldWarnings: parsed old warnings
@param newWarnings: parsed new warnings
@return: a dict object of diff | 3.807895 | 5.134523 | 0.741626 |
warnings = {}
currentModule = None
warningsCurrentModule = []
for line in result.splitlines():
if line.startswith(self.prefixModuleName):
# Save results for previous module
if currentModule:
warnings[currentModule] ... | def parseWarnings(self, result) | Transform result in string to a dict object.
@param result: a list of warnings in string
@return: a dict of warnings | 2.97166 | 3.181701 | 0.933985 |
lines = []
for modulename in sorted(warnings):
lines.append(self.prefixModuleName + modulename)
lines.extend(sorted(warnings[modulename],
key=lambda x: x.split(":")[1]))
return "\n".join(lines) | def formatWarnings(self, warnings) | Format warnings to a list of results.
@param warnings: a dict of warnings produced by parseWarnings
@return: a list of warnings in string | 4.837086 | 5.504298 | 0.878783 |
return readlengths[np.where(np.cumsum(readlengths) >= 0.5 * np.sum(readlengths))[0][0]] | def get_N50(readlengths) | Calculate read length N50.
Based on https://github.com/PapenfussLab/Mungo/blob/master/bin/fasta_stats.py | 3.205196 | 3.390114 | 0.945454 |
return df[df[columnname] < (np.median(df[columnname]) + 3 * np.std(df[columnname]))] | def remove_length_outliers(df, columnname) | Remove records with length-outliers above 3 standard deviations from the median. | 2.553121 | 2.112147 | 1.20878 |
if quals:
mq = -10 * log(sum([tab[q] for q in quals]) / len(quals), 10)
if qround:
return round(mq)
else:
return mq
else:
return None | def ave_qual(quals, qround=False, tab=errs_tab(128)) | Calculate average basecall quality of a read.
Receive the integer quality scores of a read and return the average quality for that read
First convert Phred scores to probabilities,
calculate average error probability
convert average back to Phred scale | 3.116261 | 3.635681 | 0.857133 |
if outputfile == 'stdout':
output = sys.stdout
else:
output = open(outputfile, 'wt')
stats = [Stats(df) for df in datadfs]
features = {
"Number of reads": "number_of_reads",
"Total bases": "number_of_bases",
"Total bases aligned": "number_of_bases_aligned",
... | def write_stats(datadfs, outputfile, names=[]) | Call calculation functions and write stats file.
This function takes a list of DataFrames,
and will create a column for each in the tab separated output. | 3.210287 | 3.25421 | 0.986503 |
code = text.split(" ")[0]
lineOffset = self.report.line_offset
self.warnings.append((lineOffset + lineNumber,
offset + 1, code, text)) | def errorRecorder(self, lineNumber, offset, text, check) | A function to override report_error in pycodestyle.
And record output warnings.
@param lineNumber: line number
@param offset: column offset
@param text: warning message
@param check: check object in pycodestyle | 8.59503 | 8.1717 | 1.051804 |
# Set a stream to replace stdout, and get results in it
stdoutBak = sys.stdout
streamResult = StringIO()
sys.stdout = streamResult
try:
pycodestyle.Checker.check_all(self)
finally:
sys.stdout = stdoutBak | def run(self) | Run pycodestyle checker and record warnings. | 9.429738 | 6.522798 | 1.445658 |
recorder = PyCodeStyleWarningRecorder(node.file)
self._outputMessages(recorder.warnings, node) | def visit_module(self, node) | A interface will be called when visiting a module.
@param node: The module node to check. | 39.467186 | 53.300827 | 0.740461 |
if not warnings:
# No warnings were found
return
for warning in warnings:
linenum, offset, msgidInPyCodeStyle, text = warning
if text.startswith(msgidInPyCodeStyle):
# If the PyCodeStyle code is at the start of the text, trim it o... | def _outputMessages(self, warnings, node) | Map pycodestyle results to messages in pylint, then output them.
@param warnings: it should be a list of tuple including
line number and message id | 4.036926 | 3.811345 | 1.059187 |
if data is None:
data = {}
cursor = native.cursor(cursor_factory=DictCursor)
# register the hstore option
try:
register_hstore(cursor, unicode=True)
except pg.ProgrammingError:
log.warning('HSTORE is not supported in this version of ... | def _execute(self,
native,
command,
data=None,
returning=True,
mapper=dict) | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
autoCommit | <bool> | commit database changes immediately
autoClose | <bool> | closes connections immediate... | 3.187879 | 3.23778 | 0.984588 |
if not pg:
raise orb.errors.BackendNotFound('psycopg2 is not installed.')
if db.timeout():
os.environ['PGOPTIONS'] = '-c statement_timeout={0}'.format(db.timeout())
# create the python connection
try:
return pg.connect(database=db.name(),
... | def _open(self, db, writeAccess=False) | Handles simple, SQL specific connection creation. This will not
have to manage thread information as it is already managed within
the main open method for the SQLBase class.
:param db | <orb.Database>
:return <variant> | backend specific database connection | 4.073211 | 3.9346 | 1.035229 |
levels = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
}
try:
return levels[str_level.upper()]
except KeyError:
pass
except AttributeError:
if str_... | def log_level_from_string(str_level) | Returns the proper log level core based on a given string
:param str_level: Log level string
:return: The log level code | 1.871663 | 2.083565 | 0.898299 |
package_x = package.split('.')
package_conf = {}
package_conf['class'] = package_x[-1]
package_conf['module'] = '.'.join(package_x[:-1][:])
return package_conf | def get_config_from_package(package) | Breaks a package string in module and class.
:param package: A package string.
:return: A config dict with class and module. | 3.842399 | 3.509116 | 1.094976 |
import importlib
module = importlib.import_module(module)
return getattr(module, class_name) | def get_class_from_module(module, class_name) | Returns a class from a module and a class name parameters.
This function is used by get_class_from_config and get_class_from_name.
Example:
>>> get_class_from_module("my.module", "MyClass")
:param basestring module: The module name.
:param basestring class_name: The class name.
:return: The cl... | 2.790322 | 3.407669 | 0.818836 |
result = None
with open(path, 'r') as steam:
result = yaml.safe_load(steam)
return result | def load_yaml_config_file(path) | Returns the parsed structure from a yaml config file.
:param path: Path where the yaml file is located.
:return: The yaml configuration represented by the yaml file. | 3.768019 | 4.120615 | 0.914431 |
if 'components' in config_data:
process_components_config_section(config, config_data['components'])
if 'data' in config_data:
process_data_config_section(config, config_data['data'])
if 'log' in config_data:
process_log_config_section(config, config_data['log'])
if 'managem... | def process_config(config, config_data) | Populates config with data from the configuration data dict. It handles
components, data, log, management and session sections from the
configuration data.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param config_data: The configura... | 1.685158 | 1.404744 | 1.19962 |
process_config(config, config_data)
# If apps is on config data, this is running o multi app mode
if 'apps' in config_data:
config.app['multi'] = True
process_apps_config_session(config, config_data['apps'])
else:
# If not the app definition is on the firenado config file
... | def process_app_config(config, config_data) | Populates config with data from the configuration data dict. It handles
everything that process_config does plus application section.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param config_data: The configuration data loaded from a co... | 6.266129 | 6.806574 | 0.9206 |
if 'addresses' in app_config:
config.app['addresses'] = app_config['addresses']
if 'component' in app_config:
config.app['component'] = app_config['component']
if 'data' in app_config:
if 'sources' in app_config['data']:
config.app['data']['sources'] = app_config['da... | def process_app_config_section(config, app_config) | Processes the app section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param app_config: App section from a config data dict. | 1.675402 | 1.684404 | 0.994656 |
for component_config in components_config:
if 'id' not in component_config:
raise Exception('The component %s was defined without an id.' %
component_config)
component_id = component_config['id']
if component_id not in config.components:
... | def process_components_config_section(config, components_config) | Processes the components section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param components_config: Data section from a config data dict. | 2.020948 | 2.085134 | 0.969217 |
if 'connectors' in data_config:
for connector in data_config['connectors']:
config.data['connectors'][
connector['name']] = get_config_from_package(
connector['class'])
if 'sources' in data_config:
if data_config['sources']:
for source... | def process_data_config_section(config, data_config) | Processes the data configuration section from the configuration
data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param data_config: Data configuration section from a config data dict. | 2.993327 | 3.070423 | 0.974891 |
if 'format' in log_config:
config.log['format'] = log_config['format']
if 'level' in log_config:
config.log['level'] = log_level_from_string(log_config['level']) | def process_log_config_section(config, log_config) | Processes the log section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param log_config: Log section from a config data dict. | 2.441359 | 2.77303 | 0.880394 |
if 'commands' in management_config:
for command in management_config['commands']:
config.management['commands'].append(command) | def process_management_config_section(config, management_config) | Processes the management section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param management_config: Management section from a config data dict. | 3.966794 | 4.550949 | 0.871641 |
# Setting session type as file by default
config.session['type'] = 'file'
if 'enabled' in session_config:
config.session['enabled'] = session_config['enabled']
if 'type' in session_config:
config.session['type'] = session_config['type']
if config.session['type'] == 'file':
... | def process_session_config_section(config, session_config) | Processes the session section from the configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param session_config: Session configuration section from a config data
dict. | 1.753595 | 1.75479 | 0.999319 |
if data is None:
data = {}
with native.cursor() as cursor:
log.debug('***********************')
log.debug(command % data)
log.debug('***********************')
try:
rowcount = 0
for cmd in command.split... | def _execute(self,
native,
command,
data=None,
returning=True,
mapper=dict) | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
:return [{<str> key: <variant>, ..}, ..], <int> count | 3.509433 | 3.606446 | 0.9731 |
if not pymysql:
raise orb.errors.BackendNotFound('psycopg2 is not installed.')
# create the python connection
try:
return pymysql.connect(db=db.name(),
user=db.username(),
passwd=db.password()... | def _open(self, db, writeAccess=False) | Handles simple, SQL specific connection creation. This will not
have to manage thread information as it is already managed within
the main open method for the SQLBase class.
:param db | <orb.Database>
:return <variant> | backend specific database connection | 3.667493 | 3.508628 | 1.045279 |
logger.debug("Opening script %s." % script_path)
with open(script_path, "r") as stream:
sql_command = ""
for line in stream:
# Ignore commented lines
if not line.startswith("--") and line.strip("\n"):
# Append line to the command string
... | def run_script(script_path, session, handle_command=None, handle_line=None) | Run a script file using a valid sqlalchemy session.
Based on https://bit.ly/2CToAhY.
See also sqlalchemy transaction control: https://bit.ly/2yKso0A
:param script_path: The path where the script is located
:param session: A sqlalchemy session to execute the sql commands from the
script
:param ... | 2.679257 | 2.634248 | 1.017086 |
for commands_conf in firenado.conf.management['commands']:
logger.debug("Loading %s commands from %s." % (
commands_conf['name'],
commands_conf['module']
))
exec('import %s' % commands_conf['module'])
command_index = 1
for arg in sys.argv[1:]:
com... | def run_from_command_line() | Run Firenado's management commands from a command line | 3.144603 | 2.967559 | 1.05966 |
loader = template.Loader(os.path.join(
firenado.conf.ROOT, 'management', 'templates', 'help'))
return loader.load("header.txt").generate(
parser=parser, usage_message=usage_message, usage=usage,
firenado_version=".".join(map(str, firenado.__version__))).decode(
sys.stdout.en... | def get_command_header(parser, usage_message="", usage=False) | Return the command line header
:param parser:
:param usage_message:
:param usage:
:return: The command header | 4.283769 | 4.490456 | 0.953972 |
help_header_message = get_command_header(parser, "command", usage)
loader = template.Loader(os.path.join(
firenado.conf.ROOT, 'management', 'templates', 'help'))
command_template = " {0.name:15}{0.description:40}"
help_message = loader.load("main_command_help.txt").generate(
comman... | def show_command_line_usage(parser, usage=False) | Show the command line help | 6.510602 | 6.441277 | 1.010763 |
for category, commands in iteritems(command_categories):
for existing_command in commands:
if existing_command.match(command):
return True
return False | def command_exists(command) | Check if the given command was registered. In another words if it
exists. | 5.091858 | 4.971365 | 1.024237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.