text
stringlengths
81
112k
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('...
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: ...
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']:...
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) def print_text(args, infilenames, outfilename=None): """Print text content of inf...
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) def write_pdf_files(args, infilenames, outfilename): """Write pdf file(s) to disk using pdfk...
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 write_csv_files(args, infilenames, outfilename): """Write csv file(s) to disk. Keyword argument...
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) def write_text_files(args, infilenames, outfilename): """Write text file(s) to disk. Keyword argum...
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 ex...
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 ...
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 (lxml.html.HtmlElement) (default: None) filename -- the PART....
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: None) part_num -- PART(#).html file number (int) (default: None) def...
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 in...
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_i...
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. 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 Babe...
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` def json_to_...
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 def pybel_to_json(molecule, name=None): """Converts a pybel molecule to json. ...
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: ...
Draws an interactive 3D visualization of the inputted chemical. Args: data: A string or file representing a chemical. format: The format of the `data` variable (default is 'auto'). size: Starting dimensions of visualization, in pixels. drawing_type: Specifies the molecular represent...
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.ht...
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. def to_json(data, compress=False): """Converts the output of `generate(...)` to formatted json. Floats are rounded to three decima...
Starts up the imolecule server, complete with argparse handling. 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 " ...
Evaluates the function pointed to by json-rpc. def on_message(self, message): """Evaluates the function pointed to by json-rpc.""" json_rpc = json.loads(message) logging.log(logging.DEBUG, json_rpc) if self.pool is None: self.pool = multiprocessing.Pool(processes=args.worke...
implementation based on: http://floating-point-gui.de/errors/comparison/ def nearly_eq(valA, valB, maxf=None, minf=None, epsilon=None): ''' implementation based on: http://floating-point-gui.de/errors/comparison/ ''' if valA == valB: return True if maxf is None: maxf = f...
:other: Point or point equivalent :ignorescalars: optional boolean :return: Point Class private method for converting 'other' into a Point subclasss. If 'other' already is a Point subclass, nothing is done. If ignoreScalars is True and other is a float or int type, a Typ...
:scale: optional integer scaling factor :return: list of three Point subclass Returns three points whose coordinates are the head of a unit vector from the origin ( conventionally i, j and k). def units(cls, scale=1): ''' :scale: optional integer scaling factor :return:...
:mu: mean :sigma: standard deviation :return: Point subclass Returns a point whose coordinates are picked from a Gaussian distribution with mean 'mu' and standard deviation 'sigma'. See random.gauss for further explanation of those parameters. def gaussian(cls, mu=0, sigma...
:origin: optional Point or point equivalent :radius: optional float, radius around origin :return: Point subclass Returns a point with random x, y and z coordinates bounded by the sphere defined by (origin,radius). If a sphere is not supplied, a unit sphere at the origin is ...
:other: Point or point equivalent :func: binary function to apply :inplace: optional boolean :return: Point Implementation private method. All of the binary operations funnel thru this method to reduce cut-and-paste code and enforce consistent behavior of ...
:func: unary function to apply to each coordinate :inplace: optional boolean :return: Point Implementation private method. All of the unary operations funnel thru this method to reduce cut-and-paste code and enforce consistent behavior of unary ops. Applies 'fu...
:other: Point or point equivalent :return: float Vector cross product of points U (self) and V (other), computed: U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k) s1 = u2v3 - u3v2 s2 = u3v1 - u1v3 s3 = u1v2 - u2v1 U x V = s1 + s2 + s3 Returns a floa...
:a: Point or point equivalent :b: Point or point equivalent :axis: optional string :return: float Checks the coordinates specified in 'axes' of 'self' to determine if they are bounded by 'a' and 'b'. The range is inclusive of end-points. Returns boolean. def is...
:b: Point or point equivalent :c: Point or point equivalent :axis: optional string or integer in set('x',0,'y',1,'z',2) :return: float CCW - Counter Clockwise Returns an integer signifying the direction of rotation around 'axis' described by the angle [b, self, c]. ...
:b: Point or point equivalent :c: Point or point equivalent :axis: optional string or integer in set('x',0,'y',1,'z',2) :return: boolean True if the angle determined by a,self,b around 'axis' describes a counter-clockwise rotation, otherwise False. Raises CollinearPoint...
:b: Point or point equivalent :c: Point or point equivalent :return: boolean True if 'self' is collinear with 'b' and 'c', otherwise False. def isCollinear(self, b, c): ''' :b: Point or point equivalent :c: Point or point equivalent :return: boolean Tru...
:theta: float radians to rotate self around origin :origin: optional Point, defaults to 0,0,0 Returns a Point rotated by :theta: around :origin:. def rotate2d(self, theta, origin=None, axis='z', radians=False): ''' :theta: float radians to rotate self around origin :origin: opt...
:origin: optional Point :alpha: optional float describing length of the side opposite A :beta: optional float describing length of the side opposite B :gamma: optional float describing length of the side opposite C :return: Triangle initialized with points comprising the triangle ...
Heron's forumla for computing the area of a triangle, float. Performance note: contains a square root. def heronsArea(self): ''' Heron's forumla for computing the area of a triangle, float. Performance note: contains a square root. ''' s = self.semiperimeter ...
Distance from the circumcenter to all the verticies in the Triangle, float. 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)
A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. def altitudes(self): ''' A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An alti...
True iff two side lengths are equal, boolean. 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)
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. 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 leng...
Center point of the ellipse, equidistant from foci, Point class.\n Defaults to the origin. def center(self): ''' Center point of the ellipse, equidistant from foci, Point class.\n Defaults to the origin. ''' try: return self._center except AttributeEr...
Radius of the ellipse, Point class. 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
Returns True if the major axis is parallel to the X axis, boolean. 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
Returns True if the minor axis is parallel to the X axis, boolean. 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
Returns True if the major axis is parallel to the Y axis, boolean. 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
Returns True if the minor axis is parallel to the Y axis, boolean. 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
Positive antipodal point on the major axis, Point class. 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 ret...
Negative antipodal point on the major axis, Point class. 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 ...
Positive antipodal point on the minor axis, Point class. 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 ret...
Negative antipodal point on the minor axis, Point class. 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 ...
A dictionary of four points where the axes intersect the ellipse, dict. 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}
First focus of the ellipse, Point class. 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
:param: triangle - Triangle class :return: Circle class Returns the circle where every vertex in the input triangle is on the radius of that circle. def circumcircleForTriangle(cls, triangle): ''' :param: triangle - Triangle class :return: Circle class Returns ...
:param: other - Circle class Returns True iff: self.center.distance(other.center) <= self.radius+other.radius def doesIntersect(self, other): ''' :param: other - Circle class Returns True iff: self.center.distance(other.center) <= self.radius+other.radius '...
A list containing Points A and B. 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
:return: Line Returns a Line normal (perpendicular) to this Line. def normal(self): ''' :return: Line Returns a Line normal (perpendicular) to this Line. ''' d = self.B - self.A return Line([-d.y, d.x], [d.y, -d.x])
:point: Point subclass :return: float If :point: is collinear, determine the 't' coefficient of the parametric equation: xyz = A<xyz> + t ( B<xyz> - A<xyz> ) if t < 0, point is less than A and B on the line if t >= 0 and <= 1, point is between A and B if t > 1 ...
:returns: None Swaps the positions of A and B. def flip(self): ''' :returns: None Swaps the positions of A and B. ''' tmp = self.A.xyz self.A = self.B self.B = tmp
:param: other - Line subclass :return: boolean Returns True iff: ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0 and ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0 def doesIntersect(self, other): ''' :param: other - Line sub...
:param: other - Line subclass :return: Point subclass Returns a Point object with the coordinates of the intersection between the current line and the other line. Will raise Parallel() if the two lines are parallel. Will raise Collinear() if the two lines are collinear. def in...
:param: point - Point subclass :return: float Distance from the line to the given point. def distanceFromPoint(self, point): ''' :param: point - Point subclass :return: float Distance from the line to the given point. ''' # XXX planar distance, doesn't ...
:param: other - Line subclass :return: float Returns the angle measured between two lines in radians with a range of [0, 2 * math.pi]. def radiansBetween(self, other): ''' :param: other - Line subclass :return: float Returns the angle measured between two lines...
:name: string - property name :default: float - property default value :readonly: boolean - if True, setter method is NOT generated Returns a property object that can be used to initialize a class instance variable as a property. def FloatProperty(name, default=0.0, readonly=False, docs=None): '''...
:param: radius - float :param: widthLimits - iterable of floats with length >= 2 :param: heightLimits - iterable of floats with length >= 2 :param: origin - optional Point subclass :return: Rectangle def randomSizeAndLocation(cls, radius, widthLimits, ...
:param: widthLimits - iterable of integers with length >= 2 :param: heightLimits - iterable of integers with length >= 2 :param: origin - optional Point subclass :return: Rectangle def randomSize(cls, widthLimits, heightLimits, origin=None): ''' :param: widthLimits - ite...
:param: radius - float :param: width - float :param: height - float :param: origin - optional Point subclass :return: Rectangle def randomLocation(cls, radius, width, height, origin=None): ''' :param: radius - float :param: width - float :param: height ...
Point describing the origin of the rectangle. Defaults to (0,0,0). def origin(self): ''' Point describing the origin of the rectangle. Defaults to (0,0,0). ''' try: return self._origin except AttributeError: pass self._origin = Point() ret...
Point whose coordinates are (maxX,minY,origin.z), Point. def B(self): ''' Point whose coordinates are (maxX,minY,origin.z), Point. ''' return Point(self.maxX, self.minY, self.origin.z)
Point whose coordinates are (maxX,maxY,origin.z), Point. def C(self): ''' Point whose coordinates are (maxX,maxY,origin.z), Point. ''' return Point(self.maxX, self.maxY, self.origin.z)
Point whose coordinates are (minX,maxY,origin.Z), Point. def D(self): ''' Point whose coordinates are (minX,maxY,origin.Z), Point. ''' return Point(self.minX, self.maxY, self.origin.z)
Point whose coordinates are (midX,midY,origin.z), Point. def center(self): ''' Point whose coordinates are (midX,midY,origin.z), Point. ''' return Point(self.midX, self.midY, self.origin.z)
:param: dx - optional float :param: dy - optional float Scales the rectangle's width and height by dx and dy. def scale(self, dx=1.0, dy=1.0): ''' :param: dx - optional float :param: dy - optional float Scales the rectangle's width and height by dx and dy. '''...
:param: point - Point subclass :param: Zorder - optional Boolean Is true if the point is contain in the rectangle or along the rectangle's edges. If Zorder is True, the method will check point.z for equality with the rectangle origin's Z coordinate. def containsPoint(self, po...
:origin: - optional Point subclass :radius: - optional float :return: Triangle Creates a triangle with random coordinates in the circle described by (origin,radius). If origin is unspecified, (0,0) is assumed. If the radius is unspecified, 1.0 is assumed. def random(cls, origi...
:origin: optional Point :side: optional float describing triangle side length :return: Triangle initialized with points comprising a equilateral triangle. XXX equilateral triangle definition def equilateral(cls, origin=None, side=1): ''' :origin: optional Point...
:origin: optional Point :base: optional float describing triangle base length :return: Triangle initialized with points comprising a isosceles triangle. XXX isoceles triangle definition def isosceles(cls, origin=None, base=1, alpha=90): ''' :origin: optional Po...
Third vertex of triangle, Point subclass. def C(self): ''' Third vertex of triangle, Point subclass. ''' try: return self._C except AttributeError: pass self._C = Point(0, 1) return self._C
A list of the triangle's vertices, list. 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
Vertices B and A, list. def BA(self): ''' Vertices B and A, list. ''' try: return self._BA except AttributeError: pass self._BA = [self.B, self.A] return self._BA
Vertices A and C, list. def AC(self): ''' Vertices A and C, list. ''' try: return self._AC except AttributeError: pass self._AC = [self.A, self.C] return self._AC
Vertices C and A, list. def CA(self): ''' Vertices C and A, list. ''' try: return self._CA except AttributeError: pass self._CA = [self.C, self.A] return self._CA
Vertices B and C, list. def BC(self): ''' Vertices B and C, list. ''' try: return self._BC except AttributeError: pass self._BC = [self.B, self.C] return self._BC
Vertices C and B, list. def CB(self): ''' Vertices C and B, list. ''' try: return self._CB except AttributeError: pass self._CB = [self.C, self.B] return self._CB
A list of the Triangle's line segments [AB, BC, AC], list. def segments(self): ''' A list of the Triangle's line segments [AB, BC, AC], list. ''' return [Segment(self.AB), Segment(self.BC), Segment(self.AC)]
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 t...
A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. def altitudes(self): ''' A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An alti...
True if all sides of the triangle are the same length. All equilateral triangles are also isosceles. All equilateral triangles are also acute. def isEquilateral(self): ''' True if all sides of the triangle are the same length. All equilateral triangles are also isosceles. ...
:side: - optional string :inplace: - optional boolean :return: Triangle with flipped side. The optional side paramater should have one of three values: AB, BC, or AC. Changes the order of the triangle's points, swapping the specified points. Doing so will change the res...
:param: other - Triangle or Line subclass :return: boolean Returns True iff: Any segment in self intersects any segment in other. def doesIntersect(self, other): ''' :param: other - Triangle or Line subclass :return: boolean Returns True iff: Any ...
Sum of the length of all sides, float. def perimeter(self): ''' Sum of the length of all sides, float. ''' return sum([a.distance(b) for a, b in self.pairs()])
Dense sift descriptors from an image. Returns: frames: num_frames x (2 or 3) matrix of x, y, (norm) descrs: num_frames x 128 matrix of descriptors def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1, window_size=None, float_descriptors=False, verbose=...
Converts an RGB image to grayscale using matlab's algorithm. 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,...
Converts an RGB image to HSV using scikit-image's algorithm. 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...
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...
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. def _parse_error_tree(error): """Parse an error ElementTree Node to create an ErrorInfo object :param error: The ElementTree err...