text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_arguments(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as argument list."""
|
args = node.args
dflts = node.defaults
vararg = node.vararg
kwargs = node.kwonlyargs
kwdflts = node.kw_defaults
kwarg = node.kwarg
self.compact = True
n_args_without_dflt = len(args) - len(dflts)
args_src = (arg.arg for arg in args[:n_args_without_dflt])
dflts_src = (f"{arg.arg}={self.visit(dflt)}"
for arg, dflt in zip(args[n_args_without_dflt:], dflts))
vararg_src = (f"*{vararg.arg}",) if vararg else ()
kwargs_src = ((f"{kw.arg}={self.visit(dflt)}"
if dflt is not None else f"{kw.arg}")
for kw, dflt in zip(kwargs, kwdflts))
kwarg_src = (f"**{kwarg.arg}",) if kwarg else ()
src = ', '.join(chain(args_src, dflts_src, vararg_src,
kwargs_src, kwarg_src))
self.compact = False
return src
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Lambda(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as lambda expression."""
|
with self.op_man(node):
src = f"lambda {self.visit(node.args)}: {self.visit(node.body)}"
return self.wrap_expr(src, dfltChaining)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_IfExp(self, node: AST, dfltChaining: bool = True) -> str:
|
with self.op_man(node):
src = " if ".join((self.visit(node.body, dfltChaining=False),
" else ".join((self.visit(node.test),
self.visit(node.orelse)))))
return self.wrap_expr(src, dfltChaining)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Attribute(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as attribute access."""
|
return '.'.join((self.visit(node.value), node.attr))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Slice(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as slice."""
|
elems = [self.visit(node.lower), self.visit(node.upper)]
if node.step is not None:
elems.append(self.visit(node.step))
return ':'.join(elems)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_ExtSlice(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as extended slice."""
|
return ', '.join((self.visit(dim) for dim in node.dims))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_comprehension(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as comprehension."""
|
target = node.target
try:
elts = target.elts # we have a tuple of names
except AttributeError:
names = self.visit(target)
else:
names = ', '.join(self.visit(elt) for elt in elts)
src = f"for {names} in {self.visit(node.iter)}"
if node.ifs:
src += f" {' '.join('if ' + self.visit(if_) for if_ in node.ifs)}"
return src
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as list comprehension."""
|
return f"[{self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}]"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as set comprehension."""
|
return f"{{{self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as dict comprehension."""
|
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as generator expression."""
|
return f"({self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)})"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visible_line_width(self, position = Point):
"""Return the visible width of the text in line buffer up to position."""
|
extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD])
return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u"\t")*7 + extra_char_width
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run CleanUp."""
|
import fnmatch
import shutil
import glob
matches = []
matches.extend(glob.glob('./*.pyc'))
matches.extend(glob.glob('./*.pyd'))
matches.extend(glob.glob('./*.pyo'))
matches.extend(glob.glob('./*.so'))
dirs = []
dirs.extend(glob.glob('./__pycache__'))
dirs.extend(glob.glob('docs/_build'))
for cleandir in [SOURCE, 'test', 'examples']:
for root, dirnames, filenames in os.walk(cleandir):
for filename in fnmatch.filter(filenames, '*.pyc'):
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.pyd'):
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.pyo'):
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.so'):
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.dll'):
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(os.path.join(root, filename))
for dirname in fnmatch.filter(dirnames, '__pycache__'):
dirs.append(os.path.join(root, dirname))
for match in matches:
os.remove(match)
for dir in dirs:
shutil.rmtree(dir)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run git add and commit with message if provided."""
|
if os.system('git add .'):
sys.exit(1)
if self.message is not None:
os.system('git commit -a -m "' + self.message + '"')
else:
os.system('git commit -a')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uri(self, value):
"""Set new uri value in record. It will not change the location of the underlying file! """
|
jsonpointer.set_pointer(self.record, self.pointer, value)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, mode='r', **kwargs):
"""Open file ``uri`` under the pointer."""
|
_fs, filename = opener.parse(self.uri)
return _fs.open(filename, mode=mode, **kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move(self, dst, **kwargs):
"""Move file to a new destination and update ``uri``."""
|
_fs, filename = opener.parse(self.uri)
_fs_dst, filename_dst = opener.parse(dst)
movefile(_fs, filename, _fs_dst, filename_dst, **kwargs)
self.uri = dst
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setcontents(self, source, **kwargs):
"""Create a new file from a string or file-like object."""
|
if isinstance(source, six.string_types):
_file = opener.open(source, 'rb')
else:
_file = source
# signals.document_before_content_set.send(self)
data = _file.read()
_fs, filename = opener.parse(self.uri)
_fs.setcontents(filename, data, **kwargs)
_fs.close()
# signals.document_after_content_set.send(self)
if isinstance(source, six.string_types) and hasattr(_file, 'close'):
_file.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, force=False):
"""Remove file reference from record. If force is True it removes the file from filesystem """
|
if force:
_fs, filename = opener.parse(self.uri)
_fs.remove(filename)
self.uri = None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tobytes(
self,
root=None,
encoding='UTF-8',
doctype=None,
canonicalized=True,
xml_declaration=True,
pretty_print=True,
with_comments=True,
):
"""return the content of the XML document as a byte string suitable for writing"""
|
if root is None:
root = self.root
if canonicalized == True:
return self.canonicalized_bytes(root)
else:
return etree.tostring(
root,
encoding=encoding or self.info.encoding,
doctype=doctype or self.info.doctype,
xml_declaration=xml_declaration,
pretty_print=pretty_print,
with_comments=with_comments,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tostring(self, root=None, doctype=None, pretty_print=True):
"""return the content of the XML document as a unicode string"""
|
if root is None:
root = self.root
return etree.tounicode(
root, doctype=doctype or self.info.doctype, pretty_print=pretty_print
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def digest(self, **args):
"""calculate a digest based on the hash of the XML content"""
|
return String(XML.canonicalized_string(self.root)).digest(**args)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def element(self, tag_path, test=None, **attributes):
"""given a tag in xpath form and optional attributes, find the element in self.root or return a new one."""
|
xpath = tag_path
tests = ["@%s='%s'" % (k, attributes[k]) for k in attributes]
if test is not None:
tests.insert(0, test)
if len(tests) > 0:
xpath += "[%s]" % ' and '.join(tests)
e = self.find(self.root, xpath)
if e is None:
tag = tag_path.split('/')[-1].split('[')[0]
tagname = tag.split(':')[-1]
if ':' in tag:
nstag = tag.split(':')[0]
tag = "{%s}%s" % (self.NS[nstag], tagname)
e = etree.Element(tag, **attributes)
return e
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namespace(self, elem=None):
"""return the URL, if any, for the doc root or elem, if given."""
|
if elem is None:
elem = self.root
return XML.tag_namespace(elem.tag)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_namespace(cls, tag):
"""return the namespace for a given tag, or '' if no namespace given"""
|
md = re.match("^(?:\{([^\}]*)\})", tag)
if md is not None:
return md.group(1)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_name(cls, tag):
"""return the name of the tag, with the namespace removed"""
|
while isinstance(tag, etree._Element):
tag = tag.tag
return tag.split('}')[-1]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def element_map(
self,
tags=None,
xpath="//*",
exclude_attribs=[],
include_attribs=[],
attrib_vals=False,
hierarchy=False,
minimize=False,
):
"""return a dict of element tags, their attribute names, and optionally attribute values,
in the XML document
"""
|
if tags is None:
tags = Dict()
for elem in self.root.xpath(xpath):
if elem.tag not in tags.keys():
tags[elem.tag] = Dict(**{'parents': [], 'children': [], 'attributes': Dict()})
for a in [
a
for a in elem.attrib.keys()
if (include_attribs == [] and a not in exclude_attribs) or (a in include_attribs)
]:
# Attribute Names
if a not in tags[elem.tag].attributes.keys():
tags[elem.tag].attributes[a] = []
# Attribute Values
if attrib_vals == True and elem.get(a) not in tags[elem.tag].attributes[a]:
tags[elem.tag].attributes[a].append(elem.get(a))
# Hierarchy: Parents and Children
if hierarchy == True:
parent = elem.getparent()
if parent is not None and parent.tag not in tags[elem.tag].parents:
tags[elem.tag].parents.append(parent.tag)
for child in elem.xpath("*"):
if child.tag not in tags[elem.tag].children:
tags[elem.tag].children.append(child.tag)
if minimize == True:
for tag in tags.keys():
if tags[tag].get('parents') == []:
tags[tag].pop('parents')
if tags[tag].get('children') == []:
tags[tag].pop('children')
if tags[tag].get('attributes') == {}:
tags[tag].pop('attributes')
if tags[tag] == {}:
tags.pop(tag)
return tags
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_key_tag(Class, key, namespaces=None):
"""convert a dict key into an element or attribute name"""
|
namespaces = namespaces or Class.NS
ns = Class.tag_namespace(key)
tag = Class.tag_name(key)
if ns is None and ':' in key:
prefix, tag = key.split(':')
if prefix in namespaces.keys():
ns = namespaces[prefix]
if ns is not None:
tag = "{%s}%s" % (ns, tag)
return tag
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def replace_with_contents(c, elem):
"removes an element and leaves its contents in its place. Namespaces supported."
parent = elem.getparent()
index = parent.index(elem)
children = elem.getchildren()
previous = elem.getprevious()
# text
if index == 0:
parent.text = (parent.text or '') + (elem.text or '')
else:
previous.tail = (previous.tail or '') + (elem.text or '')
# children
for child in children:
parent.insert(index + children.index(child), child)
# tail
if len(children) > 0:
last_child = children[-1]
last_child.tail = (last_child.tail or '') + (elem.tail or '')
else:
if index == 0:
parent.text = (parent.text or '') + (elem.tail or '')
else:
previous.tail = (previous.tail or '') + (elem.tail or '')
# elem
parent.remove(elem)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_range(cls, elem, end_elem, delete_end=True):
"""delete everything from elem to end_elem, including elem.
if delete_end==True, also including end_elem; otherwise, leave it."""
|
while elem is not None and elem != end_elem and end_elem not in elem.xpath("descendant::*"):
parent = elem.getparent()
nxt = elem.getnext()
parent.remove(elem)
if DEBUG == True:
print(etree.tounicode(elem))
elem = nxt
if elem == end_elem:
if delete_end == True:
cls.remove(end_elem, leave_tail=True)
elif elem is None:
if parent.tail not in [None, '']:
parent.tail = ''
cls.remove_range(parent.getnext(), end_elem)
XML.remove_if_empty(parent)
elif end_elem in elem.xpath("descendant::*"):
if DEBUG == True:
print(elem.text)
elem.text = ''
cls.remove_range(elem.getchildren()[0], end_elem)
XML.remove_if_empty(elem)
else:
print("LOGIC ERROR", file=sys.stderr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def wrap_content(cls, container, wrapper):
"wrap the content of container element with wrapper element"
wrapper.text = (container.text or '') + (wrapper.text or '')
container.text = ''
for ch in container:
wrapper.append(ch)
container.insert(0, wrapper)
return container
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_contiguous(C, node, xpath, namespaces=None):
"""Within a given node, merge elements that are next to each other
if they have the same tag and attributes.
"""
|
new_node = deepcopy(node)
elems = XML.xpath(new_node, xpath, namespaces=namespaces)
elems.reverse()
for elem in elems:
nxt = elem.getnext()
if elem.attrib == {}:
XML.replace_with_contents(elem)
elif (
elem.tail in [None, '']
and nxt is not None
and elem.tag == nxt.tag
and elem.attrib == nxt.attrib
):
# merge nxt with elem
# -- append nxt.text to elem last child tail
if len(elem.getchildren()) > 0:
lastch = elem.getchildren()[-1]
lastch.tail = (lastch.tail or '') + (nxt.text or '')
else:
elem.text = (elem.text or '') + (nxt.text or '')
# -- append nxt children to elem children
for ch in nxt.getchildren():
elem.append(ch)
# -- remove nxt
XML.remove(nxt, leave_tail=True)
return new_node
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unnest(c, elem, ignore_whitespace=False):
"""unnest the element from its parent within doc. MUTABLE CHANGES"""
|
parent = elem.getparent()
gparent = parent.getparent()
index = parent.index(elem)
# put everything up to elem into a new parent element right before the current parent
preparent = etree.Element(parent.tag)
preparent.text, parent.text = (parent.text or ''), ''
for k in parent.attrib.keys():
preparent.set(k, parent.get(k))
if index > 0:
for ch in parent.getchildren()[:index]:
preparent.append(ch)
gparent.insert(gparent.index(parent), preparent)
XML.remove_if_empty(preparent, leave_tail=True, ignore_whitespace=ignore_whitespace)
# put the element right before the current parent
XML.remove(elem, leave_tail=True)
gparent.insert(gparent.index(parent), elem)
elem.tail = ''
# if the original parent is empty, remove it
XML.remove_if_empty(parent, leave_tail=True, ignore_whitespace=ignore_whitespace)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interior_nesting(cls, elem1, xpath, namespaces=None):
"""for elem1 containing elements at xpath, embed elem1 inside each of those elements,
and then remove the original elem1"""
|
for elem2 in elem1.xpath(xpath, namespaces=namespaces):
child_elem1 = etree.Element(elem1.tag)
for k in elem1.attrib:
child_elem1.set(k, elem1.get(k))
child_elem1.text, elem2.text = elem2.text, ''
for ch in elem2.getchildren():
child_elem1.append(ch)
elem2.insert(0, child_elem1)
XML.replace_with_contents(elem1)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fragment_nesting(cls, elem1, tag2, namespaces=None):
"""for elem1 containing elements with tag2,
fragment elem1 into elems that are adjacent to and nested within tag2"""
|
elems2 = elem1.xpath("child::%s" % tag2, namespaces=namespaces)
while len(elems2) > 0:
elem2 = elems2[0]
parent2 = elem2.getparent()
index2 = parent2.index(elem2)
# all of elem2 has a new tag1 element embedded inside of it
child_elem1 = etree.Element(elem1.tag)
for k in elem1.attrib:
child_elem1.set(k, elem1.get(k))
elem2.text, child_elem1.text = '', elem2.text
for ch in elem2.getchildren():
child_elem1.append(ch)
elem2.insert(0, child_elem1)
# new_elem1 for all following children of parent2
new_elem1 = etree.Element(elem1.tag)
for k in elem1.attrib:
new_elem1.set(k, elem1.get(k))
new_elem1.text, elem2.tail = elem2.tail, ''
for ch in parent2.getchildren()[index2 + 1 :]:
new_elem1.append(ch)
# elem2 is placed after parent2
parent = parent2.getparent()
parent.insert(parent.index(parent2) + 1, elem2)
last_child = elem2
# new_elem1 is placed after elem2
parent.insert(parent.index(elem2) + 1, new_elem1)
new_elem1.tail, elem1.tail = elem1.tail, ''
XML.remove_if_empty(elem1)
XML.remove_if_empty(new_elem1)
# repeat until all tag2 elements are unpacked from the new_elem1
elem1 = new_elem1
elems2 = elem1.xpath("child::%s" % tag2, namespaces=namespaces)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def communityvisibilitystate(self):
"""Return the Visibility State of the Users Profile"""
|
if self._communityvisibilitystate == None:
return None
elif self._communityvisibilitystate in self.VisibilityState:
return self.VisibilityState[self._communityvisibilitystate]
else:
#Invalid State
return None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def personastate(self):
"""Return the Persona State of the Users Profile"""
|
if self._personastate == None:
return None
elif self._personastate in self.PersonaState:
return self.PersonaState[self._personastate]
else:
#Invalid State
return None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mcus():
"""MCU list."""
|
ls = []
for h in hwpack_names():
for b in board_names(h):
ls += [mcu(b, h)]
ls = sorted(list(set(ls)))
return ls
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logpath2dt(filepath):
""" given a dataflashlog in the format produced by Mission Planner, return a datetime which says when the file was downloaded from the APM """
|
return datetime.datetime.strptime(re.match(r'.*/(.*) .*$',filepath).groups()[0],'%Y-%m-%d %H-%M')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def url(self):
'''url of the item
Notes
-----
if remote-adderes was given, then that is used as the base
'''
path = '/web/itemdetails.html?id={}'.format(self.id)
return self.connector.get_url(path, attach_api_key=False)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def update(self, fields=''):
'''reload object info from emby
|coro|
Parameters
----------
fields : str
additional fields to request when updating
See Also
--------
refresh : same thing
send :
post :
'''
path = 'Users/{{UserId}}/Items/{}'.format(self.id)
info = await self.connector.getJson(path,
remote=False,
Fields='Path,Overview,'+fields
)
self.object_dict.update(info)
self.extras = {}
return self
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def send(self):
'''send data that was changed to emby
|coro|
This should be used after using any of the setter. Not necessarily
immediately, but soon after.
See Also
--------
post: same thing
update :
refresh :
Returns
-------
aiohttp.ClientResponse or None if nothing needed updating
'''
# Why does the whole dict need to be sent?
# because emby is dumb, and will break if I don't
path = 'Items/{}'.format(self.id)
resp = await self.connector.post(path, data=self.object_dict, remote=False)
if resp.status == 400:
await EmbyObject(self.object_dict, self.connector).update()
resp = await self.connector.post(path,data=self.object_dict,remote=False)
return resp
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_lib(lib_name):
"""remove library. :param lib_name: library name (e.g. 'PS2Keyboard') :rtype: None """
|
targ_dlib = libraries_dir() / lib_name
log.debug('remove %s', targ_dlib)
targ_dlib.rmtree()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_holidays(self, filename):
""" Read holidays from an iCalendar-format file. """
|
cal = Calendar.from_ical(open(filename, 'rb').read())
holidays = []
for component in cal.walk('VEVENT'):
start = component.decoded('DTSTART')
try:
end = component.decoded('DTEND')
except KeyError:
# RFC allows DTEND to be missing
if isinstance(start, datetime):
# For DATETIME instances, the event ends immediately.
end = start
elif isinstance(start, date):
# For DATE instances, the event ends tomorrow
end = start + timedelta(days=1)
else:
raise KeyError, 'DTEND is missing and DTSTART is not of DATE or DATETIME type'
if isinstance(start, date) and not isinstance(start, datetime):
assert (isinstance(end, date) and not isinstance(end, datetime)), \
'DTSTART is of DATE type but DTEND is not of DATE type (got %r instead)' % type(end)
# All-day event, set times to midnight local time
start = datetime.combine(start, time.min)
end = datetime.combine(end, time.min)
# check for TZ data
if start.tzinfo is None or end.tzinfo is None:
# One of them is missing tzinfo, replace both with this office's
# local time. Assume standard time if ambiguous.
start = self.tz.localize(start, is_dst=False)
end = self.tz.localize(end, is_dst=False)
yield (start, end)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_hours(self, office=None, when=None):
""" Finds if it is business hours in the given office. :param office: Office ID to look up, or None to check if any office is in business hours. :type office: str or None :param datetime.datetime when: When to check the office is open, or None for now. :returns: True if it is business hours, False otherwise. :rtype: bool :raises KeyError: If the office is unknown. """
|
if when == None:
when = datetime.now(tz=utc)
if office == None:
for office in self.offices.itervalues():
if office.in_hours(when):
return True
return False
else:
# check specific office
return self.offices[office].in_hours(when)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_logging(namespace):
""" setup global logging """
|
loglevel = {
0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG,
}.get(namespace.verbosity, logging.DEBUG)
if namespace.verbosity > 1:
logformat = '%(levelname)s csvpandas %(lineno)s %(message)s'
else:
logformat = 'csvpandas %(message)s'
logging.basicConfig(stream=namespace.log, format=logformat, level=loglevel)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_subcommands(parser, subcommands, argv):
""" Setup all sub-commands """
|
subparsers = parser.add_subparsers(dest='subparser_name')
# add help sub-command
parser_help = subparsers.add_parser(
'help', help='Detailed help for actions using `help <action>`')
parser_help.add_argument('action', nargs=1)
# add all other subcommands
modules = [
name for _, name, _ in pkgutil.iter_modules(subcommands.__path__)]
commands = [m for m in modules if m in argv]
actions = {}
# `commands` will contain the module corresponding to a single
# subcommand if provided; otherwise, generate top-level help
# message from all submodules in `modules`.
for name in commands or modules:
# set up subcommand help text. The first line of the dosctring
# in the module is displayed as the help text in the
# script-level help message (`script -h`). The entire
# docstring is displayed in the help message for the
# individual subcommand ((`script action -h`))
# if no individual subcommand is specified (run_action[False]),
# a full list of docstrings is displayed
try:
imp = '{}.{}'.format(subcommands.__name__, name)
mod = importlib.import_module(imp)
except Exception as e:
log.error(e)
continue
subparser = subparsers.add_parser(
name,
help=mod.__doc__.lstrip().split('\n', 1)[0],
description=mod.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
mod.build_parser(subparser)
# see global subcommands/__init__.py
subcommands.build_parser(subparser)
actions[name] = mod.action
return parser, actions
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opener(mode='r'):
"""Factory for creating file objects Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values as the builtin open() function. - bufsize -- The file's desired buffer size. Accepts the same values as the builtin open() function. """
|
def open_file(f):
if f is sys.stdout or f is sys.stdin:
return f
elif f == '-':
return sys.stdin if 'r' in mode else sys.stdout
elif f.endswith('.bz2'):
return bz2.BZ2File(f, mode)
elif f.endswith('.gz'):
return gzip.open(f, mode)
else:
return open(f, mode)
return open_file
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, id, no_summary=False):
""" List details for a specific tenant id """
|
resp = self.client.accounts.get(id)
if no_summary:
return self.display(resp)
results = []
# Get a list of all volumes for this tenant id
client = LunrClient(self.get_admin(), debug=self.debug)
volumes = client.volumes.list(account_id=resp['id'])
#volumes = self.client.volumes.list(resp['id'])
for volume in volumes:
if volume['status'] == 'DELETED':
continue
results.append(volume)
self.display(resp, ['name', 'status', 'last_modified', 'created_at'])
if results:
return self.display(response(results, 200),
['id', 'status', 'size'])
else:
print("-- This account has no active volumes --")
print("\nThis is a summary, use --no-summary "
"to see the entire response")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, id):
""" Create a new tenant id """
|
resp = self.client.accounts.create(id=id)
self.display(resp)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, id):
""" Delete an tenant id """
|
resp = self.client.accounts.delete(id)
self.display(resp)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Main method for debug purposes."""
|
parser = argparse.ArgumentParser()
group_tcp = parser.add_argument_group('TCP')
group_tcp.add_argument('--tcp', dest='mode', action='store_const', const=PROP_MODE_TCP, help="Set tcp mode")
group_tcp.add_argument('--host', dest='hostname', help="Specify hostname", default='')
group_tcp.add_argument('--port', dest='port', help="Specify port", default=23, type=int)
group_serial = parser.add_argument_group('Serial')
group_serial.add_argument('--serial', dest='mode', action='store_const', const=PROP_MODE_SERIAL, help="Set serial mode")
group_serial.add_argument('--interface', dest='interface', help="Specify interface", default='')
group_file = parser.add_argument_group('File')
group_file.add_argument('--file', dest='mode', action='store_const', const=PROP_MODE_FILE, help="Set file mode")
group_file.add_argument('--name', dest='file', help="Specify file name", default='')
args = parser.parse_args()
kwb = KWBEasyfire(args.mode, args.hostname, args.port, args.interface, 0, args.file)
kwb.run_thread()
time.sleep(5)
kwb.stop_thread()
print(kwb)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _open_connection(self):
"""Open a connection to the easyfire unit."""
|
if (self._mode == PROP_MODE_SERIAL):
self._serial = serial.Serial(self._serial_device, self._serial_speed)
elif (self._mode == PROP_MODE_TCP):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.connect((self._ip, self._port))
elif (self._mode == PROP_MODE_FILE):
self._file = open(self._file_path, "r")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _close_connection(self):
"""Close the connection to the easyfire unit."""
|
if (self._mode == PROP_MODE_SERIAL):
self._serial.close()
elif (self._mode == PROP_MODE_TCP):
self._socket.close()
elif (self._mode == PROP_MODE_FILE):
self._file.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_to_checksum(self, checksum, value):
"""Add a byte to the checksum."""
|
checksum = self._byte_rot_left(checksum, 1)
checksum = checksum + value
if (checksum > 255):
checksum = checksum - 255
self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(value))
return checksum
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_byte(self):
"""Read a byte from input."""
|
to_return = ""
if (self._mode == PROP_MODE_SERIAL):
to_return = self._serial.read(1)
elif (self._mode == PROP_MODE_TCP):
to_return = self._socket.recv(1)
elif (self._mode == PROP_MODE_FILE):
to_return = struct.pack("B", int(self._file.readline()))
_LOGGER.debug("READ: " + str(ord(to_return)))
self._logdata.append(ord(to_return))
if (len(self._logdata) > self._logdatalen):
self._logdata = self._logdata[len(self._logdata) - self._logdatalen:]
self._debug(PROP_LOGLEVEL_TRACE, "READ: " + str(ord(to_return)))
return to_return
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_temp(byte_1, byte_2):
"""Decode a signed short temperature as two bytes to a single number."""
|
temp = (byte_1 << 8) + byte_2
if (temp > 32767):
temp = temp - 65536
temp = temp / 10
return temp
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_packet(self):
"""Read a packet from the input."""
|
status = STATUS_WAITING
mode = 0
checksum = 0
checksum_calculated = 0
length = 0
version = 0
i = 0
cnt = 0
packet = bytearray(0)
while (status != STATUS_PACKET_DONE):
read = self._read_ord_byte()
if (status != STATUS_CTRL_CHECKSUM and status != STATUS_SENSE_CHECKSUM):
checksum_calculated = self._add_to_checksum(checksum_calculated, read)
self._debug(PROP_LOGLEVEL_TRACE, "R: " + str(read))
self._debug(PROP_LOGLEVEL_TRACE, "S: " + str(status))
if (status == STATUS_WAITING):
if (read == 2):
status = STATUS_PRE_1
checksum_calculated = read
else:
status = STATUS_WAITING
elif (status == STATUS_PRE_1):
checksum = 0
if (read == 2):
status = STATUS_SENSE_PRE_2
checksum_calculated = read
elif (read == 0):
status = STATUS_WAITING
else:
status = STATUS_CTRL_PRE_2
elif (status == STATUS_SENSE_PRE_2):
length = read
status = STATUS_SENSE_PRE_LENGTH
elif (status == STATUS_SENSE_PRE_LENGTH):
version = read
status = STATUS_SENSE_PRE_3
elif (status == STATUS_SENSE_PRE_3):
cnt = read
i = 0
status = STATUS_SENSE_DATA
elif (status == STATUS_SENSE_DATA):
packet.append(read)
i = i + 1
if (i == length):
status = STATUS_SENSE_CHECKSUM
elif (status == STATUS_SENSE_CHECKSUM):
checksum = read
mode = PROP_PACKET_SENSE
status = STATUS_PACKET_DONE
elif (status == STATUS_CTRL_PRE_2):
version = read
status = STATUS_CTRL_PRE_3
elif (status == STATUS_CTRL_PRE_3):
cnt = read
i = 0
length = 16
status = STATUS_CTRL_DATA
elif (status == STATUS_CTRL_DATA):
packet.append(read)
i = i + 1
if (i == length):
status = STATUS_CTRL_CHECKSUM
elif (status == STATUS_CTRL_CHECKSUM):
checksum = read
mode = PROP_PACKET_CTRL
status = STATUS_PACKET_DONE
else:
status = STATUS_WAITING
self._debug(PROP_LOGLEVEL_DEBUG, "MODE: " + str(mode) + " Version: " + str(version) + " Checksum: " + str(checksum) + " / " + str(checksum_calculated) + " Count: " + str(cnt) + " Length: " + str(len(packet)))
self._debug(PROP_LOGLEVEL_TRACE, "Packet: " + str(packet))
return (mode, version, packet)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_sense_packet(self, version, packet):
"""Decode a sense packet into the list of sensors."""
|
data = self._sense_packet_to_data(packet)
offset = 4
i = 0
datalen = len(data) - offset - 6
temp_count = int(datalen / 2)
temp = []
for i in range(temp_count):
temp_index = i * 2 + offset
temp.append(self._decode_temp(data[temp_index], data[temp_index + 1]))
self._debug(PROP_LOGLEVEL_DEBUG, "T: " + str(temp))
for sensor in self._sense_sensor:
if (sensor.sensor_type == PROP_SENSOR_TEMPERATURE):
sensor.value = temp[sensor.index]
elif (sensor.sensor_type == PROP_SENSOR_RAW):
sensor.value = packet
self._debug(PROP_LOGLEVEL_DEBUG, str(self))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_ctrl_packet(self, version, packet):
"""Decode a control packet into the list of sensors."""
|
for i in range(5):
input_bit = packet[i]
self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input_bit >> 1) & 1) + str(input_bit & 1))
for sensor in self._ctrl_sensor:
if (sensor.sensor_type == PROP_SENSOR_FLAG):
sensor.value = (packet[sensor.index // 8] >> (sensor.index % 8)) & 1
elif (sensor.sensor_type == PROP_SENSOR_RAW):
sensor.value = packet
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Main thread that reads from input and populates the sensors."""
|
while (self._run_thread):
(mode, version, packet) = self._read_packet()
if (mode == PROP_PACKET_SENSE):
self._decode_sense_packet(version, packet)
elif (mode == PROP_PACKET_CTRL):
self._decode_ctrl_packet(version, packet)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_thread(self):
"""Run the main thread."""
|
self._run_thread = True
self._thread.setDaemon(True)
self._thread.start()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unused(self, _dict):
""" Remove empty parameters from the dict """
|
for key, value in _dict.items():
if value is None:
del _dict[key]
return _dict
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def required(self, method, _dict, require):
""" Ensure the required items are in the dictionary """
|
for key in require:
if key not in _dict:
raise LunrError("'%s' is required argument for method '%s'"
% (key, method))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allowed(self, method, _dict, allow):
""" Only these items are allowed in the dictionary """
|
for key in _dict.keys():
if key not in allow:
raise LunrError("'%s' is not an argument for method '%s'"
% (key, method))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_event_name(name):
"""Returns the python module and obj given an event name """
|
try:
app, event = name.split('.')
return '{}.{}'.format(app, EVENTS_MODULE_NAME), event
except ValueError:
raise InvalidEventNameError(
(u'The name "{}" is invalid. '
u'Make sure you are using the "app.KlassName" format'
).format(name))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_event(name):
"""Actually import the event represented by name Raises the `EventNotFoundError` if it's not possible to find the event class refered by `name`. """
|
try:
module, klass = parse_event_name(name)
return getattr(import_module(module), klass)
except (ImportError, AttributeError):
raise EventNotFoundError(
('Event "{}" not found. '
'Make sure you have a class called "{}" inside the "{}" '
'module.'.format(name, klass, module)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_handlers(event=None):
"""Remove handlers of a given `event`. If no event is informed, wipe out all events registered. Be careful!! This function is intended to help when writing tests and for debugging purposes. If you call it, all handlers associated to an event (or to all of them) will be disassociated. Which means that you'll have to reload all modules that teclare handlers. I'm sure you don't want it. """
|
if event:
if event in HANDLER_REGISTRY:
del HANDLER_REGISTRY[event]
if event in EXTERNAL_HANDLER_REGISTRY:
del EXTERNAL_HANDLER_REGISTRY[event]
else:
HANDLER_REGISTRY.clear()
EXTERNAL_HANDLER_REGISTRY.clear()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_handlers(event_name, registry=HANDLER_REGISTRY):
"""Small helper to find all handlers associated to a given event If the event can't be found, an empty list will be returned, since this is an internal function and all validation against the event name and its existence was already performed. """
|
handlers = []
# event_name can be a BaseEvent or the string representation
if isinstance(event_name, basestring):
matched_events = [event for event in registry.keys()
if fnmatch.fnmatchcase(event_name, event)]
for matched_event in matched_events:
handlers.extend(registry.get(matched_event))
else:
handlers = registry.get(find_event(event_name), [])
return handlers
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_default_values(data):
"""Return all default values that an event should have"""
|
request = data.get('request')
result = {}
result['__datetime__'] = datetime.now()
result['__ip_address__'] = request and get_ip(request) or '0.0.0.0'
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_data_values(data):
"""Remove special values that log function can take There are some special values, like "request" that the `log()` function can take, but they're not meant to be passed to the celery task neither for the event handlers. This function filter these keys and return another dict without them. """
|
banned = ('request',)
return {key: val for key, val in data.items() if not key in banned}
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_event_modules():
"""Import all events declared for all currently installed apps This function walks through the list of installed apps and tries to import a module named `EVENTS_MODULE_NAME`. """
|
for installed_app in getsetting('INSTALLED_APPS'):
module_name = u'{}.{}'.format(installed_app, EVENTS_MODULE_NAME)
try:
import_module(module_name)
except ImportError:
pass
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_expired_accounts():
""" Check of expired accounts. """
|
ACTIVATED = RegistrationProfile.ACTIVATED
expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
to_delete = []
print "Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count())
for profile in RegistrationProfile.objects.all():
# if registration profile is expired, deactive user.
print "Processing %s" % profile.user
# If profile has been activated already, set it to be removed
# and move on to next registration profile
if profile.activation_key == ACTIVATED:
print "Found Active"
to_delete.append(profile.pk)
continue
# If the user has not activated their account and the activation
# days have passed, deactivate the user and send an email to user.
if profile.user.is_active and profile.user.date_joined + expiration_date <= datetime.datetime.now():
print "Found Expired"
user = profile.user
user.is_active = False
# Send an email notifing user of there account becoming inactive.
site = Site.objects.get_current()
ctx_dict = { 'site': site,
'activation_key': profile.activation_key}
subject = render_to_string(
'registration/email/emails/account_expired_subject.txt',
ctx_dict)
subject = ''.join(subject.splitlines())
message = render_to_string(
'registration/email/emails/account_expired.txt',
ctx_dict)
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
# Only save the user instance after the email is sent.
user.save()
# Delete the registration profiles that were set to be deleted, aka
# user has already activated their account.
print "Deleting %s registration profiles." % str(len(to_delete))
RegistrationProfile.objects.filter(pk__in=to_delete).delete()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate(self, request, activation_key):
""" Override default activation process. This will activate the user even if its passed its expiration date. """
|
if SHA1_RE.search(activation_key):
try:
profile = RegistrationProfile.objects.get(activation_key=activation_key)
except RegistrationProfile.DoesNotExist:
return False
user = profile.user
user.is_active = True
user.save()
profile.activation_key = RegistrationProfile.ACTIVATED
profile.save()
return user
return False
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, request, **kwargs):
""" Create and immediately log in a new user. Only require a email to register, username is generated automatically and a password is random generated and emailed to the user. Activation is still required for account uses after specified number of days. """
|
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
email = kwargs['email']
# Generate random password
password = User.objects.make_random_password()
# Generate username based off of the email supplied
username = sha_constructor(str(email)).hexdigest()[:30]
incr = 0
# Ensure the generated username is in fact unqiue
while User.objects.filter(username=username).count() > 0:
incr += 1
username = sha_constructor(str(email + str(incr))).hexdigest()[:30]
# Create the active user
new_user = User.objects.create_user(username, email, password)
new_user.save()
# Create the registration profile, this is still needed because
# the user still needs to activate there account for further users
# after 3 days
registration_profile = RegistrationProfile.objects.create_profile(
new_user)
# Authenticate and login the new user automatically
auth_user = authenticate(username=username, password=password)
login(request, auth_user)
# Set the expiration to when the users browser closes so user
# is forced to log in upon next visit, this should force the user
# to check there email for there generated password.
request.session.set_expiry(0)
# Create a profile instance for the new user if
# AUTH_PROFILE_MODULE is specified in settings
if hasattr(settings, 'AUTH_PROFILE_MODULE') and getattr(settings, 'AUTH_PROFILE_MODULE'):
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
model = models.get_model(app_label, model_name)
try:
profile = new_user.get_profile()
except model.DoesNotExist:
profile = model(user=new_user)
profile.save()
# Custom send activation email
self.send_activation_email(
new_user, registration_profile, password, site)
# Send user_registered signal
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_activation_email(self, user, profile, password, site):
""" Custom send email method to supplied the activation link and new generated password. """
|
ctx_dict = { 'password': password,
'site': site,
'activation_key': profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS}
subject = render_to_string(
'registration/email/emails/password_subject.txt',
ctx_dict)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('registration/email/emails/password.txt',
ctx_dict)
try:
user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
except:
pass
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_registration_redirect(self, request, user):
""" After registration, redirect to the home page or supplied "next" query string or hidden field value. """
|
next_url = "/registration/register/complete/"
if "next" in request.GET or "next" in request.POST:
next_url = request.GET.get("next", None) or request.POST.get("next", None) or "/"
return (next_url, (), {})
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" Returns the next batch for the batched sequence or `None`, if this batch is already the last batch. :rtype: :class:`Batch` instance or `None`. """
|
if self.start + self.size > self.total_size:
result = None
else:
result = Batch(self.start + self.size, self.size, self.total_size)
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def previous(self):
""" Returns the previous batch for the batched sequence or `None`, if this batch is already the first batch. :rtype: :class:`Batch` instance or `None`. """
|
if self.start - self.size < 0:
result = None
else:
result = Batch(self.start - self.size, self.size, self.total_size)
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def last(self):
""" Returns the last batch for the batched sequence. :rtype: :class:`Batch` instance. """
|
start = max(self.number - 1, 0) * self.size
return Batch(start, self.size, self.total_size)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def number(self):
""" Returns the number of batches the batched sequence contains. :rtype: integer. """
|
return int(math.ceil(self.total_size / float(self.size)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watermark(url, args=''):
""" Returns the URL to a watermarked copy of the image specified. """
|
# initialize some variables
args = args.split(',')
params = dict(
name=args.pop(0),
opacity=0.5,
tile=False,
scale=1.0,
greyscale=False,
rotation=0,
position=None,
quality=QUALITY,
obscure=OBSCURE_ORIGINAL,
random_position_once=RANDOM_POSITION_ONCE,
)
params['url'] = unquote(url)
# iterate over all parameters to see what we need to do
for arg in args:
key, value = arg.split('=')
key, value = key.strip(), value.strip()
if key == 'position':
params['position'] = value
elif key == 'opacity':
params['opacity'] = utils._percent(value)
elif key == 'tile':
params['tile'] = bool(int(value))
elif key == 'scale':
params['scale'] = value
elif key == 'greyscale':
params['greyscale'] = bool(int(value))
elif key == 'rotation':
params['rotation'] = value
elif key == 'quality':
params['quality'] = int(value)
elif key == 'obscure':
params['obscure'] = bool(int(value))
elif key == 'random_position_once':
params['random_position_once'] = bool(int(value))
return Watermarker()(**params)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT):
"""Makes a filesystem path from the specified URL path"""
|
if url_path.startswith(settings.MEDIA_URL):
url_path = url_path[len(settings.MEDIA_URL):] # strip media root url
return os.path.normpath(os.path.join(basedir, url2pathname(url_path)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_filename(self, mark, **kwargs):
"""Comes up with a good filename for the watermarked image"""
|
kwargs = kwargs.copy()
kwargs['opacity'] = int(kwargs['opacity'] * 100)
kwargs['st_mtime'] = kwargs['fstat'].st_mtime
kwargs['st_size'] = kwargs['fstat'].st_size
params = [
'%(original_basename)s',
'wm',
'w%(watermark)i',
'o%(opacity)i',
'gs%(greyscale)i',
'r%(rotation)i',
'fm%(st_mtime)i',
'fz%(st_size)i',
'p%(position)s',
]
scale = kwargs.get('scale', None)
if scale and scale != mark.size:
params.append('_s%i' % (float(kwargs['scale'][0]) / mark.size[0] * 100))
if kwargs.get('tile', None):
params.append('_tiled')
# make thumbnail filename
filename = '%s%s' % ('_'.join(params), kwargs['ext'])
return filename % kwargs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_url_path(self, basedir, original_basename, ext, name, obscure=True):
"""Determines an appropriate watermark path"""
|
try:
hash = hashlib.sha1(smart_str(name)).hexdigest()
except TypeError:
hash = hashlib.sha1(smart_str(name).encode('utf-8')).hexdigest()
# figure out where the watermark would be saved on the filesystem
if obscure is True:
logger.debug('Obscuring original image name: %s => %s' % (name, hash))
url_path = os.path.join(basedir, hash + ext)
else:
logger.debug('Not obscuring original image name.')
url_path = os.path.join(basedir, hash, original_basename + ext)
# make sure the destination directory exists
try:
fpath = self._get_filesystem_path(url_path)
os.makedirs(os.path.dirname(fpath))
except OSError as e:
if e.errno == errno.EEXIST:
pass # not to worry, directory exists
else:
logger.error('Error creating path: %s' % traceback.format_exc())
raise
else:
logger.debug('Created directory: %s' % os.path.dirname(fpath))
return url_path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_watermark(self, target, mark, fpath, quality=QUALITY, **kwargs):
"""Create the watermarked image on the filesystem"""
|
im = utils.watermark(target, mark, **kwargs)
im.save(fpath, quality=quality)
return im
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _val(var, is_percent=False):
""" Tries to determine the appropriate value of a particular variable that is passed in. If the value is supposed to be a percentage, a whole integer will be sought after and then turned into a floating point number between 0 and 1. If the value is supposed to be an integer, the variable is cast into an integer. """
|
try:
if is_percent:
var = float(int(var.strip('%')) / 100.0)
else:
var = int(var)
except ValueError:
raise ValueError('invalid watermark parameter: ' + var)
return var
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce_opacity(img, opacity):
""" Returns an image with reduced opacity. """
|
assert opacity >= 0 and opacity <= 1
if img.mode != 'RGBA':
img = img.convert('RGBA')
else:
img = img.copy()
alpha = img.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
img.putalpha(alpha)
return img
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_scale(scale, img, mark):
""" Scales an image using a specified ratio, 'F' or 'R'. If `scale` is 'F', the image is scaled to be as big as possible to fit in `img` without falling off the edges. If `scale` is 'R', the watermark resizes to a percentage of minimum size of source image. Returns the scaled `mark`. """
|
if scale:
try:
scale = float(scale)
except (ValueError, TypeError):
pass
if isinstance(scale, six.string_types) and scale.upper() == 'F':
# scale watermark to full, but preserve the aspect ratio
scale = min(
float(img.size[0]) / mark.size[0],
float(img.size[1]) / mark.size[1]
)
elif isinstance(scale, six.string_types) and scale.upper() == 'R':
# scale watermark to % of source image and preserve the aspect ratio
scale = min(
float(img.size[0]) / mark.size[0],
float(img.size[1]) / mark.size[1]
) / 100 * settings.WATERMARK_PERCENTAGE
elif type(scale) not in (float, int):
raise ValueError('Invalid scale value "%s"! Valid values are "F" '
'for ratio-preserving scaling, "R%%" for percantage aspect '
'ratio of source image and floating-point numbers and '
'integers greater than 0.' % scale)
# determine the new width and height
w = int(mark.size[0] * float(scale))
h = int(mark.size[1] * float(scale))
# apply the new width and height, and return the new `mark`
return (w, h)
else:
return mark.size
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_rotation(rotation, mark):
""" Determines the number of degrees to rotate the watermark image. """
|
if isinstance(rotation, six.string_types) and rotation.lower() == 'r':
rotation = random.randint(0, 359)
else:
rotation = _int(rotation)
return rotation
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watermark(img, mark, position=(0, 0), opacity=1, scale=1.0, tile=False, greyscale=False, rotation=0, return_name=False, **kwargs):
"""Adds a watermark to an image"""
|
if opacity < 1:
mark = reduce_opacity(mark, opacity)
if not isinstance(scale, tuple):
scale = determine_scale(scale, img, mark)
mark = mark.resize(scale, resample=Image.ANTIALIAS)
if greyscale and mark.mode != 'LA':
mark = mark.convert('LA')
rotation = determine_rotation(rotation, mark)
if rotation != 0:
# give some leeway for rotation overlapping
new_w = int(mark.size[0] * 1.5)
new_h = int(mark.size[1] * 1.5)
new_mark = Image.new('RGBA', (new_w, new_h), (0,0,0,0))
# center the watermark in the newly resized image
new_l = int((new_w - mark.size[0]) / 2)
new_t = int((new_h - mark.size[1]) / 2)
new_mark.paste(mark, (new_l, new_t))
mark = new_mark.rotate(rotation)
position = determine_position(position, img, mark)
if img.mode != 'RGBA':
img = img.convert('RGBA')
# make sure we have a tuple for a position now
assert isinstance(position, tuple), 'Invalid position "%s"!' % position
# create a transparent layer the size of the image and draw the
# watermark in that layer.
layer = Image.new('RGBA', img.size, (0,0,0,0))
if tile:
first_y = int(position[1] % mark.size[1] - mark.size[1])
first_x = int(position[0] % mark.size[0] - mark.size[0])
for y in range(first_y, img.size[1], mark.size[1]):
for x in range(first_x, img.size[0], mark.size[0]):
layer.paste(mark, (x, y))
else:
layer.paste(mark, position)
# composite the watermark with the layer
return Image.composite(layer, img, layer)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsed_file(config_file):
"""Parse an ini-style config file."""
|
parser = ConfigParser(allow_no_value=True)
parser.readfp(config_file)
return parser
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commands(config, names):
"""Return the list of commands to run."""
|
commands = {cmd: Command(**dict((minus_to_underscore(k), v)
for k, v in config.items(cmd)))
for cmd in config.sections()
if cmd != 'packages'}
try:
return tuple(commands[x] for x in names)
except KeyError as e:
raise RuntimeError(
'Section [commands] in the config file does not contain the '
'key {.args[0]!r} you requested to execute.'.format(e))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_path(*names):
"""Path to a file in the project."""
|
return os.path.join(os.path.dirname(__file__), *names)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_osa_commit(repo, ref, rpc_product=None):
"""Get the OSA sha referenced by an RPCO Repo."""
|
osa_differ.checkout(repo, ref)
functions_path = os.path.join(repo.working_tree_dir,
'scripts/functions.sh')
release_path = os.path.join(repo.working_tree_dir,
'playbooks/vars/rpc-release.yml')
if os.path.exists(release_path):
with open(release_path) as f:
rpc_release_data = yaml.safe_load(f.read())
rpc_product_releases = rpc_release_data['rpc_product_releases']
release_data = rpc_product_releases[rpc_product]
return release_data['osa_release']
elif repo.submodules['openstack-ansible']:
return repo.submodules['openstack-ansible'].hexsha
elif os.path.exists(functions_path):
# This branch doesn't use a submodule for OSA
# Pull the SHA out of functions.sh
quoted_re = re.compile('OSA_RELEASE:-?"?([^"}]+)["}]')
with open(functions_path, "r") as funcs:
for line in funcs.readlines():
match = quoted_re.search(line)
if match:
return match.groups()[0]
else:
raise SHANotFound(
("Cannot find OSA SHA in submodule or "
"script: {}".format(functions_path)))
else:
raise SHANotFound('No OSA SHA was able to be derived.')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_report(report, args, old_commit, new_commit):
"""Publish the RST report based on the user request."""
|
# Print the report to stdout unless the user specified --quiet.
output = ""
if not args.quiet and not args.gist and not args.file:
return report
if args.gist:
gist_url = post_gist(report, old_commit, new_commit)
output += "\nReport posted to GitHub Gist: {0}".format(gist_url)
if args.file is not None:
with open(args.file, 'w') as f:
f.write(report.encode('utf-8'))
output += "\nReport written to file: {0}".format(args.file)
return output
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_rpc_differ():
"""The script starts here."""
|
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't exist already.
try:
storage_directory = osa_differ.prepare_storage_dir(args.directory)
except OSError:
print("ERROR: Couldn't create the storage directory {0}. "
"Please create it manually.".format(args.directory))
sys.exit(1)
# Prepare the rpc-openstack repository.
rpc_repo_url = args.rpc_repo_url
rpc_repo_dir = "{0}/rpc-openstack".format(storage_directory)
osa_differ.update_repo(rpc_repo_dir, rpc_repo_url, args.update)
# Validate/update the commits.
rpc_old_commit = validate_rpc_sha(rpc_repo_dir, args.old_commit[0])
rpc_new_commit = validate_rpc_sha(rpc_repo_dir, args.new_commit[0])
# Generate RPC report header.
report_rst = make_rpc_report(rpc_repo_dir,
rpc_old_commit,
rpc_new_commit,
args)
# Get the list of RPC roles from the newer and older commits.
try:
role_yaml = osa_differ.get_roles(
rpc_repo_dir,
rpc_old_commit,
args.role_requirements_old_commit
)
except IOError:
role_yaml = osa_differ.get_roles(
rpc_repo_dir,
rpc_old_commit,
ROLE_REQ_FILE
)
try:
role_yaml_latest = osa_differ.get_roles(
rpc_repo_dir,
rpc_new_commit,
args.role_requirements
)
except IOError:
role_yaml_latest = osa_differ.get_roles(
rpc_repo_dir,
rpc_new_commit,
ROLE_REQ_FILE
)
# Generate the role report.
report_rst += ("\nRPC-OpenStack Roles\n"
"-------------------")
report_rst += osa_differ.make_report(storage_directory,
role_yaml,
role_yaml_latest,
args.update,
args.version_mappings)
report_rst += "\n"
# Generate OpenStack-Ansible report.
repo = Repo(rpc_repo_dir)
osa_old_commit = get_osa_commit(repo,
rpc_old_commit,
rpc_product=args.rpc_product_old_commit)
osa_new_commit = get_osa_commit(repo,
rpc_new_commit,
rpc_product=args.rpc_product)
log.debug("OSA Commits old:{old} new:{new}".format(old=osa_old_commit,
new=osa_new_commit))
osa_repo_dir = "{0}/openstack-ansible".format(storage_directory)
# NOTE:
# An exception is thrown by osa_differ if these two commits
# are the the same, but it is sometimes necessary to compare
# two RPC tags that have the same OSA SHA. For example,
# comparing two tags that only have differences between the
# two RPCO commit, but no differences between the OSA SHAs
# that correspond to those two commits.
# To handle this case, the exception will be caught and flow
# of execution will continue normally.
try:
report_rst += osa_differ.make_osa_report(osa_repo_dir,
osa_old_commit,
osa_new_commit,
args)
except exceptions.InvalidCommitRangeException:
pass
# Get the list of OpenStack-Ansible roles from the newer and older commits.
try:
role_yaml = osa_differ.get_roles(osa_repo_dir,
osa_old_commit,
args.role_requirements_old_commit)
except IOError:
role_yaml = osa_differ.get_roles(osa_repo_dir,
osa_old_commit,
ROLE_REQ_FILE)
try:
role_yaml_latest = osa_differ.get_roles(osa_repo_dir,
osa_new_commit,
args.role_requirements)
except IOError:
role_yaml_latest = osa_differ.get_roles(osa_repo_dir,
osa_new_commit,
ROLE_REQ_FILE)
# Generate the role report.
report_rst += ("\nOpenStack-Ansible Roles\n"
"-----------------------")
report_rst += osa_differ.make_report(storage_directory,
role_yaml,
role_yaml_latest,
args.update,
args.version_mappings)
project_yaml = osa_differ.get_projects(osa_repo_dir,
osa_old_commit)
project_yaml_latest = osa_differ.get_projects(osa_repo_dir,
osa_new_commit)
# Generate the project report.
report_rst += ("OpenStack-Ansible Projects\n"
"--------------------------")
report_rst += osa_differ.make_report(storage_directory,
project_yaml,
project_yaml_latest,
args.update,
args.version_mappings)
# Publish report according to the user's request.
output = publish_report(report_rst,
args,
rpc_old_commit,
rpc_new_commit)
print(output)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(raw_args=None):
"""Console script entry point."""
|
parser = argparse.ArgumentParser(
description="poor man's integration testing")
parser.add_argument(
'cmds', metavar='cmd', default=['test'], nargs='*',
help='Run command(s) defined in the configuration file. Each command '
'is run on each package before proceeding with the next command. '
'(default: "test")')
parser.add_argument(
'-c', '--config', dest='file', type=argparse.FileType('r'),
default='toll.ini',
help='ini-style file to read the configuration from')
parser.add_argument(
'--start-at', dest='start_at', type=str, default='',
help='Skip over the packages in the config file listed before this'
' one. (It does a substring match to find the first package.)')
args = parser.parse_args(raw_args)
config_file = config.parsed_file(args.file)
commands = config.commands(config_file, args.cmds)
packages = config.packages(config_file)
runner = Runner(commands, packages, start_at=args.start_at)
return runner()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, list):
""" Removes a list from the site. """
|
xml = SP.DeleteList(SP.listName(list.id))
self.opener.post_soap(LIST_WEBSERVICE, xml,
soapaction='http://schemas.microsoft.com/sharepoint/soap/DeleteList')
self.all_lists.remove(list)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name, description='', template=100):
""" Creates a new list in the site. """
|
try:
template = int(template)
except ValueError:
template = LIST_TEMPLATES[template]
if name in self:
raise ValueError("List already exists: '{0}".format(name))
if uuid_re.match(name):
raise ValueError("Cannot create a list with a UUID as a name")
xml = SP.AddList(SP.listName(name),
SP.description(description),
SP.templateID(text_type(template)))
result = self.opener.post_soap(LIST_WEBSERVICE, xml,
soapaction='http://schemas.microsoft.com/sharepoint/soap/AddList')
list_element = result.xpath('sp:AddListResult/sp:List', namespaces=namespaces)[0]
self._all_lists.append(SharePointList(self.opener, self, list_element))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.