code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
order = [ "start", "projects", ] ordered = [] commands = dict(zip([cmd for cmd in sub_commands], sub_commands)) for k in order: ordered.append(commands.get(k, "")) if k in commands: del commands[k] # Add commands not present in `order` above ...
def order_manually(sub_commands)
Order sub-commands for display
4.000103
4.070076
0.982808
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))) help = help.replace(' apps', str(crayons.yellow(' ...
def format_help(help)
Format the help string.
2.372506
2.365767
1.002849
fp = open(file) reader = csv.reader(fp) headers = next(reader) costs = Costs(headers) for line in reader: data = {} for i in range(0, len(headers)): data[headers[i]] = line[i] data['UnBlendedCost'] = decimal.Decimal(data['UnBlendedCost']) data['Blende...
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
2.519726
2.259398
1.11522
for measure in self.measures: yield measure for aggregate in self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dimension.attributes: yield attribute
def concepts(self)
Return all existing concepts, i.e. dimensions, measures and attributes within the model.
3.383237
2.693968
1.255856
try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in concept.attributes] except KeyError: return []
def match(self, ref)
Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself.
5.878635
3.365607
1.746679
raise ValueError('obj should be a dict of points') points = '\n'.join([point_template % (tuple(xyz) + (name,)) for name, xyz in obj.iteritems()]) return file_template % (mesh_filename, points)
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...
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 using xml.etree
3.259682
3.286017
0.991986
''' 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 array or list of floats ...
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 array or list of floats (treated as landm_xy...
3.94247
2.262347
1.742646
# 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']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: ...
def add(self, lineitem)
Add a line item record to this Costs object.
4.763219
4.471792
1.06517
subset = Costs(self._columns) filters = [(col, re.compile(regex)) for col, regex in filters] for lineitem in self._lineitems: for filter in filters: if filter[1].search(lineitem[filter[0]]) is None: continue subset.add(line...
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 regular expression matches the value in th...
5.009061
3.497742
1.432084
self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() log.logger.debug('Running query "%s" with args "%s"', query, args) self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = c...
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: Nick Verbeck @since: 5/12/2008
3.071093
3.055838
1.004992
self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.conn.updateCheckTime() while 1: row = cursor.fetchone(...
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 query. A mapping may also be used but your query m...
2.674534
2.569087
1.041045
self.lastError = None self.affectedRows = None self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.executemany(query, args) se...
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
2.803105
2.80311
0.999998
self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execute query and store results cursor = self.conn.getCursor() for query in queries: self.conn.query = query if query.__class__ == [].__class_...
def queryMulti(self, queries)
Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008
2.819839
2.881429
0.978625
#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 be thread safe while self.conn is None: self.conn = Pool().GetConnection(self.connInfo) if self.conn is not None: bre...
def _GetConnection(self)
Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008
5.438698
5.507348
0.987535
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 _ReturnConnection(self)
Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008
5.596321
5.841002
0.95811
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.function)(column) column = column.label(self.ref) column.quote =...
def bind(self, cube)
When one column needs to match, use the key.
6.465881
6.108912
1.058434
url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.split('/') raise InvalidCredentialsError("Either the username: '{}' or t...
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 returned from the Travis API as PKCS8 encoded, th...
4.505075
3.833812
1.17509
public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
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 RSAPublicKey. The encrypted password is t...
2.389137
2.119071
1.127445
with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
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. Parameters ---------- config: collecti...
3.426209
3.839445
0.892371
''' 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_template = 's3://bodylabs-korper-assets/is/ps/sh...
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.
5.175959
2.853825
1.813692
payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Release".rjust(7), title)) click.echo("------- ---------------") section = latest_distribution[section_name] nam...
def show_distribution_section(config, title, section_name)
Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes".
4.597147
4.03217
1.140117
python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
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 compatible.
5.677453
5.148837
1.102667
commands = super(PinaxGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
def list_commands(self, ctx)
Override for showing commands in particular order
14.017961
11.387081
1.231041
''' 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_vertices[self.e].all(axis=1) if as_boolean: ...
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
2.829758
2.239333
1.263661
''' 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. ''' if self.v is None: return i...
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.
2.536616
1.930738
1.313806
mesh = meshio.read(filename) # make sure to include the used nodes only if "tetra" in mesh.cells: points, cells = _sanitize(mesh.points, mesh.cells["tetra"]) return ( MeshTetra(points, cells), mesh.point_data, mesh.cell_data, mesh.field_d...
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. :type field_data: dict
2.493755
2.826579
0.882252
self._locked = True return self._lock.acquire(block)
def lock(self, block=True)
Lock connection from being used else where
4.633767
5.891851
0.78647
if self._locked is True: self._locked = False self._lock.release()
def release(self)
Release the connection lock
4.73059
3.563296
1.327588
if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
def getCursor(self)
Get a Dictionary Cursor for executing queries
3.672283
3.560113
1.031508
if self.connection is None: self.connection = MySQLdb.connect(*[], **self.connectionInfo.info) if self.connectionInfo.commitOnEnd is True: self.connection.autocommit() self._updateCheckTime()
def Connect(self)
Creates a new physical connection to the database @author: Nick Verbeck @since: 5/12/2008
7.859279
8.391577
0.936568
try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
def being(self)
Being a Transaction @author: Nick Verbeck @since: 5/14/2011
4.147933
3.897804
1.064172
try: if self.connection is not None: self.connection.commit() self._updateCheckTime() self.release() 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
4.727407
5.35754
0.882384
try: if self.connection is not None: self.connection.rollback() self._updateCheckTime() self.release() except Exception, e: pass
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
4.563559
5.397988
0.845418
if self.connection is not None: try: self.connection.commit() self.connection.close() self.connection = None except Exception, e: pass
def Close(self)
Commits and closes the current connection @author: Nick Verbeck @since: 5/12/2008
2.441825
2.337961
1.044425
if not hasattr(app, 'extensions'): app.extensions = {} # pragma: nocover app.extensions['babbage'] = manager return blueprint
def configure_api(app, manager)
Configure the current Flask app with an instance of ``CubeManager`` that will be used to load and query data.
5.811911
7.072331
0.821782
manager = get_manager() if not manager.has_cube(name): raise NotFound('No such cube: %r' % name) return manager.get_cube(name)
def get_cube(name)
Load the named cube from the current registered ``CubeManager``.
3.43778
3.096097
1.110359
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=status, mimetype='application/json')
def jsonify(obj, status=200, headers=None)
Custom JSONificaton to support obj.to_dict protocol.
2.401131
2.355797
1.019244
cubes = [] for cube in get_manager().list_cubes(): cubes.append({ 'name': cube }) return jsonify({ 'status': 'ok', 'data': cubes })
def cubes()
Get a listing of all publicly available cubes.
3.360422
2.921151
1.150376
cube = get_cube(name) result = cube.aggregate(aggregates=request.args.get('aggregates'), drilldowns=request.args.get('drilldown'), cuts=request.args.get('cut'), order=request.args.get('order'), p...
def aggregate(name)
Perform an aggregation request.
3.023401
2.860859
1.056815
cube = get_cube(name) result = cube.facts(fields=request.args.get('fields'), cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) ...
def facts(name)
List the fact table entries in the current cube. This is the full materialized dataset.
2.992194
2.956828
1.011961
cube = get_cube(name) result = cube.members(ref, cuts=request.args.get('cut'), order=request.args.get('order'), page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' return jsonify...
def members(name, ref)
List the members of a specific dimension or the distinct values of a given attribute.
3.656263
3.741704
0.977165
info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Binding(table, attribute.ref)) q...
def apply(self, q, bindings, drilldowns)
Apply a set of grouping criteria and project them.
5.688873
5.448936
1.044034
attributes = instance.get('attributes', {}).keys() if instance.get('key_attribute') not in attributes: return False label_attr = instance.get('label_attribute') if label_attr and label_attr not in attributes: return False return True
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.
3.387
2.511546
1.348572
hierarchies = instance.get('hierarchies', {}).values() dimensions = set(instance.get('dimensions', {}).keys()) all_levels = set() for hierarcy in hierarchies: levels = set(hierarcy.get('levels', [])) if len(all_levels.intersection(levels)) > 0: # Dimension appears in two...
def check_valid_hierarchies(instance)
Additional check for the hierarchies model, to ensure that levels given are pointing to actual dimensions
3.051843
2.874971
1.061521
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 load_validator(name)
Load the JSON Schema Draft 4 validator with the given name from the local schema directory.
3.110339
3.112485
0.999311
return Cube(self.get_engine(), name, self.get_cube_model(name))
def get_cube(self, name)
Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to.
7.671504
7.291592
1.052103
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 list_cubes(self)
List all available JSON files.
3.256625
2.632949
1.236874
self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.Close() except Exception: #We may throw exceptions due to already closed connections pass conn.release() except Exception: pass ...
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
3.515561
3.141078
1.119221
self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: open = conn.TestConnection(forceCheck=True) if open is True: conn.commit() else: #Remove the connection from the pool. Its dead better of recrea...
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
4.234903
4.110591
1.030242
self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception: conn.release() except Exception: pass finally: self.lock.release()
def Commit(self)
Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008
2.763541
2.636068
1.048357
key = ConnectionObj.getKey() connection = None if self.connections.has_key(key): connection = self._getConnectionFromPoolSet(key) if connection is None: self.lock.acquire() if len(self.connections[key]) < self.maxActiveConnections: #Create a new connection connection = self...
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: PySQLConnection Object representing your connection string @...
3.107183
3.035751
1.02353
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 = int(reg.group(1)) / 255. g = int(reg.group(2)) / 255. b = int(reg.group(3...
def main()
Generates code for name_to_rgb dict, assuming an rgb.txt file available (in X11 format).
2.262064
1.998539
1.131859
return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
async def on_date(self, date: datetime.date) -> dict
Get statistics for a certain date.
6.196312
4.227043
1.465874
endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoint) return data[key]
async def upcoming(self, details: bool = False) -> list
Return watering statistics for the next 6 days.
4.481176
3.772814
1.187754
if data.get('errorType') and data['errorType'] > 0: raise_remote_error(data['errorType']) if data.get('statusCode') and data['statusCode'] != 200: raise RequestError( 'Error requesting data from {0}: {1} {2}'.format( url, data['statusCode'], data['message']))
def _raise_for_remote_status(url: str, data: dict) -> None
Raise an error from the remote API if necessary.
3.681815
3.316113
1.11028
print('regenmaschine.client.login() is deprecated; see documentation!') client = Client(websession, request_timeout) await client.load_local(host, password, port, ssl) return next(iter(client.controllers.values()))
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.
9.703135
9.286098
1.04491
controller = LocalController( self._request, host, port, ssl, self._websession) await controller.login(password) wifi_data = await controller.provisioning.wifi() if skip_existing and wifi_data['macAddress'] in self.controllers: return version_da...
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.
3.853662
3.771114
1.02189
auth_resp = await self._request( 'post', 'https://my.rainmachine.com/login/auth', json={'user': { 'email': email, 'pwd': password, 'remember': 1 }}) access_token = auth_resp['access_token'] ...
async def load_remote( self, email: str, password: str, skip_existing: bool = True) -> None
Create a local client.
2.739147
2.706235
1.012161
if (access_token_expiration and datetime.now() >= access_token_expiration): raise TokenExpiredError('Long-lived access token has expired') if not headers: headers = {} headers.update({'Content-Type': 'application/json'}) if not params: ...
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) ...
Make a request against the RainMachine device.
2.325904
2.277438
1.021281
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 code returned: {0}'.format(error_code))
def raise_remote_error(error_code: int) -> None
Raise the appropriate error with a remote error code.
3.767848
3.319247
1.135151
year, quarter = quarter.split('Q') year = int(year) quarter = int(quarter) first_month_of_quarter = 3 * quarter - 2 last_month_of_quarter = 3 * quarter first_day = date(year, first_month_of_quarter, 1) last_day = date(year, last_month_of_quarter, monthrange(year, last_month_of_quarter)[...
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
1.737922
1.63135
1.065328
first_day, last_day = quarter_boundaries(quarter) return { 'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, # ??? 'label_name': 'onet_soc_code', 'label_type': 'categorical', 'matrix_id': 'job_postings_{}'.format(quarter), 'featur...
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
5.051364
4.661038
1.083742
train_config = metta_config(train_quarter, num_dimensions) test_config = metta_config(test_quarter, num_dimensions) X_train = pd.read_csv(train_features_path, sep=',') X_train.columns = ['doc2vec_'+str(i) for i in range(X_train.shape[1])] #X_train['label'] = pd.Series([randint(0,23) for i in r...
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 with train labels test_features_path (str) Path to matrix with test features test_labels_path (str) Path to matrix with test labels ...
1.931851
2.034815
0.949399
if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._depslock_path if deps_file_path == depslock_file_path: depslock_file_path += '.lock' if packages is None: self.s...
def usedby_packages(self, deps_file_path=None, depslock_file_path=None, packages=None)
Lock packages. Downloader search packages
2.5902
2.521371
1.027299
bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) filename = os.path.basename(filepath) key = boto.s3.key.Key( bucket=bucket, name='{}/{}'.format(prefix, filename) ) logging.info('uploading from %s to %s', filepath, key) key.set_conte...
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
2.129032
2.558955
0.831993
bucket_name, prefix = split_s3_path(s3_prefix) bucket = s3_conn.get_bucket(bucket_name) for key, value in data_to_sync.items(): full_name = '{}/{}.json'.format(prefix, key) s3_key = boto.s3.key.Key( bucket=bucket, name=full_name ) logging.info('u...
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: (dict)
1.990523
2.300807
0.865141
bucket_name, prefix = split_s3_path(s3_path) bucket = s3_conn.get_bucket(bucket_name) key = boto.s3.key.Key( bucket=bucket, name=prefix ) logging.info('loading from %s into %s', key, out_filename) key.get_contents_to_filename(out_filename, cb=log_download_progress)
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
2.426182
2.917327
0.831645
return await self._client_request( method, '{0}/{1}'.format(self._host, endpoint), access_token=self._access_token, access_token_expiration=self._access_token_expiration, headers=headers, params=params, json=json, ...
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.
2.565153
2.26946
1.130292
auth_resp = await self._client_request( 'post', '{0}/auth/login'.format(self._host), json={ 'pwd': password, 'remember': 1 }) self._access_token = auth_resp['access_token'] self._access_token_expiration = d...
async def login(self, password)
Authenticate against the device (locally).
2.994369
2.888254
1.03674
auth_resp = await self._client_request( 'post', 'https://my.rainmachine.com/devices/login-sprinkler', access_token=stage_1_access_token, json={ 'sprinklerId': sprinkler_id, 'pwd': password, }) self._acc...
async def login( self, stage_1_access_token: str, sprinkler_id: str, password: str) -> None
Authenticate against the device (remotely).
3.893221
3.573892
1.08935
package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_name = package1.package_name param_list = self._config.get_fails('unique', {}) params1 = package1.get_params(pa...
def set_duplicated_flag(self)
For all package set flag duplicated, if it's not unique package :return:
3.227366
3.19332
1.010662
# split like crosspm.template.GUS => crosspm.template, GUS try: module_name, object_name = object_path.rsplit('.', maxsplit=1) module_ = __import__(module_name, globals(), locals(), ['App'], 0) variable_ = getattr(module_, object_name) except Exception: variable_ = None ...
def get_object_from_string(object_path)
Return python object from string :param object_path: e.g os.path.join :return: python object
5.176227
5.372718
0.963428
return await self._request( 'post', 'zone/{0}/properties'.format(zone_id), json=json)
async def _post(self, zone_id: int = None, json: dict = None) -> dict
Post data to a (non)existing zone.
6.676164
5.1659
1.292353
endpoint = 'zone' if details: endpoint += '/properties' data = await self._request('get', endpoint) return [z for z in data['zones'] if include_inactive or z['active']]
async def all( self, *, details: bool = False, include_inactive: bool = False) -> list
Return all zones (with optional advanced properties).
5.397949
3.926607
1.374711
endpoint = 'zone/{0}'.format(zone_id) if details: endpoint += '/properties' return await self._request('get', endpoint)
async def get(self, zone_id: int, *, details: bool = False) -> dict
Return a specific zone.
4.711642
3.677917
1.281062
return await self._request( 'post', 'zone/{0}/start'.format(zone_id), json={'time': time})
async def start(self, zone_id: int, time: int) -> dict
Start a program.
5.013551
3.803016
1.318309
if strategy == 'instances': return ObservableMethodManager_PersistOnInstances(func) elif strategy == 'descriptor': return ObservableMethodManager_PersistOnDescriptor(func) else: raise ValueError("Strategy %s not recognized"%(strategy,))
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 bar(self, x): print("%s called bar wit...
4.515513
2.188906
2.062908
# If the observer is a bound method, if hasattr(observer, "__self__"): result = self._add_bound_method(observer, identify_observed) # Otherwise, assume observer is a normal function. else: result = self._add_function(observer, identify_observed) ...
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 whenever it is invoked. See ObserverFunction and ObserverBoun...
3.188499
3.026759
1.053437
key = self.make_key(func) if key not in self.observers: self.observers[key] = ObserverFunction( func, identify_observed, (key, self.observers)) return True else: return False
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.
4.202222
3.921908
1.071474
inst = bound_method.__self__ method_name = bound_method.__name__ key = self.make_key(bound_method) if key not in self.observers: self.observers[key] = ObserverBoundMethod( inst, method_name, identify_observed, (key, self.observers)) retur...
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, otherwise False.
3.701812
3.78632
0.977681
discarded = False key = self.make_key(observer) if key in self.observers: del self.observers[key] discarded = True return discarded
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.
3.220972
3.716247
0.866727
if hasattr(observer, "__self__"): inst = observer.__self__ method_name = observer.__name__ key = (id(inst), method_name) else: key = id(observer) return key
def make_key(observer)
Construct a unique, hashable, immutable key for an observer.
3.477999
3.071707
1.132269
from docopt import Either, Optional, OneOrMore, Required, Option, Command, Argument if type(pattern) in [Either, Optional, OneOrMore]: for child in pattern.children: build_command_tree(child, cmd_params) elif type(pattern) in [Required]: for child in pattern.children: ...
def build_command_tree(pattern, cmd_params)
Recursively fill in a command tree in cmd_params according to a docopt-parsed "pattern" object.
2.494076
2.29471
1.086881
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 yield item else: self.on_going =...
def group(self)
Yield a group from the iterable
7.924656
6.782357
1.168422
if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._depslock_path if deps_file_path == depslock_file_path: depslock_file_path += '.lock' # raise CrosspmException( ...
def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None)
Lock packages. Downloader search packages
3.123921
3.065212
1.019154
# --stdout stdout = self._args['--stdout'] if stdout: return True # CROSSPM_STDOUT stdout_env = os.getenv('CROSSPM_STDOUT', None) if stdout_env is not None: return True return False
def stdout(self)
Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT. Если есть любое значение в CROSSPM_STDOUT - оно понимается как True :return:
6.732039
3.749775
1.795318
if windows is None: windows = "win" in sys.platform if isinstance(args, str): args = shlex.split(args, posix=not windows) elif isinstance(args, list): pass elif args is None: args = sys.argv[1:] else: raise Exc...
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:
3.709395
3.485957
1.064097
endpoint = 'watering/log' if details: endpoint += '/details' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['waterLog']['days'...
async def log( self, date: datetime.date = None, days: int = None, details: bool = False) -> list
Get watering information for X days from Y date.
4.265315
3.469202
1.22948
endpoint = 'watering/past' if date and days: endpoint = '{0}/{1}/{2}'.format( endpoint, date.strftime('%Y-%m-%d'), days) data = await self._request('get', endpoint) return data['pastValues']
async def runs(self, date: datetime.date = None, days: int = None) -> list
Return all program runs for X days from Y date.
5.097985
4.741141
1.075265
_auth = source.args['auth'] if isinstance(_auth, str): if ':' in _auth: _auth = _auth.split(':') elif _auth.endswith('}') and ( _auth.startswith('{') or ':' in _auth): # {auth}, {user}:{password}, user:{password} _auth...
def search_auth(self, list_or_file_path, source)
Looking for auth in env, cmdline, str :param list_or_file_path: :param source:
2.364583
2.363103
1.000626
return await self._request( 'post', 'program/{0}'.format(program_id), json=json)
async def _post(self, program_id: int = None, json: dict = None) -> dict
Post data to a (non)existing program.
5.488411
4.070291
1.348407
data = await self._request('get', 'program') return [p for p in data['programs'] if include_inactive or p['active']]
async def all(self, include_inactive: bool = False) -> list
Return all programs.
6.933547
4.309319
1.608966
def cache_decorator(cacheable_function): @wraps(cacheable_function) def cache_wrapper(*args, **kwargs): path = CACHE_DIRECTORY + filename check_create_folder(path) if os.path.exists(path): with open(path) as infile: return ...
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
2.082989
2.154477
0.966819
os.makedirs(os.path.dirname(filename), exist_ok=True)
def check_create_folder(filename)
Check if the folder exisits. If not, create the folder
2.541157
2.430083
1.045708
shop_ns = resolve(request.path).namespace return_url = reverse('{}:{}:return'.format(shop_ns, self.namespace)) cancel_url = reverse('{}:{}:cancel'.format(shop_ns, self.namespace)) cart = CartModel.objects.get_from_request(request) cart.update(request) # to calculate the...
def get_payment_request(self, cart, request)
From the given request, redirect onto the checkout view, hosted by PayPal.
2.676999
2.607912
1.026491
logging.info('Finding postings for %s', quarter) for posting in self._iter_postings(quarter): transformed = self._transform(posting) transformed['id'] = '{}_{}'.format( self.partner_id, self._id(posting) ) if stats_...
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.
4.270519
3.575258
1.194464
search_terms = {} for test_result in self.test_results: # search for the test name itself maps to the test case search_terms[test_result['name']] = test_result['name'] if test_result['description']: for token in test_result['description'].sp...
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': ['ui.tests.TestSomething.test_hello_world', 'ui.tests.Te...
2.919941
2.799305
1.043095
logger.info('Generating HTML report...') sorted_test_results = self._sort_test_results() context = { 'test_report_title': 'Test Report', 'test_summary': self.summary_stats, 'test_results': sorted_test_results, 'autocomplete_terms': json....
def afterSummaryReport(self, event)
After everything is done, generate the report
3.514789
3.423658
1.026618
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': ((7, 1), (9, 30)), '4': ((10, 1), (12, 31)) } md = MONTH_DAY[quarter] start_md, end_md = md return ( date...
def quarter_to_daterange(quarter)
Convert a quarter in arbitrary filename-ready format (e.g. 2015Q1) into start and end datetimes
2.078046
2.076867
1.000568
year = dt.year quarter = int(math.ceil(float(dt.month)/3)) return (year, quarter)
def datetime_to_year_quarter(dt)
Args: dt: a datetime Returns: tuple of the datetime's year and quarter
2.948674
3.204777
0.920087