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 copytree(src, dst, symlinks=False, ignore=None):
"""Copy from source directory to destination""" |
# TODO(crow): OSError: [Errno 17] File exists
if not osp.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = osp.join(src, item)
d = osp.join(dst, item)
if osp.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(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 emptytree(directory):
"""Delete all the files and dirs under specified directory""" |
for p in os.listdir(directory):
fp = osp.join(directory, p)
if osp.isdir(fp):
try:
shutil.rmtree(fp)
logger.info("Delete directory %s" % fp)
except Exception, e:
logger.error("Unable to delete directory %s: %s" % (fp, str(e)))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listdir_nohidden(path):
"""List not hidden files or directories under path""" |
for f in os.listdir(path):
if isinstance(f, str):
f = unicode(f, "utf-8")
if not f.startswith('.'):
yield 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 check_config(data):
"""Check if metadata is right TODO(crow):
check more """ |
is_right = True
if "title" not in data:
logging.error("No 'title' in _config.yml")
is_right = False
return is_right |
<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_ymal_data(data):
"""Get metadata and validate them :param data: metadata in yaml format """ |
try:
format_data = yaml.load(data)
except yaml.YAMLError, e:
msg = "Yaml format error: {}".format(
unicode(str(e), "utf-8")
)
logging.error(msg)
sys.exit(1)
if not check_config(format_data):
sys.exit(1)
return format_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 parse_markdown(markdown_content, site_settings):
"""Parse markdown text to html. :param markdown_content: Markdown text lists #TODO# """ |
markdown_extensions = set_markdown_extensions(site_settings)
html_content = markdown.markdown(
markdown_content,
extensions=markdown_extensions,
)
return html_content |
<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(self):
""" Wait for the request to finish and return the result or error when finished :returns: result or error :type: result tyoe or Error """ |
self.thread.join()
if self.error is not None:
return self.error
return self.result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree.""" |
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_manager(get_item_model_class()).filter(q).distinct() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3.""" |
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
elif type(obj).__name__ == 'function':
return _fullqualname_function_py3(obj)
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_desc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fullqualname_builtin_py3(obj):
"""Fully qualified name for 'builtin_function_or_method' objects in Python 3. """ |
if obj.__module__ is not None:
# built-in functions
module = obj.__module__
else:
# built-in methods
if inspect.isclass(obj.__self__):
module = obj.__self__.__module__
else:
module = obj.__self__.__class__.__module__
return module + '.' + ob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fullqualname_function_py3(obj):
"""Fully qualified name for 'function' objects in Python 3. """ |
if hasattr(obj, "__wrapped__"):
# Required for decorator.__version__ <= 4.0.0.
qualname = obj.__wrapped__.__qualname__
else:
qualname = obj.__qualname__
return obj.__module__ + '.' + qualname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fullqualname_method_py3(obj):
"""Fully qualified name for 'method' objects in Python 3. """ |
if inspect.isclass(obj.__self__):
cls = obj.__self__.__qualname__
else:
cls = obj.__self__.__class__.__qualname__
return obj.__self__.__module__ + '.' + cls + '.' + obj.__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 fullqualname_py2(obj):
"""Fully qualified name for objects in Python 2.""" |
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py2(obj)
elif type(obj).__name__ == 'function':
return obj.__module__ + '.' + obj.__name__
elif type(obj).__name__ in ['member_descriptor', 'method_descriptor',
'wrapper_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fullqualname_builtin_py2(obj):
"""Fully qualified name for 'builtin_function_or_method' objects in Python 2. """ |
if obj.__self__ is None:
# built-in functions
module = obj.__module__
qualname = obj.__name__
else:
# built-in methods
if inspect.isclass(obj.__self__):
cls = obj.__self__
else:
cls = obj.__self__.__class__
module = cls.__module__... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fullqualname_method_py2(obj):
"""Fully qualified name for 'instancemethod' objects in Python 2. """ |
if obj.__self__ is None:
# unbound methods
module = obj.im_class.__module__
cls = obj.im_class.__name__
else:
# bound methods
if inspect.isclass(obj.__self__):
# methods decorated with @classmethod
module = obj.__self__.__module__
cls... |
<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(binary, **params):
"""Turns a TAR file into a frozen sample.""" |
binary = io.BytesIO(binary)
collection = list()
with tarfile.TarFile(fileobj=binary, mode='r') as tar:
for tar_info in tar.getmembers():
content_type, encoding = mimetypes.guess_type(tar_info.name)
content = tar.extractfile(tar_info)
content = content_encodings.g... |
<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(collection, **params):
"""Truns a frozen sample into a TAR file.""" |
binary = io.BytesIO()
with tarfile.TarFile(fileobj=binary, mode='w') as tar:
mode = params.get('mode', 0o640)
now = calendar.timegm(datetime.datetime.utcnow().timetuple())
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(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(tzid):
"""Return timezone data""" |
ns = {}
path = os.path.join(DATA_DIR, tzid)
with open(path) as f:
raw_data = f.read()
exec(raw_data, ns, ns)
z = ZoneData()
z.types = [(delta(offset), delta(save), abbr)
for offset, save, abbr in ns['types']]
z.times = [(datetime(*time), i)
for time, i ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_required(method):
"""A decorator that control if a user is logged.""" |
def wrapper(self, *arg, **karg):
if not self.user:
if self.request.method == "GET":
self.redirect(settings.LOGIN_PATH)
else:
self.error(403)
else:
method(self, *arg, **karg)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pointcut(self, value):
"""Change of pointcut. """ |
pointcut = getattr(self, Interceptor.POINTCUT)
# for all targets
for target in self.targets:
# unweave old advices
unweave(target, pointcut=pointcut, advices=self.intercepts)
# weave new advices with new pointcut
weave(target, pointcut=value, ad... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bind_target(self, target, ctx=None, *args, **kwargs):
"""Weave self.intercepts among target advices with pointcut.""" |
result = super(Interceptor, self)._bind_target(
target=target, ctx=ctx, *args, **kwargs
)
pointcut = getattr(self, Interceptor.POINTCUT)
weave(result, pointcut=pointcut, advices=self.intercepts, 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 intercepts(self, joinpoint):
"""Self target interception if self is enabled :param joinpoint: advices executor """ |
result = None
if self.enable:
interception = getattr(self, Interceptor.INTERCEPTION)
joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self
result = interception(joinpoint)
else:
result = joinpoint.proceed()
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 create_token(user):
""" Create token. """ |
payload = jwt_payload_handler(user)
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.utcnow().utctimetuple()
)
# Return values
token = jwt_encode_handler(payload)
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onepara(R):
"""Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: R : ndarray an... |
import numpy as np
import warnings
d = R.shape[0]
if d < 2:
raise Exception((
"More than one variable is required."
"Supply at least a 2x2 matrix."))
# the explicit solution
x = (np.sum(R) + np.trace(R)) / (d**2 - d)
if x < (-1. / (d - 1)) or x > 1:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_rules(self):
""" Loads the rules from the SSH-Connection """ |
with self._sftp_connection.open(self.RULE_PATH) as file:
data = file.read()
lines = (
line.strip()
for line in data.split('\n')
)
rule_strings = (
line for line in lines
if len(line) > 0
)
rules = (
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exec_command(self, command: str):
""" Executes the command and closes the handles afterwards. """ |
stdin, stdout, stderr = self._ssh.exec_command(command)
# Clearing the buffers
stdout.read()
stderr.read()
stdin.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync(self, rules: list):
""" Synchronizes the given rules with the server and ensures that there are no old rules active which are not in the given list. """ |
self._reset()
old_rules = self.rules
to_delete_rules = [
rule for rule in old_rules
if rule not in rules
]
new_rules = [
rule for rule in rules
if rule not in old_rules
]
for new_rule in new_rules:
asse... |
<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(self, rules: list):
""" Updates the given rules and stores them on the router. """ |
self._rules = rules
to_store = '\n'.join(
rule.config_string
for rule in rules
)
sftp_connection = self._sftp_connection
with sftp_connection.open(self.RULE_PATH, mode='w') as file_handle:
file_handle.write(to_store) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx):
""" Override in order to have command or argument completion. It is necessary to return a 'li... |
# TODO: Optionally check that flags are not repeated (i.e. exclude
# them from the possible matches if they are already in the
# command line)
# TODO: Support groups of mutually-exclusive flags, i.e. if one is
# already present, the others in the group are not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_address(self):
""" Local endpoint address as a tuple """ |
if not self._local_address:
self._local_address = self.proto.reader._transport.get_extra_info('sockname')
if len(self._local_address) == 4:
self._local_address = self._local_address[:2]
return self._local_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 peer_address(self):
""" Peer endpoint address as a tuple """ |
if not self._peer_address:
self._peer_address = self.proto.reader._transport.get_extra_info('peername')
if len(self._peer_address) == 4:
self._peer_address = self._peer_address[:2]
return self._peer_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 argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False):
""" Create switch function which return the status from specified nam... |
def switch_function(*args, **kwargs):
if argument_name in kwargs:
if keep:
status = kwargs.get(argument_name)
else:
status = kwargs.pop(argument_name)
if reverse:
status = not status
else:
status = defau... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def command_line():
'''
Parses users command line arguments and returns the namespace
containing parsed values.
'''
description = 'Kan helps you find the book'
version = ' '.join([__version__, __release__])
parser = ArgumentParser(prog='kan', description=description)
subparser ... |
<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(input_format, output_format, b64_data):
""" Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str):
Specification of in... |
# checks
assert input_format in INPUT_FORMATS, "Unsupported input format!"
assert output_format in OUTPUT_FORMATS, "Unsupported output format!"
with NTFile(mode="wb", suffix="." + input_format, dir="/tmp") as ifile:
ofilename = ifile.name + "." + output_format
# save received data to ... |
<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_sms(self, frm, to, text):
"""Sends a simple text message. Example usage:: :arg frm: The `from` field, a phone number (international format with or witho... |
frm = re.sub('[^\d]', '', frm)
to = re.sub('[^\d]', '', to)
api_url = '%s/sms/json' % API_ENDPOINT
params = {
'api_key': self.api_key,
'api_secret': self.api_secret,
'from': frm,
'to': to,
'text': text,
}
retur... |
<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_request(self, url, params, method='GET'):
"""Sends a raw request to the given api endpoint. :arg url: A Nexmpo api endpoint (json only) :arg params: A p... |
method = method.lower()
if method not in ['get', 'post']:
raise ValueError('The `method` parameter must be either `get` or `post`')
response = requests.request(method, url, data=params)
response_json = response.json()
status = int(response_json['messages'][0]['stat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenise(string, strict=False, replace=False, diphtongs=False, tones=False, unknown=False, merge=None):
""" Tokenise an IPA string into a list of tok... |
words = string.strip().replace('_', ' ').split()
output = []
for word in words:
tokens = tokenise_word(word, strict, replace, tones, unknown)
if diphtongs:
tokens = group(are_diphtong, tokens)
if merge is not None:
tokens = group(merge, tokens)
output.extend(tokens)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def verify_server_core(timeout=120, start_delay=90):
''' checks to see if the server_core is running
args:
delay: will cycle till core is up.
timeout: number of seconds to wait
'''
timestamp = time.time()
last_check = time.time() + start_delay - 10
last_delay_notific... |
<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_rml(self, rml_name):
""" loads an rml mapping into memory args: rml_name(str):
the name of the rml file """ |
conn = CFG.rml_tstore
cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name)
if not os.path.exists(cache_path):
results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False),
conn)
with open(cache_path, "w") as file_obj:
... |
<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_rml(self, rml_name):
""" returns the rml mapping RdfDataset rml_name(str):
Name of the rml mapping to retrieve """ |
try:
return getattr(self, rml_name)
except AttributeError:
return self.load_rml(rml_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 _set_data_filelist(self, start_path, attr_name, conn, file_exts=[], dir_filter=set()):
''' does a directory search for data files ''' def filter_path(filter_... |
if filter_terms.intersection(set(dir_path.split(os.path.sep))):
return True
else:
return False
data_obj = {}
files_dict = {}
latest_mod = 0
dir_filter = set(dir_filter)
for root, dirnames, filenames in os.walk(start_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 authenticate(self, request):
""" Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise ret... |
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(msg)
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_ascii_hex(value: int, digits: int) -> str: """Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters th... |
if digits < 1:
return ''
text = ''
for _ in range(0, digits):
text = chr(ord('0') + (value % 0x10)) + text
value //= 0x10
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any: """ Ensures the specified object is serializable, converting if necessary. :param... |
# Will be called recursively when object has children
def _serializable(parent_obj: Any, obj: Any,
on_filter: Callable[[Any, str], bool]) -> Any:
# None can be left as-is
if obj is None:
return obj
# IntFlag enums should be broken down to a list of na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int: """Encode special sensor value using the message attribute.""" |
if message_attribute == MA_TX3AC_100A:
# TX-3AC in 100A mode; use value as-is, with 0xFE indicating null
if value is None:
return 0xfe
return int(value)
elif message_attribute == MA_TX3AC_10A:
# TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_schema(schema, filtered_fields):
""" Validator for part of a schema, ignoring some fields :param schema: the Schema :param filtered_fields: fields to... |
return Schema({
k: v for k, v in schema.schema.items()
if getattr(k, 'schema', k) not in filtered_fields
}, extra=ALLOW_EXTRA) |
<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_url(url):
"""Validate URL is valid NOTE: only support http & https """ |
schemes = ['http', 'https']
netloc_re = re.compile(
r'^'
r'(?:\S+(?::\S*)?@)?' # user:pass auth
r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])'
r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]))*' # host
r'(?::[0-9]{2,5})?' # port
r'$', re.IGNORECASE
)... |
<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_reference_links(reference_links):
""" Vaidate reference links data structure Expected data structure: { "links": { id_type1: url1, id_type2: url2 },... |
allowed_keys = ['links', 'redirect_id_type']
if not isinstance(reference_links, dict):
raise Invalid('Expected reference_links to be an object')
if 'links' in reference_links and not isinstance(reference_links['links'], dict):
raise Invalid('Expected links in reference_links to be an obje... |
<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_state(state, valid_states):
"""Validate a state string""" |
if state in State:
return state.name
elif state in valid_states:
return state
else:
raise Invalid('Invalid 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 is_filelike(ob):
"""Check for filelikeness of an object. Needed to distinguish it from file names. Returns true if it has a read or a write method. """ |
if hasattr(ob, 'read') and callable(ob.read):
return True
if hasattr(ob, 'write') and callable(ob.write):
return True
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 dump_engines(target=sys.stderr):
"""Print successfully imported templating engines.""" |
print("Available templating engines:", file=target)
width = max(len(engine) for engine in engines.engines)
for handle, engine in sorted(engines.engines.items()):
description = engine.__doc__.split('\n', 0)[0]
print(" %-*s - %s" % (width, handle, description), file=target) |
<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_engine(handle):
"""Check availability of requested template engine.""" |
if handle == 'help':
dump_engines()
sys.exit(0)
if handle not in engines.engines:
print('Engine "%s" is not available.' % (handle,), file=sys.stderr)
sys.exit(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_mapping(args):
"""Make a mapping from the name=value pairs.""" |
mapping = {}
if args:
for arg in args:
name_value = arg.split('=', 1)
mapping[name_value[0]] = (name_value[1]
if len(name_value) > 1
else None)
return mapping |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_path_properties(file_or_path, prefix=''):
"""Build useful properties from a file path.""" |
is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr)
if is_std:
path = '-'
elif is_filelike(file_or_path):
try:
path = str(file_or_path.name)
except AttributeError:
path = None
else:
path = str(file_or_path)
if is_std or not 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 constant_outfile_iterator(outfiles, infiles, arggroups):
"""Iterate over all output files.""" |
assert len(infiles) == 1
assert len(arggroups) == 1
return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variable_outfile_iterator(outfiles, infiles, arggroups, engine):
"""Iterate over variable output file name template.""" |
assert len(outfiles) == 1
template = engine(outfiles[0], tolerant=False)
for infile in infiles:
properties = make_path_properties(infile, prefix='')
for arggroup in arggroups:
outfile = template.apply(dict(arggroup, **properties))
yield (outfile, infile, arggroup) |
<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_combinations(combinations, engine, tolerant=False, read_old=False, delete_empty=False, ):
"""Process outfile-infile-arggroup combinations.""" |
outfiles = set()
templatereader = CachedTemplateReader(engine, tolerant=tolerant)
for outfile, infile, arggroup in combinations:
template = templatereader.read(infile)
properties = make_path_properties(outfile, prefix='ez_')
if read_old:
if is_filelike(outfile):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform_templating(args):
"""Perform templating according to the given arguments.""" |
engine = engines.engines[args.engine]
if args.vary:
it = variable_outfile_iterator(args.outfiles,
args.infiles,
args.args,
engine)
else:
it = constant_outfile_iterator(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 read(self, file_or_path):
"""Read template from cache or file.""" |
if file_or_path in self._cached_templates:
return self._cached_templates[file_or_path]
if is_filelike(file_or_path):
template = file_or_path.read()
dirname = None
else:
with open(file_or_path, 'r') as f:
template = 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 get_config(cli_args=None, config_path=None):
""" Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param co... |
config = Config(app_name="MYAPP",
cli_args=cli_args,
config_path=config_path)
config_dict = config.get_config()
return config_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 parse_interval(interval):
""" Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects... |
a, b = str(interval).upper().strip().split('/')
if a[0] is 'P' and b[0] is 'P':
raise ParseError()
if a[0] != 'P' and b[0] != 'P':
return parse_date(a), parse_date(b)
if a[0] is 'P':
a = parse_duration(a)
else:
a = parse_date(a)
if b[0] is 'P':
b = pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False):
"""Run subcommand. Args: shell (Optional[bool]):
Run command using shell (defa... |
previous_directory = os.getcwd()
os.chdir(self.directory)
try:
kwargs = {
'stderr': sys.stderr,
'stdin': sys.stdin if stdin else None,
'env': self.env_vars,
'shell': shell,
}
if check_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 subcommand(self, *args):
"""Get subcommand acting on a service. Subcommand will run in service directory and with the environment variables used to run the s... |
return Subcommand(*args, directory=self.directory, env_vars=self.env_vars) |
<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_error(self, e):
""" Rather than allowing unmanaged exceptions to explode, or raising errors within thread, the worker thread should call this function wi... |
self.result = (False, e)
self._lock.release() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrapper(self):
""" Wraps around a few calls which need to be made in the same thread. """ |
try:
res = self.func(*self.args, **self.kw)
except Exception as e:
self.mediator.set_error(e)
else:
self.mediator.set_result(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 addinterval(instr, add, interval):
'''
adds string every n character. returns string
'''
if not isinstance(instr, str):
instr = str(instr)
return add.join(
instr[i:i+interval]
for i in xrange(0,len(instr),interval)) |
<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_ok(l1, l3):
'''
parse html when siren is ok
'''
return {
'annee': l1.text.split(' : ')[1].split()[2],
'siren valide': ''.join(
l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]),
'categorie': ' '.join(
l1.text.split(' : ')[1].split(u'\... |
<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_states(states, sort_list):
""" Returns a list of sorted states, original states list remains unsorted The sort list is a list of state field: field key ... |
sorted_states= states.copy()
for sort_pair in reversed( _convert_list_of_dict_to_tuple(sort_list) ):
if sort_pair[0].lstrip('-') in ['data','measure','meta']:
sorted_states= _state_value_sort(sorted_states, sort_pair, _state_key_function)
elif sort_pair[0] == 'groupings':
... |
<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_class(alias):
""" Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_c... |
# Try the CLASS_CACHE first
try:
return CLASS_CACHE[alias]
except KeyError:
pass
for loader in CLASS_LOADERS:
klass = loader(alias)
if klass is None:
continue
if isinstance(klass, python.class_types):
return register_class(klass, alias)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(stream, *args, **kwargs):
""" A generator function to decode a datastream. @param stream: AMF data to be decoded. @type stream: byte data. @kwarg enco... |
encoding = kwargs.pop('encoding', DEFAULT_ENCODING)
decoder = get_decoder(encoding, stream, *args, **kwargs)
return decoder |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(*args, **kwargs):
""" A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L... |
encoding = kwargs.pop('encoding', DEFAULT_ENCODING)
encoder = get_encoder(encoding, **kwargs)
[encoder.writeElement(el) for el in args]
stream = encoder.stream
stream.seek(0)
return stream |
<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_type(type_):
""" Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. @see: L{add_type} and L{remove_type} """ |
if isinstance(type_, list):
type_ = tuple(type_)
for k, v in TYPE_MAP.iteritems():
if k == type_:
return v
raise KeyError("Unknown type %r" % (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 create_signature(self, base_url, payload=None):
""" Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before crea... |
url = urlparse(base_url)
url_to_sign = "{path}?{query}".format(path=url.path, query=url.query)
converted_payload = self._convert(payload)
decoded_key = base64.urlsafe_b64decode(self.private_key.encode('utf-8'))
signature = hmac.new(decoded_key, str.encode(url_to_sign + conver... |
<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(self, payload):
""" Converts payload to a string. Complex objects are dumped to json """ |
if not isinstance(payload, six.string_types):
payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True)
return str(payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(self, document):
"""Create functional data object from JSON document retrieved from database. Parameters document : JSON Json document in database ... |
identifier = str(document['_id'])
active = document['active']
# The directory is not materilaized in database to allow moving the
# base directory without having to update the database.
directory = os.path.join(self.directory, identifier)
timestamp = datetime.datetime.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_torrent(self, torrent_id):
"""Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises T... |
params = {
'page': 'view',
'tid': torrent_id,
}
r = requests.get(self.base_url, params=params)
content = self._get_page_content(r)
# Check if the content div has any child elements
if not len(content):
# The "torrent not found" text i... |
<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_torrent(self, torrent_id):
"""Gets the `.torrent` data for the given `torrent_id`. :param torrent_id: the ID of the torrent to download :raises TorrentNo... |
params = {
'page': 'download',
'tid': torrent_id,
}
r = requests.get(self.base_url, params=params)
if r.headers.get('content-type') != 'application/x-bittorrent':
raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT)
torrent_data = r.content
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, terms, category=Category.all_categories, page=1, sort_key=SearchSortKey.date, order_key=SearchOrderKey.descending):
"""Get a list of torrents th... |
params = {
'page': 'search',
'term': terms,
'cats': category.value,
'sort': sort_key.value,
'order': order_key.value,
}
r = requests.get(self.base_url, params=params)
content = self._get_page_content(r)
# first, get th... |
<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_format_pages_isbn(html_chunk):
""" Parse format, number of pages and ISBN. Args: html_chunk (obj):
HTMLElement containing slice of the page with deta... |
ppi = get_first_content(
html_chunk.find("div", {"class": "price-overflow"})
)
if not ppi:
return None, None, None
# all information this function should parse are at one line
ppi = filter(lambda x: x.strip(), ppi.split("<br />"))[0]
# parse isbn
isbn = dhtmlparser.parseS... |
<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_price(html_chunk):
""" Parse price of the book. Args: html_chunk (obj):
HTMLElement containing slice of the page with details. Returns: str/None: Pri... |
price = get_first_content(
html_chunk.find("div", {"class": "prices"})
)
if not price:
return None
# it is always in format Cena:\n150kč
price = dhtmlparser.removeTags(price)
price = price.split("\n")[-1]
return price |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def workspaces(self, index=None):
"""return generator for all all workspace instances""" |
c = self.centralWidget()
if index is None:
return (c.widget(n) for n in range(c.count()))
else:
return c.widget(index) |
<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(func):
""" Check if annotated function arguments validate according to spec """ |
call = PythonCall(func)
@wraps(func)
def decorator(*args, **kwargs):
parameters = call.bind(args, kwargs)
for arg_name, validator in func.__annotations__.items():
if not validator(parameters[arg_name]):
raise TypeError(
"Argument {!r} failed ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def expression_type(con, topx, ex):
"take a BaseX descendant from sqparse2, return a type class from above"
if isinstance(ex,sqparse2.Literal):
if isinstance(ex.val,basestring): return STRING
else: raise NotImplementedError('literal', type(ex.val))
elif isinstance(ex,sqparse2.AttrX):
if ex.parent.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 call_cur(f):
"decorator for opening a connection and passing a cursor to the function"
@functools.wraps(f)
def f2(self, *args, **kwargs):
with self.withcur() as cur:
return f(self, cur, *args, **kwargs)
return f2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def description(self):
"this is only a property so it can raise; make it an attr once it works"
if self.lastx is None: return
if type(self.lastx) not in (sqparse2.SelectX,sqparse2.UpdateX,sqparse2.InsertX): return
if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX) and self.lastx.ret is None: ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partition(self, mapped_values):
"""Organize the mapped values by their key. Returns an unsorted sequence of tuples with a key and a sequence of values. """ |
partitioned_data = collections.defaultdict(list)
for key, value in mapped_values:
partitioned_data[key].append(value)
return partitioned_data.items() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre(self, command, output_dir, kw):
""" Prepare some context before install Added kwargs in ``kw`` will be accessible into paste template files """ |
# Build a random secret_key
chars = u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
kw['secret_key'] = ''.join([ choice(chars) for i in range(50) ])
# Paste version
kw['epaster_template_name'] = u'emencia-paste-djangocms-3'
kw['epaster_template_version'] = templat... |
<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_mods(self, project_path, vars):
""" Build the mod list to enable """ |
# Start with answers from interactive command
mods = [var.name for var in self.vars if vars[var.name].lower() == 'yes']
mods = set(mods)
# Base mods
for name in self.mods_list:
mods.add(name)
# Conditionnal mods dependancies
if 'accounts' in... |
<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(self, command, output_dir, vars):
""" Do some tasks after install """ |
if command.simulate:
return
# Find the 'project/' dir in the created paste project
project_path = join(getcwd(), vars['project'], 'project')
# 1. Mods
mods = self.get_mods(project_path, vars)
# 2. Create symlinks
for target,... |
<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_full_paths(path_list):
""" Iterates over all paths that are in a directory and its subdirectory, returning fully-specified paths. """ |
for path in path_list:
if not os.path.isdir(path):
full_path = os.path.realpath(path)
yield path
else:
for root, dirs, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.realpath(os.path.join(root, filen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def c(self):
"""Caching client for not repeapting checks""" |
if self._client is None:
self._parse_settings()
self._client = Rumetr(**self.settings)
return self._client |
<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_settings(self):
"""Gets upload options from the scrapy settings""" |
if hasattr(self, 'settings'): # parse setting only one time
return
self.settings = {
'auth_key': self._check_required_setting('RUMETR_TOKEN'),
'developer': self._check_required_setting('RUMETR_DEVELOPER'),
}
self.settings.update(self._non_required_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 _parse_deadline(deadline):
"""Translate deadline date from human-acceptable format to the machine-acceptable""" |
if '-' in deadline and len(deadline) == 10:
return deadline
if '.' in deadline and len(deadline) == 10: # russian format dd.mm.yyyy to yyyy-mm-dd
dmy = deadline.split('.')
if len(dmy) == 3 and all(v is not None for v in dmy):
return '-'.join(reverse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_files(the_path):
"""Given a path, returns whether the path has any files in it or any subfolders. Works recursively.""" |
the_path = Path(the_path)
try:
for _ in the_path.walkfiles():
return True
return False
except OSError as ex:
if ex.errno == errno.ENOENT:
# ignore
return False
else:
raise |
<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(cls, obj):
""" Convert input data to tokens :type obj list|set|tuple """ |
tokens = {}
try:
token_iterator = cls.make_iterable(obj)
_lang = cls.language_definition()
tokens = {k: [] for k in _lang.argument_types}
prev, current = None, next(token_iterator)
while True:
token = [None, None]
arg_type = None
for arg_type in _lang.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, argv, tokenizer=DefaultTokenizer):
""" Parse command line to out tree :type argv object :type tokenizer AbstractTokenizer """ |
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
#
# for param in self.__args:
# if self._is_default_arg(param):
# self.__out_tree[self.__default_arg_tag].append(param.strip())
# else:
# param = param.lstrip("-").partition('=')
# if len(param)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def action(method=None, **kwargs):
""" Decorator that turns a function or controller method into an kervi action. it is possible to call the action in other kerv... |
def action_wrap(f):
action_id = kwargs.get("action_id", f.__name__)
name = kwargs.get("name", action_id)
if not _is_method(f): # not "." in f.__qualname__:
action = Action(f, action_id, name)
Actions.add(action)
return action
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 copy(self, *args, **kwargs):
"""Copy this model element and contained elements if they exist.""" |
for slot in self.__slots__:
attr = getattr(self, slot)
if slot[0] == '_': # convert protected attribute name to public
slot = slot[1:]
if slot not in kwargs:
kwargs[slot] = attr
result = type(self)(*args, **kwargs)
return 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 update(self, other, copy=True, *args, **kwargs):
"""Update this element related to other element. :param other: same type than this. :param bool copy: copy o... |
if other: # dirty hack for python2.6
if isinstance(other, self.__class__):
if copy:
other = other.copy(*args, **kwargs)
for slot in other.__slots__:
attr = getattr(other, slot)
if attr is not 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 __i(self, other, func):
"""Process input other with input func. :param ModelElement(s) other: other ModelElement(s) to process. :param func: function to appl... |
if isinstance(other, type(self)):
other = tuple(other)
elif isinstance(other, self.__contenttype__):
other = (other, )
for melt in list(other):
if not isinstance(melt, self.__contenttype__):
raise TypeError('Wrong element {0}'.format(melt))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.