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`
... |
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
... |
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(Pr... |
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 obje... |
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... |
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,
... |
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`
N... |
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(... |
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_... |
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... |
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... |
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' ... |
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>')
... |
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... |
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 fo... |
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_sam... |
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_dat... |
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():
... |
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 = stac... |
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
... |
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 ... |
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 skip... |
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 : `... |
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.kee... |
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`... |
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):
... |
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 | %(... |
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='st... |
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()
... |
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 ... |
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_comp... |
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', ... |
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):
... |
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... |
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... |
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>"
... |
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 ... |
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 heig... |
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 + ');'
... |
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})
... |
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 ... |
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 == "li... |
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
... |
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.
:par... |
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')
... |
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 = {
... |
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_... |
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 d... |
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 wrapp... |
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... |
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_... |
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 pub... |
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 = ... |
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 J... |
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... |
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('stat... |
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 = _sequen... |
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 ... |
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)... |
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().s... |
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 shou... |
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... |
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) ... |
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))
... |
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_0... |
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}/a... |
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:
... |
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 crea... |
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 + "." + v... |
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 Regex... |
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
:pa... |
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'])
... |
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 =... |
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_na... |
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:
... |
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)
s... |
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))))
... |
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(ar... |
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, ... |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.