repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_last | def get_last(self, table=None):
"""Just the last entry."""
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() | python | def get_last(self, table=None):
"""Just the last entry."""
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",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"query",
"=",
"'SELECT * FROM \"%s\" ORDER BY ROWID DESC LIMIT 1;'",
"%",
"table",
"return",
"self",
".",
"own_curso... | Just the last entry. | [
"Just",
"the",
"last",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L283-L287 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_number | def get_number(self, num, table=None):
"""Get a specific entry by its number."""
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() | python | def get_number(self, num, table=None):
"""Get a specific entry by its number."""
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",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT * from \"%s\" LIMIT 1 OFFSET %i;'",
"%",
... | Get a specific entry by its number. | [
"Get",
"a",
"specific",
"entry",
"by",
"its",
"number",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L289-L293 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_entry | def get_entry(self, key, column=None, table=None):
"""Get a specific entry."""
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;'
q... | python | def get_entry(self, key, column=None, table=None):
"""Get a specific entry."""
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;'
q... | [
"def",
"get_entry",
"(",
"self",
",",
"key",
",",
"column",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
"column",
"is",
"None",
":",
"column",
"=",
"\"id\"",
"if... | Get a specific entry. | [
"Get",
"a",
"specific",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L296-L304 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.insert_df | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_connection) | python | def insert_df(self, table_name, df):
"""Create a table and populate it with data from a dataframe."""
df.to_sql(table_name, con=self.own_connection) | [
"def",
"insert_df",
"(",
"self",
",",
"table_name",
",",
"df",
")",
":",
"df",
".",
"to_sql",
"(",
"table_name",
",",
"con",
"=",
"self",
".",
"own_connection",
")"
] | Create a table and populate it with data from a dataframe. | [
"Create",
"a",
"table",
"and",
"populate",
"it",
"with",
"data",
"from",
"a",
"dataframe",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L316-L318 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_and_order | def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
... | python | def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
... | [
"def",
"get_and_order",
"(",
"self",
",",
"ids",
",",
"column",
"=",
"None",
",",
"table",
"=",
"None",
")",
":",
"command",
"=",
"\"\"\"\n SELECT rowid, * from \"data\"\n WHERE rowid in (%s)\n ORDER BY CASE rowid\n %s\n END;\n \"\"\"",
... | Get specific entries and order them in the same way. | [
"Get",
"specific",
"entries",
"and",
"order",
"them",
"in",
"the",
"same",
"way",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L334-L345 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.import_table | def import_table(self, source, table_name):
"""Copy a table from another SQLite database to this one."""
query = "SELECT * FROM `%s`" % table_name.lower()
df = pandas.read_sql(query, source.connection)
df.to_sql(table_name, con=self.own_connection) | python | def import_table(self, source, table_name):
"""Copy a table from another SQLite database to this one."""
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",
")",
":",
"query",
"=",
"\"SELECT * FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"df",
"=",
"pandas",
".",
"read_sql",
"(",
"query",
",",
"source",
".",
"connection",
")",
... | Copy a table from another SQLite database to this one. | [
"Copy",
"a",
"table",
"from",
"another",
"SQLite",
"database",
"to",
"this",
"one",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L350-L354 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.jsonify | 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
... | python | 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
... | [
"def",
"jsonify",
"(",
"self",
",",
"status_code",
"=",
"None",
",",
"message",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"if",
"status_code",
"is",
"None",
":",
"status_code",
"=",
"self",
".",
"status_code",
"if",
"message",
"is",
"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 | [
"Returns",
"a",
"representation",
"of",
"the",
"error",
"in",
"a",
"jsonic",
"form",
"that",
"is",
"compatible",
"with",
"flask",
"s",
"error",
"handling",
"."
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L21-L44 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.build_error_handler | 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(),
)
Ad... | python | 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(),
)
Ad... | [
"def",
"build_error_handler",
"(",
"*",
"tasks",
")",
":",
"def",
"_handler",
"(",
"error",
",",
"tasks",
"=",
"[",
"]",
")",
":",
"[",
"t",
"(",
"error",
")",
"for",
"t",
"in",
"tasks",
"]",
"return",
"error",
".",
"jsonify",
"(",
")",
",",
"err... | 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... | [
"Provides",
"a",
"generic",
"error",
"function",
"that",
"packages",
"a",
"flask_buzz",
"exception",
"so",
"that",
"it",
"can",
"be",
"handled",
"nicely",
"by",
"the",
"flask",
"error",
"handler",
"::"
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L47-L72 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.build_error_handler_for_flask_restplus | 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.... | python | 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.... | [
"def",
"build_error_handler_for_flask_restplus",
"(",
"*",
"tasks",
")",
":",
"def",
"_handler",
"(",
"error",
",",
"tasks",
"=",
"[",
"]",
")",
":",
"[",
"t",
"(",
"error",
")",
"for",
"t",
"in",
"tasks",
"]",
"response",
"=",
"error",
".",
"jsonify",... | 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... | [
"Provides",
"a",
"generic",
"error",
"function",
"that",
"packages",
"a",
"flask_buzz",
"exception",
"so",
"that",
"it",
"can",
"be",
"handled",
"by",
"the",
"flask",
"-",
"restplus",
"error",
"handler",
"::"
] | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L75-L105 |
dusktreader/flask-buzz | flask_buzz/__init__.py | FlaskBuzz.register_error_handler_with_flask_restplus | 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 regi... | python | 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 regi... | [
"def",
"register_error_handler_with_flask_restplus",
"(",
"cls",
",",
"api",
",",
"*",
"tasks",
")",
":",
"for",
"buzz_subclass",
"in",
"[",
"cls",
"]",
"+",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"api",
".",
"errorhandler",
"(",
"buzz_subclass",
")",
... | 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... | [
"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",
"han... | train | https://github.com/dusktreader/flask-buzz/blob/0f6754e196b4da4bc3f3675b63389338d660f6f7/flask_buzz/__init__.py#L108-L124 |
matllubos/django-is-core | is_core/forms/models.py | humanized_model_to_dict | 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 b... | python | 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 b... | [
"def",
"humanized_model_to_dict",
"(",
"instance",
",",
"readonly_fields",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"opts",
"=",
"instance",
".",
"_meta",
"data",
"=",
"{",
"}",
"for",
"f",
"in",
"itertools",
".",
"chain",
"(",
... | 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... | [
"Returns",
"a",
"dict",
"containing",
"the",
"humanized",
"data",
"in",
"instance",
"suitable",
"for",
"passing",
"as",
"a",
"Form",
"s",
"initial",
"keyword",
"argument",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/models.py#L170-L196 |
codeforamerica/three | three/cities.py | find_info | def find_info(name=None):
"""Find the needed city server information."""
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 | python | def find_info(name=None):
"""Find the needed city server information."""
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",
")",
":",
"if",
"not",
"name",
":",
"return",
"list",
"(",
"servers",
".",
"keys",
"(",
")",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"servers",
":",
"info",
"=",
"servers... | Find the needed city server information. | [
"Find",
"the",
"needed",
"city",
"server",
"information",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/cities.py#L10-L19 |
vcs-python/libvcs | libvcs/util.py | which | 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 d... | python | 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 d... | [
"def",
"which",
"(",
"exe",
"=",
"None",
",",
"default_paths",
"=",
"[",
"'/bin'",
",",
"'/sbin'",
",",
"'/usr/bin'",
",",
"'/usr/sbin'",
",",
"'/usr/local/bin'",
"]",
")",
":",
"def",
"_is_executable_file_or_link",
"(",
"exe",
")",
":",
"# check for os.X_OK d... | 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 | [
"Return",
"path",
"of",
"bin",
".",
"Python",
"clone",
"of",
"/",
"usr",
"/",
"bin",
"/",
"which",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L22-L63 |
vcs-python/libvcs | libvcs/util.py | run | 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,... | python | 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,... | [
"def",
"run",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"log_in_real_time",
"=",
"True",
",",
"check_returncode",
"=",
"True",
",",
"callback",
"=",
"None",
",",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd... | 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
... | [
"Run",
"cmd",
"in",
"a",
"shell",
"and",
"return",
"the",
"combined",
"contents",
"of",
"stdout",
"and",
"stderr",
"(",
"Blocking",
")",
".",
"Throws",
"an",
"exception",
"if",
"the",
"command",
"exits",
"non",
"-",
"zero",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L116-L185 |
vcs-python/libvcs | libvcs/util.py | RepoLoggingAdapter.process | def process(self, msg, kwargs):
"""Add additional context information for loggers."""
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | python | def process(self, msg, kwargs):
"""Add additional context information for loggers."""
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",
")",
":",
"prefixed_dict",
"=",
"{",
"}",
"prefixed_dict",
"[",
"'repo_vcs'",
"]",
"=",
"self",
".",
"bin_name",
"prefixed_dict",
"[",
"'repo_name'",
"]",
"=",
"self",
".",
"name",
"kwargs",
"[",
... | Add additional context information for loggers. | [
"Add",
"additional",
"context",
"information",
"for",
"loggers",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/util.py#L105-L113 |
IwoHerka/sexpr | sexpr/types/sequence.py | Sequence.pop | 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.
'''
for t in self.terms:
... | python | 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.
'''
for t in self.terms:
... | [
"def",
"pop",
"(",
"self",
",",
"sexp",
")",
":",
"for",
"t",
"in",
"self",
".",
"terms",
":",
"sexp",
"=",
"t",
".",
"pop",
"(",
"sexp",
")",
"return",
"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. | [
"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",
... | train | https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/types/sequence.py#L11-L20 |
xapple/plumbing | plumbing/git.py | GitRepo.branches | def branches(self):
"""All branches in a list"""
result = self.git(self.default + ['branch', '-a', '--no-color'])
return [l.strip(' *\n') for l in result.split('\n') if l.strip(' *\n')] | python | def branches(self):
"""All branches in a list"""
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",
")",
":",
"result",
"=",
"self",
".",
"git",
"(",
"self",
".",
"default",
"+",
"[",
"'branch'",
",",
"'-a'",
",",
"'--no-color'",
"]",
")",
"return",
"[",
"l",
".",
"strip",
"(",
"' *\\n'",
")",
"for",
"l",
"in",
"... | All branches in a list | [
"All",
"branches",
"in",
"a",
"list"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L64-L67 |
xapple/plumbing | plumbing/git.py | GitRepo.re_clone | def re_clone(self, repo_dir):
"""Clone again, somewhere else"""
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | python | def re_clone(self, repo_dir):
"""Clone again, somewhere else"""
self.git('clone', self.remote_url, repo_dir)
return GitRepo(repo_dir) | [
"def",
"re_clone",
"(",
"self",
",",
"repo_dir",
")",
":",
"self",
".",
"git",
"(",
"'clone'",
",",
"self",
".",
"remote_url",
",",
"repo_dir",
")",
"return",
"GitRepo",
"(",
"repo_dir",
")"
] | Clone again, somewhere else | [
"Clone",
"again",
"somewhere",
"else"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/git.py#L87-L90 |
xapple/plumbing | plumbing/trees/__init__.py | Node.path | def path(self):
"""Iterate over all parent nodes and one-self."""
yield self
if not self.parent: return
for node in self.parent.path: yield node | python | def path(self):
"""Iterate over all parent nodes and one-self."""
yield self
if not self.parent: return
for node in self.parent.path: yield node | [
"def",
"path",
"(",
"self",
")",
":",
"yield",
"self",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"for",
"node",
"in",
"self",
".",
"parent",
".",
"path",
":",
"yield",
"node"
] | Iterate over all parent nodes and one-self. | [
"Iterate",
"over",
"all",
"parent",
"nodes",
"and",
"one",
"-",
"self",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L40-L44 |
xapple/plumbing | plumbing/trees/__init__.py | Node.others | def others(self):
"""Iterate over all nodes of the tree excluding one self and one's children."""
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
... | python | def others(self):
"""Iterate over all nodes of the tree excluding one self and one's children."""
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
... | [
"def",
"others",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"yield",
"self",
".",
"parent",
"for",
"sibling",
"in",
"self",
".",
"parent",
".",
"children",
".",
"values",
"(",
")",
":",
"if",
"sibling",
".",
"name",
"... | Iterate over all nodes of the tree excluding one self and one's children. | [
"Iterate",
"over",
"all",
"nodes",
"of",
"the",
"tree",
"excluding",
"one",
"self",
"and",
"one",
"s",
"children",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L47-L54 |
xapple/plumbing | plumbing/trees/__init__.py | Node.get_children | def get_children(self, depth=1):
"""Iterate over all children (until a certain level) and one-self."""
yield self
if depth == 0: return
for child in self.children.values():
for node in child.get_children(depth-1): yield node | python | def get_children(self, depth=1):
"""Iterate over all children (until a certain level) and one-self."""
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",
")",
":",
"yield",
"self",
"if",
"depth",
"==",
"0",
":",
"return",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"for",
"node",
"in",
"child",
".",
"get_chi... | Iterate over all children (until a certain level) and one-self. | [
"Iterate",
"over",
"all",
"children",
"(",
"until",
"a",
"certain",
"level",
")",
"and",
"one",
"-",
"self",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L56-L61 |
xapple/plumbing | plumbing/trees/__init__.py | Node.get_level | def get_level(self, level=2):
"""Get all nodes that are exactly this far away."""
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 | python | def get_level(self, level=2):
"""Get all nodes that are exactly this far away."""
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",
")",
":",
"if",
"level",
"==",
"1",
":",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"yield",
"child",
"else",
":",
"for",
"child",
"in",
"self",
".",
"chil... | Get all nodes that are exactly this far away. | [
"Get",
"all",
"nodes",
"that",
"are",
"exactly",
"this",
"far",
"away",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L63-L69 |
xapple/plumbing | plumbing/trees/__init__.py | Node.trim | def trim(self, length):
"""Cut all branches over a certain length making new leaves at *length*."""
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.ch... | python | def trim(self, length):
"""Cut all branches over a certain length making new leaves at *length*."""
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.ch... | [
"def",
"trim",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
">",
"0",
":",
"for",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"child",
".",
"trim",
"(",
"length",
"-",
"1",
")",
"else",
":",
"if",
"hasattr",
"... | Cut all branches over a certain length making new leaves at *length*. | [
"Cut",
"all",
"branches",
"over",
"a",
"certain",
"length",
"making",
"new",
"leaves",
"at",
"*",
"length",
"*",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L88-L94 |
xapple/plumbing | plumbing/trees/__init__.py | Node.mend | def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
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))
... | python | def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
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))
... | [
"def",
"mend",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Can't mend the root !\"",
")",
"if",
"length",
"==",
"1",
":",
"return",
"self",
".",
"children",
"=",
"OrderedDict",
"(",
"(",
"node",
"... | Cut all branches from this node to its children and adopt
all nodes at certain level. | [
"Cut",
"all",
"branches",
"from",
"this",
"node",
"to",
"its",
"children",
"and",
"adopt",
"all",
"nodes",
"at",
"certain",
"level",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/trees/__init__.py#L96-L102 |
softwarefactory-project/distroinfo | distroinfo/info.py | DistroInfo.get_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
"""
raw_infos = self.fetcher.fetch(*se... | python | 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
"""
raw_infos = self.fetcher.fetch(*se... | [
"def",
"get_info",
"(",
"self",
",",
"apply_tag",
"=",
"None",
",",
"info_dicts",
"=",
"False",
")",
":",
"raw_infos",
"=",
"self",
".",
"fetcher",
".",
"fetch",
"(",
"*",
"self",
".",
"info_files",
")",
"raw_info",
"=",
"parse",
".",
"merge_infos",
"(... | 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 | [
"Get",
"data",
"from",
"distroinfo",
"instance",
"."
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/info.py#L53-L64 |
sprockets/sprockets.http | sprockets/http/__init__.py | run | 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_applic... | python | 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_applic... | [
"def",
"run",
"(",
"create_application",
",",
"settings",
"=",
"None",
",",
"log_config",
"=",
"None",
")",
":",
"from",
".",
"import",
"runner",
"app_settings",
"=",
"{",
"}",
"if",
"settings",
"is",
"None",
"else",
"settings",
".",
"copy",
"(",
")",
... | 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... | [
"Run",
"a",
"Tornado",
"create_application",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/__init__.py#L10-L71 |
vcs-python/libvcs | libvcs/git.py | GitRepo.get_url_and_revision_from_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 r... | python | 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 r... | [
"def",
"get_url_and_revision_from_pip_url",
"(",
"cls",
",",
"pip_url",
")",
":",
"if",
"'://'",
"not",
"in",
"pip_url",
":",
"assert",
"'file:'",
"not",
"in",
"pip_url",
"pip_url",
"=",
"pip_url",
".",
"replace",
"(",
"'git+'",
",",
"'git+ssh://'",
")",
"ur... | 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... | [
"Prefixes",
"stub",
"URLs",
"like",
"user"
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L85-L107 |
vcs-python/libvcs | libvcs/git.py | GitRepo.obtain | def obtain(self):
"""Retrieve the repository, clone if doesn't exist."""
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... | python | def obtain(self):
"""Retrieve the repository, clone if doesn't exist."""
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... | [
"def",
"obtain",
"(",
"self",
")",
":",
"self",
".",
"check_destination",
"(",
")",
"url",
"=",
"self",
".",
"url",
"cmd",
"=",
"[",
"'clone'",
",",
"'--progress'",
"]",
"if",
"self",
".",
"git_shallow",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--depth... | Retrieve the repository, clone if doesn't exist. | [
"Retrieve",
"the",
"repository",
"clone",
"if",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L109-L134 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remotes_get | def remotes_get(self):
"""Return remotes like git remote -v.
:rtype: dict of tuples
"""
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
r... | python | def remotes_get(self):
"""Return remotes like git remote -v.
:rtype: dict of tuples
"""
remotes = {}
cmd = self.run(['remote'])
ret = filter(None, cmd.split('\n'))
for remote_name in ret:
remotes[remote_name] = self.remote_get(remote_name)
r... | [
"def",
"remotes_get",
"(",
"self",
")",
":",
"remotes",
"=",
"{",
"}",
"cmd",
"=",
"self",
".",
"run",
"(",
"[",
"'remote'",
"]",
")",
"ret",
"=",
"filter",
"(",
"None",
",",
"cmd",
".",
"split",
"(",
"'\\n'",
")",
")",
"for",
"remote_name",
"in"... | Return remotes like git remote -v.
:rtype: dict of tuples | [
"Return",
"remotes",
"like",
"git",
"remote",
"-",
"v",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L273-L285 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remote_get | 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
"""
try:
... | python | 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
"""
try:
... | [
"def",
"remote_get",
"(",
"self",
",",
"remote",
"=",
"'origin'",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",
"'show'",
",",
"'-n'",
",",
"remote",
"]",
")",
"lines",
"=",
"ret",
".",
"split",
"(",
"'\\n'",
")... | 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 | [
"Get",
"the",
"fetch",
"and",
"push",
"URL",
"for",
"a",
"specified",
"remote",
"name",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L287-L306 |
vcs-python/libvcs | libvcs/git.py | GitRepo.remote_set | 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
"""
url = self.chomp_protocol(url)
if self.remote_get(... | python | 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
"""
url = self.chomp_protocol(url)
if self.remote_get(... | [
"def",
"remote_set",
"(",
"self",
",",
"url",
",",
"name",
"=",
"'origin'",
")",
":",
"url",
"=",
"self",
".",
"chomp_protocol",
"(",
"url",
")",
"if",
"self",
".",
"remote_get",
"(",
"name",
")",
":",
"self",
".",
"run",
"(",
"[",
"'remote'",
",",... | 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 | [
"Set",
"remote",
"with",
"name",
"and",
"URL",
"like",
"git",
"remote",
"add",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L308-L323 |
vcs-python/libvcs | libvcs/git.py | GitRepo.chomp_protocol | 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
"""
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, pa... | python | 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
"""
if '+' in url:
url = url.split('+', 1)[1]
scheme, netloc, pa... | [
"def",
"chomp_protocol",
"(",
"url",
")",
":",
"if",
"'+'",
"in",
"url",
":",
"url",
"=",
"url",
".",
"split",
"(",
"'+'",
",",
"1",
")",
"[",
"1",
"]",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag",
"=",
"urlparse",
".",
"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 | [
"Return",
"clean",
"VCS",
"url",
"from",
"RFC",
"-",
"style",
"url"
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/git.py#L326-L348 |
confirm/ansibleci | ansibleci/logger.py | Logger._log | 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.
'''
if color and self.color_ter... | python | 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.
'''
if color and self.color_ter... | [
"def",
"_log",
"(",
"self",
",",
"message",
",",
"stream",
",",
"color",
"=",
"None",
",",
"newline",
"=",
"False",
")",
":",
"if",
"color",
"and",
"self",
".",
"color_term",
":",
"colorend",
"=",
"Logger",
".",
"COLOR_END",
"else",
":",
"color",
"="... | 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. | [
"Logs",
"the",
"message",
"to",
"the",
"sys",
".",
"stdout",
"or",
"sys",
".",
"stderr",
"stream",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L43-L65 |
confirm/ansibleci | ansibleci/logger.py | Logger.info | def info(self, message):
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | python | def info(self, message):
'''
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",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stdout",
")"
] | Logs an informational message to stdout.
This method should only be used by the Runner. | [
"Logs",
"an",
"informational",
"message",
"to",
"stdout",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L78-L87 |
confirm/ansibleci | ansibleci/logger.py | Logger.passed | def passed(self, message):
'''
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
... | python | def passed(self, message):
'''
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",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"color",
"=",
"Logger",
".",
"COLOR_GREEN_BOLD",
",",
"newli... | Logs as whole test result as PASSED.
This method should only be used by the Runner. | [
"Logs",
"as",
"whole",
"test",
"result",
"as",
"PASSED",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L89-L100 |
confirm/ansibleci | ansibleci/logger.py | Logger.failed | def failed(self, message):
'''
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
... | python | def failed(self, message):
'''
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",
")",
":",
"return",
"self",
".",
"_log",
"(",
"message",
"=",
"message",
".",
"upper",
"(",
")",
",",
"stream",
"=",
"sys",
".",
"stderr",
",",
"color",
"=",
"Logger",
".",
"COLOR_RED_BOLD",
",",
"newline... | Logs as whole test result as FAILED.
This method should only be used by the Runner. | [
"Logs",
"as",
"whole",
"test",
"result",
"as",
"FAILED",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/logger.py#L102-L113 |
xapple/plumbing | plumbing/thread.py | non_blocking | 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'
... | python | 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'
... | [
"def",
"non_blocking",
"(",
"func",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"func",
")",
"def",
"non_blocking_version",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"ReturnThread",
"(",
"target",
"=",
"fun... | 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... | [
"Decorator",
"to",
"run",
"a",
"function",
"in",
"a",
"different",
"thread",
".",
"It",
"can",
"be",
"used",
"to",
"execute",
"a",
"command",
"in",
"a",
"non",
"-",
"blocking",
"way",
"like",
"this",
"::"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/thread.py#L32-L55 |
sunlightlabs/django-mediasync | mediasync/backends/__init__.py | BaseClient.media_url | 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 T... | python | 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 T... | [
"def",
"media_url",
"(",
"self",
",",
"with_ssl",
"=",
"False",
")",
":",
"if",
"self",
".",
"serve_remote",
":",
"# Hand this off to whichever backend is being used.",
"url",
"=",
"self",
".",
"remote_media_url",
"(",
"with_ssl",
")",
"else",
":",
"# Serving loca... | 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
... | [
"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",
... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/backends/__init__.py#L69-L85 |
xapple/plumbing | plumbing/runner.py | Runner.logs | def logs(self):
"""Find the log directory and return all the logs sorted."""
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 | python | def logs(self):
"""Find the log directory and return all the logs sorted."""
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",
")",
":",
"if",
"not",
"self",
".",
"parent",
".",
"loaded",
":",
"self",
".",
"parent",
".",
"load",
"(",
")",
"logs",
"=",
"self",
".",
"parent",
".",
"p",
".",
"logs_dir",
".",
"flat_directories",
"logs",
".",
"sort",... | Find the log directory and return all the logs sorted. | [
"Find",
"the",
"log",
"directory",
"and",
"return",
"all",
"the",
"logs",
"sorted",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L108-L113 |
xapple/plumbing | plumbing/runner.py | Runner.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."""
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
... | python | 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."""
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
... | [
"def",
"run_locally",
"(",
"self",
",",
"steps",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"slurm_job",
"=",
"LoggedJobSLURM",
"(",
"self",
".",
"command",
"(",
"steps",
")",
",",
"base_dir",
"=",
"self",
".",
"parent",
".",
"p",
... | A convenience method to run the same result as a SLURM job
but locally in a non-blocking way. | [
"A",
"convenience",
"method",
"to",
"run",
"the",
"same",
"result",
"as",
"a",
"SLURM",
"job",
"but",
"locally",
"in",
"a",
"non",
"-",
"blocking",
"way",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L121-L128 |
xapple/plumbing | plumbing/runner.py | Runner.run_slurm | def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.d... | python | def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.d... | [
"def",
"run_slurm",
"(",
"self",
",",
"steps",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Optional extra SLURM parameters #",
"params",
"=",
"self",
".",
"extra_slurm_params",
"params",
".",
"update",
"(",
"kwargs",
")",
"# Mandatory extra SLURM parameters... | Run the steps via the SLURM queue. | [
"Run",
"the",
"steps",
"via",
"the",
"SLURM",
"queue",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/runner.py#L131-L147 |
matllubos/django-is-core | is_core/forms/generic.py | smart_generic_inlineformset_factory | 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... | python | 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... | [
"def",
"smart_generic_inlineformset_factory",
"(",
"model",
",",
"request",
",",
"form",
"=",
"ModelForm",
",",
"formset",
"=",
"BaseGenericInlineFormSet",
",",
"ct_field",
"=",
"'content_type'",
",",
"fk_field",
"=",
"'object_id'",
",",
"fields",
"=",
"None",
","... | 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. | [
"Returns",
"a",
"GenericInlineFormSet",
"for",
"the",
"given",
"kwargs",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/generic.py#L14-L66 |
xapple/plumbing | plumbing/ec2.py | InstanceEC2.rename | def rename(self, name):
"""Set the name of the machine."""
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | python | def rename(self, name):
"""Set the name of the machine."""
self.ec2.create_tags(Resources = [self.instance_id],
Tags = [{'Key': 'Name',
'Value': name}])
self.refresh_info() | [
"def",
"rename",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"ec2",
".",
"create_tags",
"(",
"Resources",
"=",
"[",
"self",
".",
"instance_id",
"]",
",",
"Tags",
"=",
"[",
"{",
"'Key'",
":",
"'Name'",
",",
"'Value'",
":",
"name",
"}",
"]",
"... | Set the name of the machine. | [
"Set",
"the",
"name",
"of",
"the",
"machine",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L70-L75 |
xapple/plumbing | plumbing/ec2.py | InstanceEC2.update_ssh_config | def update_ssh_config(self, path="~/.ssh/config"):
"""Put the DNS into the ssh config file."""
# 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.ad... | python | def update_ssh_config(self, path="~/.ssh/config"):
"""Put the DNS into the ssh config file."""
# 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.ad... | [
"def",
"update_ssh_config",
"(",
"self",
",",
"path",
"=",
"\"~/.ssh/config\"",
")",
":",
"# Read the config file #",
"import",
"sshconf",
"config",
"=",
"sshconf",
".",
"read_ssh_config",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
"# In... | Put the DNS into the ssh config file. | [
"Put",
"the",
"DNS",
"into",
"the",
"ssh",
"config",
"file",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L77-L87 |
matllubos/django-is-core | is_core/filters/default_filters.py | RelatedUIFilter._update_widget_choices | 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
"""
widget.choices... | python | 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
"""
widget.choices... | [
"def",
"_update_widget_choices",
"(",
"self",
",",
"widget",
")",
":",
"widget",
".",
"choices",
"=",
"FilterChoiceIterator",
"(",
"widget",
".",
"choices",
",",
"self",
".",
"field",
")",
"return",
"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 | [
"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",
":",... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L33-L42 |
matllubos/django-is-core | is_core/filters/default_filters.py | UIForeignKeyFilter.get_widget | def get_widget(self, request):
"""
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering.
"""
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | python | def get_widget(self, request):
"""
Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering.
"""
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | [
"def",
"get_widget",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"_update_widget_choices",
"(",
"self",
".",
"field",
".",
"formfield",
"(",
"widget",
"=",
"RestrictedSelectWidget",
")",
".",
"widget",
")"
] | Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering. | [
"Field",
"widget",
"is",
"replaced",
"with",
"RestrictedSelectWidget",
"because",
"we",
"not",
"want",
"to",
"use",
"modified",
"widgets",
"for",
"filtering",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L56-L61 |
matllubos/django-is-core | is_core/filters/default_filters.py | UIForeignObjectRelFilter.get_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 accor... | python | 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 accor... | [
"def",
"get_widget",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"_update_widget_choices",
"(",
"forms",
".",
"ModelChoiceField",
"(",
"widget",
"=",
"RestrictedSelectWidget",
",",
"queryset",
"=",
"self",
".",
"field",
".",
"related_model",
... | 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. | [
"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",
"... | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L76-L87 |
softwarefactory-project/distroinfo | distroinfo/query.py | strip_project_url | def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
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(... | python | def strip_project_url(url):
"""strip proto:// | openstack/ prefixes and .git | -distgit suffixes"""
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(... | [
"def",
"strip_project_url",
"(",
"url",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'(?:[^:]+://)?(.*)'",
",",
"url",
")",
"if",
"m",
":",
"url",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"url",
".",
"endswith",
"(",
"'.git'",
")",
":",
"ur... | strip proto:// | openstack/ prefixes and .git | -distgit suffixes | [
"strip",
"proto",
":",
"//",
"|",
"openstack",
"/",
"prefixes",
"and",
".",
"git",
"|",
"-",
"distgit",
"suffixes"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/query.py#L138-L150 |
vcs-python/libvcs | libvcs/svn.py | get_rev_options | def get_rev_options(url, rev):
"""Return revision options.
from pip pip.vcs.subversion.
"""
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.pas... | python | def get_rev_options(url, rev):
"""Return revision options.
from pip pip.vcs.subversion.
"""
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.pas... | [
"def",
"get_rev_options",
"(",
"url",
",",
"rev",
")",
":",
"if",
"rev",
":",
"rev_options",
"=",
"[",
"'-r'",
",",
"rev",
"]",
"else",
":",
"rev_options",
"=",
"[",
"]",
"r",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"hasattr",
"(",... | Return revision options.
from pip pip.vcs.subversion. | [
"Return",
"revision",
"options",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L146-L176 |
vcs-python/libvcs | libvcs/svn.py | SubversionRepo.get_revision_file | def get_revision_file(self, location):
"""Return revision for a file."""
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']) | python | def get_revision_file(self, location):
"""Return revision for a file."""
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",
")",
":",
"current_rev",
"=",
"self",
".",
"run",
"(",
"[",
"'info'",
",",
"location",
"]",
")",
"_INI_RE",
"=",
"re",
".",
"compile",
"(",
"r\"^([^:]+):\\s+(\\S.*)$\"",
",",
"re",
".",
"M",
")",
... | Return revision for a file. | [
"Return",
"revision",
"for",
"a",
"file",
"."
] | train | https://github.com/vcs-python/libvcs/blob/f7dc055250199bac6be7439b1d2240583f0bb354/libvcs/svn.py#L77-L85 |
The-Politico/django-slackchat-serializer | slackchat/serializers/channel.py | ChannelSerializer.get_publish_path | def get_publish_path(self, obj):
"""
publish_path joins the publish_paths for the chat type and the channel.
"""
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | python | def get_publish_path(self, obj):
"""
publish_path joins the publish_paths for the chat type and the channel.
"""
return os.path.join(
obj.chat_type.publish_path, obj.publish_path.lstrip("/")
) | [
"def",
"get_publish_path",
"(",
"self",
",",
"obj",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"obj",
".",
"chat_type",
".",
"publish_path",
",",
"obj",
".",
"publish_path",
".",
"lstrip",
"(",
"\"/\"",
")",
")"
] | publish_path joins the publish_paths for the chat type and the channel. | [
"publish_path",
"joins",
"the",
"publish_paths",
"for",
"the",
"chat",
"type",
"and",
"the",
"channel",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/serializers/channel.py#L37-L43 |
intelligenia/modeltranslation | modeltranslation/models.py | trans_attr | 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 ... | python | 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 ... | [
"def",
"trans_attr",
"(",
"attr",
",",
"lang",
")",
":",
"lang",
"=",
"lang",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
".",
"lower",
"(",
")",
"return",
"\"{0}_{1}\"",
".",
"format",
"(",
"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... | [
"Returns",
"the",
"name",
"of",
"the",
"translated",
"attribute",
"of",
"the",
"object",
"<attribute",
">",
"_<lang_iso_code",
">",
".",
"For",
"example",
":",
"name_es",
"(",
"name",
"attribute",
"in",
"Spanish",
")"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L50-L59 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._init_module_cache | 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.
"""
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len... | python | 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.
"""
# While there are not loaded modules, load these ones
if len(FieldTranslation._modules) < len... | [
"def",
"_init_module_cache",
"(",
")",
":",
"# While there are not loaded modules, load these ones",
"if",
"len",
"(",
"FieldTranslation",
".",
"_modules",
")",
"<",
"len",
"(",
"FieldTranslation",
".",
"_model_module_paths",
")",
":",
"for",
"module_path",
"in",
"Fie... | 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. | [
"Module",
"caching",
"it",
"helps",
"with",
"not",
"having",
"to",
"import",
"again",
"and",
"again",
"same",
"modules",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L155-L166 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._load_source_model | 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).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.sou... | python | 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).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.sou... | [
"def",
"_load_source_model",
"(",
"self",
")",
":",
"# If source_model exists, return it",
"if",
"hasattr",
"(",
"self",
",",
"\"source_model\"",
")",
":",
"return",
"self",
".",
"source_model",
"# Getting the source model",
"module",
"=",
"self",
".",
"get_python_mod... | 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). | [
"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",
"assoc... | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L179-L201 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation._load_source_object | def _load_source_object(self):
"""
Loads related object in a dynamic attribute and returns it.
"""
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... | python | def _load_source_object(self):
"""
Loads related object in a dynamic attribute and returns it.
"""
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... | [
"def",
"_load_source_object",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"source_obj\"",
")",
":",
"self",
".",
"source_text",
"=",
"getattr",
"(",
"self",
".",
"source_obj",
",",
"self",
".",
"field",
")",
"return",
"self",
".",
"source... | Loads related object in a dynamic attribute and returns it. | [
"Loads",
"related",
"object",
"in",
"a",
"dynamic",
"attribute",
"and",
"returns",
"it",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L206-L216 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.delete_orphan_translations | def delete_orphan_translations(condition=None):
"""
Delete orphan translations.
This method needs refactoring to be improve its performance.
"""
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
... | python | def delete_orphan_translations(condition=None):
"""
Delete orphan translations.
This method needs refactoring to be improve its performance.
"""
if condition is None:
condition = {}
# TODO: optimize using one SQL sentence
translations = FieldTranslation.objects.all()
for translation in translations:
... | [
"def",
"delete_orphan_translations",
"(",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"condition",
"=",
"{",
"}",
"# TODO: optimize using one SQL sentence",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"all",
"(",
")"... | Delete orphan translations.
This method needs refactoring to be improve its performance. | [
"Delete",
"orphan",
"translations",
".",
"This",
"method",
"needs",
"refactoring",
"to",
"be",
"improve",
"its",
"performance",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L222-L235 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.update_translations | def update_translations(condition=None):
"""
Updates FieldTranslations table
"""
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 MODELT... | python | def update_translations(condition=None):
"""
Updates FieldTranslations table
"""
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 MODELT... | [
"def",
"update_translations",
"(",
"condition",
"=",
"None",
")",
":",
"if",
"condition",
"is",
"None",
":",
"condition",
"=",
"{",
"}",
"# Number of updated translations",
"num_translations",
"=",
"0",
"# Module caching",
"FieldTranslation",
".",
"_init_module_cache"... | Updates FieldTranslations table | [
"Updates",
"FieldTranslations",
"table"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L241-L278 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.factory | def factory(obj, field, source_text, lang, context=""):
"""
Static method that constructs a translation based on its contents.
"""
# Model name
obj_classname = obj.__class__.__name__
# Module name
obj_module = obj.__module__
# Computation of MD5 of the source text
source_md5 = checksum(source_tex... | python | def factory(obj, field, source_text, lang, context=""):
"""
Static method that constructs a translation based on its contents.
"""
# Model name
obj_classname = obj.__class__.__name__
# Module name
obj_module = obj.__module__
# Computation of MD5 of the source text
source_md5 = checksum(source_tex... | [
"def",
"factory",
"(",
"obj",
",",
"field",
",",
"source_text",
",",
"lang",
",",
"context",
"=",
"\"\"",
")",
":",
"# Model name",
"obj_classname",
"=",
"obj",
".",
"__class__",
".",
"__name__",
"# Module name",
"obj_module",
"=",
"obj",
".",
"__module__",
... | Static method that constructs a translation based on its contents. | [
"Static",
"method",
"that",
"constructs",
"a",
"translation",
"based",
"on",
"its",
"contents",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L313-L347 |
intelligenia/modeltranslation | modeltranslation/models.py | FieldTranslation.save | def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# 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
se... | python | def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# 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
se... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Now in UTC",
"now_datetime",
"=",
"timezone",
".",
"now",
"(",
")",
"# If we are in a creation, assigns creation_datetime",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
... | Save object in database, updating the datetimes accordingly. | [
"Save",
"object",
"in",
"database",
"updating",
"the",
"datetimes",
"accordingly",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/models.py#L413-L436 |
softwarefactory-project/distroinfo | distroinfo/parse.py | parse_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
"""
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
retu... | python | 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
"""
parse_releases(raw_info)
parse_packages(raw_info, apply_tag=apply_tag)
retu... | [
"def",
"parse_info",
"(",
"raw_info",
",",
"apply_tag",
"=",
"None",
")",
":",
"parse_releases",
"(",
"raw_info",
")",
"parse_packages",
"(",
"raw_info",
",",
"apply_tag",
"=",
"apply_tag",
")",
"return",
"raw_info"
] | 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 | [
"Parse",
"raw",
"rdoinfo",
"metadata",
"inplace",
"."
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L8-L18 |
softwarefactory-project/distroinfo | distroinfo/parse.py | info2dicts | 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'
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
... | python | 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'
"""
if 'packages' not in info and 'releases' not in info:
return info
if in_place:
... | [
"def",
"info2dicts",
"(",
"info",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"'packages'",
"not",
"in",
"info",
"and",
"'releases'",
"not",
"in",
"info",
":",
"return",
"info",
"if",
"in_place",
":",
"info_dicts",
"=",
"info",
"else",
":",
"info_dict... | 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' | [
"Return",
"info",
"with",
":"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L189-L208 |
softwarefactory-project/distroinfo | distroinfo/parse.py | info2lists | 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
"""
if 'packages' not in info and 'releases' not in i... | python | 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
"""
if 'packages' not in info and 'releases' not in i... | [
"def",
"info2lists",
"(",
"info",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"'packages'",
"not",
"in",
"info",
"and",
"'releases'",
"not",
"in",
"info",
":",
"return",
"info",
"if",
"in_place",
":",
"info_lists",
"=",
"info",
"else",
":",
"info_list... | 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 | [
"Return",
"info",
"with",
":"
] | train | https://github.com/softwarefactory-project/distroinfo/blob/86a7419232a3376157c06e70528ec627e03ff82a/distroinfo/parse.py#L211-L233 |
xapple/plumbing | plumbing/common.py | alphanumeric | 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."""
return "".join([c for c in text if re.match(r'\w', c)]) | python | 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."""
return "".join([c for c in text if re.match(r'\w', c)]) | [
"def",
"alphanumeric",
"(",
"text",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"text",
"if",
"re",
".",
"match",
"(",
"r'\\w'",
",",
"c",
")",
"]",
")"
] | Make an ultra-safe, ASCII version a string.
For instance for use as a filename.
\w matches any alphanumeric character and the underscore. | [
"Make",
"an",
"ultra",
"-",
"safe",
"ASCII",
"version",
"a",
"string",
".",
"For",
"instance",
"for",
"use",
"as",
"a",
"filename",
".",
"\\",
"w",
"matches",
"any",
"alphanumeric",
"character",
"and",
"the",
"underscore",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L23-L27 |
xapple/plumbing | plumbing/common.py | sanitize_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)."""
# First replace characters that have specific effects with their repr #
text = re.sub("(\s... | python | 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)."""
# First replace characters that have specific effects with their repr #
text = re.sub("(\s... | [
"def",
"sanitize_text",
"(",
"text",
")",
":",
"# First replace characters that have specific effects with their repr #",
"text",
"=",
"re",
".",
"sub",
"(",
"\"(\\s)\"",
",",
"lambda",
"m",
":",
"repr",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
".",
"strip"... | 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). | [
"Make",
"a",
"safe",
"representation",
"of",
"a",
"string",
".",
"Note",
":",
"the",
"\\",
"s",
"special",
"character",
"matches",
"any",
"whitespace",
"character",
".",
"This",
"is",
"equivalent",
"to",
"the",
"set",
"[",
"\\",
"t",
"\\",
"n",
"\\",
"... | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L30-L41 |
xapple/plumbing | plumbing/common.py | camel_to_snake | 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'... | python | 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'... | [
"def",
"camel_to_snake",
"(",
"text",
")",
":",
"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",
")",
"retu... | 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'
>>>... | [
"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_... | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L44-L64 |
xapple/plumbing | plumbing/common.py | bool_to_unicode | def bool_to_unicode(b):
"""Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"""
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | python | def bool_to_unicode(b):
"""Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"""
b = bool(b)
if b is True: return u"✅"
if b is False: return u"❎" | [
"def",
"bool_to_unicode",
"(",
"b",
")",
":",
"b",
"=",
"bool",
"(",
"b",
")",
"if",
"b",
"is",
"True",
":",
"return",
"u\"✅\"",
"if",
"b",
"is",
"False",
":",
"return",
"u\"❎\""
] | Different possibilities for True: ☑️✔︎✓✅👍✔️
Different possibilities for False: ✕✖︎✗✘✖️❌⛔️❎👎🛑🔴 | [
"Different",
"possibilities",
"for",
"True",
":",
"☑️✔︎✓✅👍✔️",
"Different",
"possibilities",
"for",
"False",
":",
"✕✖︎✗✘✖️❌⛔️❎👎🛑🔴"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L67-L72 |
xapple/plumbing | plumbing/common.py | access_dict_like_obj | 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, 'chara... | python | 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, 'chara... | [
"def",
"access_dict_like_obj",
"(",
"obj",
",",
"prop",
",",
"new_value",
"=",
"None",
")",
":",
"props",
"=",
"prop",
".",
"split",
"(",
"'.'",
")",
"if",
"new_value",
":",
"if",
"props",
"[",
"0",
"]",
"not",
"in",
"obj",
":",
"obj",
"[",
"props"... | 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') | [
"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",
":",
... | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L75-L89 |
xapple/plumbing | plumbing/common.py | all_combinations | def all_combinations(items):
"""Generate all combinations of a given list of items."""
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | python | def all_combinations(items):
"""Generate all combinations of a given list of items."""
return (set(compress(items,mask)) for mask in product(*[[0,1]]*len(items))) | [
"def",
"all_combinations",
"(",
"items",
")",
":",
"return",
"(",
"set",
"(",
"compress",
"(",
"items",
",",
"mask",
")",
")",
"for",
"mask",
"in",
"product",
"(",
"*",
"[",
"[",
"0",
",",
"1",
"]",
"]",
"*",
"len",
"(",
"items",
")",
")",
")"
... | Generate all combinations of a given list of items. | [
"Generate",
"all",
"combinations",
"of",
"a",
"given",
"list",
"of",
"items",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L92-L94 |
xapple/plumbing | plumbing/common.py | pad_equal_whitespace | def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
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')) | python | def pad_equal_whitespace(string, pad=None):
"""Given a multiline string, add whitespaces to every line
so that every line has the same length."""
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",
")",
":",
"if",
"pad",
"is",
"None",
":",
"pad",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"string",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"+",
"1",
"return",
"'\\n'",
"."... | Given a multiline string, add whitespaces to every line
so that every line has the same length. | [
"Given",
"a",
"multiline",
"string",
"add",
"whitespaces",
"to",
"every",
"line",
"so",
"that",
"every",
"line",
"has",
"the",
"same",
"length",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L97-L101 |
xapple/plumbing | plumbing/common.py | concatenate_by_line | def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | python | def concatenate_by_line(first, second):
"""Zip two strings together, line wise"""
return '\n'.join(x+y for x,y in zip(first.split('\n'), second.split('\n'))) | [
"def",
"concatenate_by_line",
"(",
"first",
",",
"second",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"x",
"+",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"first",
".",
"split",
"(",
"'\\n'",
")",
",",
"second",
".",
"split",
"(",
"'\\n'",
... | Zip two strings together, line wise | [
"Zip",
"two",
"strings",
"together",
"line",
"wise"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L115-L117 |
xapple/plumbing | plumbing/common.py | sort_string_by_pairs | 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."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.po... | python | 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."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.po... | [
"def",
"sort_string_by_pairs",
"(",
"strings",
")",
":",
"assert",
"len",
"(",
"strings",
")",
"%",
"2",
"==",
"0",
"pairs",
"=",
"[",
"]",
"strings",
"=",
"list",
"(",
"strings",
")",
"# This shallow copies the list",
"while",
"strings",
":",
"template",
... | Group a list of strings by pairs, by matching those with only
one character difference between each other together. | [
"Group",
"a",
"list",
"of",
"strings",
"by",
"pairs",
"by",
"matching",
"those",
"with",
"only",
"one",
"character",
"difference",
"between",
"each",
"other",
"together",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L120-L134 |
xapple/plumbing | plumbing/common.py | count_string_diff | def count_string_diff(a,b):
"""Return the number of characters in two strings that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | python | def count_string_diff(a,b):
"""Return the number of characters in two strings that don't exactly match"""
shortest = min(len(a), len(b))
return sum(a[i] != b[i] for i in range(shortest)) | [
"def",
"count_string_diff",
"(",
"a",
",",
"b",
")",
":",
"shortest",
"=",
"min",
"(",
"len",
"(",
"a",
")",
",",
"len",
"(",
"b",
")",
")",
"return",
"sum",
"(",
"a",
"[",
"i",
"]",
"!=",
"b",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",... | Return the number of characters in two strings that don't exactly match | [
"Return",
"the",
"number",
"of",
"characters",
"in",
"two",
"strings",
"that",
"don",
"t",
"exactly",
"match"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L137-L140 |
xapple/plumbing | plumbing/common.py | iflatten | def iflatten(L):
"""Iterative flatten."""
for sublist in L:
if hasattr(sublist, '__iter__'):
for item in iflatten(sublist): yield item
else: yield sublist | python | def iflatten(L):
"""Iterative flatten."""
for sublist in L:
if hasattr(sublist, '__iter__'):
for item in iflatten(sublist): yield item
else: yield sublist | [
"def",
"iflatten",
"(",
"L",
")",
":",
"for",
"sublist",
"in",
"L",
":",
"if",
"hasattr",
"(",
"sublist",
",",
"'__iter__'",
")",
":",
"for",
"item",
"in",
"iflatten",
"(",
"sublist",
")",
":",
"yield",
"item",
"else",
":",
"yield",
"sublist"
] | Iterative flatten. | [
"Iterative",
"flatten",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L143-L148 |
xapple/plumbing | plumbing/common.py | uniquify_list | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | python | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | [
"def",
"uniquify_list",
"(",
"L",
")",
":",
"return",
"[",
"e",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"L",
")",
"if",
"L",
".",
"index",
"(",
"e",
")",
"==",
"i",
"]"
] | Same order unique list using only a list compression. | [
"Same",
"order",
"unique",
"list",
"using",
"only",
"a",
"list",
"compression",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L151-L153 |
xapple/plumbing | plumbing/common.py | average | def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | python | def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count | [
"def",
"average",
"(",
"iterator",
")",
":",
"count",
"=",
"0",
"total",
"=",
"0",
"for",
"num",
"in",
"iterator",
":",
"count",
"+=",
"1",
"total",
"+=",
"num",
"return",
"float",
"(",
"total",
")",
"/",
"count"
] | Iterative mean. | [
"Iterative",
"mean",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L156-L163 |
xapple/plumbing | plumbing/common.py | get_next_item | def get_next_item(iterable):
"""Gets the next item of an iterable.
If the iterable is exhausted, returns None."""
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | python | def get_next_item(iterable):
"""Gets the next item of an iterable.
If the iterable is exhausted, returns None."""
try: x = iterable.next()
except StopIteration: x = None
except AttributeError: x = None
return x | [
"def",
"get_next_item",
"(",
"iterable",
")",
":",
"try",
":",
"x",
"=",
"iterable",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"x",
"=",
"None",
"except",
"AttributeError",
":",
"x",
"=",
"None",
"return",
"x"
] | Gets the next item of an iterable.
If the iterable is exhausted, returns None. | [
"Gets",
"the",
"next",
"item",
"of",
"an",
"iterable",
".",
"If",
"the",
"iterable",
"is",
"exhausted",
"returns",
"None",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L166-L172 |
xapple/plumbing | plumbing/common.py | pretty_now | def pretty_now():
"""Returns some thing like '2019-02-15 15:58:22 CET+0100'"""
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | python | def pretty_now():
"""Returns some thing like '2019-02-15 15:58:22 CET+0100'"""
import datetime, tzlocal
time_zone = tzlocal.get_localzone()
now = datetime.datetime.now(time_zone)
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z") | [
"def",
"pretty_now",
"(",
")",
":",
"import",
"datetime",
",",
"tzlocal",
"time_zone",
"=",
"tzlocal",
".",
"get_localzone",
"(",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"time_zone",
")",
"return",
"now",
".",
"strftime",
"(",
"\"%... | Returns some thing like '2019-02-15 15:58:22 CET+0100 | [
"Returns",
"some",
"thing",
"like",
"2019",
"-",
"02",
"-",
"15",
"15",
":",
"58",
":",
"22",
"CET",
"+",
"0100"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L175-L180 |
xapple/plumbing | plumbing/common.py | andify | def andify(list_of_strings):
"""
Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos'
"""
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = ... | python | def andify(list_of_strings):
"""
Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos'
"""
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = ... | [
"def",
"andify",
"(",
"list_of_strings",
")",
":",
"result",
"=",
"', '",
".",
"join",
"(",
"list_of_strings",
")",
"comma_index",
"=",
"result",
".",
"rfind",
"(",
"','",
")",
"if",
"comma_index",
">",
"-",
"1",
":",
"result",
"=",
"result",
"[",
":",... | Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos' | [
"Given",
"a",
"list",
"of",
"strings",
"will",
"join",
"them",
"with",
"commas",
"and",
"a",
"final",
"and",
"word",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L183-L194 |
xapple/plumbing | plumbing/common.py | num_to_ith | def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return val... | python | def num_to_ith(num):
"""1 becomes 1st, 2 becomes 2nd, etc."""
value = str(num)
before_last_digit = value[-2]
last_digit = value[-1]
if len(value) > 1 and before_last_digit == '1': return value +'th'
if last_digit == '1': return value + 'st'
if last_digit == '2': return val... | [
"def",
"num_to_ith",
"(",
"num",
")",
":",
"value",
"=",
"str",
"(",
"num",
")",
"before_last_digit",
"=",
"value",
"[",
"-",
"2",
"]",
"last_digit",
"=",
"value",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"value",
")",
">",
"1",
"and",
"before_last_di... | 1 becomes 1st, 2 becomes 2nd, etc. | [
"1",
"becomes",
"1st",
"2",
"becomes",
"2nd",
"etc",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L197-L206 |
xapple/plumbing | plumbing/common.py | isubsample | def isubsample(full_sample, k, full_sample_len=None):
"""Down-sample an enumerable list of things"""
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sampl... | python | def isubsample(full_sample, k, full_sample_len=None):
"""Down-sample an enumerable list of things"""
# Determine length #
if not full_sample_len: full_sample_len = len(full_sample)
# Check size coherence #
if not 0 <= k <= full_sample_len:
raise ValueError('Required that 0 <= k <= full_sampl... | [
"def",
"isubsample",
"(",
"full_sample",
",",
"k",
",",
"full_sample_len",
"=",
"None",
")",
":",
"# Determine length #",
"if",
"not",
"full_sample_len",
":",
"full_sample_len",
"=",
"len",
"(",
"full_sample",
")",
"# Check size coherence #",
"if",
"not",
"0",
"... | Down-sample an enumerable list of things | [
"Down",
"-",
"sample",
"an",
"enumerable",
"list",
"of",
"things"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L209-L224 |
xapple/plumbing | plumbing/common.py | moving_average | def moving_average(interval, windowsize, borders=None):
"""This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than t... | python | def moving_average(interval, windowsize, borders=None):
"""This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than t... | [
"def",
"moving_average",
"(",
"interval",
",",
"windowsize",
",",
"borders",
"=",
"None",
")",
":",
"# The window size in half #",
"half",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"windowsize",
"/",
"2.0",
")",
")",
"# The normalized rectangular signal #",
"w... | This is essentially a convolving operation. Several option exist for dealing with the border cases.
* None: Here the returned signal will be smaller than the inputted interval.
* zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original inte... | [
"This",
"is",
"essentially",
"a",
"convolving",
"operation",
".",
"Several",
"option",
"exist",
"for",
"dealing",
"with",
"the",
"border",
"cases",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L227-L269 |
xapple/plumbing | plumbing/common.py | wait | def wait(predicate, interval=1, message=lambda: "Waiting..."):
"""Wait until the predicate turns true and display a turning ball."""
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(nex... | python | def wait(predicate, interval=1, message=lambda: "Waiting..."):
"""Wait until the predicate turns true and display a turning ball."""
ball, next_ball = u"|/-\\", "|"
sys.stdout.write(" \033[K")
sys.stdout.flush()
while not predicate():
time.sleep(1)
next_ball = ball[(ball.index(nex... | [
"def",
"wait",
"(",
"predicate",
",",
"interval",
"=",
"1",
",",
"message",
"=",
"lambda",
":",
"\"Waiting...\"",
")",
":",
"ball",
",",
"next_ball",
"=",
"u\"|/-\\\\\"",
",",
"\"|\"",
"sys",
".",
"stdout",
".",
"write",
"(",
"\" \\033[K\"",
")",
"sys... | Wait until the predicate turns true and display a turning ball. | [
"Wait",
"until",
"the",
"predicate",
"turns",
"true",
"and",
"display",
"a",
"turning",
"ball",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L272-L283 |
xapple/plumbing | plumbing/common.py | natural_sort | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre... | python | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre... | [
"def",
"natural_sort",
"(",
"item",
")",
":",
"dre",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)'",
")",
"return",
"[",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"re",
".",
... | Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" | [
"Sort",
"strings",
"that",
"contain",
"numbers",
"correctly",
".",
"Works",
"in",
"Python",
"2",
"and",
"3",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L286-L296 |
xapple/plumbing | plumbing/common.py | split_thousands | def split_thousands(s):
"""
Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) a... | python | def split_thousands(s):
"""
Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012"
"""
# Check input #
if s is None: return "0"
# If it's a string #
if isinstance(s, basestring): s = float(s)
# If it's a float that should be an int #
if isinstance(s, float) a... | [
"def",
"split_thousands",
"(",
"s",
")",
":",
"# Check input #",
"if",
"s",
"is",
"None",
":",
"return",
"\"0\"",
"# If it's a string #",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"s",
"=",
"float",
"(",
"s",
")",
"# If it's a float that sho... | Splits a number on thousands.
>>> split_thousands(1000012)
"1'000'012" | [
"Splits",
"a",
"number",
"on",
"thousands",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L299-L317 |
xapple/plumbing | plumbing/common.py | reverse_compl_with_name | def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | python | def reverse_compl_with_name(old_seq):
"""Reverse a SeqIO sequence, but keep its name intact."""
new_seq = old_seq.reverse_complement()
new_seq.id = old_seq.id
new_seq.description = old_seq.description
return new_seq | [
"def",
"reverse_compl_with_name",
"(",
"old_seq",
")",
":",
"new_seq",
"=",
"old_seq",
".",
"reverse_complement",
"(",
")",
"new_seq",
".",
"id",
"=",
"old_seq",
".",
"id",
"new_seq",
".",
"description",
"=",
"old_seq",
".",
"description",
"return",
"new_seq"
... | Reverse a SeqIO sequence, but keep its name intact. | [
"Reverse",
"a",
"SeqIO",
"sequence",
"but",
"keep",
"its",
"name",
"intact",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L333-L338 |
xapple/plumbing | plumbing/common.py | load_json_path | def load_json_path(path):
"""Load a file with the json module, but report errors better if it
fails. And have it ordered too !"""
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not d... | python | def load_json_path(path):
"""Load a file with the json module, but report errors better if it
fails. And have it ordered too !"""
with open(path) as handle:
try: return json.load(handle, object_pairs_hook=collections.OrderedDict)
except ValueError as error:
message = "Could not d... | [
"def",
"load_json_path",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"handle",
":",
"try",
":",
"return",
"json",
".",
"load",
"(",
"handle",
",",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
")",
"except",
"ValueError",
... | Load a file with the json module, but report errors better if it
fails. And have it ordered too ! | [
"Load",
"a",
"file",
"with",
"the",
"json",
"module",
"but",
"report",
"errors",
"better",
"if",
"it",
"fails",
".",
"And",
"have",
"it",
"ordered",
"too",
"!"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L390-L399 |
xapple/plumbing | plumbing/common.py | md5sum | def md5sum(file_path, blocksize=65536):
"""Compute the md5 of a file. Pretty fast."""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | python | def md5sum(file_path, blocksize=65536):
"""Compute the md5 of a file. Pretty fast."""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for block in iter(lambda: f.read(blocksize), ""):
md5.update(block)
return md5.hexdigest() | [
"def",
"md5sum",
"(",
"file_path",
",",
"blocksize",
"=",
"65536",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"block",
"in",
"iter",
"(",
"lambda",
":",
"f",
... | Compute the md5 of a file. Pretty fast. | [
"Compute",
"the",
"md5",
"of",
"a",
"file",
".",
"Pretty",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L408-L414 |
xapple/plumbing | plumbing/common.py | download_from_url | def download_from_url(source, destination, progress=False, uncompress=False):
"""Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory"""
# Module... | python | def download_from_url(source, destination, progress=False, uncompress=False):
"""Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory"""
# Module... | [
"def",
"download_from_url",
"(",
"source",
",",
"destination",
",",
"progress",
"=",
"False",
",",
"uncompress",
"=",
"False",
")",
":",
"# Modules #",
"from",
"tqdm",
"import",
"tqdm",
"import",
"requests",
"from",
"autopaths",
".",
"file_path",
"import",
"Fi... | Download a file from an URL and place it somewhere. Like wget.
Uses requests and tqdm to display progress if you want.
By default it will uncompress files.
#TODO: handle case where destination is a directory | [
"Download",
"a",
"file",
"from",
"an",
"URL",
"and",
"place",
"it",
"somewhere",
".",
"Like",
"wget",
".",
"Uses",
"requests",
"and",
"tqdm",
"to",
"display",
"progress",
"if",
"you",
"want",
".",
"By",
"default",
"it",
"will",
"uncompress",
"files",
"."... | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L417-L445 |
xapple/plumbing | plumbing/common.py | reversed_lines | def reversed_lines(path):
"""Generate the lines of file in reverse order."""
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part ... | python | def reversed_lines(path):
"""Generate the lines of file in reverse order."""
with open(path, 'r') as handle:
part = ''
for block in reversed_blocks(handle):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part ... | [
"def",
"reversed_lines",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"handle",
":",
"part",
"=",
"''",
"for",
"block",
"in",
"reversed_blocks",
"(",
"handle",
")",
":",
"for",
"c",
"in",
"reversed",
"(",
"block",
")",
... | Generate the lines of file in reverse order. | [
"Generate",
"the",
"lines",
"of",
"file",
"in",
"reverse",
"order",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L448-L458 |
xapple/plumbing | plumbing/common.py | reversed_blocks | def reversed_blocks(handle, blocksize=4096):
"""Generate blocks of file's contents in reverse order."""
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | python | def reversed_blocks(handle, blocksize=4096):
"""Generate blocks of file's contents in reverse order."""
handle.seek(0, os.SEEK_END)
here = handle.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
handle.seek(here, os.SEEK_SET)
yield handle.read(delta) | [
"def",
"reversed_blocks",
"(",
"handle",
",",
"blocksize",
"=",
"4096",
")",
":",
"handle",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
"here",
"=",
"handle",
".",
"tell",
"(",
")",
"while",
"0",
"<",
"here",
":",
"delta",
"=",
"min",
... | Generate blocks of file's contents in reverse order. | [
"Generate",
"blocks",
"of",
"file",
"s",
"contents",
"in",
"reverse",
"order",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L461-L469 |
xapple/plumbing | plumbing/common.py | prepend_to_file | def prepend_to_file(path, data, bufsize=1<<15):
"""TODO:
* Add a random string to the backup file.
* Restore permissions after copy.
"""
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
... | python | def prepend_to_file(path, data, bufsize=1<<15):
"""TODO:
* Add a random string to the backup file.
* Restore permissions after copy.
"""
# Backup the file #
backupname = path + os.extsep + 'bak'
# Remove previous backup if it exists #
try: os.unlink(backupname)
except OSError: pass
... | [
"def",
"prepend_to_file",
"(",
"path",
",",
"data",
",",
"bufsize",
"=",
"1",
"<<",
"15",
")",
":",
"# Backup the file #",
"backupname",
"=",
"path",
"+",
"os",
".",
"extsep",
"+",
"'bak'",
"# Remove previous backup if it exists #",
"try",
":",
"os",
".",
"u... | TODO:
* Add a random string to the backup file.
* Restore permissions after copy. | [
"TODO",
":",
"*",
"Add",
"a",
"random",
"string",
"to",
"the",
"backup",
"file",
".",
"*",
"Restore",
"permissions",
"after",
"copy",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L472-L492 |
xapple/plumbing | plumbing/common.py | which | def which(cmd, safe=False):
"""https://github.com/jc0n/python-which"""
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd)... | python | def which(cmd, safe=False):
"""https://github.com/jc0n/python-which"""
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd)... | [
"def",
"which",
"(",
"cmd",
",",
"safe",
"=",
"False",
")",
":",
"from",
"autopaths",
".",
"file_path",
"import",
"FilePath",
"def",
"is_executable",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".... | https://github.com/jc0n/python-which | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"jc0n",
"/",
"python",
"-",
"which"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L529-L541 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | css_tag | def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
... | python | def css_tag(parser, token):
"""
Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
... | [
"def",
"css_tag",
"(",
"parser",
",",
"token",
")",
":",
"path",
"=",
"get_path_from_tokens",
"(",
"token",
")",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"2",
":",
"# Get the media types from the tag call... | Renders a tag to include the stylesheet. It takes an optional second
parameter for the media attribute; the default media is "screen, projector".
Usage::
{% css "<somefile>.css" ["<projection type(s)>"] %}
Examples::
{% css "myfile.css" %}
{% css "myfile.css" "screen, projec... | [
"Renders",
"a",
"tag",
"to",
"include",
"the",
"stylesheet",
".",
"It",
"takes",
"an",
"optional",
"second",
"parameter",
"for",
"the",
"media",
"attribute",
";",
"the",
"default",
"media",
"is",
"screen",
"projector",
".",
"Usage",
"::"
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L154-L178 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | css_print_tag | def css_print_tag(parser, token):
"""
Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %}
"""
path = get_path_from_tokens(token)
# Hard wired media type, since this is... | python | def css_print_tag(parser, token):
"""
Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %}
"""
path = get_path_from_tokens(token)
# Hard wired media type, since this is... | [
"def",
"css_print_tag",
"(",
"parser",
",",
"token",
")",
":",
"path",
"=",
"get_path_from_tokens",
"(",
"token",
")",
"# Hard wired media type, since this is for media type of 'print'.",
"media_type",
"=",
"\"print\"",
"return",
"CssTagNode",
"(",
"path",
",",
"media_t... | Shortcut to render CSS as a print stylesheet.
Usage::
{% css_print "myfile.css" %}
Which is equivalent to
{% css "myfile.css" "print" %} | [
"Shortcut",
"to",
"render",
"CSS",
"as",
"a",
"print",
"stylesheet",
".",
"Usage",
"::",
"{",
"%",
"css_print",
"myfile",
".",
"css",
"%",
"}",
"Which",
"is",
"equivalent",
"to",
"{",
"%",
"css",
"myfile",
".",
"css",
"print",
"%",
"}"
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L181-L197 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.supports_gzip | def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be serve... | python | def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be serve... | [
"def",
"supports_gzip",
"(",
"self",
",",
"context",
")",
":",
"if",
"'request'",
"in",
"context",
"and",
"client",
".",
"supports_gzip",
"(",
")",
":",
"enc",
"=",
"context",
"[",
"'request'",
"]",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT_ENCODING'",
... | Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media. | [
"Looks",
"at",
"the",
"RequestContext",
"object",
"and",
"determines",
"if",
"the",
"client",
"supports",
"gzip",
"encoded",
"content",
".",
"If",
"the",
"client",
"does",
"we",
"will",
"send",
"them",
"to",
"the",
"gzipped",
"version",
"of",
"files",
"that"... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L32-L42 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.get_media_url | def get_media_url(self, context):
"""
Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends impl... | python | def get_media_url(self, context):
"""
Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends impl... | [
"def",
"get_media_url",
"(",
"self",
",",
"context",
")",
":",
"use_ssl",
"=",
"msettings",
"[",
"'USE_SSL'",
"]",
"is_secure",
"=",
"use_ssl",
"if",
"use_ssl",
"is",
"not",
"None",
"else",
"self",
".",
"is_secure",
"(",
"context",
")",
"return",
"client",... | Checks to see whether to use the normal or the secure media source,
depending on whether the current page view is being sent over SSL.
The USE_SSL setting can be used to force HTTPS (True) or HTTP (False).
NOTE: Not all backends implement SSL media. In this case, they'll just
re... | [
"Checks",
"to",
"see",
"whether",
"to",
"use",
"the",
"normal",
"or",
"the",
"secure",
"media",
"source",
"depending",
"on",
"whether",
"the",
"current",
"page",
"view",
"is",
"being",
"sent",
"over",
"SSL",
".",
"The",
"USE_SSL",
"setting",
"can",
"be",
... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L44-L55 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | BaseTagNode.mkpath | def mkpath(self, url, path, filename=None, gzip=False):
"""
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
... | python | def mkpath(self, url, path, filename=None, gzip=False):
"""
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
... | [
"def",
"mkpath",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
"=",
"None",
",",
"gzip",
"=",
"False",
")",
":",
"if",
"path",
":",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"url",
".",
"rstrip",
"(",
"'/'",
")",
",",
"path",
".",
"strip",
"(... | Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if clien... | [
"Assembles",
"various",
"components",
"to",
"form",
"a",
"complete",
"resource",
"URL",
".",
"args",
":",
"url",
":",
"(",
"str",
")",
"A",
"base",
"media",
"URL",
".",
"path",
":",
"(",
"str",
")",
"The",
"path",
"on",
"the",
"host",
"(",
"specified... | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L57-L86 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | CssTagNode.linktag | def linktag(self, url, path, filename, media, context):
"""
Renders a <link> tag for the stylesheet(s).
"""
if msettings['DOCTYPE'] == 'xhtml':
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />"""
elif msettings['DOCTYPE'] == 'html5':
... | python | def linktag(self, url, path, filename, media, context):
"""
Renders a <link> tag for the stylesheet(s).
"""
if msettings['DOCTYPE'] == 'xhtml':
markup = """<link rel="stylesheet" href="%s" type="text/css" media="%s" />"""
elif msettings['DOCTYPE'] == 'html5':
... | [
"def",
"linktag",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
",",
"media",
",",
"context",
")",
":",
"if",
"msettings",
"[",
"'DOCTYPE'",
"]",
"==",
"'xhtml'",
":",
"markup",
"=",
"\"\"\"<link rel=\"stylesheet\" href=\"%s\" type=\"text/css\" media=\"%s... | Renders a <link> tag for the stylesheet(s). | [
"Renders",
"a",
"<link",
">",
"tag",
"for",
"the",
"stylesheet",
"(",
"s",
")",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L230-L240 |
sunlightlabs/django-mediasync | mediasync/templatetags/media.py | JsTagNode.scripttag | def scripttag(self, url, path, filename, context):
"""
Renders a <script> tag for the JS file(s).
"""
if msettings['DOCTYPE'] == 'html5':
markup = """<script src="%s"></script>"""
else:
markup = """<script type="text/javascript" charset="utf-8" src="%s"></... | python | def scripttag(self, url, path, filename, context):
"""
Renders a <script> tag for the JS file(s).
"""
if msettings['DOCTYPE'] == 'html5':
markup = """<script src="%s"></script>"""
else:
markup = """<script type="text/javascript" charset="utf-8" src="%s"></... | [
"def",
"scripttag",
"(",
"self",
",",
"url",
",",
"path",
",",
"filename",
",",
"context",
")",
":",
"if",
"msettings",
"[",
"'DOCTYPE'",
"]",
"==",
"'html5'",
":",
"markup",
"=",
"\"\"\"<script src=\"%s\"></script>\"\"\"",
"else",
":",
"markup",
"=",
"\"\"\... | Renders a <script> tag for the JS file(s). | [
"Renders",
"a",
"<script",
">",
"tag",
"for",
"the",
"JS",
"file",
"(",
"s",
")",
"."
] | train | https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/templatetags/media.py#L284-L292 |
sprockets/sprockets.http | sprockets/http/app.py | wrap_application | def wrap_application(application, before_run, on_start, shutdown):
"""
Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
... | python | def wrap_application(application, before_run, on_start, shutdown):
"""
Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
... | [
"def",
"wrap_application",
"(",
"application",
",",
"before_run",
",",
"on_start",
",",
"shutdown",
")",
":",
"before_run",
"=",
"[",
"]",
"if",
"before_run",
"is",
"None",
"else",
"before_run",
"on_start",
"=",
"[",
"]",
"if",
"on_start",
"is",
"None",
"e... | Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register ... | [
"Wrap",
"a",
"tornado",
"application",
"in",
"a",
"callback",
"-",
"aware",
"wrapper",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/app.py#L229-L257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.