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 match_tweet(self, tweet, user_stream):
""" Check if a tweet matches the defined criteria :param tweet: The tweet in question :type tweet: :class:`~responsebo... |
if user_stream:
if len(self.track) > 0:
return self.is_tweet_match_track(tweet)
return True
return self.is_tweet_match_track(tweet) or self.is_tweet_match_follow(tweet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectMSExchange(server):
""" Creates a connection for the inputted server to a Microsoft Exchange server. :param server | <smtplib.SMTP> :return (<bool> su... |
if not sspi:
return False, 'No sspi module found.'
# send the SMTP EHLO command
code, response = server.ehlo()
if code != SMTP_EHLO_OKAY:
return False, 'Server did not respond to EHLO command.'
sspi_client = sspi.ClientAuth('NTLM')
# generate NTLM Type 1 message
sec_buffe... |
<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_entries(self, entries: List[Tuple[str, str]], titles, resources):
""" Provide the template the data for the toc entries """ |
self.entries = []
for flag, pagename in entries:
title = titles[pagename].children[0]
resource = resources.get(pagename, None)
if resource and hasattr(resource,
'is_published') and not \
resource.is_published:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, builder, context, sphinx_app: Sphinx):
""" Given a Sphinx builder and context with site in it, generate HTML """ |
context['sphinx_app'] = sphinx_app
context['toctree'] = self
html = builder.templates.render(self.template + '.html', context)
return html |
<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_code(url):
""" Parse the code parameter from the a URL :param str url: URL to parse :return: code query parameter :rtype: str """ |
result = urlparse(url)
query = parse_qs(result.query)
return query['code'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_token(scopes, client_id=None, client_secret=None, redirect_uri=None):
""" Generate a user access token :param List[str] scopes: Scopes to get :param str... |
webbrowser.open_new(authorize_url(client_id=client_id, redirect_uri=redirect_uri, scopes=scopes))
code = parse_code(raw_input('Enter the URL that you were redirected to: '))
return User(code, client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consume_file(self, infile):
"""Load the specified GFF3 file into memory.""" |
reader = tag.reader.GFF3Reader(infilename=infile)
self.consume(reader) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consume(self, entrystream):
""" Load a stream of entries into memory. Only Feature objects and sequence-region directives are loaded, all other entries are d... |
for entry in entrystream:
if isinstance(entry, tag.directive.Directive) and \
entry.type == 'sequence-region':
self.consume_seqreg(entry)
elif isinstance(entry, tag.feature.Feature):
self.consume_feature(entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, seqid, start, end, strict=True):
""" Query the index for features in the specified range. :param seqid: ID of the sequence to query :param start:... |
return sorted([
intvl.data for intvl in self[seqid].search(start, end, strict)
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, stage):
"""Show the functions that are available, bubble system and custom.""" |
if not ctx.bubble:
ctx.say_yellow(
'There is no bubble present, will not show any transformer functions')
raise click.Abort()
rule_functions = get_registered_rule_functions()
ctx.gbc.say('before loading functions:' + str(len(rule_functions)))
load_rule_functions(ctx)
ctx... |
<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_utc(a_datetime, keep_utc_tzinfo=False):
""" Convert a time awared datetime to utc datetime. :param a_datetime: a timezone awared datetime. (If not, then j... |
if a_datetime.tzinfo:
utc_datetime = a_datetime.astimezone(utc) # convert to utc time
if keep_utc_tzinfo is False:
utc_datetime = utc_datetime.replace(tzinfo=None)
return utc_datetime
else:
return a_datetime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False):
""" Convert a UTC datetime to a time awared local time :param utc_datetime: :param tzinfo: :param keep_tz... |
tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo)
if keep_tzinfo is False:
tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None)
return tz_awared_datetime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repr_data_size(size_in_bytes, precision=2):
# pragma: no cover """Return human readable string represent of a file size. Doesn"t support size greater than 1E... |
if size_in_bytes < 1024:
return "%s B" % size_in_bytes
magnitude_of_data = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
index = 0
while 1:
index += 1
size_in_bytes, mod = divmod(size_in_bytes, 1024)
if size_in_bytes < 1024:
break
template = "{0:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_toctrees(kb_app: kb, sphinx_app: Sphinx, doctree: doctree, fromdocname: str):
""" Look in doctrees for toctree and replace with custom render """ |
# Only do any of this if toctree support is turned on in KaybeeSettings.
# By default, this is off.
settings: KaybeeSettings = sphinx_app.config.kaybee_settings
if not settings.articles.use_toctree:
return
# Setup a template and context
builder: StandaloneHTMLBuilder = sphinx_app.buil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stamp_excerpt(kb_app: kb, sphinx_app: Sphinx, doctree: doctree):
""" Walk the tree and extract excert into resource.excerpt """ |
# First, find out which resource this is. Won't be easy.
resources = sphinx_app.env.resources
confdir = sphinx_app.confdir
source = PurePath(doctree.attributes['source'])
# Get the relative path inside the docs dir, without .rst, then
# get the resource
docname = str(source.relative_to(co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bitfieldify(buff, count):
"""Extract a bitarray out of a bytes array. Some hardware devices read from the LSB to the MSB, but the bit types available prefer ... |
databits = bitarray()
databits.frombytes(buff)
return databits[len(databits)-count:] |
<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_byte_align_buff(bits):
"""Pad the left side of a bitarray with 0s to align its length with byte boundaries. Args: bits: A bitarray to be padded and ali... |
bitmod = len(bits)%8
if bitmod == 0:
rdiff = bitarray()
else:
#KEEP bitarray
rdiff = bitarray(8-bitmod)
rdiff.setall(False)
return rdiff+bits |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name, cidr, **kwargs):
"""This function will create a user network. Within OpenStack, it will create a network and a subnet Within AWS, it will ... |
return self.driver.create(name, cidr, **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 find_whole_word(w):
""" Scan through string looking for a location where this word produces a match, and return a corresponding MatchObject instance. Return ... |
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetCompressedFilesInDir(fileDir, fileList, ignoreDirList, supportedFormatList = ['.rar',]):
""" Get all supported files from given directory folder. Appends ... |
goodlogging.Log.Info("EXTRACT", "Parsing file directory: {0}".format(fileDir))
if os.path.isdir(fileDir) is True:
for globPath in glob.glob(os.path.join(fileDir, '*')):
if os.path.splitext(globPath)[1] in supportedFormatList:
fileList.append(globPath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MultipartArchiving(firstPartExtractList, otherPartSkippedList, archiveDir, otherPartFilePath = None):
""" Archive all parts of multi-part compressed file. If... |
if otherPartFilePath is None:
for filePath in list(otherPartSkippedList):
MultipartArchiving(firstPartExtractList, otherPartSkippedList, archiveDir, filePath)
else:
baseFileName = re.findall("(.+?)[.]part.+?rar", otherPartFilePath)[0]
if baseFileName in firstPartExtractList:
util.ArchivePr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DoRarExtraction(rarArchive, targetFile, dstDir):
""" RAR extraction with exception catching Parameters rarArchive : RarFile object RarFile object to extract.... |
try:
rarArchive.extract(targetFile, dstDir)
except BaseException as ex:
goodlogging.Log.Info("EXTRACT", "Extract failed - Exception: {0}".format(ex))
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetRarPassword(skipUserInput):
""" Get password for rar archive from user input. Parameters skipUserInput : boolean Set to skip user input. Returns string or... |
goodlogging.Log.Info("EXTRACT", "RAR file needs password to extract")
if skipUserInput is False:
prompt = "Enter password, 'x' to skip this file or 'exit' to quit this program: "
response = goodlogging.Log.Input("EXTRACT", prompt)
response = util.CheckEmptyResponse(response)
else:
response = '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 CheckPasswordReuse(skipUserInput):
""" Check with user for password reuse. Parameters skipUserInput : boolean Set to skip user input. Returns int Integer fro... |
goodlogging.Log.Info("EXTRACT", "RAR files needs password to extract")
if skipUserInput is False:
prompt = "Enter 't' to reuse the last password for just this file, " \
"'a' to reuse for all subsequent files, " \
"'n' to enter a new password for this file " \
"or 's' to 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 register(self, func, singleton=False, threadlocal=False, name=None):
""" Register a dependency function """ |
func._giveme_singleton = singleton
func._giveme_threadlocal = threadlocal
if name is None:
name = func.__name__
self._registered[name] = func
return 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 get_value(self, name):
""" Get return value of a dependency factory or a live singleton instance. """ |
factory = self._registered.get(name)
if not factory:
raise KeyError('Name not registered')
if factory._giveme_singleton:
if name in self._singletons:
return self._singletons[name]
self._singletons[name] = factory()
return self._sin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace(fun, *a, **k):
""" define a tracer for a rule function for log and statistic purposes """ |
@wraps(fun)
def tracer(*a, **k):
ret = fun(*a, **k)
print('trace:fun: %s\n ret=%s\n a=%s\nk%s\n' %
(str(fun), str(ret), str(a), str(k)))
return ret
return tracer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timer(fun, *a, **k):
""" define a timer for a rule function for log and statistic purposes """ |
@wraps(fun)
def timer(*a, **k):
start = arrow.now()
ret = fun(*a, **k)
end = arrow.now()
print('timer:fun: %s\n start:%s,end:%s, took [%s]' % (
str(fun), str(start), str(end), str(end - start)))
return ret
return timer |
<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_function(self, fun=None):
"""get function as RuleFunction or return a NoRuleFunction function""" |
sfun = str(fun)
self.say('get_function:' + sfun, verbosity=100)
if not fun:
return NoRuleFunction() # dummy to execute via no_fun
if sfun in self._rule_functions:
return self._rule_functions[sfun]
else:
self.add_function(name=sfun,
... |
<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_function(self, fun=None, name=None, fun_type=FUN_TYPE):
"""actually replace function""" |
if not name:
if six.PY2:
name = fun.func_name
else:
name = fun.__name__
self.say('adding fun(%s)' % name, verbosity=50)
self.say('adding fun_type:%s' % fun_type, verbosity=50)
if self.function_exists(name):
self.cry('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function_exists(self, fun):
""" get function's existense """ |
res = fun in self._rule_functions
self.say('function exists:' + str(fun) + ':' + str(res),
verbosity=10)
return 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 rule_function_not_found(self, fun=None):
""" any function that does not exist will be added as a dummy function that will gather inputs for easing into the p... |
sfun = str(fun)
self.cry('rule_function_not_found:' + sfun)
def not_found(*a, **k):
return(sfun + ':rule_function_not_found', k.keys())
return not_found |
<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_value(val):
""" Parse values from html """ |
val = val.replace("%", " ")\
.replace(" ","")\
.replace(",", ".")\
.replace("st","").strip()
missing = ["Ejdeltagit", "N/A"]
if val in missing:
return val
elif val == "":
return None
return float(val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_html(self, url):
""" Get html from url """ |
self.log.info(u"/GET {}".format(url))
r = requests.get(url)
if hasattr(r, 'from_cache'):
if r.from_cache:
self.log.info("(from cache)")
if r.status_code != 200:
throw_request_err(r)
return 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 _get_json(self, url):
""" Get json from url """ |
self.log.info(u"/GET " + url)
r = requests.get(url)
if hasattr(r, 'from_cache'):
if r.from_cache:
self.log.info("(from cache)")
if r.status_code != 200:
throw_request_err(r)
return r.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 regions(self):
""" Get a list of all regions """ |
regions = []
elem = self.dimensions["region"].elem
for option_elem in elem.find_all("option"):
region = option_elem.text.strip()
regions.append(region)
return regions |
<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_region_slug(self, id_or_label):
""" Get the regional slug to be used in url "Norrbotten" => "Norrbottens" :param id_or_label: Id or label of region """ |
#region = self.dimensions["region"].get(id_or_label)
region = id_or_label
slug = region\
.replace(u" ","-")\
.replace(u"ö","o")\
.replace(u"Ö","O")\
.replace(u"ä","a")\
.replace(u"å","a") + "s"
EXCEPTIONS = {
"Jamt... |
<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_value(self):
""" The default category when making a query """ |
if not hasattr(self, "_default_value"):
if self.elem_type == "select":
try:
# Get option marked "selected"
def_value = get_option_value(self.elem.select_one("[selected]"))
except AttributeError:
# ...or if 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 _parse_horizontal_scroll_table(self, table_html):
""" Get list of dicts from horizontally scrollable table """ |
row_labels = [parse_text(x.text) for x in table_html.select(".DTFC_LeftBodyWrapper tbody tr")]
row_label_ids = [None] * len(row_labels)
cols = [parse_text(x.text) for x in table_html.select(".dataTables_scrollHead th")]
value_rows = table_html.select(".dataTables_scrollBody tbody tr")
... |
<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_json_file(filename, show_warnings = False):
"""Check configuration file type is JSON Return a boolean indicating wheather the file is JSON format or not "... |
try:
config_dict = load_config(filename, file_type = "json")
is_json = True
except:
is_json = False
return(is_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 is_yaml_file(filename, show_warnings = False):
"""Check configuration file type is yaml Return a boolean indicating wheather the file is yaml format or not "... |
if is_json_file(filename):
return(False)
try:
config_dict = load_config(filename, file_type = "yaml")
if(type(config_dict) == str):
is_yaml = False
else:
is_yaml = True
except:
is_yaml = False
return(is_yaml) |
<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_ini_file(filename, show_warnings = False):
"""Check configuration file type is INI Return a boolean indicating wheather the file is INI format or not """ |
try:
config_dict = load_config(filename, file_type = "ini")
if config_dict == {}:
is_ini = False
else:
is_ini = True
except:
is_ini = False
return(is_ini) |
<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_toml_file(filename, show_warnings = False):
"""Check configuration file type is TOML Return a boolean indicating wheather the file is TOML format or not "... |
if is_yaml_file(filename):
return(False)
try:
config_dict = load_config(filename, file_type = "toml")
is_toml = True
except:
is_toml = False
return(is_toml) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collect_settings(self, apps):
""" Iterate over given apps or INSTALLED_APPS and collect the content of each's settings file, which is expected to be in JSON... |
contents = {}
if apps:
for app in apps:
if app not in settings.INSTALLED_APPS:
raise CommandError("Application '{0}' not in settings.INSTALLED_APPS".format(app))
else:
apps = settings.INSTALLED_APPS
for app in apps:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def required_unique(objects, key):
""" A pyrsistent invariant which requires all objects in the given iterable to have a unique key. :param objects: The objects ... |
keys = {}
duplicate = set()
for k in map(key, objects):
keys[k] = keys.get(k, 0) + 1
if keys[k] > 1:
duplicate.add(k)
if duplicate:
return (False, u"Duplicate object keys: {}".format(duplicate))
return (True, 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 item_by_name(self, name):
""" Find an item in this collection by its name metadata. :param unicode name: The name of the object for which to search. :raise K... |
for obj in self.items:
if obj.metadata.name == name:
return obj
raise KeyError(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 _init_name_core(self, name: str):
"""Runs whenever a new instance is initialized or `sep` is set.""" |
self.__regex = re.compile(rf'^{self._pattern}$')
self.name = 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 get_name(self, **values) -> str: """Get a new name string from this object's name values. :param values: Variable keyword arguments where the **key** should r... |
if not values and self.name:
return self.name
if values:
# if values are provided, solve compounds that may be affected
for ck, cvs in _sorted_items(self.compounds):
if ck in cvs and ck in values: # redefined compound name to outer scope e.g. fifth =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cast_config(cls, config: typing.Mapping[str, str]) -> typing.Dict[str, str]: """Cast `config` to grouped regular expressions.""" |
return {k: cls.cast(v, k) for k, v in config.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 _execute_primitives(self, commands):
"""Run a list of executable primitives on this controller, and distribute the returned data to the associated TDOPromise... |
for p in commands:
if self._scanchain and self._scanchain._debug:
print(" Executing", p)#pragma: no cover
p.execute(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 pretty_version_text():
"""Return pretty version text listing all plugins.""" |
version_lines = ["dtool, version {}".format(dtool_version)]
version_lines.append("\nBase:")
version_lines.append("dtoolcore, version {}".format(dtoolcore.__version__))
version_lines.append("dtool-cli, version {}".format(__version__))
# List the storage broker packages.
version_lines.append("\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 dtool(debug):
"""Tool to work with datasets.""" |
level = logging.WARNING
if debug:
level = logging.DEBUG
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=level) |
<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_nic(self, instance_id, net_id):
"""Add a Network Interface Controller""" |
#TODO: upgrade with port_id and fixed_ip in future
self.client.servers.interface_attach(
instance_id, None, net_id, None)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_nic(self, instance_id, port_id):
"""Delete a Network Interface Controller""" |
self.client.servers.interface_detach(instance_id, port_id)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disassociate_public_ip(self, public_ip_id):
"""Disassociate a external IP""" |
floating_ip = self.client.floating_ips.get(public_ip_id)
floating_ip = floating_ip.to_dict()
instance_id = floating_ip.get('instance_id')
address = floating_ip.get('ip')
self.client.servers.remove_floating_ip(instance_id, address)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, bitindex):
"""Split a promise into two promises at the provided index. A common operation in JTAG is reading/writing to a register. During the op... |
if bitindex < 0:
raise ValueError("bitindex must be larger or equal to 0.")
if bitindex > len(self):
raise ValueError(
"bitindex larger than the array's size. "
"Len: %s; bitindex: %s"%(len(self), bitindex))
if bitindex == 0:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fulfill(self, bits, ignore_nonpromised_bits=False):
"""Supply the promise with the bits from its associated primitive's execution. The fulfillment process m... |
if self._allsubsfulfilled():
if not self._components:
if ignore_nonpromised_bits:
self._value = bits[self._bitstartselective:
self._bitstartselective +
self._bitlength]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makesubatoffset(self, bitoffset, *, _offsetideal=None):
"""Create a copy of this promise with an offset, and use it as this promise's child. If this promise'... |
if _offsetideal is None:
_offsetideal = bitoffset
if bitoffset is 0:
return self
newpromise = TDOPromise(
self._chain,
self._bitstart + bitoffset,
self._bitlength,
_parent=self,
bitstartselective=self._bitstarts... |
<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, promise, bitoffset, *, _offsetideal=None):
"""Add a promise to the promise collection at an optional offset. Args: promise: A TDOPromise to add to ... |
#This Assumes that things are added in order.
#Sorting or checking should likely be added.
if _offsetideal is None:
_offsetideal = bitoffset
if isinstance(promise, TDOPromise):
newpromise = promise.makesubatoffset(
bitoffset, _offsetideal=_offseti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, bitindex):
"""Split a promise into two promises. A tail bit, and the 'rest'. Same operation as the one on TDOPromise, except this works with a co... |
if bitindex < 0:
raise ValueError("bitindex must be larger or equal to 0.")
if bitindex == 0:
return None, self
lastend = 0
split_promise = False
for splitindex, p in enumerate(self._promises):
if bitindex in range(lastend, p._bitstart):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makesubatoffset(self, bitoffset, *, _offsetideal=None):
"""Create a copy of this PromiseCollection with an offset applied to each contained promise and regis... |
if _offsetideal is None:
_offsetideal = bitoffset
if bitoffset is 0:
return self
newpromise = TDOPromiseCollection(self._chain)
for promise in self._promises:
newpromise.add(promise, bitoffset, _offsetideal=_offsetideal)
return newpromise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, stage):
"""Show transformer rules""" |
if not ctx.bubble:
ctx.say_yellow('There is no bubble present, ' +
'will not show any transformer rules')
raise click.Abort()
path = ctx.home + '/'
RULES = None
ctx.say('Stage:'+stage, verbosity=10)
if stage in STAGES:
if stage in ctx.cfg.CFG:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectExec(connection, protocol, commandLine):
"""Connect a Protocol to a ssh exec session """ |
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestExec(commandLine)
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectShell(connection, protocol):
"""Connect a Protocol to a ssh shell session """ |
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestShell()
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectSubsystem(connection, protocol, subsystem):
"""Connect a Protocol to a ssh subsystem channel """ |
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestSubsystem(subsystem)
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectSession(connection, protocol, sessionFactory=None, *args, **kwargs):
"""Open a SSHSession channel and connect a Protocol to it @param connection: the ... |
factory = sessionFactory or defaultSessionFactory
session = factory(*args, **kwargs)
session.dataReceived = protocol.dataReceived
session.closed = lambda: protocol.connectionLost(connectionDone)
deferred = defer.Deferred()
@deferred.addCallback
def connectProtocolAndReturnSession(specificD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requestSubsystem(self, subsystem):
"""Request a subsystem and return a deferred reply. """ |
data = common.NS(subsystem)
return self.sendRequest('subsystem', data, wantReply=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requestPty(self, term=None, rows=0, cols=0, xpixel=0, ypixel=0, modes=''):
"""Request allocation of a pseudo-terminal for a channel @param term: TERM environ... |
#TODO: Needs testing!
term = term or os.environ.get('TERM', '')
data = packRequest_pty_req(term, (rows, cols, xpixel, ypixel), modes)
return self.sendRequest('pty-req', 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 requestEnv(self, env={}):
"""Send requests to set the environment variables for the channel """ |
for variable, value in env.items():
data = common.NS(variable) + common.NS(value)
self.sendRequest('env', 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 commandstr(command):
"""Convert command into string.""" |
if command == CMD_MESSAGE_ERROR:
msg = "CMD_MESSAGE_ERROR"
elif command == CMD_MESSAGE_LIST:
msg = "CMD_MESSAGE_LIST"
elif command == CMD_MESSAGE_PASSWORD:
msg = "CMD_MESSAGE_PASSWORD"
elif command == CMD_MESSAGE_MP3:
msg = "CMD_MESSAGE_MP3"
elif command == CMD_MESSA... |
<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():
"""Command for reflection database objects""" |
parser = OptionParser(
version=__version__, description=__doc__,
)
parser.add_option(
'-u', '--url', dest='url',
help='Database URL (connection string)',
)
parser.add_option(
'-r', '--render', dest='render', default='dot',
choices=['plantuml', 'dot'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh(self):
""" Refresh all class attributes. """ |
strawpoll_response = requests.get('{api_url}/{poll_id}'.format(api_url=api_url, poll_id=self.id))
raise_status(strawpoll_response)
self.status_code = strawpoll_response.status_code
self.response_json = strawpoll_response.json()
self.id = self.response_json['id']
self.tit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_json_file(self, path):
""" Serialize this VariantCollection to a JSON representation and write it out to a text file. """ |
with open(path, "w") as f:
f.write(self.to_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 read_json_file(cls, path):
""" Construct a VariantCollection from a JSON file. """ |
with open(path, 'r') as f:
json_string = f.read()
return cls.from_json(json_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dumps(data, escape=False, **kwargs):
"""A wrapper around `json.dumps` that can handle objects that json module is not aware. This function is aware of a list... |
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = True
converted = json.dumps(data, default=_converter, **kwargs)
if escape:
# We're escaping the whole dumped string here cause there's no (easy)
# way to hook into the native json library and change how they process
# valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(klass, data):
"""Helper function to access a method that creates objects of a given `klass` with the received `data`. """ |
handler = DESERIALIZE_REGISTRY.get(klass)
if handler:
return handler(data)
raise TypeError("There is no deserializer registered to handle "
"instances of '{}'".format(klass.__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_from(data):
"""Internal function that will be hooked to the native `json.loads` Find the right deserializer for a given value, taking into account t... |
try:
module, klass_name = data['__class__'].rsplit('.', 1)
klass = getattr(import_module(module), klass_name)
except (ImportError, AttributeError, KeyError):
# But I still haven't found what I'm looking for
#
# Waiting for three different exceptions here. KeyError will
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _converter(data):
"""Internal function that will be passed to the native `json.dumps`. This function uses the `REGISTRY` of serializers and try to convert a ... |
handler = REGISTRY.get(data.__class__)
if handler:
full_name = '{}.{}'.format(
data.__class__.__module__,
data.__class__.__name__)
return {
'__class__': full_name,
'__value__': handler(data),
}
raise TypeError(repr(data) + " is not JSO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_error(self, error):
""" Try to detect repetitive errors and sleep for a while to avoid being marked as spam """ |
logging.exception("try to sleep if there are repeating errors.")
error_desc = str(error)
now = datetime.datetime.now()
if error_desc not in self.error_time_log:
self.error_time_log[error_desc] = now
return
time_of_last_encounter = self.error_time_log[str... |
<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_isodate(datestr):
"""Parse a string that loosely fits ISO 8601 formatted date-time string """ |
m = isodate_rx.search(datestr)
assert m, 'unrecognized date format: ' + datestr
year, month, day = m.group('year', 'month', 'day')
hour, minute, second, fraction = m.group('hour', 'minute', 'second', 'fraction')
tz, tzhh, tzmm = m.group('tz', 'tzhh', 'tzmm')
dt = datetime.datetime(int(year), 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 ls( self, rev, path, recursive=False, recursive_dirs=False, directory=False, report=() ):
"""List directory or file :param rev: The revision to use. :param p... |
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log( self, revrange=None, limit=None, firstparent=False, merges=None, path=None, follow=False ):
"""Get commit logs :param revrange: Either a single revision... |
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_create(self, cloudflare_email, cloudflare_pass, unique_id=None):
""" Create new cloudflare user with selected email and id. Optionally also select uniqu... |
params = {
'act': 'user_create',
'cloudflare_email': cloudflare_email,
'cloudflare_pass': cloudflare_pass
}
if unique_id:
params['unique_id'] = unique_id
return self._request(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone_set(self, user_key, zone_name, resolve_to, subdomains):
""" Create new zone for user associated with this user_key. :param user_key: The unique 3auth st... |
params = {
'act': 'zone_set',
'user_key': user_key,
'zone_name': zone_name,
'resolve_to': resolve_to,
'subdomains': subdomains,
}
return self._request(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_zone_set(self, user_key, zone_name):
""" Create new zone and all subdomains for user associated with this user_key. :param user_key: The unique 3auth st... |
params = {
'act': 'full_zone_set',
'user_key': user_key,
'zone_name': zone_name,
}
return self._request(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_lookup(self, cloudflare_email=None, unique_id=None):
""" Lookup user data based on either his cloudflare_email or his unique_id. :param cloudflare_email... |
if not cloudflare_email and not unique_id:
raise KeyError(
'Either cloudflare_email or unique_id must be present')
params = {'act': 'user_lookup'}
if cloudflare_email:
params['cloudflare_email'] = cloudflare_email
else:
params['unique... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_auth( self, cloudflare_email=None, cloudflare_pass=None, unique_id=None ):
""" Get user_key based on either his email and password or unique_id. :param ... |
if not (cloudflare_email and cloudflare_pass) and not unique_id:
raise KeyError(
'Either cloudflare_email and cloudflare_pass or unique_id must be present')
params = {'act': 'user_auth'}
if cloudflare_email and cloudflare_pass:
params['cloudflare_email'] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone_list( self, user_key, limit=100, offset=0, zone_name=None, sub_id=None, zone_status='ALL', sub_status='ALL', ):
""" List zones for a user. :param user_k... |
if zone_status not in ['V', 'D', 'ALL']:
raise ValueError('zone_status has to be V, D or ALL')
if sub_status not in ['V', 'CNL', 'ALL']:
raise ValueError('sub_status has to be V, CNL or ALL')
params = {
'act': 'zone_list',
'user_key': user_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 attr_exists(self, attr):
"""Returns True if at least on instance of the attribute is found """ |
gen = self.attr_gen(attr)
n_instances = len(list(gen))
if n_instances > 0:
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 datasets(self):
"""Method returns a list of dataset paths. Examples -------- print(dataset) '/dataset1/data1/data' '/dataset1/data2/data' '/dataset2/data1/da... |
HiisiHDF._clear_cache()
self.visititems(HiisiHDF._is_dataset)
return HiisiHDF.CACHE['dataset_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 create_from_filedict(self, filedict):
""" Creates h5 file from dictionary containing the file structure. Filedict is a regular dictinary whose keys are hdf5 ... |
if self.mode in ['r+','w', 'w-', 'x', 'a']:
for h5path, path_content in filedict.iteritems():
if path_content.has_key('DATASET'):
# If path exist, write only metadata
if h5path in self:
for key, value in path_content.it... |
<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, attr, value, tolerance=0):
"""Find paths with a key value match Parameters attr : str name of the attribute value : str or numerical value value... |
found_paths = []
gen = self.attr_gen(attr)
for path_attr_pair in gen:
# if attribute is numerical use numerical_value_tolerance in
# value comparison. If attribute is string require exact match
if isinstance(path_attr_pair.value, str):
type_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 _extractReporterIons(ionArrays, reporterMz, mzTolerance):
"""Find and a list of reporter ions and return mz and intensity values. Expected reporter mz values... |
reporterIons = {'mz': [], 'i': []}
for reporterMzValue in reporterMz:
limHi = reporterMzValue * (1+mzTolerance)
limLo = reporterMzValue * (1-mzTolerance)
loPos = bisect.bisect_left(ionArrays['mz'], limLo)
upPos = bisect.bisect_right(ionArrays['mz'], limHi)
matchingValue... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _correctIsotopeImpurities(matrix, intensities):
"""Corrects observed reporter ion intensities for isotope impurities. :params matrix: a matrix (2d nested lis... |
correctedIntensities, _ = scipy.optimize.nnls(matrix, intensities)
return correctedIntensities |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalizeImpurityMatrix(matrix):
"""Normalize each row of the matrix that the sum of the row equals 1. :params matrix: a matrix (2d nested list) containing ... |
newMatrix = list()
for line in matrix:
total = sum(line)
if total != 0:
newMatrix.append([i / total for i in line])
else:
newMatrix.append(line)
return newMatrix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _padImpurityMatrix(matrix, preChannels, postChannels):
"""Align the values of an isotope impurity matrix and fill up with 0. NOTE: The length of the rows in ... |
extendedMatrix = list()
lastMatrixI = len(matrix)-1
for i, line in enumerate(matrix):
prePadding = itertools.repeat(0., i)
postPadding = itertools.repeat(0., lastMatrixI-i)
newLine = list(itertools.chain(prePadding, line, postPadding))
extendedMatrix.append(newLine[preChanne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _processImpurityMatrix(self):
"""Process the impurity matrix so that it can be used to correct observed reporter intensities. """ |
processedMatrix = _normalizeImpurityMatrix(self.impurityMatrix)
processedMatrix = _padImpurityMatrix(
processedMatrix, self.matrixPreChannels, self.matrixPostChannels
)
processedMatrix = _transposeMatrix(processedMatrix)
return processedMatrix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception(message):
"""Exception method convenience wrapper.""" |
def decorator(method):
"""Inner decorator so we can accept arguments."""
@wraps(method)
def wrapper(self, *args, **kwargs):
"""Innermost decorator wrapper - this is confusing."""
if self.messages:
kwargs['message'] = args[0] if args else kwargs.get(... |
<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_dict(self):
"""Convert Exception class to a Python dictionary.""" |
val = dict(self.payload or ())
if self.message:
val['message'] = self.message
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app, config=None, statsd=None):
"""Init Flask Extension.""" |
if config is not None:
self.config = config
elif self.config is None:
self.config = app.config
self.messages = self.config.get('EXCEPTION_MESSAGE', True)
self.prefix = self.config.get('EXCEPTION_PREFIX', DEFAULT_PREFIX)
self.statsd = statsd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.