text
stringlengths
81
112k
Calculates simple interest of specified entries over time. Does not accumulate interest to interest. :param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending) :param rate_pct: Interest rate %, e.g. 8.00 for 8% :param interest_date: Interest end date. Default is current ...
Creates a list-table directive for a set of defined environment variables Parameters: name (str): The name of the config section command (object): The sdss_access path instance templates (dict): A dictionary of the path templates Yields: ...
Generate the relevant Sphinx nodes. Generates a section for the Tree datamodel. Formats a tree section as a list-table directive. Parameters: name (str): The name of the config to be documented, e.g. 'sdsswork' command (object): The load...
Compute the delta for b - a. Even/odd and odd/even are handled specially, as described above. def _Delta(a, b): """Compute the delta for b - a. Even/odd and odd/even are handled specially, as described above.""" if a+1 == b: if a%2 == 0: return 'EvenOdd' else: return 'OddEven' if ...
Return a + delta, handling EvenOdd and OddEven specially. def _AddDelta(a, delta): """Return a + delta, handling EvenOdd and OddEven specially.""" if type(delta) == int: return a+delta if delta == 'EvenOdd': if a%2 == 0: return a+1 else: return a-1 if delta == 'OddEven': if a%2 == 1...
Turn a list like [(65,97), (66, 98), ..., (90,122)] into [(65, 90, +32)]. def _MakeRanges(pairs): """Turn a list like [(65,97), (66, 98), ..., (90,122)] into [(65, 90, +32)].""" ranges = [] last = -100 def evenodd(last, a, b, r): if a != last+1 or b != _AddDelta(a, r[2]): return False ...
Pads lines so that all rows in single column match. Columns separated by '|' in every line. :param lines: list of lines :param column_separator: column separator. default is '|' :return: list of lines def align_lines(lines: list, column_separator: str='|') -> list: """ Pads lines so that all rows i...
Marks invoices with as un-sent. :param modeladmin: :param request: :param queryset: :return: def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet): """ Marks invoices with as un-sent. :param modeladmin: :param request: :param queryset: :return: """ us...
This needs to be called from a derived class clean(). :param source_invoice: :param settled_invoice: :param account: :return: None def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw): """ This needs to be cal...
Short date format. :param obj: date or datetime or None :return: str def _format_date(self, obj) -> str: """ Short date format. :param obj: date or datetime or None :return: str """ if obj is None: return '' if isinstance(obj, datetime...
Returns aggregate sum of queryset 'amount' field. :param qs: QuerySet :param key: Field to sum (default: 'amount') :param default: Default value if no results :return: Sum of 'amount' field values (coalesced 0 if None) def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal: ...
Build a blueprint that contains the endpoints for callback URLs of the current subscriber. Only call this once per instance. Arguments: - url_prefix; this allows you to prefix the callback URLs in your app. def build_blueprint(self, url_prefix=''): """Build a blueprint that contains the endpoi...
Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful. def unsubscribe(self, callback_id): """Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful. """ request = self....
Automatically renew subscriptions that are close to expiring, or have already expired. margin_in_seconds determines if a subscription is in fact close to expiring. By default, said margin is set to be a single day (24 hours). This is a long-running method for any non-trivial usage of th...
Discover the hub url and topic url of a given url. Firstly, by inspecting the page's headers, secondarily by inspecting the content for link tags. timeout determines how long to wait for the url to load. It defaults to 3. def discover(url, timeout=None): """Discover the hub url and topic url of a given ur...
Context to ensure correct file permissions for certs and directories Ensures: - A containing directory with appropriate permissions - Correct file permissions based on what the file is (0o600 for keys and 0o644 for certs) def open_tls_file(file_path, mode, private=True): """Context to ...
Load from a file and return an x509 object def load(self): """Load from a file and return an x509 object""" private = self.is_private() with open_tls_file(self.file_path, 'r', private=private) as fh: if private: self.x509 = crypto.load_privatekey(self.encoding, fh.r...
Persist this x509 object to disk def save(self, x509): """Persist this x509 object to disk""" self.x509 = x509 with open_tls_file(self.file_path, 'w', private=self.is_private()) as fh: fh.write(str(self))
Initiates TLSFIle objects with the paths given to this bundle def _setup_tls_files(self, files): """Initiates TLSFIle objects with the paths given to this bundle""" for file_type in TLSFileType: if file_type.value in files: file_path = files[file_type.value] ...
Saves the x509 objects to the paths known by this bundle def save_x509s(self, x509s): """Saves the x509 objects to the paths known by this bundle""" for file_type in TLSFileType: if file_type.value in x509s: x509 = x509s[file_type.value] if file_type is not ...
Create a CertStore record from this TLSFileBundle def to_record(self): """Create a CertStore record from this TLSFileBundle""" tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]] # If a cert isn't defined in this bundle, remove it tf_list = fil...
Build a bundle from a CertStore record def from_record(self, record): """Build a bundle from a CertStore record""" self.record = record self._setup_tls_files(self.record['files']) return self
Write the store dict to a file specified by store_file_path def save(self): """Write the store dict to a file specified by store_file_path""" with open(self.store_file_path, 'w') as fh: fh.write(json.dumps(self.store, indent=4))
Read the store dict from file def load(self): """Read the store dict from file""" with open(self.store_file_path, 'r') as fh: self.store = json.loads(fh.read())
Return the record associated with this common name In most cases, all that's really needed to use an existing cert are the file paths to the files that make up that cert. This method returns just that and doesn't bother loading the associated files. def get_record(self, common_name): "...
Return a bundle of TLS files associated with a common name def get_files(self, common_name): """Return a bundle of TLS files associated with a common name""" record = self.get_record(common_name) return TLSFileBundle(common_name).from_record(record)
Manually create a record of certs Generally, Certipy can be left to manage certificate locations and storage, but it is occasionally useful to keep track of a set of certs that were created externally (for example, let's encrypt) def add_record(self, common_name, serial=0, parent_ca='', ...
Add a set files comprising a certificate to Certipy Used with all the defaults, Certipy will manage creation of file paths to be used to store these files to disk and automatically calls save on all TLSFiles that it creates (and where it makes sense to). def add_files(self, common_name, x509s,...
Removes signee_name to the signee list for ca_name def remove_sign_link(self, ca_name, signee_name): """Removes signee_name to the signee list for ca_name""" ca_record = self.get_record(ca_name) signee_record = self.get_record(signee_name) signees = ca_record['signees'] or {} s...
Update fields in an existing record def update_record(self, common_name, **fields): """Update fields in an existing record""" record = self.get_record(common_name) if fields is not None: for field, value in fields: record[field] = value self.save() r...
Delete the record associated with this common name def remove_record(self, common_name): """Delete the record associated with this common name""" bundle = self.get_files(common_name) num_signees = len(Counter(bundle.record['signees'])) if bundle.is_ca() and num_signees > 0: ...
Delete files and record associated with this common name def remove_files(self, common_name, delete_dir=False): """Delete files and record associated with this common name""" record = self.remove_record(common_name) if delete_dir: delete_dirs = [] if 'files' in record: ...
Create a public/private key pair. Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA bits - Number of bits to use in the key Returns: The public/private key pair in a PKey object def create_key_pair(self, cert_type, bits): """ Create a public/private ...
Generate a certificate given a certificate request. Arguments: req - Certificate request to use issuer_cert - The certificate of the issuer issuer_key - The private key of the issuer not_before - Timestamp (relative to now) when the ...
Create a CA bundle to trust only certs defined in names def create_ca_bundle_for_names(self, bundle_name, names): """Create a CA bundle to trust only certs defined in names """ records = [rec for name, rec in self.store.store.items() if name in names] return self.cre...
Create a bundle of public certs for trust distribution This will create a bundle of both CAs and/or regular certificates. Arguments: names - The names of certs to include in the bundle bundle_name - The name of the bundle file to output Returns: Path to the bundle fil...
Create a set of trust bundles from a relationship graph. Components in this sense are defined by unique CAs. This method assists in setting up complicated trust between various components that need to do TLS auth. Arguments: graph - dict component:list(components) Returns: dic...
Create a certificate authority Arguments: name - The name of the CA cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP...
Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name - The name of the CA to sign this cert cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An arra...
7. Content Distribution def send_change_notification(hub, topic_url, updated_content=None): """7. Content Distribution""" if updated_content: body = base64.b64decode(updated_content['content']) else: body, updated_content = get_new_content(hub.config, topic_url) b64_body = updated_cont...
5.2 Subscription Validation def subscribe(hub, callback_url, topic_url, lease_seconds, secret, endpoint_hook_data): """5.2 Subscription Validation""" for validate in hub.validators: error = validate(callback_url, topic_url, lease_seconds, secret, endpoint_hook_da...
5.3 Hub Verifies Intent of the Subscriber def intent_verified(hub, callback_url, mode, topic_url, lease_seconds): """ 5.3 Hub Verifies Intent of the Subscriber""" challenge = uuid4() params = { 'hub.mode': mode, 'hub.topic': topic_url, 'hub.challenge': challenge, 'hub.lease...
Registers the celery tasks on the hub object. def init_celery(self, celery): """Registers the celery tasks on the hub object.""" count = next(self.counter) def task_with_hub(f, **opts): @functools.wraps(f) def wrapper(*args, **kwargs): return f(self, *a...
Calling this with your flask app as argument is required for the publisher decorator to work. def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'w...
This decorator makes it easier to implement a websub publisher. You use it on an endpoint, and Link headers will automatically be added. To also include these links in your template html/atom/rss (and you should!) you can use the following to get the raw links: - {{ websub_self_url }} - {{ websub_h...
Get the count of records matching the query. def count_results(cube, q): """ Get the count of records matching the query. """ q = select(columns=[func.count(True)], from_obj=q.alias()) return cube.engine.execute(q).scalar()
Generate the resulting records for this query, applying pagination. Values will be returned by their reference. def generate_results(cube, q): """ Generate the resulting records for this query, applying pagination. Values will be returned by their reference. """ if q._limit is not None and q._limit < 1...
Sort on a set of field specifications of the type (ref, direction) in order of the submitted list. def apply(self, q, bindings, ordering, distinct=None): """ Sort on a set of field specifications of the type (ref, direction) in order of the submitted list. """ info = [] for (ref...
Returns a deep copy with all of the numpy arrays copied If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied def copy(self, only=None): ''' Returns a deep copy with all of the numpy arrays copied If only is a list of strings, i.e. ['f', 'v'], then onl...
Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. """ nargs = len(args) if nargs == 1: ...
Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to connect on @param commitOnEnd: Default False, When query is comple...
Create a new PySQLQuery Class @param PySQLConnectionObj: Connection Object representing your connection string @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd suppo...
Encrypt passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the password that needs to be encrypted. The given password will then be encrypted via the P...
Define a set of fields to return for a non-aggregated query. def apply(self, q, bindings, fields, distinct=False): """ Define a set of fields to return for a non-aggregated query. """ info = [] group_by = None for field in self.parse(fields): for concept in self.cube.model...
drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec def drag(self, NewPt): # //Mouse drag, calculate rotation (Point2fT Quat4fT) """ drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec """ X = 0 Y = 1 Z = 2 W = 3 self.m_EnVec = self._mapToS...
Computes the volumes of the "cells" in the mesh. def create_cell_volumes(self): """Computes the volumes of the "cells" in the mesh. """ self.cell_volumes = numpy.array( [ abs( self.node_coords[cell["nodes"]][1] - self.node_coor...
Compute the control volumes of all nodes in the mesh. def create_control_volumes(self): """Compute the control volumes of all nodes in the mesh. """ self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float) for k, cell in enumerate(self.cells): node_ids = cell["...
Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array. def create_rectangular_prism(origin, size): ''' Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrical...
Return a Mesh which is a triangular prism whose base is the triangle p1, p2, p3. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. def create_triangular_prism(p1, p2, p3, height): ''' Return a Mesh which is a triangular prism whose base is the triangle ...
Creates a horizontal plane. def create_horizontal_plane(): ''' Creates a horizontal plane. ''' v = np.array([ [1., 0., 0.], [-1., 0., 0.], [0., 0., 1.], [0., 0., -1.] ]) f = [[0, 1, 2], [3, 1, 0]] return Mesh(v=v, f=f)
Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label. def match_ref(self, ref): """ Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label. """ ...
Return the SQLAlchemy Column object matching a given, possibly qualified, column name (i.e.: 'table.column'). If no table is named, the fact table is assumed. def _physical_column(self, cube, column_name): """ Return the SQLAlchemy Column object matching a given, possibly qualified, col...
Map a model reference to an physical column in the database. def bind(self, cube): """ Map a model reference to an physical column in the database. """ table, column = self._physical_column(cube, self.column_name) column = column.label(self.matched_ref) column.quote = True retur...
Add new source (for example: a new card) to the customer The new source will be automatically set as customer's default payment source. Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated. def add_new_source(self, source_token, stripe_js_response=None): ...
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if commit is False. def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True): ...
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe API or update the local object with data fetched from Stripe. def save(self, force_retrieve=False, *args, **kwargs): """ Use the force_retrieve parameter to create a new StripeCoupon ...
Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. def get_signed_simplex_volumes(cells, pts): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = p...
Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this routine returns the indices where the blocks of equal integers start and how long the blocks are. def grp_start_len(a): """Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this routine returns the indices where the ...
Computes the circumcenters of all given triangles. def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej): """Computes the circumcenters of all given triangles. """ # The input argument are the dot products # # <e1, e2> # <e2, e0> # <e0, e1> # # of the edges # # ...
Get faces which are fully in subdomain. def get_edge_mask(self, subdomain=None): """Get faces which are fully in subdomain. """ if subdomain is None: # https://stackoverflow.com/a/42392791/353337 return numpy.s_[:] if subdomain not in self.subdomains: ...
Get faces which are fully in subdomain. def get_face_mask(self, subdomain): """Get faces which are fully in subdomain. """ if subdomain is None: # https://stackoverflow.com/a/42392791/353337 return numpy.s_[:] if subdomain not in self.subdomains: sel...
Mark faces/edges which are fully in subdomain. def _mark_vertices(self, subdomain): """Mark faces/edges which are fully in subdomain. """ if subdomain is None: is_inside = numpy.ones(len(self.node_coords), dtype=bool) else: is_inside = subdomain.is_inside(self.no...
Dump a yaml configuration as an OrderedDict. def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds): """Dump a yaml configuration as an OrderedDict.""" class OrderedDumper(Dumper): pass def dict_representer(dumper, data): return dumper.represent_mapping(yaml.resolver.BaseResol...
Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if it doesn't match def _check_type(self, ref, value): """ Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if i...
Returns the API type of the given value based on its python type. def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types):...
Apply a set of filters, which can be given as a set of tuples in the form (ref, operator, value), or as a string in query form. If it is ``None``, no filter will be applied. def apply(self, q, bindings, cuts): """ Apply a set of filters, which can be given as a set of tuples in the form...
Given an array of size NxM (usually Nx3), we accept color in the following ways: - A string color name. The accepted names are roughly what's in X11's rgb.txt - An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape - A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per ve...
Color each vertex by its height above the floor point. axis: The axis to use. 0 means x, 1 means y, 2 means z. threshold: The top of the range. Points at and above this height will be the same color. def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable...
Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with known scale. def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP): ''' Truncate weights to the range [0, max_weight] and rescale, as you would want for a heatmap with k...
Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array. def quads_to_tris(quads): ''' Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array. ''' import numpy as np tris = np.empty((2 * len(quads), 3)) tris[0::2, :] = quad...
returns all of the faces that contain at least one of the vertices in v_indices def all_faces_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' import numpy as np included_vertices = np.zeros(se...
Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns face indices def vertex_indices_in_segments(self, segments, ret_face_indices=False): ...
Keep the faces and vertices for given segments, discarding all others. When preserve_segmentation is false self.segm is discarded for speed. def keep_segments(self, segments_to_keep, preserve_segmentation=True): ''' Keep the faces and vertices for given segments, discarding all others. ...
Remove the faces and vertices for given segments, keeping all others. Args: segments_to_remove: a list of segnments whose vertices will be removed def remove_segments(self, segments_to_remove): ''' Remove the faces and vertices for given segments, keeping all others. Args: ...
returns array of all vertex indices common to each segment in segments def verts_in_common(self, segments): """ returns array of all vertex indices common to each segment in segments""" verts_by_segm = self.verts_by_segm return sorted(reduce(lambda s0, s1: s0.intersection(s1), ...
This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face, and hence has only one texture def uniquified_mesh(self): """This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face...
Returns a downsampled copy of this mesh. Args: step: the step size for the sampling Returns: a new, downsampled Mesh object. Raises: ValueError if this Mesh has faces. def downsampled_mesh(self, step): """Returns a downsampled copy of this mesh. ...
Keep the given vertices and discard the others, and any faces to which they may belong. If `ret_kept_faces` is `True`, return the original indices of the kept faces. Otherwise return `self` for chaining. def keep_vertices(self, indices_to_keep, ret_kept_faces=False): ''' Keep ...
Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or Lines objects. def create_from_mesh_and_lines(cls, mesh, lines): ''' Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or ...
Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects. def add_lines(self, lines): ''' Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects. ''' import numpy as np if not lines: return ...
Returns a sparse matrix (of size #verts x #verts) where each nonzero element indicates a neighborhood relation. For example, if there is a nonzero element in position (15, 12), that means vertex 15 is connected by an edge to vertex 12. def vert_connectivity(self): """Returns a sparse ma...
Returns a dictionary from vertidx-pairs to opposites. For example, a key consist of [4, 5)] meaning the edge between vertices 4 and 5, and a value might be [10, 11] which are the indices of the vertices opposing this edge. def vert_opposites_per_edge(self): """Returns a dictionary from ...
Returns an Ex2 array of adjacencies between faces, where each element in the array is a face index. Each edge is included only once. Edges that are not shared by 2 faces are not included. def faces_per_edge(self): """Returns an Ex2 array of adjacencies between faces, where each element ...
Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. Edges that are not shared by 2 faces are not included. def vertices_per_edge(self): """Returns an Ex2 array of adjacencies between vertices, where ea...
Returns a matrix M, which if multiplied by vertices, gives back edges (so "e = M.dot(v)"). Note that this generates one edge per edge, *not* two edges per triangle. Args: want_xyz: if true, takes and returns xyz coordinates, otherwise takes and returns x *or* y *or* ...
Given verts and faces, this remove colocated vertices def remove_redundant_verts(self, eps=1e-10): """Given verts and faces, this remove colocated vertices""" import numpy as np from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module fshape = self.f.shape tre...
Group the cardinality of the dimension into one of four buckets, from very small (less than 5) to very large (more than 1000). def cardinality_class(self): """ Group the cardinality of the dimension into one of four buckets, from very small (less than 5) to very large (more than 1000). """ ...
write_mtl: When True and mesh has a texture, includes a mtllib reference in the .obj and writes a .mtl alongside. def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name ''' write_mtl: When True and mesh has a texture,...
Signed area of a triangle in 2D. def signed_cell_areas(self): """Signed area of a triangle in 2D. """ # http://mathworld.wolfram.com/TriangleArea.html assert ( self.node_coords.shape[1] == 2 ), "Signed areas only make sense for triangles in 2D." if self._sig...
Set up edge-node and edge-cell relations. def create_edges(self): """Set up edge-node and edge-cell relations. """ # Reshape into individual edges. # Sort the columns to make it possible for `unique()` to identify # individual edges. s = self.idx_hierarchy.shape ...