code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, version_id)
return g.obj | def protect_api(uuid=None, **kwargs) | Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory. | 8.016666 | 7.390938 | 1.084662 |
if hasattr(g, 'obj'):
obj = g.obj
else:
obj = protect_api(key)
fp = obj.file.storage().open('rb')
# If ImageMagick with Wand is installed, extract first page
# for PDF/text.
if HAS_IMAGEMAGICK and obj.mimetype in ['application/pdf', 'text/plain']:
first_page = Imag... | def image_opener(key) | Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object. | 6.661941 | 6.947443 | 0.958905 |
# If we are on unix use mdbtools instead #
if os.name == "posix":
mdb_tables = sh.Command("mdb-tables")
tables_list = mdb_tables('-1', self.path).split('\n')
condition = lambda t: t and not t.startswith('MSys')
return [t.lower() for t in tables... | def tables(self) | The complete list of tables. | 7.017766 | 6.942555 | 1.010833 |
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | def table_as_df(self, table_name) | Return a table as a dataframe. | 4.787472 | 4.177656 | 1.145971 |
df.to_sql(table_name, con=self.own_conn) | def insert_df(self, table_name, df) | Create a table and populate it with data from a dataframe. | 8.100907 | 6.479557 | 1.250225 |
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | def count_rows(self, table_name) | Return the number of entries in a table by counting them. | 3.593898 | 3.272377 | 1.098253 |
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | def tables_with_counts(self) | Return the number of entries in all table. | 4.384076 | 3.683054 | 1.190337 |
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if destination is None: destination = self.replace_extension('sqlite')
# Delete if it exists #
destination.remove()
# Method with shell ... | def convert_to_sqlite(self, destination=None, method="shell", progress=False) | Who wants to use Access when you can deal with SQLite databases instead? | 4.301889 | 4.33822 | 0.991625 |
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | def sqlite_by_shell(self, destination) | Method with shell and a temp file. This is hopefully fast. | 11.798128 | 11.875034 | 0.993524 |
db = SQLiteDatabase(destination)
db.create()
for script in self.sqlite_dump_string(progress): db.cursor.executescript(script)
db.close() | def sqlite_by_object(self, destination, progress) | This is probably not very fast. | 6.666599 | 6.201937 | 1.074922 |
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | def sqlite_by_df(self, destination, progress) | Is this fast? | 6.017264 | 5.324717 | 1.130063 |
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds things up when importing #
script_path.append("\n\n\nBEGIN TRANSACTION;\n")
# Then export every table #
for table in self.tables:
... | def sqlite_dump_shell(self, script_path) | Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*. | 5.37162 | 5.277949 | 1.017748 |
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transaction, speeds things up when importing #
yield "BEGIN TRANSACTION;\n"
# Then export every table #
mdb_export = sh.Command("mdb-... | def sqlite_dump_string(self, progress) | Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string. | 5.822747 | 5.197624 | 1.120271 |
# Run commands #
wsl = sh.Command("wsl.exe")
table_schema = wsl("-e", "mdb-schema", "-T", table_name, source.wsl_style, "access")
table_contents = wsl("-e", "mdb-export", "-I", "access", source.wsl_style, table_name)
# Filter #
table_schema = ' '.join(l for l i... | def import_table(self, source, table_name) | Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment. | 5.508674 | 4.822058 | 1.142391 |
mdb_gz_b64 =
pristine = StringIO()
pristine.write(base64.b64decode(mdb_gz_b64))
pristine.seek(0)
pristine = gzip.GzipFile(fileobj=pristine, mode='rb')
with open(destination, 'wb') as handle: shutil.copyfileobj(pristine, handle)
return cls(destination) | def create(cls, destination) | Create a new empty MDB at destination. | 3.522118 | 3.419635 | 1.029969 |
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory = self.factory
return result | def tables(self) | The complete list of SQL tables. | 3.281069 | 2.907616 | 1.128439 |
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | def new_connection(self) | Make a new connection. | 3.634587 | 3.43094 | 1.059356 |
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
download_from_url(self.retrieve, self.path, progress=True)
else: raise Exception("The file '" + self.path + "' does not exist.")
self.check_format... | def prepare(self) | Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5. | 5.237936 | 3.749298 | 1.397044 |
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we want it empty #
if columns is None:
self.touch()
# Make the table #
else:
... | def create(self, columns=None, type_map=None, overwrite=False) | Create a new database with a certain schema. | 5.953587 | 6.292148 | 0.946193 |
# Check types mapping #
if type_map is None and isinstance(columns, dict): types = columns
if type_map is None: types = {}
# Safe or unsafe #
if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);'
else: query =... | def add_table(self, name, columns, type_map=None, if_not_exists=False) | Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'}) | 4.214443 | 4.082146 | 1.032409 |
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A PRAGMA statement will implicitly issue a commit, don't use #
self.own_cursor.execute('SELECT * from "%s" LIMIT 1;' % table)
columns = [x[0] for x in se... | def get_columns_of_table(self, table=None) | Return the list of columns for a particular table
by querying the SQL for the complete list of column names. | 5.80726 | 5.516838 | 1.052643 |
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
# Default columns #
question_marks = ','.join('?' for c in columns)
cols = ','.join('"' + c + '"' for c in columns... | def add(self, entries, table=None, columns=None, ignore=False) | Add entries to a table.
The *entries* variable should be an iterable. | 3.870464 | 3.842168 | 1.007365 |
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | def add_by_steps(self, entries_by_step, table=None, columns=None) | Add entries to the main table.
The *entries* variable should be an iterable yielding iterables. | 3.902117 | 3.519751 | 1.108635 |
if table is None: table = self.main_table
self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table)
return int(self.own_cursor.fetchone()[0]) | def count_entries(self, table=None) | How many rows in a table. | 3.250221 | 2.868847 | 1.132936 |
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | def get_first(self, table=None) | Just the first entry. | 3.915304 | 3.479833 | 1.125142 |
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | def get_last(self, table=None) | Just the last entry. | 3.895445 | 3.405023 | 1.144029 |
if table is None: table = self.main_table
self.own_cursor.execute('SELECT * from "%s" LIMIT 1 OFFSET %i;' % (self.main_table, num))
return self.own_cursor.fetchone() | def get_number(self, num, table=None) | Get a specific entry by its number. | 4.138539 | 3.509022 | 1.1794 |
if table is None: table = self.main_table
if column is None: column = "id"
if isinstance(key, basestring): key = key.replace("'","''")
query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;'
query = query % (table, column, key)
self.own_cursor.execute(query)
... | def get_entry(self, key, column=None, table=None) | Get a specific entry. | 3.218487 | 3.035504 | 1.060281 |
df.to_sql(table_name, con=self.own_connection) | def insert_df(self, table_name, df) | Create a table and populate it with data from a dataframe. | 8.276418 | 6.498227 | 1.273643 |
command =
ordered = ','.join(map(str,ids))
rowids = '\n'.join("WHEN '%s' THEN %s" % (row,i) for i,row in enumerate(ids))
command = command % (ordered, rowids) | def get_and_order(self, ids, column=None, table=None) | Get specific entries and order them in the same way. | 7.66867 | 7.686358 | 0.997699 |
query = "SELECT * FROM `%s`" % table_name.lower()
df = pandas.read_sql(query, source.connection)
df.to_sql(table_name, con=self.own_connection) | def import_table(self, source, table_name) | Copy a table from another SQLite database to this one. | 4.523333 | 4.396662 | 1.028811 |
if status_code is None:
status_code = self.status_code
if message is None:
message = self.message
if headers is None:
headers = self.headers
response = flask.jsonify({
'status_code': status_code,
'error': repr(self),
... | def jsonify(self, status_code=None, message=None, headers=None) | Returns a representation of the error in a jsonic form that is
compatible with flask's error handling.
Keyword arguments allow custom error handlers to override parts of the
exception when it is jsonified | 1.747822 | 1.797652 | 0.97228 |
def _handler(error, tasks=[]):
[t(error) for t in tasks]
return error.jsonify(), error.status_code, error.headers
return functools.partial(_handler, tasks=tasks) | def build_error_handler(*tasks) | Provides a generic error function that packages a flask_buzz exception
so that it can be handled nicely by the flask error handler::
app.register_error_handler(
FlaskBuzz, FlaskBuzz.build_error_handler(),
)
Additionally, extra tasks may be applied to the error p... | 7.192021 | 6.633336 | 1.084224 |
def _handler(error, tasks=[]):
[t(error) for t in tasks]
response = error.jsonify()
return flask.json.loads(response.get_data()), response.status_code
return functools.partial(_handler, tasks=tasks) | def build_error_handler_for_flask_restplus(*tasks) | Provides a generic error function that packages a flask_buzz exception
so that it can be handled by the flask-restplus error handler::
@api.errorhandler(SFBDError)
def do_it(error):
return SFBDError.build_error_handler_for_flask_restplus()()
or::
ap... | 5.578125 | 6.395469 | 0.8722 |
for buzz_subclass in [cls] + cls.__subclasses__():
api.errorhandler(buzz_subclass)(
cls.build_error_handler_for_flask_restplus(*tasks)
) | def register_error_handler_with_flask_restplus(cls, api, *tasks) | Registers an error handler for FlaskBuzz derived errors that are
currently imported. This is useful since flask-restplus
(prior to 0.11.0) does not handle derived errors. This is probably the
easist way to register error handlers for FlaskBuzz errors with
flask-restplus::
Fl... | 8.001007 | 5.556703 | 1.439884 |
opts = instance._meta
data = {}
for f in itertools.chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields and f.name not in fields:
continue
if f.name not in readonly_fields:
... | def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None) | Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provid... | 2.156982 | 2.346567 | 0.919208 |
if not name:
return list(servers.keys())
name = name.lower()
if name in servers:
info = servers[name]
else:
raise CityNotFound("Could not find the specified city: %s" % name)
return info | def find_info(name=None) | Find the needed city server information. | 4.547852 | 3.600809 | 1.263008 |
def _is_executable_file_or_link(exe):
# check for os.X_OK doesn't suffice because directory may executable
return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe))
if _is_executable_file_or_link(exe):
# executable in cwd or fullpath
return exe
#... | def which(
exe=None, default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin']
) | Return path of bin. Python clone of /usr/bin/which.
from salt.util - https://www.github.com/saltstack/salt - license apache
:param exe: Application to search PATHs for.
:type exe: str
:param default_path: Application to search PATHs for.
:type default_path: list
:rtype: str | 4.17402 | 4.298711 | 0.970994 |
proc = subprocess.Popen(
cmd,
shell=shell,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
creationflags=0,
bufsize=1,
cwd=cwd,
)
all_output = []
code = None
line = None
while code is None:
code = proc.poll()
# output... | def run(
cmd,
shell=False,
cwd=None,
log_in_real_time=True,
check_returncode=True,
callback=None,
) | Run 'cmd' in a shell and return the combined contents of stdout and
stderr (Blocking). Throws an exception if the command exits non-zero.
:param cmd: list of str (or single str, if shell==True) indicating
the command to run
:param shell: boolean indicating whether we are using advanced shell
... | 2.634624 | 2.558977 | 1.029561 |
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | def process(self, msg, kwargs) | Add additional context information for loggers. | 8.526649 | 7.809244 | 1.091866 |
'''
Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of the list.
'''
for t in self.terms:
sexp = t.pop(sexp... | def pop(self, sexp) | Notes: Sequence works a bit different than other nodes.
This method (like others) expectes a list. However, sequence matches
against the list, whereas other nodes try to match against elements
of the list. | 15.314672 | 2.109296 | 7.26056 |
result = self.git(self.default + ['branch', '-a', '--no-color'])
return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')] | def branches(self) | All branches in a list | 4.468982 | 4.165616 | 1.072826 |
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | def re_clone(self, repo_dir) | Clone again, somewhere else | 4.249534 | 4.031364 | 1.054118 |
yield self
if not self.parent: return
for node in self.parent.path: yield node | def path(self) | Iterate over all parent nodes and one-self. | 8.373472 | 4.90006 | 1.708851 |
if not self.parent: return
yield self.parent
for sibling in self.parent.children.values():
if sibling.name == self.name: continue
for node in sibling: yield node
for node in self.parent.others: yield node | def others(self) | Iterate over all nodes of the tree excluding one self and one's children. | 4.068381 | 3.249981 | 1.251817 |
yield self
if depth == 0: return
for child in self.children.values():
for node in child.get_children(depth-1): yield node | def get_children(self, depth=1) | Iterate over all children (until a certain level) and one-self. | 3.363406 | 2.783226 | 1.208456 |
if level == 1:
for child in self.children.values(): yield child
else:
for child in self.children.values():
for node in child.get_level(level-1): yield node | def get_level(self, level=2) | Get all nodes that are exactly this far away. | 3.025476 | 2.551831 | 1.18561 |
if length > 0:
for child in self.children.values(): child.trim(length-1)
else:
if hasattr(self, 'count'): self.count = sum(map(lambda x: x.count, self))
self.children = OrderedDict() | def trim(self, length) | Cut all branches over a certain length making new leaves at *length*. | 4.303393 | 3.733089 | 1.15277 |
if length == 0: raise Exception("Can't mend the root !")
if length == 1: return
self.children = OrderedDict((node.name, node) for node in self.get_level(length))
for child in self.children.values(): child.parent = self | def mend(self, length) | Cut all branches from this node to its children and adopt
all nodes at certain level. | 4.796649 | 4.412945 | 1.08695 |
raw_infos = self.fetcher.fetch(*self.info_files)
raw_info = parse.merge_infos(*raw_infos, info_dicts=info_dicts)
info = parse.parse_info(raw_info, apply_tag=apply_tag)
return info | def get_info(self, apply_tag=None, info_dicts=False) | Get data from distroinfo instance.
:param apply_tag: apply supplied tag to info
:param info_dicts: return packages and releases as dicts
:return: parsed info metadata | 4.079899 | 4.943685 | 0.825275 |
from . import runner
app_settings = {} if settings is None else settings.copy()
debug_mode = bool(app_settings.get('debug',
int(os.environ.get('DEBUG', 0)) != 0))
app_settings['debug'] = debug_mode
logging.config.dictConfig(_get_logging_config(debug_mode)... | def run(create_application, settings=None, log_config=None) | Run a Tornado create_application.
:param create_application: function to call to create a new
application instance
:param dict|None settings: optional configuration dictionary
that will be passed through to ``create_application``
as kwargs.
:param dict|None log_config: optional logg... | 2.967592 | 2.908199 | 1.020423 |
if '://' not in pip_url:
assert 'file:' not in pip_url
pip_url = pip_url.replace('git+', 'git+ssh://')
url, rev = super(GitRepo, cls).get_url_and_revision_from_pip_url(pip_url)
url = url.replace('ssh://', '')
elif 'github.com:' in pip_url:
... | def get_url_and_revision_from_pip_url(cls, pip_url) | Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes doesn't
work with a ssh:// scheme (e.g. Github). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
The manpage fo... | 3.303071 | 3.116414 | 1.059895 |
self.check_destination()
url = self.url
cmd = ['clone', '--progress']
if self.git_shallow:
cmd.extend(['--depth', '1'])
if self.tls_verify:
cmd.extend(['-c', 'http.sslVerify=false'])
cmd.extend([url, self.path])
self.info('Cloni... | def obtain(self) | Retrieve the repository, clone if doesn't exist. | 3.09876 | 2.833027 | 1.093798 |
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
return remotes | def remotes_get(self) | Return remotes like git remote -v.
:rtype: dict of tuples | 4.626216 | 5.056006 | 0.914994 |
try:
ret = self.run(['remote', 'show', '-n', remote])
lines = ret.split('\n')
remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip()
remote_push_url = lines[2].replace('Push URL: ', '').strip()
if remote_fetch_url != remote and remote... | def remote_get(self, remote='origin') | Get the fetch and push URL for a specified remote name.
:param remote: the remote name used to define the fetch and push URL
:type remote: str
:returns: remote name and url in tuple form
:rtype: tuple | 2.998852 | 2.963215 | 1.012027 |
url = self.chomp_protocol(url)
if self.remote_get(name):
self.run(['remote', 'rm', 'name'])
self.run(['remote', 'add', name, url])
return self.remote_get(remote=name) | def remote_set(self, url, name='origin') | Set remote with name and URL like git remote add.
:param url: defines the remote URL
:type url: str
:param name: defines the remote name.
:type name: str | 5.352074 | 4.927839 | 1.086089 |
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, path, query, frag = urlparse.urlsplit(url)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
if url.startswith(... | def chomp_protocol(url) | Return clean VCS url from RFC-style url
:param url: url
:type url: str
:rtype: str
:returns: url as VCS software would accept it
:seealso: #14 | 2.573963 | 2.605462 | 0.98791 |
'''
Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored.
'''
if color and self.color_term:
colorend = Logger.COLOR_END
else:
... | def _log(self, message, stream, color=None, newline=False) | Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored. | 4.87959 | 2.96711 | 1.64456 |
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | def info(self, message) | Logs an informational message to stdout.
This method should only be used by the Runner. | 9.292413 | 5.345573 | 1.738338 |
'''
Logs as whole test result as PASSED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout,
color=Logger.COLOR_GREEN_BOLD,
newline=True
) | def passed(self, message) | Logs as whole test result as PASSED.
This method should only be used by the Runner. | 11.050325 | 4.884251 | 2.26244 |
'''
Logs as whole test result as FAILED.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stderr,
color=Logger.COLOR_RED_BOLD,
newline=True
) | def failed(self, message) | Logs as whole test result as FAILED.
This method should only be used by the Runner. | 11.65463 | 5.053286 | 2.306347 |
from functools import wraps
@wraps(func)
def non_blocking_version(*args, **kwargs):
t = ReturnThread(target=func, args=args, kwargs=kwargs)
t.start()
return t
return non_blocking_version | def non_blocking(func) | Decorator to run a function in a different thread.
It can be used to execute a command in a non-blocking way
like this::
@non_blocking
def add_one(n):
print 'starting'
import time
time.sleep(2)
print 'ending'
return n+1
thread... | 2.656609 | 2.929224 | 0.906933 |
if self.serve_remote:
# Hand this off to whichever backend is being used.
url = self.remote_media_url(with_ssl)
else:
# Serving locally, just use the value in settings.py.
url = self.local_media_url
return url.rstrip('/') | def media_url(self, with_ssl=False) | Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
... | 6.056281 | 4.527474 | 1.337673 |
if not self.parent.loaded: self.parent.load()
logs = self.parent.p.logs_dir.flat_directories
logs.sort(key=lambda x: x.mod_time)
return logs | def logs(self) | Find the log directory and return all the logs sorted. | 7.739733 | 5.660491 | 1.367325 |
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**kwargs)
self.slurm_job.run_locally() | def run_locally(self, steps=None, **kwargs) | A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. | 8.024586 | 6.967711 | 1.151682 |
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.default_time
if 'job_name' not in params: params['job_name'] = self.job_... | def run_slurm(self, steps=None, **kwargs) | Run the steps via the SLURM queue. | 3.996471 | 4.019804 | 0.994196 |
opts = model._meta
# if there is no field called `ct_field` let the exception propagate
ct_field = opts.get_field(ct_field)
if not isinstance(ct_field, models.ForeignKey) or ct_field.related_model != ContentType:
raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
... | def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max... | Returns a ``GenericInlineFormSet`` for the given kwargs.
You must provide ``ct_field`` and ``fk_field`` if they are different from
the defaults ``content_type`` and ``object_id`` respectively. | 1.794431 | 1.839623 | 0.975434 |
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | def rename(self, name) | Set the name of the machine. | 5.164067 | 4.71583 | 1.095049 |
# Read the config file #
import sshconf
config = sshconf.read_ssh_config(os.path.expanduser(path))
# In case it doesn't exist #
if not config.host(self.instance_name): config.add(self.instance_name)
# Add the new DNS #
config.set(self.instance_name, Hostn... | def update_ssh_config(self, path="~/.ssh/config") | Put the DNS into the ssh config file. | 4.256258 | 3.967252 | 1.072848 |
widget.choices = FilterChoiceIterator(widget.choices, self.field)
return widget | def _update_widget_choices(self, widget) | Updates widget choices with special choice iterator that removes blank values and adds none value to clear
filter data.
:param widget: widget with choices
:return: updated widget with filter choices | 19.999676 | 10.720077 | 1.865628 |
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | def get_widget(self, request) | Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering. | 16.404007 | 6.131691 | 2.675283 |
return self._update_widget_choices(
forms.ModelChoiceField(
widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all()
).widget
) | def get_widget(self, request) | Table view is not able to get form field from reverse relation.
Therefore this widget returns similar form field as direct relation (ModelChoiceField).
Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to
count objects in the queryset. | 6.880417 | 4.566187 | 1.506819 |
m = re.match(r'(?:[^:]+://)?(.*)', url)
if m:
url = m.group(1)
if url.endswith('.git'):
url, _, _ = url.rpartition('.')
if url.endswith('-distgit'):
url, _, _ = url.rpartition('-')
if url.startswith('openstack/'):
# openstack is always special :-p
_, _, u... | def strip_project_url(url) | strip proto:// | openstack/ prefixes and .git | -distgit suffixes | 3.959574 | 3.009648 | 1.315627 |
if rev:
rev_options = ['-r', rev]
else:
rev_options = []
r = urlparse.urlsplit(url)
if hasattr(r, 'username'):
# >= Python-2.5
username, password = r.username, r.password
else:
netloc = r[1]
if '@' in netloc:
auth = netloc.split('@')[... | def get_rev_options(url, rev) | Return revision options.
from pip pip.vcs.subversion. | 2.315159 | 2.27733 | 1.016611 |
current_rev = self.run(['info', location])
_INI_RE = re.compile(r"^([^:]+):\s+(\S.*)$", re.M)
info_list = _INI_RE.findall(current_rev)
return int(dict(info_list)['Revision']) | def get_revision_file(self, location) | Return revision for a file. | 7.098075 | 6.432917 | 1.103399 |
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | def get_publish_path(self, obj) | publish_path joins the publish_paths for the chat type and the channel. | 7.562719 | 3.954843 | 1.912268 |
lang = lang.replace("-","_").lower()
return "{0}_{1}".format(attr,lang) | def trans_attr(attr, lang) | Returns the name of the translated attribute of the object <attribute>_<lang_iso_code>.
For example: name_es (name attribute in Spanish)
@param attr Attribute whose name will form the name translated attribute.
@param lang ISO Language code that will be the suffix of the translated attribute.
@return: string with t... | 4.391047 | 5.297936 | 0.828822 |
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths):
for module_path in FieldTranslation._model_module_paths:
FieldTranslation._modules[module_path] = importlib.import_module(module_path)
return True
return False | def _init_module_cache() | Module caching, it helps with not having to import again and again same modules.
@return: boolean, True if module caching has been done, False if module caching was already done. | 4.713928 | 4.58126 | 1.028959 |
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.source_model
# Getting the source model
module = self.get_python_module()
# Test if module has inside the model we are looking for
if hasattr(module, self.model):
# Setting of source model
self.source_model = ge... | def _load_source_model(self) | Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated). | 3.489698 | 3.18455 | 1.095821 |
if hasattr(self, "source_obj"):
self.source_text = getattr(self.source_obj, self.field)
return self.source_obj
self._load_source_model()
self.source_obj = self.source_model.objects.get(id=self.object_id)
return self.source_obj | def _load_source_object(self) | Loads related object in a dynamic attribute and returns it. | 3.056792 | 2.904292 | 1.052509 |
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
translation._load_source_model()
condition["id"] = translation.object_id
if not translation.source_model.objects.filter(**condition).exists()... | def delete_orphan_translations(condition=None) | Delete orphan translations.
This method needs refactoring to be improve its performance. | 4.676774 | 4.484775 | 1.042811 |
if condition is None:
condition = {}
# Number of updated translations
num_translations = 0
# Module caching
FieldTranslation._init_module_cache()
# Current languages dict
LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES)
if settings.LANGUAGE_CODE in LANGUAGES:
del LANGUAGES[... | def update_translations(condition=None) | Updates FieldTranslations table | 3.585848 | 3.55613 | 1.008357 |
# Model name
obj_classname = obj.__class__.__name__
# Module name
obj_module = obj.__module__
# Computation of MD5 of the source text
source_md5 = checksum(source_text)
# Translated text
translation = ""
# Translation text attribute name
field_lang = trans_attr(field,lang)
# If in sourc... | def factory(obj, field, source_text, lang, context="") | Static method that constructs a translation based on its contents. | 3.439306 | 3.356643 | 1.024627 |
# Now in UTC
now_datetime = timezone.now()
# If we are in a creation, assigns creation_datetime
if not self.id:
self.creation_datetime = now_datetime
# Las update datetime is always updated
self.last_update_datetime = now_datetime
# Current user is creator
# (get current user with django-cuse... | def save(self, *args, **kwargs) | Save object in database, updating the datetimes accordingly. | 5.160635 | 5.115139 | 1.008894 |
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
return raw_info | def parse_info(raw_info, apply_tag=None) | Parse raw rdoinfo metadata inplace.
:param raw_info: raw info to parse
:param apply_tag: tag to apply
:returns: dictionary containing all packages in rdoinfo | 4.416167 | 6.646675 | 0.664418 |
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_dicts = info
else:
info_dicts = info.copy()
packages = info.get('packages')
if packages:
info_dicts['packages'] = list2dict(packages, 'project')
releases = info.get('releases'... | def info2dicts(info, in_place=False) | Return info with:
1) `packages` list replaced by a 'packages' dict indexed by 'project'
2) `releases` list replaced by a 'releases' dict indexed by 'name' | 2.328977 | 1.883651 | 1.236416 |
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
info_lists = info
else:
info_lists = info.copy()
packages = info.get('packages')
if packages:
info_lists['packages'] = list(packages.values())
releases = info.get('releases')
... | def info2lists(info, in_place=False) | Return info with:
1) `packages` dict replaced by a 'packages' list with indexes removed
2) `releases` dict replaced by a 'releases' list with indexes removed
info2list(info2dicts(info)) == info | 2.133111 | 1.851844 | 1.151885 |
return "".join([c for c in text if re.match(r'\w', c)]) | def alphanumeric(text) | Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore. | 3.940982 | 4.590154 | 0.858573 |
# First replace characters that have specific effects with their repr #
text = re.sub("(\s)", lambda m: repr(m.group(0)).strip("'"), text)
# Make it a unicode string (the try supports python 2 and 3) #
try: text = text.decode('utf-8')
except AttributeError: pass
# Normalize it “
text = ... | def sanitize_text(text) | Make a safe representation of a string.
Note: the `\s` special character matches any whitespace character.
This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace). | 7.569469 | 6.942562 | 1.090299 |
step_one = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
step_two = re.sub('([a-z0-9])([A-Z])', r'\1_\2', step_one)
return step_two.lower() | def camel_to_snake(text) | Will convert CamelCaseStrings to snake_case_strings.
>>> camel_to_snake('CamelCase')
'camel_case'
>>> camel_to_snake('CamelCamelCase')
'camel_camel_case'
>>> camel_to_snake('Camel2Camel2Case')
'camel2_camel2_case'
>>> camel_to_snake('getHTTPResponseCode')
'get_http_response_code'
>>>... | 1.835258 | 2.191128 | 0.837586 |
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | def bool_to_unicode(b) | Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴 | 3.621098 | 4.054425 | 0.893122 |
props = prop.split('.')
if new_value:
if props[0] not in obj: obj[props[0]] = {}
if len(props)==1: obj[prop] = new_value
else: return access_dict_like_obj(obj[props[0]], '.'.join(props[1:]), new_value)
else:
if len(props)==1: return obj[prop]
else: return access_... | def access_dict_like_obj(obj, prop, new_value=None) | Access a dictionary like if it was an object with properties.
If no "new_value", then it's a getter, otherwise it's a setter.
>>> {'characters': {'cast': 'Jean-Luc Picard', 'featuring': 'Deanna Troi'}}
>>> access_dict_like_obj(startrek, 'characters.cast', 'Pierce Brosnan') | 1.749616 | 2.074405 | 0.84343 |
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | def all_combinations(items) | Generate all combinations of a given list of items. | 6.097717 | 6.874719 | 0.886977 |
if pad is None: pad = max(map(len, string.split('\n'))) + 1
return '\n'.join(('{0: <%i}' % pad).format(line) for line in string.split('\n')) | def pad_equal_whitespace(string, pad=None) | Given a multiline string, add whitespaces to every line
so that every line has the same length. | 2.914171 | 2.67438 | 1.089662 |
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | def concatenate_by_line(first, second) | Zip two strings together, line wise | 3.293132 | 2.716822 | 1.212127 |
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if count_string_diff(template, candidate) == 1:
pair = [template, strings.pop(i)... | def sort_string_by_pairs(strings) | Group a list of strings by pairs, by matching those with only
one character difference between each other together. | 3.719672 | 3.621172 | 1.027201 |
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | def count_string_diff(a,b) | Return the number of characters in two strings that don't exactly match | 2.710678 | 2.687545 | 1.008608 |
for sublist in L:
if hasattr(sublist, '__iter__'):
for item in iflatten(sublist): yield item
else: yield sublist | def iflatten(L) | Iterative flatten. | 2.85843 | 2.869576 | 0.996116 |
return [e for i, e in enumerate(L) if L.index(e) == i] | def uniquify_list(L) | Same order unique list using only a list compression. | 3.199758 | 2.905445 | 1.101297 |
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | def average(iterator) | Iterative mean. | 2.604825 | 2.580086 | 1.009588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.