INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Orders attributes names alphabetically except for the class attribute which is kept last.
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))
Convert the color from RGB coordinates to HSL.
def rgb_to_hsl(r, g=None, b=None): """Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360],...
Convert the color from HSL coordinates to RGB.
def hsl_to_rgb(h, s=None, l=None): """Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r...
Convert the color from RGB coordinates to HSV.
def rgb_to_hsv(r, g=None, b=None): """Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360],...
Convert the color from RGB coordinates to HSV.
def hsv_to_rgb(h, s=None, v=None): """Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], ...
Convert the color from RGB to YIQ.
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1],...
Convert the color from YIQ coordinates to RGB.
def yiq_to_rgb(y, i=None, q=None): """Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0......
Convert the color from RGB coordinates to YUV.
def rgb_to_yuv(r, g=None, b=None): """Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], ...
Convert the color from YUV coordinates to RGB.
def yuv_to_rgb(y, u=None, v=None): """Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[...
Convert the color from sRGB to CIE XYZ.
def rgb_to_xyz(r, g=None, b=None): """Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0......
Convert the color from CIE XYZ coordinates to sRGB.
def xyz_to_rgb(x, y=None, z=None): """Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [...
Convert the color from CIE XYZ to CIE L * a * b *.
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF): """Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Re...
Convert the color from CIE L * a * b * to CIE 1931 XYZ.
def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF): """Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: ...
Convert the color from CMYK coordinates to CMY.
def cmyk_to_cmy(c, m=None, y=None, k=None): """Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: ...
Convert the color from CMY coordinates to CMYK.
def cmy_to_cmyk(c, m=None, y=None): """Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c...
Convert the color from RGB coordinates to CMY.
def rgb_to_cmy(r, g=None, b=None): """Convert the color from RGB coordinates to CMY. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], ...
Convert the color from CMY coordinates to RGB.
def cmy_to_rgb(c, m=None, y=None): """Convert the color from CMY coordinates to RGB. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0......
Convert the color in the standard [ 0... 1 ] range to ints in the [ 0.. 255 ] range.
def rgb_to_ints(r, g=None, b=None): """Convert the color in the standard [0...1] range to ints in the [0..255] range. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tu...
Convert ints in the [ 0... 255 ] range to the standard [ 0... 1 ] range.
def ints_to_rgb(r, g=None, b=None): """Convert ints in the [0...255] range to the standard [0...1] range. Parameters: :r: The Red component value [0...255] :g: The Green component value [0...255] :b: The Blue component value [0...255] Returns: The color as an (r, g, b) tuple in...
Convert the color from ( r g b ) to #RRGGBB.
def rgb_to_html(r, g=None, b=None): """Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> rg...
Convert the HTML color to ( r g b ).
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither...
Convert the color from RGB to a PIL - compatible integer.
def rgb_to_pil(r, g=None, b=None): """Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x'...
Convert the color from a PIL - compatible integer to RGB.
def pil_to_rgb(pil): """Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff)...
Convert a color component to its web safe equivalent.
def _websafe_component(c, alt=False): """Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value. """ # This suck...
Convert the color from RGB to web safe RGB
def rgb_to_websafe(r, g=None, b=None, alt=False): """Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of th...
Convert the color from RGB to its greyscale equivalent
def rgb_to_greyscale(r, g=None, b=None): """Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: ...
Maps a hue on the RGB color wheel to Itten s RYB wheel.
def rgb_to_ryb(hue): """Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0 """ d = hue % 15 i = int(hue / 15) x0 = _RybWhee...
Maps a hue on Itten s RYB color wheel to the standard RGB wheel.
def ryb_to_rgb(hue): """Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> ryb_to_rgb(15) 8.0 """ d = hue % 15 i = int(hue / 15...
Create a new instance based on the specifed RGB values.
def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color t...
Create a new instance based on the specifed HSL values.
def from_hsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: T...
Create a new instance based on the specifed HSV values.
def from_hsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color t...
Create a new instance based on the specifed YIQ values.
def from_yiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparen...
Create a new instance based on the specifed YUV values.
def from_yuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: Th...
Create a new instance based on the specifed CIE - XYZ values.
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The col...
Create a new instance based on the specifed CIE - LAB values.
def from_lab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1]...
Create a new instance based on the specifed CMY values.
def from_cmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The co...
Create a new instance based on the specifed CMYK values.
def from_cmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The B...
Create a new instance based on the specifed HTML color definition.
def from_html(html, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: ...
Create a new instance based on the specifed PIL color.
def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, def...
Create a new instance based on this one with a new white reference.
def with_white_ref(self, wref, labAsRef=False): """Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwis...
Create a new instance based on this one but less saturated.
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 the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desatu...
Return the two websafe colors nearest to this one.
def websafe_dither(self): """Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.from_rgb(1.0, 0.45, 0.0) >>> c1, c2 = c.websafe_dither() >>> c1 Color(1.0, 0.4, 0.0, ...
Create a new instance which is the complementary color of this one.
def complementary_color(self, mode='ryb'): """Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5).complementary_co...
Return two colors analogous to this one.
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 grapefr...
Alpha - blend this color on the other one.
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. >>> c1 = Color.from_rgb(1, 0.5, ...
blend this color with the other one.
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. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) ...
Parse command - line arguments.
def get_parser(): """Parse command-line arguments.""" parser = ArgumentParser(description='a command-line web scraping tool') parser.add_argument('query', metavar='QUERY', type=str, nargs='*', help='URLs/files to scrape') parser.add_argument('-a', '--attributes', type=str, nargs=...
Write scraped or local file ( s ) in desired format.
def write_files(args, infilenames, outfilename): """Write scraped or local file(s) in desired format. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output file (str) Remove PART(#).html files afte...
Write to a single output file and/ or subdirectory.
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html file...
Write to multiple output files and/ or subdirectories.
def write_multiple_files(args, base_dir, crawler): """Write to multiple output files and/or subdirectories.""" for i, query in enumerate(args['query']): if query in args['files']: # Write files if args['out'] and i < len(args['out']): outfilename = args['out'][i] ...
Split query input into local files and URLs.
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('/'))
Detect whether to save to a single or multiple files.
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: ...
Scrape webpage content.
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_i...
Prompt user for filetype if none specified.
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)...
Prompt user to save images when crawling ( for pdf and HTML formats ).
def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ...
Handle command - line interaction.
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)) ret...
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.
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.schem...
Updates the classifier with new data.
def train(self, training_data, testing_data=None, verbose=False): """ Updates the classifier with new data. """ model_fn = None training_fn = None clean_training = False testing_fn = None clean_testing = False try: # Valida...
Iterates over the predicted values and probability ( if supported ). Each iteration yields a tuple of the form ( prediction probability ). If the file is a test file ( i. e. contains no query variables ) then the tuple will be of the form ( prediction actual ). See http:// weka. wikispaces. com/ Making + predictions fo...
def predict(self, query_data, verbose=False, distribution=False, cleanup=True): """ Iterates over the predicted values and probability (if supported). Each iteration yields a tuple of the form (prediction, probability). If the file is a test file (i.e. contains no query variable...
Returns a ratio of classifiers that were able to be trained successfully.
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)
Get new links from a URL and filter them.
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...
Check if page has been crawled by hashing its text content.
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)) ...
Find new links given a seed URL and follow them breadth - first.
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 s...
Get available proxies to use with requests library.
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(v...
Get webpage response as an lxml. html. HtmlElement object.
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) ...
Enable requests library cache.
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_cac...
Return MD5 hash of a string.
def hash_text(text): """Return MD5 hash of a string.""" md5 = hashlib.md5() md5.update(text) return md5.hexdigest()
Add a page to the page cache.
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)
Filter text using regular expressions.
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: ...
Remove unnecessary whitespace while keeping logical structure.
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. """ ...
Filter text using XPath regex keywords and tag attributes.
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 t...
Parse and return text content of infiles.
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...
Filter HTML using XPath.
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
Add base netloc and path to internal URLs and remove www fragments.
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 = '...
Add. com suffix to URL if none found.
def add_url_suffix(url): """Add .com suffix to URL if none found.""" url = url.rstrip('/') if not has_suffix(url): return '{0}.com'.format(url) return url
Construct the output filename from domain and end of path.
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...
Use first possible entry in query as filename.
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(...
Modify filename to have a unique numerical identifier.
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...
If filename exists overwrite or modify it to be unique.
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: t...
Print text content of infiles to stdout.
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...
Write pdf file ( s ) to disk using pdfkit.
def write_pdf_files(args, infilenames, outfilename): """Write pdf file(s) to disk using pdfkit. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output pdf file (str) """ if not outfilename.endswi...
Write csv file ( s ) to disk.
def write_csv_files(args, infilenames, outfilename): """Write csv file(s) to disk. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output text file (str) """ def csv_convert(line): """Str...
Write text file ( s ) to disk.
def write_text_files(args, infilenames, outfilename): """Write text file(s) to disk. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output text file (str) """ if not outfilename.endswith('.txt')...
Write a single file to disk.
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...
Get the number of PART. html files currently saved to disk.
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
Write image file ( s ) associated with HTML to disk substituting filenames.
def write_part_images(url, raw_html, html, filename): """Write image file(s) associated with HTML to disk, substituting filenames. Keywords arguments: url -- the URL from which the HTML has been extracted from (str) raw_html -- unparsed HTML file content (list) html -- parsed HTML file content (lxm...
Write PART. html file ( s ) to disk images in PART_files directory.
def write_part_file(args, url, raw_html, html=None, part_num=None): """Write PART.html file(s) to disk, images in PART_files directory. Keyword arguments: args -- program arguments (dict) raw_html -- unparsed HTML file content (list) html -- parsed HTML file content (lxml.html.HtmlElement) (default...
Get numbered PART. html filenames.
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)]
Read a file into memory.
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()
Remove PART ( # ) _files directory containing images from disk.
def remove_part_images(filename): """Remove PART(#)_files directory containing images from disk.""" dirname = '{0}_files'.format(os.path.splitext(filename)[0]) if os.path.exists(dirname): shutil.rmtree(dirname)
Remove PART ( # ). html files and image directories from disk.
def remove_part_files(num_parts=None): """Remove PART(#).html files and image directories from disk.""" filenames = get_part_filenames(num_parts) for filename in filenames: remove_part_images(filename) remove_file(filename)
Check user input for yes no or an exit signal.
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 ...
Change directory and/ or create it if necessary.
def mkdir_and_cd(dirname): """Change directory and/or create it if necessary.""" if not os.path.exists(dirname): os.makedirs(dirname) os.chdir(dirname) else: os.chdir(dirname)
Converts between two inputted chemical formats.
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 `dat...
Converts python data structure to pybel. Molecule.
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: ...
Converts a pybel molecule to json.
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...
Fired when an unserializable object is hit.
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} wit...
Draws an interactive 3D visualization of the inputted chemical.
def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick', camera_type='perspective', shader='lambert', display_html=True, element_properties=None, show_save=False): """Draws an interactive 3D visualization of the inputted chemical. Args: data: A string or file repr...
Converts input chemical formats to json and optimizes structure.
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://openba...
Converts the output of generate (... ) to formatted json.
def to_json(data, compress=False): """Converts the output of `generate(...)` to formatted json. Floats are rounded to three decimals and positional vectors are printed on one line with some whitespace buffer. """ return json.compress(data) if compress else json.dumps(data)