Search is not available for this dataset
text
stringlengths
75
104k
def list_dirnames_in_directory(self, dirname): """List all names of directories that exist at the root of this bucket directory. Note that *directories* don't exist in S3; rather directories are inferred from path names. Parameters ---------- dirname : `str` Directory name in the bucket relative to ``bucket_root``. Returns ------- dirnames : `list` List of directory names (`str`), relative to ``bucket_root/``, that exist at the root of ``dirname``. """ prefix = self._create_prefix(dirname) dirnames = [] for obj in self._bucket.objects.filter(Prefix=prefix): # get directory name of every object under this path prefix dirname = os.path.dirname(obj.key) # dirname is empty if the object happens to be the directory # redirect object object for the prefix directory (directory # redirect objects are named after directories and have metadata # that tells Fastly to redirect the browser to the index.html # contained in the directory). if dirname == '': dirname = obj.key + '/' # Strip out the path prefix from the directory name rel_dirname = os.path.relpath(dirname, start=prefix) # If there's only one part then this directory is at the root # relative to the prefix. We want this. dir_parts = rel_dirname.split('/') if len(dir_parts) == 1: dirnames.append(dir_parts[0]) # Above algorithm finds root directories for all *files* in sub # subdirectories; trim down to the unique set. dirnames = list(set(dirnames)) # Remove posix-like relative directory names that can appear # in the bucket listing. for filtered_dir in ('.', '..'): if filtered_dir in dirnames: dirnames.remove(filtered_dir) return dirnames
def _create_prefix(self, dirname): """Make an absolute directory path in the bucker for dirname, which is is assumed relative to the self._bucket_root prefix directory. """ if dirname in ('.', '/'): dirname = '' # Strips trailing slash from dir prefix for comparisons # os.path.dirname() returns directory names without a trailing / prefix = os.path.join(self._bucket_root, dirname) prefix = prefix.rstrip('/') return prefix
def delete_file(self, filename): """Delete a file from the bucket. Parameters ---------- filename : `str` Name of the file, relative to ``bucket_root/``. """ key = os.path.join(self._bucket_root, filename) objects = list(self._bucket.objects.filter(Prefix=key)) for obj in objects: obj.delete()
def delete_directory(self, dirname): """Delete a directory (and contents) from the bucket. Parameters ---------- dirname : `str` Name of the directory, relative to ``bucket_root/``. Raises ------ RuntimeError Raised when there are no objects to delete (directory does not exist). """ key = os.path.join(self._bucket_root, dirname) if not key.endswith('/'): key += '/' key_objects = [{'Key': obj.key} for obj in self._bucket.objects.filter(Prefix=key)] if len(key_objects) == 0: msg = 'No objects in bucket directory {}'.format(dirname) raise RuntimeError(msg) delete_keys = {'Objects': key_objects} # based on http://stackoverflow.com/a/34888103 s3 = self._session.resource('s3') r = s3.meta.client.delete_objects(Bucket=self._bucket.name, Delete=delete_keys) self._logger.debug(r) if 'Errors' in r: raise S3Error('S3 could not delete {0}'.format(key))
def ensure_login(ctx): """Ensure a token is in the Click context object or authenticate and obtain the token from LTD Keeper. Parameters ---------- ctx : `click.Context` The Click context. ``ctx.obj`` must be a `dict` that contains keys: ``keeper_hostname``, ``username``, ``password``, ``token``. This context object is prepared by the main Click group, `ltdconveyor.cli.main.main`. """ logger = logging.getLogger(__name__) logger.info('utils name %r', __name__) if ctx.obj['token'] is None: if ctx.obj['username'] is None or ctx.obj['password'] is None: raise click.UsageError( 'Use `ltd -u <username> -p <password> COMMAND` to ' 'authenticate to the LTD Keeper server.') sys.exit(1) logger.debug( 'About to get token for user %s at %s', ctx.obj['username'], ctx.obj['keeper_hostname']) token = get_keeper_token( ctx.obj['keeper_hostname'], ctx.obj['username'], ctx.obj['password']) ctx.obj['token'] = token logger.debug( 'Got token for user %s at %s', ctx.obj['username'], ctx.obj['keeper_hostname']) else: logger.debug( 'Token already exists.')
def loud(self, lang='englist'): """Speak loudly! FIVE! Use upper case!""" lang_method = getattr(self, lang, None) if lang_method: return lang_method().upper() else: return self.english().upper()
def rotate(self, word): """Replaced by a letter 5 right shift. e.g. a->f, b->g, . -> .""" before = string.printable[:62] after = ''.join([i[5:] + i[:5] for i in [string.digits, string.ascii_lowercase, string.ascii_uppercase]]) table = dict(zip(before, after)) processed_word = [table[i] if i in before else i for i in word] return ''.join(processed_word)
def delete_dir(bucket_name, root_path, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None): """Delete all objects in the S3 bucket named ``bucket_name`` that are found in the ``root_path`` directory. Parameters ---------- bucket_name : `str` Name of an S3 bucket. root_path : `str` Directory in the S3 bucket that will be deleted. aws_access_key_id : `str` The access key for your AWS account. Also set ``aws_secret_access_key``. aws_secret_access_key : `str` The secret key for your AWS account. aws_profile : `str`, optional Name of AWS profile in :file:`~/.aws/credentials`. Use this instead of ``aws_access_key_id`` and ``aws_secret_access_key`` for file-based credentials. Raises ------ ltdconveyor.s3.S3Error Thrown by any unexpected faults from the S3 API. """ logger = logging.getLogger(__name__) session = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) s3 = session.resource('s3') client = s3.meta.client # Normalize directory path for searching patch prefixes of objects if not root_path.endswith('/'): root_path.rstrip('/') paginator = client.get_paginator('list_objects_v2') pages = paginator.paginate(Bucket=bucket_name, Prefix=root_path) keys = dict(Objects=[]) for item in pages.search('Contents'): try: keys['Objects'].append({'Key': item['Key']}) except TypeError: # item is None; nothing to delete continue # Delete immediately when 1000 objects are listed # the delete_objects method can only take a maximum of 1000 keys if len(keys['Objects']) >= 1000: try: client.delete_objects(Bucket=bucket_name, Delete=keys) except Exception: message = 'Error deleting objects from %r' % root_path logger.exception(message) raise S3Error(message) keys = dict(Objects=[]) # Delete remaining keys if len(keys['Objects']) > 0: try: client.delete_objects(Bucket=bucket_name, Delete=keys) except Exception: message = 'Error deleting objects from %r' % root_path logger.exception(message) raise S3Error(message)
def home_url(): """Get project's home URL based on settings.PROJECT_HOME_NAMESPACE. Returns None if PROJECT_HOME_NAMESPACE is not defined in settings. """ try: return reverse(home_namespace) except Exception: url = home_namespace try: validate_url = URLValidator() if '://' not in url: url = 'http://' + url validate_url(url) return(url) except ValidationError: return None
def silence_without_namespace(f): """Decorator to silence template tags if 'PROJECT_HOME_NAMESPACE' is not defined in settings. Usage Example: from django import template register = template.Library() @register.simple_tag @silence_without_namespace def a_template_tag(*args): ... """ @wraps(f) def wrapped(label=None): if not home_namespace: return '' if label: return f(label) else: return f(home_label) return wrapped
def project_home_breadcrumb_bs3(label): """A template tag to return the project's home URL and label formatted as a Bootstrap 3 breadcrumb. PROJECT_HOME_NAMESPACE must be defined in settings, for example: PROJECT_HOME_NAMESPACE = 'project_name:index_view' Usage Example: {% load project_home_tags %} <ol class="breadcrumb"> {% project_home_breadcrumb_bs3 %} {# <--- #} <li><a href="{% url 'app:namespace' %}">List of Objects</a></li> <li class="active">Object Detail</li> </ol> This gets converted into: <ol class="breadcrumb"> <li><a href="{% url 'project_name:index_view' %}">Home</a></li> {# <--- #} <li><a href="{% url 'app:namespace' %}">List of Objects</a></li> <li class="active">Object Detail</li> </ol> By default, the link's text is 'Home'. A project-wide label can be defined with PROJECT_HOME_LABEL in settings. Both the default and the project-wide label can be overridden by passing a string to the template tag. For example: {% project_home_breadcrumb_bs3 'Custom Label' %} """ url = home_url() if url: return format_html( '<li><a href="{}">{}</a></li>', url, label) else: return format_html('<li>{}</li>', label)
def project_home_breadcrumb_bs4(label): """A template tag to return the project's home URL and label formatted as a Bootstrap 4 breadcrumb. PROJECT_HOME_NAMESPACE must be defined in settings, for example: PROJECT_HOME_NAMESPACE = 'project_name:index_view' Usage Example: {% load project_home_tags %} <ol class="breadcrumb"> {% project_home_breadcrumb_bs4 %} {# <--- #} <li class="breadcrumb-item" aria-label="breadcrumb"><a href="{% url 'app:namespace' %}">List of Objects</a></li> <li class=" breadcrumb-item active" aria-label="breadcrumb" aria-current="page">Object Detail</li> </ol> This gets converted into: <ol class="breadcrumb"> <li class="breadcrumb-item" aria-label="breadcrumb"><a href="{% url 'project_name:index_view' %}">Home</a></li> {# <--- #} <li class="breadcrumb-item" aria-label="breadcrumb"><a href="{% url 'app:namespace' %}">List of Objects</a></li> <li class=" breadcrumb-item active" aria-label="breadcrumb" aria-current="page">Object Detail</li> </ol> By default, the link's text is 'Home'. A project-wide label can be defined with PROJECT_HOME_LABEL in settings. Both the default and the project-wide label can be overridden by passing a string to the template tag. For example: {% project_home_breadcrumb_bs4 'Custom Label' %} """ url = home_url() if url: return format_html( '<li class="breadcrumb-item" aria-label="breadcrumb"><a href="{}">{}</a></li>', url, label) else: return format_html( '<li class="breadcrumb-item" aria-label="breadcrumb">{}</li>', label)
def pm(client, event, channel, nick, rest): 'Arggh matey' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel if random.random() > 0.95: return f"Arrggh ye be doin' great, grand work, {rcpt}!" return f"Arrggh ye be doin' good work, {rcpt}!"
def lm(client, event, channel, nick, rest): 'Rico Suave' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel return f'¡Estás haciendo un buen trabajo, {rcpt}!'
def fm(client, event, channel, nick, rest): 'pmxbot parle français' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel return f'Vous bossez bien, {rcpt}!'
def zorsupas(client, event, channel, nick, rest): 'Zor supas! — !زۆر سوپاس' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return ( f'Zor supas {rcpt}, to zor zor barezi! —' ' زۆر سوپاس، تۆ زۆر زۆر به‌ره‌زی' )
def danke(client, event, channel, nick, rest): 'Danke schön!' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return f'Danke schön, {rcpt}! Danke schön!'
def schneier(client, event, channel, nick, rest): 'schneier "facts"' rcpt = rest.strip() or channel if rest.strip(): Karma.store.change(rcpt, 2) url = 'https://www.schneierfacts.com/' d = requests.get(url).text start_tag = re.escape('<p class="fact">') end_tag = re.escape('</p>') p = re.compile( start_tag + '(.*?)' + end_tag, flags=re.DOTALL | re.MULTILINE) match = p.search(d) if not match: return "Sorry, no facts found (check your crypto anyway)." phrase = match.group(1).replace('\n', ' ').strip() if rcpt != channel: phrase = re.sub('(Bruce ?)?Schneier', rcpt, phrase, flags=re.I) phrase = re.sub('Bruce', rcpt, phrase, flags=re.I) # unescape HTML h = html.parser.HTMLParser() phrase = h.unescape(phrase) # Correct improperly-encoded strings phrase = ftfy.fix_encoding(phrase) return phrase
def get_interaction_energy(ampal_objs, ff=None, assign_ff=True): """Calculates the interaction energy between AMPAL objects. Parameters ---------- ampal_objs: [AMPAL Object] A list of any AMPAL objects with `get_atoms` methods. ff: BuffForceField, optional The force field to be used for scoring. If no force field is provided then the most current version of the BUDE force field will be used. assign_ff: bool, optional If true, then force field assignment on the AMPAL object will be will be updated. Returns ------- BUFF_score: BUFFScore A BUFFScore object with information about each of the interactions and the atoms involved. """ if ff is None: ff = FORCE_FIELDS['bude_2016v1'] if assign_ff: for ampal_obj in ampal_objs: assign_force_field(ampal_obj, ff) interactions = find_inter_ampal(ampal_objs, ff.distance_cutoff) buff_score = score_interactions(interactions, ff) return buff_score
def get_internal_energy(ampal_obj, ff=None, assign_ff=True): """Calculates the internal energy of the AMPAL object. Parameters ---------- ampal_obj: AMPAL Object Any AMPAL object with a `get_atoms` method. ff: BuffForceField, optional The force field to be used for scoring. If no force field is provided then the most current version of the BUDE force field will be used. assign_ff: bool, optional If true, then force field assignment on the AMPAL object will be will be updated. Returns ------- BUFF_score: BUFFScore A BUFFScore object with information about each of the interactions and the atoms involved. """ if ff is None: ff = FORCE_FIELDS['bude_2016v1'] if assign_ff: assign_force_field(ampal_obj, ff) interactions = find_intra_ampal(ampal_obj, ff.distance_cutoff) buff_score = score_interactions(interactions, ff) return buff_score
def rooted_samples_by_file(self): ''' Get sample counts by file, and root thread function. (Useful for answering quesitons like "what modules are hot?") ''' rooted_leaf_samples, _ = self.live_data_copy() rooted_file_samples = {} for root, counts in rooted_leaf_samples.items(): cur = {} for key, count in counts.items(): code, lineno = key cur.setdefault(code.co_filename, 0) cur[code.co_filename] += count rooted_file_samples[root] = cur return rooted_file_samples
def rooted_samples_by_line(self, filename): ''' Get sample counts by line, and root thread function. (For one file, specified as a parameter.) This is useful for generating "side-by-side" views of source code and samples. ''' rooted_leaf_samples, _ = self.live_data_copy() rooted_line_samples = {} for root, counts in rooted_leaf_samples.items(): cur = {} for key, count in counts.items(): code, lineno = key if code.co_filename != filename: continue cur[lineno] = count rooted_line_samples[root] = cur return rooted_line_samples
def hotspots(self): ''' Get lines sampled accross all threads, in order from most to least sampled. ''' rooted_leaf_samples, _ = self.live_data_copy() line_samples = {} for _, counts in rooted_leaf_samples.items(): for key, count in counts.items(): line_samples.setdefault(key, 0) line_samples[key] += count return sorted( line_samples.items(), key=lambda v: v[1], reverse=True)
def flame_map(self): ''' return sampled stacks in form suitable for inclusion in a flame graph (https://github.com/brendangregg/FlameGraph) ''' flame_map = {} _, stack_counts = self.live_data_copy() for stack, count in stack_counts.items(): root = stack[-2].co_name stack_elements = [] for i in range(len(stack)): if type(stack[i]) in (int, long): continue code = stack[i] stack_elements.append("{0}`{1}`{2}".format( root, code.co_filename, code.co_name)) flame_key = ';'.join(stack_elements) flame_map.setdefault(flame_key, 0) flame_map[flame_key] += count return flame_map
def get_keeper_token(host, username, password): """Get a temporary auth token from LTD Keeper. Parameters ---------- host : `str` Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``). username : `str` Username. password : `str` Password. Returns ------- token : `str` LTD Keeper API token. Raises ------ KeeperError Raised if the LTD Keeper API cannot return a token. """ token_endpoint = urljoin(host, '/token') r = requests.get(token_endpoint, auth=(username, password)) if r.status_code != 200: raise KeeperError('Could not authenticate to {0}: error {1:d}\n{2}'. format(host, r.status_code, r.json())) return r.json()['token']
def upload(ctx, product, git_ref, dirname, aws_id, aws_secret, ci_env, on_travis_push, on_travis_pr, on_travis_api, on_travis_cron, skip_upload): """Upload a new site build to LSST the Docs. """ logger = logging.getLogger(__name__) if skip_upload: click.echo('Skipping ltd upload.') sys.exit(0) logger.debug('CI environment: %s', ci_env) logger.debug('Travis events settings. ' 'On Push: %r, PR: %r, API: %r, Cron: %r', on_travis_push, on_travis_pr, on_travis_api, on_travis_cron) # Abort upload on Travis CI under certain events if ci_env == 'travis' and \ _should_skip_travis_event( on_travis_push, on_travis_pr, on_travis_api, on_travis_cron): sys.exit(0) # Authenticate to LTD Keeper host ensure_login(ctx) # Detect git refs git_refs = _get_git_refs(ci_env, git_ref) build_resource = register_build( ctx.obj['keeper_hostname'], ctx.obj['token'], product, git_refs ) logger.debug('Created build resource %r', build_resource) # Do the upload. # This cache_control is appropriate for builds since they're immutable. # The LTD Keeper server changes the cache settings when copying the build # over to be a mutable edition. upload_dir( build_resource['bucket_name'], build_resource['bucket_root_dir'], dirname, aws_access_key_id=aws_id, aws_secret_access_key=aws_secret, surrogate_key=build_resource['surrogate_key'], cache_control='max-age=31536000', surrogate_control=None, upload_dir_redirect_objects=True) logger.debug('Upload complete for %r', build_resource['self_url']) # Confirm upload confirm_build( build_resource['self_url'], ctx.obj['token'] ) logger.debug('Build %r complete', build_resource['self_url'])
def _should_skip_travis_event(on_travis_push, on_travis_pr, on_travis_api, on_travis_cron): """Detect if the upload should be skipped based on the ``TRAVIS_EVENT_TYPE`` environment variable. Returns ------- should_skip : `bool` True if the upload should be skipped based on the combination of ``TRAVIS_EVENT_TYPE`` and user settings. """ travis_event = os.getenv('TRAVIS_EVENT_TYPE') if travis_event is None: raise click.UsageError( 'Using --travis but the TRAVIS_EVENT_TYPE ' 'environment variable is not detected.') if travis_event == 'push' and on_travis_push is False: click.echo('Skipping upload on Travis push event.') return True elif travis_event == 'pull_request' and on_travis_pr is False: click.echo('Skipping upload on Travis pull request event.') return True elif travis_event == 'api' and on_travis_api is False: click.echo('Skipping upload on Travis pull request event.') return True elif travis_event == 'cron' and on_travis_cron is False: click.echo('Skipping upload on Travis cron event.') return True else: return False
def purge_key(surrogate_key, service_id, api_key): """Instant purge URLs with a given surrogate key from the Fastly caches. Parameters ---------- surrogate_key : `str` Surrogate key header (``x-amz-meta-surrogate-key``) value of objects to purge from the Fastly cache. service_id : `str` Fastly service ID. api_key : `str` Fastly API key. Raises ------ FastlyError Error with the Fastly API usage. Notes ----- This function uses Fastly's ``/service/{service}/purge/{key}`` endpoint. See the `Fastly Purge documentation <http://ls.st/jxg>`_ for more information. For other Fastly APIs, consider using `fastly-py <https://github.com/fastly/fastly-py>`_. """ logger = logging.getLogger(__name__) api_root = 'https://api.fastly.com' path = '/service/{service}/purge/{surrogate_key}'.format( service=service_id, surrogate_key=surrogate_key) logger.info('Fastly purge {0}'.format(path)) r = requests.post(api_root + path, headers={'Fastly-Key': api_key, 'Accept': 'application/json'}) if r.status_code != 200: raise FastlyError(r.json)
def register_build(host, keeper_token, product, git_refs): """Register a new build for a product on LSST the Docs. Wraps ``POST /products/{product}/builds/``. Parameters ---------- host : `str` Hostname of LTD Keeper API server. keeper_token : `str` Auth token (`ltdconveyor.keeper.get_keeper_token`). product : `str` Name of the product in the LTD Keeper service. git_refs : `list` of `str` List of Git refs that correspond to the version of the build. Git refs can be tags or branches. Returns ------- build_info : `dict` LTD Keeper build resource. Raises ------ ltdconveyor.keeper.KeeperError Raised if there is an error communicating with the LTD Keeper API. """ data = { 'git_refs': git_refs } endpoint_url = uritemplate.expand( urljoin(host, '/products/{p}/builds/'), p=product) r = requests.post( endpoint_url, auth=(keeper_token, ''), json=data) if r.status_code != 201: raise KeeperError(r.json()) build_info = r.json() return build_info
def confirm_build(build_url, keeper_token): """Confirm a build upload is complete. Wraps ``PATCH /builds/{build}``. Parameters ---------- build_url : `str` URL of the build resource. Given a build resource, this URL is available from the ``self_url`` field. keeper_token : `str` Auth token (`ltdconveyor.keeper.get_keeper_token`). Raises ------ ltdconveyor.keeper.KeeperError Raised if there is an error communicating with the LTD Keeper API. """ data = { 'uploaded': True } r = requests.patch( build_url, auth=(keeper_token, ''), json=data) if r.status_code != 200: raise KeeperError(r)
def deep_update(d, u): """Deeply updates a dictionary. List values are concatenated. Args: d (dict): First dictionary which will be updated u (dict): Second dictionary use to extend the first one Returns: dict: The merge dictionary """ for k, v in u.items(): if isinstance(v, Mapping): d[k] = deep_update(d.get(k, {}), v) elif isinstance(v, list): existing_elements = d.get(k, []) d[k] = existing_elements + [ele for ele in v if ele not in existing_elements] else: d[k] = v return d
def main(ctx, log_level, keeper_hostname, username, password): """ltd is a command-line client for LSST the Docs. Use ltd to upload new site builds, and to work with the LTD Keeper API. """ ch = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(levelname)8s %(name)s | %(message)s') ch.setFormatter(formatter) logger = logging.getLogger('ltdconveyor') logger.addHandler(ch) logger.setLevel(log_level.upper()) # Subcommands should use the click.pass_obj decorator to get this # ctx.obj object as the first argument. ctx.obj = { 'keeper_hostname': keeper_hostname, 'username': username, 'password': password, 'token': None }
def part_edit_cmd(): 'Edit a part from an OOXML Package without unzipping it' parser = argparse.ArgumentParser(description=inspect.getdoc(part_edit_cmd)) parser.add_argument( 'path', help='Path to part (including path to zip file, i.e. ./file.zipx/part)', ) parser.add_argument( '--reformat-xml', action='store_true', help=( 'run the content through an XML pretty-printer ' 'first for improved editability' ), ) args = parser.parse_args() part_edit(args.path, args.reformat_xml)
def pack_dir_cmd(): 'List the contents of a subdirectory of a zipfile' parser = argparse.ArgumentParser(description=inspect.getdoc(part_edit_cmd)) parser.add_argument( 'path', help=( 'Path to list (including path to zip file, ' 'i.e. ./file.zipx or ./file.zipx/subdir)' ), ) args = parser.parse_args() for item, is_file in sorted(list_contents(args.path)): prefix = 'd ' if not is_file else ' ' msg = prefix + item print(msg)
def split_all(path): """ recursively call os.path.split until we have all of the components of a pathname suitable for passing back to os.path.join. """ drive, path = os.path.splitdrive(path) head, tail = os.path.split(path) terminators = [os.path.sep, os.path.altsep, ''] parts = split_all(head) if head not in terminators else [head] return [drive] + parts + [tail]
def find_file(path): """ Given a path to a part in a zip file, return a path to the file and the path to the part. Assuming /foo.zipx exists as a file, >>> find_file('/foo.zipx/dir/part') # doctest: +SKIP ('/foo.zipx', '/dir/part') >>> find_file('/foo.zipx') # doctest: +SKIP ('/foo.zipx', '') """ path_components = split_all(path) def get_assemblies(): """ Enumerate the various combinations of file paths and part paths """ for n in range(len(path_components), 0, -1): file_c = path_components[:n] part_c = path_components[n:] or [''] yield (os.path.join(*file_c), posixpath.join(*part_c)) for file_path, part_path in get_assemblies(): if os.path.isfile(file_path): return file_path, part_path
def get_editor(filepath): """ Give preference to an XML_EDITOR or EDITOR defined in the environment. Otherwise use notepad on Windows and edit on other platforms. """ default_editor = ['edit', 'notepad'][sys.platform.startswith('win32')] return os.environ.get( 'XML_EDITOR', os.environ.get('EDITOR', default_editor), )
def permission_check(apikey, endpoint): """ return (user, seckey) if url end point is in allowed entry point list """ try: ak = APIKeys.objects.get(apikey=apikey) apitree = cPickle.loads(ak.apitree.encode("ascii")) if apitree.match(endpoint): return ak.user if ak.user else AnonymousUser(), ak.seckey except APIKeys.DoesNotExist: pass return None, None
def process_module(self, node): """Process the astroid node stream.""" if self.config.file_header: if sys.version_info[0] < 3: pattern = re.compile( '\A' + self.config.file_header, re.LOCALE | re.MULTILINE) else: # The use of re.LOCALE is discouraged in python 3 pattern = re.compile( '\A' + self.config.file_header, re.MULTILINE) content = None with node.stream() as stream: # Explicit decoding required by python 3 content = stream.read().decode('utf-8') matches = pattern.findall(content) if len(matches) != 1: self.add_message('invalid-file-header', 1, args=self.config.file_header)
def gen(self, slug, name, dataobj, xfield, yfield, time_unit=None, chart_type="line", width=800, height=300, color=Color(), size=Size(), scale=Scale(zero=False), shape=Shape(), filepath=None, html_before="", html_after=""): """ Generates an html chart from either a pandas dataframe, a dictionnary, a list or an Altair Data object and optionally write it to a file """ chart_obj = self.serialize(dataobj, xfield, yfield, time_unit, chart_type, width, height, color, size, scale, shape) html = self.html(slug, name, chart_obj, filepath, html_before, html_after) return html
def html(self, slug, name, chart_obj, filepath=None, html_before="", html_after=""): """ Generate html from an Altair chart object and optionally write it to a file """ try: html = "" if name: html = "<h3>" + name + "</h3>" json_data = chart_obj.to_json() json_data = self._patch_json(json_data) html = html_before + html +\ self._json_to_html(slug, json_data) + html_after except Exception as e: tr.new(e) tr.check() # generate file if filepath is not None: self._write_file(slug, filepath, html) return None else: return html
def serialize(self, dataobj, xfield, yfield, time_unit=None, chart_type="line", width=800, height=300, color=None, size=None, scale=Scale(zero=False), shape=None, options={}): """ Serialize to an Altair chart object from either a pandas dataframe, a dictionnary, a list or an Altair Data object """ dataset = dataobj if self._is_dict(dataobj) is True: dataset = self._dict_to_df(dataobj, xfield, yfield) elif isinstance(dataobj, list): dataset = Data(values=dataobj) xencode, yencode = self._encode_fields( xfield, yfield, time_unit) opts = dict(x=xencode, y=yencode) if color is not None: opts["color"] = color if size is not None: opts["size"] = size if shape is not None: opts["shape"] = shape chart = self._chart_class(dataset, chart_type, **options).encode( **opts ).configure_cell( width=width, height=height, ) return chart
def _patch_json(self, json_data): """ Patch the Altair generated json to the newest Vega Lite spec """ json_data = json.loads(json_data) # add schema json_data["$schema"] = "https://vega.github.io/schema/vega-lite/2.0.0-beta.15.json" # add top level width and height json_data["width"] = json_data["config"]["cell"]["width"] json_data["height"] = json_data["config"]["cell"]["height"] del(json_data["config"]["cell"]) return json.dumps(json_data)
def _json_to_html(self, slug, json_data): """ Generates html from Vega lite data """ html = '<div id="chart-' + slug + '"></div>' html += '<script>' html += 'var s' + slug + ' = ' + json_data + ';' html += 'vega.embed("#chart-' + slug + '", s' + slug + ');' #html += 'console.log(JSON.stringify(s{id}, null, 2));' html += '</script>' return html
def _dict_to_df(self, dictobj, xfield, yfield): """ Converts a dictionnary to a pandas dataframe """ x = [] y = [] for datapoint in dictobj: x.append(datapoint) y.append(dictobj[datapoint]) df = pd.DataFrame({xfield[0]: x, yfield[0]: y}) return df
def _write_file(self, slug, folderpath, html): """ Writes a chart's html to a file """ # check directories if not os.path.isdir(folderpath): try: os.makedirs(folderpath) except Exception as e: tr.err(e) # construct file path filepath = folderpath + "/" + slug + ".html" #~ write the file try: filex = open(filepath, "w") filex.write(html) filex.close() except Exception as e: tr.err(e)
def _chart_class(self, df, chart_type, **kwargs): """ Get the right chart class from a string """ if chart_type == "bar": return Chart(df).mark_bar(**kwargs) elif chart_type == "circle": return Chart(df).mark_circle(**kwargs) elif chart_type == "line": return Chart(df).mark_line(**kwargs) elif chart_type == "point": return Chart(df).mark_point(**kwargs) elif chart_type == "area": return Chart(df).mark_area(**kwargs) elif chart_type == "tick": return Chart(df).mark_tick(**kwargs) elif chart_type == "text": return Chart(df).mark_text(**kwargs) elif chart_type == "square": return Chart(df).mark_square(**kwargs) elif chart_type == "rule": return Chart(df).mark_rule(**kwargs) return None
def _encode_fields(self, xfield, yfield, time_unit=None, scale=Scale(zero=False)): """ Encode the fields in Altair format """ if scale is None: scale = Scale() xfieldtype = xfield[1] yfieldtype = yfield[1] x_options = None if len(xfield) > 2: x_options = xfield[2] y_options = None if len(yfield) > 2: y_options = yfield[2] if time_unit is not None: if x_options is None: xencode = X(xfieldtype, timeUnit=time_unit) else: xencode = X( xfieldtype, axis=Axis(**x_options), timeUnit=time_unit, scale=scale ) else: if x_options is None: xencode = X(xfieldtype) else: xencode = X( xfieldtype, axis=Axis(**x_options), scale=scale ) if y_options is None: yencode = Y(yfieldtype, scale=scale) else: yencode = Y( yfieldtype, axis=Axis(**y_options), scale=scale ) return xencode, yencode
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ # app = inliner.document.settings.env.app #app.info('user link %r' % text) ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], []
def _infer_tarball_url(): """Returns the tarball URL inferred from an app.json, if present.""" try: with click.open_file('app.json', 'r') as f: contents = f.read() app_json = json.loads(contents) except IOError: return None repository = app_json.get('repository') if not repository: return None else: return app_json.get('repository') + '/tarball/master/'
def up(tarball_url, auth_token, env, app_name): """Brings up a Heroku app.""" tarball_url = tarball_url or _infer_tarball_url() if not tarball_url: click.echo('No tarball URL found.') sys.exit(1) if env: # Split ["KEY=value", ...] into {"KEY": "value", ...} env = { arg.split('=')[0]: arg.split('=')[1] for arg in env } happy = Happy(auth_token=auth_token) click.echo('Creating app... ', nl=False) build_id, app_name = happy.create( tarball_url=tarball_url, env=env, app_name=app_name, ) click.echo(app_name) click.echo('Building... ', nl=False) happy.wait(build_id) _write_app_name(app_name) click.echo('done') click.echo("It's up! :) https://%s.herokuapp.com" % app_name)
def down(auth_token, force, app_name): """Brings down a Heroku app.""" if not app_name: click.echo( 'WARNING: Inferring the app name when deleting is deprecated. ' 'Starting with happy 2.0, the app_name parameter will be required.' ) app_name = app_name or _read_app_name() if not app_name: click.echo('No app name given.') sys.exit(1) if not force: click.confirm( 'Are you sure you want to delete %s?' % app_name, abort=True, ) happy = Happy(auth_token=auth_token) click.echo('Destroying app %s... ' % app_name, nl=False) happy.delete(app_name=app_name) _delete_app_name_file() click.echo('done') click.echo("It's down. :(")
def iter_attribute(iterable_name) -> Union[Iterable, Callable]: """Decorator implementing Iterator interface with nicer manner. Example ------- @iter_attribute('my_attr'): class DecoratedClass: ... Warning: ======== When using PyCharm or MYPY you'll probably see issues with decorated class not being recognized as Iterator. That's an issue which I could not overcome yet, it's probably due to the fact that interpretation of object is being done statically rather than dynamically. MYPY checks for definition of methods in class code which changes at runtime. Since __iter__ and __next__ are added dynamically MYPY cannot find those defined in objects before object of a class is created. Possible workarounds for this issue are: 1. Define ``dummy`` __iter__ class like: @iter_attribute('attr') class Test: def __init__(self) -> None: self.attr = [1, 2, 3] def __iter__(self): pass 2. After creating object use cast or assert function denoting that particular instance inherits from collections.Iterator: assert isinstance(my_object, collections.Iterator) :param iterable_name: string representing attribute name which has to be iterated :return: DecoratedClass with implemented '__iter__' and '__next__' methods. """ def create_new_class(decorated_class) -> Union[Iterable, Callable]: """Class extender implementing __next__ and __iter__ methods. :param decorated_class: class to be extended with iterator interface :return: new class """ assert inspect.isclass(decorated_class), 'You can only decorate class objects!' assert isinstance(iterable_name, str), 'Please provide attribute name string' decorated_class.iterator_attr_index = 0 def __iter__(instance) -> Iterable: """Implement __iter__ method :param instance: __iter__ uses instance of class which is being extended :return: instance of decorated_class """ return instance def __next__(instance) -> Any: """Implement __next__ method :param instance: __next__ uses instance of class which is being extended :return: instance of decorated_class """ assert hasattr(instance, iterable_name), \ 'Decorated object does not have attribute named {}'.format(iterable_name) assert isinstance(getattr(instance, iterable_name), collections.Iterable), \ '{} of object {} is not iterable'.format(iterable_name, instance.__class__.__name__) ind = instance.iterator_attr_index while ind < len(getattr(instance, iterable_name)): val = getattr(instance, iterable_name)[ind] instance.iterator_attr_index += 1 return val instance.iterator_attr_index = 0 raise StopIteration dct = dict(decorated_class.__dict__) dct['__iter__'] = __iter__ dct['__next__'] = __next__ dct['iterator_attr_index'] = decorated_class.iterator_attr_index return type(decorated_class.__name__, (collections.Iterable,), dct) return create_new_class
def api_auth(function=None): """ check: 1, timestamp in reasonable range 2, api key exists 3, entry point allowed for this api key 4, signature correctness effect: - add user object in request if the api key is binding with an user """ def real_decorator(func): def wrapped(request, *args, **kwargs): try: user = _auth_url(request.get_full_path(), request.body) request.user = user # put user object in request except Exception as e: return JsonResponse({"error": str(e)}, status=403) return func(request, *args, **kwargs) setattr(wrapped, '__djapiauth__', True) return wrapped return real_decorator if not function else real_decorator(function)
def text(length, choices=string.ascii_letters): """ returns a random (fixed length) string :param length: string length :param choices: string containing all the chars can be used to build the string .. seealso:: :py:func:`rtext` """ return ''.join(choice(choices) for x in range(length))
def rtext(maxlength, minlength=1, choices=string.ascii_letters): """ returns a random (variable length) string. :param maxlength: maximum string length :param minlength: minimum string length :param choices: string containing all the chars can be used to build the string .. seealso:: :py:func:`text` """ return ''.join(choice(choices) for x in range(randint(minlength, maxlength)))
def binary(length): """ returns a a random string that represent a binary representation :param length: number of bits """ num = randint(1, 999999) mask = '0' * length return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]
def ipaddress(not_valid=None): """ returns a string representing a random ip address :param not_valid: if passed must be a list of integers representing valid class A netoworks that must be ignored """ not_valid_class_A = not_valid or [] class_a = [r for r in range(1, 256) if r not in not_valid_class_A] shuffle(class_a) first = class_a.pop() return ".".join([str(first), str(randrange(1, 256)), str(randrange(1, 256)), str(randrange(1, 256))])
def ip(private=True, public=True, max_attempts=10000): """ returns a :class:`netaddr.IPAddress` instance with a random value :param private: if False does not return private networks :param public: if False does not return public networks :param max_attempts: """ if not (private or public): raise ValueError('Cannot disable both `private` and `public` network') if private != public: if private: is_valid = lambda address: address.is_private() not_valid = [n for n in range(1, 255) if n not in NOT_NET] else: is_valid = lambda address: not address.is_private() not_valid = NOT_NET attempt = 0 while attempt < max_attempts: attempt += 1 ip = IPAddress(ipaddress(not_valid)) if is_valid(ip): return ip else: return IPAddress(ipaddress())
def date(start, end): """Get a random date between two dates""" stime = date_to_timestamp(start) etime = date_to_timestamp(end) ptime = stime + random.random() * (etime - stime) return datetime.date.fromtimestamp(ptime)
def _get_session(self): """Returns a prepared ``Session`` instance.""" session = Session() session.headers = { 'Content-type': 'application/json', 'Accept': 'application/vnd.heroku+json; version=3', } if self._auth_token: session.trust_env = False # Effectively disable netrc auth session.headers['Authorization'] = 'Bearer %s' % self._auth_token return session
def api_request(self, method, endpoint, data=None, *args, **kwargs): """Sends an API request to Heroku. :param method: HTTP method. :param endpoint: API endpoint, e.g. ``/apps``. :param data: A dict sent as JSON in the body of the request. :returns: A dict represntation of the JSON response. """ session = self._get_session() api_root = 'https://api.heroku.com' url = api_root + endpoint if data: data = json.dumps(data) response = session.request(method, url, data=data, *args, **kwargs) if not response.ok: try: message = response.json().get('message') except ValueError: message = response.content raise APIError(message) return response.json()
def create_build(self, tarball_url, env=None, app_name=None): """Creates an app-setups build. Returns response data as a dict. :param tarball_url: URL of a tarball containing an ``app.json``. :param env: Dict containing environment variable overrides. :param app_name: Name of the Heroku app to create. :returns: Response data as a ``dict``. """ data = { 'source_blob': { 'url': tarball_url } } if env: data['overrides'] = {'env': env} if app_name: data['app'] = {'name': app_name} return self.api_request('POST', '/app-setups', data=data)
def check_build_status(self, build_id): """Checks the status of an app-setups build. :param build_id: ID of the build to check. :returns: ``True`` if succeeded, ``False`` if pending. """ data = self.api_request('GET', '/app-setups/%s' % build_id) status = data.get('status') if status == 'pending': return False elif status == 'succeeded': return True else: raise BuildError(str(data))
def sequence(prefix, cache=None): """ generator that returns an unique string :param prefix: prefix of string :param cache: cache used to store the last used number >>> next(sequence('abc')) 'abc-0' >>> next(sequence('abc')) 'abc-1' """ if cache is None: cache = _sequence_counters if cache == -1: cache = {} if prefix not in cache: cache[prefix] = infinite() while cache[prefix]: yield "{0}-{1}".format(prefix, next(cache[prefix]))
def _get_memoized_value(func, args, kwargs): """Used internally by memoize decorator to get/store function results""" key = (repr(args), repr(kwargs)) if not key in func._cache_dict: ret = func(*args, **kwargs) func._cache_dict[key] = ret return func._cache_dict[key]
def memoize(func): """Decorator that stores function results in a dictionary to be used on the next time that the same arguments were informed.""" func._cache_dict = {} @wraps(func) def _inner(*args, **kwargs): return _get_memoized_value(func, args, kwargs) return _inner
def unique(func, num_args=0, max_attempts=100, cache=None): """ wraps a function so that produce unique results :param func: :param num_args: >>> import random >>> choices = [1,2] >>> a = unique(random.choice, 1) >>> a,b = a(choices), a(choices) >>> a == b False """ if cache is None: cache = _cache_unique @wraps(func) def wrapper(*args): key = "%s_%s" % (str(func.__name__), str(args[:num_args])) attempt = 0 while attempt < max_attempts: attempt += 1 drawn = cache.get(key, []) result = func(*args) if result not in drawn: drawn.append(result) cache[key] = drawn return result raise MaxAttemptException() return wrapper
def register_sub_commands(self, parser): """ Add any sub commands to the argument parser. :param parser: The argument parser object """ sub_commands = self.get_sub_commands() if sub_commands: sub_parsers = parser.add_subparsers(dest=self.sub_parser_dest_name) for name, cls in sub_commands.items(): cmd = cls(name) sub_parser = sub_parsers.add_parser(name, help=name, description=cmd.get_help(), formatter_class=cmd.get_formatter_class()) cmd.add_args(sub_parser) cmd.register_sub_commands(sub_parser)
def get_root_argparser(self): """ Gets the root argument parser object. """ return self.arg_parse_class(description=self.get_help(), formatter_class=self.get_formatter_class())
def get_description(self): """ Gets the description of the command. If its not supplied the first sentence of the doc string is used. """ if self.description: return self.description elif self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().split('.')[0] + '.' else: return ''
def get_help(self): """ Gets the help text for the command. If its not supplied the doc string is used. """ if self.help: return self.help elif self.__doc__ and self.__doc__.strip(): return self.__doc__.strip() else: return ''
def run(self, args=None): """ Runs the command passing in the parsed arguments. :param args: The arguments to run the command with. If ``None`` the arguments are gathered from the argument parser. This is automatically set when calling sub commands and in most cases should not be set for the root command. :return: The status code of the action (0 on success) """ args = args or self.parse_args() sub_command_name = getattr(args, self.sub_parser_dest_name, None) if sub_command_name: sub_commands = self.get_sub_commands() cmd_cls = sub_commands[sub_command_name] return cmd_cls(sub_command_name).run(args) return self.action(args) or 0
def get_api_key_form(userfilter={}): """ userfileter: when binding api key with user, filter some users if necessary """ class APIKeyForm(ModelForm): class Meta: model = APIKeys exclude = ("apitree",) user = forms.ModelChoiceField(queryset=get_user_model().objects.filter(**userfilter), required=True,) return APIKeyForm
def encode(self, *args, **kwargs): """Encode wrapper for a dataset with maximum value Datasets can be one or two dimensional Strings are ignored as ordinal encoding""" if isinstance(args[0], str): return self.encode([args[0]],**kwargs) elif isinstance(args[0], int) or isinstance(args[0], float): return self.encode([[args[0]]],**kwargs) if len(args)>1: dataset = args else: dataset = args[0] typemap = list(map(type,dataset)) code = self.encoding[0] if type('') in typemap: data = ','.join(map(str,dataset)) elif type([]) in typemap or type(()) in typemap: data = self.codeset['char'].join(map(self.encodedata, dataset)) elif len(dataset) == 1 and hasattr(dataset[0], '__iter__'): data = self.encodedata(dataset[0]) else: try: data = self.encodedata(dataset) except ValueError: data = self.encodedata(','.join(map(unicode,dataset))) if not '.' in data and code == 't': code = 'e' return '%s%s:%s'%(code,self.series,data)
def get_athletes(self): """Get all available athletes This method is cached to prevent unnecessary calls to GC. """ response = self._get_request(self.host) response_buffer = StringIO(response.text) return pd.read_csv(response_buffer)
def get_last_activities(self, n): """Get all activity data for the last activity Keyword arguments: """ filenames = self.get_activity_list().iloc[-n:].filename.tolist() last_activities = [self.get_activity(f) for f in filenames] return last_activities
def _request_activity_list(self, athlete): """Actually do the request for activity list This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete """ response = self._get_request(self._athlete_endpoint(athlete)) response_buffer = StringIO(response.text) activity_list = pd.read_csv( filepath_or_buffer=response_buffer, parse_dates={'datetime': ['date', 'time']}, sep=',\s*', engine='python' ) activity_list.rename(columns=lambda x: x.lower(), inplace=True) activity_list.rename( columns=lambda x: '_' + x if x[0].isdigit() else x, inplace=True) activity_list['has_hr'] = activity_list.average_heart_rate.map(bool) activity_list['has_spd'] = activity_list.average_speed.map(bool) activity_list['has_pwr'] = activity_list.average_power.map(bool) activity_list['has_cad'] = activity_list.average_heart_rate.map(bool) activity_list['data'] = pd.Series(dtype=np.dtype("object")) return activity_list
def _request_activity_data(self, athlete, filename): """Actually do the request for activity filename This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') """ response = self._get_request(self._activity_endpoint(athlete, filename)).json() activity = pd.DataFrame(response['RIDE']['SAMPLES']) activity = activity.rename(columns=ACTIVITY_COLUMN_TRANSLATION) activity.index = pd.to_timedelta(activity.time, unit='s') activity.drop('time', axis=1, inplace=True) return activity[[i for i in ACTIVITY_COLUMN_ORDER if i in activity.columns]]
def _athlete_endpoint(self, athlete): """Construct athlete endpoint from host and athlete name Keyword arguments: athlete -- Full athlete name """ return '{host}{athlete}'.format( host=self.host, athlete=quote_plus(athlete) )
def _activity_endpoint(self, athlete, filename): """Construct activity endpoint from host, athlete name and filename Keyword arguments: athlete -- Full athlete name filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') """ return '{host}{athlete}/activity/{filename}'.format( host=self.host, athlete=quote_plus(athlete), filename=filename )
def _get_request(self, endpoint): """Do actual GET request to GC REST API Also validates responses. Keyword arguments: endpoint -- full endpoint for GET request """ try: response = requests.get(endpoint) except requests.exceptions.RequestException: raise GoldenCheetahNotAvailable(endpoint) if response.text.startswith('unknown athlete'): match = re.match( pattern='unknown athlete (?P<athlete>.+)', string=response.text) raise AthleteDoesNotExist( athlete=match.groupdict()['athlete']) elif response.text == 'file not found': match = re.match( pattern='.+/activity/(?P<filename>.+)', string=endpoint) raise ActivityDoesNotExist( filename=match.groupdict()['filename']) return response
def get_version(): """ Return package version as listed in `__version__` in `init.py`. """ with open(os.path.join(os.path.dirname(__file__), 'argparsetree', '__init__.py')) as init_py: return re.search('__version__ = [\'"]([^\'"]+)[\'"]', init_py.read()).group(1)
def create(self, tarball_url, env=None, app_name=None): """Creates a Heroku app-setup build. :param tarball_url: URL of a tarball containing an ``app.json``. :param env: (optional) Dict containing environment variable overrides. :param app_name: (optional) Name of the Heroku app to create. :returns: A tuple with ``(build_id, app_name)``. """ data = self._api.create_build( tarball_url=tarball_url, env=env, app_name=app_name, ) return (data['id'], data['app']['name'])
def url_with_auth(regex, view, kwargs=None, name=None, prefix=''): """ if view is string based, must be a full path """ from djapiauth.auth import api_auth if isinstance(view, six.string_types): # view is a string, must be full path return url(regex, api_auth(import_by_path(prefix + "." + view if prefix else view))) elif isinstance(view, (list, tuple)): # include return url(regex, view, name, prefix, **kwargs) else: # view is an object return url(regex, api_auth(view))
def traverse_urls(urlpattern, prefixre=[], prefixname=[], patternFunc=None, resolverFunc=None): """ urlpattern: urlpattern object prefix?? : for multiple level urls defined in different urls.py files prefixre: compiled regex object prefixnames: regex text patternFunc: function to process RegexURLPattern resolverFunc: function to process RegexURLResolver """ for u in urlpattern: if isinstance(u, RegexURLResolver): # inspect sub urls if resolverFunc: resolverFunc(u, prefixre, prefixname) traverse_urls(u.url_patterns, prefixre + [u.regex, ], prefixname + [u._regex, ], patternFunc, resolverFunc) else: if patternFunc: patternFunc(u, prefixre, prefixname)
def title(languages=None, genders=None): """ returns a random title .. code-block:: python >>> d.title() u'Mrs.' >>> d.title(['es']) u'El Sr.' >>> d.title(None, [GENDER_FEMALE]) u'Mrs.' :param languages: list of allowed languages. ['en'] if None :param genders: list of allowed genders. (GENDER_FEMALE, GENDER_MALE) if None """ languages = languages or ['en'] genders = genders or (GENDER_FEMALE, GENDER_MALE) choices = _get_titles(languages) gender = {'m':0, 'f':1}[random.choice(genders)] return random.choice(choices)[gender]
def person(languages=None, genders=None): """ returns a random tuple representing person information .. code-block:: python >>> d.person() (u'Derren', u'Powell', 'm') >>> d.person(genders=['f']) (u'Marge', u'Rodriguez', u'Mrs.', 'f') >>> d.person(['es'],['m']) (u'Jacinto', u'Delgado', u'El Sr.', 'm') :param language: :param genders: """ languages = languages or ['en'] genders = genders or (GENDER_FEMALE, GENDER_MALE) lang = random.choice(languages) g = random.choice(genders) t = title([lang], [g]) return first_name([lang], [g]), last_name([lang]), t, g
def first_name(languages=None, genders=None): """ return a random first name :return: >>> from mock import patch >>> with patch('%s._get_firstnamess' % __name__, lambda *args: ['aaa']): ... first_name() 'Aaa' """ choices = [] languages = languages or ['en'] genders = genders or [GENDER_MALE, GENDER_FEMALE] for lang in languages: for gender in genders: samples = _get_firstnames(lang, gender) choices.extend(samples) return random.choice(choices).title()
def last_name(languages=None): """ return a random last name >>> from mock import patch >>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']): ... last_name() 'Aaa' >>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]): ... last_name(['it']) 'It_Lastname' """ choices = [] languages = languages or ['en'] for lang in languages: samples = _get_lastnames(lang) choices.extend(samples) return random.choice(choices).title()
def lookup_color(color): """ Returns the hex color for any valid css color name >>> lookup_color('aliceblue') 'F0F8FF' """ if color is None: return color = color.lower() if color in COLOR_MAP: return COLOR_MAP[color] return color
def color_args(args, *indexes): """ Color a list of arguments on particular indexes >>> c = color_args([None,'blue'], 1) >>> c.next() None >>> c.next() '0000FF' """ for i,arg in enumerate(args): if i in indexes: yield lookup_color(arg) else: yield arg
def tick(self, index, length): """ Add tick marks in order of axes by width APIPARAM: chxtc <axis index>,<length of tick mark> """ assert int(length) <= 25, 'Width cannot be more than 25' self.data['ticks'].append('%s,%d'%(index,length)) return self.parent
def type(self, atype): """ Define the type of axes you wish to use atype must be one of x,t,y,r APIPARAM: chxt """ for char in atype: assert char in 'xtyr', 'Invalid axes type: %s'%char if not ',' in atype: atype = ','.join(atype) self['chxt'] = atype return self.parent
def label(self, index, *args): """ Label each axes one at a time args are of the form <label 1>,...,<label n> APIPARAM: chxl """ self.data['labels'].append( str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','') ) return self.parent
def range(self, index, *args): """ Set the range of each axis, one at a time args are of the form <start of range>,<end of range>,<interval> APIPARAM: chxr """ self.data['ranges'].append('%s,%s'%(index, ','.join(map(smart_str, args)))) return self.parent
def style(self, index, *args): """ Add style to your axis, one at a time args are of the form:: <axis color>, <font size>, <alignment>, <drawing control>, <tick mark color> APIPARAM: chxs """ args = color_args(args, 0) self.data['styles'].append( ','.join([str(index)]+list(map(str,args))) ) return self.parent
def render(self): """Render the axes data into the dict data""" for opt,values in self.data.items(): if opt == 'ticks': self['chxtc'] = '|'.join(values) else: self['chx%s'%opt[0]] = '|'.join(values) return self
def fromurl(cls, qs): """ Reverse a chart URL or dict into a GChart instance >>> G = GChart.fromurl('http://chart.apis.google.com/chart?...') >>> G <GChartWrapper.GChart instance at...> >>> G.image().save('chart.jpg','JPEG') """ if isinstance(qs, dict): return cls(**qs) return cls(**dict(parse_qsl(qs[qs.index('?')+1:])))
def map(self, geo, country_codes): """ Creates a map of the defined geography with the given country/state codes Geography choices are africa, asia, europe, middle_east, south_america, and world ISO country codes can be found at http://code.google.com/apis/chart/isocodes.html US state codes can be found at http://code.google.com/apis/chart/statecodes.html APIPARAMS: chtm & chld """ assert geo in GEO, 'Geograpic area %s not recognized'%geo self._geo = geo self._ld = country_codes return self