text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Remove leading and trailing white spaces in columns names
<END_TASK>
<USER_TASK:>
Description:
def strip_cols(self):
"""
Remove leading and trailing white spaces in columns names
:example: ``ds.strip_cols()``
""" |
cols = {}
skipped = []
for col in self.df.columns.values:
try:
cols[col] = col.strip()
except Exception:
skipped.append(str(col))
self.df = self.df.rename(columns=cols)
self.ok("White spaces removed in columns names")
if len(skipped) > 0:
self.info("Skipped columns", ','.join(
skipped), "while removing white spaces") |
<SYSTEM_TASK:>
Round floats in a column. Numbers are going to be
<END_TASK>
<USER_TASK:>
Description:
def roundvals(self, col: str, precision: int=2):
"""
Round floats in a column. Numbers are going to be
converted to floats if they are not already
:param col: column name
:type col: str
:param precision: float precision, defaults to 2
:param precision: int, optional
:example: ``ds.roundvals("mycol")``
""" |
try:
self.df[col] = self.df[col].astype("float64")
self.df[col] = self.df[col].apply(lambda x: round(x, precision))
except Exception as e:
self.err(e, "Can not round column values")
return
self.ok("Rounded values in column " + col) |
<SYSTEM_TASK:>
Replace a value in a column in the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def replace(self, col: str, searchval: str, replaceval: str):
"""
Replace a value in a column in the main dataframe
:param col: column name
:type col: str
:param searchval: value to replace
:type searchval: str
:param replaceval: new value
:type replaceval: str
:example: ``ds.replace("mycol", "value", "new_value")``
""" |
try:
self.df[col] = self.df[col].replace(searchval, replaceval)
except Exception as e:
self.err(e, "Can not replace value in column") |
<SYSTEM_TASK:>
Set the default language for all objects returned with this
<END_TASK>
<USER_TASK:>
Description:
def for_language(self, language_code):
"""
Set the default language for all objects returned with this
query.
""" |
clone = self._clone()
clone._default_language = language_code
return clone |
<SYSTEM_TASK:>
Add the default language information to all returned objects.
<END_TASK>
<USER_TASK:>
Description:
def iterator(self):
"""
Add the default language information to all returned objects.
""" |
default_language = getattr(self, '_default_language', None)
for obj in super(MultilingualModelQuerySet, self).iterator():
obj._default_language = default_language
yield obj |
<SYSTEM_TASK:>
Override _clone to preserve additional information needed by
<END_TASK>
<USER_TASK:>
Description:
def _clone(self, klass=None, **kwargs):
"""
Override _clone to preserve additional information needed by
MultilingualModelQuerySet.
""" |
clone = super(MultilingualModelQuerySet, self)._clone(klass, **kwargs)
clone._default_language = getattr(self, '_default_language', None)
return clone |
<SYSTEM_TASK:>
Limit selection to a range in the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def limit(self, r=5):
"""
Limit selection to a range in the main dataframe
""" |
try:
self.df = self.df[:r]
except Exception as e:
self.err(e, "Can not limit data") |
<SYSTEM_TASK:>
Returns a DataSwim instance with rows in a date range
<END_TASK>
<USER_TASK:>
Description:
def daterange_(self, datecol, date_start, op, **args):
"""
Returns a DataSwim instance with rows in a date range
""" |
df = self._daterange(datecol, date_start, op, **args)
if df is None:
self.err("Can not select date range data")
return self._duplicate_(df) |
<SYSTEM_TASK:>
Builds the preauth string and hmac it, following the zimbra spec.
<END_TASK>
<USER_TASK:>
Description:
def build_preauth_str(preauth_key, account_name, timestamp, expires,
admin=False):
""" Builds the preauth string and hmac it, following the zimbra spec.
Spec and examples are here http://wiki.zimbra.com/wiki/Preauth
""" |
if admin:
s = '{0}|1|name|{1}|{2}'.format(account_name, expires, timestamp)
else:
s = '{0}|name|{1}|{2}'.format(account_name, expires, timestamp)
return hmac.new(preauth_key.encode('utf-8'), s.encode('utf-8'),
hashlib.sha1).hexdigest() |
<SYSTEM_TASK:>
Get a XML response and tries to convert it to Python base object
<END_TASK>
<USER_TASK:>
Description:
def auto_type(s):
""" Get a XML response and tries to convert it to Python base object
""" |
if isinstance(s, bool):
return s
elif s is None:
return ''
elif s == 'TRUE':
return True
elif s == 'FALSE':
return False
else:
try:
try:
# telephone numbers may be wrongly interpretted as ints
if s.startswith('+'):
return s
else:
return int(s)
except ValueError:
return float(s)
except ValueError:
return s |
<SYSTEM_TASK:>
Transforms an XML string it to python-zimbra dict format
<END_TASK>
<USER_TASK:>
Description:
def xml_str_to_dict(s):
""" Transforms an XML string it to python-zimbra dict format
For format, see:
https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md
:param: a string, containing XML
:returns: a dict, with python-zimbra format
""" |
xml = minidom.parseString(s)
return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild) |
<SYSTEM_TASK:>
Executes the query and yields items.
<END_TASK>
<USER_TASK:>
Description:
def _execute(self):
"""Executes the query and yields items.""" |
query = [
'gerrit', 'query',
'--current-patch-set',
str(self._filters),
'--format=JSON']
results = self.client.exec_command(' '.join(query))
stdin, stdout, stderr = results
for line in stdout:
normalized = json.loads(line)
# Do not return the last item
# since it is the summary of
# of the query
if "rowCount" in normalized:
raise StopIteration
yield normalized |
<SYSTEM_TASK:>
the function taking the parsed tag and returning
<END_TASK>
<USER_TASK:>
Description:
def do_macro(parser, token):
""" the function taking the parsed tag and returning
a DefineMacroNode object.
""" |
try:
bits = token.split_contents()
tag_name, macro_name, arguments = bits[0], bits[1], bits[2:]
except IndexError:
raise template.TemplateSyntaxError(
"'{0}' tag requires at least one argument (macro name)".format(
token.contents.split()[0]))
# use regex's to parse the arguments into arg
# and kwarg definitions
# the regex for identifying python variable names is:
# r'^[A-Za-z_][\w_]*$'
# args must be proper python variable names
# we'll want to capture it from the regex also.
arg_regex = r'^([A-Za-z_][\w_]*)$'
# kwargs must be proper variable names with a
# default value, name="value", or name=value if
# value is a template variable (potentially with
# filters).
# we'll want to capture the name and value from
# the regex as well.
kwarg_regex = (
r'^([A-Za-z_][\w_]*)=(".*"|{0}.*{0}|[A-Za-z_][\w_]*)$'.format("'"))
# leave further validation to the template variable class
args = []
kwargs = {}
for argument in arguments:
arg_match = regex_match(
arg_regex, argument)
if arg_match:
args.append(arg_match.groups()[0])
else:
kwarg_match = regex_match(
kwarg_regex, argument)
if kwarg_match:
kwargs[kwarg_match.groups()[0]] = template.Variable(
# convert to a template variable here
kwarg_match.groups()[1])
else:
raise template.TemplateSyntaxError(
"Malformed arguments to the {0} tag.".format(
tag_name))
# parse to the endmacro tag and get the contents
nodelist = parser.parse(('endmacro',))
parser.delete_first_token()
# store macro in parser._macros, creating attribute
# if necessary
_setup_macros_dict(parser)
parser._macros[macro_name] = DefineMacroNode(
macro_name, nodelist, args, kwargs)
return parser._macros[macro_name] |
<SYSTEM_TASK:>
The function taking a parsed tag and returning
<END_TASK>
<USER_TASK:>
Description:
def do_loadmacros(parser, token):
""" The function taking a parsed tag and returning
a LoadMacrosNode object, while also loading the macros
into the page.
""" |
try:
tag_name, filename = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
"'{0}' tag requires exactly one argument (filename)".format(
token.contents.split()[0]))
if filename[0] in ('"', "'") and filename[-1] == filename[0]:
filename = filename[1:-1]
else:
raise template.TemplateSyntaxError(
"Malformed argument to the {0} template tag."
" Argument must be in quotes.".format(tag_name)
)
t = get_template(filename)
try:
# Works for Django 1.8
nodelist = t.template.nodelist
except AttributeError:
# Works for Django < 1.8
nodelist = t.nodelist
macros = nodelist.get_nodes_by_type(DefineMacroNode)
# make sure the _macros attribute dictionary is instantiated
# on the parser, then add the macros to it.
_setup_macros_dict(parser)
for macro in macros:
parser._macros[macro.name] = macro
# pass macros to LoadMacrosNode so that it can
# resolve the macros template variable kwargs on render
return LoadMacrosNode(macros) |
<SYSTEM_TASK:>
Common parsing logic for both use_macro and macro_block
<END_TASK>
<USER_TASK:>
Description:
def parse_macro_params(token):
"""
Common parsing logic for both use_macro and macro_block
""" |
try:
bits = token.split_contents()
tag_name, macro_name, values = bits[0], bits[1], bits[2:]
except IndexError:
raise template.TemplateSyntaxError(
"{0} tag requires at least one argument (macro name)".format(
token.contents.split()[0]))
args = []
kwargs = {}
# leaving most validation up to the template.Variable
# class, but use regex here so that validation could
# be added in future if necessary.
kwarg_regex = (
r'^([A-Za-z_][\w_]*)=(".*"|{0}.*{0}|[A-Za-z_][\w_]*)$'.format(
"'"))
arg_regex = r'^([A-Za-z_][\w_]*|".*"|{0}.*{0}|(\d+))$'.format(
"'")
for value in values:
# must check against the kwarg regex first
# because the arg regex matches everything!
kwarg_match = regex_match(
kwarg_regex, value)
if kwarg_match:
kwargs[kwarg_match.groups()[0]] = template.Variable(
# convert to a template variable here
kwarg_match.groups()[1])
else:
arg_match = regex_match(
arg_regex, value)
if arg_match:
args.append(template.Variable(arg_match.groups()[0]))
else:
raise template.TemplateSyntaxError(
"Malformed arguments to the {0} tag.".format(
tag_name))
return tag_name, macro_name, args, kwargs |
<SYSTEM_TASK:>
Used to mark a method on a ViewSet that should be routed for detail requests.
<END_TASK>
<USER_TASK:>
Description:
def detail_route(methods=None, **kwargs):
"""
Used to mark a method on a ViewSet that should be routed for detail requests.
Usage::
class UserViewSet(ModelCRUDViewSet):
model = User
schema = UserSchema
@detail_route(methods=['post'], url_path='lock-user')
def lock_user(request, id):
...
:param methods: An iterable of strings representing the HTTP (GET, POST, etc.) methods accepted by the route.
:param url_path: Replaces the route automatically generated by the ViewSetRouter for the decorated method
with the value provided.
""" |
methods = ['get'] if (methods is None) else methods
def decorator(func):
func.bind_to_methods = methods
func.detail = True
func.kwargs = kwargs
return func
return decorator |
<SYSTEM_TASK:>
Used to mark a method on a ViewSet that should be routed for list requests.
<END_TASK>
<USER_TASK:>
Description:
def list_route(methods=None, **kwargs):
"""
Used to mark a method on a ViewSet that should be routed for list requests.
Usage::
class UserViewSet(ModelCRUDViewSet):
model = User
schema = UserSchema
@list_route(methods=['get'], url_path='active-users')
def active_users(request, *args, **kwargs):
...
:param methods: An iterable of strings representing the HTTP (GET, POST, etc.) methods accepted by the route.
:param url_path: Replaces the route automatically generated by the ViewSetRouter for the decorated method
with the value provided.
""" |
methods = ['get'] if (methods is None) else methods
def decorator(func):
func.bind_to_methods = methods
func.detail = False
func.kwargs = kwargs
return func
return decorator |
<SYSTEM_TASK:>
Count the number of null values in a column
<END_TASK>
<USER_TASK:>
Description:
def count_nulls(self, field):
"""
Count the number of null values in a column
""" |
try:
n = self.df[field].isnull().sum()
except KeyError:
self.warning("Can not find column", field)
return
except Exception as e:
self.err(e, "Can not count nulls")
return
self.ok("Found", n, "nulls in column", field) |
<SYSTEM_TASK:>
Counts the number of rows of the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def count(self):
"""
Counts the number of rows of the main dataframe
""" |
try:
num = len(self.df.index)
except Exception as e:
self.err(e, "Can not count data")
return
self.ok("Found", num, "rows in the dataframe") |
<SYSTEM_TASK:>
Returns the number of rows of the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def count_(self):
"""
Returns the number of rows of the main dataframe
""" |
try:
num = len(self.df.index)
except Exception as e:
self.err(e, "Can not count data")
return
return num |
<SYSTEM_TASK:>
List of empty row indices
<END_TASK>
<USER_TASK:>
Description:
def count_empty(self, field):
"""
List of empty row indices
""" |
try:
df2 = self.df[[field]]
vals = where(df2.applymap(lambda x: x == ''))
num = len(vals[0])
except Exception as e:
self.err(e, "Can not count empty values")
return
self.ok("Found", num, "empty rows in column " + field) |
<SYSTEM_TASK:>
Return the number of unique values in a column
<END_TASK>
<USER_TASK:>
Description:
def count_unique_(self, field):
"""
Return the number of unique values in a column
""" |
try:
num = self.df[field].nunique()
except Exception as e:
self.err(e, "Can not count unique values")
return
self.ok("Found", num, "unique values in column", field) |
<SYSTEM_TASK:>
Search the list of customers.
<END_TASK>
<USER_TASK:>
Description:
def search_customer(self, limit=100, offset=0, email_pattern=None, last_name_pattern=None,
company_name_pattern=None, with_additional_data=False):
"""Search the list of customers.""" |
response = self.request(E.searchCustomerRequest(
E.limit(limit),
E.offset(offset),
E.emailPattern(email_pattern or ''),
E.lastNamePattern(last_name_pattern or ''),
E.companyNamePattern(company_name_pattern or ''),
E.withAdditionalData(int(with_additional_data)),
))
return response.as_models(Customer) |
<SYSTEM_TASK:>
Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
<END_TASK>
<USER_TASK:>
Description:
def import_namespaced_class(path):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class
""" |
parts = path.split('.')
return getattr(importlib.import_module('.'.join(parts[0:-1])), parts[-1]) |
<SYSTEM_TASK:>
Find all valid modules in the given folder which must be in
<END_TASK>
<USER_TASK:>
Description:
def get_modules(folder):
"""Find all valid modules in the given folder which must be in
in the same directory as this loader.py module. A valid module
has a .py extension, and is importable.
@return: all loaded valid modules
@rtype: iterator of module
""" |
if is_frozen():
# find modules in library.zip filename
zipname = os.path.dirname(os.path.dirname(__file__))
parentmodule = os.path.basename(os.path.dirname(__file__))
with zipfile.ZipFile(zipname, 'r') as f:
prefix = "%s/%s/" % (parentmodule, folder)
modnames = [os.path.splitext(n[len(prefix):])[0]
for n in f.namelist()
if n.startswith(prefix) and "__init__" not in n]
else:
dirname = os.path.join(os.path.dirname(__file__), folder)
modnames = get_importable_modules(dirname)
for modname in modnames:
try:
name ="..%s.%s" % (folder, modname)
yield importlib.import_module(name, __name__)
except ImportError as msg:
out.error("could not load module %s: %s" % (modname, msg)) |
<SYSTEM_TASK:>
Find all class objects in all modules.
<END_TASK>
<USER_TASK:>
Description:
def get_plugins(modules, classobj):
"""Find all class objects in all modules.
@param modules: the modules to search
@ptype modules: iterator of modules
@return: found classes
@rytpe: iterator of class objects
""" |
for module in modules:
for plugin in get_module_plugins(module, classobj):
yield plugin |
<SYSTEM_TASK:>
Get the html for a chart and store it
<END_TASK>
<USER_TASK:>
Description:
def stack(self, slug, chart_obj=None, title=None):
"""
Get the html for a chart and store it
""" |
if chart_obj is None:
if self.chart_obj is None:
self.err(
self.stack,
"No chart object set: please provide one in parameters")
return
chart_obj = self.chart_obj
try:
seaborn_chart = None
if self.engine == "chartjs":
html = chart_obj
elif self.engine == "seaborn":
html = ""
seaborn_chart = chart_obj
else:
html = self.get_html(chart_obj, slug)
if html is None and seaborn_chart is None:
self.err(
self.stack, "Can not stack: empty html reveived for " +
str(chart_obj), "-", slug)
return
report = dict(slug=slug, html=html)
if seaborn_chart is not None:
report["seaborn_chart"] = seaborn_chart
if self.engine not in self.report_engines:
self.report_engines.append(self.engine)
self.reports.append(report)
except Exception as e:
self.err(e, self.stack, "Can not stack report")
return
self.ok("Stacked report", slug) |
<SYSTEM_TASK:>
Prints a title for pipelines
<END_TASK>
<USER_TASK:>
Description:
def title(self, txt):
"""
Prints a title for pipelines
""" |
num = len(txt)
ticks = "=" * num
print(ticks)
print(txt)
print(ticks) |
<SYSTEM_TASK:>
Prints a subtitle for pipelines
<END_TASK>
<USER_TASK:>
Description:
def subtitle(self, txt):
"""
Prints a subtitle for pipelines
""" |
num = len(txt)
ticks = "-" * num
print(txt)
print(ticks) |
<SYSTEM_TASK:>
Return a dictionary of HTTPServer arguments using the default values
<END_TASK>
<USER_TASK:>
Description:
def http_config(self):
"""Return a dictionary of HTTPServer arguments using the default values
as specified in the HTTPServer class docstrings if no values are
specified.
:param dict config: The HTTPServer specific section of the config
:rtype: dict
""" |
return {config.NO_KEEP_ALIVE:
self.namespace.server.get(config.NO_KEEP_ALIVE, False),
config.SSL_OPTIONS: self.ssl_options,
config.XHEADERS: self.namespace.server.get(config.XHEADERS,
False)} |
<SYSTEM_TASK:>
Stop the HTTP Server and IO Loop, shutting down the process
<END_TASK>
<USER_TASK:>
Description:
def on_sigabrt(self, signal_unused, frame_unused):
"""Stop the HTTP Server and IO Loop, shutting down the process
:param int signal_unused: Unused signal number
:param frame frame_unused: Unused frame the signal was caught in
""" |
LOGGER.info('Stopping HTTP Server and IOLoop')
self.http_server.stop()
self.ioloop.stop() |
<SYSTEM_TASK:>
Reload the configuration
<END_TASK>
<USER_TASK:>
Description:
def on_sighup(self, signal_unused, frame_unused):
"""Reload the configuration
:param int signal_unused: Unused signal number
:param frame frame_unused: Unused frame the signal was caught in
""" |
# Update HTTP configuration
for setting in self.http_config:
if getattr(self.http_server, setting) != self.http_config[setting]:
LOGGER.debug('Changing HTTPServer %s setting', setting)
setattr(self.http_server, setting, self.http_config[setting])
# Update Application Settings
for setting in self.settings:
if self.app.settings[setting] != self.settings[setting]:
LOGGER.debug('Changing Application %s setting', setting)
self.app.settings[setting] = self.settings[setting]
# Update the routes
self.app.handlers = []
self.app.named_handlers = {}
routes = self.namespace.config.get(config.ROUTES)
self.app.add_handlers(".*$", self.app.prepare_routes(routes))
LOGGER.info('Configuration reloaded') |
<SYSTEM_TASK:>
Called when the process has started
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Called when the process has started
:param int port: The HTTP Server port
""" |
LOGGER.debug('Initializing process')
# Setup logging
self.logging_config = self.setup_logging()
# Register the signal handlers
self.setup_signal_handlers()
# Create the application instance
try:
self.app = self.create_application()
except exceptions.NoRoutesException:
return
# Create the HTTPServer
self.http_server = self.create_http_server()
# Hold on to the IOLoop in case it's needed for responding to signals
self.ioloop = ioloop.IOLoop.instance()
# Start the IOLoop, blocking until it is stopped
try:
self.ioloop.start()
except KeyboardInterrupt:
pass |
<SYSTEM_TASK:>
Called when a child process is spawned to register the signal
<END_TASK>
<USER_TASK:>
Description:
def setup_signal_handlers(self):
"""Called when a child process is spawned to register the signal
handlers
""" |
LOGGER.debug('Registering signal handlers')
signal.signal(signal.SIGABRT, self.on_sigabrt) |
<SYSTEM_TASK:>
Check the config to see if SSL configuration options have been passed
<END_TASK>
<USER_TASK:>
Description:
def ssl_options(self):
"""Check the config to see if SSL configuration options have been passed
and replace none, option, and required with the correct values in
the certreqs attribute if it is specified.
:rtype: dict
""" |
opts = self.namespace.server.get(config.SSL_OPTIONS) or dict()
if config.CERT_REQS in opts:
opts[config.CERT_REQS] = \
self.CERT_REQUIREMENTS[opts[config.CERT_REQS]]
return opts or None |
<SYSTEM_TASK:>
Validates given slug depending on settings.
<END_TASK>
<USER_TASK:>
Description:
def is_valid_article_slug(article, language, slug):
"""Validates given slug depending on settings.
""" |
from ..models import Title
qs = Title.objects.filter(slug=slug, language=language)
if article.pk:
qs = qs.exclude(Q(language=language) & Q(article=article))
qs = qs.exclude(article__publisher_public=article)
if qs.count():
return False
return True |
<SYSTEM_TASK:>
Estimates the memory of the supplied array in bytes
<END_TASK>
<USER_TASK:>
Description:
def array_bytes(array):
""" Estimates the memory of the supplied array in bytes """ |
return np.product(array.shape)*np.dtype(array.dtype).itemsize |
<SYSTEM_TASK:>
Reify arrays, given the supplied dimensions. If copy is True,
<END_TASK>
<USER_TASK:>
Description:
def reify_arrays(arrays, dims, copy=True):
"""
Reify arrays, given the supplied dimensions. If copy is True,
returns a copy of arrays else performs this inplace.
""" |
arrays = ({ k : AttrDict(**a) for k, a in arrays.iteritems() }
if copy else arrays)
for n, a in arrays.iteritems():
a.shape = tuple(dims[v].extent_size if isinstance(v, str) else v
for v in a.shape)
return arrays |
<SYSTEM_TASK:>
Check if the request should be permitted for a given object.
<END_TASK>
<USER_TASK:>
Description:
def check_object_permissions(self, request, obj):
"""
Check if the request should be permitted for a given object.
Raises an appropriate exception if the request is not permitted.
:param request: Pyramid Request object.
:param obj: The SQLAlchemy model instance that permissions will be evaluated against.
""" |
for permission in self.get_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(request, message=getattr(permission, 'message', None)) |
<SYSTEM_TASK:>
Skip pages without images.
<END_TASK>
<USER_TASK:>
Description:
def shouldSkipUrl(self, url, data):
"""Skip pages without images.""" |
return url in (
self.stripUrl % '130217', # video
self.stripUrl % '130218', # video
self.stripUrl % '130226', # video
self.stripUrl % '130424', # video
) |
<SYSTEM_TASK:>
Get ArticleForm for the Article model and modify its fields depending on
<END_TASK>
<USER_TASK:>
Description:
def get_form(self, request, obj=None, **kwargs):
"""
Get ArticleForm for the Article model and modify its fields depending on
the request.
""" |
language = get_language_from_request(request)
form = super(ArticleAdmin, self).get_form(
request, obj,
form=(obj and ArticleForm or ArticleCreateForm),
**kwargs
)
# get_form method operates by overriding initial fields value which
# may persist across invocation. Code below deepcopies fields definition
# to avoid leaks
for field in tuple(form.base_fields.keys()):
form.base_fields[field] = copy.deepcopy(form.base_fields[field])
if 'language' in form.base_fields:
form.base_fields['language'].initial = language
if obj:
title_obj = obj.get_title_obj(language=language, fallback=False, force_reload=True)
if hasattr(title_obj, 'id'):
for name in ('title', 'description', 'page_title', 'menu_title', 'meta_description', 'image'):
if name in form.base_fields:
form.base_fields[name].initial = getattr(title_obj, name)
try:
slug = self.SLUG_REGEXP.search(title_obj.slug).groups()[settings.CMS_ARTICLES_SLUG_GROUP_INDEX]
except AttributeError:
warnings.warn('Failed to parse slug from CMS_ARTICLES_SLUG_REGEXP. '
'It probably doesn\'t correspond to CMS_ARTICLES_SLUG_FORMAT.')
slug = title_obj.slug
form.base_fields['slug'].initial = slug
return form |
<SYSTEM_TASK:>
Publish or unpublish a language of a article
<END_TASK>
<USER_TASK:>
Description:
def unpublish(self, request, article_id, language):
"""
Publish or unpublish a language of a article
""" |
article = get_object_or_404(self.model, pk=article_id)
if not article.has_publish_permission(request):
return HttpResponseForbidden(force_text(_('You do not have permission to unpublish this article')))
if not article.publisher_public_id:
return HttpResponseForbidden(force_text(_('This article was never published')))
try:
article.unpublish(language)
message = _('The %(language)s article "%(article)s" was successfully unpublished') % {
'language': get_language_object(language)['name'], 'article': article}
messages.info(request, message)
LogEntry.objects.log_action(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(Article).pk,
object_id=article_id,
object_repr=article.get_title(),
action_flag=CHANGE,
change_message=message,
)
except RuntimeError:
exc = sys.exc_info()[1]
messages.error(request, exc.message)
except ValidationError:
exc = sys.exc_info()[1]
messages.error(request, exc.message)
path = admin_reverse('cms_articles_article_changelist')
if request.GET.get('redirect_language'):
path = '%s?language=%s&article_id=%s' % (
path,
request.GET.get('redirect_language'),
request.GET.get('redirect_article_id')
)
return HttpResponseRedirect(path) |
<SYSTEM_TASK:>
Count the number of rows for a measurement
<END_TASK>
<USER_TASK:>
Description:
def influx_count_(self, measurement):
"""
Count the number of rows for a measurement
""" |
try:
q = "select count(*) from " + measurement
self.start("Querying: count ...")
datalen = self.influx_cli.query(q)
self.end("Finished querying")
numrows = int(datalen[measurement][datalen[measurement].keys()[0]])
return numrows
except Exception as e:
self.err(e, self.influx_count_,
"Can not count rows for measurement") |
<SYSTEM_TASK:>
Batch export data from an Influxdb measurement to csv
<END_TASK>
<USER_TASK:>
Description:
def influx_to_csv(self, measurement, batch_size=5000):
"""
Batch export data from an Influxdb measurement to csv
""" |
if self.autoprint is True:
print("Processing data from InfluxDb to csv")
try:
q = "select count(*) from " + measurement
numrows = self.influx_cli.query(q)[measurement].iloc[0, 0]
self.info("Processing", str(numrows),
"datapoints from InfluxDb to csv")
done = 0
offset = 1
while (done + 1) < numrows:
q = "select * from " + measurement + \
" limit " + str(batch_size)
if done > 0:
q += " offset " + str(offset)
if self.autoprint is True:
self.start(
"Querying database for the next " +
str(batch_size) + " datapoints")
res = self.influx_cli.query(q)
if self.autoprint is True:
self.end("Finished to query")
numres = 0
try:
numres = len(res[measurement])
except KeyError:
return
df = res[measurement]
ds2 = self.clone_(df)
ds2.to_csv("data/" + measurement +
".csv", index=False, mode='a')
ds2.df = None
if numres < batch_size:
done += numres
else:
done += batch_size
self.progress("Processed points", offset, "to", done)
offset += batch_size
# if (done + 1) == numrows:
# break
except Exception as e:
self.err(e, self.influx_to_csv,
"Can not transfer data from Influxdb to csv")
return
if self.autoprint is True:
print("Finished processing data from InfluxDb to csv") |
<SYSTEM_TASK:>
Get a list comic scraper classes. Can return more than one entries if
<END_TASK>
<USER_TASK:>
Description:
def find_scraperclasses(comic, multiple_allowed=False):
"""Get a list comic scraper classes. Can return more than one entries if
multiple_allowed is True, else it raises a ValueError if multiple
modules match. The match is a case insensitive substring search.""" |
if not comic:
raise ValueError("empty comic name")
candidates = []
cname = comic.lower()
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname == cname:
# perfect match
if not multiple_allowed:
return [scraperclass]
else:
candidates.append(scraperclass)
elif cname in lname:
candidates.append(scraperclass)
if len(candidates) > 1 and not multiple_allowed:
comics = ", ".join(x.getName() for x in candidates)
raise ValueError('multiple comics found: %s' % comics)
elif not candidates:
raise ValueError('comic %r not found' % comic)
return candidates |
<SYSTEM_TASK:>
Find all comic scraper classes in the plugins directory.
<END_TASK>
<USER_TASK:>
Description:
def get_scraperclasses():
"""Find all comic scraper classes in the plugins directory.
The result is cached.
@return: list of Scraper classes
@rtype: list of Scraper
""" |
global _scraperclasses
if _scraperclasses is None:
out.debug(u"Loading comic modules...")
modules = loader.get_modules('plugins')
plugins = loader.get_plugins(modules, Scraper)
_scraperclasses = list(plugins)
check_scrapers()
out.debug(u"... %d modules loaded." % len(_scraperclasses))
return _scraperclasses |
<SYSTEM_TASK:>
Check for duplicate scraper class names.
<END_TASK>
<USER_TASK:>
Description:
def check_scrapers():
"""Check for duplicate scraper class names.""" |
d = {}
for scraperclass in _scraperclasses:
name = scraperclass.getName().lower()
if name in d:
name1 = scraperclass.getName()
name2 = d[name].getName()
raise ValueError('duplicate scrapers %s and %s found' % (name1, name2))
d[name] = scraperclass |
<SYSTEM_TASK:>
Get comic strip downloader for given URL and data.
<END_TASK>
<USER_TASK:>
Description:
def getComicStrip(self, url, data):
"""Get comic strip downloader for given URL and data.""" |
imageUrls = self.fetchUrls(url, data, self.imageSearch)
# map modifier function on image URLs
imageUrls = [self.imageUrlModifier(x, data) for x in imageUrls]
# remove duplicate URLs
imageUrls = set(imageUrls)
if len(imageUrls) > 1 and not self.multipleImagesPerStrip:
out.warn(u"Found %d images instead of 1 at %s with expressions %s" % (len(imageUrls), url, prettyMatcherList(self.imageSearch)))
image = sorted(imageUrls)[0]
out.warn(u"Choosing image %s" % image)
imageUrls = (image,)
elif not imageUrls:
out.warn(u"Found no images at %s with expressions %s" % (url, prettyMatcherList(self.imageSearch)))
if self.textSearch:
text = self.fetchText(url, data, self.textSearch, optional=self.textOptional)
else:
text = None
return ComicStrip(self.getName(), url, imageUrls, self.namer, self.session, text=text) |
<SYSTEM_TASK:>
Get comic strips for an URL. If maxstrips is a positive number, stop after
<END_TASK>
<USER_TASK:>
Description:
def getStripsFor(self, url, maxstrips):
"""Get comic strips for an URL. If maxstrips is a positive number, stop after
retrieving the given number of strips.""" |
self.hitFirstStripUrl = False
seen_urls = set()
while url:
out.info(u'Get strip URL %s' % url, level=1)
data = self.getPage(url)
if self.shouldSkipUrl(url, data):
out.info(u'Skipping URL %s' % url)
self.skippedUrls.add(url)
else:
try:
yield self.getComicStrip(url, data)
except ValueError as msg:
# image not found
out.exception(msg)
if self.firstStripUrl == url:
out.debug(u"Stop at first URL %s" % url)
self.hitFirstStripUrl = True
break
if maxstrips is not None:
maxstrips -= 1
if maxstrips <= 0:
break
prevUrl = self.getPrevUrl(url, data)
seen_urls.add(url)
if prevUrl in seen_urls:
# avoid recursive URL loops
out.warn(u"Already seen previous URL %r" % prevUrl)
break
url = prevUrl
if url:
# wait up to 2 seconds for next URL
time.sleep(1.0 + random.random()) |
<SYSTEM_TASK:>
Cast a public vote for this comic.
<END_TASK>
<USER_TASK:>
Description:
def vote(cls):
"""Cast a public vote for this comic.""" |
url = configuration.VoteUrl + 'count/'
uid = get_system_uid()
data = {"name": cls.getName().replace('/', '_'), "uid": uid}
page = urlopen(url, cls.session, data=data)
return page.text |
<SYSTEM_TASK:>
Get filename indicating all comics are downloaded.
<END_TASK>
<USER_TASK:>
Description:
def getCompleteFile(self, basepath):
"""Get filename indicating all comics are downloaded.""" |
dirname = getDirname(self.getName())
return os.path.join(basepath, dirname, "complete.txt") |
<SYSTEM_TASK:>
Set complete flag for this comic, ie. all comics are downloaded.
<END_TASK>
<USER_TASK:>
Description:
def setComplete(self, basepath):
"""Set complete flag for this comic, ie. all comics are downloaded.""" |
if self.endOfLife:
filename = self.getCompleteFile(basepath)
if not os.path.exists(filename):
with open(filename, 'w') as f:
f.write('All comics should be downloaded here.') |
<SYSTEM_TASK:>
Return language of the comic as a human-readable language name instead
<END_TASK>
<USER_TASK:>
Description:
def language(cls):
"""
Return language of the comic as a human-readable language name instead
of a 2-character ISO639-1 code.
""" |
lang = 'Unknown (%s)' % cls.lang
if pycountry is None:
if cls.lang in languages.Languages:
lang = languages.Languages[cls.lang]
else:
try:
lang = pycountry.languages.get(alpha2 = cls.lang).name
except KeyError:
try:
lang = pycountry.languages.get(iso639_1_code = cls.lang).name
except KeyError:
pass
return lang |
<SYSTEM_TASK:>
Resample and add a sum the main dataframe to a time period
<END_TASK>
<USER_TASK:>
Description:
def rsum(self, time_period: str, num_col: str="Number", dateindex: str=None):
"""
Resample and add a sum the main dataframe to a time period
:param time_period: unit + period: periods are Y, M, D, H, Min, S
:param time_period: str
:param num_col: number of the new column, defaults to "Number"
:param num_col: str, optional
:param dateindex: column name to use as date index, defaults to None
:param dateindex: str, optional
:example: ``ds.rsum("1D")``
""" |
try:
df = self._resample_("sum", time_period,
num_col, dateindex)
self.df = df
if df is None:
self.err("Can not sum data")
except Exceptions as e:
self.err(e, "Can not sum data") |
<SYSTEM_TASK:>
Add an event handler with given name.
<END_TASK>
<USER_TASK:>
Description:
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False):
"""Add an event handler with given name.""" |
if basepath is None:
basepath = '.'
_handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale)) |
<SYSTEM_TASK:>
Emit comic downloaded events for handlers.
<END_TASK>
<USER_TASK:>
Description:
def comicDownloaded(self, comic, filename, text=None):
"""Emit comic downloaded events for handlers.""" |
for handler in _handlers:
handler.comicDownloaded(comic, filename, text=text) |
<SYSTEM_TASK:>
Emit an event to inform the handler about links between comic pages. Should be overridden in subclass.
<END_TASK>
<USER_TASK:>
Description:
def comicPageLink(self, comic, url, prevUrl):
"""Emit an event to inform the handler about links between comic pages. Should be overridden in subclass.""" |
for handler in _handlers:
handler.comicPageLink(comic, url, prevUrl) |
<SYSTEM_TASK:>
Do a SOAP request and returns the result.
<END_TASK>
<USER_TASK:>
Description:
def request(self, name, content={}, namespace=None):
""" Do a SOAP request and returns the result.
Simple wrapper arround pythonzimbra functions
:param name: ex: 'Auth' for performing an 'AuthRequest'
:param content: a dict formatted pythonzimbra-style for request
:param namespace: (optional), the namespace, if different from the
client's
:returns: a dict with response
""" |
if not namespace:
namespace = self.NAMESPACE
req_name = name+'Request'
resp_name = name+'Response'
req = pythonzimbra.request_xml.RequestXml()
resp = pythonzimbra.response_xml.ResponseXml()
if self._session.is_logged_in():
req.set_auth_token(self._session.authToken)
req.add_request(req_name, content, namespace)
try:
self.com.send_request(req, resp)
except HTTPError as e:
if resp:
raise ZimbraSoapServerError(e.req, e.resp)
else:
raise
try:
resp_content = resp.get_response()
return resp_content[resp_name]
except KeyError:
if 'Fault' in resp_content:
raise ZimbraSoapServerError(req, resp)
raise ZimbraSoapUnexpectedResponse(
req, resp, 'Cannot find {} in response "{}"'.format(
resp_name, resp.get_response()))
return resp_content |
<SYSTEM_TASK:>
Simple wrapper arround request to extract a single response
<END_TASK>
<USER_TASK:>
Description:
def request_single(self, name, content={}):
""" Simple wrapper arround request to extract a single response
:returns: the first tag in the response body
""" |
resp = self.request(name, content)
# We stop on the first non-attribute (attributes are unicode/str)
# If it's a list, we only return the first one.
for i in resp.values():
if type(i) == list:
return i[0]
elif type(i) == dict:
return i
return None |
<SYSTEM_TASK:>
Use another client to get logged in via preauth mechanism by an
<END_TASK>
<USER_TASK:>
Description:
def get_logged_in_by(self, login, parent_zc, duration=0):
"""Use another client to get logged in via preauth mechanism by an
already logged in admin.
It required the domain of the admin user to have preAuthKey
The preauth key cannot be created by API, do it with zmprov :
zmprov gdpak <domain>
""" |
domain_name = zobjects.Account(name=login).get_domain()
preauth_key = parent_zc.get_domain(domain_name)['zimbraPreAuthKey']
rc = self.REST_PREAUTH(
self._server_host, parent_zc._server_port, preauth_key=preauth_key)
authToken = rc.get_preauth_token(login)
self.login_with_authToken(authToken) |
<SYSTEM_TASK:>
Use another client to get logged in via delegated_auth mechanism by an
<END_TASK>
<USER_TASK:>
Description:
def delegated_login(self, login, admin_zc, duration=0):
"""Use another client to get logged in via delegated_auth mechanism by an
already logged in admin.
:param admin_zc: An already logged-in admin client
:type admin_zc: ZimbraAdminClient
:param login: the user login (or email) you want to log as
""" |
# a duration of zero is interpretted literaly by the API...
selector = zobjects.Account(name=login).to_selector()
delegate_args = {'account': selector}
if duration:
delegate_args['duration': duration]
resp = admin_zc.request('DelegateAuth', delegate_args)
lifetime = resp['lifetime']
authToken = resp['authToken']
self.login_account = login
self.login_with_authToken(authToken, lifetime) |
<SYSTEM_TASK:>
Get all signatures for the current user
<END_TASK>
<USER_TASK:>
Description:
def get_signatures(self):
""" Get all signatures for the current user
:returns: a list of zobjects.Signature
""" |
signatures = self.request_list('GetSignatures')
return [zobjects.Signature.from_dict(i) for i in signatures] |
<SYSTEM_TASK:>
Retrieve one signature, discriminated by name or id.
<END_TASK>
<USER_TASK:>
Description:
def get_signature(self, signature):
"""Retrieve one signature, discriminated by name or id.
Note that signature name is not case sensitive.
:param: a zobjects.Signature describing the signature
like "Signature(name='my-sig')"
:returns: a zobjects.Signature object, filled with the signature if no
signature is matching, returns None.
""" |
resp = self.request_list('GetSignatures')
# GetSignature does not allow to filter the results, so we do it by
# hand...
if resp and (len(resp) > 0):
for sig_dict in resp:
sig = zobjects.Signature.from_dict(sig_dict)
if hasattr(signature, 'id'):
its_this_one = (sig.id == signature.id)
elif hasattr(signature, 'name'):
its_this_one = (sig.name.upper() == signature.name.upper())
else:
raise ValueError('should mention one of id,name')
if its_this_one:
return sig
else:
return None |
<SYSTEM_TASK:>
Modify an existing signature
<END_TASK>
<USER_TASK:>
Description:
def modify_signature(self, signature):
""" Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
content/contentype/name, the id should be present and
valid, the name does not allows to identify the
signature for that operation.
""" |
# if no content is specified, just use a selector (id/name)
dic = signature.to_creator(for_modify=True)
self.request('ModifySignature', {'signature': dic}) |
<SYSTEM_TASK:>
Gets all the preferences of the current user
<END_TASK>
<USER_TASK:>
Description:
def get_preferences(self):
""" Gets all the preferences of the current user
:returns: a dict presenting the preferences by name, values are
typed to str/bool/int/float regarding their content.
""" |
pref_list = self.request('GetPrefs')['pref']
out = {}
for pref in pref_list:
out[pref['name']] = utils.auto_type(pref['_content'])
return out |
<SYSTEM_TASK:>
Gets a single named preference
<END_TASK>
<USER_TASK:>
Description:
def get_preference(self, pref_name):
""" Gets a single named preference
:returns: the value, typed to str/bool/int/float regarding its content.
""" |
resp = self.request_single('GetPrefs', {'pref': {'name': pref_name}})
return utils.auto_type(resp['_content']) |
<SYSTEM_TASK:>
Get identities matching name and attrs
<END_TASK>
<USER_TASK:>
Description:
def get_identities(self, identity=None, attrs=None):
""" Get identities matching name and attrs
of the user, as a list
:param: zobjects.Identity or identity name (string)
:param: attrs dict of attributes to return only identities matching
:returns: list of zobjects.Identity
""" |
resp = self.request('GetIdentities')
if 'identity' in resp:
identities = resp['identity']
if type(identities) != list:
identities = [identities]
if identity or attrs:
wanted_identities = []
for u_identity in [
zobjects.Identity.from_dict(i) for i in identities]:
if identity:
if isinstance(identity, zobjects.Identity):
if u_identity.name == identity.name:
return [u_identity]
else:
if u_identity.name == identity:
return [u_identity]
elif attrs:
for attr, value in attrs.items():
if (attr in u_identity._a_tags and
u_identity._a_tags[attr] == value):
wanted_identities.append(u_identity)
return wanted_identities
else:
return [zobjects.Identity.from_dict(i) for i in identities]
else:
return [] |
<SYSTEM_TASK:>
Modify some attributes of an identity or its name.
<END_TASK>
<USER_TASK:>
Description:
def modify_identity(self, identity, **kwargs):
""" Modify some attributes of an identity or its name.
:param: identity a zobjects.Identity with `id` set (mandatory). Also
set items you want to modify/set and/or the `name` attribute to
rename the identity.
Can also take the name in string and then attributes to modify
:returns: zobjects.Identity object
""" |
if isinstance(identity, zobjects.Identity):
self.request('ModifyIdentity', {'identity': identity._full_data})
return self.get_identities(identity=identity.name)[0]
else:
attrs = []
for attr, value in kwargs.items():
attrs.append({
'name': attr,
'_content': value
})
self.request('ModifyIdentity', {
'identity': {
'name': identity,
'a': attrs
}
})
return self.get_identities(identity=identity)[0] |
<SYSTEM_TASK:>
Delete an identity from its name or id
<END_TASK>
<USER_TASK:>
Description:
def delete_identity(self, identity):
""" Delete an identity from its name or id
:param: a zobjects.Identity object with name or id defined or a string
of the identity's name
""" |
if isinstance(identity, zobjects.Identity):
self.request(
'DeleteIdentity', {'identity': identity.to_selector()})
else:
self.request('DeleteIdentity', {'identity': {'name': identity}}) |
<SYSTEM_TASK:>
Returns the ID of a Zobject wether it's already known or not
<END_TASK>
<USER_TASK:>
Description:
def _get_or_fetch_id(self, zobj, fetch_func):
""" Returns the ID of a Zobject wether it's already known or not
If zobj.id is not known (frequent if zobj is a selector), fetches first
the object and then returns its ID.
:type zobj: a zobject subclass
:type fetch_func: the function to fetch the zobj from server if its id
is undefined.
:returns: the object id
""" |
try:
return zobj.id
except AttributeError:
try:
return fetch_func(zobj).id
except AttributeError:
raise ValueError('Unqualified Resource') |
<SYSTEM_TASK:>
Fetches an calendar resource with all its attributes.
<END_TASK>
<USER_TASK:>
Description:
def get_calendar_resource(self, cal_resource):
""" Fetches an calendar resource with all its attributes.
:param account: a CalendarResource, with either id or
name attribute set.
:returns: a CalendarResource object, filled.
""" |
selector = cal_resource.to_selector()
resp = self.request_single('GetCalendarResource',
{'calresource': selector})
return zobjects.CalendarResource.from_dict(resp) |
<SYSTEM_TASK:>
Count the number of accounts for a given domain, sorted by cos
<END_TASK>
<USER_TASK:>
Description:
def count_account(self, domain):
""" Count the number of accounts for a given domain, sorted by cos
:returns: a list of pairs <ClassOfService object>,count
""" |
selector = domain.to_selector()
cos_list = self.request_list('CountAccount', {'domain': selector})
ret = []
for i in cos_list:
count = int(i['_content'])
ret.append((zobjects.ClassOfService.from_dict(i), count))
return list(ret) |
<SYSTEM_TASK:>
Fetch the cos for a given account
<END_TASK>
<USER_TASK:>
Description:
def get_account_cos(self, account):
""" Fetch the cos for a given account
Quite different from the original request which returns COS + various
URL + COS + zimbraMailHost... But all other informations are accessible
through get_account.
:type account: zobjects.Account
:rtype: zobjects.COS
""" |
resp = self.request(
'GetAccountInfo', {'account': account.to_selector()})
return zobjects.COS.from_dict(resp['cos']) |
<SYSTEM_TASK:>
Adds members to the distribution list
<END_TASK>
<USER_TASK:>
Description:
def add_distribution_list_member(self, distribution_list, members):
""" Adds members to the distribution list
:type distribution_list: zobjects.DistributionList
:param members: list of email addresses you want to add
:type members: list of str
""" |
members = [{'_content': v} for v in members]
resp = self.request_single('AddDistributionListMember', {
'id': self._get_or_fetch_id(distribution_list,
self.get_distribution_list),
'dlm': members
})
return resp |
<SYSTEM_TASK:>
Fetches an account with all its attributes.
<END_TASK>
<USER_TASK:>
Description:
def get_account(self, account):
""" Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled.
""" |
selector = account.to_selector()
resp = self.request_single('GetAccount', {'account': selector})
return zobjects.Account.from_dict(resp) |
<SYSTEM_TASK:>
Rename an account.
<END_TASK>
<USER_TASK:>
Description:
def rename_account(self, account, new_name):
""" Rename an account.
:param account: a zobjects.Account
:param new_name: a string of new account name
""" |
self.request('RenameAccount', {
'id': self._get_or_fetch_id(account, self.get_account),
'newName': new_name
}) |
<SYSTEM_TASK:>
Builds an authentification token, using preauth mechanism.
<END_TASK>
<USER_TASK:>
Description:
def mk_auth_token(self, account, admin=False, duration=0):
""" Builds an authentification token, using preauth mechanism.
See http://wiki.zimbra.com/wiki/Preauth
:param duration: in seconds defaults to 0, which means "use account
default"
:param account: an account object to be used as a selector
:returns: the auth string
""" |
domain = account.get_domain()
try:
preauth_key = self.get_domain(domain)['zimbraPreAuthKey']
except KeyError:
raise DomainHasNoPreAuthKey(domain)
timestamp = int(time.time())*1000
expires = duration*1000
return utils.build_preauth_str(preauth_key, account.name, timestamp,
expires, admin) |
<SYSTEM_TASK:>
Uses the DelegateAuthRequest to provide a ZimbraAccountClient
<END_TASK>
<USER_TASK:>
Description:
def delegate_auth(self, account):
""" Uses the DelegateAuthRequest to provide a ZimbraAccountClient
already logged with the provided account.
It's the mechanism used with the "view email" button in admin console.
""" |
warnings.warn("delegate_auth() on parent client is deprecated,"
" use delegated_login() on child client instead",
DeprecationWarning)
selector = account.to_selector()
resp = self.request('DelegateAuth', {'account': selector})
lifetime = resp['lifetime']
authToken = resp['authToken']
zc = ZimbraAccountClient(self._server_host)
zc.login_with_authToken(authToken, lifetime)
return zc |
<SYSTEM_TASK:>
Use the DelegateAuthRequest to provide a token and his lifetime
<END_TASK>
<USER_TASK:>
Description:
def get_account_authToken(self, account=None, account_name=''):
""" Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
""" |
if account is None:
account = self.get_account(zobjects.Account(name=account_name))
selector = account.to_selector()
resp = self.request('DelegateAuth', {'account': selector})
authToken = resp['authToken']
lifetime = int(resp['lifetime'])
return authToken, lifetime |
<SYSTEM_TASK:>
SearchAccount is deprecated, using SearchDirectory
<END_TASK>
<USER_TASK:>
Description:
def search_directory(self, **kwargs):
"""
SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
:param offset: The starting offset (0, 25, etc)
:param domain: The domain name to limit the search to
:param applyCos: applyCos - Flag whether or not to apply the COS
policy to account. Specify 0 (false) if only requesting attrs that
aren't inherited from COS
:param applyConfig: whether or not to apply the global config attrs to
account. specify 0 (false) if only requesting attrs that aren't
inherited from global config
:param sortBy: Name of attribute to sort on. Default is the account
name.
:param types: Comma-separated list of types to return. Legal values
are: accounts|distributionlists|aliases|resources|domains|coses
(default is accounts)
:param sortAscending: Whether to sort in ascending order. Default is
1 (true)
:param countOnly: Whether response should be count only. Default is
0 (false)
:param attrs: Comma-seperated list of attrs to return ("displayName",
"zimbraId", "zimbraAccountStatus")
:return: dict of list of "account" "alias" "dl" "calresource" "domain"
"cos"
""" |
search_response = self.request('SearchDirectory', kwargs)
result = {}
items = {
"account": zobjects.Account.from_dict,
"domain": zobjects.Domain.from_dict,
"dl": zobjects.DistributionList.from_dict,
"cos": zobjects.COS.from_dict,
"calresource": zobjects.CalendarResource.from_dict
# "alias": TODO,
}
for obj_type, func in items.items():
if obj_type in search_response:
if isinstance(search_response[obj_type], list):
result[obj_type] = [
func(v) for v in search_response[obj_type]]
else:
result[obj_type] = func(search_response[obj_type])
return result |
<SYSTEM_TASK:>
Create a task
<END_TASK>
<USER_TASK:>
Description:
def create_task(self, subject, desc):
"""Create a task
:param subject: the task's subject
:param desc: the task's content in plain-text
:returns: the task's id
""" |
task = zobjects.Task()
task_creator = task.to_creator(subject, desc)
resp = self.request('CreateTask', task_creator)
task_id = resp['calItemId']
return task_id |
<SYSTEM_TASK:>
Retrieve one task, discriminated by id.
<END_TASK>
<USER_TASK:>
Description:
def get_task(self, task_id):
"""Retrieve one task, discriminated by id.
:param: task_id: the task id
:returns: a zobjects.Task object ;
if no task is matching, returns None.
""" |
task = self.request_single('GetTask', {'id': task_id})
if task:
return zobjects.Task.from_dict(task)
else:
return None |
<SYSTEM_TASK:>
Create a contact
<END_TASK>
<USER_TASK:>
Description:
def create_contact(self, attrs, members=None, folder_id=None, tags=None):
"""Create a contact
Does not include VCARD nor group membership yet
XML example :
<cn l="7> ## ContactSpec
<a n="lastName">MARTIN</a>
<a n="firstName">Pierre</a>
<a n="email">[email protected]</a>
</cn>
Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',
'firstname': 'Pierre',
'email': '[email protected]' }
folder_id = 7
:param folder_id: a string of the ID's folder where to create
contact. Default '7'
:param tags: comma-separated list of tag names
:param attrs: a dictionary of attributes to set ({key:value,...}). At
least one attr is required
:returns: the created zobjects.Contact
""" |
cn = {}
if folder_id:
cn['l'] = str(folder_id)
if tags:
tags = self._return_comma_list(tags)
cn['tn'] = tags
if members:
cn['m'] = members
attrs = [{'n': k, '_content': v} for k, v in attrs.items()]
cn['a'] = attrs
resp = self.request_single('CreateContact', {'cn': cn})
return zobjects.Contact.from_dict(resp) |
<SYSTEM_TASK:>
Get all contacts for the current user
<END_TASK>
<USER_TASK:>
Description:
def get_contacts(self, ids=None, **kwargs):
""" Get all contacts for the current user
:param l: string of a folder id
:param ids: An coma separated list of contact's ID to look for
:returns: a list of zobjects.Contact
""" |
params = {}
if ids:
ids = self._return_comma_list(ids)
params['cn'] = {'id': ids}
for key, value in kwargs.items():
if key in ['a', 'ma']:
params[key] = {'n': value}
else:
params[key] = value
contacts = self.request_list('GetContacts', params)
return [zobjects.Contact.from_dict(i) for i in contacts] |
<SYSTEM_TASK:>
Delete selected contacts for the current user
<END_TASK>
<USER_TASK:>
Description:
def delete_contacts(self, ids):
""" Delete selected contacts for the current user
:param ids: list of ids
""" |
str_ids = self._return_comma_list(ids)
self.request('ContactAction', {'action': {'op': 'delete',
'id': str_ids}}) |
<SYSTEM_TASK:>
Create a contact group
<END_TASK>
<USER_TASK:>
Description:
def create_group(self, attrs, members, folder_id=None, tags=None):
"""Create a contact group
XML example :
<cn l="7> ## ContactSpec
<a n="lastName">MARTIN</a>
<a n="firstName">Pierre</a>
<a n="email">[email protected]</a>
</cn>
Which would be in zimsoap : attrs = { 'lastname': 'MARTIN',
'firstname': 'Pierre',
'email': '[email protected]' }
folder_id = 7
:param folder_id: a string of the ID's folder where to create
contact. Default '7'
:param tags: comma-separated list of tag names
:param members: list of dict. Members with their type. Example
{'type': 'I', 'value': '[email protected]'}.
:param attrs: a dictionary of attributes to set ({key:value,...}). At
least one attr is required
:returns: the created zobjects.Contact
""" |
cn = {}
cn['m'] = members
if folder_id:
cn['l'] = str(folder_id)
if tags:
cn['tn'] = tags
attrs = [{'n': k, '_content': v} for k, v in attrs.items()]
attrs.append({'n': 'type', '_content': 'group'})
cn['a'] = attrs
resp = self.request_single('CreateContact', {'cn': cn})
return zobjects.Contact.from_dict(resp) |
<SYSTEM_TASK:>
Delete selected conversations
<END_TASK>
<USER_TASK:>
Description:
def delete_conversations(self, ids):
""" Delete selected conversations
:params ids: list of ids
""" |
str_ids = self._return_comma_list(ids)
self.request('ConvAction', {'action': {'op': 'delete',
'id': str_ids
}}) |
<SYSTEM_TASK:>
Move selected conversations to an other folder
<END_TASK>
<USER_TASK:>
Description:
def move_conversations(self, ids, folder):
""" Move selected conversations to an other folder
:params ids: list of ids
:params folder: folder id
""" |
str_ids = self._return_comma_list(ids)
self.request('ConvAction', {'action': {'op': 'move',
'id': str_ids,
'l': str(folder)}}) |
<SYSTEM_TASK:>
Inject a message
<END_TASK>
<USER_TASK:>
Description:
def add_message(self, msg_content, folder, **kwargs):
""" Inject a message
:params string msg_content: The entire message's content.
:params string folder: Folder pathname (starts with '/') or folder ID
""" |
content = {'m': kwargs}
content['m']['l'] = str(folder)
content['m']['content'] = {'_content': msg_content}
return self.request('AddMsg', content) |
<SYSTEM_TASK:>
Move selected messages to an other folder
<END_TASK>
<USER_TASK:>
Description:
def move_messages(self, ids, folder_id):
""" Move selected messages to an other folder
:param msg_ids: list of message's ids to move
:param folder_id: folder's id where to move messages
""" |
str_ids = self._return_comma_list(ids)
params = {'action': {
'id': str_ids,
'op': 'move',
'l': folder_id
}}
self.request('MsgAction', params) |
<SYSTEM_TASK:>
Delete selected messages for the current user
<END_TASK>
<USER_TASK:>
Description:
def delete_messages(self, ids):
""" Delete selected messages for the current user
:param ids: list of ids
""" |
str_ids = self._return_comma_list(ids)
return self.request('MsgAction', {'action': {'op': 'delete',
'id': str_ids}}) |
<SYSTEM_TASK:>
Search object in account
<END_TASK>
<USER_TASK:>
Description:
def search(self, query, **kwargs):
""" Search object in account
:returns: a dic where value c contains the list of results (if there
is any). Example : {
'more': '0',
'offset': '0',
'sortBy': 'dateDesc',
'c': [
{
'id': '-261',
'm': {'id': '261',
's': '2556',
'l': '2'},
'u': '0', 'd': '1450714720000',
'sf': '1450714720000',
'e': {'t': 'f',
'd': 'kokopu',
'a': '[email protected]'},
'n': '1',
'fr': {'_content': 'Hello there !'},
'su': {'_content': 'The subject is cool'}
}
]
""" |
content = kwargs
content['query'] = {'_content': query}
return self.request('Search', content) |
<SYSTEM_TASK:>
Return the filter rule
<END_TASK>
<USER_TASK:>
Description:
def get_filter_rule(self, _filter, way='in'):
""" Return the filter rule
:param: _filter a zobjects.FilterRule or the filter name
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: a zobjects.FilterRule""" |
if isinstance(_filter, zobjects.FilterRule):
_filter = _filter.name
for f in self.get_filter_rules(way=way):
if f.name == _filter:
return f
return None |
<SYSTEM_TASK:>
delete a filter rule
<END_TASK>
<USER_TASK:>
Description:
def delete_filter_rule(self, _filter, way='in'):
""" delete a filter rule
:param: _filter a zobjects.FilterRule or the filter name
:param: way string discribing if filter is for 'in' or 'out' messages
:returns: a list of zobjects.FilterRule
""" |
updated_rules = []
rules = self.get_filter_rules(way=way)
if isinstance(_filter, zobjects.FilterRule):
_filter = _filter.name
if rules:
for rule in rules:
if not rule.name == _filter:
updated_rules.append(rule)
if rules != updated_rules:
content = {
'filterRules': {
'filterRule': [f._full_data for f in updated_rules]
}
}
if way == 'in':
self.request('ModifyFilterRules', content)
elif way == 'out':
self.request('ModifyOutgoingFilterRules', content)
return updated_rules |
<SYSTEM_TASK:>
Computes and store an absolute end_date session according to the
<END_TASK>
<USER_TASK:>
Description:
def set_end_date(self, lifetime):
"""Computes and store an absolute end_date session according to the
lifetime of the session""" |
self.end_date = (datetime.datetime.now() +
datetime.timedelta(0, lifetime)) |
<SYSTEM_TASK:>
Search the list of available extensions.
<END_TASK>
<USER_TASK:>
Description:
def search_extension(self, limit=100, offset=0, **kw):
"""Search the list of available extensions.""" |
response = self.request(E.searchExtensionRequest(
E.limit(limit),
E.offset(offset),
E.withDescription(int(kw.get('with_description', 0))),
E.withPrice(int(kw.get('with_price', 0))),
E.withUsageCount(int(kw.get('with_usage_count', 0))),
))
return response.as_models(Extension) |
<SYSTEM_TASK:>
Looks up instruction, which can either be a function or a string.
<END_TASK>
<USER_TASK:>
Description:
def lookup(instruction, instructions = None):
"""Looks up instruction, which can either be a function or a string.
If it's a string, returns the corresponding method.
If it's a function, returns the corresponding name.
""" |
if instructions is None:
instructions = default_instructions
if isinstance(instruction, str):
return instructions[instruction]
elif hasattr(instruction, "__call__"):
rev = dict(((v,k) for (k,v) in instructions.items()))
return rev[instruction]
else:
raise errors.MachineError(KeyError("Unknown instruction: %s" %
str(instruction))) |
<SYSTEM_TASK:>
Decorates a method requiring that the requesting IP address is
<END_TASK>
<USER_TASK:>
Description:
def whitelisted(argument=None):
"""Decorates a method requiring that the requesting IP address is
whitelisted. Requires a whitelist value as a list in the
Application.settings dictionary. IP addresses can be an individual IP
address or a subnet.
Examples:
['10.0.0.0/8','192.168.1.0/24', '1.2.3.4/32']
:param list argument: List of whitelisted ip addresses or blocks
:raises: web.HTTPError
:raises: ValueError
:rtype: any
""" |
def is_whitelisted(remote_ip, whitelist):
"""Check to see if an IP address is whitelisted.
:param str ip_address: The IP address to check
:param list whitelist: The whitelist to check against
:rtype: bool
"""
# Convert the ip into a long int version of the ip address
user_ip = ipaddr.IPv4Address(remote_ip)
# Loop through the ranges in the whitelist and check
if any([user_ip in ipaddr.IPv4Network(entry) for entry in whitelist]):
return True
return False
# If the argument is a function then there were no parameters
if type(argument) is types.FunctionType:
def wrapper(self, *args, **kwargs):
"""Check the whitelist against our application.settings dictionary
whitelist key.
:rtype: any
:raises: web.HTTPError
"""
# Validate we have a configured whitelist
if 'whitelist' not in self.application.settings:
raise ValueError('whitelist not found in Application.settings')
# If the IP address is whitelisted, call the wrapped function
if is_whitelisted(self.request.remote_ip,
self.application.settings['whitelist']):
# Call the original function, IP is whitelisted
return argument(self, *args, **kwargs)
# The ip address was not in the whitelist
raise web.HTTPError(403)
# Return the wrapper method
return wrapper
# They passed in string or list?
else:
# Convert a single ip address to a list
if isinstance(argument, str):
argument = [argument]
# Make sure it's a list
elif not isinstance(argument, list):
raise ValueError('whitelisted requires no parameters or '
'a string or list')
def argument_wrapper(method):
"""Wrapper for a method passing in the IP addresses that constitute
the whitelist.
:param method method: The method being wrapped
:rtype: any
:raises: web.HTTPError
"""
def validate(self, *args, **kwargs):
"""
Validate the ip address agross the list of ip addresses
passed in as a list
"""
if is_whitelisted(self.request.remote_ip, argument):
# Call the original function, IP is whitelisted
return method(self, *args, **kwargs)
# The ip address was not in the whitelist
raise web.HTTPError(403)
# Return the validate method
return validate
# Return the wrapper method
return argument_wrapper |
<SYSTEM_TASK:>
Add a column to the main dataframe populted with
<END_TASK>
<USER_TASK:>
Description:
def lreg(self, xcol, ycol, name="Regression"):
"""
Add a column to the main dataframe populted with
the model's linear regression for a column
""" |
try:
x = self.df[xcol].values.reshape(-1, 1)
y = self.df[ycol]
lm = linear_model.LinearRegression()
lm.fit(x, y)
predictions = lm.predict(x)
self.df[name] = predictions
except Exception as e:
self.err(e, "Can not calculate linear regression") |
<SYSTEM_TASK:>
Returns the coefficient of variance of a column
<END_TASK>
<USER_TASK:>
Description:
def cvar_(self, col):
"""
Returns the coefficient of variance of a column
in percentage
""" |
try:
v = (np.std(self.df[col]) / np.mean(self.df[col])) * 100
return v
except Exception as e:
self.err(e,
"Can not calculate coefficient of variance") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.