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
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
xapple/plumbing | plumbing/graphs.py | Graph.plot_and_save | def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
pyplot.close(self.fig) | python | def plot_and_save(self, **kwargs):
"""Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig"""
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
pyplot.close(self.fig) | [
"def",
"plot_and_save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"fig",
"=",
"pyplot",
".",
"figure",
"(",
")",
"self",
".",
"plot",
"(",
")",
"self",
".",
"axes",
"=",
"pyplot",
".",
"gca",
"(",
")",
"self",
".",
"save_plot",
"(",
"self",
".",
"fig",
",",
"self",
".",
"axes",
",",
"*",
"*",
"kwargs",
")",
"pyplot",
".",
"close",
"(",
"self",
".",
"fig",
")"
] | Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig | [
"Used",
"when",
"the",
"plot",
"method",
"defined",
"does",
"not",
"create",
"a",
"figure",
"nor",
"calls",
"save_plot",
"Then",
"the",
"plot",
"method",
"has",
"to",
"use",
"self",
".",
"fig"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L162-L169 |
xapple/plumbing | plumbing/graphs.py | Graph.plot | def plot(self, bins=250, **kwargs):
"""An example plot function. You have to subclass this method."""
# Data #
counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
# Linear bins in logarithmic space #
if 'log' in kwargs.get('x_scale', ''):
start, stop = numpy.log10(1), numpy.log10(max(counts))
bins = list(numpy.logspace(start=start, stop=stop, num=bins))
bins.insert(0, 0)
# Plot #
fig = pyplot.figure()
pyplot.hist(counts, bins=bins, color='gray')
axes = pyplot.gca()
# Information #
title = 'Distribution of the total nucleotide count in the bins'
axes.set_title(title)
axes.set_xlabel('Number of nucleotides in a bin')
axes.set_ylabel('Number of bins with that many nucleotides in them')
# Save it #
self.save_plot(fig, axes, **kwargs)
pyplot.close(fig)
# For convenience #
return self | python | def plot(self, bins=250, **kwargs):
"""An example plot function. You have to subclass this method."""
# Data #
counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
# Linear bins in logarithmic space #
if 'log' in kwargs.get('x_scale', ''):
start, stop = numpy.log10(1), numpy.log10(max(counts))
bins = list(numpy.logspace(start=start, stop=stop, num=bins))
bins.insert(0, 0)
# Plot #
fig = pyplot.figure()
pyplot.hist(counts, bins=bins, color='gray')
axes = pyplot.gca()
# Information #
title = 'Distribution of the total nucleotide count in the bins'
axes.set_title(title)
axes.set_xlabel('Number of nucleotides in a bin')
axes.set_ylabel('Number of bins with that many nucleotides in them')
# Save it #
self.save_plot(fig, axes, **kwargs)
pyplot.close(fig)
# For convenience #
return self | [
"def",
"plot",
"(",
"self",
",",
"bins",
"=",
"250",
",",
"*",
"*",
"kwargs",
")",
":",
"# Data #",
"counts",
"=",
"[",
"sum",
"(",
"map",
"(",
"len",
",",
"b",
".",
"contigs",
")",
")",
"for",
"b",
"in",
"self",
".",
"parent",
".",
"bins",
"]",
"# Linear bins in logarithmic space #",
"if",
"'log'",
"in",
"kwargs",
".",
"get",
"(",
"'x_scale'",
",",
"''",
")",
":",
"start",
",",
"stop",
"=",
"numpy",
".",
"log10",
"(",
"1",
")",
",",
"numpy",
".",
"log10",
"(",
"max",
"(",
"counts",
")",
")",
"bins",
"=",
"list",
"(",
"numpy",
".",
"logspace",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"num",
"=",
"bins",
")",
")",
"bins",
".",
"insert",
"(",
"0",
",",
"0",
")",
"# Plot #",
"fig",
"=",
"pyplot",
".",
"figure",
"(",
")",
"pyplot",
".",
"hist",
"(",
"counts",
",",
"bins",
"=",
"bins",
",",
"color",
"=",
"'gray'",
")",
"axes",
"=",
"pyplot",
".",
"gca",
"(",
")",
"# Information #",
"title",
"=",
"'Distribution of the total nucleotide count in the bins'",
"axes",
".",
"set_title",
"(",
"title",
")",
"axes",
".",
"set_xlabel",
"(",
"'Number of nucleotides in a bin'",
")",
"axes",
".",
"set_ylabel",
"(",
"'Number of bins with that many nucleotides in them'",
")",
"# Save it #",
"self",
".",
"save_plot",
"(",
"fig",
",",
"axes",
",",
"*",
"*",
"kwargs",
")",
"pyplot",
".",
"close",
"(",
"fig",
")",
"# For convenience #",
"return",
"self"
] | An example plot function. You have to subclass this method. | [
"An",
"example",
"plot",
"function",
".",
"You",
"have",
"to",
"subclass",
"this",
"method",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L171-L193 |
xapple/plumbing | plumbing/graphs.py | Graph.save_anim | def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
"""Not functional -- TODO"""
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bitrate= bitrate, fps=fps)
# Save #
self.avi_path = self.base_dir + self.short_name + '.avi'
anim.save(self.avi_path, writer=writer, codec='x264') | python | def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
"""Not functional -- TODO"""
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bitrate= bitrate, fps=fps)
# Save #
self.avi_path = self.base_dir + self.short_name + '.avi'
anim.save(self.avi_path, writer=writer, codec='x264') | [
"def",
"save_anim",
"(",
"self",
",",
"fig",
",",
"animate",
",",
"init",
",",
"bitrate",
"=",
"10000",
",",
"fps",
"=",
"30",
")",
":",
"from",
"matplotlib",
"import",
"animation",
"anim",
"=",
"animation",
".",
"FuncAnimation",
"(",
"fig",
",",
"animate",
",",
"init_func",
"=",
"init",
",",
"frames",
"=",
"360",
",",
"interval",
"=",
"20",
")",
"FFMpegWriter",
"=",
"animation",
".",
"writers",
"[",
"'ffmpeg'",
"]",
"writer",
"=",
"FFMpegWriter",
"(",
"bitrate",
"=",
"bitrate",
",",
"fps",
"=",
"fps",
")",
"# Save #",
"self",
".",
"avi_path",
"=",
"self",
".",
"base_dir",
"+",
"self",
".",
"short_name",
"+",
"'.avi'",
"anim",
".",
"save",
"(",
"self",
".",
"avi_path",
",",
"writer",
"=",
"writer",
",",
"codec",
"=",
"'x264'",
")"
] | Not functional -- TODO | [
"Not",
"functional",
"--",
"TODO"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L195-L203 |
xapple/plumbing | plumbing/slurm/__init__.py | count_processors | def count_processors():
"""How many cores does the current computer have ?"""
if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
text = os.environ['SLURM_JOB_CPUS_PER_NODE']
if is_integer(text): return int(text)
else:
n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0]
return int(n) * int(N)
else: return multiprocessing.cpu_count() | python | def count_processors():
"""How many cores does the current computer have ?"""
if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
text = os.environ['SLURM_JOB_CPUS_PER_NODE']
if is_integer(text): return int(text)
else:
n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0]
return int(n) * int(N)
else: return multiprocessing.cpu_count() | [
"def",
"count_processors",
"(",
")",
":",
"if",
"'SLURM_NTASKS'",
"in",
"os",
".",
"environ",
":",
"return",
"int",
"(",
"os",
".",
"environ",
"[",
"'SLURM_NTASKS'",
"]",
")",
"elif",
"'SLURM_JOB_CPUS_PER_NODE'",
"in",
"os",
".",
"environ",
":",
"text",
"=",
"os",
".",
"environ",
"[",
"'SLURM_JOB_CPUS_PER_NODE'",
"]",
"if",
"is_integer",
"(",
"text",
")",
":",
"return",
"int",
"(",
"text",
")",
"else",
":",
"n",
",",
"N",
"=",
"re",
".",
"findall",
"(",
"\"([1-9]+)\\(x([1-9]+)\\)\"",
",",
"text",
")",
"[",
"0",
"]",
"return",
"int",
"(",
"n",
")",
"*",
"int",
"(",
"N",
")",
"else",
":",
"return",
"multiprocessing",
".",
"cpu_count",
"(",
")"
] | How many cores does the current computer have ? | [
"How",
"many",
"cores",
"does",
"the",
"current",
"computer",
"have",
"?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L10-L19 |
xapple/plumbing | plumbing/slurm/__init__.py | guess_server_name | def guess_server_name():
"""We often use the same servers, which one are we running on now ?"""
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou': return "milou"
elif os.environ.get('LAPTOP') == 'macbook_air': return "macbook_air"
else: return "unknown" | python | def guess_server_name():
"""We often use the same servers, which one are we running on now ?"""
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou': return "milou"
elif os.environ.get('LAPTOP') == 'macbook_air': return "macbook_air"
else: return "unknown" | [
"def",
"guess_server_name",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'CSCSERVICE'",
")",
"==",
"'sisu'",
":",
"return",
"\"sisu\"",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'SLURM_JOB_PARTITION'",
")",
"==",
"'halvan'",
":",
"return",
"\"halvan\"",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'SNIC_RESOURCE'",
")",
"==",
"'milou'",
":",
"return",
"\"milou\"",
"elif",
"os",
".",
"environ",
".",
"get",
"(",
"'LAPTOP'",
")",
"==",
"'macbook_air'",
":",
"return",
"\"macbook_air\"",
"else",
":",
"return",
"\"unknown\""
] | We often use the same servers, which one are we running on now ? | [
"We",
"often",
"use",
"the",
"same",
"servers",
"which",
"one",
"are",
"we",
"running",
"on",
"now",
"?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L22-L28 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.get_instance | def get_instance(cls, instance_or_pk):
"""Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_balance(account, amount):
# Here `Account` is a subclass of `db.Model`.
account = Account.get_instance(account)
account.balance += amount
# Now `increase_account_balance` can be
# called with an account instance:
increase_account_balance(my_account, 100.00)
# or with an account primary key (1234):
increase_account_balance(1234, 100.00)
"""
if isinstance(instance_or_pk, cls):
if instance_or_pk in cls._flask_signalbus_sa.session:
return instance_or_pk
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return cls.query.get(instance_or_pk) | python | def get_instance(cls, instance_or_pk):
"""Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_balance(account, amount):
# Here `Account` is a subclass of `db.Model`.
account = Account.get_instance(account)
account.balance += amount
# Now `increase_account_balance` can be
# called with an account instance:
increase_account_balance(my_account, 100.00)
# or with an account primary key (1234):
increase_account_balance(1234, 100.00)
"""
if isinstance(instance_or_pk, cls):
if instance_or_pk in cls._flask_signalbus_sa.session:
return instance_or_pk
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return cls.query.get(instance_or_pk) | [
"def",
"get_instance",
"(",
"cls",
",",
"instance_or_pk",
")",
":",
"if",
"isinstance",
"(",
"instance_or_pk",
",",
"cls",
")",
":",
"if",
"instance_or_pk",
"in",
"cls",
".",
"_flask_signalbus_sa",
".",
"session",
":",
"return",
"instance_or_pk",
"instance_or_pk",
"=",
"inspect",
"(",
"cls",
")",
".",
"primary_key_from_instance",
"(",
"instance_or_pk",
")",
"return",
"cls",
".",
"query",
".",
"get",
"(",
"instance_or_pk",
")"
] | Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_balance(account, amount):
# Here `Account` is a subclass of `db.Model`.
account = Account.get_instance(account)
account.balance += amount
# Now `increase_account_balance` can be
# called with an account instance:
increase_account_balance(my_account, 100.00)
# or with an account primary key (1234):
increase_account_balance(1234, 100.00) | [
"Return",
"a",
"model",
"instance",
"in",
"db",
".",
"session",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L21-L49 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.lock_instance | def lock_instance(cls, instance_or_pk, read=False):
"""Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obtained instead of
a writing lock.
"""
mapper = inspect(cls)
pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key]
pk_values = cls.get_pk_values(instance_or_pk)
clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)])
return cls.query.filter(clause).with_for_update(read=read).one_or_none() | python | def lock_instance(cls, instance_or_pk, read=False):
"""Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obtained instead of
a writing lock.
"""
mapper = inspect(cls)
pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key]
pk_values = cls.get_pk_values(instance_or_pk)
clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)])
return cls.query.filter(clause).with_for_update(read=read).one_or_none() | [
"def",
"lock_instance",
"(",
"cls",
",",
"instance_or_pk",
",",
"read",
"=",
"False",
")",
":",
"mapper",
"=",
"inspect",
"(",
"cls",
")",
"pk_attrs",
"=",
"[",
"mapper",
".",
"get_property_by_column",
"(",
"c",
")",
".",
"class_attribute",
"for",
"c",
"in",
"mapper",
".",
"primary_key",
"]",
"pk_values",
"=",
"cls",
".",
"get_pk_values",
"(",
"instance_or_pk",
")",
"clause",
"=",
"and_",
"(",
"*",
"[",
"attr",
"==",
"value",
"for",
"attr",
",",
"value",
"in",
"zip",
"(",
"pk_attrs",
",",
"pk_values",
")",
"]",
")",
"return",
"cls",
".",
"query",
".",
"filter",
"(",
"clause",
")",
".",
"with_for_update",
"(",
"read",
"=",
"read",
")",
".",
"one_or_none",
"(",
")"
] | Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obtained instead of
a writing lock. | [
"Return",
"a",
"locked",
"model",
"instance",
"in",
"db",
".",
"session",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L52-L68 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | _ModelUtilitiesMixin.get_pk_values | def get_pk_values(cls, instance_or_pk):
"""Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
"""
if isinstance(instance_or_pk, cls):
cls._flask_signalbus_sa.session.flush()
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return instance_or_pk if isinstance(instance_or_pk, tuple) else (instance_or_pk,) | python | def get_pk_values(cls, instance_or_pk):
"""Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
"""
if isinstance(instance_or_pk, cls):
cls._flask_signalbus_sa.session.flush()
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return instance_or_pk if isinstance(instance_or_pk, tuple) else (instance_or_pk,) | [
"def",
"get_pk_values",
"(",
"cls",
",",
"instance_or_pk",
")",
":",
"if",
"isinstance",
"(",
"instance_or_pk",
",",
"cls",
")",
":",
"cls",
".",
"_flask_signalbus_sa",
".",
"session",
".",
"flush",
"(",
")",
"instance_or_pk",
"=",
"inspect",
"(",
"cls",
")",
".",
"primary_key_from_instance",
"(",
"instance_or_pk",
")",
"return",
"instance_or_pk",
"if",
"isinstance",
"(",
"instance_or_pk",
",",
"tuple",
")",
"else",
"(",
"instance_or_pk",
",",
")"
] | Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple. | [
"Return",
"a",
"primary",
"key",
"as",
"a",
"tuple",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L71-L83 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | AtomicProceduresMixin.atomic | def atomic(self, func):
"""A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function ``f``, which is wrapped in an
atomic block. Wrapping a function in an atomic block gives
several guarantees:
1. The database transaction will be automatically committed if
the function returns normally, and automatically rolled
back if the function raises unhandled exception.
2. When the transaction is committed, all objects in
``db.session`` will be expunged. This means that no lazy
loading will be performed on them.
3. If a transaction serialization error occurs during the
execution of the function, the function will be
re-executed. (It might be re-executed several times.)
Atomic blocks can be nested, but in this case the outermost
block takes full control of transaction's life-cycle, and
inner blocks do nothing.
"""
@wraps(func)
def wrapper(*args, **kwargs):
session = self.session
session_info = session.info
if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY):
return func(*args, **kwargs)
f = retry_on_deadlock(session)(func)
session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = True
try:
result = f(*args, **kwargs)
session.flush()
session.expunge_all()
session.commit()
return result
except Exception:
session.rollback()
raise
finally:
session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = False
return wrapper | python | def atomic(self, func):
"""A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function ``f``, which is wrapped in an
atomic block. Wrapping a function in an atomic block gives
several guarantees:
1. The database transaction will be automatically committed if
the function returns normally, and automatically rolled
back if the function raises unhandled exception.
2. When the transaction is committed, all objects in
``db.session`` will be expunged. This means that no lazy
loading will be performed on them.
3. If a transaction serialization error occurs during the
execution of the function, the function will be
re-executed. (It might be re-executed several times.)
Atomic blocks can be nested, but in this case the outermost
block takes full control of transaction's life-cycle, and
inner blocks do nothing.
"""
@wraps(func)
def wrapper(*args, **kwargs):
session = self.session
session_info = session.info
if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY):
return func(*args, **kwargs)
f = retry_on_deadlock(session)(func)
session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = True
try:
result = f(*args, **kwargs)
session.flush()
session.expunge_all()
session.commit()
return result
except Exception:
session.rollback()
raise
finally:
session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = False
return wrapper | [
"def",
"atomic",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"self",
".",
"session",
"session_info",
"=",
"session",
".",
"info",
"if",
"session_info",
".",
"get",
"(",
"_ATOMIC_FLAG_SESSION_INFO_KEY",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"f",
"=",
"retry_on_deadlock",
"(",
"session",
")",
"(",
"func",
")",
"session_info",
"[",
"_ATOMIC_FLAG_SESSION_INFO_KEY",
"]",
"=",
"True",
"try",
":",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"session",
".",
"flush",
"(",
")",
"session",
".",
"expunge_all",
"(",
")",
"session",
".",
"commit",
"(",
")",
"return",
"result",
"except",
"Exception",
":",
"session",
".",
"rollback",
"(",
")",
"raise",
"finally",
":",
"session_info",
"[",
"_ATOMIC_FLAG_SESSION_INFO_KEY",
"]",
"=",
"False",
"return",
"wrapper"
] | A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function ``f``, which is wrapped in an
atomic block. Wrapping a function in an atomic block gives
several guarantees:
1. The database transaction will be automatically committed if
the function returns normally, and automatically rolled
back if the function raises unhandled exception.
2. When the transaction is committed, all objects in
``db.session`` will be expunged. This means that no lazy
loading will be performed on them.
3. If a transaction serialization error occurs during the
execution of the function, the function will be
re-executed. (It might be re-executed several times.)
Atomic blocks can be nested, but in this case the outermost
block takes full control of transaction's life-cycle, and
inner blocks do nothing. | [
"A",
"decorator",
"that",
"wraps",
"a",
"function",
"in",
"an",
"atomic",
"block",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L129-L185 |
epandurski/flask_signalbus | flask_signalbus/atomic.py | AtomicProceduresMixin.retry_on_integrity_error | def retry_on_integrity_error(self):
"""Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
:class:`~sqlalchemy.exc.IntegrityError` if another transaction
inserted a row with this primary key in the meantime. But if
we do (within an atomic block)::
with db.retry_on_integrity_error():
db.session.add(instance)
then if the before-mentioned race condition occurs,
`DBSerializationError` will be raised instead of
:class:`~sqlalchemy.exc.IntegrityError`, so that the
transaction will be retried (by the atomic block), and the
second time our prior-to-INSERT check will correctly detect a
primary key collision.
Note: :meth:`retry_on_integrity_error` triggers a session
flush.
"""
session = self.session
assert session.info.get(_ATOMIC_FLAG_SESSION_INFO_KEY), \
'Calls to "retry_on_integrity_error" must be wrapped in atomic block.'
session.flush()
try:
yield
session.flush()
except IntegrityError:
raise DBSerializationError | python | def retry_on_integrity_error(self):
"""Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
:class:`~sqlalchemy.exc.IntegrityError` if another transaction
inserted a row with this primary key in the meantime. But if
we do (within an atomic block)::
with db.retry_on_integrity_error():
db.session.add(instance)
then if the before-mentioned race condition occurs,
`DBSerializationError` will be raised instead of
:class:`~sqlalchemy.exc.IntegrityError`, so that the
transaction will be retried (by the atomic block), and the
second time our prior-to-INSERT check will correctly detect a
primary key collision.
Note: :meth:`retry_on_integrity_error` triggers a session
flush.
"""
session = self.session
assert session.info.get(_ATOMIC_FLAG_SESSION_INFO_KEY), \
'Calls to "retry_on_integrity_error" must be wrapped in atomic block.'
session.flush()
try:
yield
session.flush()
except IntegrityError:
raise DBSerializationError | [
"def",
"retry_on_integrity_error",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"session",
"assert",
"session",
".",
"info",
".",
"get",
"(",
"_ATOMIC_FLAG_SESSION_INFO_KEY",
")",
",",
"'Calls to \"retry_on_integrity_error\" must be wrapped in atomic block.'",
"session",
".",
"flush",
"(",
")",
"try",
":",
"yield",
"session",
".",
"flush",
"(",
")",
"except",
"IntegrityError",
":",
"raise",
"DBSerializationError"
] | Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
:class:`~sqlalchemy.exc.IntegrityError` if another transaction
inserted a row with this primary key in the meantime. But if
we do (within an atomic block)::
with db.retry_on_integrity_error():
db.session.add(instance)
then if the before-mentioned race condition occurs,
`DBSerializationError` will be raised instead of
:class:`~sqlalchemy.exc.IntegrityError`, so that the
transaction will be retried (by the atomic block), and the
second time our prior-to-INSERT check will correctly detect a
primary key collision.
Note: :meth:`retry_on_integrity_error` triggers a session
flush. | [
"Re",
"-",
"raise",
":",
"class",
":",
"~sqlalchemy",
".",
"exc",
".",
"IntegrityError",
"as",
"DBSerializationError",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L209-L243 |
intelligenia/modeltranslation | modeltranslation/translation.py | _save_translations | def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
"""
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translations
if not hasattr(cls._meta, "translatable_fields"):
return False
# For each translatable field, get its value, computes its md5 and for each language creates its
# empty translation.
for field in cls._meta.translatable_fields:
value = getattr(instance,field)
if not value is None:
md5_value = checksum(value)
setattr( instance, u"md5"+field, md5_value )
for lang in settings.LANGUAGES:
lang = lang[0]
# print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE)
if lang != settings.LANGUAGE_CODE:
context = u"Updating from object"
if hasattr(instance, "trans_context"):
context = getattr(instance, "trans_context")
trans = FieldTranslation.update(instance, field, lang, context) | python | def _save_translations(sender, instance, *args, **kwargs):
"""
This signal saves model translations.
"""
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translations
if not hasattr(cls._meta, "translatable_fields"):
return False
# For each translatable field, get its value, computes its md5 and for each language creates its
# empty translation.
for field in cls._meta.translatable_fields:
value = getattr(instance,field)
if not value is None:
md5_value = checksum(value)
setattr( instance, u"md5"+field, md5_value )
for lang in settings.LANGUAGES:
lang = lang[0]
# print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE)
if lang != settings.LANGUAGE_CODE:
context = u"Updating from object"
if hasattr(instance, "trans_context"):
context = getattr(instance, "trans_context")
trans = FieldTranslation.update(instance, field, lang, context) | [
"def",
"_save_translations",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# If we are in a site with one language there is no need of saving translations",
"if",
"site_is_monolingual",
"(",
")",
":",
"return",
"False",
"cls",
"=",
"sender",
"# If its class has no \"translatable_fields\" then there are no translations",
"if",
"not",
"hasattr",
"(",
"cls",
".",
"_meta",
",",
"\"translatable_fields\"",
")",
":",
"return",
"False",
"# For each translatable field, get its value, computes its md5 and for each language creates its",
"# empty translation.",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"translatable_fields",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"field",
")",
"if",
"not",
"value",
"is",
"None",
":",
"md5_value",
"=",
"checksum",
"(",
"value",
")",
"setattr",
"(",
"instance",
",",
"u\"md5\"",
"+",
"field",
",",
"md5_value",
")",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
":",
"lang",
"=",
"lang",
"[",
"0",
"]",
"# print \"({0}!={1}) = {2}\".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE)",
"if",
"lang",
"!=",
"settings",
".",
"LANGUAGE_CODE",
":",
"context",
"=",
"u\"Updating from object\"",
"if",
"hasattr",
"(",
"instance",
",",
"\"trans_context\"",
")",
":",
"context",
"=",
"getattr",
"(",
"instance",
",",
"\"trans_context\"",
")",
"trans",
"=",
"FieldTranslation",
".",
"update",
"(",
"instance",
",",
"field",
",",
"lang",
",",
"context",
")"
] | This signal saves model translations. | [
"This",
"signal",
"saves",
"model",
"translations",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L53-L82 |
intelligenia/modeltranslation | modeltranslation/translation.py | _get_fieldtranslations | def _get_fieldtranslations(instance, field=None, lang=None):
"""
Get all the translations for this object.
"""
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"] = lang
# If we specify a field we get ONE translation (this field translation)
if field:
_filter["field"] = field
try:
return FieldTranslation.objects.get(**_filter)
except FieldTranslation.DoesNotExist:
return False
# Otherwise, we get all translations
return FieldTranslation.objects.filter(**_filter) | python | def _get_fieldtranslations(instance, field=None, lang=None):
"""
Get all the translations for this object.
"""
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"] = lang
# If we specify a field we get ONE translation (this field translation)
if field:
_filter["field"] = field
try:
return FieldTranslation.objects.get(**_filter)
except FieldTranslation.DoesNotExist:
return False
# Otherwise, we get all translations
return FieldTranslation.objects.filter(**_filter) | [
"def",
"_get_fieldtranslations",
"(",
"instance",
",",
"field",
"=",
"None",
",",
"lang",
"=",
"None",
")",
":",
"# Basic filtering: filter translations by module, model an object_id",
"_filter",
"=",
"{",
"\"module\"",
":",
"instance",
".",
"__module__",
",",
"\"model\"",
":",
"instance",
".",
"__class__",
".",
"__name__",
",",
"\"object_id\"",
":",
"instance",
".",
"id",
"}",
"if",
"lang",
":",
"_filter",
"[",
"\"lang\"",
"]",
"=",
"lang",
"# If we specify a field we get ONE translation (this field translation)",
"if",
"field",
":",
"_filter",
"[",
"\"field\"",
"]",
"=",
"field",
"try",
":",
"return",
"FieldTranslation",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"_filter",
")",
"except",
"FieldTranslation",
".",
"DoesNotExist",
":",
"return",
"False",
"# Otherwise, we get all translations",
"return",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"_filter",
")"
] | Get all the translations for this object. | [
"Get",
"all",
"the",
"translations",
"for",
"this",
"object",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L93-L113 |
intelligenia/modeltranslation | modeltranslation/translation.py | _load_translations | def _load_translations(instance, lang=None):
"""
Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy
"""
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for this language
field_lang = trans_attr(translation_i.field, translation_i.lang)
setattr(instance, field_lang, translation_i.translation)
# Sets is_fuzzy value for this language
field_isfuzzy_lang = trans_is_fuzzy_attr(translation_i.field, translation_i.lang)
#print "{0} ({1}), attr_name={2} value={3}".format(translation.field, translation.lang, isfuzzy_lang,translation.is_fuzzy)
setattr(instance, field_isfuzzy_lang, translation_i.is_fuzzy)
return True | python | def _load_translations(instance, lang=None):
"""
Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy
"""
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for this language
field_lang = trans_attr(translation_i.field, translation_i.lang)
setattr(instance, field_lang, translation_i.translation)
# Sets is_fuzzy value for this language
field_isfuzzy_lang = trans_is_fuzzy_attr(translation_i.field, translation_i.lang)
#print "{0} ({1}), attr_name={2} value={3}".format(translation.field, translation.lang, isfuzzy_lang,translation.is_fuzzy)
setattr(instance, field_isfuzzy_lang, translation_i.is_fuzzy)
return True | [
"def",
"_load_translations",
"(",
"instance",
",",
"lang",
"=",
"None",
")",
":",
"# Gets field translations",
"translations",
"=",
"_get_fieldtranslations",
"(",
"instance",
"=",
"instance",
",",
"lang",
"=",
"lang",
")",
"for",
"translation_i",
"in",
"translations",
":",
"# Sets translated field lang for this language",
"field_lang",
"=",
"trans_attr",
"(",
"translation_i",
".",
"field",
",",
"translation_i",
".",
"lang",
")",
"setattr",
"(",
"instance",
",",
"field_lang",
",",
"translation_i",
".",
"translation",
")",
"# Sets is_fuzzy value for this language",
"field_isfuzzy_lang",
"=",
"trans_is_fuzzy_attr",
"(",
"translation_i",
".",
"field",
",",
"translation_i",
".",
"lang",
")",
"#print \"{0} ({1}), attr_name={2} value={3}\".format(translation.field, translation.lang, isfuzzy_lang,translation.is_fuzzy)",
"setattr",
"(",
"instance",
",",
"field_isfuzzy_lang",
",",
"translation_i",
".",
"is_fuzzy",
")",
"return",
"True"
] | Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy | [
"Loads",
"all",
"translations",
"as",
"dynamic",
"attributes",
":",
"<attr",
">",
"_<lang_code",
">",
"<attr",
">",
"_<lang_code",
">",
"_is_fuzzy"
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L118-L134 |
intelligenia/modeltranslation | modeltranslation/translation.py | _set_dict_translations | def _set_dict_translations(instance, dict_translations):
"""
Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones.
"""
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
# Translatable fields
translatable_fields = instance._meta.translatable_fields
# For each translatable field and for each language (excluding default language), we have to see if there is
# two dynamic fields:
# - <attribute>_<language_code>: translated atribute in <language_code>.
# For example: name_fr, name_es, description_it, etc.
# - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>.
# For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc.
for field in translatable_fields:
for lang in settings.LANGUAGES:
lang = lang[0]
if lang != settings.LANGUAGE_CODE:
# Translated field name
trans_field = trans_attr(field,lang)
# If translated field name is in the dict, we assign it to the object
if dict_translations.has_key(trans_field):
setattr(instance,trans_field,dict_translations[trans_field])
# Is fuzzy attribute
trans_isfuzzy = trans_is_fuzzy_attr(field,lang)
# If "is fuzzy" name is in the dict, we assign it to the object
if dict_translations.has_key(trans_isfuzzy):
is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1)
setattr(instance,trans_isfuzzy, is_fuzzy_value) | python | def _set_dict_translations(instance, dict_translations):
"""
Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones.
"""
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
# Translatable fields
translatable_fields = instance._meta.translatable_fields
# For each translatable field and for each language (excluding default language), we have to see if there is
# two dynamic fields:
# - <attribute>_<language_code>: translated atribute in <language_code>.
# For example: name_fr, name_es, description_it, etc.
# - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>.
# For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc.
for field in translatable_fields:
for lang in settings.LANGUAGES:
lang = lang[0]
if lang != settings.LANGUAGE_CODE:
# Translated field name
trans_field = trans_attr(field,lang)
# If translated field name is in the dict, we assign it to the object
if dict_translations.has_key(trans_field):
setattr(instance,trans_field,dict_translations[trans_field])
# Is fuzzy attribute
trans_isfuzzy = trans_is_fuzzy_attr(field,lang)
# If "is fuzzy" name is in the dict, we assign it to the object
if dict_translations.has_key(trans_isfuzzy):
is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1)
setattr(instance,trans_isfuzzy, is_fuzzy_value) | [
"def",
"_set_dict_translations",
"(",
"instance",
",",
"dict_translations",
")",
":",
"# If class has no translatable fields get out",
"if",
"not",
"hasattr",
"(",
"instance",
".",
"_meta",
",",
"\"translatable_fields\"",
")",
":",
"return",
"False",
"# If we are in a site with one language there is no need of saving translations",
"if",
"site_is_monolingual",
"(",
")",
":",
"return",
"False",
"# Translatable fields",
"translatable_fields",
"=",
"instance",
".",
"_meta",
".",
"translatable_fields",
"# For each translatable field and for each language (excluding default language), we have to see if there is",
"# two dynamic fields:",
"# - <attribute>_<language_code>: translated atribute in <language_code>.",
"# For example: name_fr, name_es, description_it, etc.",
"# - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>.",
"# For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc.",
"for",
"field",
"in",
"translatable_fields",
":",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
":",
"lang",
"=",
"lang",
"[",
"0",
"]",
"if",
"lang",
"!=",
"settings",
".",
"LANGUAGE_CODE",
":",
"# Translated field name",
"trans_field",
"=",
"trans_attr",
"(",
"field",
",",
"lang",
")",
"# If translated field name is in the dict, we assign it to the object",
"if",
"dict_translations",
".",
"has_key",
"(",
"trans_field",
")",
":",
"setattr",
"(",
"instance",
",",
"trans_field",
",",
"dict_translations",
"[",
"trans_field",
"]",
")",
"# Is fuzzy attribute",
"trans_isfuzzy",
"=",
"trans_is_fuzzy_attr",
"(",
"field",
",",
"lang",
")",
"# If \"is fuzzy\" name is in the dict, we assign it to the object",
"if",
"dict_translations",
".",
"has_key",
"(",
"trans_isfuzzy",
")",
":",
"is_fuzzy_value",
"=",
"(",
"dict_translations",
"[",
"trans_isfuzzy",
"]",
"==",
"\"1\"",
")",
"or",
"(",
"dict_translations",
"[",
"trans_isfuzzy",
"]",
"==",
"1",
")",
"setattr",
"(",
"instance",
",",
"trans_isfuzzy",
",",
"is_fuzzy_value",
")"
] | Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones. | [
"Establece",
"los",
"atributos",
"de",
"traducciones",
"a",
"partir",
"de",
"una",
"dict",
"que",
"contiene",
"todas",
"las",
"traducciones",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L139-L178 |
intelligenia/modeltranslation | modeltranslation/translation.py | add_translation | def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslations", _get_fieldtranslations)
# 3. Adss load_translations. Remember that this method included all the translations as dynamic attributes.
sender.add_to_class("load_translations", _load_translations)
# 4. Adds _set_dict_translations. This methods allows us setting all the translated fields form a dict.
# Very useful when dealing with ModelForms.
sender.add_to_class("set_translation_fields", _set_dict_translations)
# 5. This methods returns one translated attribute in Django.
# Avoid using _ and use get_trans_attr because Django maketranslations parser is fooled believing that everything
# inside _ methods is translatable.
sender.add_to_class("_", _get_translated_field)
sender.add_to_class("get_trans_attr", _get_translated_field)
sender.add_to_class("_t", _get_translated_field) | python | def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslations", _get_fieldtranslations)
# 3. Adss load_translations. Remember that this method included all the translations as dynamic attributes.
sender.add_to_class("load_translations", _load_translations)
# 4. Adds _set_dict_translations. This methods allows us setting all the translated fields form a dict.
# Very useful when dealing with ModelForms.
sender.add_to_class("set_translation_fields", _set_dict_translations)
# 5. This methods returns one translated attribute in Django.
# Avoid using _ and use get_trans_attr because Django maketranslations parser is fooled believing that everything
# inside _ methods is translatable.
sender.add_to_class("_", _get_translated_field)
sender.add_to_class("get_trans_attr", _get_translated_field)
sender.add_to_class("_t", _get_translated_field) | [
"def",
"add_translation",
"(",
"sender",
")",
":",
"# 1. Execute _save_translations when saving an object",
"signals",
".",
"post_save",
".",
"connect",
"(",
"_save_translations",
",",
"sender",
"=",
"sender",
")",
"# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.",
"sender",
".",
"add_to_class",
"(",
"\"get_fieldtranslations\"",
",",
"_get_fieldtranslations",
")",
"# 3. Adss load_translations. Remember that this method included all the translations as dynamic attributes.",
"sender",
".",
"add_to_class",
"(",
"\"load_translations\"",
",",
"_load_translations",
")",
"# 4. Adds _set_dict_translations. This methods allows us setting all the translated fields form a dict.",
"# Very useful when dealing with ModelForms.",
"sender",
".",
"add_to_class",
"(",
"\"set_translation_fields\"",
",",
"_set_dict_translations",
")",
"# 5. This methods returns one translated attribute in Django.",
"# Avoid using _ and use get_trans_attr because Django maketranslations parser is fooled believing that everything",
"# inside _ methods is translatable.",
"sender",
".",
"add_to_class",
"(",
"\"_\"",
",",
"_get_translated_field",
")",
"sender",
".",
"add_to_class",
"(",
"\"get_trans_attr\"",
",",
"_get_translated_field",
")",
"sender",
".",
"add_to_class",
"(",
"\"_t\"",
",",
"_get_translated_field",
")"
] | Adds the actions to a class. | [
"Adds",
"the",
"actions",
"to",
"a",
"class",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L216-L234 |
StorjOld/file-encryptor | file_encryptor/convergence.py | encrypt_file_inline | def encrypt_file_inline(filename, passphrase):
"""Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
:type filename: str
:param passphrase: The passphrase used to decrypt the file.
:type passphrase: str or None
:returns: The key required to decrypt the file.
:rtype: str
"""
key = key_generators.key_from_file(filename, passphrase)
inline_transform(filename, key)
return key | python | def encrypt_file_inline(filename, passphrase):
"""Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
:type filename: str
:param passphrase: The passphrase used to decrypt the file.
:type passphrase: str or None
:returns: The key required to decrypt the file.
:rtype: str
"""
key = key_generators.key_from_file(filename, passphrase)
inline_transform(filename, key)
return key | [
"def",
"encrypt_file_inline",
"(",
"filename",
",",
"passphrase",
")",
":",
"key",
"=",
"key_generators",
".",
"key_from_file",
"(",
"filename",
",",
"passphrase",
")",
"inline_transform",
"(",
"filename",
",",
"key",
")",
"return",
"key"
] | Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
:type filename: str
:param passphrase: The passphrase used to decrypt the file.
:type passphrase: str or None
:returns: The key required to decrypt the file.
:rtype: str | [
"Encrypt",
"file",
"inline",
"with",
"an",
"optional",
"passphrase",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L33-L51 |
StorjOld/file-encryptor | file_encryptor/convergence.py | inline_transform | def inline_transform(filename, key):
"""Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
"""
pos = 0
for chunk, fp in iter_transform(filename, key):
fp.seek(pos)
fp.write(chunk)
fp.flush()
pos = fp.tell() | python | def inline_transform(filename, key):
"""Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
"""
pos = 0
for chunk, fp in iter_transform(filename, key):
fp.seek(pos)
fp.write(chunk)
fp.flush()
pos = fp.tell() | [
"def",
"inline_transform",
"(",
"filename",
",",
"key",
")",
":",
"pos",
"=",
"0",
"for",
"chunk",
",",
"fp",
"in",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"fp",
".",
"seek",
"(",
"pos",
")",
"fp",
".",
"write",
"(",
"chunk",
")",
"fp",
".",
"flush",
"(",
")",
"pos",
"=",
"fp",
".",
"tell",
"(",
")"
] | Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str | [
"Encrypt",
"file",
"inline",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L85-L102 |
StorjOld/file-encryptor | file_encryptor/convergence.py | iter_transform | def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
:returns: A generator that produces encrypted file chunks.
:rtype: generator
"""
# We are not specifying the IV here.
aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128))
with open(filename, 'rb+') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
yield aes.encrypt(chunk), f | python | def iter_transform(filename, key):
"""Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
:returns: A generator that produces encrypted file chunks.
:rtype: generator
"""
# We are not specifying the IV here.
aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128))
with open(filename, 'rb+') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
yield aes.encrypt(chunk), f | [
"def",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"# We are not specifying the IV here.",
"aes",
"=",
"AES",
".",
"new",
"(",
"key",
",",
"AES",
".",
"MODE_CTR",
",",
"counter",
"=",
"Counter",
".",
"new",
"(",
"128",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"CHUNK_SIZE",
")",
",",
"b''",
")",
":",
"yield",
"aes",
".",
"encrypt",
"(",
"chunk",
")",
",",
"f"
] | Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
:returns: A generator that produces encrypted file chunks.
:rtype: generator | [
"Generate",
"encrypted",
"file",
"with",
"given",
"key",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/convergence.py#L105-L124 |
matllubos/django-is-core | is_core/auth/permissions.py | PermissionsSet.set | def set(self, name, permission):
"""
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance
"""
assert isinstance(permission, BasePermission), 'Only permission instances can be added to the set'
self._permissions[name] = permission | python | def set(self, name, permission):
"""
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance
"""
assert isinstance(permission, BasePermission), 'Only permission instances can be added to the set'
self._permissions[name] = permission | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"permission",
")",
":",
"assert",
"isinstance",
"(",
"permission",
",",
"BasePermission",
")",
",",
"'Only permission instances can be added to the set'",
"self",
".",
"_permissions",
"[",
"name",
"]",
"=",
"permission"
] | Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance | [
"Adds",
"permission",
"with",
"the",
"given",
"name",
"to",
"the",
"set",
".",
"Permission",
"with",
"the",
"same",
"name",
"will",
"be",
"overridden",
".",
"Args",
":",
"name",
":",
"name",
"of",
"the",
"permission",
"permission",
":",
"permission",
"instance"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/auth/permissions.py#L114-L123 |
matllubos/django-is-core | is_core/forms/boundfield.py | SmartBoundField.as_widget | def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
widget = self.field.widget
if self.field.localize:
widget.is_localized = True
attrs = attrs or {}
attrs = self.build_widget_attrs(attrs, widget)
auto_id = self.auto_id
if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
if not only_initial:
attrs['id'] = auto_id
else:
attrs['id'] = self.html_initial_id
if not only_initial:
name = self.html_name
else:
name = self.html_initial_name
if isinstance(widget, SmartWidgetMixin) and hasattr(self.form, '_request'):
return force_text(widget.smart_render(self.form._request, name, self.value(), self.initial,
self.form, attrs=attrs))
else:
return force_text(widget.render(name, self.value(), attrs=attrs)) | python | def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
widget = self.field.widget
if self.field.localize:
widget.is_localized = True
attrs = attrs or {}
attrs = self.build_widget_attrs(attrs, widget)
auto_id = self.auto_id
if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
if not only_initial:
attrs['id'] = auto_id
else:
attrs['id'] = self.html_initial_id
if not only_initial:
name = self.html_name
else:
name = self.html_initial_name
if isinstance(widget, SmartWidgetMixin) and hasattr(self.form, '_request'):
return force_text(widget.smart_render(self.form._request, name, self.value(), self.initial,
self.form, attrs=attrs))
else:
return force_text(widget.render(name, self.value(), attrs=attrs)) | [
"def",
"as_widget",
"(",
"self",
",",
"widget",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"only_initial",
"=",
"False",
")",
":",
"if",
"not",
"widget",
":",
"widget",
"=",
"self",
".",
"field",
".",
"widget",
"if",
"self",
".",
"field",
".",
"localize",
":",
"widget",
".",
"is_localized",
"=",
"True",
"attrs",
"=",
"attrs",
"or",
"{",
"}",
"attrs",
"=",
"self",
".",
"build_widget_attrs",
"(",
"attrs",
",",
"widget",
")",
"auto_id",
"=",
"self",
".",
"auto_id",
"if",
"auto_id",
"and",
"'id'",
"not",
"in",
"attrs",
"and",
"'id'",
"not",
"in",
"widget",
".",
"attrs",
":",
"if",
"not",
"only_initial",
":",
"attrs",
"[",
"'id'",
"]",
"=",
"auto_id",
"else",
":",
"attrs",
"[",
"'id'",
"]",
"=",
"self",
".",
"html_initial_id",
"if",
"not",
"only_initial",
":",
"name",
"=",
"self",
".",
"html_name",
"else",
":",
"name",
"=",
"self",
".",
"html_initial_name",
"if",
"isinstance",
"(",
"widget",
",",
"SmartWidgetMixin",
")",
"and",
"hasattr",
"(",
"self",
".",
"form",
",",
"'_request'",
")",
":",
"return",
"force_text",
"(",
"widget",
".",
"smart_render",
"(",
"self",
".",
"form",
".",
"_request",
",",
"name",
",",
"self",
".",
"value",
"(",
")",
",",
"self",
".",
"initial",
",",
"self",
".",
"form",
",",
"attrs",
"=",
"attrs",
")",
")",
"else",
":",
"return",
"force_text",
"(",
"widget",
".",
"render",
"(",
"name",
",",
"self",
".",
"value",
"(",
")",
",",
"attrs",
"=",
"attrs",
")",
")"
] | Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used. | [
"Renders",
"the",
"field",
"by",
"rendering",
"the",
"passed",
"widget",
"adding",
"any",
"HTML",
"attributes",
"passed",
"as",
"attrs",
".",
"If",
"no",
"widget",
"is",
"specified",
"then",
"the",
"field",
"s",
"default",
"widget",
"will",
"be",
"used",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/boundfield.py#L12-L41 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | _setup_schema | def _setup_schema(Base, session):
"""Create a function which adds `__marshmallow__` attribute to all signal models."""
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
model = m
else:
class Meta(object):
model = m
sqla_session = session
schema_class_name = '%sSchema' % m.__name__
return type(schema_class_name, (ModelSchema,), {'Meta': Meta})
def setup_schema_fn():
for model in Base._decl_class_registry.values():
if hasattr(model, '__tablename__'):
if model.__name__.endswith("Schema"):
raise ModelConversionError(
'Unexpected model name: "{}". '
'For safety, _setup_schema() can not be used when a '
'model class ends with "Schema".'.format(model.__name__)
)
schema_class = getattr(model, '__marshmallow__', None)
if schema_class is None:
schema_class = model.__marshmallow__ = create_schema_class(model)
if hasattr(model, 'send_signalbus_message'):
setattr(model, '__marshmallow_schema__', schema_class())
return setup_schema_fn | python | def _setup_schema(Base, session):
"""Create a function which adds `__marshmallow__` attribute to all signal models."""
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
model = m
else:
class Meta(object):
model = m
sqla_session = session
schema_class_name = '%sSchema' % m.__name__
return type(schema_class_name, (ModelSchema,), {'Meta': Meta})
def setup_schema_fn():
for model in Base._decl_class_registry.values():
if hasattr(model, '__tablename__'):
if model.__name__.endswith("Schema"):
raise ModelConversionError(
'Unexpected model name: "{}". '
'For safety, _setup_schema() can not be used when a '
'model class ends with "Schema".'.format(model.__name__)
)
schema_class = getattr(model, '__marshmallow__', None)
if schema_class is None:
schema_class = model.__marshmallow__ = create_schema_class(model)
if hasattr(model, 'send_signalbus_message'):
setattr(model, '__marshmallow_schema__', schema_class())
return setup_schema_fn | [
"def",
"_setup_schema",
"(",
"Base",
",",
"session",
")",
":",
"def",
"create_schema_class",
"(",
"m",
")",
":",
"if",
"hasattr",
"(",
"m",
",",
"'send_signalbus_message'",
")",
":",
"# Signal models should not use the SQLAlchemy session.",
"class",
"Meta",
"(",
"object",
")",
":",
"model",
"=",
"m",
"else",
":",
"class",
"Meta",
"(",
"object",
")",
":",
"model",
"=",
"m",
"sqla_session",
"=",
"session",
"schema_class_name",
"=",
"'%sSchema'",
"%",
"m",
".",
"__name__",
"return",
"type",
"(",
"schema_class_name",
",",
"(",
"ModelSchema",
",",
")",
",",
"{",
"'Meta'",
":",
"Meta",
"}",
")",
"def",
"setup_schema_fn",
"(",
")",
":",
"for",
"model",
"in",
"Base",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"model",
",",
"'__tablename__'",
")",
":",
"if",
"model",
".",
"__name__",
".",
"endswith",
"(",
"\"Schema\"",
")",
":",
"raise",
"ModelConversionError",
"(",
"'Unexpected model name: \"{}\". '",
"'For safety, _setup_schema() can not be used when a '",
"'model class ends with \"Schema\".'",
".",
"format",
"(",
"model",
".",
"__name__",
")",
")",
"schema_class",
"=",
"getattr",
"(",
"model",
",",
"'__marshmallow__'",
",",
"None",
")",
"if",
"schema_class",
"is",
"None",
":",
"schema_class",
"=",
"model",
".",
"__marshmallow__",
"=",
"create_schema_class",
"(",
"model",
")",
"if",
"hasattr",
"(",
"model",
",",
"'send_signalbus_message'",
")",
":",
"setattr",
"(",
"model",
",",
"'__marshmallow_schema__'",
",",
"schema_class",
"(",
")",
")",
"return",
"setup_schema_fn"
] | Create a function which adds `__marshmallow__` attribute to all signal models. | [
"Create",
"a",
"function",
"which",
"adds",
"__marshmallow__",
"attribute",
"to",
"all",
"signal",
"models",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L272-L303 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBusMixin.signalbus | def signalbus(self):
"""The associated `SignalBus` object."""
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | python | def signalbus(self):
"""The associated `SignalBus` object."""
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | [
"def",
"signalbus",
"(",
"self",
")",
":",
"try",
":",
"signalbus",
"=",
"self",
".",
"__signalbus",
"except",
"AttributeError",
":",
"signalbus",
"=",
"self",
".",
"__signalbus",
"=",
"SignalBus",
"(",
"self",
",",
"init_app",
"=",
"False",
")",
"return",
"signalbus"
] | The associated `SignalBus` object. | [
"The",
"associated",
"SignalBus",
"object",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L53-L60 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.get_signal_models | def get_signal_models(self):
"""Return all signal types in a list.
:rtype: list(`signal-model`)
"""
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
and hasattr(cls, 'send_signalbus_message')
)
] | python | def get_signal_models(self):
"""Return all signal types in a list.
:rtype: list(`signal-model`)
"""
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
and hasattr(cls, 'send_signalbus_message')
)
] | [
"def",
"get_signal_models",
"(",
"self",
")",
":",
"base",
"=",
"self",
".",
"db",
".",
"Model",
"return",
"[",
"cls",
"for",
"cls",
"in",
"base",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
"if",
"(",
"isinstance",
"(",
"cls",
",",
"type",
")",
"and",
"issubclass",
"(",
"cls",
",",
"base",
")",
"and",
"hasattr",
"(",
"cls",
",",
"'send_signalbus_message'",
")",
")",
"]"
] | Return all signal types in a list.
:rtype: list(`signal-model`) | [
"Return",
"all",
"signal",
"types",
"in",
"a",
"list",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L118-L132 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.flush | def flush(self, models=None, wait=3.0):
"""Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after obtaining the list of pending signals, to allow
concurrent senders to complete
:return: The total number of signals that have been sent
"""
models_to_flush = self.get_signal_models() if models is None else models
pks_to_flush = {}
try:
for model in models_to_flush:
_raise_error_if_not_signal_model(model)
m = inspect(model)
pk_attrs = [m.get_property_by_column(c).class_attribute for c in m.primary_key]
pks_to_flush[model] = self.signal_session.query(*pk_attrs).all()
self.signal_session.rollback()
time.sleep(wait)
return sum(
self._flush_signals_with_retry(model, pk_values_set=set(pks_to_flush[model]))
for model in models_to_flush
)
finally:
self.signal_session.remove() | python | def flush(self, models=None, wait=3.0):
"""Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after obtaining the list of pending signals, to allow
concurrent senders to complete
:return: The total number of signals that have been sent
"""
models_to_flush = self.get_signal_models() if models is None else models
pks_to_flush = {}
try:
for model in models_to_flush:
_raise_error_if_not_signal_model(model)
m = inspect(model)
pk_attrs = [m.get_property_by_column(c).class_attribute for c in m.primary_key]
pks_to_flush[model] = self.signal_session.query(*pk_attrs).all()
self.signal_session.rollback()
time.sleep(wait)
return sum(
self._flush_signals_with_retry(model, pk_values_set=set(pks_to_flush[model]))
for model in models_to_flush
)
finally:
self.signal_session.remove() | [
"def",
"flush",
"(",
"self",
",",
"models",
"=",
"None",
",",
"wait",
"=",
"3.0",
")",
":",
"models_to_flush",
"=",
"self",
".",
"get_signal_models",
"(",
")",
"if",
"models",
"is",
"None",
"else",
"models",
"pks_to_flush",
"=",
"{",
"}",
"try",
":",
"for",
"model",
"in",
"models_to_flush",
":",
"_raise_error_if_not_signal_model",
"(",
"model",
")",
"m",
"=",
"inspect",
"(",
"model",
")",
"pk_attrs",
"=",
"[",
"m",
".",
"get_property_by_column",
"(",
"c",
")",
".",
"class_attribute",
"for",
"c",
"in",
"m",
".",
"primary_key",
"]",
"pks_to_flush",
"[",
"model",
"]",
"=",
"self",
".",
"signal_session",
".",
"query",
"(",
"*",
"pk_attrs",
")",
".",
"all",
"(",
")",
"self",
".",
"signal_session",
".",
"rollback",
"(",
")",
"time",
".",
"sleep",
"(",
"wait",
")",
"return",
"sum",
"(",
"self",
".",
"_flush_signals_with_retry",
"(",
"model",
",",
"pk_values_set",
"=",
"set",
"(",
"pks_to_flush",
"[",
"model",
"]",
")",
")",
"for",
"model",
"in",
"models_to_flush",
")",
"finally",
":",
"self",
".",
"signal_session",
".",
"remove",
"(",
")"
] | Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after obtaining the list of pending signals, to allow
concurrent senders to complete
:return: The total number of signals that have been sent | [
"Send",
"all",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L134-L161 |
epandurski/flask_signalbus | flask_signalbus/signalbus.py | SignalBus.flushmany | def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when recovering from long periods
of disconnectedness from the message bus.
:return: The total number of signals that have been sent
"""
models_to_flush = self.get_signal_models()
try:
return sum(self._flushmany_signals(model) for model in models_to_flush)
finally:
self.signal_session.remove() | python | def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when recovering from long periods
of disconnectedness from the message bus.
:return: The total number of signals that have been sent
"""
models_to_flush = self.get_signal_models()
try:
return sum(self._flushmany_signals(model) for model in models_to_flush)
finally:
self.signal_session.remove() | [
"def",
"flushmany",
"(",
"self",
")",
":",
"models_to_flush",
"=",
"self",
".",
"get_signal_models",
"(",
")",
"try",
":",
"return",
"sum",
"(",
"self",
".",
"_flushmany_signals",
"(",
"model",
")",
"for",
"model",
"in",
"models_to_flush",
")",
"finally",
":",
"self",
".",
"signal_session",
".",
"remove",
"(",
")"
] | Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when recovering from long periods
of disconnectedness from the message bus.
:return: The total number of signals that have been sent | [
"Send",
"a",
"potentially",
"huge",
"number",
"of",
"pending",
"signals",
"over",
"the",
"message",
"bus",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/signalbus.py#L163-L180 |
sprockets/sprockets.http | examples.py | StatusHandler.get | def get(self, status_code):
"""
Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase
"""
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_code}
if self.get_query_argument('reason', None):
kwargs['reason'] = self.get_query_argument('reason')
if self.get_query_argument('log_message', None):
kwargs['log_message'] = self.get_query_argument('log_message')
self.send_error(**kwargs)
else:
self.set_status(status_code) | python | def get(self, status_code):
"""
Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase
"""
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_code}
if self.get_query_argument('reason', None):
kwargs['reason'] = self.get_query_argument('reason')
if self.get_query_argument('log_message', None):
kwargs['log_message'] = self.get_query_argument('log_message')
self.send_error(**kwargs)
else:
self.set_status(status_code) | [
"def",
"get",
"(",
"self",
",",
"status_code",
")",
":",
"status_code",
"=",
"int",
"(",
"status_code",
")",
"if",
"status_code",
">=",
"400",
":",
"kwargs",
"=",
"{",
"'status_code'",
":",
"status_code",
"}",
"if",
"self",
".",
"get_query_argument",
"(",
"'reason'",
",",
"None",
")",
":",
"kwargs",
"[",
"'reason'",
"]",
"=",
"self",
".",
"get_query_argument",
"(",
"'reason'",
")",
"if",
"self",
".",
"get_query_argument",
"(",
"'log_message'",
",",
"None",
")",
":",
"kwargs",
"[",
"'log_message'",
"]",
"=",
"self",
".",
"get_query_argument",
"(",
"'log_message'",
")",
"self",
".",
"send_error",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"self",
".",
"set_status",
"(",
"status_code",
")"
] | Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase | [
"Returns",
"the",
"requested",
"status",
"."
] | train | https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/examples.py#L10-L27 |
inveniosoftware/invenio-iiif | invenio_iiif/ext.py | InvenioIIIF.init_app | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
self.iiif_ext = IIIF(app=app)
self.iiif_ext.api_decorator_handler(protect_api)
self.iiif_ext.uuid_to_image_opener_handler(image_opener)
app.extensions['invenio-iiif'] = self | python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
self.iiif_ext = IIIF(app=app)
self.iiif_ext.api_decorator_handler(protect_api)
self.iiif_ext.uuid_to_image_opener_handler(image_opener)
app.extensions['invenio-iiif'] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"self",
".",
"iiif_ext",
"=",
"IIIF",
"(",
"app",
"=",
"app",
")",
"self",
".",
"iiif_ext",
".",
"api_decorator_handler",
"(",
"protect_api",
")",
"self",
".",
"iiif_ext",
".",
"uuid_to_image_opener_handler",
"(",
"image_opener",
")",
"app",
".",
"extensions",
"[",
"'invenio-iiif'",
"]",
"=",
"self"
] | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/ext.py#L28-L34 |
inveniosoftware/invenio-iiif | invenio_iiif/ext.py | InvenioIIIFAPI.init_app | def init_app(self, app):
"""Flask application initialization."""
super(InvenioIIIFAPI, self).init_app(app)
api = Api(app=app)
self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX']) | python | def init_app(self, app):
"""Flask application initialization."""
super(InvenioIIIFAPI, self).init_app(app)
api = Api(app=app)
self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX']) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"super",
"(",
"InvenioIIIFAPI",
",",
"self",
")",
".",
"init_app",
"(",
"app",
")",
"api",
"=",
"Api",
"(",
"app",
"=",
"app",
")",
"self",
".",
"iiif_ext",
".",
"init_restful",
"(",
"api",
",",
"prefix",
"=",
"app",
".",
"config",
"[",
"'IIIF_API_PREFIX'",
"]",
")"
] | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/ext.py#L46-L50 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_absolute_path | def get_absolute_path(self, path):
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
if os.path.isabs(path):
return path
else:
return os.path.abspath(os.path.join(self.config.BASEDIR, path)) | python | def get_absolute_path(self, path):
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
if os.path.isabs(path):
return path
else:
return os.path.abspath(os.path.join(self.config.BASEDIR, path)) | [
"def",
"get_absolute_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config",
".",
"BASEDIR",
",",
"path",
")",
")"
] | Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended. | [
"Returns",
"the",
"absolute",
"path",
"of",
"the",
"path",
"argument",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L25-L35 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_roles_paths | def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return roles | python | def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return roles | [
"def",
"get_roles_paths",
"(",
"self",
")",
":",
"roles",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"config",
".",
"ROLES",
":",
"roles",
".",
"append",
"(",
"self",
".",
"get_absolute_path",
"(",
"path",
")",
")",
"return",
"roles"
] | Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables. | [
"Returns",
"all",
"absolute",
"paths",
"to",
"the",
"roles",
"/",
"directories",
"while",
"considering",
"the",
"BASEDIR",
"and",
"ROLES",
"config",
"variables",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L37-L47 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_roles | def get_roles(self):
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
for entry in os.listdir(path):
rolepath = os.path.join(path, entry)
if os.path.isdir(rolepath):
roles[entry] = rolepath
return roles | python | def get_roles(self):
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
for entry in os.listdir(path):
rolepath = os.path.join(path, entry)
if os.path.isdir(rolepath):
roles[entry] = rolepath
return roles | [
"def",
"get_roles",
"(",
"self",
")",
":",
"roles",
"=",
"{",
"}",
"paths",
"=",
"self",
".",
"get_roles_paths",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"rolepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"entry",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"rolepath",
")",
":",
"roles",
"[",
"entry",
"]",
"=",
"rolepath",
"return",
"roles"
] | Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path. | [
"Returns",
"a",
"key",
"-",
"value",
"dict",
"with",
"a",
"roles",
"while",
"the",
"key",
"is",
"the",
"role",
"name",
"and",
"the",
"value",
"is",
"the",
"absolute",
"role",
"path",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L49-L63 |
confirm/ansibleci | ansibleci/helper.py | Helper.read_yaml | def read_yaml(self, filename):
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | python | def read_yaml(self, filename):
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | [
"def",
"read_yaml",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"d",
"=",
"re",
".",
"sub",
"(",
"r'\\{\\{ *([^ ]+) *\\}\\}'",
",",
"r'\\1'",
",",
"f",
".",
"read",
"(",
")",
")",
"y",
"=",
"yaml",
".",
"safe_load",
"(",
"d",
")",
"return",
"y",
"if",
"y",
"else",
"{",
"}"
] | Reads and parses a YAML file and returns the content. | [
"Reads",
"and",
"parses",
"a",
"YAML",
"file",
"and",
"returns",
"the",
"content",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L65-L72 |
confirm/ansibleci | ansibleci/helper.py | Helper.get_yaml_items | def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned.
'''
result = []
if not os.path.isdir(dir_path):
return []
for filename in os.listdir(dir_path):
path = os.path.join(dir_path, filename)
items = self.read_yaml(path)
for item in items:
if param:
if param in item:
item = item[param]
if isinstance(item, list):
result.extend(item)
else:
result.append(item)
else:
result.append(item)
return result | python | def get_yaml_items(self, dir_path, param=None):
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned.
'''
result = []
if not os.path.isdir(dir_path):
return []
for filename in os.listdir(dir_path):
path = os.path.join(dir_path, filename)
items = self.read_yaml(path)
for item in items:
if param:
if param in item:
item = item[param]
if isinstance(item, list):
result.extend(item)
else:
result.append(item)
else:
result.append(item)
return result | [
"def",
"get_yaml_items",
"(",
"self",
",",
"dir_path",
",",
"param",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_path",
")",
":",
"return",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"filename",
")",
"items",
"=",
"self",
".",
"read_yaml",
"(",
"path",
")",
"for",
"item",
"in",
"items",
":",
"if",
"param",
":",
"if",
"param",
"in",
"item",
":",
"item",
"=",
"item",
"[",
"param",
"]",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"result",
".",
"extend",
"(",
"item",
")",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] | Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned. | [
"Loops",
"through",
"the",
"dir_path",
"and",
"parses",
"all",
"YAML",
"files",
"inside",
"the",
"directory",
"."
] | train | https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/helper.py#L74-L105 |
The-Politico/django-slackchat-serializer | slackchat/tasks/webhook.py | clean_response | def clean_response(response):
""" Cleans string quoting in response. """
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | python | def clean_response(response):
""" Cleans string quoting in response. """
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | [
"def",
"clean_response",
"(",
"response",
")",
":",
"response",
"=",
"re",
".",
"sub",
"(",
"\"^['\\\"]\"",
",",
"\"\"",
",",
"response",
")",
"response",
"=",
"re",
".",
"sub",
"(",
"\"['\\\"]$\"",
",",
"\"\"",
",",
"response",
")",
"return",
"response"
] | Cleans string quoting in response. | [
"Cleans",
"string",
"quoting",
"in",
"response",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/tasks/webhook.py#L63-L67 |
epandurski/flask_signalbus | flask_signalbus/utils.py | retry_on_deadlock | def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
"""Return function decorator that executes the function again in case of a deadlock."""
def decorator(action):
"""Function decorator that retries `action` in case of a deadlock."""
@wraps(action)
def f(*args, **kwargs):
num_failures = 0
while True:
try:
return action(*args, **kwargs)
except (DBAPIError, DBSerializationError) as e:
num_failures += 1
is_serialization_error = (
isinstance(e, DBSerializationError)
or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES
)
if num_failures > retries or not is_serialization_error:
raise
session.rollback()
wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1))
time.sleep(wait_seconds)
return f
return decorator | python | def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0):
"""Return function decorator that executes the function again in case of a deadlock."""
def decorator(action):
"""Function decorator that retries `action` in case of a deadlock."""
@wraps(action)
def f(*args, **kwargs):
num_failures = 0
while True:
try:
return action(*args, **kwargs)
except (DBAPIError, DBSerializationError) as e:
num_failures += 1
is_serialization_error = (
isinstance(e, DBSerializationError)
or get_db_error_code(e.orig) in DEADLOCK_ERROR_CODES
)
if num_failures > retries or not is_serialization_error:
raise
session.rollback()
wait_seconds = min(max_wait, min_wait * 2 ** (num_failures - 1))
time.sleep(wait_seconds)
return f
return decorator | [
"def",
"retry_on_deadlock",
"(",
"session",
",",
"retries",
"=",
"6",
",",
"min_wait",
"=",
"0.1",
",",
"max_wait",
"=",
"10.0",
")",
":",
"def",
"decorator",
"(",
"action",
")",
":",
"\"\"\"Function decorator that retries `action` in case of a deadlock.\"\"\"",
"@",
"wraps",
"(",
"action",
")",
"def",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"num_failures",
"=",
"0",
"while",
"True",
":",
"try",
":",
"return",
"action",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"DBAPIError",
",",
"DBSerializationError",
")",
"as",
"e",
":",
"num_failures",
"+=",
"1",
"is_serialization_error",
"=",
"(",
"isinstance",
"(",
"e",
",",
"DBSerializationError",
")",
"or",
"get_db_error_code",
"(",
"e",
".",
"orig",
")",
"in",
"DEADLOCK_ERROR_CODES",
")",
"if",
"num_failures",
">",
"retries",
"or",
"not",
"is_serialization_error",
":",
"raise",
"session",
".",
"rollback",
"(",
")",
"wait_seconds",
"=",
"min",
"(",
"max_wait",
",",
"min_wait",
"*",
"2",
"**",
"(",
"num_failures",
"-",
"1",
")",
")",
"time",
".",
"sleep",
"(",
"wait_seconds",
")",
"return",
"f",
"return",
"decorator"
] | Return function decorator that executes the function again in case of a deadlock. | [
"Return",
"function",
"decorator",
"that",
"executes",
"the",
"function",
"again",
"in",
"case",
"of",
"a",
"deadlock",
"."
] | train | https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/utils.py#L28-L54 |
xapple/plumbing | plumbing/cache.py | cached | def cached(f):
"""Decorator for functions evaluated only once."""
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | python | def cached(f):
"""Decorator for functions evaluated only once."""
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | [
"def",
"cached",
"(",
"f",
")",
":",
"def",
"memoized",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"memoized",
",",
"'__cache__'",
")",
":",
"return",
"memoized",
".",
"__cache__",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"memoized",
".",
"__cache__",
"=",
"result",
"return",
"result",
"return",
"memoized"
] | Decorator for functions evaluated only once. | [
"Decorator",
"for",
"functions",
"evaluated",
"only",
"once",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L12-L20 |
xapple/plumbing | plumbing/cache.py | property_pickled | def property_pickled(f):
"""Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cached."""
# Called when you access the property #
def retrieve_from_cache(self):
# Is it in the cache ? #
if '__cache__' not in self.__dict__: self.__cache__ = {}
if f.__name__ in self.__cache__: return self.__cache__[f.__name__]
# Where should we look in the file system ? #
if 'cache_dir' in self.__dict__:
path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle')
else:
path = getattr(self.p, f.func_name)
# Is it on disk ? #
if path.exists:
with open(path) as handle: result = pickle.load(handle)
self.__cache__[f.__name__] = result
return result
# Otherwise let's compute it #
result = f(self)
with open(path, 'w') as handle: pickle.dump(result, handle)
self.__cache__[f.__name__] = result
return result
# Called when you set the property #
def overwrite_cache(self, value):
# Where should we look in the file system ? #
if 'cache_dir' in self.__dict__:
path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle')
else:
path = getattr(self.p, f.func_name)
if value is None: path.remove()
else: raise Exception("You can't set a pickled property, you can only delete it")
# Return a wrapper #
retrieve_from_cache.__doc__ = f.__doc__
return property(retrieve_from_cache, overwrite_cache) | python | def property_pickled(f):
"""Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cached."""
# Called when you access the property #
def retrieve_from_cache(self):
# Is it in the cache ? #
if '__cache__' not in self.__dict__: self.__cache__ = {}
if f.__name__ in self.__cache__: return self.__cache__[f.__name__]
# Where should we look in the file system ? #
if 'cache_dir' in self.__dict__:
path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle')
else:
path = getattr(self.p, f.func_name)
# Is it on disk ? #
if path.exists:
with open(path) as handle: result = pickle.load(handle)
self.__cache__[f.__name__] = result
return result
# Otherwise let's compute it #
result = f(self)
with open(path, 'w') as handle: pickle.dump(result, handle)
self.__cache__[f.__name__] = result
return result
# Called when you set the property #
def overwrite_cache(self, value):
# Where should we look in the file system ? #
if 'cache_dir' in self.__dict__:
path = FilePath(self.__dict__['cache_dir'] + f.func_name + '.pickle')
else:
path = getattr(self.p, f.func_name)
if value is None: path.remove()
else: raise Exception("You can't set a pickled property, you can only delete it")
# Return a wrapper #
retrieve_from_cache.__doc__ = f.__doc__
return property(retrieve_from_cache, overwrite_cache) | [
"def",
"property_pickled",
"(",
"f",
")",
":",
"# Called when you access the property #",
"def",
"retrieve_from_cache",
"(",
"self",
")",
":",
"# Is it in the cache ? #",
"if",
"'__cache__'",
"not",
"in",
"self",
".",
"__dict__",
":",
"self",
".",
"__cache__",
"=",
"{",
"}",
"if",
"f",
".",
"__name__",
"in",
"self",
".",
"__cache__",
":",
"return",
"self",
".",
"__cache__",
"[",
"f",
".",
"__name__",
"]",
"# Where should we look in the file system ? #",
"if",
"'cache_dir'",
"in",
"self",
".",
"__dict__",
":",
"path",
"=",
"FilePath",
"(",
"self",
".",
"__dict__",
"[",
"'cache_dir'",
"]",
"+",
"f",
".",
"func_name",
"+",
"'.pickle'",
")",
"else",
":",
"path",
"=",
"getattr",
"(",
"self",
".",
"p",
",",
"f",
".",
"func_name",
")",
"# Is it on disk ? #",
"if",
"path",
".",
"exists",
":",
"with",
"open",
"(",
"path",
")",
"as",
"handle",
":",
"result",
"=",
"pickle",
".",
"load",
"(",
"handle",
")",
"self",
".",
"__cache__",
"[",
"f",
".",
"__name__",
"]",
"=",
"result",
"return",
"result",
"# Otherwise let's compute it #",
"result",
"=",
"f",
"(",
"self",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"handle",
":",
"pickle",
".",
"dump",
"(",
"result",
",",
"handle",
")",
"self",
".",
"__cache__",
"[",
"f",
".",
"__name__",
"]",
"=",
"result",
"return",
"result",
"# Called when you set the property #",
"def",
"overwrite_cache",
"(",
"self",
",",
"value",
")",
":",
"# Where should we look in the file system ? #",
"if",
"'cache_dir'",
"in",
"self",
".",
"__dict__",
":",
"path",
"=",
"FilePath",
"(",
"self",
".",
"__dict__",
"[",
"'cache_dir'",
"]",
"+",
"f",
".",
"func_name",
"+",
"'.pickle'",
")",
"else",
":",
"path",
"=",
"getattr",
"(",
"self",
".",
"p",
",",
"f",
".",
"func_name",
")",
"if",
"value",
"is",
"None",
":",
"path",
".",
"remove",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"You can't set a pickled property, you can only delete it\"",
")",
"# Return a wrapper #",
"retrieve_from_cache",
".",
"__doc__",
"=",
"f",
".",
"__doc__",
"return",
"property",
"(",
"retrieve_from_cache",
",",
"overwrite_cache",
")"
] | Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cached. | [
"Same",
"thing",
"as",
"above",
"but",
"the",
"result",
"will",
"be",
"stored",
"on",
"disk",
"The",
"path",
"of",
"the",
"pickle",
"file",
"will",
"be",
"determined",
"by",
"looking",
"for",
"the",
"cache_dir",
"attribute",
"of",
"the",
"instance",
"containing",
"the",
"cached",
"property",
".",
"If",
"no",
"cache_dir",
"attribute",
"exists",
"the",
"p",
"attribute",
"will",
"be",
"accessed",
"with",
"the",
"name",
"of",
"the",
"property",
"being",
"cached",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/cache.py#L85-L122 |
matllubos/django-is-core | is_core/forms/formsets.py | smartformset_factory | def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
"""Return a FormSet for the given form class."""
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on forms instantiated, to prevent memory-exhaustion attacks
# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
# if max_num is None in the first place)
absolute_max = max_num + DEFAULT_MAX_NUM
if min_num is None:
min_num = 0
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete, 'min_num': min_num,
'max_num': max_num, 'absolute_max': absolute_max, 'validate_min': validate_min,
'validate_max': validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs) | python | def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False):
"""Return a FormSet for the given form class."""
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on forms instantiated, to prevent memory-exhaustion attacks
# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
# if max_num is None in the first place)
absolute_max = max_num + DEFAULT_MAX_NUM
if min_num is None:
min_num = 0
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete, 'min_num': min_num,
'max_num': max_num, 'absolute_max': absolute_max, 'validate_min': validate_min,
'validate_max': validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs) | [
"def",
"smartformset_factory",
"(",
"form",
",",
"formset",
"=",
"BaseFormSet",
",",
"extra",
"=",
"1",
",",
"can_order",
"=",
"False",
",",
"can_delete",
"=",
"False",
",",
"min_num",
"=",
"None",
",",
"max_num",
"=",
"None",
",",
"validate_min",
"=",
"False",
",",
"validate_max",
"=",
"False",
")",
":",
"if",
"max_num",
"is",
"None",
":",
"max_num",
"=",
"DEFAULT_MAX_NUM",
"# hard limit on forms instantiated, to prevent memory-exhaustion attacks",
"# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM",
"# if max_num is None in the first place)",
"absolute_max",
"=",
"max_num",
"+",
"DEFAULT_MAX_NUM",
"if",
"min_num",
"is",
"None",
":",
"min_num",
"=",
"0",
"attrs",
"=",
"{",
"'form'",
":",
"form",
",",
"'extra'",
":",
"extra",
",",
"'can_order'",
":",
"can_order",
",",
"'can_delete'",
":",
"can_delete",
",",
"'min_num'",
":",
"min_num",
",",
"'max_num'",
":",
"max_num",
",",
"'absolute_max'",
":",
"absolute_max",
",",
"'validate_min'",
":",
"validate_min",
",",
"'validate_max'",
":",
"validate_max",
"}",
"return",
"type",
"(",
"form",
".",
"__name__",
"+",
"str",
"(",
"'FormSet'",
")",
",",
"(",
"formset",
",",
")",
",",
"attrs",
")"
] | Return a FormSet for the given form class. | [
"Return",
"a",
"FormSet",
"for",
"the",
"given",
"form",
"class",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/formsets.py#L34-L50 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DefaultFormView.save_form | def save_form(self, form, **kwargs):
"""Contains formset save, prepare obj for saving"""
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | python | def save_form(self, form, **kwargs):
"""Contains formset save, prepare obj for saving"""
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | [
"def",
"save_form",
"(",
"self",
",",
"form",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"change",
"=",
"obj",
".",
"pk",
"is",
"not",
"None",
"self",
".",
"save_obj",
"(",
"obj",
",",
"form",
",",
"change",
")",
"if",
"hasattr",
"(",
"form",
",",
"'save_m2m'",
")",
":",
"form",
".",
"save_m2m",
"(",
")",
"return",
"obj"
] | Contains formset save, prepare obj for saving | [
"Contains",
"formset",
"save",
"prepare",
"obj",
"for",
"saving"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L109-L117 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DefaultFormView.get_method_returning_field_value | def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | python | def get_method_returning_field_value(self, field_name):
"""
Field values can be obtained from view or core.
"""
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | [
"def",
"get_method_returning_field_value",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"(",
"super",
"(",
")",
".",
"get_method_returning_field_value",
"(",
"field_name",
")",
"or",
"self",
".",
"core",
".",
"get_method_returning_field_value",
"(",
"field_name",
")",
")"
] | Field values can be obtained from view or core. | [
"Field",
"values",
"can",
"be",
"obtained",
"from",
"view",
"or",
"core",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L267-L274 |
matllubos/django-is-core | is_core/generic_views/form_views.py | DetailModelFormView._get_perm_obj_or_404 | def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all objects.
If object does not exist is raised Http404
"""
if pk:
obj = get_object_or_none(self.core.model, pk=pk)
else:
try:
obj = self.get_obj(False)
except Http404:
obj = get_object_or_none(self.core.model, **self.get_obj_filters())
if not obj:
raise Http404
return obj | python | def _get_perm_obj_or_404(self, pk=None):
"""
If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all objects.
If object does not exist is raised Http404
"""
if pk:
obj = get_object_or_none(self.core.model, pk=pk)
else:
try:
obj = self.get_obj(False)
except Http404:
obj = get_object_or_none(self.core.model, **self.get_obj_filters())
if not obj:
raise Http404
return obj | [
"def",
"_get_perm_obj_or_404",
"(",
"self",
",",
"pk",
"=",
"None",
")",
":",
"if",
"pk",
":",
"obj",
"=",
"get_object_or_none",
"(",
"self",
".",
"core",
".",
"model",
",",
"pk",
"=",
"pk",
")",
"else",
":",
"try",
":",
"obj",
"=",
"self",
".",
"get_obj",
"(",
"False",
")",
"except",
"Http404",
":",
"obj",
"=",
"get_object_or_none",
"(",
"self",
".",
"core",
".",
"model",
",",
"*",
"*",
"self",
".",
"get_obj_filters",
"(",
")",
")",
"if",
"not",
"obj",
":",
"raise",
"Http404",
"return",
"obj"
] | If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all objects.
If object does not exist is raised Http404 | [
"If",
"is",
"send",
"parameter",
"pk",
"is",
"returned",
"object",
"according",
"this",
"pk",
"else",
"is",
"returned",
"object",
"from",
"get_obj",
"method",
"but",
"it",
"search",
"only",
"inside",
"filtered",
"values",
"for",
"current",
"user",
"finally",
"if",
"object",
"is",
"still",
"None",
"is",
"returned",
"according",
"the",
"input",
"key",
"from",
"all",
"objects",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/form_views.py#L652-L669 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | view_all | def view_all(request, language, filter=None):
"""
View all translations that are in site.
"""
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"])))
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))+"?search="+data["search"])
LANGUAGES = dict(lang for lang in settings.LANGUAGES)
if language not in LANGUAGES.keys():
raise Http404(u"Language {0} does not exist".format(language))
if language == settings.LANGUAGE_CODE:
raise Http404(u"El idioma {0} es el idioma por defecto".format(language))
# Translation filter
trans_filter = {"lang":language}
if filter == "all" or filter is None:
pass
elif filter == "fuzzy":
trans_filter["is_fuzzy"] = True
elif filter == "completed":
trans_filter["is_fuzzy"] = False
search_query = ""
if request.GET and "search" in request.GET and request.GET.get("search")!="":
search_query = request.GET.get("search")
trans_filter["source_text__icontains"] = search_query
translations = FieldTranslation.objects.filter(**trans_filter)
# Update translations
active_translations = []
for translation in translations:
source_model = translation.get_source_model()
if not translation.field in source_model._meta.translatable_fields:
translation.delete()
else:
active_translations.append(translation)
replacements = {"translations":active_translations, "filter":filter, "lang":language, "language":LANGUAGES[language], "search_query":search_query}
return render_to_response('modeltranslation/admin/list.html',replacements, RequestContext(request)) | python | def view_all(request, language, filter=None):
"""
View all translations that are in site.
"""
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"])))
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"]))+"?search="+data["search"])
LANGUAGES = dict(lang for lang in settings.LANGUAGES)
if language not in LANGUAGES.keys():
raise Http404(u"Language {0} does not exist".format(language))
if language == settings.LANGUAGE_CODE:
raise Http404(u"El idioma {0} es el idioma por defecto".format(language))
# Translation filter
trans_filter = {"lang":language}
if filter == "all" or filter is None:
pass
elif filter == "fuzzy":
trans_filter["is_fuzzy"] = True
elif filter == "completed":
trans_filter["is_fuzzy"] = False
search_query = ""
if request.GET and "search" in request.GET and request.GET.get("search")!="":
search_query = request.GET.get("search")
trans_filter["source_text__icontains"] = search_query
translations = FieldTranslation.objects.filter(**trans_filter)
# Update translations
active_translations = []
for translation in translations:
source_model = translation.get_source_model()
if not translation.field in source_model._meta.translatable_fields:
translation.delete()
else:
active_translations.append(translation)
replacements = {"translations":active_translations, "filter":filter, "lang":language, "language":LANGUAGES[language], "search_query":search_query}
return render_to_response('modeltranslation/admin/list.html',replacements, RequestContext(request)) | [
"def",
"view_all",
"(",
"request",
",",
"language",
",",
"filter",
"=",
"None",
")",
":",
"# Is there any filter?",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"data",
"=",
"request",
".",
"POST",
".",
"dict",
"(",
")",
"if",
"not",
"data",
"[",
"\"search\"",
"]",
"or",
"data",
"[",
"\"search\"",
"]",
"==",
"\"\"",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"\"modeltranslation:view_all_url\"",
",",
"args",
"=",
"(",
"data",
"[",
"\"language\"",
"]",
",",
"data",
"[",
"\"filter\"",
"]",
")",
")",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"\"modeltranslation:view_all_url\"",
",",
"args",
"=",
"(",
"data",
"[",
"\"language\"",
"]",
",",
"data",
"[",
"\"filter\"",
"]",
")",
")",
"+",
"\"?search=\"",
"+",
"data",
"[",
"\"search\"",
"]",
")",
"LANGUAGES",
"=",
"dict",
"(",
"lang",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
")",
"if",
"language",
"not",
"in",
"LANGUAGES",
".",
"keys",
"(",
")",
":",
"raise",
"Http404",
"(",
"u\"Language {0} does not exist\"",
".",
"format",
"(",
"language",
")",
")",
"if",
"language",
"==",
"settings",
".",
"LANGUAGE_CODE",
":",
"raise",
"Http404",
"(",
"u\"El idioma {0} es el idioma por defecto\"",
".",
"format",
"(",
"language",
")",
")",
"# Translation filter",
"trans_filter",
"=",
"{",
"\"lang\"",
":",
"language",
"}",
"if",
"filter",
"==",
"\"all\"",
"or",
"filter",
"is",
"None",
":",
"pass",
"elif",
"filter",
"==",
"\"fuzzy\"",
":",
"trans_filter",
"[",
"\"is_fuzzy\"",
"]",
"=",
"True",
"elif",
"filter",
"==",
"\"completed\"",
":",
"trans_filter",
"[",
"\"is_fuzzy\"",
"]",
"=",
"False",
"search_query",
"=",
"\"\"",
"if",
"request",
".",
"GET",
"and",
"\"search\"",
"in",
"request",
".",
"GET",
"and",
"request",
".",
"GET",
".",
"get",
"(",
"\"search\"",
")",
"!=",
"\"\"",
":",
"search_query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"search\"",
")",
"trans_filter",
"[",
"\"source_text__icontains\"",
"]",
"=",
"search_query",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"trans_filter",
")",
"# Update translations",
"active_translations",
"=",
"[",
"]",
"for",
"translation",
"in",
"translations",
":",
"source_model",
"=",
"translation",
".",
"get_source_model",
"(",
")",
"if",
"not",
"translation",
".",
"field",
"in",
"source_model",
".",
"_meta",
".",
"translatable_fields",
":",
"translation",
".",
"delete",
"(",
")",
"else",
":",
"active_translations",
".",
"append",
"(",
"translation",
")",
"replacements",
"=",
"{",
"\"translations\"",
":",
"active_translations",
",",
"\"filter\"",
":",
"filter",
",",
"\"lang\"",
":",
"language",
",",
"\"language\"",
":",
"LANGUAGES",
"[",
"language",
"]",
",",
"\"search_query\"",
":",
"search_query",
"}",
"return",
"render_to_response",
"(",
"'modeltranslation/admin/list.html'",
",",
"replacements",
",",
"RequestContext",
"(",
"request",
")",
")"
] | View all translations that are in site. | [
"View",
"all",
"translations",
"that",
"are",
"in",
"site",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L27-L74 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | edit | def edit(request, translation):
"""
Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection.
"""
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel" in request.POST:
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all")))
elif "save" in request.POST:
form = FieldTranslationForm(request.POST, instance=translation)
valid_form = form.is_valid()
if valid_form:
translation = form.save(commit=False)
translation.context = u"Admin. Traducciones"
translation.save()
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all")))
else:
form = FieldTranslationForm(instance=translation)
else:
form = FieldTranslationForm(instance=translation)
LANGUAGES = dict(lang for lang in settings.LANGUAGES)
language = LANGUAGES[translation.lang]
return render_to_response('modeltranslation/admin/edit_translation.html',{"translation":translation, "form":form, "lang":translation.lang, "language":language}, RequestContext(request)) | python | def edit(request, translation):
"""
Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection.
"""
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel" in request.POST:
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all")))
elif "save" in request.POST:
form = FieldTranslationForm(request.POST, instance=translation)
valid_form = form.is_valid()
if valid_form:
translation = form.save(commit=False)
translation.context = u"Admin. Traducciones"
translation.save()
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all")))
else:
form = FieldTranslationForm(instance=translation)
else:
form = FieldTranslationForm(instance=translation)
LANGUAGES = dict(lang for lang in settings.LANGUAGES)
language = LANGUAGES[translation.lang]
return render_to_response('modeltranslation/admin/edit_translation.html',{"translation":translation, "form":form, "lang":translation.lang, "language":language}, RequestContext(request)) | [
"def",
"edit",
"(",
"request",
",",
"translation",
")",
":",
"translation",
"=",
"get_object_or_404",
"(",
"FieldTranslation",
",",
"id",
"=",
"translation",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"\"cancel\"",
"in",
"request",
".",
"POST",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"\"modeltranslation:view_all_url\"",
",",
"args",
"=",
"(",
"translation",
".",
"lang",
",",
"\"all\"",
")",
")",
")",
"elif",
"\"save\"",
"in",
"request",
".",
"POST",
":",
"form",
"=",
"FieldTranslationForm",
"(",
"request",
".",
"POST",
",",
"instance",
"=",
"translation",
")",
"valid_form",
"=",
"form",
".",
"is_valid",
"(",
")",
"if",
"valid_form",
":",
"translation",
"=",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"translation",
".",
"context",
"=",
"u\"Admin. Traducciones\"",
"translation",
".",
"save",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"\"modeltranslation:view_all_url\"",
",",
"args",
"=",
"(",
"translation",
".",
"lang",
",",
"\"all\"",
")",
")",
")",
"else",
":",
"form",
"=",
"FieldTranslationForm",
"(",
"instance",
"=",
"translation",
")",
"else",
":",
"form",
"=",
"FieldTranslationForm",
"(",
"instance",
"=",
"translation",
")",
"LANGUAGES",
"=",
"dict",
"(",
"lang",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
")",
"language",
"=",
"LANGUAGES",
"[",
"translation",
".",
"lang",
"]",
"return",
"render_to_response",
"(",
"'modeltranslation/admin/edit_translation.html'",
",",
"{",
"\"translation\"",
":",
"translation",
",",
"\"form\"",
":",
"form",
",",
"\"lang\"",
":",
"translation",
".",
"lang",
",",
"\"language\"",
":",
"language",
"}",
",",
"RequestContext",
"(",
"request",
")",
")"
] | Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection. | [
"Edit",
"a",
"translation",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L80-L107 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | export_translations | def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
replacements = {"translations":translations, "lang":language}
if len(settings.ADMINS)>0:
replacements["last_translator"] = settings.ADMINS[0][0]
replacements["last_translator_email"] = settings.ADMINS[0][1]
if settings.WEBSITE_NAME:
replacements["website_name"] = settings.WEBSITE_NAME
response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
return response | python | def export_translations(request, language):
"""
Export translations view.
"""
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
replacements = {"translations":translations, "lang":language}
if len(settings.ADMINS)>0:
replacements["last_translator"] = settings.ADMINS[0][0]
replacements["last_translator_email"] = settings.ADMINS[0][1]
if settings.WEBSITE_NAME:
replacements["website_name"] = settings.WEBSITE_NAME
response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
return response | [
"def",
"export_translations",
"(",
"request",
",",
"language",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"translations",
"=",
"FieldTranslation",
".",
"objects",
".",
"filter",
"(",
"lang",
"=",
"language",
")",
"for",
"trans",
"in",
"translations",
":",
"trans",
".",
"source_text",
"=",
"trans",
".",
"source_text",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\'\"",
")",
".",
"replace",
"(",
"\"\\\"\"",
",",
"\"\\\\\\\"\"",
")",
"trans",
".",
"translation",
"=",
"trans",
".",
"translation",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\'\"",
")",
".",
"replace",
"(",
"\"\\\"\"",
",",
"\"\\\\\\\"\"",
")",
"replacements",
"=",
"{",
"\"translations\"",
":",
"translations",
",",
"\"lang\"",
":",
"language",
"}",
"if",
"len",
"(",
"settings",
".",
"ADMINS",
")",
">",
"0",
":",
"replacements",
"[",
"\"last_translator\"",
"]",
"=",
"settings",
".",
"ADMINS",
"[",
"0",
"]",
"[",
"0",
"]",
"replacements",
"[",
"\"last_translator_email\"",
"]",
"=",
"settings",
".",
"ADMINS",
"[",
"0",
"]",
"[",
"1",
"]",
"if",
"settings",
".",
"WEBSITE_NAME",
":",
"replacements",
"[",
"\"website_name\"",
"]",
"=",
"settings",
".",
"WEBSITE_NAME",
"response",
"=",
"render",
"(",
"request",
"=",
"request",
",",
"template_name",
"=",
"'modeltranslation/admin/export_translations.po'",
",",
"dictionary",
"=",
"replacements",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"content_type",
"=",
"\"text/x-gettext-translation\"",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename=\"{0}.po\"'",
".",
"format",
"(",
"language",
")",
"return",
"response"
] | Export translations view. | [
"Export",
"translations",
"view",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L182-L199 |
intelligenia/modeltranslation | modeltranslation/admin/views.py | update_translations | def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request)) | python | def update_translations(request):
"""
Update translations: delete orphan translations and creates empty translations for new objects in database.
"""
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request)) | [
"def",
"update_translations",
"(",
"request",
")",
":",
"FieldTranslation",
".",
"delete_orphan_translations",
"(",
")",
"num_translations",
"=",
"FieldTranslation",
".",
"update_translations",
"(",
")",
"return",
"render_to_response",
"(",
"'modeltranslation/admin/update_translations_ok.html'",
",",
"{",
"\"num_translations\"",
":",
"num_translations",
"}",
",",
"RequestContext",
"(",
"request",
")",
")"
] | Update translations: delete orphan translations and creates empty translations for new objects in database. | [
"Update",
"translations",
":",
"delete",
"orphan",
"translations",
"and",
"creates",
"empty",
"translations",
"for",
"new",
"objects",
"in",
"database",
"."
] | train | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/admin/views.py#L205-L211 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_get | def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | python | def client_get(self, url, **kwargs):
"""Send GET request with given url."""
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | [
"def",
"client_get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"Exception",
"(",
"'{status}: {reason}.\\nCircleCI Status NOT OK'",
".",
"format",
"(",
"status",
"=",
"response",
".",
"status_code",
",",
"reason",
"=",
"response",
".",
"reason",
")",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Send GET request with given url. | [
"Send",
"GET",
"request",
"with",
"given",
"url",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L37-L44 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_post | def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | python | def client_post(self, url, **kwargs):
"""Send POST request with given url and keyword args."""
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | [
"def",
"client_post",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"kwargs",
")",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"Exception",
"(",
"'{status}: {reason}.\\nCircleCI Status NOT OK'",
".",
"format",
"(",
"status",
"=",
"response",
".",
"status_code",
",",
"reason",
"=",
"response",
".",
"reason",
")",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Send POST request with given url and keyword args. | [
"Send",
"POST",
"request",
"with",
"given",
"url",
"and",
"keyword",
"args",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L46-L55 |
qba73/circleclient | circleclient/circleclient.py | CircleClient.client_delete | def client_delete(self, url, **kwargs):
"""Send POST request with given url."""
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | python | def client_delete(self, url, **kwargs):
"""Send POST request with given url."""
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | [
"def",
"client_delete",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"delete",
"(",
"self",
".",
"make_url",
"(",
"url",
")",
",",
"headers",
"=",
"self",
".",
"headers",
")",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"Exception",
"(",
"'{status}: {reason}.\\nCircleCI Status NOT OK'",
".",
"format",
"(",
"status",
"=",
"response",
".",
"status_code",
",",
"reason",
"=",
"response",
".",
"reason",
")",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Send POST request with given url. | [
"Send",
"POST",
"request",
"with",
"given",
"url",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L57-L64 |
qba73/circleclient | circleclient/circleclient.py | Projects.list_projects | def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | python | def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | [
"def",
"list_projects",
"(",
"self",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"'/projects?circle-token={token}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Return a list of all followed projects. | [
"Return",
"a",
"list",
"of",
"all",
"followed",
"projects",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L97-L103 |
qba73/circleclient | circleclient/circleclient.py | Build.trigger | def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
branch=branch, token=self.client.api_token))
if build_params is not None:
json_data = self.client.request(method, url,
build_parameters=build_params)
else:
json_data = self.client.request(method, url)
return json_data | python | def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
branch=branch, token=self.client.api_token))
if build_params is not None:
json_data = self.client.request(method, url,
build_parameters=build_params)
else:
json_data = self.client.request(method, url)
return json_data | [
"def",
"trigger",
"(",
"self",
",",
"username",
",",
"project",
",",
"branch",
",",
"*",
"*",
"build_params",
")",
":",
"method",
"=",
"'POST'",
"url",
"=",
"(",
"'/project/{username}/{project}/tree/{branch}?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"project",
",",
"branch",
"=",
"branch",
",",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
")",
"if",
"build_params",
"is",
"not",
"None",
":",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
",",
"build_parameters",
"=",
"build_params",
")",
"else",
":",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Trigger new build and return a summary of the build. | [
"Trigger",
"new",
"build",
"and",
"return",
"a",
"summary",
"of",
"the",
"build",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L111-L124 |
qba73/circleclient | circleclient/circleclient.py | Build.cancel | def cancel(self, username, project, build_num):
"""Cancel the build and return its summary."""
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=project,
build_num=build_num,
token=self.client.api_token))
json_data = self.client.request(method, url)
return json_data | python | def cancel(self, username, project, build_num):
"""Cancel the build and return its summary."""
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=project,
build_num=build_num,
token=self.client.api_token))
json_data = self.client.request(method, url)
return json_data | [
"def",
"cancel",
"(",
"self",
",",
"username",
",",
"project",
",",
"build_num",
")",
":",
"method",
"=",
"'POST'",
"url",
"=",
"(",
"'/project/{username}/{project}/{build_num}/cancel?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"project",
",",
"build_num",
"=",
"build_num",
",",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Cancel the build and return its summary. | [
"Cancel",
"the",
"build",
"and",
"return",
"its",
"summary",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L126-L135 |
qba73/circleclient | circleclient/circleclient.py | Build.recent_all_projects | def recent_all_projects(self, limit=30, offset=0):
"""Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries.
"""
method = 'GET'
url = ('/recent-builds?circle-token={token}&limit={limit}&'
'offset={offset}'.format(token=self.client.api_token,
limit=limit,
offset=offset))
json_data = self.client.request(method, url)
return json_data | python | def recent_all_projects(self, limit=30, offset=0):
"""Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries.
"""
method = 'GET'
url = ('/recent-builds?circle-token={token}&limit={limit}&'
'offset={offset}'.format(token=self.client.api_token,
limit=limit,
offset=offset))
json_data = self.client.request(method, url)
return json_data | [
"def",
"recent_all_projects",
"(",
"self",
",",
"limit",
"=",
"30",
",",
"offset",
"=",
"0",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"(",
"'/recent-builds?circle-token={token}&limit={limit}&'",
"'offset={offset}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
")",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries. | [
"Return",
"information",
"about",
"recent",
"builds",
"across",
"all",
"projects",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L173-L189 |
qba73/circleclient | circleclient/circleclient.py | Build.recent | def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""):
"""Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name of the user.
project (str): Name of the project.
limit (int): Number of builds to return, default=1, max=100.
offset (int): Returns builds starting from given offset.
branch (str): Optional branch name as string. If specified only
builds from given branch are returned.
status_filter (str): Restricts which builds are returned. Set to
"completed", "successful", "failed", "running", or defaults
to no filter.
Returns:
A list of dictionaries with information about each build.
"""
method = 'GET'
if branch is not None:
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format(
username=username, project=project, branch=branch,
token=self.client.api_token, limit=limit,
offset=offset, status_filter=status_filter))
else:
url = ('/project/{username}/{project}?'
'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format(
username=username, project=project,
token=self.client.api_token, limit=limit,
offset=offset, status_filter=status_filter))
json_data = self.client.request(method, url)
return json_data | python | def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""):
"""Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name of the user.
project (str): Name of the project.
limit (int): Number of builds to return, default=1, max=100.
offset (int): Returns builds starting from given offset.
branch (str): Optional branch name as string. If specified only
builds from given branch are returned.
status_filter (str): Restricts which builds are returned. Set to
"completed", "successful", "failed", "running", or defaults
to no filter.
Returns:
A list of dictionaries with information about each build.
"""
method = 'GET'
if branch is not None:
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format(
username=username, project=project, branch=branch,
token=self.client.api_token, limit=limit,
offset=offset, status_filter=status_filter))
else:
url = ('/project/{username}/{project}?'
'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format(
username=username, project=project,
token=self.client.api_token, limit=limit,
offset=offset, status_filter=status_filter))
json_data = self.client.request(method, url)
return json_data | [
"def",
"recent",
"(",
"self",
",",
"username",
",",
"project",
",",
"limit",
"=",
"1",
",",
"offset",
"=",
"0",
",",
"branch",
"=",
"None",
",",
"status_filter",
"=",
"\"\"",
")",
":",
"method",
"=",
"'GET'",
"if",
"branch",
"is",
"not",
"None",
":",
"url",
"=",
"(",
"'/project/{username}/{project}/tree/{branch}?'",
"'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"project",
",",
"branch",
"=",
"branch",
",",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
",",
"status_filter",
"=",
"status_filter",
")",
")",
"else",
":",
"url",
"=",
"(",
"'/project/{username}/{project}?'",
"'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"project",
",",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
",",
"status_filter",
"=",
"status_filter",
")",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name of the user.
project (str): Name of the project.
limit (int): Number of builds to return, default=1, max=100.
offset (int): Returns builds starting from given offset.
branch (str): Optional branch name as string. If specified only
builds from given branch are returned.
status_filter (str): Restricts which builds are returned. Set to
"completed", "successful", "failed", "running", or defaults
to no filter.
Returns:
A list of dictionaries with information about each build. | [
"Return",
"status",
"of",
"recent",
"builds",
"for",
"given",
"project",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L191-L225 |
qba73/circleclient | circleclient/circleclient.py | Cache.clear | def clear(self, username, project):
"""Clear the cache for given project."""
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
token=self.client.api_token))
json_data = self.client.request(method, url)
return json_data | python | def clear(self, username, project):
"""Clear the cache for given project."""
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
token=self.client.api_token))
json_data = self.client.request(method, url)
return json_data | [
"def",
"clear",
"(",
"self",
",",
"username",
",",
"project",
")",
":",
"method",
"=",
"'DELETE'",
"url",
"=",
"(",
"'/project/{username}/{project}/build-cache?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"project",
",",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
"(",
"method",
",",
"url",
")",
"return",
"json_data"
] | Clear the cache for given project. | [
"Clear",
"the",
"cache",
"for",
"given",
"project",
"."
] | train | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L233-L241 |
The-Politico/django-slackchat-serializer | slackchat/views/api/channel.py | ChannelDeserializer.post | def post(self, request, format=None):
"""
Add a new Channel.
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
None, data["publish_path"], ct.publish_path
):
return notUnique400
# Get user record
try:
u = User.objects.get(pk=data.pop("owner"))
data["owner"] = u
except User.DoesNotExist:
return userNotFound404
c = Channel(**data)
c.save()
self.handle_webhook(c)
return Response(
{
"text": "Channel saved.",
"method": "POST",
"saved": ChannelCMSSerializer(c).data,
},
200,
) | python | def post(self, request, format=None):
"""
Add a new Channel.
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
None, data["publish_path"], ct.publish_path
):
return notUnique400
# Get user record
try:
u = User.objects.get(pk=data.pop("owner"))
data["owner"] = u
except User.DoesNotExist:
return userNotFound404
c = Channel(**data)
c.save()
self.handle_webhook(c)
return Response(
{
"text": "Channel saved.",
"method": "POST",
"saved": ChannelCMSSerializer(c).data,
},
200,
) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"format",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"data",
".",
"copy",
"(",
")",
"# Get chat type record",
"try",
":",
"ct",
"=",
"ChatType",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"data",
".",
"pop",
"(",
"\"chat_type\"",
")",
")",
"data",
"[",
"\"chat_type\"",
"]",
"=",
"ct",
"except",
"ChatType",
".",
"DoesNotExist",
":",
"return",
"typeNotFound404",
"if",
"not",
"self",
".",
"is_path_unique",
"(",
"None",
",",
"data",
"[",
"\"publish_path\"",
"]",
",",
"ct",
".",
"publish_path",
")",
":",
"return",
"notUnique400",
"# Get user record",
"try",
":",
"u",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"data",
".",
"pop",
"(",
"\"owner\"",
")",
")",
"data",
"[",
"\"owner\"",
"]",
"=",
"u",
"except",
"User",
".",
"DoesNotExist",
":",
"return",
"userNotFound404",
"c",
"=",
"Channel",
"(",
"*",
"*",
"data",
")",
"c",
".",
"save",
"(",
")",
"self",
".",
"handle_webhook",
"(",
"c",
")",
"return",
"Response",
"(",
"{",
"\"text\"",
":",
"\"Channel saved.\"",
",",
"\"method\"",
":",
"\"POST\"",
",",
"\"saved\"",
":",
"ChannelCMSSerializer",
"(",
"c",
")",
".",
"data",
",",
"}",
",",
"200",
",",
")"
] | Add a new Channel. | [
"Add",
"a",
"new",
"Channel",
"."
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L66-L103 |
The-Politico/django-slackchat-serializer | slackchat/views/api/channel.py | ChannelDeserializer.patch | def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
data["id"], data["publish_path"], ct.publish_path
):
return notUnique400
# Get channel record
try:
c = Channel.objects.get(id=data.pop("id"))
except Channel.DoesNotExist:
return channelNotFound404
# Save new data
for key, value in data.items():
setattr(c, key, value)
c.save()
self.handle_webhook(c)
return Response(
{
"text": "Channel saved.",
"method": "PATCH",
"saved": ChannelCMSSerializer(c).data,
},
200,
) | python | def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
data["id"], data["publish_path"], ct.publish_path
):
return notUnique400
# Get channel record
try:
c = Channel.objects.get(id=data.pop("id"))
except Channel.DoesNotExist:
return channelNotFound404
# Save new data
for key, value in data.items():
setattr(c, key, value)
c.save()
self.handle_webhook(c)
return Response(
{
"text": "Channel saved.",
"method": "PATCH",
"saved": ChannelCMSSerializer(c).data,
},
200,
) | [
"def",
"patch",
"(",
"self",
",",
"request",
",",
"format",
"=",
"None",
")",
":",
"data",
"=",
"request",
".",
"data",
".",
"copy",
"(",
")",
"# Get chat type record",
"try",
":",
"ct",
"=",
"ChatType",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"data",
".",
"pop",
"(",
"\"chat_type\"",
")",
")",
"data",
"[",
"\"chat_type\"",
"]",
"=",
"ct",
"except",
"ChatType",
".",
"DoesNotExist",
":",
"return",
"typeNotFound404",
"if",
"not",
"self",
".",
"is_path_unique",
"(",
"data",
"[",
"\"id\"",
"]",
",",
"data",
"[",
"\"publish_path\"",
"]",
",",
"ct",
".",
"publish_path",
")",
":",
"return",
"notUnique400",
"# Get channel record",
"try",
":",
"c",
"=",
"Channel",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"data",
".",
"pop",
"(",
"\"id\"",
")",
")",
"except",
"Channel",
".",
"DoesNotExist",
":",
"return",
"channelNotFound404",
"# Save new data",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"c",
",",
"key",
",",
"value",
")",
"c",
".",
"save",
"(",
")",
"self",
".",
"handle_webhook",
"(",
"c",
")",
"return",
"Response",
"(",
"{",
"\"text\"",
":",
"\"Channel saved.\"",
",",
"\"method\"",
":",
"\"PATCH\"",
",",
"\"saved\"",
":",
"ChannelCMSSerializer",
"(",
"c",
")",
".",
"data",
",",
"}",
",",
"200",
",",
")"
] | Update an existing Channel | [
"Update",
"an",
"existing",
"Channel"
] | train | https://github.com/The-Politico/django-slackchat-serializer/blob/9a41e0477d1bc7bb2ec3f8af40baddf8d4230d40/slackchat/views/api/channel.py#L105-L143 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | sha256_file | def sha256_file(path):
"""Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method
"""
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
h.update(chunk)
return h.hexdigest() | python | def sha256_file(path):
"""Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method
"""
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
h.update(chunk)
return h.hexdigest() | [
"def",
"sha256_file",
"(",
"path",
")",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"CHUNK_SIZE",
")",
",",
"b''",
")",
":",
"h",
".",
"update",
"(",
"chunk",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method | [
"Calculate",
"sha256",
"hex",
"digest",
"of",
"a",
"file",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L32-L46 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | key_from_file | def key_from_file(filename, passphrase):
"""Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attacks.
:param filename: The filename you want to create a key for.
:type filename: str
:param passphrase: The passphrase you want to use to encrypt the file.
:type passphrase: str or None
:returns: A convergent encryption key.
:rtype: str
"""
hexdigest = sha256_file(filename)
if passphrase is None:
passphrase = DEFAULT_HMAC_PASSPHRASE
return keyed_hash(hexdigest, passphrase) | python | def key_from_file(filename, passphrase):
"""Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attacks.
:param filename: The filename you want to create a key for.
:type filename: str
:param passphrase: The passphrase you want to use to encrypt the file.
:type passphrase: str or None
:returns: A convergent encryption key.
:rtype: str
"""
hexdigest = sha256_file(filename)
if passphrase is None:
passphrase = DEFAULT_HMAC_PASSPHRASE
return keyed_hash(hexdigest, passphrase) | [
"def",
"key_from_file",
"(",
"filename",
",",
"passphrase",
")",
":",
"hexdigest",
"=",
"sha256_file",
"(",
"filename",
")",
"if",
"passphrase",
"is",
"None",
":",
"passphrase",
"=",
"DEFAULT_HMAC_PASSPHRASE",
"return",
"keyed_hash",
"(",
"hexdigest",
",",
"passphrase",
")"
] | Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attacks.
:param filename: The filename you want to create a key for.
:type filename: str
:param passphrase: The passphrase you want to use to encrypt the file.
:type passphrase: str or None
:returns: A convergent encryption key.
:rtype: str | [
"Calculate",
"convergent",
"encryption",
"key",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L49-L70 |
StorjOld/file-encryptor | file_encryptor/key_generators.py | keyed_hash | def keyed_hash(digest, passphrase):
"""Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str
"""
encodedPassphrase = passphrase.encode()
encodedDigest = digest.encode()
return hmac.new(encodedPassphrase, encodedDigest, hashlib.sha256).digest() | python | def keyed_hash(digest, passphrase):
"""Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str
"""
encodedPassphrase = passphrase.encode()
encodedDigest = digest.encode()
return hmac.new(encodedPassphrase, encodedDigest, hashlib.sha256).digest() | [
"def",
"keyed_hash",
"(",
"digest",
",",
"passphrase",
")",
":",
"encodedPassphrase",
"=",
"passphrase",
".",
"encode",
"(",
")",
"encodedDigest",
"=",
"digest",
".",
"encode",
"(",
")",
"return",
"hmac",
".",
"new",
"(",
"encodedPassphrase",
",",
"encodedDigest",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")"
] | Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str | [
"Calculate",
"a",
"HMAC",
"/",
"keyed",
"hash",
"."
] | train | https://github.com/StorjOld/file-encryptor/blob/245191c45dbd68e09a4a8f07c5d7331be195dc6b/file_encryptor/key_generators.py#L73-L86 |
IwoHerka/sexpr | sexpr/utils.py | find_child | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
"""Search for a tag among direct children of the s-expression."""
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | python | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
"""Search for a tag among direct children of the s-expression."""
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | [
"def",
"find_child",
"(",
"sexpr",
":",
"Sexpr",
",",
"*",
"tags",
":",
"str",
")",
"->",
"Optional",
"[",
"Sexpr",
"]",
":",
"_assert_valid_sexpr",
"(",
"sexpr",
")",
"for",
"child",
"in",
"sexpr",
"[",
"1",
":",
"]",
":",
"if",
"_is_sexpr",
"(",
"child",
")",
"and",
"child",
"[",
"0",
"]",
"in",
"tags",
":",
"return",
"child",
"return",
"None"
] | Search for a tag among direct children of the s-expression. | [
"Search",
"for",
"a",
"tag",
"among",
"direct",
"children",
"of",
"the",
"s",
"-",
"expression",
"."
] | train | https://github.com/IwoHerka/sexpr/blob/28e32f543a127bbbf832b2dba7cb93f9e57db3b6/sexpr/utils.py#L51-L59 |
matllubos/django-is-core | is_core/forms/widgets.py | WrapperWidget.build_attrs | def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | python | def build_attrs(self, *args, **kwargs):
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"attrs",
"=",
"self",
".",
"widget",
".",
"build_attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"attrs"
] | Helper function for building an attribute dictionary. | [
"Helper",
"function",
"for",
"building",
"an",
"attribute",
"dictionary",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L52-L55 |
matllubos/django-is-core | is_core/forms/widgets.py | ClearableFileInput.get_template_substitution_values | def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | python | def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | [
"def",
"get_template_substitution_values",
"(",
"self",
",",
"value",
")",
":",
"return",
"{",
"'initial'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"conditional_escape",
"(",
"value",
")",
")",
",",
"'initial_url'",
":",
"conditional_escape",
"(",
"value",
".",
"url",
")",
",",
"}"
] | Return value-related substitutions. | [
"Return",
"value",
"-",
"related",
"substitutions",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L109-L116 |
matllubos/django-is-core | is_core/forms/widgets.py | RestrictedSelectWidgetMixin.is_restricted | def is_restricted(self):
"""
Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
"""
return (
not hasattr(self.choices, 'queryset') or
self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES
) | python | def is_restricted(self):
"""
Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices.
"""
return (
not hasattr(self.choices, 'queryset') or
self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES
) | [
"def",
"is_restricted",
"(",
"self",
")",
":",
"return",
"(",
"not",
"hasattr",
"(",
"self",
".",
"choices",
",",
"'queryset'",
")",
"or",
"self",
".",
"choices",
".",
"queryset",
".",
"count",
"(",
")",
">",
"settings",
".",
"FOREIGN_KEY_MAX_SELECBOX_ENTRIES",
")"
] | Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices. | [
"Returns",
"True",
"or",
"False",
"according",
"to",
"number",
"of",
"objects",
"in",
"queryset",
".",
"If",
"queryset",
"contains",
"too",
"much",
"objects",
"the",
"widget",
"will",
"be",
"restricted",
"and",
"won",
"t",
"be",
"used",
"select",
"box",
"with",
"choices",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/forms/widgets.py#L412-L420 |
codeforamerica/three | three/api.py | city | def city(name=None):
"""
Store the city that will be queried against.
>>> three.city('sf')
"""
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | python | def city(name=None):
"""
Store the city that will be queried against.
>>> three.city('sf')
"""
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | [
"def",
"city",
"(",
"name",
"=",
"None",
")",
":",
"info",
"=",
"find_info",
"(",
"name",
")",
"os",
".",
"environ",
"[",
"'OPEN311_CITY_INFO'",
"]",
"=",
"dumps",
"(",
"info",
")",
"return",
"Three",
"(",
"*",
"*",
"info",
")"
] | Store the city that will be queried against.
>>> three.city('sf') | [
"Store",
"the",
"city",
"that",
"will",
"be",
"queried",
"against",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L23-L31 |
codeforamerica/three | three/api.py | dev | def dev(endpoint, **kwargs):
"""
Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development.
"""
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kwargs) | python | def dev(endpoint, **kwargs):
"""
Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development.
"""
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kwargs) | [
"def",
"dev",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'endpoint'",
"]",
"=",
"endpoint",
"os",
".",
"environ",
"[",
"'OPEN311_CITY_INFO'",
"]",
"=",
"dumps",
"(",
"kwargs",
")",
"return",
"Three",
"(",
"*",
"*",
"kwargs",
")"
] | Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development. | [
"Use",
"an",
"endpoint",
"and",
"any",
"additional",
"keyword",
"arguments",
"rather",
"than",
"one",
"of",
"the",
"pre",
"-",
"defined",
"cities",
".",
"Similar",
"to",
"the",
"city",
"function",
"but",
"useful",
"for",
"development",
"."
] | train | https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L40-L48 |
matllubos/django-is-core | is_core/utils/__init__.py | flatten_fieldsets | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('fields', ()):
if isinstance(field, (list, tuple)):
field_names.extend(field)
else:
field_names.append(field)
return field_names | python | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('fields', ()):
if isinstance(field, (list, tuple)):
field_names.extend(field)
else:
field_names.append(field)
return field_names | [
"def",
"flatten_fieldsets",
"(",
"fieldsets",
")",
":",
"field_names",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"field_names",
"+=",
"flatten_fieldsets",
"(",
"opts",
".",
"get",
"(",
"'fieldsets'",
")",
")",
"else",
":",
"for",
"field",
"in",
"opts",
".",
"get",
"(",
"'fields'",
",",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"field_names",
".",
"extend",
"(",
"field",
")",
"else",
":",
"field_names",
".",
"append",
"(",
"field",
")",
"return",
"field_names"
] | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L44-L56 |
matllubos/django-is-core | is_core/utils/__init__.py | get_inline_views_from_fieldsets | def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts.get('inline_view'))
return inline_views | python | def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts.get('inline_view'))
return inline_views | [
"def",
"get_inline_views_from_fieldsets",
"(",
"fieldsets",
")",
":",
"inline_views",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"inline_views",
"+=",
"get_inline_views_from_fieldsets",
"(",
"opts",
".",
"get",
"(",
"'fieldsets'",
")",
")",
"elif",
"'inline_view'",
"in",
"opts",
":",
"inline_views",
".",
"append",
"(",
"opts",
".",
"get",
"(",
"'inline_view'",
")",
")",
"return",
"inline_views"
] | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L59-L67 |
matllubos/django-is-core | is_core/utils/__init__.py | get_inline_views_opts_from_fieldsets | def get_inline_views_opts_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts)
return inline_views | python | def get_inline_views_opts_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts)
return inline_views | [
"def",
"get_inline_views_opts_from_fieldsets",
"(",
"fieldsets",
")",
":",
"inline_views",
"=",
"[",
"]",
"for",
"_",
",",
"opts",
"in",
"fieldsets",
"or",
"(",
")",
":",
"if",
"'fieldsets'",
"in",
"opts",
":",
"inline_views",
"+=",
"get_inline_views_opts_from_fieldsets",
"(",
"opts",
".",
"get",
"(",
"'fieldsets'",
")",
")",
"elif",
"'inline_view'",
"in",
"opts",
":",
"inline_views",
".",
"append",
"(",
"opts",
")",
"return",
"inline_views"
] | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L70-L78 |
matllubos/django-is-core | is_core/utils/__init__.py | get_readonly_field_data | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
"""
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
field humanized value, label and widget which are used to display readonly data
"""
fun_kwargs = fun_kwargs or {}
if view:
view_readonly_data = _get_view_readonly_data(field_name, view, fun_kwargs)
if view_readonly_data is not None:
return view_readonly_data
field_data = _get_model_readonly_data(field_name, instance, fun_kwargs)
if field_data is not None:
return field_data
raise FieldOrMethodDoesNotExist('Field or method with name {} not found'.format(field_name)) | python | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
"""
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
field humanized value, label and widget which are used to display readonly data
"""
fun_kwargs = fun_kwargs or {}
if view:
view_readonly_data = _get_view_readonly_data(field_name, view, fun_kwargs)
if view_readonly_data is not None:
return view_readonly_data
field_data = _get_model_readonly_data(field_name, instance, fun_kwargs)
if field_data is not None:
return field_data
raise FieldOrMethodDoesNotExist('Field or method with name {} not found'.format(field_name)) | [
"def",
"get_readonly_field_data",
"(",
"field_name",
",",
"instance",
",",
"view",
"=",
"None",
",",
"fun_kwargs",
"=",
"None",
")",
":",
"fun_kwargs",
"=",
"fun_kwargs",
"or",
"{",
"}",
"if",
"view",
":",
"view_readonly_data",
"=",
"_get_view_readonly_data",
"(",
"field_name",
",",
"view",
",",
"fun_kwargs",
")",
"if",
"view_readonly_data",
"is",
"not",
"None",
":",
"return",
"view_readonly_data",
"field_data",
"=",
"_get_model_readonly_data",
"(",
"field_name",
",",
"instance",
",",
"fun_kwargs",
")",
"if",
"field_data",
"is",
"not",
"None",
":",
"return",
"field_data",
"raise",
"FieldOrMethodDoesNotExist",
"(",
"'Field or method with name {} not found'",
".",
"format",
"(",
"field_name",
")",
")"
] | Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
field humanized value, label and widget which are used to display readonly data | [
"Returns",
"field",
"humanized",
"value",
"label",
"and",
"widget",
"which",
"are",
"used",
"to",
"display",
"of",
"instance",
"or",
"view",
"readonly",
"data",
".",
"Args",
":",
"field_name",
":",
"name",
"of",
"the",
"field",
"which",
"will",
"be",
"displayed",
"instance",
":",
"model",
"instance",
"view",
":",
"view",
"instance",
"fun_kwargs",
":",
"kwargs",
"that",
"can",
"be",
"used",
"inside",
"method",
"call"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L223-L246 |
matllubos/django-is-core | is_core/utils/__init__.py | display_object_data | def display_object_data(obj, field_name, request=None):
"""
Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
field with choices ==> string value of choice
field with humanize function ==> result of humanize function
"""
from is_core.forms.utils import ReadonlyValue
value, _, _ = get_readonly_field_data(field_name, obj)
return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request) | python | def display_object_data(obj, field_name, request=None):
"""
Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
field with choices ==> string value of choice
field with humanize function ==> result of humanize function
"""
from is_core.forms.utils import ReadonlyValue
value, _, _ = get_readonly_field_data(field_name, obj)
return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request) | [
"def",
"display_object_data",
"(",
"obj",
",",
"field_name",
",",
"request",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"forms",
".",
"utils",
"import",
"ReadonlyValue",
"value",
",",
"_",
",",
"_",
"=",
"get_readonly_field_data",
"(",
"field_name",
",",
"obj",
")",
"return",
"display_for_value",
"(",
"value",
".",
"humanized_value",
"if",
"isinstance",
"(",
"value",
",",
"ReadonlyValue",
")",
"else",
"value",
",",
"request",
"=",
"request",
")"
] | Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
field with choices ==> string value of choice
field with humanize function ==> result of humanize function | [
"Returns",
"humanized",
"value",
"of",
"model",
"object",
"that",
"can",
"be",
"rendered",
"to",
"HTML",
"or",
"returned",
"as",
"part",
"of",
"REST"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L249-L262 |
matllubos/django-is-core | is_core/utils/__init__.py | display_for_value | def display_for_value(value, request=None):
"""
Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format
"""
from is_core.utils.compatibility import admin_display_for_value
if request and isinstance(value, Model):
return render_model_object_with_link(request, value)
else:
return (
(value and ugettext('Yes') or ugettext('No')) if isinstance(value, bool) else admin_display_for_value(value)
) | python | def display_for_value(value, request=None):
"""
Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format
"""
from is_core.utils.compatibility import admin_display_for_value
if request and isinstance(value, Model):
return render_model_object_with_link(request, value)
else:
return (
(value and ugettext('Yes') or ugettext('No')) if isinstance(value, bool) else admin_display_for_value(value)
) | [
"def",
"display_for_value",
"(",
"value",
",",
"request",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"utils",
".",
"compatibility",
"import",
"admin_display_for_value",
"if",
"request",
"and",
"isinstance",
"(",
"value",
",",
"Model",
")",
":",
"return",
"render_model_object_with_link",
"(",
"request",
",",
"value",
")",
"else",
":",
"return",
"(",
"(",
"value",
"and",
"ugettext",
"(",
"'Yes'",
")",
"or",
"ugettext",
"(",
"'No'",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
"else",
"admin_display_for_value",
"(",
"value",
")",
")"
] | Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format | [
"Converts",
"humanized",
"value"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L265-L281 |
matllubos/django-is-core | is_core/utils/__init__.py | get_url_from_model_core | def get_url_from_model_core(request, obj):
"""
Returns object URL from model core.
"""
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
return (
edit_pattern.get_url_string(request, obj=obj)
if edit_pattern and edit_pattern.has_permission('get', request, obj=obj) else None
)
else:
return None | python | def get_url_from_model_core(request, obj):
"""
Returns object URL from model core.
"""
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
return (
edit_pattern.get_url_string(request, obj=obj)
if edit_pattern and edit_pattern.has_permission('get', request, obj=obj) else None
)
else:
return None | [
"def",
"get_url_from_model_core",
"(",
"request",
",",
"obj",
")",
":",
"from",
"is_core",
".",
"site",
"import",
"get_model_core",
"model_core",
"=",
"get_model_core",
"(",
"obj",
".",
"__class__",
")",
"if",
"model_core",
"and",
"hasattr",
"(",
"model_core",
",",
"'ui_patterns'",
")",
":",
"edit_pattern",
"=",
"model_core",
".",
"ui_patterns",
".",
"get",
"(",
"'detail'",
")",
"return",
"(",
"edit_pattern",
".",
"get_url_string",
"(",
"request",
",",
"obj",
"=",
"obj",
")",
"if",
"edit_pattern",
"and",
"edit_pattern",
".",
"has_permission",
"(",
"'get'",
",",
"request",
",",
"obj",
"=",
"obj",
")",
"else",
"None",
")",
"else",
":",
"return",
"None"
] | Returns object URL from model core. | [
"Returns",
"object",
"URL",
"from",
"model",
"core",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L284-L298 |
matllubos/django-is-core | is_core/utils/__init__.py | get_obj_url | def get_obj_url(request, obj):
"""
Returns object URL if current logged user has permissions to see the object
"""
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))):
return call_method_with_unknown_input(obj.get_absolute_url, request=request)
else:
return get_url_from_model_core(request, obj) | python | def get_obj_url(request, obj):
"""
Returns object URL if current logged user has permissions to see the object
"""
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))):
return call_method_with_unknown_input(obj.get_absolute_url, request=request)
else:
return get_url_from_model_core(request, obj) | [
"def",
"get_obj_url",
"(",
"request",
",",
"obj",
")",
":",
"if",
"(",
"is_callable",
"(",
"getattr",
"(",
"obj",
",",
"'get_absolute_url'",
",",
"None",
")",
")",
"and",
"(",
"not",
"hasattr",
"(",
"obj",
",",
"'can_see_edit_link'",
")",
"or",
"(",
"is_callable",
"(",
"getattr",
"(",
"obj",
",",
"'can_see_edit_link'",
",",
"None",
")",
")",
"and",
"obj",
".",
"can_see_edit_link",
"(",
"request",
")",
")",
")",
")",
":",
"return",
"call_method_with_unknown_input",
"(",
"obj",
".",
"get_absolute_url",
",",
"request",
"=",
"request",
")",
"else",
":",
"return",
"get_url_from_model_core",
"(",
"request",
",",
"obj",
")"
] | Returns object URL if current logged user has permissions to see the object | [
"Returns",
"object",
"URL",
"if",
"current",
"logged",
"user",
"has",
"permissions",
"to",
"see",
"the",
"object"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L301-L310 |
matllubos/django-is-core | is_core/utils/__init__.py | get_link_or_none | def get_link_or_none(pattern_name, request, view_kwargs=None):
"""
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_kwargs (dict): list of kwargs necessary for URL generator
Returns:
"""
from is_core.patterns import reverse_pattern
pattern = reverse_pattern(pattern_name)
assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name)
if pattern.has_permission('get', request, view_kwargs=view_kwargs):
return pattern.get_url_string(request, view_kwargs=view_kwargs)
else:
return None | python | def get_link_or_none(pattern_name, request, view_kwargs=None):
"""
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_kwargs (dict): list of kwargs necessary for URL generator
Returns:
"""
from is_core.patterns import reverse_pattern
pattern = reverse_pattern(pattern_name)
assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name)
if pattern.has_permission('get', request, view_kwargs=view_kwargs):
return pattern.get_url_string(request, view_kwargs=view_kwargs)
else:
return None | [
"def",
"get_link_or_none",
"(",
"pattern_name",
",",
"request",
",",
"view_kwargs",
"=",
"None",
")",
":",
"from",
"is_core",
".",
"patterns",
"import",
"reverse_pattern",
"pattern",
"=",
"reverse_pattern",
"(",
"pattern_name",
")",
"assert",
"pattern",
"is",
"not",
"None",
",",
"'Invalid pattern name {}'",
".",
"format",
"(",
"pattern_name",
")",
"if",
"pattern",
".",
"has_permission",
"(",
"'get'",
",",
"request",
",",
"view_kwargs",
"=",
"view_kwargs",
")",
":",
"return",
"pattern",
".",
"get_url_string",
"(",
"request",
",",
"view_kwargs",
"=",
"view_kwargs",
")",
"else",
":",
"return",
"None"
] | Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_kwargs (dict): list of kwargs necessary for URL generator
Returns: | [
"Helper",
"that",
"generate",
"URL",
"prom",
"pattern",
"name",
"and",
"kwargs",
"and",
"check",
"if",
"current",
"request",
"has",
"permission",
"to",
"open",
"the",
"URL",
".",
"If",
"not",
"None",
"is",
"returned",
"."
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L339-L360 |
matllubos/django-is-core | is_core/utils/__init__.py | GetMethodFieldMixin.get_method_returning_field_value | def get_method_returning_field_value(self, field_name):
"""
Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value
"""
method = getattr(self, field_name, None)
return method if method and callable(method) else None | python | def get_method_returning_field_value(self, field_name):
"""
Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value
"""
method = getattr(self, field_name, None)
return method if method and callable(method) else None | [
"def",
"get_method_returning_field_value",
"(",
"self",
",",
"field_name",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"field_name",
",",
"None",
")",
"return",
"method",
"if",
"method",
"and",
"callable",
"(",
"method",
")",
"else",
"None"
] | Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value | [
"Method",
"should",
"return",
"object",
"method",
"that",
"can",
"be",
"used",
"to",
"get",
"field",
"value",
".",
"Args",
":",
"field_name",
":",
"name",
"of",
"the",
"field"
] | train | https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/utils/__init__.py#L365-L375 |
inveniosoftware/invenio-iiif | invenio_iiif/handlers.py | protect_api | def protect_api(uuid=None, **kwargs):
"""Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory.
"""
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, version_id)
return g.obj | python | def protect_api(uuid=None, **kwargs):
"""Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory.
"""
bucket, version_id, key = uuid.split(':', 2)
g.obj = ObjectResource.get_object(bucket, key, version_id)
return g.obj | [
"def",
"protect_api",
"(",
"uuid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"bucket",
",",
"version_id",
",",
"key",
"=",
"uuid",
".",
"split",
"(",
"':'",
",",
"2",
")",
"g",
".",
"obj",
"=",
"ObjectResource",
".",
"get_object",
"(",
"bucket",
",",
"key",
",",
"version_id",
")",
"return",
"g",
".",
"obj"
] | Retrieve object and check permissions.
Retrieve ObjectVersion of image being requested and check permission
using the Invenio-Files-REST permission factory. | [
"Retrieve",
"object",
"and",
"check",
"permissions",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L29-L37 |
inveniosoftware/invenio-iiif | invenio_iiif/handlers.py | image_opener | def image_opener(key):
"""Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object.
"""
if hasattr(g, 'obj'):
obj = g.obj
else:
obj = protect_api(key)
fp = obj.file.storage().open('rb')
# If ImageMagick with Wand is installed, extract first page
# for PDF/text.
if HAS_IMAGEMAGICK and obj.mimetype in ['application/pdf', 'text/plain']:
first_page = Image(Image(fp).sequence[0])
tempfile_ = tempfile.TemporaryFile()
with first_page.convert(format='png') as converted:
converted.save(file=tempfile_)
return tempfile_
return fp | python | def image_opener(key):
"""Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object.
"""
if hasattr(g, 'obj'):
obj = g.obj
else:
obj = protect_api(key)
fp = obj.file.storage().open('rb')
# If ImageMagick with Wand is installed, extract first page
# for PDF/text.
if HAS_IMAGEMAGICK and obj.mimetype in ['application/pdf', 'text/plain']:
first_page = Image(Image(fp).sequence[0])
tempfile_ = tempfile.TemporaryFile()
with first_page.convert(format='png') as converted:
converted.save(file=tempfile_)
return tempfile_
return fp | [
"def",
"image_opener",
"(",
"key",
")",
":",
"if",
"hasattr",
"(",
"g",
",",
"'obj'",
")",
":",
"obj",
"=",
"g",
".",
"obj",
"else",
":",
"obj",
"=",
"protect_api",
"(",
"key",
")",
"fp",
"=",
"obj",
".",
"file",
".",
"storage",
"(",
")",
".",
"open",
"(",
"'rb'",
")",
"# If ImageMagick with Wand is installed, extract first page",
"# for PDF/text.",
"if",
"HAS_IMAGEMAGICK",
"and",
"obj",
".",
"mimetype",
"in",
"[",
"'application/pdf'",
",",
"'text/plain'",
"]",
":",
"first_page",
"=",
"Image",
"(",
"Image",
"(",
"fp",
")",
".",
"sequence",
"[",
"0",
"]",
")",
"tempfile_",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"with",
"first_page",
".",
"convert",
"(",
"format",
"=",
"'png'",
")",
"as",
"converted",
":",
"converted",
".",
"save",
"(",
"file",
"=",
"tempfile_",
")",
"return",
"tempfile_",
"return",
"fp"
] | Handler to locate file based on key.
:param key: A key encoded in the format "<bucket>:<version>:<object_key>".
:returns: A file-like object. | [
"Handler",
"to",
"locate",
"file",
"based",
"on",
"key",
"."
] | train | https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/handlers.py#L40-L61 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.tables | def tables(self):
"""The complete list of tables."""
# If we are on unix use mdbtools instead #
if os.name == "posix":
mdb_tables = sh.Command("mdb-tables")
tables_list = mdb_tables('-1', self.path).split('\n')
condition = lambda t: t and not t.startswith('MSys')
return [t.lower() for t in tables_list if condition(t)]
# Default case #
return [table[2].lower() for table in self.own_cursor.tables() if not table[2].startswith('MSys')] | python | def tables(self):
"""The complete list of tables."""
# If we are on unix use mdbtools instead #
if os.name == "posix":
mdb_tables = sh.Command("mdb-tables")
tables_list = mdb_tables('-1', self.path).split('\n')
condition = lambda t: t and not t.startswith('MSys')
return [t.lower() for t in tables_list if condition(t)]
# Default case #
return [table[2].lower() for table in self.own_cursor.tables() if not table[2].startswith('MSys')] | [
"def",
"tables",
"(",
"self",
")",
":",
"# If we are on unix use mdbtools instead #",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"mdb_tables",
"=",
"sh",
".",
"Command",
"(",
"\"mdb-tables\"",
")",
"tables_list",
"=",
"mdb_tables",
"(",
"'-1'",
",",
"self",
".",
"path",
")",
".",
"split",
"(",
"'\\n'",
")",
"condition",
"=",
"lambda",
"t",
":",
"t",
"and",
"not",
"t",
".",
"startswith",
"(",
"'MSys'",
")",
"return",
"[",
"t",
".",
"lower",
"(",
")",
"for",
"t",
"in",
"tables_list",
"if",
"condition",
"(",
"t",
")",
"]",
"# Default case #",
"return",
"[",
"table",
"[",
"2",
"]",
".",
"lower",
"(",
")",
"for",
"table",
"in",
"self",
".",
"own_cursor",
".",
"tables",
"(",
")",
"if",
"not",
"table",
"[",
"2",
"]",
".",
"startswith",
"(",
"'MSys'",
")",
"]"
] | The complete list of tables. | [
"The",
"complete",
"list",
"of",
"tables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L84-L93 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.table_as_df | def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | python | def table_as_df(self, table_name):
"""Return a table as a dataframe."""
self.table_must_exist(table_name)
query = "SELECT * FROM `%s`" % table_name.lower()
return pandas.read_sql(query, self.own_conn) | [
"def",
"table_as_df",
"(",
"self",
",",
"table_name",
")",
":",
"self",
".",
"table_must_exist",
"(",
"table_name",
")",
"query",
"=",
"\"SELECT * FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"return",
"pandas",
".",
"read_sql",
"(",
"query",
",",
"self",
".",
"own_conn",
")"
] | Return a table as a dataframe. | [
"Return",
"a",
"table",
"as",
"a",
"dataframe",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L134-L138 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.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_conn) | 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_conn) | [
"def",
"insert_df",
"(",
"self",
",",
"table_name",
",",
"df",
")",
":",
"df",
".",
"to_sql",
"(",
"table_name",
",",
"con",
"=",
"self",
".",
"own_conn",
")"
] | 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/access_database.py#L140-L142 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.count_rows | def count_rows(self, table_name):
"""Return the number of entries in a table by counting them."""
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | python | def count_rows(self, table_name):
"""Return the number of entries in a table by counting them."""
self.table_must_exist(table_name)
query = "SELECT COUNT (*) FROM `%s`" % table_name.lower()
self.own_cursor.execute(query)
return int(self.own_cursor.fetchone()[0]) | [
"def",
"count_rows",
"(",
"self",
",",
"table_name",
")",
":",
"self",
".",
"table_must_exist",
"(",
"table_name",
")",
"query",
"=",
"\"SELECT COUNT (*) FROM `%s`\"",
"%",
"table_name",
".",
"lower",
"(",
")",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"query",
")",
"return",
"int",
"(",
"self",
".",
"own_cursor",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
")"
] | Return the number of entries in a table by counting them. | [
"Return",
"the",
"number",
"of",
"entries",
"in",
"a",
"table",
"by",
"counting",
"them",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L144-L149 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.tables_with_counts | def tables_with_counts(self):
"""Return the number of entries in all table."""
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | python | def tables_with_counts(self):
"""Return the number of entries in all table."""
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | [
"def",
"tables_with_counts",
"(",
"self",
")",
":",
"table_to_count",
"=",
"lambda",
"t",
":",
"self",
".",
"count_rows",
"(",
"t",
")",
"return",
"zip",
"(",
"self",
".",
"tables",
",",
"map",
"(",
"table_to_count",
",",
"self",
".",
"tables",
")",
")"
] | Return the number of entries in all table. | [
"Return",
"the",
"number",
"of",
"entries",
"in",
"all",
"table",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L155-L158 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.convert_to_sqlite | def convert_to_sqlite(self, destination=None, method="shell", progress=False):
"""Who wants to use Access when you can deal with SQLite databases instead?"""
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if destination is None: destination = self.replace_extension('sqlite')
# Delete if it exists #
destination.remove()
# Method with shell and a temp file #
if method == 'shell': return self.sqlite_by_shell(destination)
# Method without a temp file #
if method == 'object': return self.sqlite_by_object(destination, progress)
# Method with dataframe #
if method == 'dataframe': return self.sqlite_by_df(destination, progress) | python | def convert_to_sqlite(self, destination=None, method="shell", progress=False):
"""Who wants to use Access when you can deal with SQLite databases instead?"""
# Display progress bar #
if progress: progress = tqdm.tqdm
else: progress = lambda x:x
# Default path #
if destination is None: destination = self.replace_extension('sqlite')
# Delete if it exists #
destination.remove()
# Method with shell and a temp file #
if method == 'shell': return self.sqlite_by_shell(destination)
# Method without a temp file #
if method == 'object': return self.sqlite_by_object(destination, progress)
# Method with dataframe #
if method == 'dataframe': return self.sqlite_by_df(destination, progress) | [
"def",
"convert_to_sqlite",
"(",
"self",
",",
"destination",
"=",
"None",
",",
"method",
"=",
"\"shell\"",
",",
"progress",
"=",
"False",
")",
":",
"# Display progress bar #",
"if",
"progress",
":",
"progress",
"=",
"tqdm",
".",
"tqdm",
"else",
":",
"progress",
"=",
"lambda",
"x",
":",
"x",
"# Default path #",
"if",
"destination",
"is",
"None",
":",
"destination",
"=",
"self",
".",
"replace_extension",
"(",
"'sqlite'",
")",
"# Delete if it exists #",
"destination",
".",
"remove",
"(",
")",
"# Method with shell and a temp file #",
"if",
"method",
"==",
"'shell'",
":",
"return",
"self",
".",
"sqlite_by_shell",
"(",
"destination",
")",
"# Method without a temp file #",
"if",
"method",
"==",
"'object'",
":",
"return",
"self",
".",
"sqlite_by_object",
"(",
"destination",
",",
"progress",
")",
"# Method with dataframe #",
"if",
"method",
"==",
"'dataframe'",
":",
"return",
"self",
".",
"sqlite_by_df",
"(",
"destination",
",",
"progress",
")"
] | Who wants to use Access when you can deal with SQLite databases instead? | [
"Who",
"wants",
"to",
"use",
"Access",
"when",
"you",
"can",
"deal",
"with",
"SQLite",
"databases",
"instead?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L167-L181 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_shell | def sqlite_by_shell(self, destination):
"""Method with shell and a temp file. This is hopefully fast."""
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | python | def sqlite_by_shell(self, destination):
"""Method with shell and a temp file. This is hopefully fast."""
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | [
"def",
"sqlite_by_shell",
"(",
"self",
",",
"destination",
")",
":",
"script_path",
"=",
"new_temp_path",
"(",
")",
"self",
".",
"sqlite_dump_shell",
"(",
"script_path",
")",
"shell_output",
"(",
"'sqlite3 -bail -init \"%s\" \"%s\" .quit'",
"%",
"(",
"script",
",",
"destination",
")",
")",
"script",
".",
"remove",
"(",
")"
] | Method with shell and a temp file. This is hopefully fast. | [
"Method",
"with",
"shell",
"and",
"a",
"temp",
"file",
".",
"This",
"is",
"hopefully",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L183-L188 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_object | def sqlite_by_object(self, destination, progress):
"""This is probably not very fast."""
db = SQLiteDatabase(destination)
db.create()
for script in self.sqlite_dump_string(progress): db.cursor.executescript(script)
db.close() | python | def sqlite_by_object(self, destination, progress):
"""This is probably not very fast."""
db = SQLiteDatabase(destination)
db.create()
for script in self.sqlite_dump_string(progress): db.cursor.executescript(script)
db.close() | [
"def",
"sqlite_by_object",
"(",
"self",
",",
"destination",
",",
"progress",
")",
":",
"db",
"=",
"SQLiteDatabase",
"(",
"destination",
")",
"db",
".",
"create",
"(",
")",
"for",
"script",
"in",
"self",
".",
"sqlite_dump_string",
"(",
"progress",
")",
":",
"db",
".",
"cursor",
".",
"executescript",
"(",
"script",
")",
"db",
".",
"close",
"(",
")"
] | This is probably not very fast. | [
"This",
"is",
"probably",
"not",
"very",
"fast",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L190-L195 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_by_df | def sqlite_by_df(self, destination, progress):
"""Is this fast?"""
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | python | def sqlite_by_df(self, destination, progress):
"""Is this fast?"""
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | [
"def",
"sqlite_by_df",
"(",
"self",
",",
"destination",
",",
"progress",
")",
":",
"db",
"=",
"SQLiteDatabase",
"(",
"destination",
")",
"db",
".",
"create",
"(",
")",
"for",
"table",
"in",
"progress",
"(",
"self",
".",
"real_tables",
")",
":",
"self",
"[",
"table",
"]",
".",
"to_sql",
"(",
"table",
",",
"con",
"=",
"db",
".",
"connection",
")",
"db",
".",
"close",
"(",
")"
] | Is this fast? | [
"Is",
"this",
"fast?"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L197-L202 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_dump_shell | def sqlite_dump_shell(self, script_path):
"""Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*."""
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds things up when importing #
script_path.append("\n\n\nBEGIN TRANSACTION;\n")
# Then export every table #
for table in self.tables:
command = 'mdb-export -I sqlite "%s" "%s" >> "%s"'
shell_output(command % (self.path, table, script_path))
# End the transaction
script_path.append("\n\n\nEND TRANSACTION;\n") | python | def sqlite_dump_shell(self, script_path):
"""Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*."""
# First the schema #
shell_output('mdb-schema "%s" sqlite >> "%s"' % (self.path, script_path))
# Start a transaction, speeds things up when importing #
script_path.append("\n\n\nBEGIN TRANSACTION;\n")
# Then export every table #
for table in self.tables:
command = 'mdb-export -I sqlite "%s" "%s" >> "%s"'
shell_output(command % (self.path, table, script_path))
# End the transaction
script_path.append("\n\n\nEND TRANSACTION;\n") | [
"def",
"sqlite_dump_shell",
"(",
"self",
",",
"script_path",
")",
":",
"# First the schema #",
"shell_output",
"(",
"'mdb-schema \"%s\" sqlite >> \"%s\"'",
"%",
"(",
"self",
".",
"path",
",",
"script_path",
")",
")",
"# Start a transaction, speeds things up when importing #",
"script_path",
".",
"append",
"(",
"\"\\n\\n\\nBEGIN TRANSACTION;\\n\"",
")",
"# Then export every table #",
"for",
"table",
"in",
"self",
".",
"tables",
":",
"command",
"=",
"'mdb-export -I sqlite \"%s\" \"%s\" >> \"%s\"'",
"shell_output",
"(",
"command",
"%",
"(",
"self",
".",
"path",
",",
"table",
",",
"script_path",
")",
")",
"# End the transaction",
"script_path",
".",
"append",
"(",
"\"\\n\\n\\nEND TRANSACTION;\\n\"",
")"
] | Generate a text dump compatible with SQLite by using
shell commands. Place this script at *script_path*. | [
"Generate",
"a",
"text",
"dump",
"compatible",
"with",
"SQLite",
"by",
"using",
"shell",
"commands",
".",
"Place",
"this",
"script",
"at",
"*",
"script_path",
"*",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L204-L216 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.sqlite_dump_string | def sqlite_dump_string(self, progress):
"""Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string."""
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transaction, speeds things up when importing #
yield "BEGIN TRANSACTION;\n"
# Then export every table #
mdb_export = sh.Command("mdb-export")
for table in progress(self.tables):
yield mdb_export('-I', 'sqlite', self.path, table).encode('utf8')
# End the transaction
yield "END TRANSACTION;\n" | python | def sqlite_dump_string(self, progress):
"""Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string."""
# First the schema #
mdb_schema = sh.Command("mdb-schema")
yield mdb_schema(self.path, "sqlite").encode('utf8')
# Start a transaction, speeds things up when importing #
yield "BEGIN TRANSACTION;\n"
# Then export every table #
mdb_export = sh.Command("mdb-export")
for table in progress(self.tables):
yield mdb_export('-I', 'sqlite', self.path, table).encode('utf8')
# End the transaction
yield "END TRANSACTION;\n" | [
"def",
"sqlite_dump_string",
"(",
"self",
",",
"progress",
")",
":",
"# First the schema #",
"mdb_schema",
"=",
"sh",
".",
"Command",
"(",
"\"mdb-schema\"",
")",
"yield",
"mdb_schema",
"(",
"self",
".",
"path",
",",
"\"sqlite\"",
")",
".",
"encode",
"(",
"'utf8'",
")",
"# Start a transaction, speeds things up when importing #",
"yield",
"\"BEGIN TRANSACTION;\\n\"",
"# Then export every table #",
"mdb_export",
"=",
"sh",
".",
"Command",
"(",
"\"mdb-export\"",
")",
"for",
"table",
"in",
"progress",
"(",
"self",
".",
"tables",
")",
":",
"yield",
"mdb_export",
"(",
"'-I'",
",",
"'sqlite'",
",",
"self",
".",
"path",
",",
"table",
")",
".",
"encode",
"(",
"'utf8'",
")",
"# End the transaction",
"yield",
"\"END TRANSACTION;\\n\""
] | Generate a text dump compatible with SQLite.
By yielding every table one by one as a byte string. | [
"Generate",
"a",
"text",
"dump",
"compatible",
"with",
"SQLite",
".",
"By",
"yielding",
"every",
"table",
"one",
"by",
"one",
"as",
"a",
"byte",
"string",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L218-L231 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.import_table | def import_table(self, source, table_name):
"""Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment."""
# Run commands #
wsl = sh.Command("wsl.exe")
table_schema = wsl("-e", "mdb-schema", "-T", table_name, source.wsl_style, "access")
table_contents = wsl("-e", "mdb-export", "-I", "access", source.wsl_style, table_name)
# Filter #
table_schema = ' '.join(l for l in table_schema.split('\n') if not l.startswith("--"))
# Execute statements #
self.cursor.execute(str(table_schema))
self.cursor.execute(str(table_contents)) | python | def import_table(self, source, table_name):
"""Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment."""
# Run commands #
wsl = sh.Command("wsl.exe")
table_schema = wsl("-e", "mdb-schema", "-T", table_name, source.wsl_style, "access")
table_contents = wsl("-e", "mdb-export", "-I", "access", source.wsl_style, table_name)
# Filter #
table_schema = ' '.join(l for l in table_schema.split('\n') if not l.startswith("--"))
# Execute statements #
self.cursor.execute(str(table_schema))
self.cursor.execute(str(table_contents)) | [
"def",
"import_table",
"(",
"self",
",",
"source",
",",
"table_name",
")",
":",
"# Run commands #",
"wsl",
"=",
"sh",
".",
"Command",
"(",
"\"wsl.exe\"",
")",
"table_schema",
"=",
"wsl",
"(",
"\"-e\"",
",",
"\"mdb-schema\"",
",",
"\"-T\"",
",",
"table_name",
",",
"source",
".",
"wsl_style",
",",
"\"access\"",
")",
"table_contents",
"=",
"wsl",
"(",
"\"-e\"",
",",
"\"mdb-export\"",
",",
"\"-I\"",
",",
"\"access\"",
",",
"source",
".",
"wsl_style",
",",
"table_name",
")",
"# Filter #",
"table_schema",
"=",
"' '",
".",
"join",
"(",
"l",
"for",
"l",
"in",
"table_schema",
".",
"split",
"(",
"'\\n'",
")",
"if",
"not",
"l",
".",
"startswith",
"(",
"\"--\"",
")",
")",
"# Execute statements #",
"self",
".",
"cursor",
".",
"execute",
"(",
"str",
"(",
"table_schema",
")",
")",
"self",
".",
"cursor",
".",
"execute",
"(",
"str",
"(",
"table_contents",
")",
")"
] | Copy a table from another Access database to this one.
Requires that you have mdbtools command line executables installed
in a Windows Subsystem for Linux environment. | [
"Copy",
"a",
"table",
"from",
"another",
"Access",
"database",
"to",
"this",
"one",
".",
"Requires",
"that",
"you",
"have",
"mdbtools",
"command",
"line",
"executables",
"installed",
"in",
"a",
"Windows",
"Subsystem",
"for",
"Linux",
"environment",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L234-L246 |
xapple/plumbing | plumbing/databases/access_database.py | AccessDatabase.create | def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
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
"""
pristine = StringIO()
pristine.write(base64.b64decode(mdb_gz_b64))
pristine.seek(0)
pristine = gzip.GzipFile(fileobj=pristine, mode='rb')
with open(destination, 'wb') as handle: shutil.copyfileobj(pristine, handle)
return cls(destination) | python | def create(cls, destination):
"""Create a new empty MDB at destination."""
mdb_gz_b64 = """\
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
"""
pristine = StringIO()
pristine.write(base64.b64decode(mdb_gz_b64))
pristine.seek(0)
pristine = gzip.GzipFile(fileobj=pristine, mode='rb')
with open(destination, 'wb') as handle: shutil.copyfileobj(pristine, handle)
return cls(destination) | [
"def",
"create",
"(",
"cls",
",",
"destination",
")",
":",
"mdb_gz_b64",
"=",
"\"\"\"\\\n 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\n \"\"\"",
"pristine",
"=",
"StringIO",
"(",
")",
"pristine",
".",
"write",
"(",
"base64",
".",
"b64decode",
"(",
"mdb_gz_b64",
")",
")",
"pristine",
".",
"seek",
"(",
"0",
")",
"pristine",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"pristine",
",",
"mode",
"=",
"'rb'",
")",
"with",
"open",
"(",
"destination",
",",
"'wb'",
")",
"as",
"handle",
":",
"shutil",
".",
"copyfileobj",
"(",
"pristine",
",",
"handle",
")",
"return",
"cls",
"(",
"destination",
")"
] | Create a new empty MDB at destination. | [
"Create",
"a",
"new",
"empty",
"MDB",
"at",
"destination",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/access_database.py#L250-L299 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.tables | def tables(self):
"""The complete list of SQL tables."""
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory = self.factory
return result | python | def tables(self):
"""The complete list of SQL tables."""
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory = self.factory
return result | [
"def",
"tables",
"(",
"self",
")",
":",
"self",
".",
"own_connection",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT name from sqlite_master where type=\"table\";'",
")",
"result",
"=",
"[",
"x",
"[",
"0",
"]",
".",
"encode",
"(",
"'ascii'",
")",
"for",
"x",
"in",
"self",
".",
"own_cursor",
".",
"fetchall",
"(",
")",
"]",
"self",
".",
"own_connection",
".",
"row_factory",
"=",
"self",
".",
"factory",
"return",
"result"
] | The complete list of SQL tables. | [
"The",
"complete",
"list",
"of",
"SQL",
"tables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L100-L106 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.new_connection | def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | python | def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | [
"def",
"new_connection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"prepared",
":",
"self",
".",
"prepare",
"(",
")",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"path",
",",
"isolation_level",
"=",
"self",
".",
"isolation",
")",
"con",
".",
"row_factory",
"=",
"self",
".",
"factory",
"if",
"self",
".",
"text_fact",
":",
"con",
".",
"text_factory",
"=",
"self",
".",
"text_fact",
"return",
"con"
] | Make a new connection. | [
"Make",
"a",
"new",
"connection",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L134-L140 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.prepare | def prepare(self):
"""Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5."""
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
download_from_url(self.retrieve, self.path, progress=True)
else: raise Exception("The file '" + self.path + "' does not exist.")
self.check_format()
if self.known_md5: assert self.known_md5 == self.md5
self.prepared = True | python | def prepare(self):
"""Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5."""
if not os.path.exists(self.path):
if self.retrieve:
print("Downloading SQLite3 database...")
download_from_url(self.retrieve, self.path, progress=True)
else: raise Exception("The file '" + self.path + "' does not exist.")
self.check_format()
if self.known_md5: assert self.known_md5 == self.md5
self.prepared = True | [
"def",
"prepare",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"if",
"self",
".",
"retrieve",
":",
"print",
"(",
"\"Downloading SQLite3 database...\"",
")",
"download_from_url",
"(",
"self",
".",
"retrieve",
",",
"self",
".",
"path",
",",
"progress",
"=",
"True",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"The file '\"",
"+",
"self",
".",
"path",
"+",
"\"' does not exist.\"",
")",
"self",
".",
"check_format",
"(",
")",
"if",
"self",
".",
"known_md5",
":",
"assert",
"self",
".",
"known_md5",
"==",
"self",
".",
"md5",
"self",
".",
"prepared",
"=",
"True"
] | Check that the file exists, optionally downloads it.
Checks that the file is indeed an SQLite3 database.
Optionally check the MD5. | [
"Check",
"that",
"the",
"file",
"exists",
"optionally",
"downloads",
"it",
".",
"Checks",
"that",
"the",
"file",
"is",
"indeed",
"an",
"SQLite3",
"database",
".",
"Optionally",
"check",
"the",
"MD5",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L142-L153 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.create | def create(self, columns=None, type_map=None, overwrite=False):
"""Create a new database with a certain schema."""
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we want it empty #
if columns is None:
self.touch()
# Make the table #
else:
self.add_table(self.main_table, columns=columns, type_map=type_map) | python | def create(self, columns=None, type_map=None, overwrite=False):
"""Create a new database with a certain schema."""
# Check already exists #
if self.count_bytes > 0:
if overwrite: self.remove()
else: raise Exception("File exists already at '%s'" % self)
# If we want it empty #
if columns is None:
self.touch()
# Make the table #
else:
self.add_table(self.main_table, columns=columns, type_map=type_map) | [
"def",
"create",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"type_map",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"# Check already exists #",
"if",
"self",
".",
"count_bytes",
">",
"0",
":",
"if",
"overwrite",
":",
"self",
".",
"remove",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"File exists already at '%s'\"",
"%",
"self",
")",
"# If we want it empty #",
"if",
"columns",
"is",
"None",
":",
"self",
".",
"touch",
"(",
")",
"# Make the table #",
"else",
":",
"self",
".",
"add_table",
"(",
"self",
".",
"main_table",
",",
"columns",
"=",
"columns",
",",
"type_map",
"=",
"type_map",
")"
] | Create a new database with a certain schema. | [
"Create",
"a",
"new",
"database",
"with",
"a",
"certain",
"schema",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L161-L172 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add_table | def add_table(self, name, columns, type_map=None, if_not_exists=False):
"""Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})"""
# Check types mapping #
if type_map is None and isinstance(columns, dict): types = columns
if type_map is None: types = {}
# Safe or unsafe #
if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);'
else: query = 'CREATE table "%s" (%s);'
# Do it #
cols = ','.join(['"' + c + '"' + ' ' + types.get(c, 'text') for c in columns])
self.own_cursor.execute(query % (self.main_table, cols)) | python | def add_table(self, name, columns, type_map=None, if_not_exists=False):
"""Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})"""
# Check types mapping #
if type_map is None and isinstance(columns, dict): types = columns
if type_map is None: types = {}
# Safe or unsafe #
if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);'
else: query = 'CREATE table "%s" (%s);'
# Do it #
cols = ','.join(['"' + c + '"' + ' ' + types.get(c, 'text') for c in columns])
self.own_cursor.execute(query % (self.main_table, cols)) | [
"def",
"add_table",
"(",
"self",
",",
"name",
",",
"columns",
",",
"type_map",
"=",
"None",
",",
"if_not_exists",
"=",
"False",
")",
":",
"# Check types mapping #",
"if",
"type_map",
"is",
"None",
"and",
"isinstance",
"(",
"columns",
",",
"dict",
")",
":",
"types",
"=",
"columns",
"if",
"type_map",
"is",
"None",
":",
"types",
"=",
"{",
"}",
"# Safe or unsafe #",
"if",
"if_not_exists",
":",
"query",
"=",
"'CREATE TABLE IF NOT EXISTS \"%s\" (%s);'",
"else",
":",
"query",
"=",
"'CREATE table \"%s\" (%s);'",
"# Do it #",
"cols",
"=",
"','",
".",
"join",
"(",
"[",
"'\"'",
"+",
"c",
"+",
"'\"'",
"+",
"' '",
"+",
"types",
".",
"get",
"(",
"c",
",",
"'text'",
")",
"for",
"c",
"in",
"columns",
"]",
")",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"query",
"%",
"(",
"self",
".",
"main_table",
",",
"cols",
")",
")"
] | Add add a new table to the database. For instance you could do this:
self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'}) | [
"Add",
"add",
"a",
"new",
"table",
"to",
"the",
"database",
".",
"For",
"instance",
"you",
"could",
"do",
"this",
":",
"self",
".",
"add_table",
"(",
"data",
"{",
"id",
":",
"integer",
"source",
":",
"text",
"pubmed",
":",
"integer",
"}",
")"
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L174-L185 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_columns_of_table | def get_columns_of_table(self, table=None):
"""Return the list of columns for a particular table
by querying the SQL for the complete list of column names."""
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A PRAGMA statement will implicitly issue a commit, don't use #
self.own_cursor.execute('SELECT * from "%s" LIMIT 1;' % table)
columns = [x[0] for x in self.own_cursor.description]
self.cursor.fetchall()
return columns | python | def get_columns_of_table(self, table=None):
"""Return the list of columns for a particular table
by querying the SQL for the complete list of column names."""
# Check the table exists #
if table is None: table = self.main_table
if not table in self.tables: return []
# A PRAGMA statement will implicitly issue a commit, don't use #
self.own_cursor.execute('SELECT * from "%s" LIMIT 1;' % table)
columns = [x[0] for x in self.own_cursor.description]
self.cursor.fetchall()
return columns | [
"def",
"get_columns_of_table",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"# Check the table exists #",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
"not",
"table",
"in",
"self",
".",
"tables",
":",
"return",
"[",
"]",
"# A PRAGMA statement will implicitly issue a commit, don't use #",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT * from \"%s\" LIMIT 1;'",
"%",
"table",
")",
"columns",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"own_cursor",
".",
"description",
"]",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")",
"return",
"columns"
] | Return the list of columns for a particular table
by querying the SQL for the complete list of column names. | [
"Return",
"the",
"list",
"of",
"columns",
"for",
"a",
"particular",
"table",
"by",
"querying",
"the",
"SQL",
"for",
"the",
"complete",
"list",
"of",
"column",
"names",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L191-L201 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add | def add(self, entries, table=None, columns=None, ignore=False):
"""Add entries to a table.
The *entries* variable should be an iterable."""
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
# Default columns #
question_marks = ','.join('?' for c in columns)
cols = ','.join('"' + c + '"' for c in columns)
ignore = " OR IGNORE" if ignore else ""
sql_command = 'INSERT%s into "%s"(%s) VALUES (%s);'
sql_command = sql_command % (ignore, table, cols, question_marks)
# Possible errors we want to catch #
errors = (sqlite3.OperationalError, sqlite3.ProgrammingError)
errors += (sqlite3.IntegrityError, sqlite3.InterfaceError, ValueError)
# Do it #
try:
new_cursor = self.own_connection.cursor()
new_cursor.executemany(sql_command, entries)
except errors as err:
raise Exception(self.detailed_error(sql_command, columns, entries, err))
except KeyboardInterrupt as err:
print("You interrupted the data insertion.")
print("Committing everything done up to this point.")
self.own_connection.commit()
raise err | python | def add(self, entries, table=None, columns=None, ignore=False):
"""Add entries to a table.
The *entries* variable should be an iterable."""
# Default table and columns #
if table is None: table = self.main_table
if columns is None: columns = self.get_columns_of_table(table)
# Default columns #
question_marks = ','.join('?' for c in columns)
cols = ','.join('"' + c + '"' for c in columns)
ignore = " OR IGNORE" if ignore else ""
sql_command = 'INSERT%s into "%s"(%s) VALUES (%s);'
sql_command = sql_command % (ignore, table, cols, question_marks)
# Possible errors we want to catch #
errors = (sqlite3.OperationalError, sqlite3.ProgrammingError)
errors += (sqlite3.IntegrityError, sqlite3.InterfaceError, ValueError)
# Do it #
try:
new_cursor = self.own_connection.cursor()
new_cursor.executemany(sql_command, entries)
except errors as err:
raise Exception(self.detailed_error(sql_command, columns, entries, err))
except KeyboardInterrupt as err:
print("You interrupted the data insertion.")
print("Committing everything done up to this point.")
self.own_connection.commit()
raise err | [
"def",
"add",
"(",
"self",
",",
"entries",
",",
"table",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"ignore",
"=",
"False",
")",
":",
"# Default table and columns #",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"self",
".",
"get_columns_of_table",
"(",
"table",
")",
"# Default columns #",
"question_marks",
"=",
"','",
".",
"join",
"(",
"'?'",
"for",
"c",
"in",
"columns",
")",
"cols",
"=",
"','",
".",
"join",
"(",
"'\"'",
"+",
"c",
"+",
"'\"'",
"for",
"c",
"in",
"columns",
")",
"ignore",
"=",
"\" OR IGNORE\"",
"if",
"ignore",
"else",
"\"\"",
"sql_command",
"=",
"'INSERT%s into \"%s\"(%s) VALUES (%s);'",
"sql_command",
"=",
"sql_command",
"%",
"(",
"ignore",
",",
"table",
",",
"cols",
",",
"question_marks",
")",
"# Possible errors we want to catch #",
"errors",
"=",
"(",
"sqlite3",
".",
"OperationalError",
",",
"sqlite3",
".",
"ProgrammingError",
")",
"errors",
"+=",
"(",
"sqlite3",
".",
"IntegrityError",
",",
"sqlite3",
".",
"InterfaceError",
",",
"ValueError",
")",
"# Do it #",
"try",
":",
"new_cursor",
"=",
"self",
".",
"own_connection",
".",
"cursor",
"(",
")",
"new_cursor",
".",
"executemany",
"(",
"sql_command",
",",
"entries",
")",
"except",
"errors",
"as",
"err",
":",
"raise",
"Exception",
"(",
"self",
".",
"detailed_error",
"(",
"sql_command",
",",
"columns",
",",
"entries",
",",
"err",
")",
")",
"except",
"KeyboardInterrupt",
"as",
"err",
":",
"print",
"(",
"\"You interrupted the data insertion.\"",
")",
"print",
"(",
"\"Committing everything done up to this point.\"",
")",
"self",
".",
"own_connection",
".",
"commit",
"(",
")",
"raise",
"err"
] | Add entries to a table.
The *entries* variable should be an iterable. | [
"Add",
"entries",
"to",
"a",
"table",
".",
"The",
"*",
"entries",
"*",
"variable",
"should",
"be",
"an",
"iterable",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L203-L228 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.add_by_steps | def add_by_steps(self, entries_by_step, table=None, columns=None):
"""Add entries to the main table.
The *entries* variable should be an iterable yielding iterables."""
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | python | def add_by_steps(self, entries_by_step, table=None, columns=None):
"""Add entries to the main table.
The *entries* variable should be an iterable yielding iterables."""
for entries in entries_by_step: self.add(entries, table=table, columns=columns) | [
"def",
"add_by_steps",
"(",
"self",
",",
"entries_by_step",
",",
"table",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"for",
"entries",
"in",
"entries_by_step",
":",
"self",
".",
"add",
"(",
"entries",
",",
"table",
"=",
"table",
",",
"columns",
"=",
"columns",
")"
] | Add entries to the main table.
The *entries* variable should be an iterable yielding iterables. | [
"Add",
"entries",
"to",
"the",
"main",
"table",
".",
"The",
"*",
"entries",
"*",
"variable",
"should",
"be",
"an",
"iterable",
"yielding",
"iterables",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L255-L258 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.count_entries | def count_entries(self, table=None):
"""How many rows in a table."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table)
return int(self.own_cursor.fetchone()[0]) | python | def count_entries(self, table=None):
"""How many rows in a table."""
if table is None: table = self.main_table
self.own_cursor.execute('SELECT COUNT(1) FROM "%s";' % table)
return int(self.own_cursor.fetchone()[0]) | [
"def",
"count_entries",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT COUNT(1) FROM \"%s\";'",
"%",
"table",
")",
"return",
"int",
"(",
"self",
".",
"own_cursor",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
")"
] | How many rows in a table. | [
"How",
"many",
"rows",
"in",
"a",
"table",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L260-L264 |
xapple/plumbing | plumbing/databases/sqlite_database.py | SQLiteDatabase.get_first | def get_first(self, table=None):
"""Just the first entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | python | def get_first(self, table=None):
"""Just the first entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | [
"def",
"get_first",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"table",
"=",
"self",
".",
"main_table",
"query",
"=",
"'SELECT * FROM \"%s\" LIMIT 1;'",
"%",
"table",
"return",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")"
] | Just the first entry. | [
"Just",
"the",
"first",
"entry",
"."
] | train | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L277-L281 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.