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... |
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 v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 rang... |
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 rang... |
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 desaturat... |
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... |
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.... |
<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.... |
# 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 ... |
<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.Col... |
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']:
# ... |
<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:
filety... |
<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()
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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... |
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['... |
<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 ... |
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.h... |
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()
... |
<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... |
<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())
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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():
... |
<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) R... |
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)
... |
<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... |
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 is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parsed_text(args, infilename):
"""Parse and return text content of infiles. Keyword arguments: args -- program arguments (dict) infilenames -- name of us... |
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(htm... |
<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(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 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]
... |
<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 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 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(... |
<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): '
... |
<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 ... |
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}'
... |
<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 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 convert(data, in_format, out_format, name=None, pretty=False):
"""Converts between two inputted chemical formats. Args: data: A string representing the chemi... |
# 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:... |
<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 load... |
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('_ato... |
<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 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.partia... |
<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... |
<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 forma... |
# 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_converte... |
<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 "
"transm... |
<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)) ... |
<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
... |
<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, s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 z... |
<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 ... |
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 obj... |
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 t... |
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:... |
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 f... |
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))
... |
<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>... |
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))... |
<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 w... |
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))... |
<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 syst... |
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.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 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... |
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 i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_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 req... |
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('./... |
<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(... |
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 r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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:`deviceclo... |
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'):
... |
<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 t... |
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 = []
... |
<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 req... |
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):... |
<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... |
# 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 ea... |
<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... |
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 ... |
# 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)
... |
<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 service... |
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.