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 _get_args_to_parse(args, sys_argv):
"""Return the given arguments if it is not None else sys.argv if it contains something, an empty list otherwise. Args: ar... |
arguments = args if args is not None else sys_argv[1:]
_LOG.debug("Parsing arguments: %s", arguments)
return arguments |
<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_parser_call_method(func):
"""Returns the method that is linked to the 'call' method of the parser Args: func: the decorated function Raises: ParseThisEr... |
func_name = func.__name__
parser = func.parser
def inner_call(instance=None, args=None):
"""This is method attached to <parser>.call.
Args:
instance: the instance of the parser
args: arguments to be parsed
"""
_LOG.debug("Calling %s.parser.call", fu... |
<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_args_name_from_parser(parser):
"""Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """ |
# Retrieve the 'action' destination of the method parser i.e. its
# argument name. The HelpAction is ignored.
return [action.dest for action in parser._actions if not
isinstance(action, argparse._HelpAction)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call(callable_obj, arg_names, namespace):
"""Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable obj... |
arguments = {arg_name: getattr(namespace, arg_name)
for arg_name in arg_names}
return callable_obj(**arguments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call_method_from_namespace(obj, method_name, namespace):
"""Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any... |
method = getattr(obj, method_name)
method_parser = method.parser
arg_names = _get_args_name_from_parser(method_parser)
if method_name == "__init__":
return _call(obj, arg_names, namespace)
return _call(method, arg_names, namespace) |
<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(profile, resource):
"""Get the URL for a resource. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell... |
repo = profile["repo"]
url = GITHUB_API_BASE_URL + "repos/" + repo + "/git" + resource
return 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 post_merge_request(profile, payload):
"""Do a POST request to Github's API to merge. Args: profile A profile generated from ``simplygithub.authentication.pro... |
repo = profile["repo"]
url = GITHUB_API_BASE_URL + "repos/" + repo + "/merges"
headers = get_headers(profile)
response = requests.post(url, json=payload, headers=headers)
return 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 get_request(profile, resource):
"""Do a GET request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such pro... |
url = get_url(profile, resource)
headers = get_headers(profile)
response = requests.get(url, headers=headers)
return response.json() |
<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_request(profile, resource, payload):
"""Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile`... |
url = get_url(profile, resource)
headers = get_headers(profile)
response = requests.post(url, json=payload, headers=headers)
return response.json() |
<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_request(profile, resource):
"""Do a DELETE request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Su... |
url = get_url(profile, resource)
headers = get_headers(profile)
return requests.delete(url, headers=headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_updater(self):
""" Get the update and reset the buffer. Return `None` if there is no update. """ |
if self._node is self._buffer:
return None
else:
updater = (self._node, self._buffer)
self._buffer = self._node
return updater |
<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_graph(self):
""" Produce a dependency graph based on a list of tasks produced by the parser. """ |
self._graph.add_nodes_from(self.tasks)
for node1 in self._graph.nodes:
for node2 in self._graph.nodes:
for input_file in node1.inputs:
for output_file in node2.outputs:
if output_file == input_file:
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 get_value(self, key, args, kwargs):
"""Get value only from mapping and possibly convert key to string.""" |
if (self.tolerant and
not isinstance(key, basestring) and
key not in kwargs):
key = str(key)
return kwargs[key] |
<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_field(self, field_name, args, kwargs):
"""Create a special value when field missing and tolerant.""" |
try:
obj, arg_used = super(FormatterWrapper, self).get_field(
field_name, args, kwargs)
except (KeyError, IndexError, AttributeError):
if not self.tolerant:
raise
obj = MissingField(field_name)
arg_used = field_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 convert_field(self, value, conversion):
"""When field missing, store conversion specifier.""" |
if isinstance(value, MissingField):
if conversion is not None:
value.conversion = conversion
return value
return super(FormatterWrapper, self).convert_field(value, conversion) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_field(self, value, format_spec):
"""When field missing, return original spec.""" |
if isinstance(value, MissingField):
if format_spec is not None:
value.format_spec = format_spec
return str(value)
return super(FormatterWrapper, self).format_field(value, format_spec) |
<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_last_thread(self):
""" Return the last modified thread """ |
cache_key = '_get_last_thread_cache'
if not hasattr(self, cache_key):
item = None
res = self.thread_set.filter(visible=True).order_by('-modified')[0:1]
if len(res)>0:
item = res[0]
setattr(self, cache_key, item)
return getattr(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 save(self, *args, **kwargs):
""" Fill 'created' and 'modified' attributes on first create """ |
if self.created is None:
self.created = tz_now()
if self.modified is None:
self.modified = self.created
super(Thread, self).save(*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 get_paginated_urlargs(self):
""" Return url arguments to retrieve the Post in a paginated list """ |
position = self.get_paginated_position()
if not position:
return '#forum-post-{0}'.format(self.id)
return '?page={0}#forum-post-{1}'.format(position, self.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_paginated_position(self):
""" Return the Post position in the paginated list """ |
# If Post list is not paginated
if not settings.FORUM_THREAD_DETAIL_PAGINATE:
return 0
count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1
return int(math.ceil(count / float(settings.FORUM_THREAD_DETAIL_PAGINATE))) |
<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(self, *args, **kwargs):
""" Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute """ |
edited = not(self.created is None)
if self.created is None:
self.created = tz_now()
# Update de la date de modif. du message
if self.modified is None:
self.modified = self.created
else:
self.modified = tz_now()
... |
<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(search="unsigned"):
""" List all available plugins""" |
plugins = []
for i in os.walk('/usr/lib/nagios/plugins'):
for f in i[2]:
plugins.append(f)
return plugins |
<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(plugin_name, *args, **kwargs):
""" Run a specific plugin """ |
plugindir = nago.settings.get_option('plugin_dir')
plugin = plugindir + "/" + plugin_name
if not os.path.isfile(plugin):
raise ValueError("Plugin %s not found" % plugin)
command = [plugin] + list(args)
p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,)
stdout... |
<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_ctx(elt):
"""Get the right ctx related to input elt. In order to keep safe memory as much as possible, it is important to find the right context element... |
result = elt # by default, result is ctx
# if elt is ctx and elt is a method, it is possible to find the best ctx
if ismethod(elt):
# get instance and class of the elt
instance = get_method_self(elt)
# if instance is not None, the right context is the instance
if instance... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def free_cache(ctx, *elts):
"""Free properties bound to input cached elts. If empty, free the whole cache. """ |
for elt in elts:
if isinstance(elt, Hashable):
cache = __STATIC_ELEMENTS_CACHE__
else:
cache = __UNHASHABLE_ELTS_CACHE__
elt = id(elt)
if elt in cache:
del cache[elt]
if not elts:
__STATIC_ELEMENTS_CACHE__.clear()
__UNHAS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ctx_elt_properties(elt, ctx=None, create=False):
"""Get elt properties related to a ctx. :param elt: property component elt. Not None methods or unhashable ... |
result = None
if ctx is None:
ctx = find_ctx(elt=elt)
ctx_properties = None
# in case of dynamic object, parse the ctx __dict__
ctx__dict__ = getattr(ctx, __DICT__, None)
if ctx__dict__ is not None and isinstance(ctx__dict__, dict):
# if properties exist in ctx__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 get_properties(elt, keys=None, ctx=None):
"""Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of pro... |
# initialize keys if str
if isinstance(keys, string_types):
keys = (keys,)
result = _get_properties(elt, keys=keys, local=False, ctx=ctx)
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 get_property(elt, key, ctx=None):
"""Get elt key property. :param elt: property elt. Not None methods. :param key: property key to get from elt. :param ctx: ... |
result = []
properties = get_properties(elt=elt, ctx=ctx, keys=key)
if key in properties:
result = properties[key]
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 get_first_properties(elt, keys=None, ctx=None):
"""Get first properties related to one input key. :param elt: first property elt. Not None methods. :param li... |
# ensure keys is an iterable if not None
if isinstance(keys, string_types):
keys = (keys,)
result = _get_properties(elt, keys=keys, first=True, ctx=ctx)
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 get_first_property(elt, key, default=None, ctx=None):
"""Get first property related to one input key. :param elt: first property elt. Not None methods. :para... |
result = default
properties = _get_properties(elt, keys=(key,), ctx=ctx, first=True)
# set value if key exists in properties
if key in properties:
result = properties[key]
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 get_local_property(elt, key, default=None, ctx=None):
"""Get one local property related to one input key or default value if key is not found. :param elt: lo... |
result = default
local_properties = get_local_properties(elt=elt, keys=(key,), ctx=ctx)
if key in local_properties:
result = local_properties[key]
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 put(properties, ttl=None, ctx=None):
"""Decorator dedicated to put properties on an element. """ |
def put_on(elt):
return put_properties(elt=elt, properties=properties, ttl=ttl, ctx=ctx)
return put_on |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_properties(elt, keys=None, ctx=None):
"""Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete f... |
# get the best context
if ctx is None:
ctx = find_ctx(elt=elt)
elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=False)
# if elt properties exist
if elt_properties is not None:
if keys is None:
keys = list(elt_properties.keys())
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setdefault(elt, key, default, ctx=None):
""" Get a local property and create default value if local property does not exist. :param elt: local proprety elt t... |
result = default
# get the best context
if ctx is None:
ctx = find_ctx(elt=elt)
# get elt properties
elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=True)
# if key exists in elt properties
if key in elt_properties:
# result is elt_properties[key]
re... |
<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_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the object. """ |
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(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 get_corrected_stats(package, use_honeypot=True):
""" Fetches statistics for `package` and then corrects them using a special honeypot. """ |
honeypot, __, __ = get_stats('python-bogus-project-honeypot')
if not honeypot:
raise RuntimeError("Could not get honeypot data")
honeypot = honeypot['releases']
# Add a field used to store diff when choosing the best honey pot release
# for some statistic
for x in honeypot:
x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_subclass(value, types):
""" Ensure value is a subclass of types Traceback (most recent call last):
TypeError: """ |
ensure_class(value)
if not issubclass(value, types):
raise TypeError(
"expected subclass of {}, not {}".format(
types, 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 ensure_instance(value, types):
""" Ensure value is an instance of a certain type Traceback (most recent call last):
TypeError: Traceback (most recent call l... |
if not isinstance(value, types):
raise TypeError(
"expected instance of {}, got {}".format(
types, 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 iter_ensure_instance(iterable, types):
""" Iterate over object and check each item type Traceback (most recent call last):
TypeError: Traceback (most recent... |
ensure_instance(iterable, Iterable)
[ ensure_instance(item, types) for item in iterable ] |
<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_bases(cls, *bases):
""" Add bases to class False True """ |
assert inspect.isclass(cls), "Expected class object"
for mixin in bases:
assert inspect.isclass(mixin), "Expected class object for bases"
new_bases = (bases + cls.__bases__)
cls.__bases__ = new_bases |
<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_dict_by_key(obj):
""" Sort dict by its keys OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """ |
sort_func = lambda x: x[0]
return OrderedDict(sorted(obj.items(), key=sort_func)) |
<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_random_token(length=32):
""" Generate random secure token 32 6 """ |
chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits)
return ''.join(random.choice(chars) for _ in range(length)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default(*args, **kwargs):
""" Return first argument which is "truthy" 1 123 None """ |
default = kwargs.get('default', None)
for arg in args:
if arg:
return arg
return 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 is_int(value):
""" Check if value is an int :type value: int, str, bytes, float, Decimal (True, True, True) (False, False, False) Traceback (most recent call... |
ensure_instance(value, (int, str, bytes, float, Decimal))
if isinstance(value, int):
return True
elif isinstance(value, float):
return False
elif isinstance(value, Decimal):
return str(value).isdigit()
elif isinstance(value, (str, bytes)):
return value.isdigit()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
""" Coerce value to bytes Traceback (most recent call last):
TypeError: Cannot coerce... |
PY2 = sys.version_info[0] == 2
if PY2: # pragma: nocover
if x is None:
return None
if isinstance(x, (bytes, bytearray, buffer)):
return bytes(x)
if isinstance(x, unicode):
return x.encode(charset, errors)
raise TypeError('Cannot coerce to byte... |
<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(self):
"""Remove any created temp paths""" |
for path in self.paths:
if isinstance(path, tuple):
os.close(path[0])
os.unlink(path[1])
else:
shutil.rmtree(path)
self.paths = [] |
<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_vertex_surrounding_multicolor(graph, vertex):
""" Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present ... |
result = Multicolor()
for edge in graph.get_edges_by_vertex(vertex):
result += edge.multicolor
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 get_irregular_edge_by_vertex(graph, vertex):
""" Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" s... |
for edge in graph.get_edges_by_vertex(vertex):
if edge.is_irregular_edge:
return edge
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 assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None):
""" This function actually does assembling being provided a graph, t... |
if verbose:
print(">>Assembling for multicolor", [e.name for e in multicolor.multicolors.elements()],
file=verbose_destination)
for assembly in assemblies:
v1, v2, (before, after, ex_data) = assembly
iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_map(func):
"""Wrap exceptions raised by requests. .. py:decorator:: error_map """ |
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions.RequestException as err:
raise TVDBRequestException(
err,
response=getattr(err, 'response', None),
request=getattr(err, 'req... |
<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_message(username, message):
""" Creates a standard message from a given user with the message
Replaces newline with html break """ |
message = message.replace('\n', '<br/>')
return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username) |
<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(self, xer, primary, type):
""" Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already ... |
if xer not in primary:
primary[xer] = TwistedSocketNotifier(None, self, xer, type) |
<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, xer, primary):
""" Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case ... |
if xer in primary:
notifier = primary.pop(xer)
notifier.shutdown() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeAll(self):
""" Remove all selectables, and return a list of them. """ |
rv = self._removeAll(self._reads, self._writes)
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def doIteration(self, delay=None, fromqt=False):
'This method is called by a Qt timer or by network activity on a file descriptor'
if not self.running and self._blockApp:
self._blockApp.quit()
self._timer.stop()
delay = max(delay, 1)
if not fromqt:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addEvent(self, event, fd, action):
""" Add a new win32 event to the event loop. """ |
self._events[event] = (fd, action) |
<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_levenshtein(first, second):
"""\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ |
if not first:
return len(second)
if not second:
return len(first)
prev_distances = range(0, len(second) + 1)
curr_distances = None
# Find the minimum edit distance between each substring of 'first' and
# the entirety of 'second'. The first column of each distance list is
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_matches(self, target, choices, group=False, include_rank=False):
"""\ Get all choices listed from best match to worst match. If `group` is `True`, then m... |
dist = self.get_distance
# Keep everything here as an iterator in case we're given a lot of
# choices
matched = ((dist(target, choice), choice) for choice in choices)
matched = sorted(matched)
if group:
for rank, choices in groupby(matched, key=lambda m: 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 best_matches(self, target, choices):
"""\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param targe... |
all = self.all_matches
try:
matches = next(all(target, choices, group=True))
for match in matches:
yield match
except StopIteration:
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 best_match(self, target, choices):
"""\ Return the best match. """ |
all = self.all_matches
try:
best = next(all(target, choices, group=False))
return best
except StopIteration:
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 agenerator():
"""Arandom number generator""" |
free_mem = psutil.virtual_memory().available
mem_24 = 0.24 * free_mem
mem_26 = 0.26 * free_mem
a = MemEater(int(mem_24))
b = MemEater(int(mem_26))
sleep(5)
return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000 |
<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_signal(self, sig):
"""Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if ... |
if not isinstance(sig, int):
raise TypeError('sig must be an int, not {!r}'.format(sig))
if signal is None:
raise RuntimeError('Signals are not supported')
if not (1 <= sig < signal.NSIG):
raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_version(self):
""" Query the Cassandra server for the version. :returns: string -- the version tag """ |
def _vers(client):
return client.describe_version()
d = self._connection()
d.addCallback(_vers)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, query, args, consistency):
""" Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: Th... |
prep_query = prepare(query, args)
def _execute(client):
exec_d = client.execute_cql3_query(prep_query,
ttypes.Compression.NONE, consistency)
if self._disconnect_on_cancel:
cancellable_d = Deferred(lambda d: self.dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getfiles(qfiles, dirname, names):
"""Get rule files in a directory""" |
for name in names:
fullname = os.path.join(dirname, name)
if os.path.isfile(fullname) and \
fullname.endswith('.cf') or \
fullname.endswith('.post'):
qfiles.put(fullname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_file(source, dest):
"""Deploy a file""" |
date = datetime.utcnow().strftime('%Y-%m-%d')
shandle = open(source)
with open(dest, 'w') as handle:
for line in shandle:
if line == '# Updated: %date%\n':
newline = '# Updated: %s\n' % date
else:
newline = line
handle.write(newlin... |
<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_counter(counterfile):
"""Get the counter value""" |
try:
version_num = open(counterfile).read()
version_num = int(version_num) + 1
except (ValueError, IOError):
version_num = 1
create_file(counterfile, "%d" % version_num)
except BaseException as msg:
raise SaChannelUpdateError(msg)
return version_num |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update_dns(config, record, sa_version):
"Update the DNS record"
try:
domain = config.get('domain_name', 'sa.baruwa.com.')
dns_key = config.get('domain_key')
dns_ip = config.get('domain_ip', '127.0.0.1')
keyring = tsigkeyring.from_text({domain: dns_key})
transaction = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(config, s_filename):
"""sign the package""" |
gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg')
gpg_pass = config.get('gpg_passphrase')
gpg_keyid = config.get('gpg_keyid')
gpg = GPG(gnupghome=gpg_home)
try:
plaintext = open(s_filename, 'rb')
signature = gpg.sign_file(
plaintext, keyid=gpg_keyid, pas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_file(tar_filename):
"""hash the file""" |
hasher = sha1()
with open(tar_filename, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_filename))
create_file('%s.sha1' % tar_filename, dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(config, remote_loc, u_filename):
"""Upload the files""" |
rcode = False
try:
sftp, transport = get_sftp_conn(config)
remote_dir = get_remote_path(remote_loc)
for part in ['sha1', 'asc']:
local_file = '%s.%s' % (u_filename, part)
remote_file = os.path.join(remote_dir, local_file)
sftp.put(local_file, remote_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue_files(dirpath, queue):
"""Add files in a directory to a queue""" |
for root, _, files in os.walk(os.path.abspath(dirpath)):
if not files:
continue
for filename in files:
queue.put(os.path.join(root, filename)) |
<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_cf_files(path, queue):
"""Get rule files in a directory and put them in a queue""" |
for root, _, files in os.walk(os.path.abspath(path)):
if not files:
continue
for filename in files:
fullname = os.path.join(root, filename)
if os.path.isfile(fullname) and fullname.endswith('.cf') or \
fullname.endswith('.post'):
... |
<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(dest, tardir, counterfile):
"""Remove existing rules""" |
thefiles = Queue()
# dest directory files
queue_files(dest, thefiles)
# tar directory files
queue_files(tardir, thefiles)
while not thefiles.empty():
d_file = thefiles.get()
info("Deleting file: %s" % d_file)
os.unlink(d_file)
if os.path.exists(counterfile):
... |
<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_required(config):
"""Validate the input""" |
if config.get('domain_key') is None:
raise CfgError("The domain_key option is required")
if config.get('remote_loc') is None:
raise CfgError("The remote_location option is required")
if config.get('gpg_keyid') is None:
raise CfgError("The gpg_keyid option is required") |
<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_result(result):
""" Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/... |
lines = filter(lambda x: x.strip(), result.splitlines()) # rm blank lines
if not lines:
return {}
out = {}
for line in lines:
line = line.split(":")
fn = line[0].strip()
line = " ".join(line[1:])
line = line.rsplit(None, 1)
status = line.pop().strip(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan_file(path):
""" Scan `path` for viruses using ``clamscan`` program. Args: path (str):
Relative or absolute path of file/directory you need to scan. Ret... |
path = os.path.abspath(path)
assert os.path.exists(path), "Unreachable file '%s'." % path
result = sh.clamscan(path, no_summary=True, infected=True, _ok_code=[0, 1])
return _parse_result(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 connect(self):
"""Initializes a connection to the smtp server :return: True on success, False otherwise """ |
connection_method = 'SMTP_SSL' if self.ssl else 'SMTP'
self._logger.debug('Trying to connect via {}'.format(connection_method))
smtp = getattr(smtplib, connection_method)
if self.port:
self._smtp = smtp(self.address, self.port)
else:
self._smtp = smtp(sel... |
<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(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'):
"""Sends the email :param sender: The server of the... |
if not self.connected:
self._logger.error(('Server not connected, cannot send message, '
'please connect() first and disconnect() when '
'the connection is not needed any more'))
return False
try:
messag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
"""Disconnects from the remote smtp server :return: True on success, False otherwise """ |
if self.connected:
try:
self._smtp.close()
self._connected = False
result = True
except Exception: # noqa
self._logger.exception('Something went wrong!')
result = False
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 send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'):
"""Sends the email by connecting and disconnecting ... |
self._server.connect()
self._server.send(sender,
recipients,
cc,
bcc,
subject,
body,
attachments,
content)
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 _setup_message(self):
"""Constructs the actual underlying message with provided values""" |
if self.content == 'html':
self._message = MIMEMultipart('alternative')
part = MIMEText(self.body, 'html', 'UTF-8')
else:
self._message = MIMEMultipart()
part = MIMEText(self.body, 'plain', 'UTF-8')
self._message.preamble = 'Multipart massage.\n'
... |
<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_simple(email):
"""Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email addres... |
name, address = parseaddr(email)
if not re.match('[^@]+@[^@]+\.[^@]+', address):
raise ValueError('Invalid email :{email}'.format(email=email))
return address |
<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_cache(cache):
""" Save cahce to the disk. Args: cache (set):
Set with cached data. """ |
with open(settings.DUP_FILTER_FILE, "w") as f:
f.write(
json.dumps(list(cache))
) |
<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_cache():
""" Load cache from the disk. Return: set: Deserialized data from disk. """ |
if not os.path.exists(settings.DUP_FILTER_FILE):
return set()
with open(settings.DUP_FILTER_FILE) as f:
return set(
json.loads(f.read())
) |
<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_publication(publication, cache=_CACHE):
""" Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is f... |
if cache is None:
cache = load_cache()
if publication._get_hash() in cache:
return None
cache.update(
[publication._get_hash()]
)
save_cache(cache)
return publication |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formfield(self, **kwargs):
""" Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """ |
default = kwargs.get("widget", None) or AdminTextareaWidget
if default is AdminTextareaWidget:
from yacms.conf import settings
richtext_widget_path = settings.RICHTEXT_WIDGET_CLASS
try:
widget_class = import_dotted_path(richtext_widget_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(url):
"""Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object re... |
text = urlopen(url).read()
soup = BeautifulSoup(text)
return Response(text=text, soup=soup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_decorator(*a, **k):
""" An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """ |
# This is a decorator without parameters, e.g.
#
# @login_required
# def some_view(request):
# ...
#
if a:
# This could fail in the instance where a callable argument is passed
# as a parameter to the decorator!
if callable(a[0]):
def wrapper(*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 tinsel(to_patch, module_name, decorator=mock_decorator):
""" Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the... |
def fn_decorator(function):
def wrapper(*args, **kwargs):
with patch(to_patch, decorator):
m = importlib.import_module(module_name)
reload(m)
function(*args, **kwargs)
reload(m)
return wrapper
return fn_decorator |
<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 anext(self):
"""Fetch the next value from the iterable.""" |
try:
f = next(self._iter)
except StopIteration as exc:
raise StopAsyncIteration() from exc
return await f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _new_token(self, chars=None, line_no=None):
""" Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no... |
if not line_no:
line_no = self._line_no
if not chars:
chars = self._token_chars
if chars:
# add new token
self._tokens.append((line_no, ''.join(chars)))
self._token_chars = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_newline(self, char):
""" Process a newline character. """ |
state = self._state
# inside string, just append char to token
if state == self.ST_STRING:
self._token_chars.append(char)
else:
# otherwise, add new token
self._new_token()
self._line_no += 1 # update line counter
# finished with ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_string(self, char):
""" Process a character as part of a string token. """ |
if char in self.QUOTES:
# end of quoted string:
# 1) quote must match original quote
# 2) not escaped quote (e.g. "hey there" vs "hey there\")
# 3) actual escape char prior (e.g. "hey there\\")
if (char == self._last_quote and
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_tokens(self, char):
""" Process a token character. """ |
if (char in self.WHITESPACE or char == self.COMMENT_START or
char in self.QUOTES or char in self.TOKENS):
add_token = True
# escaped chars, keep going
if char == self.SPACE or char in self.TOKENS:
if self._escaped:
add_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tokenize(self, stream):
""" Tokenizes data from the provided string. ``stream`` ``File``-like object. """ |
self._tokens = []
self._reset_token()
self._state = self.ST_TOKEN
for chunk in iter(lambda: stream.read(8192), ''):
for char in chunk:
if char in self.NEWLINES:
self._process_newline(char)
else:
state... |
<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(self, filename):
""" Reads the file specified and tokenizes the data for parsing. """ |
try:
with open(filename, 'r') as _file:
self._filename = filename
self.readstream(_file)
return True
except IOError:
self._filename = None
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 _escaped(self):
""" Escape character is at end of accumulated token character list. """ |
chars = self._token_info['chars']
count = len(chars)
# prev char is escape, keep going
if count and chars[count - 1] == self.ESCAPE:
chars.pop() # swallow escape char
return True
else:
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 checkResponse(request):
'''
Returns if a request has an okay error code, otherwise raises InvalidRequest.
'''
# Check the status code of the returned request
if str(request.status_code)[0] not in ['2', '3']:
w = str(request.text).split('\\r')[0][2:]
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 checkKey(self, key=None):
'''
Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.