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 branch(self):
""" Get a flattened representation of the branch. @return: A flat list of nodes. @rtype: [L{Element},..] """ |
branch = [self]
for c in self.children:
branch += c.branch()
return branch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ancestors(self):
""" Get a list of ancestors. @return: A list of ancestors. @rtype: [L{Element},..] """ |
ancestors = []
p = self.parent
while p is not None:
ancestors.append(p)
p = p.parent
return ancestors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def walk(self, visitor):
""" Walk the branch and call the visitor function on each node. @param visitor: A function. @return: self @rtype: L{Element} """ |
visitor(self)
for c in self.children:
c.walk(visitor)
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:
def prune(self):
""" Prune the branch of empty nodes. """ |
pruned = []
for c in self.children:
c.prune()
if c.isempty(False):
pruned.append(c)
for p in pruned:
self.children.remove(p) |
<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):
""" Get the next child. @return: The next child. @rtype: L{Element} @raise StopIterator: At the end. """ |
try:
child = self.children[self.pos]
self.pos += 1
return child
except:
raise StopIteration() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pset(self, n):
""" Convert the nodes nsprefixes into a set. @param n: A node. @type n: L{Element} @return: A set of namespaces. @rtype: set """ |
s = set()
for ns in n.nsprefixes.items():
if self.permit(ns):
s.add(ns[1])
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tostr(self, object, indent=-2):
""" get s string representation of object """ |
history = []
return self.process(object, history, indent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attributes(self, filter=Filter()):
""" Get only the attribute content. @param filter: A filter to constrain the result. @type filter: L{Filter} @return: A list of tuples (attr, ancestry) @rtype: [(L{SchemaObject}, [L{SchemaObject},..]),..] """ |
result = []
for child, ancestry in self:
if child.isattr() and child in filter:
result.append((child, ancestry))
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 namespace(self, prefix=None):
""" Get this properties namespace @param prefix: The default prefix. @type prefix: str @return: The schema's target namespace @rtype: (I{prefix},I{URI}) """ |
ns = self.schema.tns
if ns[0] is None:
ns = (prefix, ns[1])
return ns |
<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(self, qref, classes=()):
""" Find a referenced type in self or children. @param qref: A qualified reference. @type qref: qref @param classes: A list of classes used to qualify the match. @return: The referenced type. @rtype: L{SchemaObject} @see: L{qualify()} """ |
if not len(classes):
classes = (self.__class__,)
if self.qname == qref and self.__class__ in classes:
return self
for c in self.rawchildren:
p = c.find(qref, classes)
if p is not None:
return p
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 merge(self, other):
""" Merge another object as needed. """ |
other.qualify()
for n in ('name',
'qname',
'min',
'max',
'default',
'type',
'nillable',
'form_qualified',):
if getattr(self, n) is not None:
continue
v = getattr(other, n)
if v is None:
continue
setattr(self, n, v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str(self, indent=0, history=None):
""" Get a string representation of this object. @param indent: The indent. @type indent: int @return: A string. @rtype: str """ |
if history is None:
history = []
if self in history:
return '%s ...' % Repr(self)
history.append(self)
tab = '%*s' % (indent * 3, '')
result = []
result.append('%s<%s' % (tab, self.id))
for n in self.description():
if not hasattr(self, n):
continue
v = getattr(self, n)
if v is None:
continue
result.append(' %s="%s"' % (n, v))
if len(self):
result.append('>')
for c in self.rawchildren:
result.append('\n')
result.append(c.str(indent+1, history[:]))
if c.isattr():
result.append('@')
result.append('\n%s' % tab)
result.append('</%s>' % self.__class__.__name__)
else:
result.append(' />')
return ''.join(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 find(self, node, list):
""" Traverse the tree looking for matches. @param node: A node to match on. @type node: L{SchemaObject} @param list: A list to fill. @type list: list """ |
if self.matcher.match(node):
list.append(node)
self.limit -= 1
if self.limit == 0:
return
for c in node.rawchildren:
self.find(c, list)
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:
def setduration(self, **duration):
""" Set the caching duration which defines how long the file will be cached. @param duration: The cached file duration which defines how long the file will be cached. A duration=0 means forever. The duration may be: (months|weeks|days|hours|minutes|seconds). @type duration: {unit:value} """ |
if len(duration) == 1:
arg = [x[0] for x in duration.items()]
if not arg[0] in self.units:
raise Exception('must be: %s' % str(self.units))
self.duration = arg
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:
def sort(self, content):
""" Sort suds object attributes based on ordering defined in the XSD type information. @param content: The content to sort. @type content: L{Object} @return: self @rtype: L{Typed} """ |
v = content.value
if isinstance(v, Object):
md = v.__metadata__
md.ordering = self.ordering(content.real)
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:
def ordering(self, type):
""" Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list """ |
result = []
for child, ancestry in type.resolve():
name = child.name
if child.name is None:
continue
if child.isattr():
name = '_%s' % child.name
result.append(name)
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 build(self, name):
"build an object for the specified typename as defined in the schema"
if isinstance(name, basestring):
type = self.resolver.find(name)
if type is None:
raise TypeNotFound(name)
else:
type = name
cls = type.name
if type.mixed():
data = Factory.property(cls)
else:
data = Factory.object(cls)
resolved = type.resolve()
md = data.__metadata__
md.sxtype = resolved
md.ordering = self.ordering(resolved)
history = []
self.add_attributes(data, resolved)
for child, ancestry in type.children():
if self.skip_child(child, ancestry):
continue
self.process(data, child, history[:])
return data |
<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_attributes(self, data, type):
""" add required attributes """ |
for attr, ancestry in type.attributes():
name = '_%s' % attr.name
value = attr.get_default()
setattr(data, name, 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 validate(self, pA, pB):
""" Validate that the two properties may be linked. @param pA: Endpoint (A) to link. @type pA: L{Endpoint} @param pB: Endpoint (B) to link. @type pB: L{Endpoint} @return: self @rtype: L{Link} """ |
if pA in pB.links or \
pB in pA.links:
raise Exception('Already linked')
dA = pA.domains()
dB = pB.domains()
for d in dA:
if d in dB:
raise Exception('Duplicate domain "%s" found' % d)
for d in dB:
if d in dA:
raise Exception('Duplicate domain "%s" found' % d)
kA = pA.keys()
kB = pB.keys()
for k in kA:
if k in kB:
raise Exception('Duplicate key %s found' % k)
for k in kB:
if k in kA:
raise Exception('Duplicate key %s found' % k)
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:
def prime(self):
""" Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties} """ |
for d in self.definitions.values():
self.defined[d.name] = d.default
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:
def list_scanners(zap_helper, scanners):
"""Get a list of scanners and whether or not they are enabled.""" |
scanner_list = zap_helper.zap.ascan.scanners()
if scanners is not None and 'all' not in scanners:
scanner_list = filter_by_ids(scanner_list, scanners)
click.echo(tabulate([[s['id'], s['name'], s['policyId'], s['enabled'], s['attackStrength'], s['alertThreshold']]
for s in scanner_list],
headers=['ID', 'Name', 'Policy ID', 'Enabled', 'Strength', 'Threshold'],
tablefmt='grid')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scanner_strength(zap_helper, scanners, strength):
"""Set the attack strength for scanners.""" |
if not scanners or 'all' in scanners:
scanners = _get_all_scanner_ids(zap_helper)
with zap_error_handler():
zap_helper.set_scanner_attack_strength(scanners, strength)
console.info('Set attack strength to {0}.'.format(strength)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scanner_threshold(zap_helper, scanners, threshold):
"""Set the alert threshold for scanners.""" |
if not scanners or 'all' in scanners:
scanners = _get_all_scanner_ids(zap_helper)
with zap_error_handler():
zap_helper.set_scanner_alert_threshold(scanners, threshold)
console.info('Set alert threshold to {0}.'.format(threshold)) |
<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_all_scanner_ids(zap_helper):
"""Get all scanner IDs.""" |
scanners = zap_helper.zap.ascan.scanners()
return [s['id'] for s in scanners] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_policies(zap_helper, policy_ids):
""" Get a list of policies and whether or not they are enabled. """ |
policies = filter_by_ids(zap_helper.zap.ascan.policies(), policy_ids)
click.echo(tabulate([[p['id'], p['name'], p['enabled'], p['attackStrength'], p['alertThreshold']]
for p in policies],
headers=['ID', 'Name', 'Enabled', 'Strength', 'Threshold'],
tablefmt='grid')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_policies(zap_helper, policy_ids):
""" Set the enabled policies to use in a scan. When you enable a selection of policies, all other policies are disabled. """ |
if not policy_ids:
policy_ids = _get_all_policy_ids(zap_helper)
with zap_error_handler():
zap_helper.enable_policies_by_ids(policy_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_policy_strength(zap_helper, policy_ids, strength):
"""Set the attack strength for policies.""" |
if not policy_ids:
policy_ids = _get_all_policy_ids(zap_helper)
with zap_error_handler():
zap_helper.set_policy_attack_strength(policy_ids, strength)
console.info('Set attack strength to {0}.'.format(strength)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_policy_threshold(zap_helper, policy_ids, threshold):
"""Set the alert threshold for policies.""" |
if not policy_ids:
policy_ids = _get_all_policy_ids(zap_helper)
with zap_error_handler():
zap_helper.set_policy_alert_threshold(policy_ids, threshold)
console.info('Set alert threshold to {0}.'.format(threshold)) |
<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_all_policy_ids(zap_helper):
"""Get all policy IDs.""" |
policies = zap_helper.zap.ascan.policies()
return [p['id'] for p in policies] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, options=None):
"""Start the ZAP Daemon.""" |
if self.is_running():
self.logger.warn('ZAP is already running on port {0}'.format(self.port))
return
if platform.system() == 'Windows' or platform.system().startswith('CYGWIN'):
executable = 'zap.bat'
else:
executable = 'zap.sh'
executable_path = os.path.join(self.zap_path, executable)
if not os.path.isfile(executable_path):
raise ZAPError(('ZAP was not found in the path "{0}". You can set the path to where ZAP is ' +
'installed on your system using the --zap-path command line parameter or by ' +
'default using the ZAP_PATH environment variable.').format(self.zap_path))
zap_command = [executable_path, '-daemon', '-port', str(self.port)]
if options:
extra_options = shlex.split(options)
zap_command += extra_options
if self.log_path is None:
log_path = os.path.join(self.zap_path, 'zap.log')
else:
log_path = os.path.join(self.log_path, 'zap.log')
self.logger.debug('Starting ZAP process with command: {0}.'.format(' '.join(zap_command)))
self.logger.debug('Logging to {0}'.format(log_path))
with open(log_path, 'w+') as log_file:
subprocess.Popen(
zap_command, cwd=self.zap_path, stdout=log_file,
stderr=subprocess.STDOUT)
self.wait_for_zap(self.timeout)
self.logger.debug('ZAP started successfully.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self):
"""Shutdown ZAP.""" |
if not self.is_running():
self.logger.warn('ZAP is not running.')
return
self.logger.debug('Shutting down ZAP.')
self.zap.core.shutdown()
timeout_time = time.time() + self.timeout
while self.is_running():
if time.time() > timeout_time:
raise ZAPError('Timed out waiting for ZAP to shutdown.')
time.sleep(2)
self.logger.debug('ZAP shutdown successfully.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_zap(self, timeout):
"""Wait for ZAP to be ready to receive API calls.""" |
timeout_time = time.time() + timeout
while not self.is_running():
if time.time() > timeout_time:
raise ZAPError('Timed out waiting for ZAP to start.')
time.sleep(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_running(self):
"""Check if ZAP is running.""" |
try:
result = requests.get(self.proxy_url)
except RequestException:
return False
if 'ZAP-Header' in result.headers.get('Access-Control-Allow-Headers', []):
return True
raise ZAPError('Another process is listening on {0}'.format(self.proxy_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 open_url(self, url, sleep_after_open=2):
"""Access a URL through ZAP.""" |
self.zap.urlopen(url)
# Give the sites tree a chance to get updated
time.sleep(sleep_after_open) |
<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_spider(self, target_url, context_name=None, user_name=None):
"""Run spider against a URL.""" |
self.logger.debug('Spidering target {0}...'.format(target_url))
context_id, user_id = self._get_context_and_user_ids(context_name, user_name)
if user_id:
self.logger.debug('Running spider in context {0} as user {1}'.format(context_id, user_id))
scan_id = self.zap.spider.scan_as_user(context_id, user_id, target_url)
else:
scan_id = self.zap.spider.scan(target_url)
if not scan_id:
raise ZAPError('Error running spider.')
elif not scan_id.isdigit():
raise ZAPError('Error running spider: "{0}"'.format(scan_id))
self.logger.debug('Started spider with ID {0}...'.format(scan_id))
while int(self.zap.spider.status()) < 100:
self.logger.debug('Spider progress %: {0}'.format(self.zap.spider.status()))
time.sleep(self._status_check_sleep)
self.logger.debug('Spider #{0} completed'.format(scan_id)) |
<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_active_scan(self, target_url, recursive=False, context_name=None, user_name=None):
"""Run an active scan against a URL.""" |
self.logger.debug('Scanning target {0}...'.format(target_url))
context_id, user_id = self._get_context_and_user_ids(context_name, user_name)
if user_id:
self.logger.debug('Scanning in context {0} as user {1}'.format(context_id, user_id))
scan_id = self.zap.ascan.scan_as_user(target_url, context_id, user_id, recursive)
else:
scan_id = self.zap.ascan.scan(target_url, recurse=recursive)
if not scan_id:
raise ZAPError('Error running active scan.')
elif not scan_id.isdigit():
raise ZAPError(('Error running active scan: "{0}". Make sure the URL is in the site ' +
'tree by using the open-url or scanner commands before running an active ' +
'scan.').format(scan_id))
self.logger.debug('Started scan with ID {0}...'.format(scan_id))
while int(self.zap.ascan.status()) < 100:
self.logger.debug('Scan progress %: {0}'.format(self.zap.ascan.status()))
time.sleep(self._status_check_sleep)
self.logger.debug('Scan #{0} completed'.format(scan_id)) |
<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_ajax_spider(self, target_url):
"""Run AJAX Spider against a URL.""" |
self.logger.debug('AJAX Spidering target {0}...'.format(target_url))
self.zap.ajaxSpider.scan(target_url)
while self.zap.ajaxSpider.status == 'running':
self.logger.debug('AJAX Spider: {0}'.format(self.zap.ajaxSpider.status))
time.sleep(self._status_check_sleep)
self.logger.debug('AJAX Spider completed') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alerts(self, alert_level='High'):
"""Get a filtered list of alerts at the given alert level, and sorted by alert level.""" |
alerts = self.zap.core.alerts()
alert_level_value = self.alert_levels[alert_level]
alerts = sorted((a for a in alerts if self.alert_levels[a['risk']] >= alert_level_value),
key=lambda k: self.alert_levels[k['risk']], reverse=True)
return alerts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enabled_scanner_ids(self):
"""Retrieves a list of currently enabled scanners.""" |
enabled_scanners = []
scanners = self.zap.ascan.scanners()
for scanner in scanners:
if scanner['enabled'] == 'true':
enabled_scanners.append(scanner['id'])
return enabled_scanners |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_scanners_by_ids(self, scanner_ids):
"""Enable a list of scanner IDs.""" |
scanner_ids = ','.join(scanner_ids)
self.logger.debug('Enabling scanners with IDs {0}'.format(scanner_ids))
return self.zap.ascan.enable_scanners(scanner_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_scanners_by_ids(self, scanner_ids):
"""Disable a list of scanner IDs.""" |
scanner_ids = ','.join(scanner_ids)
self.logger.debug('Disabling scanners with IDs {0}'.format(scanner_ids))
return self.zap.ascan.disable_scanners(scanner_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_scanners_by_group(self, group):
""" Enables the scanners in the group if it matches one in the scanner_group_map. """ |
if group == 'all':
self.logger.debug('Enabling all scanners')
return self.zap.ascan.enable_all_scanners()
try:
scanner_list = self.scanner_group_map[group]
except KeyError:
raise ZAPError(
'Invalid group "{0}" provided. Valid groups are: {1}'.format(
group, ', '.join(self.scanner_groups)
)
)
self.logger.debug('Enabling scanner group {0}'.format(group))
return self.enable_scanners_by_ids(scanner_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 disable_scanners_by_group(self, group):
""" Disables the scanners in the group if it matches one in the scanner_group_map. """ |
if group == 'all':
self.logger.debug('Disabling all scanners')
return self.zap.ascan.disable_all_scanners()
try:
scanner_list = self.scanner_group_map[group]
except KeyError:
raise ZAPError(
'Invalid group "{0}" provided. Valid groups are: {1}'.format(
group, ', '.join(self.scanner_groups)
)
)
self.logger.debug('Disabling scanner group {0}'.format(group))
return self.disable_scanners_by_ids(scanner_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 set_scanner_attack_strength(self, scanner_ids, attack_strength):
"""Set the attack strength for the given scanners.""" |
for scanner_id in scanner_ids:
self.logger.debug('Setting strength for scanner {0} to {1}'.format(scanner_id, attack_strength))
result = self.zap.ascan.set_scanner_attack_strength(scanner_id, attack_strength)
if result != 'OK':
raise ZAPError('Error setting strength for scanner with ID {0}: {1}'.format(scanner_id, 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 enable_policies_by_ids(self, policy_ids):
"""Set enabled policy from a list of IDs.""" |
policy_ids = ','.join(policy_ids)
self.logger.debug('Setting enabled policies to IDs {0}'.format(policy_ids))
self.zap.ascan.set_enabled_policies(policy_ids) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_policy_attack_strength(self, policy_ids, attack_strength):
"""Set the attack strength for the given policies.""" |
for policy_id in policy_ids:
self.logger.debug('Setting strength for policy {0} to {1}'.format(policy_id, attack_strength))
result = self.zap.ascan.set_policy_attack_strength(policy_id, attack_strength)
if result != 'OK':
raise ZAPError('Error setting strength for policy with ID {0}: {1}'.format(policy_id, 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 exclude_from_all(self, exclude_regex):
"""Exclude a pattern from proxy, spider and active scanner.""" |
try:
re.compile(exclude_regex)
except re.error:
raise ZAPError('Invalid regex "{0}" provided'.format(exclude_regex))
self.logger.debug('Excluding {0} from proxy, spider and active scanner.'.format(exclude_regex))
self.zap.core.exclude_from_proxy(exclude_regex)
self.zap.spider.exclude_from_scan(exclude_regex)
self.zap.ascan.exclude_from_scan(exclude_regex) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xml_report(self, file_path):
"""Generate and save XML report""" |
self.logger.debug('Generating XML report')
report = self.zap.core.xmlreport()
self._write_report(report, file_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 md_report(self, file_path):
"""Generate and save MD report""" |
self.logger.debug('Generating MD report')
report = self.zap.core.mdreport()
self._write_report(report, file_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 html_report(self, file_path):
"""Generate and save HTML report.""" |
self.logger.debug('Generating HTML report')
report = self.zap.core.htmlreport()
self._write_report(report, file_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 _write_report(report, file_path):
"""Write report to the given file path.""" |
with open(file_path, mode='wb') as f:
if not isinstance(report, binary_type):
report = report.encode('utf-8')
f.write(report) |
<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_context_info(self, context_name):
"""Get the context ID for a given context name.""" |
context_info = self.zap.context.context(context_name)
if not isinstance(context_info, dict):
raise ZAPError('Context with name "{0}" wasn\'t found'.format(context_name))
return context_info |
<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_context_and_user_ids(self, context_name, user_name):
"""Helper to get the context ID and user ID from the given names.""" |
if context_name is None:
return None, None
context_id = self.get_context_info(context_name)['id']
user_id = None
if user_name:
user_id = self._get_user_id_from_name(context_id, user_name)
return context_id, user_id |
<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_user_id_from_name(self, context_id, user_name):
"""Get a user ID from the user name.""" |
users = self.zap.users.users_list(context_id)
for user in users:
if user['name'] == user_name:
return user['id']
raise ZAPError('No user with the name "{0}"" was found for context {1}'.format(user_name, context_id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_scripts(zap_helper):
"""List scripts currently loaded into ZAP.""" |
scripts = zap_helper.zap.script.list_scripts
output = []
for s in scripts:
if 'enabled' not in s:
s['enabled'] = 'N/A'
output.append([s['name'], s['type'], s['engine'], s['enabled']])
click.echo(tabulate(output, headers=['Name', 'Type', 'Engine', 'Enabled'], tablefmt='grid')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_engines(zap_helper):
"""List engines that can be used to run scripts.""" |
engines = zap_helper.zap.script.list_engines
console.info('Available engines: {}'.format(', '.join(engines))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_script(zap_helper, script_name):
"""Enable a script.""" |
with zap_error_handler():
console.debug('Enabling script "{0}"'.format(script_name))
result = zap_helper.zap.script.enable(script_name)
if result != 'OK':
raise ZAPError('Error enabling script: {0}'.format(result))
console.info('Script "{0}" enabled'.format(script_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 disable_script(zap_helper, script_name):
"""Disable a script.""" |
with zap_error_handler():
console.debug('Disabling script "{0}"'.format(script_name))
result = zap_helper.zap.script.disable(script_name)
if result != 'OK':
raise ZAPError('Error disabling script: {0}'.format(result))
console.info('Script "{0}" disabled'.format(script_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 remove_script(zap_helper, script_name):
"""Remove a script.""" |
with zap_error_handler():
console.debug('Removing script "{0}"'.format(script_name))
result = zap_helper.zap.script.remove(script_name)
if result != 'OK':
raise ZAPError('Error removing script: {0}'.format(result))
console.info('Script "{0}" removed'.format(script_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 load_script(zap_helper, **options):
"""Load a script from a file.""" |
with zap_error_handler():
if not os.path.isfile(options['file_path']):
raise ZAPError('No file found at "{0}", cannot load script.'.format(options['file_path']))
if not _is_valid_script_engine(zap_helper.zap, options['engine']):
engines = zap_helper.zap.script.list_engines
raise ZAPError('Invalid script engine provided. Valid engines are: {0}'.format(', '.join(engines)))
console.debug('Loading script "{0}" from "{1}"'.format(options['name'], options['file_path']))
result = zap_helper.zap.script.load(options['name'], options['script_type'], options['engine'],
options['file_path'], scriptdescription=options['description'])
if result != 'OK':
raise ZAPError('Error loading script: {0}'.format(result))
console.info('Script "{0}" loaded'.format(options['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 _is_valid_script_engine(zap, engine):
"""Check if given script engine is valid.""" |
engine_names = zap.script.list_engines
short_names = [e.split(' : ')[1] for e in engine_names]
return engine in engine_names or engine in short_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 start_zap_daemon(zap_helper, start_options):
"""Helper to start the daemon using the current config.""" |
console.info('Starting ZAP daemon')
with helpers.zap_error_handler():
zap_helper.start(options=start_options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_status(zap_helper, timeout):
""" Check if ZAP is running and able to receive API calls. You can provide a timeout option which is the amount of time in seconds the command should wait for ZAP to start if it is not currently running. This is useful to run before calling other commands if ZAP was started outside of zap-cli. For example: zap-cli status -t 60 && zap-cli open-url "http://127.0.0.1/" Exits with code 1 if ZAP is either not running or the command timed out waiting for ZAP to start. """ |
with helpers.zap_error_handler():
if zap_helper.is_running():
console.info('ZAP is running')
elif timeout is not None:
zap_helper.wait_for_zap(timeout)
console.info('ZAP is running')
else:
console.error('ZAP is not running')
sys.exit(2) |
<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_url(zap_helper, url):
"""Open a URL using the ZAP proxy.""" |
console.info('Accessing URL {0}'.format(url))
zap_helper.open_url(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 spider_url(zap_helper, url, context_name, user_name):
"""Run the spider against a URL.""" |
console.info('Running spider...')
with helpers.zap_error_handler():
zap_helper.run_spider(url, context_name, user_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 active_scan(zap_helper, url, scanners, recursive, context_name, user_name):
""" Run an Active Scan against a URL. The URL to be scanned must be in ZAP's site tree, i.e. it should have already been opened using the open-url command or found by running the spider command. """ |
console.info('Running an active scan...')
with helpers.zap_error_handler():
if scanners:
zap_helper.set_enabled_scanners(scanners)
zap_helper.run_active_scan(url, recursive, context_name, user_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 show_alerts(zap_helper, alert_level, output_format, exit_code):
"""Show alerts at the given alert level.""" |
alerts = zap_helper.alerts(alert_level)
helpers.report_alerts(alerts, output_format)
if exit_code:
code = 1 if len(alerts) > 0 else 0
sys.exit(code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quick_scan(zap_helper, url, **options):
""" Run a quick scan of a site by opening a URL, optionally spidering the URL, running an Active Scan, and reporting any issues found. This command contains most scan options as parameters, so you can do everything in one go. If any alerts are found for the given alert level, this command will exit with a status code of 1. """ |
if options['self_contained']:
console.info('Starting ZAP daemon')
with helpers.zap_error_handler():
zap_helper.start(options['start_options'])
console.info('Running a quick scan for {0}'.format(url))
with helpers.zap_error_handler():
if options['scanners']:
zap_helper.set_enabled_scanners(options['scanners'])
if options['exclude']:
zap_helper.exclude_from_all(options['exclude'])
zap_helper.open_url(url)
if options['spider']:
zap_helper.run_spider(url, options['context_name'], options['user_name'])
if options['ajax_spider']:
zap_helper.run_ajax_spider(url)
zap_helper.run_active_scan(url, options['recursive'], options['context_name'], options['user_name'])
alerts = zap_helper.alerts(options['alert_level'])
helpers.report_alerts(alerts, options['output_format'])
if options['self_contained']:
console.info('Shutting down ZAP daemon')
with helpers.zap_error_handler():
zap_helper.shutdown()
exit_code = 1 if len(alerts) > 0 else 0
sys.exit(exit_code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report(zap_helper, output, output_format):
"""Generate XML, MD or HTML report.""" |
if output_format == 'html':
zap_helper.html_report(output)
elif output_format == 'md':
zap_helper.md_report(output)
else:
zap_helper.xml_report(output)
console.info('Report saved to "{0}"'.format(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 validate_ids(ctx, param, value):
"""Validate a list of IDs and convert them to a list.""" |
if not value:
return None
ids = [x.strip() for x in value.split(',')]
for id_item in ids:
if not id_item.isdigit():
raise click.BadParameter('Non-numeric value "{0}" provided for an ID.'.format(id_item))
return ids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_scanner_list(ctx, param, value):
""" Validate a comma-separated list of scanners and extract it into a list of groups and IDs. """ |
if not value:
return None
valid_groups = ctx.obj.scanner_groups
scanners = [x.strip() for x in value.split(',')]
if 'all' in scanners:
return ['all']
scanner_ids = []
for scanner in scanners:
if scanner.isdigit():
scanner_ids.append(scanner)
elif scanner in valid_groups:
scanner_ids += ctx.obj.scanner_group_map[scanner]
else:
raise click.BadParameter('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.'
.format(scanner))
return scanner_ids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_regex(ctx, param, value):
""" Validate that a provided regex compiles. """ |
if not value:
return None
try:
re.compile(value)
except re.error:
raise click.BadParameter('Invalid regex "{0}" provided'.format(value))
return 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 report_alerts(alerts, output_format='table'):
""" Print our alerts in the given format. """ |
num_alerts = len(alerts)
if output_format == 'json':
click.echo(json.dumps(alerts, indent=4))
else:
console.info('Issues found: {0}'.format(num_alerts))
if num_alerts > 0:
click.echo(tabulate([[a['alert'], a['risk'], a['cweid'], a['url']] for a in alerts],
headers=['Alert', 'Risk', 'CWE ID', 'URL'], tablefmt='grid')) |
<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_by_ids(original_list, ids_to_filter):
"""Filter a list of dicts by IDs using an id key on each dict.""" |
if not ids_to_filter:
return original_list
return [i for i in original_list if i['id'] in ids_to_filter] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_session(zap_helper, file_path):
"""Save the session.""" |
console.debug('Saving the session to "{0}"'.format(file_path))
zap_helper.zap.core.save_session(file_path, overwrite='true') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_session(zap_helper, file_path):
"""Load a given session.""" |
with zap_error_handler():
if not os.path.isfile(file_path):
raise ZAPError('No file found at "{0}", cannot load session.'.format(file_path))
console.debug('Loading session from "{0}"'.format(file_path))
zap_helper.zap.core.load_session(file_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 context_list(zap_helper):
"""List the available contexts.""" |
contexts = zap_helper.zap.context.context_list
if len(contexts):
console.info('Available contexts: {0}'.format(contexts[1:-1]))
else:
console.info('No contexts available in the current session') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_new(zap_helper, name):
"""Create a new context.""" |
console.info('Creating context with name: {0}'.format(name))
res = zap_helper.zap.context.new_context(contextname=name)
console.info('Context "{0}" created with ID: {1}'.format(name, res)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_include(zap_helper, name, pattern):
"""Include a pattern in a given context.""" |
console.info('Including regex {0} in context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.include_in_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Including regex from context failed: {}'.format(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 context_exclude(zap_helper, name, pattern):
"""Exclude a pattern from a given context.""" |
console.info('Excluding regex {0} from context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.exclude_from_context(contextname=name, regex=pattern)
if result != 'OK':
raise ZAPError('Excluding regex from context failed: {}'.format(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 context_info(zap_helper, context_name):
"""Get info about the given context.""" |
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
console.info('ID: {}'.format(info['id']))
console.info('Name: {}'.format(info['name']))
console.info('Authentication type: {}'.format(info['authType']))
console.info('Included regexes: {}'.format(info['includeRegexs']))
console.info('Excluded regexes: {}'.format(info['excludeRegexs'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_list_users(zap_helper, context_name):
"""List the users available for a given context.""" |
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for user in users])
console.info('Available users for the context {0}: {1}'.format(context_name, user_list))
else:
console.info('No users configured for the context {}'.format(context_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 context_import(zap_helper, file_path):
"""Import a saved context file.""" |
with zap_error_handler():
result = zap_helper.zap.context.import_context(file_path)
if not result.isdigit():
raise ZAPError('Importing context from file failed: {}'.format(result))
console.info('Imported context from {}'.format(file_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 context_export(zap_helper, name, file_path):
"""Export a given context to a file.""" |
with zap_error_handler():
result = zap_helper.zap.context.export_context(name, file_path)
if result != 'OK':
raise ZAPError('Exporting context to file failed: {}'.format(result))
console.info('Exported context {0} to {1}'.format(name, file_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 _get_value(obj, key, default=missing):
"""Slightly-modified version of marshmallow.utils.get_value. If a dot-delimited ``key`` is passed and any attribute in the path is `None`, return `None`. """ |
if "." in key:
return _get_value_for_keys(obj, key.split("."), default)
else:
return _get_value_for_key(obj, key, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rapply(d, func, *args, **kwargs):
"""Apply a function to all values in a dictionary or list of dictionaries, recursively.""" |
if isinstance(d, (tuple, list)):
return [_rapply(each, func, *args, **kwargs) for each in d]
if isinstance(d, dict):
return {
key: _rapply(value, func, *args, **kwargs) for key, value in iteritems(d)
}
else:
return func(d, *args, **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 _url_val(val, key, obj, **kwargs):
"""Function applied by `HyperlinksField` to get the correct value in the schema. """ |
if isinstance(val, URLFor):
return val.serialize(key, obj, **kwargs)
else:
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attach_fields(obj):
"""Attach all the marshmallow fields classes to ``obj``, including Flask-Marshmallow's custom fields. """ |
for attr in base_fields.__all__:
if not hasattr(obj, attr):
setattr(obj, attr, getattr(base_fields, attr))
for attr in fields.__all__:
setattr(obj, attr, getattr(fields, 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 init_app(self, app):
"""Initializes the application with the extension. :param Flask app: The Flask application object. """ |
app.extensions = getattr(app, "extensions", {})
# If using Flask-SQLAlchemy, attach db.session to ModelSchema
if has_sqla and "sqlalchemy" in app.extensions:
db = app.extensions["sqlalchemy"].db
self.ModelSchema.OPTIONS_CLASS.session = db.session
app.extensions[EXTENSION_NAME] = 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 jsonify(self, obj, many=sentinel, *args, **kwargs):
"""Return a JSON response containing the serialized data. :param obj: Object to serialize. :param bool many: Whether `obj` should be serialized as an instance or as a collection. If unset, defaults to the value of the `many` attribute on this Schema. :param kwargs: Additional keyword arguments passed to `flask.jsonify`. .. versionchanged:: 0.6.0 Takes the same arguments as `marshmallow.Schema.dump`. Additional keyword arguments are passed to `flask.jsonify`. .. versionchanged:: 0.6.3 The `many` argument for this method defaults to the value of the `many` attribute on the Schema. Previously, the `many` argument of this method defaulted to False, regardless of the value of `Schema.many`. """ |
if many is sentinel:
many = self.many
if _MARSHMALLOW_VERSION_INFO[0] >= 3:
data = self.dump(obj, many=many)
else:
data = self.dump(obj, many=many).data
return flask.jsonify(data, *args, **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 _hjoin_multiline(join_char, strings):
"""Horizontal join of multiline strings """ |
cstrings = [string.split("\n") for string in strings]
max_num_lines = max(len(item) for item in cstrings)
pp = []
for k in range(max_num_lines):
p = [cstring[k] for cstring in cstrings]
pp.append(join_char + join_char.join(p) + join_char)
return "\n".join([p.rstrip() for p in pp]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks(raw):
"""Yield successive EVENT_SIZE sized chunks from raw.""" |
for i in range(0, len(raw), EVENT_SIZE):
yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_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 convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval.""" |
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.floor(whole)
return seconds, microseconds |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quartz_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using newer Quartz.""" |
# Quartz only on the mac, so don't warn about Quartz
# pylint: disable=import-error
import Quartz
# pylint: disable=no-member
class QuartzMouseListener(QuartzMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Constants below listed at:
https://developer.apple.com/documentation/coregraphics/
cgeventtype?language=objc#topics
"""
# Keep Mac Names to make it easy to find the documentation
# pylint: disable=invalid-name
NSMachPort = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletPointer) |
Quartz.CGEventMaskBit(Quartz.kCGEventTabletProximity) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDragged),
self.handle_input,
None)
CFRunLoopSourceRef = Quartz.CFMachPortCreateRunLoopSource(
None,
NSMachPort,
0)
CFRunLoopRef = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(
CFRunLoopRef,
CFRunLoopSourceRef,
Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(
NSMachPort,
True)
def listen(self):
"""Listen for quartz events."""
while self.active:
Quartz.CFRunLoopRunInMode(
Quartz.kCFRunLoopDefaultMode, 5, False)
def uninstall_handle_input(self):
self.active = False
def _get_mouse_button_number(self, event):
"""Get the mouse button number from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventButtonNumber)
def _get_click_state(self, event):
"""The click state from an event."""
return Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventClickState)
def _get_scroll(self, event):
"""The scroll values from an event."""
scroll_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis1)
scroll_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGScrollWheelEventDeltaAxis2)
return scroll_x, scroll_y
def _get_absolute(self, event):
"""Get abolute cursor location."""
return Quartz.CGEventGetLocation(event)
def _get_relative(self, event):
"""Get the relative mouse movement."""
delta_x = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaX)
delta_y = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGMouseEventDeltaY)
return delta_x, delta_y
mouse = QuartzMouseListener(pipe)
mouse.listen() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def appkit_mouse_process(pipe):
"""Single subprocess for reading mouse events on Mac using older AppKit.""" |
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from Foundation import NSObject
from AppKit import NSApplication, NSApp
from Cocoa import (NSEvent, NSLeftMouseDownMask,
NSLeftMouseUpMask, NSRightMouseDownMask,
NSRightMouseUpMask, NSMouseMovedMask,
NSLeftMouseDraggedMask,
NSRightMouseDraggedMask, NSMouseEnteredMask,
NSMouseExitedMask, NSScrollWheelMask,
NSOtherMouseDownMask, NSOtherMouseUpMask)
from PyObjCTools import AppHelper
import objc
class MacMouseSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacMouseSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the listen method as the handler for mouse events."""
mask = (NSLeftMouseDownMask | NSLeftMouseUpMask |
NSRightMouseDownMask | NSRightMouseUpMask |
NSMouseMovedMask | NSLeftMouseDraggedMask |
NSRightMouseDraggedMask | NSScrollWheelMask |
NSMouseEnteredMask | NSMouseExitedMask |
NSOtherMouseDownMask | NSOtherMouseUpMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacMouseListener(AppKitMouseBaseListener):
"""Loosely emulate Evdev mouse behaviour on the Macs.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacMouseSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
mouse = MacMouseListener(pipe, events=[]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mac_keyboard_process(pipe):
"""Single subprocesses for reading keyboard on Mac.""" |
# pylint: disable=import-error,too-many-locals
# Note Objective C does not support a Unix style fork.
# So these imports have to be inside the child subprocess since
# otherwise the child process cannot use them.
# pylint: disable=no-member, no-name-in-module
from AppKit import NSApplication, NSApp
from Foundation import NSObject
from Cocoa import (NSEvent, NSKeyDownMask, NSKeyUpMask,
NSFlagsChangedMask)
from PyObjCTools import AppHelper
import objc
class MacKeyboardSetup(NSObject):
"""Setup the handler."""
@objc.python_method
def init_with_handler(self, handler):
"""
Init method that receives the write end of the pipe.
"""
# ALWAYS call the super's designated initializer.
# Also, make sure to re-bind "self" just in case it
# returns something else!
# pylint: disable=self-cls-assignment
self = super(MacKeyboardSetup, self).init()
self.handler = handler
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
# pylint: disable=invalid-name, unused-argument
def applicationDidFinishLaunching_(self, notification):
"""Bind the handler to listen to keyboard events."""
mask = NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
mask, self.handler)
class MacKeyboardListener(AppKitKeyboardListener):
"""Loosely emulate Evdev keyboard behaviour on the Mac.
Listen for key events then buffer them in a pipe.
"""
def install_handle_input(self):
"""Install the hook."""
self.app = NSApplication.sharedApplication()
# pylint: disable=no-member
delegate = MacKeyboardSetup.alloc().init_with_handler(
self.handle_input)
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
def __del__(self):
"""Stop the listener on deletion."""
AppHelper.stopEventLoop()
# pylint: disable=unused-variable
keyboard = MacKeyboardListener(pipe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delay_and_stop(duration, dll, device_number):
"""Stop vibration aka force feedback aka rumble on Windows after duration miliseconds.""" |
xinput = getattr(ctypes.windll, dll)
time.sleep(duration/1000)
xinput_set_state = xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(0, 0)
xinput_set_state(device_number, ctypes.byref(vibration)) |
<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_event_object(self, event_type, code, value, timeval=None):
"""Create an evdev style structure.""" |
if not timeval:
self.update_timeval()
timeval = self.timeval
try:
event_code = self.type_codes[event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel. In evdev, a single click forwards of the mouse wheel is 1 and a click back is -1. Windows uses 120 and -120. We floor divide the Windows number by 120. This is fine for the digital scroll wheels found on the vast majority of mice. It also works on the analogue ball on the top of the Apple mouse. What do the analogue scroll wheels found on 200 quid high end gaming mice do? If the lowest unit is 120 then we are okay. If they report changes of less than 120 units Windows, then this might be an unacceptable loss of precision. Needless to say, I don't have such a mouse to test one way or the other. """ |
if direction == 'x':
code = 0x06
elif direction == 'z':
# Not enitely sure if this exists
code = 0x07
else:
code = 0x08
if WIN:
data = data // 120
return self.create_event_object(
"Relative",
code,
data,
timeval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_rel(self, key_code, value, timeval):
"""Emulate the relative changes of the mouse cursor.""" |
return self.create_event_object(
"Relative",
key_code,
value,
timeval) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.