repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
awacha/credolib | credolib/io.py | filter_headers | python | def filter_headers(criterion):
ip = get_ipython()
for headerkind in ['processed', 'raw']:
for h in ip.user_ns['_headers'][headerkind][:]:
if not criterion(h):
ip.user_ns['_headers'][headerkind].remove(h)
ip.user_ns['allsamplenames'] = {h.title for h in ip.user_ns['_header... | Filter already loaded headers against some criterion.
The criterion function must accept a single argument, which is an instance
of sastool.classes2.header.Header, or one of its subclasses. The function
must return True if the header is to be kept or False if it needs to be
discarded. All manipulations... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L13-L27 | null | __all__ = ['load_headers', 'getsascurve', 'getsasexposure', 'getheaders', 'getdists', 'filter_headers', 'load_exposure',
'load_mask']
from typing import List, Tuple, Union
import numpy as np
from IPython.core.getipython import get_ipython
from sastool.classes2.curve import Curve
from sastool.classes2.exposu... |
awacha/credolib | credolib/io.py | load_headers | python | def load_headers(fsns:List[int]):
ip = get_ipython()
ip.user_ns['_headers'] = {}
for type_ in ['raw', 'processed']:
print("Loading %d headers (%s)" % (len(fsns), type_), flush=True)
processed = type_ == 'processed'
headers = []
for f in fsns:
for l in [l_ for l_ i... | Load header files | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L29-L55 | null | __all__ = ['load_headers', 'getsascurve', 'getsasexposure', 'getheaders', 'getdists', 'filter_headers', 'load_exposure',
'load_mask']
from typing import List, Tuple, Union
import numpy as np
from IPython.core.getipython import get_ipython
from sastool.classes2.curve import Curve
from sastool.classes2.exposu... |
awacha/credolib | credolib/interpretation.py | guinieranalysis | python | def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix='', dist=None,
plotguinier=True, graph_extension='.png', dmax=None, dmax_from_shanum=False):
figpr = plt.figure()
ip = get_ipython()
axpr = figpr.add_subplot(1, 1, 1)
if qranges is None:
... | Perform Guinier analysis on the samples.
Inputs:
samplenames: list of sample names
qranges: dictionary of q ranges for each sample. The keys are sample names. The special '__default__' key
corresponds to all samples which do not have a key in the dict.
qmax_from_shanum: use the ... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/interpretation.py#L16-L161 | [
"def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True):\n \"\"\"Execute autorg.\n\n Inputs:\n filename: either a name of an ascii file, or an instance of Curve.\n mininterval: the minimum number of points in the Guinier range\n qminrg: the maximum value of qmin*Rg... | __all__ = ['guinieranalysis']
import os
import ipy_table
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.getipython import get_ipython
from IPython.display import display
from .atsas import autorg, gnom, datgnom, shanum, datporod
from .io import getsascurve
from .utils import writemarkdown
|
awacha/credolib | credolib/atsas.py | autorg | python | def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True):
if isinstance(filename, Curve):
curve = filename
with tempfile.NamedTemporaryFile('w+b',
delete=False) as f:
curve.save(f)
filename = f.name
cmdline = ... | Execute autorg.
Inputs:
filename: either a name of an ascii file, or an instance of Curve.
mininterval: the minimum number of points in the Guinier range
qminrg: the maximum value of qmin*Rg. Default of autorg is 1.0
qmaxrg: the maximum value of qmax*Rg. Default of autorg is 1.3
... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L156-L197 | [
"def execute_command(cmd, input_to_command=None, eat_output=False, noprint=False):\n if isinstance(input_to_command, str):\n stdin = subprocess.PIPE\n else:\n stdin = input_to_command\n popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=stdin)\n if (isinsta... | __all__ = ['read_gnom_pr', 'execute_command', 'autorg', 'shanum', 'datgnom', 'dammif', 'bodies', 'datcmp', 'datporod',
'gnom']
import itertools
import os
import re
import shutil
import subprocess
import tempfile
import ipy_table
import numpy as np
from IPython.display import display
from sastool.classes2.cu... |
awacha/credolib | credolib/atsas.py | shanum | python | def shanum(filename, dmax=None, noprint=True):
if isinstance(filename, Curve):
curve = filename
with tempfile.NamedTemporaryFile('w+b', delete=False) as f:
curve.save(f)
filename = f.name
cmdline = ['shanum', filename]
if dmax is not None:
cmdline.append(str(f... | Execute the shanum program to determine the optimum qmax
according to an estimation of the optimum number of Shannon
channels.
Inputs:
filename: either a name of an ascii file, or an instance
of Curve
dmax: the cut-off of the P(r) function, if known. If None,
thi... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L231-L271 | [
"def execute_command(cmd, input_to_command=None, eat_output=False, noprint=False):\n if isinstance(input_to_command, str):\n stdin = subprocess.PIPE\n else:\n stdin = input_to_command\n popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=stdin)\n if (isinsta... | __all__ = ['read_gnom_pr', 'execute_command', 'autorg', 'shanum', 'datgnom', 'dammif', 'bodies', 'datcmp', 'datporod',
'gnom']
import itertools
import os
import re
import shutil
import subprocess
import tempfile
import ipy_table
import numpy as np
from IPython.display import display
from sastool.classes2.cu... |
awacha/credolib | credolib/atsas.py | datcmp | python | def datcmp(*curves, alpha=None, adjust=None, test='CORMAP'):
if len({len(c) for c in curves}) != 1:
raise ValueError('All curves have to be of the same length.')
datcmpargs = []
if alpha is not None:
datcmpargs.append('--alpha=%f' % alpha)
if adjust is not None:
datcmpargs.append... | Run datcmp on the scattering curves.
Inputs:
*curves: scattering curves as positional arguments
alpha: confidence parameter
adjust: adjustment type (string), see the help of datcmp for details
test: test (string), see the help of datcmp for details
Outputs:
matC: the C ... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L371-L428 | null | __all__ = ['read_gnom_pr', 'execute_command', 'autorg', 'shanum', 'datgnom', 'dammif', 'bodies', 'datcmp', 'datporod',
'gnom']
import itertools
import os
import re
import shutil
import subprocess
import tempfile
import ipy_table
import numpy as np
from IPython.display import display
from sastool.classes2.cu... |
awacha/credolib | credolib/atsas.py | datporod | python | def datporod(gnomoutfile):
results = subprocess.check_output(['datporod', gnomoutfile]).decode('utf-8').strip().split()
return float(results[0]), float(results[1]), float(results[2]) | Run datporod and return the estimated Porod volume.
Returns:
Radius of gyration found in the input file
I0 found in the input file
Vporod: the estimated Porod volume | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L431-L440 | null | __all__ = ['read_gnom_pr', 'execute_command', 'autorg', 'shanum', 'datgnom', 'dammif', 'bodies', 'datcmp', 'datporod',
'gnom']
import itertools
import os
import re
import shutil
import subprocess
import tempfile
import ipy_table
import numpy as np
from IPython.display import display
from sastool.classes2.cu... |
awacha/credolib | credolib/atsas.py | gnom | python | def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None):
with tempfile.TemporaryDirectory(prefix='credolib_gnom') as td:
curve.save(os.path.join(td, 'curve.dat'))
print('Using curve for GNOM: qrange from {} to {}'.format(curve.q.min(), curve.q.max()))
if Npoint... | Run GNOM on the dataset.
Inputs:
curve: an instance of sastool.classes2.Curve or anything which has a
save() method, saving the scattering curve to a given .dat file,
in q=4*pi*sin(theta)/lambda [1/nm] units
Rmax: the estimated maximum extent of the scattering object, in nm.... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L443-L518 | [
"def read_gnom_pr(filename, get_metadata=False):\n metadata = {}\n with open(filename, 'rt', encoding='utf-8') as f:\n l = f.readline()\n while 'Final results' not in l:\n l = f.readline()\n assert (not f.readline().strip()) # skip empty line\n assert (f.readline().stri... | __all__ = ['read_gnom_pr', 'execute_command', 'autorg', 'shanum', 'datgnom', 'dammif', 'bodies', 'datcmp', 'datporod',
'gnom']
import itertools
import os
import re
import shutil
import subprocess
import tempfile
import ipy_table
import numpy as np
from IPython.display import display
from sastool.classes2.cu... |
awacha/credolib | credolib/plotting.py | guinierplot | python | def guinierplot(*args, **kwargs):
ret=plotsascurve(*args, **kwargs)
plt.xscale('power',exponent=2)
plt.yscale('log')
return ret | Make a Guinier plot. This is simply a wrapper around plotsascurve(). | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/plotting.py#L40-L45 | [
"def plotsascurve(samplename, *args, **kwargs):\n if 'dist' not in kwargs:\n kwargs['dist'] = None\n data1d, dist = getsascurve(samplename, kwargs['dist'])\n del kwargs['dist']\n if 'factor' in kwargs:\n factor=kwargs['factor']\n del kwargs['factor']\n else:\n factor=1\n ... | __all__=['plotsascurve','guinierplot','kratkyplot']
from .io import getsascurve
import matplotlib.pyplot as plt
from sastool.libconfig import qunit, dunit
def plotsascurve(samplename, *args, **kwargs):
if 'dist' not in kwargs:
kwargs['dist'] = None
data1d, dist = getsascurve(samplename, kwargs['dist'])... |
awacha/credolib | credolib/procedures.py | summarize | python | def summarize(reintegrate=True, dist_tolerance=3, qranges=None,
samples=None, raw=False, late_radavg=True, graph_ncols=3,
std_multiplier=3, graph_extension='png',
graph_dpi=80, correlmatrix_colormap='coolwarm',
image_colormap='viridis', correlmatrix_logarithmic=Tr... | Summarize scattering patterns and curves for all samples defined
by the global `allsamplenames`.
Inputs:
reintegrate (bool, default=True): if the curves are to be obained
by reintegrating the patterns. Otherwise 1D curves are loaded.
dist_tolerance (float, default=3): sample-to... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/procedures.py#L136-L367 | [
"def writemarkdown(*args):\n display(Markdown(' '.join(str(a) for a in args)))\n",
"def get_different_distances(headers, tolerance=2) -> List[float]:\n alldists = {float(h.distance) for h in headers}\n dists = []\n for d in alldists:\n if [d_ for d_ in dists if abs(d - d_) < tolerance]:\n ... | __all__ = ['summarize', 'unite', 'subtract_bg']
import numbers
import os
import sys
import traceback
import ipy_table
import matplotlib
import matplotlib.cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.getipython import get_ipython
from IPython.display import display
f... |
awacha/credolib | credolib/procedures.py | _merge_two_curves | python | def _merge_two_curves(curve1: Curve, curve2: Curve, qmin, qmax, qsep, use_additive_constant=False):
curve1=curve1.sanitize()
curve2=curve2.sanitize()
if len(curve1.trim(qmin, qmax)) > len(curve2.trim(qmin, qmax)):
curve2_interp = curve2.trim(qmin, qmax)
curve1_interp = curve1.interpolate(cur... | Merge two scattering curves
:param curve1: the first curve (longer distance)
:type curve1: sastool.classes.curve.GeneralCurve
:param curve2: the second curve (shorter distance)
:type curve2: sastool.classes.curve.GeneralCurve
:param qmin: lower bound of the interval for determining the scaling fact... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/procedures.py#L370-L401 | null | __all__ = ['summarize', 'unite', 'subtract_bg']
import numbers
import os
import sys
import traceback
import ipy_table
import matplotlib
import matplotlib.cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.getipython import get_ipython
from IPython.display import display
f... |
awacha/credolib | credolib/procedures.py | subtract_bg | python | def subtract_bg(samplename, bgname, factor=1, distance=None, disttolerance=2,
subname=None, qrange=(), graph_extension='png', graph_dpi=80):
ip = get_ipython()
data1d = ip.user_ns['_data1d']
data2d = ip.user_ns['_data2d']
if 'subtractedsamplenames' not in ip.user_ns:
ip.user_ns['... | Subtract background from measurements.
Inputs:
samplename: the name of the sample
bgname: the name of the background measurements. Alternatively, it can
be a numeric value (float or ErrorValue), which will be subtracted.
If None, this constant will be determined by integrati... | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/procedures.py#L519-L602 | [
"def plotsascurve(samplename, *args, **kwargs):\n if 'dist' not in kwargs:\n kwargs['dist'] = None\n data1d, dist = getsascurve(samplename, kwargs['dist'])\n del kwargs['dist']\n if 'factor' in kwargs:\n factor=kwargs['factor']\n del kwargs['factor']\n else:\n factor=1\n ... | __all__ = ['summarize', 'unite', 'subtract_bg']
import numbers
import os
import sys
import traceback
import ipy_table
import matplotlib
import matplotlib.cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from IPython.core.getipython import get_ipython
from IPython.display import display
f... |
awacha/credolib | credolib/utils.py | putlogo | python | def putlogo(figure=None):
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1], anchor='NW')
logoaxis.set_axis_off()
logoaxis.xaxis.set_visible(False)
logoaxis.yaxis.set_visible(False)
logoaxis.imshow(cred... | Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied). | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/utils.py#L16-L30 | null | __all__=['writemarkdown','putlogo','print_abscissavalue','figsize']
from IPython.display import display,Markdown
from IPython.core.getipython import get_ipython
import matplotlib.pyplot as plt
import sastool
import numpy as np
import pkg_resources
from scipy.misc import imread
credo_logo = imread(pkg_resources.resourc... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.image_by_id | python | def image_by_id(self, id):
if not id:
return None
return next((image for image in self.images() if image['Id'] == id),
None) | Return image with given Id | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L21-L28 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_tag(self, tag):
"""
Return image with given tag
"""
if not t... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.image_by_tag | python | def image_by_tag(self, tag):
if not tag:
return None
return next((image for image in self.images() if tag
in image['RepoTags']), None) | Return image with given tag | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L30-L38 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.image_exists | python | def image_exists(self, id=None, tag=None):
exists = False
if id and self.image_by_id(id):
exists = True
elif tag and self.image_by_tag(tag):
exists = True
return exists | Check if specified image exists | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L40-L50 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.container_by_id | python | def container_by_id(self, id):
if not id:
return None
return next((container for container in self.containers(all=True)
if container['Id'] == id), None) | Returns container with given id | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L52-L59 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.container_by_name | python | def container_by_name(self, name):
if not name:
return None
# docker prepends a '/' to container names in the container dict
name = '/'+name
return next((container for container in self.containers(all=True)
if name in container['Names']), None) | Returns container with given name | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L61-L71 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.container_exists | python | def container_exists(self, id=None, name=None):
exists = False
if id and self.container_by_id(id):
exists = True
elif name and self.container_by_name(name):
exists = True
return exists | Checks if container exists already | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L73-L83 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.container_running | python | def container_running(self, id=None, name=None):
running = False
if id:
running = self.inspect_container(id)['State']['Running']
elif name:
running = self.inspect_container(name)['State']['Running']
return running | Checks if container is running | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L85-L94 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/docker_helper.py | DockerHelper.get_container_ip | python | def get_container_ip(self, container):
info = self.inspect_container(container)
if not info:
return None
netInfo = info['NetworkSettings']
if not netInfo:
return None
ip = netInfo['IPAddress']
if not ip:
return None
return ip | Returns the internal ip of the container if available | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/docker_helper.py#L96-L112 | null | class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__(self):
super(DockerHelper, self).__init__(version=DEFAULT_DOCKER_API_VERSION)
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
... |
kshlm/gant | gant/utils/ssh.py | launch_shell | python | def launch_shell(username, hostname, password, port=22):
if not username or not hostname or not password:
return False
with tempfile.NamedTemporaryFile() as tmpFile:
os.system(sshCmdLine.format(password, tmpFile.name, username, hostname,
port))
return Tru... | Launches an ssh shell | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/ssh.py#L10-L20 | null | from __future__ import unicode_literals, print_function
import os
import tempfile
sshCmdLine = ('sshpass -p {0} ssh -q -o UserKnownHostsFile={1} '
'-o StrictHostKeyChecking=no {2}@{3} -p {4}')
def do_cmd(username, hostname, password, command, port=22):
"""
Runs a command via ssh
"""
i... |
kshlm/gant | gant/utils/gant_docker.py | check_permissions | python | def check_permissions():
if (
not grp.getgrnam('docker').gr_gid in os.getgroups()
and not os.geteuid() == 0
):
exitStr = """
User doesn't have permission to use docker.
You can do either of the following,
1. Add user to the 'docker' group (preferred)
2. Ru... | Checks if current user can access docker | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L14-L28 | null | from __future__ import unicode_literals
import os
import grp
import time
import json
from click import echo
from .docker_helper import DockerHelper
from . import ssh
class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(Gan... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.build_base_image_cmd | python | def build_base_image_cmd(self, force):
check_permissions()
basetag = self.conf.basetag
basedir = self.conf.basedir
verbose = self.conf.verbose
if self.image_exists(tag=basetag):
if not force:
echo("Image with tag '{0}' already exists".format(basetag)... | Build the glusterbase image | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L50-L76 | [
"def check_permissions():\n \"\"\"\n Checks if current user can access docker\n \"\"\"\n if (\n not grp.getgrnam('docker').gr_gid in os.getgroups()\n and not os.geteuid() == 0\n ):\n exitStr = \"\"\"\n User doesn't have permission to use docker.\n You can do either ... | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.build_main_image_cmd | python | def build_main_image_cmd(self, srcdir, force):
check_permissions()
basetag = self.conf.basetag
basedir = self.conf.basedir
maintag = self.conf.maintag
if not self.image_exists(tag=basetag):
if not force:
exit("Base image with tag {0} does not exist".... | Build the main image to be used for launching containers | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L78-L118 | [
"def check_permissions():\n \"\"\"\n Checks if current user can access docker\n \"\"\"\n if (\n not grp.getgrnam('docker').gr_gid in os.getgroups()\n and not os.geteuid() == 0\n ):\n exitStr = \"\"\"\n User doesn't have permission to use docker.\n You can do either ... | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.launch_cmd | python | def launch_cmd(self, n, force):
check_permissions()
prefix = self.conf.prefix
maintag = self.conf.maintag
commandStr = "supervisord -c /etc/supervisor/conf.d/supervisord.conf"
for i in range(1, n+1):
cName = "{0}-{1}".format(prefix, i)
if self.containe... | Launch the specified docker containers using the main image | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L120-L150 | [
"def check_permissions():\n \"\"\"\n Checks if current user can access docker\n \"\"\"\n if (\n not grp.getgrnam('docker').gr_gid in os.getgroups()\n and not os.geteuid() == 0\n ):\n exitStr = \"\"\"\n User doesn't have permission to use docker.\n You can do either ... | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.stop_cmd | python | def stop_cmd(self, name, force):
check_permissions()
if name:
echo("Would stop container {0}".format(name))
else:
echo("Would stop all containers")
echo("For now use 'docker stop' to stop the containers") | Stop the specified or all docker containers launched by us | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L152-L162 | [
"def check_permissions():\n \"\"\"\n Checks if current user can access docker\n \"\"\"\n if (\n not grp.getgrnam('docker').gr_gid in os.getgroups()\n and not os.geteuid() == 0\n ):\n exitStr = \"\"\"\n User doesn't have permission to use docker.\n You can do either ... | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.ssh_cmd | python | def ssh_cmd(self, name, ssh_command):
if not self.container_exists(name=name):
exit("Unknown container {0}".format(name))
if not self.container_running(name=name):
exit("Container {0} is not running".format(name))
ip = self.get_container_ip(name)
if not ip:
... | SSH into given container and executre command if given | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L170-L187 | null | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/utils/gant_docker.py | GantDocker.ip_cmd | python | def ip_cmd(self, name):
if not self.container_exists(name=name):
exit('Unknown container {0}'.format(name))
ip = self.get_container_ip(name)
if not ip:
exit("Failed to get network address for"
" container {0}".format(name))
else:
echo... | Print ip of given container | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L189-L201 | null | class GantDocker (DockerHelper):
"""
Gluster test env specific helper functions for docker
"""
def __init__(self):
super(GantDocker, self).__init__()
def setConf(self, conf):
self.conf = conf
def __handle_build_stream(self, stream, verbose):
for line in stream:
... |
kshlm/gant | gant/main.py | gant | python | def gant(ctx, conf, basedir, basetag, maintag, prefix, verbose):
ctx.obj.initConf(basetag, maintag, basedir, prefix, verbose)
ctx.obj.gd.setConf(ctx.obj.conf) | GAnt : The Gluster helper ant\n
Creates GlusterFS development and testing environments using Docker | train | https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/main.py#L76-L82 | null | #! /usr/bin/env python
from __future__ import unicode_literals, print_function
from .utils.gant_ctx import GantCtx
import os
import click
helpStr = """
Gant : The Gluster helper ant
Creates GlusterFS development and testing environments using Docker
Usage:
gant [options] build-base [force]
gant [options] b... |
laysakura/relshell | relshell/recorddef.py | RecordDef.colindex_by_colname | python | def colindex_by_colname(self, colname):
for i, coldef in enumerate(self): # iterate each column's definition
if coldef.name == colname:
return i
raise ValueError('No column named "%s" found' % (colname)) | Return column index whose name is :param:`column`
:raises: `ValueError` when no column with :param:`colname` found | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/recorddef.py#L67-L75 | null | class RecordDef(object):
"""Used as DDL (like CREATE TABLE) information."""
# APIs
def __init__(self, record_def):
"""Creates an object with each column property from `record_def`.
:param record_def: list of column definition hash (see example below)
*Example:*
.. code-blo... |
laysakura/relshell | relshell/shelloperator.py | ShellOperator.run | python | def run(self, in_batches):
if len(in_batches) != len(self._batcmd.batch_to_file_s):
BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s) # [todo] - Removing tmpfiles can be easily forgot. Less lifetime for tmpfile.
raise AttributeError('len(in_batches) == %d, while... | Run shell operator synchronously to eat `in_batches`
:param in_batches: `tuple` of batches to process | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/shelloperator.py#L49-L78 | [
"def _start_process(batcmd, cwd, env, non_blocking_stdout=False):\n try:\n p = Popen(\n shlex.split(batcmd.sh_cmd),\n stdin = PIPE if batcmd.has_input_from_stdin() else None,\n stdout = PIPE if batcmd.batch_from_file and batcmd.batch_from_file.is_stdout() else None,\n ... | class ShellOperator(BaseShellOperator):
"""ShellOperator
"""
def __init__(
self,
# non-kw & common w/ BaseShellOperator param
cmd,
out_record_def,
# non-kw & original param
out_col_patterns,
# kw & common w/ BaseShellOperator param
success_... |
laysakura/relshell | relshell/base_shelloperator.py | BaseShellOperator._batches_to_tmpfile | python | def _batches_to_tmpfile(in_record_sep, in_column_sep, in_batches, batch_to_file_s):
for i, b2f in enumerate(batch_to_file_s):
if b2f.is_tmpfile():
input_str = BaseShellOperator._input_str(in_batches[i], in_record_sep, in_column_sep)
b2f.write_tmpfile(input_str) | Create files to store in-batches contents (if necessary) | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/base_shelloperator.py#L94-L99 | [
"def _input_str(in_batch, in_record_sep, in_column_sep):\n if len(in_batch) == 0:\n return ''\n\n input_str_list = []\n for record in in_batch:\n for col in record:\n input_str_list.append(str(col))\n input_str_list.append(in_column_sep)\n del input_str_list[-1] ... | class BaseShellOperator(object):
"""BaseShellOperator
"""
__metaclass__ = ABCMeta
_logger = None
def __init__(
self,
cmd,
out_record_def,
success_exitcodes,
cwd,
env,
in_record_sep, # [todo] - explain how this parameter is used (using diagra... |
laysakura/relshell | relshell/base_shelloperator.py | BaseShellOperator._batch_to_stdin | python | def _batch_to_stdin(process, in_record_sep, in_column_sep, in_batches, batch_to_file_s):
for i, b2f in enumerate(batch_to_file_s):
if b2f.is_stdin():
input_str = BaseShellOperator._input_str(in_batches[i], in_record_sep, in_column_sep)
b2f.write_stdin(process.stdin, i... | Write in-batch contents to `process` 's stdin (if necessary) | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/base_shelloperator.py#L102-L109 | [
"def _input_str(in_batch, in_record_sep, in_column_sep):\n if len(in_batch) == 0:\n return ''\n\n input_str_list = []\n for record in in_batch:\n for col in record:\n input_str_list.append(str(col))\n input_str_list.append(in_column_sep)\n del input_str_list[-1] ... | class BaseShellOperator(object):
"""BaseShellOperator
"""
__metaclass__ = ABCMeta
_logger = None
def __init__(
self,
cmd,
out_record_def,
success_exitcodes,
cwd,
env,
in_record_sep, # [todo] - explain how this parameter is used (using diagra... |
laysakura/relshell | relshell/timestamp.py | Timestamp.datetime | python | def datetime(self):
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) | Return `datetime` object | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/timestamp.py#L63-L68 | [
"def year(self):\n \"\"\"Return year\"\"\"\n return int(str(self._ts)[0:4])\n",
"def month(self):\n \"\"\"Return month\"\"\"\n return int(str(self._ts)[4:6])\n",
"def day(self):\n \"\"\"Return day\"\"\"\n return int(str(self._ts)[6:8])\n",
"def hour(self):\n \"\"\"Return hour\"\"\"\n r... | class Timestamp(object):
"""Provides efficient data structure to represent timestamp
"""
def __init__(self, timestamp_str):
"""Constructor
:param timestamp_str: timestamp string
:type timestamp_str: `%Y-%m-%d %H:%M:%S` or `%Y-%m-%d`
"""
try:
t = dt.dateti... |
laysakura/relshell | relshell/type.py | Type.equivalent_relshell_type | python | def equivalent_relshell_type(val):
builtin_type = type(val)
if builtin_type not in Type._typemap:
raise NotImplementedError("builtin type %s is not convertible to relshell type" %
(builtin_type))
relshell_type_str = Type._typemap[builtin_type]
... | Returns `val`'s relshell compatible type.
:param val: value to check relshell equivalent type
:raises: `NotImplementedError` if val's relshell compatible type is not implemented. | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/type.py#L53-L64 | null | class Type(object):
"""Types of columns."""
_typemap = {
# python type : relshell type
int : 'INT',
str : 'STRING',
Timestamp : 'TIMESTAMP'
}
type_list = _typemap.values()
"""List of relshell types."""
# APIs
def __init__(self, relshell_type_str)... |
laysakura/relshell | relshell/daemon_shelloperator.py | DaemonShellOperator.run | python | def run(self, in_batches):
if len(in_batches) != len(self._batcmd.batch_to_file_s):
BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s) # [todo] - Removing tmpfiles can be easily forgot. Less lifetime for tmpfile.
raise AttributeError('len(in_batches) == %d, while... | Run shell operator synchronously to eat `in_batches`
:param in_batches: `tuple` of batches to process | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/daemon_shelloperator.py#L82-L118 | [
"def _start_process(batcmd, cwd, env, non_blocking_stdout=False):\n try:\n p = Popen(\n shlex.split(batcmd.sh_cmd),\n stdin = PIPE if batcmd.has_input_from_stdin() else None,\n stdout = PIPE if batcmd.batch_from_file and batcmd.batch_from_file.is_stdout() else None,\n ... | class DaemonShellOperator(BaseShellOperator):
"""Instantiate process and keep it running.
`DaemonShellOperator` can instantiate processes which satisfy the following constraints:
1. Inputs records from `stdin`
2. Safely dies when `EOF` is input
3. Outputs deterministic string when inputting a spec... |
laysakura/relshell | relshell/daemon_shelloperator.py | DaemonShellOperator.kill | python | def kill(self):
BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)
BaseShellOperator._wait_process(self._process, self._batcmd.sh_cmd, self._success_exitcodes)
BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)
self._process = None | Kill instantiated process
:raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_ | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/daemon_shelloperator.py#L120-L128 | [
"def _wait_process(process, sh_cmd, success_exitcodes):\n exitcode = process.wait() # [todo] - if this call does not return, it means 2nd `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_ are not sutisfied => raise `AttributeError`\n if exitcode not in success_exitcodes:\n raise OSE... | class DaemonShellOperator(BaseShellOperator):
"""Instantiate process and keep it running.
`DaemonShellOperator` can instantiate processes which satisfy the following constraints:
1. Inputs records from `stdin`
2. Safely dies when `EOF` is input
3. Outputs deterministic string when inputting a spec... |
laysakura/relshell | relshell/batch_command.py | BatchCommand._parse | python | def _parse(batch_cmd):
cmd_array = shlex.split(batch_cmd)
(cmd_array, batch_to_file_s) = BatchCommand._parse_in_batches(cmd_array)
(cmd_array, batch_from_file) = BatchCommand._parse_out_batch(cmd_array)
return (list2cmdline(cmd_array), batch_to_file_s, batch_from_file) | :rtype: (sh_cmd, batch_to_file_s, batch_from_file)
:returns: parsed result like below:
.. code-block:: python
# when parsing 'diff IN_BATCH0 IN_BATCH1 > OUT_BATCH'
(
'diff /tmp/relshell-AbCDeF /tmp/relshell-uVwXyz',
( <instance of BatchToFile>,... | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L40-L57 | [
"def _parse_in_batches(cmd_array):\n \"\"\"Find patterns that match to `in_batches_pat` and replace them into `STDIN` or `TMPFILE`.\n\n :param cmd_array: `shlex.split`-ed command\n :rtype: ([cmd_array], ( batch_to_file, batch_to_file, ... ) )\n :returns: Modified `cmd_array` and tuple to show how each... | class BatchCommand(object):
"""BatchCommand"""
in_batches_pat = re.compile('IN_BATCH(\d+)')
"""Input batches"""
out_batch_pat = re.compile('OUT_BATCH')
"""Output batch"""
def __init__(self, batch_cmd):
"""Constructor
:param batch_cmd: command string w/ (IN|OUT)_BATCH*.
... |
laysakura/relshell | relshell/batch_command.py | BatchCommand._parse_in_batches | python | def _parse_in_batches(cmd_array):
res_cmd_array = cmd_array[:]
res_batch_to_file_s = []
in_batches_cmdidx = BatchCommand._in_batches_cmdidx(cmd_array)
for batch_id, cmdidx in enumerate(in_batches_cmdidx):
if cmdidx > 0 and cmd_array[cmdidx - 1] == '<': # e.g. `< IN_BA... | Find patterns that match to `in_batches_pat` and replace them into `STDIN` or `TMPFILE`.
:param cmd_array: `shlex.split`-ed command
:rtype: ([cmd_array], ( batch_to_file, batch_to_file, ... ) )
:returns: Modified `cmd_array` and tuple to show how each IN_BATCH is instantiated (TMPFILE or STDI... | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L60-L83 | null | class BatchCommand(object):
"""BatchCommand"""
in_batches_pat = re.compile('IN_BATCH(\d+)')
"""Input batches"""
out_batch_pat = re.compile('OUT_BATCH')
"""Output batch"""
def __init__(self, batch_cmd):
"""Constructor
:param batch_cmd: command string w/ (IN|OUT)_BATCH*.
... |
laysakura/relshell | relshell/batch_command.py | BatchCommand._parse_out_batch | python | def _parse_out_batch(cmd_array):
res_cmd_array = cmd_array[:]
res_batch_from_file = None
out_batch_cmdidx = BatchCommand._out_batch_cmdidx(cmd_array)
if out_batch_cmdidx is None:
return (res_cmd_array, res_batch_from_file)
if out_batch_cmdidx > 0 and cmd_array[o... | Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`.
:param cmd_array: `shlex.split`-ed command
:rtype: ([cmd_array], batch_from_file)
:returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated (TMPFILE or STDOUT).
Returned `... | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L86-L110 | null | class BatchCommand(object):
"""BatchCommand"""
in_batches_pat = re.compile('IN_BATCH(\d+)')
"""Input batches"""
out_batch_pat = re.compile('OUT_BATCH')
"""Output batch"""
def __init__(self, batch_cmd):
"""Constructor
:param batch_cmd: command string w/ (IN|OUT)_BATCH*.
... |
laysakura/relshell | relshell/batch_command.py | BatchCommand._in_batches_cmdidx | python | def _in_batches_cmdidx(cmd_array):
in_batches_cmdidx_dict = {}
for cmdidx, tok in enumerate(cmd_array):
mat = BatchCommand.in_batches_pat.match(tok)
if mat:
batch_idx = int(mat.group(1))
if batch_idx in in_batches_cmdidx_dict:
r... | Raise `IndexError` if IN_BATCH0 - IN_BATCHx is not used sequentially in `cmd_array`
:returns: (IN_BATCH0's cmdidx, IN_BATCH1's cmdidx, ...)
$ cat a.txt IN_BATCH1 IN_BATCH0 b.txt c.txt IN_BATCH2 => (3, 2, 5) | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L113-L139 | null | class BatchCommand(object):
"""BatchCommand"""
in_batches_pat = re.compile('IN_BATCH(\d+)')
"""Input batches"""
out_batch_pat = re.compile('OUT_BATCH')
"""Output batch"""
def __init__(self, batch_cmd):
"""Constructor
:param batch_cmd: command string w/ (IN|OUT)_BATCH*.
... |
laysakura/relshell | relshell/batch_command.py | BatchCommand._out_batch_cmdidx | python | def _out_batch_cmdidx(cmd_array):
out_batch_cmdidx = None
for cmdidx, tok in enumerate(cmd_array):
mat = BatchCommand.out_batch_pat.match(tok)
if mat:
if out_batch_cmdidx:
raise IndexError(
'OUT_BATCH is used multiple ti... | Raise `IndexError` if OUT_BATCH is used multiple time
:returns: OUT_BATCH cmdidx (None if OUT_BATCH is not in `cmd_array`)
$ cat a.txt > OUT_BATCH => 3 | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L142-L157 | null | class BatchCommand(object):
"""BatchCommand"""
in_batches_pat = re.compile('IN_BATCH(\d+)')
"""Input batches"""
out_batch_pat = re.compile('OUT_BATCH')
"""Output batch"""
def __init__(self, batch_cmd):
"""Constructor
:param batch_cmd: command string w/ (IN|OUT)_BATCH*.
... |
laysakura/relshell | relshell/batch.py | Batch.next | python | def next(self):
if self._records_iter >= len(self._records):
raise StopIteration
self._records_iter += 1
return self._records[self._records_iter - 1] | Return one of record in this batch in out-of-order.
:raises: `StopIteration` when no more record is in this batch | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch.py#L39-L47 | null | class Batch(object):
"""Set of records"""
def __init__(self, record_def, records, check_datatype=True):
"""Create an *immutable* batch of records
:param record_def: instance of `RecordDef <#relshell.recorddef.RecordDef>`_
:param records: records. Leftmost element is oldest (has to be tr... |
laysakura/relshell | relshell/batch.py | Batch.formatted_str | python | def formatted_str(self, format):
assert(format in ('json', 'csv'))
ret_str_list = []
for rec in self._records:
if format == 'json':
ret_str_list.append('{')
for i in xrange(len(rec)):
colname, colval = self._rdef[i].name, rec[i]
... | Return formatted str.
:param format: one of 'json', 'csv' are supported | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch.py#L52-L77 | null | class Batch(object):
"""Set of records"""
def __init__(self, record_def, records, check_datatype=True):
"""Create an *immutable* batch of records
:param record_def: instance of `RecordDef <#relshell.recorddef.RecordDef>`_
:param records: records. Leftmost element is oldest (has to be tr... |
laysakura/relshell | relshell/record.py | Record.next | python | def next(self):
if self._cur_col >= len(self._rec):
self._cur_col = 0
raise StopIteration
col = self._rec[self._cur_col]
self._cur_col += 1
return col | Return a column one by one
:raises: StopIteration | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/record.py#L42-L52 | null | class Record(object):
"""Record."""
# APIs
def __init__(self, *columns):
"""Creates a record with `record_def` constraints.
:param \*columns: contents of columns
"""
self._rec = Record._internal_repl(columns)
self._cur_col = 0 # Used for `next()`
def _... |
laysakura/relshell | relshell/record.py | Record._chk_type | python | def _chk_type(recdef, rec):
if len(recdef) != len(rec):
raise TypeError("Number of columns (%d) is different from RecordDef (%d)" % (len(rec), len(recdef)))
for i in xrange(len(recdef)):
try:
def_type = recdef[i].type
col_type = Type.equivalent_re... | Checks if type of `rec` matches `recdef`
:param recdef: instance of RecordDef
:param rec: instance of Record
:raises: `TypeError` | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/record.py#L66-L87 | [
"def equivalent_relshell_type(val):\n \"\"\"Returns `val`'s relshell compatible type.\n\n :param val: value to check relshell equivalent type\n :raises: `NotImplementedError` if val's relshell compatible type is not implemented.\n \"\"\"\n builtin_type = type(val)\n if builtin_type not in Typ... | class Record(object):
"""Record."""
# APIs
def __init__(self, *columns):
"""Creates a record with `record_def` constraints.
:param \*columns: contents of columns
"""
self._rec = Record._internal_repl(columns)
self._cur_col = 0 # Used for `next()`
def _... |
tus/tus-py-client | tusclient/uploader.py | Uploader.headers | python | def headers(self):
client_headers = getattr(self.client, 'headers', {})
return dict(self.DEFAULT_HEADERS, **client_headers) | Return headers of the uploader instance. This would include the headers of the
client instance. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L139-L145 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.headers_as_list | python | def headers_as_list(self):
headers = self.headers
headers_list = ['{}: {}'.format(key, value) for key, value in iteritems(headers)]
return headers_list | Does the same as 'headers' except it is returned as a list. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L148-L154 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_offset | python | def get_offset(self):
resp = requests.head(self.url, headers=self.headers)
offset = resp.headers.get('upload-offset')
if offset is None:
msg = 'Attempt to retrieve offset fails with status {}'.format(resp.status_code)
raise TusCommunicationError(msg, resp.status_code, res... | Return offset from tus server.
This is different from the instance attribute 'offset' because this makes an
http request to the tus server to retrieve the offset. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L170-L182 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.encode_metadata | python | def encode_metadata(self):
encoded_list = []
for key, value in iteritems(self.metadata):
key_str = str(key) # dict keys may be of any object type.
# confirm that the key does not contain unwanted characters.
if re.search(r'^$|[\s,]+', key_str):
msg =... | Return list of encoded metadata as defined by the Tus protocol. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L184-L199 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_url | python | def get_url(self):
if self.store_url and self.url_storage:
key = self.fingerprinter.get_fingerprint(self.get_file_stream())
url = self.url_storage.get_item(key)
if not url:
url = self.create_url()
self.url_storage.set_item(key, url)
... | Return the tus upload url.
If resumability is enabled, this would try to get the url from storage if available,
otherwise it would request a new upload url from the tus server. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L201-L216 | [
"def get_file_stream(self):\n \"\"\"\n Return a file stream instance of the upload.\n \"\"\"\n if self.file_stream:\n self.file_stream.seek(0)\n return self.file_stream\n elif os.path.isfile(self.file_path):\n return open(self.file_path, 'rb')\n else:\n raise ValueError... | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.create_url | python | def create_url(self):
headers = self.headers
headers['upload-length'] = str(self.file_size)
headers['upload-metadata'] = ','.join(self.encode_metadata())
resp = requests.post(self.client.url, headers=headers)
url = resp.headers.get("location")
if url is None:
... | Return upload url.
Makes request to tus server to create a new upload url for the required file upload. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L219-L233 | [
"def encode_metadata(self):\n \"\"\"\n Return list of encoded metadata as defined by the Tus protocol.\n \"\"\"\n encoded_list = []\n for key, value in iteritems(self.metadata):\n key_str = str(key) # dict keys may be of any object type.\n\n # confirm that the key does not contain unwa... | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.request_length | python | def request_length(self):
remainder = self.stop_at - self.offset
return self.chunk_size if remainder > self.chunk_size else remainder | Return length of next chunk upload. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L236-L241 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.verify_upload | python | def verify_upload(self):
if self.request.status_code == 204:
return True
else:
raise TusUploadFailed('', self.request.status_code, self.request.response_content) | Confirm that the last upload was sucessful.
Raises TusUploadFailed exception if the upload was not sucessful. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L243-L251 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.get_file_stream | python | def get_file_stream(self):
if self.file_stream:
self.file_stream.seek(0)
return self.file_stream
elif os.path.isfile(self.file_path):
return open(self.file_path, 'rb')
else:
raise ValueError("invalid file {}".format(self.file_path)) | Return a file stream instance of the upload. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L253-L263 | null | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.file_size | python | def file_size(self):
stream = self.get_file_stream()
stream.seek(0, os.SEEK_END)
return stream.tell() | Return size of the file. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L266-L272 | [
"def get_file_stream(self):\n \"\"\"\n Return a file stream instance of the upload.\n \"\"\"\n if self.file_stream:\n self.file_stream.seek(0)\n return self.file_stream\n elif os.path.isfile(self.file_path):\n return open(self.file_path, 'rb')\n else:\n raise ValueError... | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.upload | python | def upload(self, stop_at=None):
self.stop_at = stop_at or self.file_size
while self.offset < self.stop_at:
self.upload_chunk()
else:
if self.log_func:
self.log_func("maximum upload specified({} bytes) has been reached".format(self.stop_at)) | Perform file upload.
Performs continous upload of chunks of the file. The size uploaded at each cycle is
the value of the attribute 'chunk_size'.
:Args:
- stop_at (Optional[int]):
Determines at what offset value the upload should stop. If not specified this
... | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L274-L292 | [
"def upload_chunk(self):\n \"\"\"\n Upload chunk of file.\n \"\"\"\n self._retried = 0\n self._do_request()\n self.offset = int(self.request.response_headers.get('upload-offset'))\n if self.log_func:\n msg = '{} bytes uploaded ...'.format(self.offset)\n self.log_func(msg)\n"
] | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/uploader.py | Uploader.upload_chunk | python | def upload_chunk(self):
self._retried = 0
self._do_request()
self.offset = int(self.request.response_headers.get('upload-offset'))
if self.log_func:
msg = '{} bytes uploaded ...'.format(self.offset)
self.log_func(msg) | Upload chunk of file. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/uploader.py#L294-L303 | [
"def _do_request(self):\n # TODO: Maybe the request should not be re-created everytime.\n # The request handle could be left open until upload is done instead.\n self.request = TusRequest(self)\n try:\n self.request.perform()\n self.verify_upload()\n except TusUploadFailed as error... | class Uploader(object):
"""
Object to control upload related functions.
:Attributes:
- file_path (str):
This is the path(absolute/relative) to the file that is intended for upload
to the tus server. On instantiation this attribute is required.
- file_stream (file):
... |
tus/tus-py-client | tusclient/storage/filestorage.py | FileStorage.get_item | python | def get_item(self, key):
result = self._db.search(self._urls.key == key)
return result[0].get('url') if result else None | Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this case, url)
:Returns: url[str] | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L14-L23 | null | class FileStorage(interface.Storage):
def __init__(self, fp):
self._db = TinyDB(fp)
self._urls = Query()
def set_item(self, key, url):
"""
Store the url value under the unique key.
:Args:
- key[str]: The unique id to which the item (in this case, url) would... |
tus/tus-py-client | tusclient/storage/filestorage.py | FileStorage.set_item | python | def set_item(self, key, url):
if self._db.search(self._urls.key == key):
self._db.update({'url': url}, self._urls.key == key)
else:
self._db.insert({'key': key, 'url': url}) | Store the url value under the unique key.
:Args:
- key[str]: The unique id to which the item (in this case, url) would be stored.
- value[str]: The actual url value to be stored. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L25-L36 | null | class FileStorage(interface.Storage):
def __init__(self, fp):
self._db = TinyDB(fp)
self._urls = Query()
def get_item(self, key):
"""
Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this... |
tus/tus-py-client | tusclient/storage/filestorage.py | FileStorage.remove_item | python | def remove_item(self, key):
self._db.remove(self._urls.key==key) | Remove/Delete the url value under the unique key from storage. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/storage/filestorage.py#L38-L42 | null | class FileStorage(interface.Storage):
def __init__(self, fp):
self._db = TinyDB(fp)
self._urls = Query()
def get_item(self, key):
"""
Return the tus url of a file, identified by the key specified.
:Args:
- key[str]: The unique id for the stored item (in this... |
tus/tus-py-client | tusclient/request.py | TusRequest.perform | python | def perform(self):
try:
host = '{}://{}'.format(self._url.scheme, self._url.netloc)
path = self._url.geturl().replace(host, '', 1)
chunk = self.file.read(self._content_length)
if self._upload_checksum:
self._request_headers["upload-checksum"] = \
... | Perform actual request. | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/request.py#L56-L84 | null | class TusRequest(object):
"""
Http Request Abstraction.
Sets up tus custom http request on instantiation.
requires argument 'uploader' an instance of tusclient.uploader.Uploader
on instantiation.
:Attributes:
- handle (<http.client.HTTPConnection>)
- response_headers (dict)
... |
tus/tus-py-client | tusclient/fingerprint/fingerprint.py | Fingerprint.get_fingerprint | python | def get_fingerprint(self, fs):
hasher = hashlib.md5()
# we encode the content to avoid python 3 uncicode errors
buf = self._encode_data(fs.read(self.BLOCK_SIZE))
while len(buf) > 0:
hasher.update(buf)
buf = fs.read(self.BLOCK_SIZE)
return 'md5:' + hasher.h... | Return a unique fingerprint string value based on the file stream recevied
:Args:
- fs[file]: The file stream instance of the file for which a fingerprint would be generated.
:Returns: fingerprint[str] | train | https://github.com/tus/tus-py-client/blob/0e5856efcfae6fc281171359ce38488a70468993/tusclient/fingerprint/fingerprint.py#L15-L29 | [
"def _encode_data(self, data):\n try:\n return b(data)\n except AttributeError:\n # in case the content is already binary, this failure would happen.\n return data\n"
] | class Fingerprint(interface.Fingerprint):
BLOCK_SIZE = 65536
def _encode_data(self, data):
try:
return b(data)
except AttributeError:
# in case the content is already binary, this failure would happen.
return data
|
crate/crash | src/crate/crash/tabulate.py | _padleft | python | def _padleft(width, s, has_invisible=True):
def impl(val):
iwidth = width + len(val) - len(_strip_invisible(val)) if has_invisible else width
fmt = "{0:>%ds}" % iwidth
return fmt.format(val)
num_lines = s.splitlines()
return len(num_lines) > 1 and '\n'.join(map(impl, num_lines)) or... | Flush right.
>>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430'
True | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L392-L406 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/tabulate.py | _visible_width | python | def _visible_width(s):
if isinstance(s, _text_type) or isinstance(s, _binary_type):
return _max_line_width(_strip_invisible(s))
else:
return _max_line_width(_text_type(s)) | Visible width of a printed string. ANSI color codes are removed.
>>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
(5, 5) | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L468-L478 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/tabulate.py | _column_type | python | def _column_type(values, has_invisible=True):
return reduce(_more_generic, [type(v) for v in values], int) | The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
T... | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L582-L602 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/tabulate.py | _normalize_tabular_data | python | def _normalize_tabular_data(tabular_data, headers):
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
# dict-like and pandas.DataFrame?
if hasattr(tabular_data.values, "__call__"):
# likely a conventional dict
keys = tabular_data.keys()
rows =... | Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* list of dicts (usually used with headers="keys")
* list of OrderedDicts (usually ... | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L659-L767 | null | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/tabulate.py | tabulate | python | def tabulate(tabular_data, headers=(), tablefmt="simple",
floatfmt="g", numalign="decimal", stralign="left",
missingval=""):
if tabular_data is None:
tabular_data = []
list_of_lists, headers = _normalize_tabular_data(tabular_data, headers)
# optimization: look for ANSI... | Format a fixed width table for pretty printing.
>>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]]))
--- ---------
1 2.34
-56 8.999
2 10001
--- ---------
The first required argument (`tabular_data`) can be a
list-of-lists (or another iterable of iterables),... | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L770-L1055 | [
"def _is_multiline(s):\n if isinstance(s, _text_type):\n return bool(re.search(_multiline_codes, s))\n else: # a bytestring\n return bool(re.search(_multiline_codes_bytes, s))\n",
"def _choose_width_fn(has_invisible, enable_widechars, is_multiline):\n \"\"\"Return a function to calculate v... | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/tabulate.py | _format_table | python | def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline):
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + 2 * pad) for w in colwidths]
if is_multiline:
pad_row = lam... | Produce a plain-text representation of the table. | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L1118-L1158 | [
"def _pad_row(cells, padding):\n if cells:\n pad = \" \" * padding\n padded_cells = [pad + cell + pad for cell in cells]\n return padded_cells\n else:\n return cells\n",
"def _append_basic_row(lines, padded_cells, colwidths, colaligns, rowfmt):\n lines.append(_build_row(padded... | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2014 Sergey Astanin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy,... |
crate/crash | src/crate/crash/layout.py | create_layout | python | def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
# Create processors list.
input_processors = ... | Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| ... | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/layout.py#L39-L157 | null | # vim: set fileencodings=utf-8
# -*- coding: utf-8; -*-
# PYTHON_ARGCOMPLETE_OK
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to y... |
crate/crash | src/crate/crash/command.py | parse_config_path | python | def parse_config_path(args=sys.argv):
config = CONFIG_PATH
if '--config' in args:
idx = args.index('--config')
if len(args) > idx + 1:
config = args.pop(idx + 1)
args.pop(idx)
return config | Preprocess sys.argv and extract --config argument. | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L85-L96 | null | # vim: set fileencodings=utf-8
# -*- coding: utf-8; -*-
# PYTHON_ARGCOMPLETE_OK
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to y... |
crate/crash | src/crate/crash/command.py | get_parser | python | def get_parser(output_formats=[], conf=None):
def _conf_or_default(key, value):
return value if conf is None else conf.get_or_set(key, value)
parser = ArgumentParser(description='crate shell')
parser.add_argument('-v', '--verbose', action='count',
dest='verbose', default=_c... | Create an argument parser that reads default values from a
configuration file if provided. | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L121-L178 | [
"def _conf_or_default(key, value):\n return value if conf is None else conf.get_or_set(key, value)\n"
] | # vim: set fileencodings=utf-8
# -*- coding: utf-8; -*-
# PYTHON_ARGCOMPLETE_OK
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to y... |
crate/crash | src/crate/crash/command.py | _parse_statements | python | def _parse_statements(lines):
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield '\n'.join(parts)
parts[:] = []
if parts:
... | Return a generator of statements
Args: A list of strings that can contain one or more statements.
Statements are separated using ';' at the end of a line
Everything after the last ';' will be treated as the last statement.
>>> list(_parse_statements(['select * from ', 't1;', 'select name']... | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L191-L213 | null | # vim: set fileencodings=utf-8
# -*- coding: utf-8; -*-
# PYTHON_ARGCOMPLETE_OK
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to y... |
crate/crash | src/crate/crash/command.py | host_and_port | python | def host_and_port(host_or_port):
if ':' in host_or_port:
if len(host_or_port) == 1:
return 'localhost:4200'
elif host_or_port.startswith(':'):
return 'localhost' + host_or_port
return host_or_port
return host_or_port + ':4200' | Return full hostname/IP + port, possible input formats are:
* host:port -> host:port
* : -> localhost:4200
* :port -> localhost:port
* host -> host:4200 | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L519-L533 | null | # vim: set fileencodings=utf-8
# -*- coding: utf-8; -*-
# PYTHON_ARGCOMPLETE_OK
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to y... |
crate/crash | src/crate/crash/command.py | CrateShell._show_tables | python | def _show_tables(self, *args):
v = self.connection.lowest_server_version
schema_name = \
"table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name"
table_filter = \
" AND table_type = 'BASE TABLE'" if v >= TABLE_TYPE_MIN_VERSION else ""
self._exec("SELECT... | print the existing tables within the 'doc' schema | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L321-L333 | null | class CrateShell:
def __init__(self,
crate_hosts=['localhost:4200'],
output_writer=None,
error_trace=False,
is_tty=True,
autocomplete=True,
autocapitalize=True,
verify_ssl=True,
c... |
crate/crash | src/crate/crash/command.py | CrateShell._quit | python | def _quit(self, *args):
self.logger.warn('Bye!')
sys.exit(self.exit()) | quit crash | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L336-L339 | null | class CrateShell:
def __init__(self,
crate_hosts=['localhost:4200'],
output_writer=None,
error_trace=False,
is_tty=True,
autocomplete=True,
autocapitalize=True,
verify_ssl=True,
c... |
crate/crash | src/crate/crash/command.py | CrateShell._connect | python | def _connect(self, servers):
self._do_connect(servers.split(' '))
self._verify_connection(verbose=True) | connect to the given server, e.g.: \\connect localhost:4200 | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L362-L365 | null | class CrateShell:
def __init__(self,
crate_hosts=['localhost:4200'],
output_writer=None,
error_trace=False,
is_tty=True,
autocomplete=True,
autocapitalize=True,
verify_ssl=True,
c... |
crate/crash | src/crate/crash/sysinfo.py | SysInfoCommand.execute | python | def execute(self):
if not self.cmd.is_conn_available():
return
if self.cmd.connection.lowest_server_version >= SYSINFO_MIN_VERSION:
success, rows = self._sys_info()
self.cmd.exit_code = self.cmd.exit_code or int(not success)
if success:
for... | print system and cluster info | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/sysinfo.py#L72-L87 | null | class SysInfoCommand(object):
CLUSTER_INFO = {
'shards_query': """
select count(*) as number_of_shards, cast(sum(num_docs) as long) as number_of_records
from sys.shards
where "primary" = true
""",
'nodes_query': """
select count(*) as number_of_nodes
from sys.nodes
""",
}
N... |
crate/crash | src/crate/crash/config.py | Configuration.bwc_bool_transform_from | python | def bwc_bool_transform_from(cls, x):
if x.lower() == 'true':
return True
elif x.lower() == 'false':
return False
return bool(int(x)) | Read boolean values from old config files correctly
and interpret 'True' and 'False' as correct booleans. | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/config.py#L44-L53 | null | class Configuration(object):
"""
Model that reads default values for the CLI argument parser
from a configuration file.
"""
@classmethod
def __init__(self, path):
self.type_mapping = {
str: partial(self._get_or_set,
transform_from=lambda x: str(x),... |
crate/crash | src/crate/crash/outputs.py | _transform_field | python | def _transform_field(field):
if isinstance(field, bool):
return TRUE if field else FALSE
elif isinstance(field, (list, dict)):
return json.dumps(field, sort_keys=True, ensure_ascii=False)
else:
return field | transform field for displaying | train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/outputs.py#L42-L49 | null | import csv
import json
import sys
from pygments import highlight
from pygments.lexers.data import JsonLexer
from pygments.formatters import TerminalFormatter
from colorama import Fore, Style
from .tabulate import TableFormat, Line as TabulateLine, DataRow, tabulate, float_format
if sys.version_info[:2] == (2, 6):
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/application_policy.py | ApplicationPolicy.validate | python | def validate(self):
if not self.principals:
raise InvalidApplicationPolicyError(error_message='principals not provided')
if not self.actions:
raise InvalidApplicationPolicyError(error_message='actions not provided')
if any(not self._PRINCIPAL_PATTERN.match(p) for p in s... | Check if the formats of principals and actions are valid.
:return: True, if the policy is valid
:raises: InvalidApplicationPolicyError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_policy.py#L44-L66 | null | class ApplicationPolicy(object):
"""Class representing SAR application policy."""
# Supported actions for setting SAR application permissions
GET_APPLICATION = 'GetApplication'
LIST_APPLICATION_DEPENDENCIES = 'ListApplicationDependencies'
CREATE_CLOUD_FORMATION_CHANGE_SET = 'CreateCloudFormationCha... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | publish_application | python | def publish_application(template, sar_client=None):
if not template:
raise ValueError('Require SAM template to publish the application')
if not sar_client:
sar_client = boto3.client('serverlessrepo')
template_dict = _get_template_dict(template)
app_metadata = get_app_metadata(template_... | Create a new application or new application version in SAR.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:param sar_client: The boto3 client used to access SAR
:type sar_client: boto3.client
:return: Dictionary containing application id, actions taken... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L21-L76 | [
"def yaml_dump(dict_to_dump):\n \"\"\"\n Dump the dictionary as a YAML document.\n\n :param dict_to_dump: Data to be serialized as YAML\n :type dict_to_dump: dict\n :return: YAML document\n :rtype: str\n \"\"\"\n yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)\n return yam... | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | update_application_metadata | python | def update_application_metadata(template, application_id, sar_client=None):
if not template or not application_id:
raise ValueError('Require SAM template and application ID to update application metadata')
if not sar_client:
sar_client = boto3.client('serverlessrepo')
template_dict = _get_... | Update the application metadata.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param sar_client: The boto3 client used to access SAR
:type sar_clien... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L79-L100 | [
"def get_app_metadata(template_dict):\n \"\"\"\n Get the application metadata from a SAM template.\n\n :param template_dict: SAM template as a dictionary\n :type template_dict: dict\n :return: Application metadata as defined in the template\n :rtype: ApplicationMetadata\n :raises ApplicationMet... | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _get_template_dict | python | def _get_template_dict(template):
if isinstance(template, str):
return parse_template(template)
if isinstance(template, dict):
return copy.deepcopy(template)
raise ValueError('Input template should be a string or dictionary') | Parse string template and or copy dictionary template.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:return: Template as a dictionary
:rtype: dict
:raises ValueError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L103-L119 | [
"def parse_template(template_str):\n \"\"\"\n Parse the SAM template.\n\n :param template_str: A packaged YAML or json CloudFormation template\n :type template_str: str\n :return: Dictionary with keys defined in the template\n :rtype: dict\n \"\"\"\n try:\n # PyYAML doesn't support js... | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _create_application_request | python | def _create_application_request(app_metadata, template):
app_metadata.validate(['author', 'description', 'name'])
request = {
'Author': app_metadata.author,
'Description': app_metadata.description,
'HomePageUrl': app_metadata.home_page_url,
'Labels': app_metadata.labels,
... | Construct the request body to create application.
:param app_metadata: Object containing app metadata
:type app_metadata: ApplicationMetadata
:param template: A packaged YAML or JSON SAM template
:type template: str
:return: SAR CreateApplication request body
:rtype: dict | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L122-L148 | null | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _update_application_request | python | def _update_application_request(app_metadata, application_id):
request = {
'ApplicationId': application_id,
'Author': app_metadata.author,
'Description': app_metadata.description,
'HomePageUrl': app_metadata.home_page_url,
'Labels': app_metadata.labels,
'ReadmeUrl': a... | Construct the request body to update application.
:param app_metadata: Object containing app metadata
:type app_metadata: ApplicationMetadata
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:return: SAR UpdateApplication request body
:rtype: di... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L151-L170 | null | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _create_application_version_request | python | def _create_application_version_request(app_metadata, application_id, template):
app_metadata.validate(['semantic_version'])
request = {
'ApplicationId': application_id,
'SemanticVersion': app_metadata.semantic_version,
'SourceCodeUrl': app_metadata.source_code_url,
'TemplateBody... | Construct the request body to create application version.
:param app_metadata: Object containing app metadata
:type app_metadata: ApplicationMetadata
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param template: A packaged YAML or JSON SAM templ... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L173-L193 | null | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _wrap_client_error | python | def _wrap_client_error(e):
error_code = e.response['Error']['Code']
message = e.response['Error']['Message']
if error_code == 'BadRequestException':
if "Failed to copy S3 object. Access denied:" in message:
match = re.search('bucket=(.+?), key=(.+?)$', message)
if match:
... | Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L208-L227 | null | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/publish.py | _get_publish_details | python | def _get_publish_details(actions, app_metadata_template):
if actions == [CREATE_APPLICATION]:
return {k: v for k, v in app_metadata_template.items() if v}
include_keys = [
ApplicationMetadata.AUTHOR,
ApplicationMetadata.DESCRIPTION,
ApplicationMetadata.HOME_PAGE_URL,
App... | Get the changed application details after publishing.
:param actions: Actions taken during publishing
:type actions: list of str
:param app_metadata_template: Original template definitions of app metadata
:type app_metadata_template: dict
:return: Updated fields and values of the application
:r... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/publish.py#L230-L256 | null | """Module containing functions to publish or update application."""
import re
import copy
import boto3
from botocore.exceptions import ClientError
from .application_metadata import ApplicationMetadata
from .parser import (
yaml_dump, parse_template, get_app_metadata,
parse_application_id, strip_app_metadata
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/application_metadata.py | ApplicationMetadata.validate | python | def validate(self, required_props):
missing_props = [p for p in required_props if not getattr(self, p)]
if missing_props:
missing_props_str = ', '.join(sorted(missing_props))
raise InvalidApplicationMetadataError(properties=missing_props_str)
return True | Check if the required application metadata properties have been populated.
:param required_props: List of required properties
:type required_props: list
:return: True, if the metadata is valid
:raises: InvalidApplicationMetadataError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/application_metadata.py#L44-L57 | null | class ApplicationMetadata(object):
"""Class representing SAR metadata."""
# SAM template SAR metadata properties
NAME = 'Name'
DESCRIPTION = 'Description'
AUTHOR = 'Author'
SPDX_LICENSE_ID = 'SpdxLicenseId'
LICENSE_URL = 'LicenseUrl'
README_URL = 'ReadmeUrl'
LABELS = 'Labels'
HO... |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | yaml_dump | python | def yaml_dump(dict_to_dump):
yaml.SafeDumper.add_representer(OrderedDict, _dict_representer)
return yaml.safe_dump(dict_to_dump, default_flow_style=False) | Dump the dictionary as a YAML document.
:param dict_to_dump: Data to be serialized as YAML
:type dict_to_dump: dict
:return: YAML document
:rtype: str | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L61-L71 | null | """Helper to parse JSON/YAML SAM template and dump YAML files."""
import re
import copy
import json
from collections import OrderedDict
import six
import yaml
from yaml.resolver import ScalarNode, SequenceNode
from .application_metadata import ApplicationMetadata
from .exceptions import ApplicationMetadataNotFoundEr... |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | parse_template | python | def parse_template(template_str):
try:
# PyYAML doesn't support json as well as it should, so if the input
# is actually just json it is better to parse it with the standard
# json parser.
return json.loads(template_str, object_pairs_hook=OrderedDict)
except ValueError:
y... | Parse the SAM template.
:param template_str: A packaged YAML or json CloudFormation template
:type template_str: str
:return: Dictionary with keys defined in the template
:rtype: dict | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L78-L95 | null | """Helper to parse JSON/YAML SAM template and dump YAML files."""
import re
import copy
import json
from collections import OrderedDict
import six
import yaml
from yaml.resolver import ScalarNode, SequenceNode
from .application_metadata import ApplicationMetadata
from .exceptions import ApplicationMetadataNotFoundEr... |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | get_app_metadata | python | def get_app_metadata(template_dict):
if SERVERLESS_REPO_APPLICATION in template_dict.get(METADATA, {}):
app_metadata_dict = template_dict.get(METADATA).get(SERVERLESS_REPO_APPLICATION)
return ApplicationMetadata(app_metadata_dict)
raise ApplicationMetadataNotFoundError(
error_message='m... | Get the application metadata from a SAM template.
:param template_dict: SAM template as a dictionary
:type template_dict: dict
:return: Application metadata as defined in the template
:rtype: ApplicationMetadata
:raises ApplicationMetadataNotFoundError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L98-L113 | null | """Helper to parse JSON/YAML SAM template and dump YAML files."""
import re
import copy
import json
from collections import OrderedDict
import six
import yaml
from yaml.resolver import ScalarNode, SequenceNode
from .application_metadata import ApplicationMetadata
from .exceptions import ApplicationMetadataNotFoundEr... |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | parse_application_id | python | def parse_application_id(text):
result = re.search(APPLICATION_ID_PATTERN, text)
return result.group(0) if result else None | Extract the application id from input text.
:param text: text to parse
:type text: str
:return: application id if found in the input
:rtype: str | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L116-L126 | null | """Helper to parse JSON/YAML SAM template and dump YAML files."""
import re
import copy
import json
from collections import OrderedDict
import six
import yaml
from yaml.resolver import ScalarNode, SequenceNode
from .application_metadata import ApplicationMetadata
from .exceptions import ApplicationMetadataNotFoundEr... |
awslabs/aws-serverlessrepo-python | serverlessrepo/parser.py | strip_app_metadata | python | def strip_app_metadata(template_dict):
if SERVERLESS_REPO_APPLICATION not in template_dict.get(METADATA, {}):
return template_dict
template_dict_copy = copy.deepcopy(template_dict)
# strip the whole metadata section if SERVERLESS_REPO_APPLICATION is the only key in it
if not [k for k in templa... | Strip the "AWS::ServerlessRepo::Application" metadata section from template.
:param template_dict: SAM template as a dictionary
:type template_dict: dict
:return: stripped template content
:rtype: str | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/parser.py#L129-L149 | null | """Helper to parse JSON/YAML SAM template and dump YAML files."""
import re
import copy
import json
from collections import OrderedDict
import six
import yaml
from yaml.resolver import ScalarNode, SequenceNode
from .application_metadata import ApplicationMetadata
from .exceptions import ApplicationMetadataNotFoundEr... |
awslabs/aws-serverlessrepo-python | serverlessrepo/permission_helper.py | make_application_private | python | def make_application_private(application_id, sar_client=None):
if not application_id:
raise ValueError('Require application id to make the app private')
if not sar_client:
sar_client = boto3.client('serverlessrepo')
sar_client.put_application_policy(
ApplicationId=application_id,
... | Set the application to be private.
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param sar_client: The boto3 client used to access SAR
:type sar_client: boto3.client
:raises ValueError | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L32-L51 | null | """Module containing methods to manage application permissions."""
import boto3
from .application_policy import ApplicationPolicy
def make_application_public(application_id, sar_client=None):
"""
Set the application to be public.
:param application_id: The Amazon Resource Name (ARN) of the application
... |
awslabs/aws-serverlessrepo-python | serverlessrepo/permission_helper.py | share_application_with_accounts | python | def share_application_with_accounts(application_id, account_ids, sar_client=None):
if not application_id or not account_ids:
raise ValueError('Require application id and list of AWS account IDs to share the app')
if not sar_client:
sar_client = boto3.client('serverlessrepo')
application_po... | Share the application privately with given AWS account IDs.
:param application_id: The Amazon Resource Name (ARN) of the application
:type application_id: str
:param account_ids: List of AWS account IDs, or *
:type account_ids: list of str
:param sar_client: The boto3 client used to access SAR
... | train | https://github.com/awslabs/aws-serverlessrepo-python/blob/e2126cee0191266cfb8a3a2bc3270bf50330907c/serverlessrepo/permission_helper.py#L54-L77 | [
"def validate(self):\n \"\"\"\n Check if the formats of principals and actions are valid.\n\n :return: True, if the policy is valid\n :raises: InvalidApplicationPolicyError\n \"\"\"\n if not self.principals:\n raise InvalidApplicationPolicyError(error_message='principals not provided')\n\n ... | """Module containing methods to manage application permissions."""
import boto3
from .application_policy import ApplicationPolicy
def make_application_public(application_id, sar_client=None):
"""
Set the application to be public.
:param application_id: The Amazon Resource Name (ARN) of the application
... |
asifpy/django-crudbuilder | crudbuilder/registry.py | CrudBuilderRegistry.extract_args | python | def extract_args(cls, *args):
model = None
crudbuilder = None
for arg in args:
if issubclass(arg, models.Model):
model = arg
else:
crudbuilder = arg
return [model, crudbuilder] | Takes any arguments like a model and crud, or just one of
those, in any order, and return a model and crud. | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L18-L32 | null | class CrudBuilderRegistry(dict):
"""Dictionary like object representing a collection of objects."""
@classmethod
def register(self, *args, **kwargs):
"""
Register a crud.
Two unordered arguments are accepted, at least one should be passed:
- a model,
- a crudbuild... |
asifpy/django-crudbuilder | crudbuilder/registry.py | CrudBuilderRegistry.register | python | def register(self, *args, **kwargs):
assert len(args) <= 2, 'register takes at most 2 args'
assert len(args) > 0, 'register takes at least 1 arg'
model, crudbuilder = self.__class__.extract_args(*args)
if not issubclass(model, models.Model):
msg = "First argument should be... | Register a crud.
Two unordered arguments are accepted, at least one should be passed:
- a model,
- a crudbuilder class | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/registry.py#L34-L61 | [
"def _model_key(self, model, crudbuilder):\n app_label = model._meta.app_label\n model_name = model.__name__.lower()\n postfix_url = helpers.custom_postfix_url(crudbuilder(), model_name)\n return '{}-{}-{}'.format(app_label, model_name, postfix_url)\n"
] | class CrudBuilderRegistry(dict):
"""Dictionary like object representing a collection of objects."""
@classmethod
def extract_args(cls, *args):
"""
Takes any arguments like a model and crud, or just one of
those, in any order, and return a model and crud.
"""
model = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.