text
stringlengths
18
773k
def format_help(help): """Format the help string.""" help = help.replace('Options:', str(crayons.black('Options:', bold=True))) help = help.replace('Usage: pinax', str('Usage: {0}'.format(crayons.black('pinax', bold=True)))) help = help.replace(' start', str(crayons.green(' start', bold=True))) ...
def load(file): """ This function expects a path to a file containing a **Detailed billing report with resources and tags** report from AWS. It returns a ``Costs`` object containing all of the lineitems from that detailed billing report """ fp = open(file) reader = csv.reader(fp) ...
def concepts(self): """ Return all existing concepts, i.e. dimensions, measures and attributes within the model. """ for measure in self.measures: yield measure for aggregate in self.aggregates: yield aggregate for dimension in self.dimensions: ...
def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in con...
def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument ''' obj: A dictionary mapping names to a 3-dimension array. mesh_filename: If provided, this value is included in the <DataFileName> attribute, which Meshlab doesn't seem to use. TODO Maybe reconstruct this usi...
def landm(self, val): ''' Sets landmarks given any of: - ppfile - ldmk file - dict of {name:inds} (i.e. mesh.landm) - dict of {name:xyz} (i.e. mesh.landm_xyz) - Nx1 array or list of ints (treated as landm, given sequential integers as names) - Nx3 ar...
def add(self, lineitem): """ Add a line item record to this Costs object. """ # Check for a ProductName in the lineitem. # If its not there, it is a subtotal line and including it # will throw the total cost calculation off. So ignore it. if lineitem['ProductName...
def filter(self, filters): """ Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the ...
def query(self, query, args=None): """ Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author...
def queryOne(self, query, args=None): """ Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your quer...
def queryMany(self, query, args): """ Executes a series of the same Insert Statments Each tuple in the args list will be applied to the query and executed. This is the equivilant of MySQLDB.cursor.executemany() @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = ...
def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execu...
def _GetConnection(self): """ Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008 """ #Attempt to get a connection. If all connections are in use and we have reached the max number of connections, #we wait 1 second and try again. #The Connection is returned locked to ...
def _ReturnConnection(self): """ Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 """ if self.conn is not None: if self.connInfo.commitOnEnd is True or self.commitOnEnd is True: self.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation function: column = getattr(func, self.functi...
def retrieve_public_key(user_repo): """Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being return...
def encrypt_key(key, password): """Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPub...
def dump_travis_configuration(config, path): """Dump the travis configuration settings to the travis.yml file. The configuration settings from the travis.yml will be dumped with ordering preserved. Thus, when a password is added to the travis.yml file, a diff will show that only the password was added....
def load_texture(self, texture_version): ''' Expect a texture version number as an integer, load the texture version from /is/ps/shared/data/body/template/texture_coordinates/. Currently there are versions [0, 1, 2, 3] availiable. ''' import numpy as np lowres_tex_templat...
def show_distribution_section(config, title, section_name): """ Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". """ payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = ...
def validate_django_compatible_with_python(): """ Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be comp...
def list_commands(self, ctx): """Override for showing commands in particular order""" commands = super(PinaxGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
def all_edges_with_verts(self, v_indices, as_boolean=False): ''' returns all of the faces that contain at least one of the vertices in v_indices ''' included_vertices = np.zeros(self.v.shape[0], dtype=bool) included_vertices[v_indices] = True edges_with_verts = included_v...
def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of the kept edges. Otherwise return `self` for chaining. ...
def read(filename): """Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data. :returns point_data: Point data read from file. :type point_data: dict :returns field_data: Field data read from file. :t...
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
def Connect(self): """ Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() se...
def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
def commit(self): """ Commit MySQL Transaction to database. MySQLDB: If the database and the tables support transactions, this commits the current transaction; otherwise this method successfully does nothing. @author: Nick Verbeck @since: 5/12/2008 """ try: if self.connection is not None: ...
def rollback(self): """ Rollback MySQL Transaction to database. MySQLDB: If the database and tables support transactions, this rolls back (cancels) the current transaction; otherwise a NotSupportedError is raised. @author: Nick Verbeck @since: 5/12/2008 """ try: if self.connection is not None:...
def Close(self): """ Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008 """ if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
def configure_api(app, manager): """ Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data. """ if not hasattr(app, 'extensions'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
def get_cube(name): """ Load the named cube from the current registered ``CubeManager``. """ manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
def jsonify(obj, status=200, headers=None): """ Custom JSONificaton to support obj.to_dict protocol. """ data = JSONEncoder().encode(obj) if 'callback' in request.args: cb = request.args.get('callback') data = '%s && %s(%s)' % (cb, cb, data) return Response(data, headers=headers, status=...
def cubes(): """ Get a listing of all publicly available cubes. """ cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
def aggregate(name): """ Perform an aggregation request. """ cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), or...
def facts(name): """ List the fact table entries in the current cube. This is the full materialized dataset. """ cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), cuts=request.args.get('cut'), order=request.args.get('order'), ...
def members(name, ref): """ List the members of a specific dimension or the distinct values of a given attribute. """ cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get(...
def apply(self, q, bindings, drilldowns): """ Apply a set of grouping criteria and project them. """ info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attrib...
def check_attribute_exists(instance): """ Additional check for the dimension model, to ensure that attributes given as the key and label attribute on the dimension exist. """ attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False l...
def check_valid_hierarchies(instance): """ Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions """ hierarchies = instance.get('hierarchies', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy ...
def load_validator(name): """ Load the JSON Schema Draft 4 validator with the given name from the local schema directory. """ with open(os.path.join(SCHEMA_PATH, name)) as fh: schema = json.load(fh) Draft4Validator.check_schema(schema) return Draft4Validator(schema, format_checker=checker)
def get_cube(self, name): """ Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to. """ return Cube(self.get_engine(), name, self.get_cube_model(name))
def list_cubes(self): """ List all available JSON files. """ for file_name in os.listdir(self.directory): if '.' in file_name: name, ext = file_name.rsplit('.', 1) if ext.lower() == 'json': yield name
def Terminate(self): """ Close all open connections Loop though all the connections and commit all queries and close all the connections. This should be called at the end of your application. @author: Nick Verbeck @since: 5/12/2008 """ self.lock.acquire() try: for bucket in self.connectio...
def Cleanup(self): """ Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.loc...
def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception:...
def GetConnection(self, ConnectionObj): """ Get a Open and active connection Returns a PySQLConnectionManager if one is open else it will create a new one if the max active connections hasn't been hit. If all possible connections are used. Then None is returned. @param PySQLConnectionObj: PySQLConnectio...
def main(): """ Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).""" import re with open('rgb.txt') as fp: line = fp.readline() while line: reg = re.match(r'\s*(\d+)\s*(\d+)\s*(\d+)\s*(\w.*\w).*', line) if reg: r ...
async def on_date(self, date: datetime.date) -> dict: """Get statistics for a certain date.""" return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
async def upcoming(self, details: bool = False) -> list: """Return watering statistics for the next 6 days.""" endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoin...
async def main(): """Run.""" async with ClientSession() as websession: try: client = Client(websession) await client.load_local('<IP ADDRESS>', '<PASSWORD>', websession) for controller in client.controllers.values(): print('CLIENT INFORMATION') ...
def _raise_for_remote_status(url: str, data: dict) -> None: """Raise an error from the remote API if necessary.""" if data.get('errorType') and data['errorType'] > 0: raise_remote_error(data['errorType']) if data.get('statusCode') and data['statusCode'] != 200: raise RequestError( ...
async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAULT_TIMEOUT) -> Controller: """Authenticate against a RainMachine device.""" print('regenmaschine.client.login() is depr...
async def load_local( # pylint: disable=too-many-arguments self, host: str, password: str, port: int = DEFAULT_LOCAL_PORT, ssl: bool = True, skip_existing: bool = True) -> None: """Create a local client.""" controller = LocalContro...
async def load_remote( self, email: str, password: str, skip_existing: bool = True) -> None: """Create a local client.""" auth_resp = await self._request( 'post', 'https://my.rainmachine.com/login/auth', json={'user': { 'email':...
async def _request( self, method: str, url: str, *, access_token: str = None, access_token_expiration: datetime = None, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) ...
def raise_remote_error(error_code: int) -> None: """Raise the appropriate error with a remote error code.""" try: error = next((v for k, v in ERROR_CODES.items() if k == error_code)) raise RequestError(error) except StopIteration: raise RequestError( 'Unknown remote error...
def quarter_boundaries(quarter): """Returns first and last day of a quarter Args: quarter (str) quarter, in format '2015Q1' Returns: (tuple) datetime.dates for the first and last days of the quarter """ year, quarter = quarter.split('Q') year = int(year) quarter = int(quarter) ...
def metta_config(quarter, num_dimensions): """Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test """ first...
def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions): """Store train and test matrices using metta Args: train_features_path (str) Path to matrix with train features train_labels_path (str) Path to matrix ...
def usedby_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): """ Lock packages. Downloader search packages """ if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._...
def upload(s3_conn, filepath, s3_path): """Uploads the given file to s3 Args: s3_conn: (boto.s3.connection) an s3 connection filepath (str) the local filename s3_path (str) the destination path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucke...
def upload_dict(s3_conn, s3_prefix, data_to_sync): """Syncs a dictionary to an S3 bucket, serializing each value in the dictionary as a JSON file with the key as its name. Args: s3_conn: (boto.s3.connection) an s3 connection s3_prefix: (str) the destination prefix data_to_sync: (dic...
def download(s3_conn, out_filename, s3_path): """Downloads the given s3_path Args: s3_conn (boto.s3.connection) a boto s3 connection out_filename (str) local filename to save the file s3_path (str) the source path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket...
async def _request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None, json: dict = None, ssl: bool = True) -> dict: """Wrap the generic request method to add access token, etc.""" ...
async def login(self, password): """Authenticate against the device (locally).""" auth_resp = await self._client_request( 'post', '{0}/auth/login'.format(self._host), json={ 'pwd': password, 'remember': 1 }) self._a...
async def login( self, stage_1_access_token: str, sprinkler_id: str, password: str) -> None: """Authenticate against the device (remotely).""" auth_resp = await self._client_request( 'post', 'https://my.rainmachine.com/devices/login-sprinkler', ...
def set_duplicated_flag(self): """ For all package set flag duplicated, if it's not unique package :return: """ package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_...
def get_object_from_string(object_path): """ Return python object from string :param object_path: e.g os.path.join :return: python object """ # split like crosspm.template.GUS => crosspm.template, GUS try: module_name, object_name = object_path.rsplit('.', maxsplit=1) module_...
async def _post(self, zone_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing zone.""" return await self._request( 'post', 'zone/{0}/properties'.format(zone_id), json=json)
async def all( self, *, details: bool = False, include_inactive: bool = False) -> list: """Return all zones (with optional advanced properties).""" endpoint = 'zone' if details: endpoint += '/properties' data = await self._request('get', endpoint) ...
async def get(self, zone_id: int, *, details: bool = False) -> dict: """Return a specific zone.""" endpoint = 'zone/{0}'.format(zone_id) if details: endpoint += '/properties' return await self._request('get', endpoint)
async def start(self, zone_id: int, time: int) -> dict: """Start a program.""" return await self._request( 'post', 'zone/{0}/start'.format(zone_id), json={'time': time})
def observable_method(func, strategy='instances'): """ I turn a method into something that can be observed by other callables. You can use me as a decorator on a method, like this: class Foo(object): __init__(self, name): self.name = name @observable_method...
def add_observer(self, observer, identify_observed=False): """Register an observer to observe me. Args: observer: The callable to register as an observer. identify_observed: If True, then the observer will get myself passed as an additional first argument wheneve...
def _add_function(self, func, identify_observed): """Add a function as an observer. Args: func: The function to register as an observer. identify_observed: See docstring for add_observer. Returns: True if the function is added, otherwise False. """ ...
def _add_bound_method(self, bound_method, identify_observed): """Add an bound method as an observer. Args: bound_method: The bound method to add as an observer. identify_observed: See the docstring for add_observer. Returns: True if the bound method is added...
def discard_observer(self, observer): """Un-register an observer. Args: observer: The observer to un-register. Returns true if an observer was removed, otherwise False. """ discarded = False key = self.make_key(observer) if key in self.observers: ...
def make_key(observer): """Construct a unique, hashable, immutable key for an observer.""" if hasattr(observer, "__self__"): inst = observer.__self__ method_name = observer.__name__ key = (id(inst), method_name) else: key = id(observer) re...
def build_command_tree(pattern, cmd_params): """ Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object. """ from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument if type(pattern) in [Either, Optional, OneOrMore]: for chil...
def group(self): """Yield a group from the iterable""" yield self.current # start enumerate at 1 because we already yielded the last saved item for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break ...
def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): """ Lock packages. Downloader search packages """ if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._de...
def stdout(self): """ Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT. Если есть любое значение в CROSSPM_STDOUT - оно понимается как True :return: """ # --stdout stdout = self._args['--stdout'] if stdout: return True ...
def prepare_args(args, windows=None): """ Prepare args - add support for old interface, e.g: - --recursive was "flag" and for now it support True or False value :param args: :return: """ if windows is None: windows = "win" in sys.platform ...
async def log( self, date: datetime.date = None, days: int = None, details: bool = False) -> list: """Get watering information for X days from Y date.""" endpoint = 'watering/log' if details: endpoint += '/details' if date and ...
async def runs(self, date: datetime.date = None, days: int = None) -> list: """Return all program runs for X days from Y date.""" endpoint = 'watering/past' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = ...
def search_auth(self, list_or_file_path, source): """ Looking for auth in env, cmdline, str :param list_or_file_path: :param source: """ _auth = source.args['auth'] if isinstance(_auth, str): if ':' in _auth: _auth = _auth.split(':') ...
async def _post(self, program_id: int = None, json: dict = None) -> dict: """Post data to a (non)existing program.""" return await self._request( 'post', 'program/{0}'.format(program_id), json=json)
async def all(self, include_inactive: bool = False) -> list: """Return all programs.""" data = await self._request('get', 'program') return [p for p in data['programs'] if include_inactive or p['active']]
def cache_json(filename): """Caches the JSON-serializable output of the function to a given file Args: filename (str) The filename (sans directory) to store the output Returns: decorator, applicable to a function that produces JSON-serializable output """ def cache_decorator(cacheable_func...
def check_create_folder(filename): """Check if the folder exisits. If not, create the folder""" os.makedirs(os.path.dirname(filename), exist_ok=True)
def get_payment_request(self, cart, request): """ From the given request, redirect onto the checkout view, hosted by PayPal. """ shop_ns = resolve(request.path).namespace return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace)) cancel_url = reverse('{}:{}:canc...
def postings(self, quarter, stats_counter=None): """Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method. ...
def _generate_search_terms(self): """ Map search terms to what test case(s) they're related to Returns: dict: maps search terms to what test case(s) it's relevant to Example: { '12034': ['ui.tests.TestSomething.test_hello_world'], 'buggy': ['...
def afterSummaryReport(self, event): """ After everything is done, generate the report """ logger.info('Generating HTML report...') sorted_test_results = self._sort_test_results() context = { 'test_report_title': 'Test Report', 'test_summary': se...
def quarter_to_daterange(quarter): """Convert a quarter in arbitrary filename-ready format (e.g. 2015Q1) into start and end datetimes""" assert len(quarter) == 6 year = int(quarter[0:4]) quarter = quarter[5] MONTH_DAY = { '1': ((1, 1), (3, 31)), '2': ((4, 1), (6, 30)), '3...
def datetime_to_year_quarter(dt): """ Args: dt: a datetime Returns: tuple of the datetime's year and quarter """ year = dt.year quarter = int(math.ceil(float(dt.month)/3)) return (year, quarter)