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 define_attribute(self, name, atype, data=None):
""" Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ |
self.attributes.append(name)
assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),)
self.attribute_types[name] = atype
self.attribute_data[name] = 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 dump(self):
"""Print an overview of the ARFF file.""" |
print("Relation " + self.relation)
print(" With attributes")
for n in self.attributes:
if self.attribute_types[n] != TYPE_NOMINAL:
print(" %s of type %s" % (n, self.attribute_types[n]))
else:
print(" " + n + " of type nominal with values " + ', '.join(self.attribute_data[n]))
for d in self.data:
print(d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alphabetize_attributes(self):
""" Orders attributes names alphabetically, except for the class attribute, which is kept last. """ |
self.attributes.sort(key=lambda name: (name == self.class_attr_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 rgb_to_cmy(r, g=None, b=None):
"""Convert the color from RGB coordinates to CMY. Parameters: :r: :g: :b: Returns: The color as an (c, m, y) tuple in the range: (0, 0.5, 1) """ |
if type(r) in [list,tuple]:
r, g, b = r
return (1-r, 1-g, 1-b) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmy_to_rgb(c, m=None, y=None):
"""Convert the color from CMY coordinates to RGB. Parameters: :c: :m: :y: Returns: The color as an (r, g, b) tuple in the range: (1, 0.5, 0) """ |
if type(c) in [list,tuple]:
c, m, y = c
return (1-c, 1-m, 1-y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def desaturate(self, level):
"""Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce Returns: A grapefruit.Color instance. Color(0.625, 0.5, 0.375, 1.0) (30.0, 0.25, 0.5) """ |
h, s, l = self.__hsl
return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref) |
<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_analogous_scheme(self, angle=30, mode='ryb'):
"""Return two colors analogous to this one. Args: :angle: The angle between the hues of the created colors and this one. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of grapefruit.Colors analogous to this one. (330.0, 1.0, 0.5) (90.0, 1.0, 0.5) (20.0, 1.0, 0.5) (40.0, 1.0, 0.5) """ |
h, s, l = self.__hsl
if mode == 'ryb': h = rgb_to_ryb(h)
h += 360
h1 = (h - angle) % 360
h2 = (h + angle) % 360
if mode == 'ryb':
h1 = ryb_to_rgb(h1)
h2 = ryb_to_rgb(h2)
return (Color((h1, s, l), 'hsl', self.__a, self.__wref),
Color((h2, s, l), 'hsl', self.__a, self.__wref)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alpha_blend(self, other):
"""Alpha-blend this color on the other one. Args: :other: The grapefruit.Color to alpha-blend with this one. Returns: A grapefruit.Color instance which is the result of alpha-blending this color on the other one. Color(1.0, 0.875, 0.75, 0.84) """ |
# get final alpha channel
fa = self.__a + other.__a - (self.__a * other.__a)
# get percentage of source alpha compared to final alpha
if fa==0: sa = 0
else: sa = min(1.0, self.__a/other.__a)
# destination percentage is just the additive inverse
da = 1.0 - sa
sr, sg, sb = [v * sa for v in self.__rgb]
dr, dg, db = [v * da for v in other.__rgb]
return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blend(self, other, percent=0.5):
"""blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. Color(1.0, 0.75, 0.5, 0.4) """ |
dest = 1.0 - percent
rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb)))
a = (self.__a * percent) + (other.__a * dest)
return Color(rgb, 'rgb', a, self.__wref) |
<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_input(args):
"""Split query input into local files and URLs.""" |
args['files'] = []
args['urls'] = []
for arg in args['query']:
if os.path.isfile(arg):
args['files'].append(arg)
else:
args['urls'].append(arg.strip('/')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_output_type(args):
"""Detect whether to save to a single or multiple files.""" |
if not args['single'] and not args['multiple']:
# Save to multiple files if multiple files/URLs entered
if len(args['query']) > 1 or len(args['out']) > 1:
args['multiple'] = True
else:
args['single'] = 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 scrape(args):
"""Scrape webpage content.""" |
try:
base_dir = os.getcwd()
if args['out'] is None:
args['out'] = []
# Detect whether to save to a single or multiple files
detect_output_type(args)
# Split query input into local files and URLs
split_input(args)
if args['urls']:
# Add URL extensions and schemes and update query and URLs
urls_with_exts = [utils.add_url_suffix(x) for x in args['urls']]
args['query'] = [utils.add_protocol(x) if x in args['urls'] else x
for x in urls_with_exts]
args['urls'] = [x for x in args['query'] if x not in args['files']]
# Print error if attempting to convert local files to HTML
if args['files'] and args['html']:
sys.stderr.write('Cannot convert local files to HTML.\n')
args['files'] = []
# Instantiate web crawler if necessary
crawler = None
if args['crawl'] or args['crawl_all']:
crawler = Crawler(args)
if args['single']:
return write_single_file(args, base_dir, crawler)
elif args['multiple']:
return write_multiple_files(args, base_dir, crawler)
except (KeyboardInterrupt, Exception):
if args['html']:
try:
os.chdir(base_dir)
except OSError:
pass
else:
utils.remove_part_files()
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 prompt_filetype(args):
"""Prompt user for filetype if none specified.""" |
valid_types = ('print', 'text', 'csv', 'pdf', 'html')
if not any(args[x] for x in valid_types):
try:
filetype = input('Print or save output as ({0}): '
.format(', '.join(valid_types))).lower()
while filetype not in valid_types:
filetype = input('Invalid entry. Choose from ({0}): '
.format(', '.join(valid_types))).lower()
except (KeyboardInterrupt, EOFError):
return
args[filetype] = 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 command_line_runner():
"""Handle command-line interaction.""" |
parser = get_parser()
args = vars(parser.parse_args())
if args['version']:
print(__version__)
return
if args['clear_cache']:
utils.clear_cache()
print('Cleared {0}.'.format(utils.CACHE_DIR))
return
if not args['query']:
parser.print_help()
return
# Enable cache unless user sets environ variable SCRAPE_DISABLE_CACHE
if not os.getenv('SCRAPE_DISABLE_CACHE'):
utils.enable_cache()
# Save images unless user sets environ variable SCRAPE_DISABLE_IMGS
if os.getenv('SCRAPE_DISABLE_IMGS'):
args['no_images'] = True
# Prompt user for filetype if none specified
prompt_filetype(args)
# Prompt user to save images when crawling (for pdf and HTML formats)
prompt_save_images(args)
# Scrape webpage content
scrape(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 load_raw(cls, model_fn, schema, *args, **kwargs):
""" Loads a trained classifier from the raw Weka model format. Must specify the model schema and classifier name, since these aren't currently deduced from the model format. """ |
c = cls(*args, **kwargs)
c.schema = schema.copy(schema_only=True)
c._model_data = open(model_fn, 'rb').read()
return c |
<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_training_coverage(self):
""" Returns a ratio of classifiers that were able to be trained successfully. """ |
total = len(self.training_results)
i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring))
return i/float(total) |
<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_new_links(self, url, resp):
"""Get new links from a URL and filter them.""" |
links_on_page = resp.xpath('//a/@href')
links = [utils.clean_url(u, url) for u in links_on_page]
# Remove non-links through filtering by protocol
links = [x for x in links if utils.check_protocol(x)]
# Restrict new URLs by the domain of the input URL
if not self.args['nonstrict']:
domain = utils.get_domain(url)
links = [x for x in links if utils.get_domain(x) == domain]
# Filter URLs by regex keywords, if any
if self.args['crawl']:
links = utils.re_filter(links, self.args['crawl'])
return links |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_crawled(self, page_resp):
"""Check if page has been crawled by hashing its text content. Add new pages to the page cache. Return whether page was found in cache. """ |
page_text = utils.parse_text(page_resp)
page_hash = utils.hash_text(''.join(page_text))
if page_hash not in self.page_cache:
utils.cache_page(self.page_cache, page_hash, self.args['cache_size'])
return False
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 crawl_links(self, seed_url=None):
"""Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling. """ |
if seed_url is not None:
self.seed_url = seed_url
if self.seed_url is None:
sys.stderr.write('Crawling requires a seed URL.\n')
return []
prev_part_num = utils.get_num_part_files()
crawled_links = set()
uncrawled_links = OrderedSet()
uncrawled_links.add(self.seed_url)
try:
while uncrawled_links:
# Check limit on number of links and pages to crawl
if self.limit_reached(len(crawled_links)):
break
url = uncrawled_links.pop(last=False)
# Remove protocol, fragments, etc. to get unique URLs
unique_url = utils.remove_protocol(utils.clean_url(url))
if unique_url not in crawled_links:
raw_resp = utils.get_raw_resp(url)
if raw_resp is None:
if not self.args['quiet']:
sys.stderr.write('Failed to parse {0}.\n'.format(url))
continue
resp = lh.fromstring(raw_resp)
if self.page_crawled(resp):
continue
crawled_links.add(unique_url)
new_links = self.get_new_links(url, resp)
uncrawled_links.update(new_links)
if not self.args['quiet']:
print('Crawled {0} (#{1}).'.format(url, len(crawled_links)))
# Write page response to PART.html file
utils.write_part_file(self.args, url, raw_resp, resp, len(crawled_links))
except (KeyboardInterrupt, EOFError):
pass
curr_part_num = utils.get_num_part_files()
return utils.get_part_filenames(curr_part_num, prev_part_num) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_proxies():
"""Get available proxies to use with requests library.""" |
proxies = getproxies()
filtered_proxies = {}
for key, value in proxies.items():
if key.startswith('http://'):
if not value.startswith('http://'):
filtered_proxies[key] = 'http://{0}'.format(value)
else:
filtered_proxies[key] = value
return filtered_proxies |
<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_resp(url):
"""Get webpage response as an lxml.html.HtmlElement object.""" |
try:
headers = {'User-Agent': random.choice(USER_AGENTS)}
try:
request = requests.get(url, headers=headers, proxies=get_proxies())
except MissingSchema:
url = add_protocol(url)
request = requests.get(url, headers=headers, proxies=get_proxies())
return lh.fromstring(request.text.encode('utf-8') if PY2 else request.text)
except Exception:
sys.stderr.write('Failed to retrieve {0}.\n'.format(url))
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 enable_cache():
"""Enable requests library cache.""" |
try:
import requests_cache
except ImportError as err:
sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err)))
return
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
requests_cache.install_cache(CACHE_FILE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_text(text):
"""Return MD5 hash of a string.""" |
md5 = hashlib.md5()
md5.update(text)
return md5.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_page(page_cache, page_hash, cache_size):
"""Add a page to the page cache.""" |
page_cache.append(page_hash)
if len(page_cache) > cache_size:
page_cache.pop(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 re_filter(text, regexps):
"""Filter text using regular expressions.""" |
if not regexps:
return text
matched_text = []
compiled_regexps = [re.compile(x) for x in regexps]
for line in text:
if line in matched_text:
continue
for regexp in compiled_regexps:
found = regexp.search(line)
if found and found.group():
matched_text.append(line)
return matched_text or 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 remove_whitespace(text):
"""Remove unnecessary whitespace while keeping logical structure. Keyword arguments: text -- text to remove whitespace from (list) Retain paragraph structure but remove other whitespace, such as between words on a line and at the start and end of the text. """ |
clean_text = []
curr_line = ''
# Remove any newlines that follow two lines of whitespace consecutively
# Also remove whitespace at start and end of text
while text:
if not curr_line:
# Find the first line that is not whitespace and add it
curr_line = text.pop(0)
while not curr_line.strip() and text:
curr_line = text.pop(0)
if curr_line.strip():
clean_text.append(curr_line)
else:
# Filter the rest of the lines
curr_line = text.pop(0)
if not text:
# Add the final line if it is not whitespace
if curr_line.strip():
clean_text.append(curr_line)
continue
if curr_line.strip():
clean_text.append(curr_line)
else:
# If the current line is whitespace then make sure there is
# no more than one consecutive line of whitespace following
if not text[0].strip():
if len(text) > 1 and text[1].strip():
clean_text.append(curr_line)
else:
clean_text.append(curr_line)
# Now filter each individual line for extraneous whitespace
cleaner_text = []
for line in clean_text:
clean_line = ' '.join(line.split())
if not clean_line.strip():
clean_line += '\n'
cleaner_text.append(clean_line)
return cleaner_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 parse_text(infile, xpath=None, filter_words=None, attributes=None):
"""Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list) attributes -- HTML tag attributes (list) Return a list of strings of text. """ |
infiles = []
text = []
if xpath is not None:
infile = parse_html(infile, xpath)
if isinstance(infile, list):
if isinstance(infile[0], lh.HtmlElement):
infiles = list(infile)
else:
text = [line + '\n' for line in infile]
elif isinstance(infile, lh.HtmlElement):
infiles = [infile]
else:
text = [infile]
else:
infiles = [infile]
if attributes is not None:
attributes = [clean_attr(x) for x in attributes]
attributes = [x for x in attributes if x]
else:
attributes = ['text()']
if not text:
text_xpath = '//*[not(self::script) and not(self::style)]'
for attr in attributes:
for infile in infiles:
if isinstance(infile, lh.HtmlElement):
new_text = infile.xpath('{0}/{1}'.format(text_xpath, attr))
else:
# re.split preserves delimiters place in the list
new_text = [x for x in re.split('(\n)', infile) if x]
text += new_text
if filter_words is not None:
text = re_filter(text, filter_words)
return [''.join(x for x in line if x in string.printable)
for line in remove_whitespace(text) if line] |
<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_parsed_text(args, infilename):
"""Parse and return text content of infiles. Keyword arguments: args -- program arguments (dict) infilenames -- name of user-inputted and/or downloaded file (str) Return a list of strings of text. """ |
parsed_text = []
if infilename.endswith('.html'):
# Convert HTML to lxml object for content parsing
html = lh.fromstring(read_files(infilename))
text = None
else:
html = None
text = read_files(infilename)
if html is not None:
parsed_text = parse_text(html, args['xpath'], args['filter'],
args['attributes'])
elif text is not None:
parsed_text = parse_text(text, args['xpath'], args['filter'])
else:
if not args['quiet']:
sys.stderr.write('Failed to parse text from {0}.\n'
.format(infilename))
return parsed_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 parse_html(infile, xpath):
"""Filter HTML using XPath.""" |
if not isinstance(infile, lh.HtmlElement):
infile = lh.fromstring(infile)
infile = infile.xpath(xpath)
if not infile:
raise ValueError('XPath {0} returned no results.'.format(xpath))
return infile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_url(url, base_url=None):
"""Add base netloc and path to internal URLs and remove www, fragments.""" |
parsed_url = urlparse(url)
fragment = '{url.fragment}'.format(url=parsed_url)
if fragment:
url = url.split(fragment)[0]
# Identify internal URLs and fix their format
netloc = '{url.netloc}'.format(url=parsed_url)
if base_url is not None and not netloc:
parsed_base = urlparse(base_url)
split_base = '{url.scheme}://{url.netloc}{url.path}/'.format(url=parsed_base)
url = urljoin(split_base, url)
netloc = '{url.netloc}'.format(url=urlparse(url))
if 'www.' in netloc:
url = url.replace(netloc, netloc.replace('www.', ''))
return url.rstrip(string.punctuation) |
<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_outfilename(url, domain=None):
"""Construct the output filename from domain and end of path.""" |
if domain is None:
domain = get_domain(url)
path = '{url.path}'.format(url=urlparse(url))
if '.' in path:
tail_url = path.split('.')[-2]
else:
tail_url = path
if tail_url:
if '/' in tail_url:
tail_pieces = [x for x in tail_url.split('/') if x]
tail_url = tail_pieces[-1]
# Keep length of return string below or equal to max_len
max_len = 24
if domain:
max_len -= (len(domain) + 1)
if len(tail_url) > max_len:
if '-' in tail_url:
tail_pieces = [x for x in tail_url.split('-') if x]
tail_url = tail_pieces.pop(0)
if len(tail_url) > max_len:
tail_url = tail_url[:max_len]
else:
# Add as many tail pieces that can fit
tail_len = 0
for piece in tail_pieces:
tail_len += len(piece)
if tail_len <= max_len:
tail_url += '-' + piece
else:
break
else:
tail_url = tail_url[:max_len]
if domain:
return '{0}-{1}'.format(domain, tail_url).lower()
return tail_url
return domain.lower() |
<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_single_outfilename(args):
"""Use first possible entry in query as filename.""" |
for arg in args['query']:
if arg in args['files']:
return ('.'.join(arg.split('.')[:-1])).lower()
for url in args['urls']:
if arg.strip('/') in url:
domain = get_domain(url)
return get_outfilename(url, domain)
sys.stderr.write('Failed to construct a single out filename.\n')
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier.""" |
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1
# Reconstruct filename with incremented id and its extension
filename = ''.join((re.sub(id_num_re, '({0})'.format(new_id_num),
split_filename[-2]), split_filename[-1]))
else:
split_filename = os.path.splitext(filename)
# Reconstruct filename with new id and its extension
filename = ''.join(('{0} (2)'.format(split_filename[-2]),
split_filename[-1]))
return 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 overwrite_file_check(args, filename):
"""If filename exists, overwrite or modify it to be unique.""" |
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
try:
overwrite = confirm_input(input('Overwrite {0}? (yes/no): '
.format(filename)))
except (KeyboardInterrupt, EOFError):
sys.exit()
if not overwrite:
new_filename = modify_filename_id(filename)
while os.path.exists(new_filename):
new_filename = modify_filename_id(new_filename)
return new_filename
return 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 print_text(args, infilenames, outfilename=None):
"""Print text content of infiles to stdout. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- only used for interface purposes (None) """ |
for infilename in infilenames:
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
for line in parsed_text:
print(line)
print('') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_file(data, outfilename):
"""Write a single file to disk.""" |
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
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 get_num_part_files():
"""Get the number of PART.html files currently saved to disk.""" |
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts |
<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_part_filenames(num_parts=None, start_num=0):
"""Get numbered PART.html filenames.""" |
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+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 read_files(filenames):
"""Read a file into memory.""" |
if isinstance(filenames, list):
for filename in filenames:
with open(filename, 'r') as infile:
return infile.read()
else:
with open(filenames, 'r') as infile:
return infile.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 confirm_input(user_input):
"""Check user input for yes, no, or an exit signal.""" |
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except AttributeError:
u_inp = user_input
# Check for exit signal
if u_inp in ('q', 'quit', 'exit'):
sys.exit()
if u_inp in ('y', 'yes'):
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 convert(data, in_format, out_format, name=None, pretty=False):
"""Converts between two inputted chemical formats. Args: data: A string representing the chemical file to be converted. If the `in_format` is "json", this can also be a Python object in_format: The format of the `data` string. Can be "json" or any format recognized by Open Babel out_format: The format to convert to. Can be "json" or any format recognized by Open Babel name: (Optional) If `out_format` is "json", will save the specified value in a "name" property pretty: (Optional) If True and `out_format` is "json", will pretty- print the output for human readability Returns: A string representing the inputted `data` in the specified `out_format` """ |
# Decide on a json formatter depending on desired prettiness
dumps = json.dumps if pretty else json.compress
# Shortcut for avoiding pybel dependency
if not has_ob and in_format == 'json' and out_format == 'json':
return dumps(json.loads(data) if is_string(data) else data)
elif not has_ob:
raise ImportError("Chemical file format conversion requires pybel.")
# These use the open babel library to interconvert, with additions for json
if in_format == 'json':
mol = json_to_pybel(json.loads(data) if is_string(data) else data)
elif in_format == 'pybel':
mol = data
else:
mol = pybel.readstring(in_format, data)
# Infer structure in cases where the input format has no specification
if not mol.OBMol.HasNonZeroCoords():
mol.make3D()
# Make P1 if that's a thing, recalculating bonds in process
if in_format == 'mmcif' and hasattr(mol, 'unitcell'):
mol.unitcell.FillUnitCell(mol.OBMol)
mol.OBMol.ConnectTheDots()
mol.OBMol.PerceiveBondOrders()
mol.OBMol.Center()
if out_format == 'pybel':
return mol
elif out_format == 'object':
return pybel_to_json(mol, name)
elif out_format == 'json':
return dumps(pybel_to_json(mol, name))
else:
return mol.write(out_format) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_to_pybel(data, infer_bonds=False):
"""Converts python data structure to pybel.Molecule. This will infer bond data if not specified. Args: data: The loaded json data of a molecule, as a Python object infer_bonds (Optional):
If no bonds specified in input, infer them Returns: An instance of `pybel.Molecule` """ |
obmol = ob.OBMol()
obmol.BeginModify()
for atom in data['atoms']:
obatom = obmol.NewAtom()
obatom.SetAtomicNum(table.GetAtomicNum(str(atom['element'])))
obatom.SetVector(*atom['location'])
if 'label' in atom:
pd = ob.OBPairData()
pd.SetAttribute('_atom_site_label')
pd.SetValue(atom['label'])
obatom.CloneData(pd)
# If there is no bond data, try to infer them
if 'bonds' not in data or not data['bonds']:
if infer_bonds:
obmol.ConnectTheDots()
obmol.PerceiveBondOrders()
# Otherwise, use the bonds in the data set
else:
for bond in data['bonds']:
if 'atoms' not in bond:
continue
obmol.AddBond(bond['atoms'][0] + 1, bond['atoms'][1] + 1,
bond['order'])
# Check for unit cell data
if 'unitcell' in data:
uc = ob.OBUnitCell()
uc.SetData(*(ob.vector3(*v) for v in data['unitcell']))
uc.SetSpaceGroup('P1')
obmol.CloneData(uc)
obmol.EndModify()
mol = pybel.Molecule(obmol)
# Add partial charges
if 'charge' in data['atoms'][0]:
mol.OBMol.SetPartialChargesPerceived()
for atom, pyatom in zip(data['atoms'], mol.atoms):
pyatom.OBAtom.SetPartialCharge(atom['charge'])
return mol |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json. Args: molecule: An instance of `pybel.Molecule` name: (Optional) If specified, will save a "name" property Returns: A Python dictionary containing atom and bond data """ |
# Save atom element type and 3D location.
atoms = [{'element': table.GetSymbol(atom.atomicnum),
'location': list(atom.coords)}
for atom in molecule.atoms]
# Recover auxiliary data, if exists
for json_atom, pybel_atom in zip(atoms, molecule.atoms):
if pybel_atom.partialcharge != 0:
json_atom['charge'] = pybel_atom.partialcharge
if pybel_atom.OBAtom.HasData('_atom_site_label'):
obatom = pybel_atom.OBAtom
json_atom['label'] = obatom.GetData('_atom_site_label').GetValue()
if pybel_atom.OBAtom.HasData('color'):
obatom = pybel_atom.OBAtom
json_atom['color'] = obatom.GetData('color').GetValue()
# Save number of bonds and indices of endpoint atoms
bonds = [{'atoms': [b.GetBeginAtom().GetIndex(),
b.GetEndAtom().GetIndex()],
'order': b.GetBondOrder()}
for b in ob.OBMolBondIter(molecule.OBMol)]
output = {'atoms': atoms, 'bonds': bonds, 'units': {}}
# If there's unit cell data, save it to the json output
if hasattr(molecule, 'unitcell'):
uc = molecule.unitcell
output['unitcell'] = [[v.GetX(), v.GetY(), v.GetZ()]
for v in uc.GetCellVectors()]
density = (sum(atom.atomicmass for atom in molecule.atoms) /
(uc.GetCellVolume() * 0.6022))
output['density'] = density
output['units']['density'] = 'kg / L'
# Save the formula to json. Use Hill notation, just to have a standard.
element_count = Counter(table.GetSymbol(a.atomicnum) for a in molecule)
hill_count = []
for element in ['C', 'H']:
if element in element_count:
hill_count += [(element, element_count[element])]
del element_count[element]
hill_count += sorted(element_count.items())
# If it's a crystal, then reduce the Hill formula
div = (reduce(gcd, (c[1] for c in hill_count))
if hasattr(molecule, 'unitcell') else 1)
output['formula'] = ''.join(n if c / div == 1 else '%s%d' % (n, c / div)
for n, c in hill_count)
output['molecular_weight'] = molecule.molwt / div
output['units']['molecular_weight'] = 'g / mol'
# If the input has been given a name, add that
if name:
output['name'] = name
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 default(self, obj):
"""Fired when an unserializable object is hit.""" |
if hasattr(obj, '__dict__'):
return obj.__dict__.copy()
elif HAS_NUMPY and isinstance(obj, np.ndarray):
return obj.copy().tolist()
else:
raise TypeError(("Object of type {:s} with value of {:s} is not "
"JSON serializable").format(type(obj), repr(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 generate(data, format="auto"):
"""Converts input chemical formats to json and optimizes structure. Args: data: A string or file representing a chemical format: The format of the `data` variable (default is 'auto') The `format` can be any value specified by Open Babel (http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto' option uses the extension for files (ie. my_file.mol -> mol) and defaults to SMILES (smi) for strings. """ |
# Support both files and strings and attempt to infer file type
try:
with open(data) as in_file:
if format == 'auto':
format = data.split('.')[-1]
data = in_file.read()
except:
if format == 'auto':
format = 'smi'
return format_converter.convert(data, format, '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 start_server():
"""Starts up the imolecule server, complete with argparse handling.""" |
parser = argparse.ArgumentParser(description="Opens a browser-based "
"client that interfaces with the "
"chemical format converter.")
parser.add_argument('--debug', action="store_true", help="Prints all "
"transmitted data streams.")
parser.add_argument('--port', type=int, default=8000, help="The port "
"on which to serve the website.")
parser.add_argument('--timeout', type=int, default=5, help="The maximum "
"time, in seconds, allowed for a process to run "
"before returning an error.")
parser.add_argument('--workers', type=int, default=2, help="The number of "
"worker processes to use with the server.")
parser.add_argument('--no-browser', action="store_true", help="Disables "
"opening a browser window on startup.")
global args
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
(r'/static/(.*)', tornado.web.StaticFileHandler,
{'path': os.path.normpath(os.path.dirname(__file__))})]
application = tornado.web.Application(handlers)
application.listen(args.port)
if not args.no_browser:
webbrowser.open('http://localhost:%d/' % args.port, new=2)
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
tornado.ioloop.IOLoop.instance().stop()
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 heronsArea(self):
'''
Heron's forumla for computing the area of a triangle, float.
Performance note: contains a square root.
'''
s = self.semiperimeter
return math.sqrt(s * ((s - self.a) * (s - self.b) * (s - self.c))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def circumradius(self):
'''
Distance from the circumcenter to all the verticies in
the Triangle, float.
'''
return (self.a * self.b * self.c) / (self.area * 4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def isIsosceles(self):
'''
True iff two side lengths are equal, boolean.
'''
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def congruent(self, other):
'''
A congruent B
True iff all angles of 'A' equal angles in 'B' and
all side lengths of 'A' equal all side lengths of 'B', boolean.
'''
a = set(self.angles)
b = set(other.angles)
if len(a) != len(b) or len(a.difference(b)) != 0:
return False
a = set(self.sides)
b = set(other.sides)
return len(a) == len(b) and len(a.difference(b)) == 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 center(self):
'''
Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin.
'''
try:
return self._center
except AttributeError:
pass
self._center = Point()
return self._center |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def radius(self):
'''
Radius of the ellipse, Point class.
'''
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.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 xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.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 yAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the Y axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def yAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the Y axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def a(self):
'''
Positive antipodal point on the major axis, Point class.
'''
a = Point(self.center)
if self.xAxisIsMajor:
a.x += self.majorRadius
else:
a.y += self.majorRadius
return 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 a_neg(self):
'''
Negative antipodal point on the major axis, Point class.
'''
na = Point(self.center)
if self.xAxisIsMajor:
na.x -= self.majorRadius
else:
na.y -= self.majorRadius
return 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 b(self):
'''
Positive antipodal point on the minor axis, Point class.
'''
b = Point(self.center)
if self.xAxisIsMinor:
b.x += self.minorRadius
else:
b.y += self.minorRadius
return b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def b_neg(self):
'''
Negative antipodal point on the minor axis, Point class.
'''
nb = Point(self.center)
if self.xAxisIsMinor:
nb.x -= self.minorRadius
else:
nb.y -= self.minorRadius
return nb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vertices(self):
'''
A dictionary of four points where the axes intersect the ellipse, dict.
'''
return {'a': self.a, 'a_neg': self.a_neg,
'b': self.b, 'b_neg': self.b_neg} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def focus0(self):
'''
First focus of the ellipse, Point class.
'''
f = Point(self.center)
if self.xAxisIsMajor:
f.x -= self.linearEccentricity
else:
f.y -= self.linearEccentricity
return 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 AB(self):
'''
A list containing Points A and B.
'''
try:
return self._AB
except AttributeError:
pass
self._AB = [self.A, self.B]
return self._AB |
<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):
'''
Third vertex of triangle, Point subclass.
'''
try:
return self._C
except AttributeError:
pass
self._C = Point(0, 1)
return self._C |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ABC(self):
'''
A list of the triangle's vertices, list.
'''
try:
return self._ABC
except AttributeError:
pass
self._ABC = [self.A, self.B, self.C]
return self._ABC |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BA(self):
'''
Vertices B and A, list.
'''
try:
return self._BA
except AttributeError:
pass
self._BA = [self.B, self.A]
return self._BA |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def AC(self):
'''
Vertices A and C, list.
'''
try:
return self._AC
except AttributeError:
pass
self._AC = [self.A, self.C]
return self._AC |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def CA(self):
'''
Vertices C and A, list.
'''
try:
return self._CA
except AttributeError:
pass
self._CA = [self.C, self.A]
return self._CA |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def BC(self):
'''
Vertices B and C, list.
'''
try:
return self._BC
except AttributeError:
pass
self._BC = [self.B, self.C]
return self._BC |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def CB(self):
'''
Vertices C and B, list.
'''
try:
return self._CB
except AttributeError:
pass
self._CB = [self.C, self.B]
return self._CB |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def circumcenter(self):
'''
The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
BUG: only finds the circumcenter in the XY plane
'''
if self.isRight:
return self.hypotenuse.midpoint
if self.A.isOrigin:
t = self
else:
# translate triangle to origin
t = Triangle(self.A - self.A, self.B - self.A, self.C - self.A)
# XXX translation would be easier by defining add and sub for points
# t = self - self.A
if not t.A.isOrigin:
raise ValueError('failed to translate {} to origin'.format(t))
BmulC = t.B * t.C.yx
d = 2 * (BmulC.x - BmulC.y)
bSqSum = sum((t.B ** 2).xy)
cSqSum = sum((t.C ** 2).xy)
x = (((t.C.y * bSqSum) - (t.B.y * cSqSum)) / d) + self.A.x
y = (((t.B.x * cSqSum) - (t.C.x * bSqSum)) / d) + self.A.y
return Point(x, y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def isEquilateral(self):
'''
True if all sides of the triangle are the same length.
All equilateral triangles are also isosceles.
All equilateral triangles are also acute.
'''
if not nearly_eq(self.a, self.b):
return False
if not nearly_eq(self.b, self.c):
return False
return nearly_eq(self.a, self.c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def perimeter(self):
'''
Sum of the length of all sides, float.
'''
return sum([a.distance(b) for a, b in self.pairs()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rgb2gray(img):
"""Converts an RGB image to grayscale using matlab's algorithm.""" |
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * r + g_c * g + b_c * b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rgb2hsv(arr):
"""Converts an RGB image to HSV using scikit-image's algorithm.""" |
arr = np.asanyarray(arr)
if arr.ndim != 3 or arr.shape[2] != 3:
raise ValueError("the input array must have a shape == (.,.,3)")
arr = as_float_image(arr)
out = np.empty_like(arr)
# -- V channel
out_v = arr.max(-1)
# -- S channel
delta = arr.ptp(-1)
# Ignore warning for zero divided by zero
old_settings = np.seterr(invalid='ignore')
out_s = delta / out_v
out_s[delta == 0.] = 0.
# -- H channel
# red is max
idx = (arr[:, :, 0] == out_v)
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[:, :, 1] == out_v)
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = (arr[:, :, 2] == out_v)
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out_h = (out[:, :, 0] / 6.) % 1.
out_h[delta == 0.] = 0.
np.seterr(**old_settings)
# -- output
out[:, :, 0] = out_h
out[:, :, 1] = out_s
out[:, :, 2] = out_v
# remove NaN
out[np.isnan(out)] = 0
return out |
<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_command_response(response):
"""Parse an SCI command response into ElementTree XML This is a helper method that takes a Requests Response object of an SCI command response and will parse it into an ElementTree Element representing the root of the XML response. :param response: The requests response object :return: An ElementTree Element that is the root of the response XML :raises ResponseParseError: If the response XML is not well formed """ |
try:
root = ET.fromstring(response.text)
except ET.ParseError:
raise ResponseParseError(
"Unexpected response format, could not parse XML. Response: {}".format(response.text))
return root |
<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_error_tree(error):
"""Parse an error ElementTree Node to create an ErrorInfo object :param error: The ElementTree error node :return: An ErrorInfo object containing the error ID and the message. """ |
errinf = ErrorInfo(error.get('id'), None)
if error.text is not None:
errinf.message = error.text
else:
desc = error.find('./desc')
if desc is not None:
errinf.message = desc.text
return errinf |
<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_data(self):
"""Get the contents of this file :return: The contents of this file :rtype: six.binary_type """ |
target = DeviceTarget(self.device_id)
return self._fssapi.get_file(target, self.path)[self.device_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete this file from the device .. note:: After deleting the file, this object will no longer contain valid information and further calls to delete or get_data will return :class:`~.ErrorInfo` objects """ |
target = DeviceTarget(self.device_id)
return self._fssapi.delete_file(target, self.path)[self.device_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_contents(self):
"""List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo object ldata = dirinfo.list_contents() if isinstance(ldata, ErrorInfo):
# Do some error handling logger.warn("Error listing file info: (%s) %s", ldata.errno, ldata.message) # It's of type LsInfo else: # Look at all the files for finfo in ldata.files: logger.info("Found file %s of size %s", finfo.path, finfo.size) # Look at all the directories for dinfo in ldata.directories: logger.info("Found directory %s of last modified %s", dinfo.path, dinfo.last_modified) """ |
target = DeviceTarget(self.device_id)
return self._fssapi.list_files(target, self.path)[self.device_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_response(cls, response, device_id=None, fssapi=None, **kwargs):
"""Parse the server response for this ls command This will parse xml of the following form:: <ls hash="hash_type"> <dir path="dir_path" last_modified=last_modified_time /> </ls> or with an error:: <ls> </ls> :param response: The XML root of the response for an ls command :type response: :class:`xml.etree.ElementTree.Element` :param device_id: The device id of the device this ls response came from :param fssapi: A reference to a :class:`~FileSystemServiceAPI` for use with the :class:`~FileInfo` and :class:`~DirectoryInfo` objects for future commands :return: An :class:`~LsInfo` object containing the list of directories and files on the device or an :class:`~ErrorInfo` if the xml contained an error """ |
if response.tag != cls.command_name:
raise ResponseParseError(
"Received response of type {}, LsCommand can only parse responses of type {}".format(response.tag,
cls.command_name))
if fssapi is None:
raise FileSystemServiceException("fssapi is required to parse an LsCommand response")
if device_id is None:
raise FileSystemServiceException("device_id is required to parse an LsCommand response")
error = response.find('./error')
if error is not None:
return _parse_error_tree(error)
hash_type = response.get('hash')
dirs = []
files = []
# Get each file listed in this response
for myfile in response.findall('./file'):
fi = FileInfo(fssapi,
device_id,
myfile.get('path'),
int(myfile.get('last_modified')),
int(myfile.get('size')),
myfile.get('hash'),
hash_type)
files.append(fi)
# Get each directory listed for this device
for mydir in response.findall('./dir'):
di = DirectoryInfo(fssapi,
device_id,
mydir.get('path'),
int(mydir.get('last_modified')))
dirs.append(di)
return LsInfo(directories=dirs, files=files) |
<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_response(cls, response, **kwargs):
"""Parse the server response for this get file command This will parse xml of the following form:: <get_file> <data> asdfasdfasdfasdfasf </data> </get_file> or with an error:: <get_file> </get_file> :param response: The XML root of the response for a get file command :type response: :class:`xml.etree.ElementTree.Element` :return: a six.binary_type string of the data of a file or an :class:`~ErrorInfo` if the xml contained an error """ |
if response.tag != cls.command_name:
raise ResponseParseError(
"Received response of type {}, GetCommand can only parse responses of type {}".format(response.tag,
cls.command_name))
error = response.find('./error')
if error is not None:
return _parse_error_tree(error)
text = response.find('./data').text
if text:
return base64.b64decode(six.b(text))
else:
return six.b('') |
<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_response(cls, response, **kwargs):
"""Parse the server response for this put file command This will parse xml of the following form:: <put_file /> or with an error:: <put_file> </put_file> :param response: The XML root of the response for a put file command :type response: :class:`xml.etree.ElementTree.Element` :return: None if everything was ok or an :class:`~ErrorInfo` if the xml contained an error """ |
if response.tag != cls.command_name:
raise ResponseParseError(
"Received response of type {}, PutCommand can only parse responses of type {}".format(response.tag,
cls.command_name))
error = response.find('./error')
if error is not None:
return _parse_error_tree(error)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_command_block(self, target, command_block):
"""Send an arbitrary file system command block The primary use for this method is to send multiple file system commands with a single web service request. This can help to avoid throttling. :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param command_block: The block of commands to execute on the target :type command_block: :class:`~FileSystemServiceCommandBlock` :return: The response will be a dictionary where the keys are device_ids and the values are the parsed responses of each command sent in the order listed in the command response for that device. In practice it seems to be the same order as the commands were sent in, however, Device Cloud documentation does not explicitly state anywhere that is the case so I cannot guarantee it. This does mean that if you send different types of commands the response list will be different types. Please see the commands parse_response functions for what those types will be. (:meth:`LsCommand.parse_response`, :class:`GetCommand.parse_response`, :class:`PutCommand.parse_response`, :class:`DeleteCommand.parse_response`) """ |
root = _parse_command_response(
self._sci_api.send_sci("file_system", target, command_block.get_command_string()))
out_dict = {}
for device in root.findall('./file_system/device'):
device_id = device.get('id')
results = []
for command in device.find('./commands'):
for command_class in FILE_SYSTEM_COMMANDS:
if command_class.command_name == command.tag.lower():
results.append(command_class.parse_response(command, fssapi=self, device_id=device_id))
out_dict[device_id] = results
return out_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 list_files(self, target, path, hash='any'):
"""List all files and directories in the path on the target :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to list files and directories from :param hash: an optional attribute which indicates a hash over the file contents should be retrieved. Values include none, any, md5, and crc32. any is used to indicate the device should choose its best available hash. :return: A dictionary with keys of device ids and values of :class:`~.LsInfo` objects containing the files and directories or an :class:`~.ErrorInfo` object if there was an error response :raises: :class:`~.ResponseParseError` If the SCI response has unrecognized formatting Here is an example usage:: # dc is a DeviceCloud instance fssapi = dc.get_fss_api() target = AllTarget() ls_dir = '/root/home/user/important_files/' ls_data = fssapi.list_files(target, ls_dir) # Loop over all device results for device_id, device_data in ls_data.iteritems():
# Check if it succeeded or was an error if isinstance(device_data, ErrorInfo):
# Do some error handling logger.warn("Error listing file info on device %s. errno: %s message:%s", device_id, device_data.errno, device_data.message) # It's of type LsInfo else: # Look at all the files for finfo in device_data.files: logger.info("Found file %s of size %s on device %s", finfo.path, finfo.size, device_id) # Look at all the directories for dinfo in device_data.directories: logger.info("Found directory %s of last modified %s on device %s", dinfo.path, dinfo.last_modified, device_id) """ |
command_block = FileSystemServiceCommandBlock()
command_block.add_command(LsCommand(path, hash=hash))
root = _parse_command_response(
self._sci_api.send_sci("file_system", target, command_block.get_command_string()))
out_dict = {}
# At this point the XML we have is of the form
# <sci_reply>
# <file_system>
# <device id="device_id">
# <commands>
# <ls hash="hash_type">
# <file path="file_path" last_modified=last_modified_time ... />
# ...
# <dir path="dir_path" last_modified=last_modified_time />
# ...
# </ls>
# </commands>
# </device>
# <device id="device_id">
# <commands>
# <ls hash="hash_type">
# <file path="file_path" last_modified=last_modified_time ... />
# ...
# <dir path="dir_path" last_modified=last_modified_time />
# ...
# </ls>
# </commands>
# </device>
# ...
# </file_system>
# </sci_reply>
# Here we will get each of the XML trees rooted at the device nodes
for device in root.findall('./file_system/device'):
device_id = device.get('id')
error = device.find('./error')
if error is not None:
out_dict[device_id] = _parse_error_tree(error)
else:
linfo = LsCommand.parse_response(device.find('./commands/ls'), device_id=device_id, fssapi=self)
out_dict[device_id] = linfo
return out_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file(self, target, path, offset=None, length=None):
"""Get the contents of a file on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the file to retrieve :param offset: Start retrieving data from this byte position in the file, if None start from the beginning :param length: How many bytes to retrieve, if None retrieve until the end of the file :return: A dictionary with keys of device ids and values of the bytes of the file (or partial file if offset and/or length are specified) or an :class:`~.ErrorInfo` object if there was an error response :raises: :class:`~.ResponseParseError` If the SCI response has unrecognized formatting """ |
command_block = FileSystemServiceCommandBlock()
command_block.add_command(GetCommand(path, offset, length))
root = _parse_command_response(
self._sci_api.send_sci("file_system", target, command_block.get_command_string()))
out_dict = {}
for device in root.findall('./file_system/device'):
device_id = device.get('id')
error = device.find('./error')
if error is not None:
out_dict[device_id] = _parse_error_tree(error)
else:
data = GetCommand.parse_response(device.find('./commands/get_file'))
out_dict[device_id] = data
return out_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 put_file(self, target, path, file_data=None, server_file=None, offset=None, truncate=False):
"""Put data into a file on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the file to write to. If the file already exists it will be overwritten. :param file_data: A `six.binary_type` containing the data to put into the file :param server_file: The path to a file on the devicecloud server containing the data to put into the file on the device :param offset: Start writing bytes to the file at this position, if None start at the beginning :param truncate: Boolean, if True after bytes are done being written end the file their even if previous data exists beyond it. If False, leave any existing data in place. :return: A dictionary with keys being device ids and value being None if successful or an :class:`~.ErrorInfo` if the operation failed on that device :raises: :class:`~.FileSystemServiceException` if either both file_data and server_file are specified or neither are specified :raises: :class:`~.ResponseParseError` If the SCI response has unrecognized formatting """ |
command_block = FileSystemServiceCommandBlock()
command_block.add_command(PutCommand(path, file_data, server_file, offset, truncate))
root = _parse_command_response(self._sci_api.send_sci("file_system", target, command_block.get_command_string()))
out_dict = {}
for device in root.findall('./file_system/device'):
device_id = device.get('id')
error = device.find('./error')
if error is not None:
out_dict[device_id] = _parse_error_tree(error)
else:
out_dict[device_id] = PutCommand.parse_response(device.find('./commands/put_file'))
return out_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 delete_file(self, target, path):
"""Delete a file from a device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the file to delete. :return: A dictionary with keys being device ids and value being None if successful or an :class:`~.ErrorInfo` if the operation failed on that device :raises: :class:`~.ResponseParseError` If the SCI response has unrecognized formatting """ |
command_block = FileSystemServiceCommandBlock()
command_block.add_command(DeleteCommand(path))
root = _parse_command_response(self._sci_api.send_sci("file_system", target, command_block.get_command_string()))
out_dict = {}
for device in root.findall('./file_system/device'):
device_id = device.get('id')
error = device.find('./error')
if error is not None:
out_dict[device_id] = _parse_error_tree(error)
else:
out_dict[device_id] = DeleteCommand.parse_response(device.find('./commands/rm'))
return out_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_modified_items(self, target, path, last_modified_cutoff):
"""Get all files and directories from a path on the device modified since a given time :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to the directory to check for modified files. :param last_modified_cutoff: The time (as Unix epoch time) to get files modified since :type last_modified_cutoff: int :return: A dictionary where the key is a device id and the value is either an :class:`~.ErrorInfo` if there was a problem with the operation or a :class:`~.LsInfo` with the items modified since the specified date """ |
file_list = self.list_files(target, path)
out_dict = {}
for device_id, device_data in six.iteritems(file_list):
if isinstance(device_data, ErrorInfo):
out_dict[device_id] = device_data
else:
files = []
dirs = []
for cur_file in device_data.files:
if cur_file.last_modified > last_modified_cutoff:
files.append(cur_file)
for cur_dir in device_data.directories:
if cur_dir.last_modified > last_modified_cutoff:
dirs.append(cur_dir)
out_dict[device_id] = LsInfo(directories=dirs, files=files)
return out_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 exists(self, target, path, path_sep="/"):
"""Check if path refers to an existing path on the device :param target: The device(s) to be targeted with this request :type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances :param path: The path on the target to check for existence. :param path_sep: The path separator of the device :return: A dictionary where the key is a device id and the value is either an :class:`~.ErrorInfo` if there was a problem with the operation or a boolean with the existence status of the path on that device """ |
if path.endswith(path_sep):
path = path[:-len(path_sep)]
par_dir, filename = path.rsplit(path_sep, 1)
file_list = self.list_files(target, par_dir)
out_dict = {}
for device_id, device_data in six.iteritems(file_list):
if isinstance(device_data, ErrorInfo):
out_dict[device_id] = device_data
else:
out_dict[device_id] = False
for cur_file in device_data.files:
if cur_file.path == path:
out_dict[device_id] = True
for cur_dir in device_data.directories:
if cur_dir.path == path:
out_dict[device_id] = True
return out_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_group_tree_root(self, page_size=1000):
r"""Return the root group for this accounts' group tree This will return the root group for this tree but with all links between nodes (i.e. children starting from root) populated. Examples:: # print the group hierarchy to stdout dc.devicecore.get_group_tree_root().print_subtree() # gather statistics about devices in each group including # the count from its subgroups (recursively) # # This also shows how you can go from a group reference to devices # for that particular group. stats = {} # group -> devices count including children def count_nodes(group):
count_for_this_node = \ len(list(dc.devicecore.get_devices(group_path == group.get_path()))) subnode_count = 0 for child in group.get_children():
subnode_count += count_nodes(child) total = count_for_this_node + subnode_count stats[group] = total return total count_nodes(dc.devicecore.get_group_tree_root()) :param int page_size: The number of results to fetch in a single page. In general, the default will suffice. :returns: The root group for this device cloud accounts group hierarchy. """ |
# first pass, build mapping
group_map = {} # map id -> group
page_size = validate_type(page_size, *six.integer_types)
for group in self.get_groups(page_size=page_size):
group_map[group.get_id()] = group
# second pass, find root and populate list of children for each node
root = None
for group_id, group in group_map.items():
if group.is_root():
root = group
else:
parent = group_map[group.get_parent_id()]
parent.add_child(group)
return root |
<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_groups(self, condition=None, page_size=1000):
"""Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them for group in dc.devicecore.get_groups():
print group # Iterate over all devices which are in a group with a specific # ID. group = dc.devicore.get_groups(group_id == 123)[0] for device in dc.devicecore.get_devices(group_path == group.get_path()):
print device.get_mac() :param condition: A condition to use when filtering the results set. If unspecified, all groups will be returned. :param int page_size: The number of results to fetch in a single page. In general, the default will suffice. :returns: Generator over the groups in this device cloud account. No guarantees about the order of results is provided and child links between nodes will not be populated. """ |
query_kwargs = {}
if condition is not None:
query_kwargs["condition"] = condition.compile()
for group_data in self._conn.iter_json_pages("/ws/Group", page_size=page_size, **query_kwargs):
yield Group.from_json(group_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 provision_devices(self, devices):
"""Provision multiple devices with a single API call This method takes an iterable of dictionaries where the values in the dictionary are expected to match the arguments of a call to :meth:`provision_device`. The contents of each dictionary will be validated. :param list devices: An iterable of dictionaries each containing information about a device to be provision. The form of the dictionary should match the keyword arguments taken by :meth:`provision_device`. :raises DeviceCloudHttpException: If there is an unexpected error reported by Device Cloud. :raises ValueError: If any input fields are known to have a bad form. :return: A list of dictionaries in the form described for :meth:`provision_device` in the order matching the requested device list. Note that it is possible for there to be mixed success and error when provisioning multiple devices. """ |
# Validate all the input for each device provided
sio = six.StringIO()
def write_tag(tag, val):
sio.write("<{tag}>{val}</{tag}>".format(tag=tag, val=val))
def maybe_write_element(tag, val):
if val is not None:
write_tag(tag, val)
return True
return False
sio.write("<list>")
for d in devices:
sio.write("<DeviceCore>")
mac_address = d.get("mac_address")
device_id = d.get("device_id")
imei = d.get("imei")
if mac_address is not None:
write_tag("devMac", mac_address)
elif device_id is not None:
write_tag("devConnectwareId", device_id)
elif imei is not None:
write_tag("devCellularModemId", imei)
else:
raise ValueError("mac_address, device_id, or imei must be provided for device %r" % d)
# Write optional elements if present.
maybe_write_element("grpPath", d.get("group_path"))
maybe_write_element("dpUserMetaData", d.get("metadata"))
maybe_write_element("dpTags", d.get("tags"))
maybe_write_element("dpMapLong", d.get("map_long"))
maybe_write_element("dpMapLat", d.get("map_lat"))
maybe_write_element("dpContact", d.get("contact"))
maybe_write_element("dpDescription", d.get("description"))
sio.write("</DeviceCore>")
sio.write("</list>")
# Send the request, set the Accept XML as a nicety
results = []
response = self._conn.post("/ws/DeviceCore", sio.getvalue(), headers={'Accept': 'application/xml'})
root = ET.fromstring(response.content) # <result> tag is root of <list> response
for child in root:
if child.tag.lower() == "location":
results.append({
"error": False,
"error_msg": None,
"location": child.text
})
else: # we expect "error" but handle generically
results.append({
"error": True,
"location": None,
"error_msg": child.text
})
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_subtree(self, fobj=sys.stdout, level=0):
"""Print this group node and the subtree rooted at it""" |
fobj.write("{}{!r}\n".format(" " * (level * 2), self))
for child in self.get_children():
child.print_subtree(fobj, level + 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 get_device_json(self, use_cached=True):
"""Get the JSON metadata for this device as a python data structure If ``use_cached`` is not True, then a web services request will be made synchronously in order to get the latest device metatdata. This will update the cached data for this device. """ |
if not use_cached:
devicecore_data = self._conn.get_json(
"/ws/DeviceCore/{}".format(self.get_device_id()))
self._device_json = devicecore_data["items"][0] # should only be 1
return self._device_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 get_tags(self, use_cached=True):
"""Get the list of tags for this device""" |
device_json = self.get_device_json(use_cached)
potential_tags = device_json.get("dpTags")
if potential_tags:
return list(filter(None, potential_tags.split(",")))
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_connected(self, use_cached=True):
"""Return True if the device is currrently connect and False if not""" |
device_json = self.get_device_json(use_cached)
return int(device_json.get("dpConnectionStatus")) > 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 get_device_id(self, use_cached=True):
"""Get this device's device id""" |
device_json = self.get_device_json(use_cached)
return device_json["id"].get("devId") |
<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_ip(self, use_cached=True):
"""Get the last known IP of this device""" |
device_json = self.get_device_json(use_cached)
return device_json.get("dpLastKnownIp") |
<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_mac(self, use_cached=True):
"""Get the MAC address of this device""" |
device_json = self.get_device_json(use_cached)
return device_json.get("devMac") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.