code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
async def create_user(self, device_type):
result = await self.request('post', '', {
'devicetype': device_type
}, auth=False)
self.username = result[0]['success']['username']
return self.username | Create a user.
https://developers.meethue.com/documentation/configuration-api#71_create_user |
async def request(self, method, path, json=None, auth=True):
url = 'http://{}/api/'.format(self.host)
if auth:
url += '{}/'.format(self.username)
url += path
try:
async with self.websession.request(method, url, json=json) as res:
if res.c... | Make a request to the API. |
async def set_config(self, on=None, long=None, lat=None,
sunriseoffset=None, sunsetoffset=None):
data = {
key: value for key, value in {
'on': on,
'long': long,
'lat': lat,
'sunriseoffset': sunriseoffse... | Change config of a Daylight sensor. |
async def set_config(self, on=None, tholddark=None, tholdoffset=None):
data = {
key: value for key, value in {
'on': on,
'tholddark': tholddark,
'tholdoffset': tholdoffset,
}.items() if value is not None
}
await se... | Change config of a CLIP LightLevel sensor. |
def get_unpaid_invoices_with_transactions(branch=None):
if not client: # pragma: nocover
return None
result = {}
try:
unpaid_invoices = client.fetch_json(
'invoices', query_params={'state': 'unpaid'})
except (ConnectionError, HTTPError): # pragma: nocover
resul... | Returns all invoices that are unpaid on freckle but have transactions.
This means, that the invoice is either partially paid and can be left as
unpaid in freckle, or the invoice has been fully paid and should be set to
paid in freckle as well. |
def load_cfg(self, src_dir):
# last files override previous ones
cfg_files = [os.path.expanduser(USER_CFG_FILE),
os.path.abspath(os.path.join(src_dir, '.dirsync'))]
cfg = ConfigParser()
cfg.read(cfg_files)
if not cfg.has_section('default... | Load defaults from configuration file:
- from the source/directory/.dirsync file (prioritary)
- and/or a %HOME%/.dirsync user config file |
def copy_fields(src, to):
args = tuple(getattr(src, field.attname) for field in src._meta.fields)
return to(*args) | Returns a new instance of `to_cls` with fields data fetched from `src`.
Useful for getting a model proxy instance from concrete model instance or
the other way around. Note that we use *arg calling to get a faster model
initialization. |
def active_status(self, request):
app_installed = "djcelery" in settings.INSTALLED_APPS
if not app_installed:
return Response(status=status.HTTP_501_NOT_IMPLEMENTED)
from djcelery.models import WorkerState
count_workers = WorkerState.objects.all().count()
... | This will only work if you have django-celery installed (for now).
In case you only need to work with status codes to find out if the
workers are up or not.
This will only work if we assume our db only contains "active workers".
To use this feature, you must ensure you use only named wor... |
def do_work(self):
self._starttime = time.time()
if not os.path.isdir(self._dir2):
if self._maketarget:
if self._verbose:
self.log('Creating directory %s' % self._dir2)
try:
os.makedirs(self._dir2)
... | Do work |
def _cmptimestamps(self, filest1, filest2):
mtime_cmp = int((filest1.st_mtime - filest2.st_mtime) * 1000) > 0
if self._use_ctime:
return mtime_cmp or \
int((filest1.st_ctime - filest2.st_mtime) * 1000) > 0
else:
return mtime_cmp | Compare time stamps of two files and return True
if file1 (source) is more recent than file2 (target) |
def _dirdiffandcopy(self, dir1, dir2):
self._dowork(dir1, dir2, self._copy) | Private function which does directory diff & copy |
def _dirdiffandupdate(self, dir1, dir2):
self._dowork(dir1, dir2, None, self._update) | Private function which does directory diff & update |
def _dirdiffcopyandupdate(self, dir1, dir2):
self._dowork(dir1, dir2, self._copy, self._update) | Private function which does directory diff, copy and update (synchro) |
def _diff(self, dir1, dir2):
self._dcmp = self._compare(dir1, dir2)
if self._dcmp.left_only:
self.log('Only in %s' % dir1)
for x in sorted(self._dcmp.left_only):
self.log('>> %s' % x)
self.log('')
if self._dcmp.right_only:
... | Private function which only does directory diff |
def sync(self):
self._copyfiles = True
self._updatefiles = True
self._creatdirs = True
self._copydirection = 0
if self._verbose:
self.log('Synchronizing directory %s with %s\n' %
(self._dir2, self._dir1))
self._dirdiffcopyandupd... | Synchronize will try to synchronize two directories w.r.t
each other's contents, copying files if necessary from source
to target, and creating directories if necessary. If the optional
argument purge is True, directories in target (dir2) that are
not present in the source (dir1) will be... |
def update(self):
self._copyfiles = False
self._updatefiles = True
self._purge = False
self._creatdirs = False
if self._verbose:
self.log('Updating directory %s with %s\n' %
(self._dir2, self._dir1))
self._dirdiffandupdate(self.... | Update will try to update the target directory
w.r.t source directory. Only files that are common
to both directories will be updated, no new files
or directories are created |
def diff(self):
self._copyfiles = False
self._updatefiles = False
self._purge = False
self._creatdirs = False
self._updatefiles = False
self.log('Difference of directory %s from %s\n' %
(self._dir2, self._dir1))
self._diff(self._dir1, s... | Only report difference in content between two directories |
def report(self):
# We need only the first 4 significant digits
tt = (str(self._endtime - self._starttime))[:4]
self.log('\n%s finished in %s seconds.' % (__pkg_name__, tt))
self.log('%d directories parsed, %d files copied' %
(self._numdirs, self._numfiles))
... | Print report of work at the end |
async def set_action(self, on=None, bri=None, hue=None, sat=None, xy=None,
ct=None, alert=None, effect=None, transitiontime=None,
bri_inc=None, sat_inc=None, hue_inc=None, ct_inc=None,
xy_inc=None, scene=None):
data = {
... | Change action of a group. |
def handle(self, **options):
self.flushdb = options.get('flushdb')
self._pre_tasks()
self._create_users()
self._create_badges()
self._create_awards() | Command handler. |
def _pre_tasks(self):
if self.flushdb:
management.call_command('flush', verbosity=0, interactive=False)
logger.info('Flushed database') | Pre-tasks handler. |
def _create_users(self):
rn = RandomNicknames()
for name in rn.random_nicks(count=50):
username = '%s%d' % (slugify(name), random.randrange(1, 99))
user = User.objects.create_user(
username=username,
email='%s@example.com' % username,
... | Creates users. |
def _create_badges(self):
rn = RandomNicknames()
for name in rn.random_nicks(count=20):
slug = slugify(name)
badge = Badge.objects.create(
name=name,
slug=slug,
description='Lorem ipsum dolor sit amet, consectetur adipisic... | Creates badges. |
def _create_awards(self):
users = User.objects.all()
for user in users:
everyone_badge = Badge.objects.last()
badge = Badge.objects.order_by('?')[0]
try:
award = Award.objects.create(user=user, badge=badge)
everyone_award = Aw... | Creates awards. |
def chunks(l, n):
for i in _range(0, len(l), n):
yield l[i:i + n] | Yields successive n-sized chunks from l. |
def log_queries(recipe):
logger.debug(
'β Badge %s: SQL queries time %.2f second(s)',
recipe.slug,
sum([float(q['time']) for q in connection.queries])) | Logs recipe instance SQL queries (actually, only time). |
def sanitize_command_options(options):
multiples = [
'badges',
'exclude_badges',
]
for option in multiples:
if options.get(option):
value = options[option]
if value:
options[option] = [v for v in value.split(' ') if v]
return options | Sanitizes command options. |
def register(self, recipe):
if not isinstance(recipe, (list, tuple)):
recipe = [recipe, ]
for item in recipe:
recipe = self.get_recipe_instance_from_class(item)
self._registry[recipe.slug] = recipe | Registers a new recipe class. |
def unregister(self, recipe):
recipe = self.get_recipe_instance_from_class(recipe)
if recipe.slug in self._registry:
del self._registry[recipe.slug] | Unregisters a given recipe class. |
def get_recipe_instance(self, badge):
from .exceptions import BadgeNotFound
if badge in self._registry:
return self.recipes[badge]
raise BadgeNotFound() | Returns the recipe instance for the given badge slug.
If badge has not been registered, raises ``exceptions.BadgeNotFound``. |
def get_recipe_instances(self, badges=None, excluded=None):
if badges:
if not isinstance(badges, (list, tuple)):
badges = [badges]
if excluded:
if not isinstance(excluded, (list, tuple)):
excluded = [excluded]
badges = list(se... | Returns all recipe instances or just those for the given badges. |
def get_recipe_instances_for_badges(self, badges):
from .exceptions import BadgeNotFound
valid, invalid = [], []
if not isinstance(badges, (list, tuple)):
badges = [badges]
for badge in badges:
try:
recipe = self.get_recipe_instance(bad... | Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``. |
def _init_taskqueue_stub(self, **stub_kwargs):
task_args = {}
# root_path is required so the stub can find 'queue.yaml' or 'queue.yml'
if 'root_path' not in stub_kwargs:
for p in self._app_path:
# support --gae-application values that may be a .yaml file
... | Initializes the taskqueue stub using nosegae config magic |
def _init_datastore_v3_stub(self, **stub_kwargs):
task_args = dict(datastore_file=self._data_path)
task_args.update(stub_kwargs)
self.testbed.init_datastore_v3_stub(**task_args) | Initializes the datastore stub using nosegae config magic |
def _init_user_stub(self, **stub_kwargs):
# do a little dance to keep the same kwargs for multiple tests in the same class
# because the user stub will barf if you pass these items into it
# stub = user_service_stub.UserServiceStub(**stub_kw_args)
# TypeError: __init__() got an ... | Initializes the user stub using nosegae config magic |
def _init_modules_stub(self, **_):
from google.appengine.api import request_info
# edit all_versions per modules & versions thereof needing tests
all_versions = {} # {'default': [1], 'andsome': [2], 'others': [1]}
def_versions = {} # {m: all_versions[m][0] for m in all_version... | Initializes the modules stub based off of your current yaml files
Implements solution from
http://stackoverflow.com/questions/28166558/invalidmoduleerror-when-using-testbed-to-unit-test-google-app-engine |
def _init_stub(self, stub_init, **stub_kwargs):
getattr(self.testbed, stub_init, lambda **kwargs: None)(**stub_kwargs) | Initializes all other stubs for consistency's sake |
def html_for_env_var(key):
value = os.getenv(key)
return KEY_VALUE_TEMPLATE.format(key, value) | Returns an HTML snippet for an environment variable.
Args:
key: A string representing an environment variable name.
Returns:
String HTML representing the value and variable. |
def html_for_cgi_argument(argument, form):
value = form[argument].value if argument in form else None
return KEY_VALUE_TEMPLATE.format(argument, value) | Returns an HTML snippet for a CGI argument.
Args:
argument: A string representing an CGI argument name in a form.
form: A CGI FieldStorage object.
Returns:
String HTML representing the CGI value and variable. |
def html_for_modules_method(method_name, *args, **kwargs):
method = getattr(modules, method_name)
value = method(*args, **kwargs)
return KEY_VALUE_TEMPLATE.format(method_name, value) | Returns an HTML snippet for a Modules API method.
Args:
method_name: A string containing a Modules API method.
args: Positional arguments to be passed to the method.
kwargs: Keyword arguments to be passed to the method.
Returns:
String HTML representing the Modules API method a... |
def get(self):
environment_variables_output = [html_for_env_var(key)
for key in sorted(os.environ)]
cgi_arguments_output = []
if os.getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded':
# Note: a blank Content-type header wil... | GET handler that serves environment data. |
def sync_badges(**kwargs):
update = kwargs.get('update', False)
created_badges = []
instances = registry.get_recipe_instances()
for instance in instances:
reset_queries()
badge, created = instance.create_badge(update=update)
if created:
created_badges.append(bad... | Iterates over registered recipes and creates missing badges. |
def sync_counts(**kwargs):
badges = kwargs.get('badges')
excluded = kwargs.get('exclude_badges')
instances = registry.get_recipe_instances(badges=badges, excluded=excluded)
updated_badges, unchanged_badges = [], []
for instance in instances:
reset_queries()
badge, updated = in... | Iterates over registered recipes and denormalizes ``Badge.users.count()``
into ``Badge.users_count`` field. |
def sync_awards(**kwargs):
badges = kwargs.get('badges')
excluded = kwargs.get('exclude_badges')
disable_signals = kwargs.get('disable_signals')
batch_size = kwargs.get('batch_size', None)
db_read = kwargs.get('db_read', None)
award_post_save = True
if disable_signals:
setting... | Iterates over registered recipes and possibly creates awards. |
def show_stats(**kwargs):
db_read = kwargs.get('db_read', DEFAULT_DB_ALIAS)
badges = (Badge.objects.using(db_read)
.all()
.annotate(u_count=Count('users'))
.order_by('u_count'))
for badge in badges:
logger.info('... | Shows badges stats. |
def reset_awards(**kwargs):
filter_badges = kwargs.get('badges', None)
exclude_badges = kwargs.get('exclude_badges', None)
for option in [filter_badges, exclude_badges]:
if option:
if not isinstance(option, (list, tuple)):
option = [option]
signals.pre_delete.d... | Resets badges stats. |
def bulk_create_awards(objects, batch_size=500, post_save_signal=True):
count = len(objects)
if not count:
return
badge = objects[0].badge
try:
Award.objects.bulk_create(objects, batch_size=batch_size)
if post_save_signal:
for obj in objects:
sign... | Saves award objects. |
def get_badge(self):
try:
obj = Badge.objects.using(self.db_read).get(slug=self.slug)
logger.debug('β Badge %s: fetched from db (%s)', obj.slug, self.db_read)
except Badge.DoesNotExist:
obj = None
return obj | The related ``Badge`` object. |
def create_badge(self, update=False):
badge, created = self.badge, False
if badge:
logger.debug('β Badge %s: already created', badge.slug)
if update:
to_update = {}
for field in ('name', 'slug', 'description', 'image'):
... | Saves the badge in the database (or updates it if ``update`` is ``True``).
Returns a tuple: ``badge`` (the badge object) and ``created`` (``True``, if
badge has been created). |
def can_perform_awarding(self):
if not self.user_ids:
logger.debug(
'β Badge %s: no users to check (empty user_ids property)',
self.slug)
return False
if not self.badge:
logger.debug(
'β Badge %s: does not exis... | Checks if we can perform awarding process (is ``user_ids`` property
defined? Does Badge object exists? and so on). If we can perform db
operations safely, returns ``True``. Otherwise, ``False``. |
def update_badge_users_count(self):
logger.debug('β Badge %s: syncing users count...', self.slug)
badge, updated = self.badge, False
if not badge:
logger.debug(
'β Badge %s: does not exist in the database (run badgify_sync badges)',
self.slu... | Denormalizes ``Badge.users.count()`` into ``Bagdes.users_count`` field. |
def get_already_awarded_user_ids(self, db_read=None, show_log=True):
db_read = db_read or self.db_read
already_awarded_ids = self.badge.users.using(db_read).values_list('id', flat=True)
already_awarded_ids_count = len(already_awarded_ids)
if show_log:
logger.debug... | Returns already awarded user ids and the count. |
def get_current_user_ids(self, db_read=None):
db_read = db_read or self.db_read
return self.user_ids.using(db_read) | Returns current user ids and the count. |
def get_unawarded_user_ids(self, db_read=None):
db_read = db_read or self.db_read
already_awarded_ids = self.get_already_awarded_user_ids(db_read=db_read)
current_ids = self.get_current_user_ids(db_read=db_read)
unawarded_ids = list(set(current_ids) - set(already_awarded_ids))
... | Returns unawarded user ids (need to be saved) and the count. |
def get_obsolete_user_ids(self, db_read=None):
db_read = db_read or self.db_read
already_awarded_ids = self.get_already_awarded_user_ids(db_read=db_read, show_log=False)
current_ids = self.get_current_user_ids(db_read=db_read)
obsolete_ids = list(set(already_awarded_ids) - set(... | Returns obsolete users IDs to unaward. |
def create_awards(self, db_read=None, batch_size=None,
post_save_signal=True):
if not self.can_perform_awarding():
return
User = get_user_model()
db_read = db_read or self.db_read
batch_size = batch_size or self.batch_size
unawarded_i... | Create awards. |
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument('--badges',
action='store',
dest='badges',
type=str)
parser.add_argument('--db-read',
... | Command arguments. |
def handle_label(self, label, **options):
if not hasattr(commands, 'sync_%s' % label):
raise CommandError('"%s" is not a valid command.' % label)
getattr(commands, 'sync_%s' % label)(**sanitize_command_options(options)) | Command handler. |
def extract_suffix(self, name):
# don't extract suffixes if we can't reasonably suspect we have enough parts to the name for there to be one
if len(name.strip().split()) > 2:
name, suffix = self.extract_matching_portion(r'\b(?P<suffix>{})(?=\b|\s|\Z|\W)'.format(SUFFIX_RE), name)
... | Returns a tuple of (name, suffix), or (name, None) if no suffix could be found.
As the method name indicates, the name is returned without the suffix.
Suffixes deemed to be degrees are discarded. |
def reverse_last_first(self, name):
# make sure we don't put a suffix in the middle, as in "Smith, Tom II"
name, suffix = self.extract_suffix(name)
split = re.split(', ?', name)
# make sure that the comma is not just preceding a suffix, such as "Jr",
# by checking that... | Takes a name that is in [last, first] format and returns it in a hopefully [first last] order.
Also extracts the suffix and puts it back on the end, in case it's embedded somewhere in the middle. |
def compare(cls, match, subject):
if match.expand().lower() == subject.expand().lower():
return 4
elif match.kernel().lower() == subject.kernel().lower():
return 3
# law and lobbying firms in CRP data typically list only the first two partners
# before 'e... | Accepts two OrganizationName objects and returns an arbitrary,
numerical score based upon how well the names match. |
def badgify_badges(**kwargs):
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objec... | Returns all badges or only awarded badges for the given user. |
def without_extra_phrases(self):
# the last parenthesis is optional, because sometimes they are truncated
name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name)
name = re.sub(r'(?i)\s* formerly.*$', '', name)
name = re.sub(r'(?i)\s*and its affiliates$', '', name)
name = re.s... | Removes parenthethical and dashed phrases |
def kernel(self):
stop_words = [ y.lower() for y in self.abbreviations.values() + self.filler_words ]
kernel = ' '.join([ x for x in self.expand().split() if x.lower() not in stop_words ])
# this is a hack to get around the fact that this is the only two-word phrase we want to block
... | The 'kernel' is an attempt to get at just the most pithy words in the name |
def detect_and_fix_two_part_surname(self, args):
i = 0
while i < len(args) - 1:
if args[i].lower() in self.family_name_prefixes:
args[i] = ' '.join(args[i:i+2])
del(args[i+1])
break
else:
i += 1 | This detects common family name prefixes and joins them to the last name,
so names like "De Kuyper" don't end up with "De" as a middle name. |
def case_name_parts(self):
if not self.is_mixed_case():
self.honorific = self.honorific.title() if self.honorific else None
self.nick = self.nick.title() if self.nick else None
if self.first:
self.first = self.first.title()
self.first... | Convert all the parts of the name to the proper case... carefully! |
def main(args=None):
args = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("safe_file", type=str, nargs='+')
parser.add_argument("--granules", action="store_true")
parsed = parser.parse_args(args)
pp = pprint.PrettyPrinter()
for safe_file in parsed.safe_file:
... | Print metadata as JSON strings. |
def open(safe_file):
if os.path.isdir(safe_file) or os.path.isfile(safe_file):
return SentinelDataSet(safe_file)
else:
raise IOError("file not found: %s" % safe_file) | Return a SentinelDataSet object. |
def _pvi_path(granule):
pvi_name = granule._metadata.iter("PVI_FILENAME").next().text
pvi_name = pvi_name.split("/")
pvi_path = os.path.join(
granule.granule_path,
pvi_name[len(pvi_name)-2], pvi_name[len(pvi_name)-1]
)
try:
assert os.path.isfile(pvi_path) or \
... | Determine the PreView Image (PVI) path inside the SAFE pkg. |
def _granule_identifier_to_xml_name(granule_identifier):
# Replace "MSI" with "MTD".
changed_item_type = re.sub("_MSI_", "_MTD_", granule_identifier)
# Split string up by underscores.
split_by_underscores = changed_item_type.split("_")
del split_by_underscores[-1]
cleaned = str()
# Stit... | Very ugly way to convert the granule identifier.
e.g.
From
Granule Identifier:
S2A_OPER_MSI_L1C_TL_SGS__20150817T131818_A000792_T28QBG_N01.03
To
Granule Metadata XML name:
S2A_OPER_MTD_L1C_TL_SGS__20150817T131818_A000792_T28QBG.xml |
def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2):
assert len(coords) % dims == 0
number_of_points = len(coords)/dims
coords_as_array = np.array(coords)
reshaped = coords_as_array.reshape(number_of_points, dims)
points = [
(float(i[1]), float(i[0])) if swap else ((floa... | Return Shapely Polygon from coordinates.
- coords: list of alterating latitude / longitude coordinates
- fix_geom: automatically fix geometry |
def product_metadata_path(self):
data_object_section = self._manifest_safe.find("dataObjectSection")
for data_object in data_object_section:
# Find product metadata XML.
if data_object.attrib.get("ID") == "S2_Level-1C_Product_Metadata":
relpath = os.path.... | Return path to product metadata XML file. |
def footprint(self):
product_footprint = self._product_metadata.iter("Product_Footprint")
# I don't know why two "Product_Footprint" items are found.
for element in product_footprint:
global_footprint = None
for global_footprint in element.iter("Global_Footprint"... | Return product footprint. |
def granules(self):
for element in self._product_metadata.iter("Product_Info"):
product_organisation = element.find("Product_Organisation")
if self.product_format == 'SAFE':
return [
SentinelGranule(_id.find("Granules"), self)
for _id in p... | Return list of SentinelGranule objects. |
def granule_paths(self, band_id):
band_id = str(band_id).zfill(2)
try:
assert isinstance(band_id, str)
assert band_id in BAND_IDS
except AssertionError:
raise AttributeError(
"band ID not valid: %s" % band_id
)
... | Return the path of all granules of a given band. |
def metadata_path(self):
xml_name = _granule_identifier_to_xml_name(self.granule_identifier)
metadata_path = os.path.join(self.granule_path, xml_name)
try:
assert os.path.isfile(metadata_path) or \
metadata_path in self.dataset._zipfile.namelist()
exc... | Determine the metadata path. |
def tci_path(self):
tci_paths = [
path for path in self.dataset._product_metadata.xpath(
".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()"
% self.granule_identifier
) if path.endswith('TCI')
]
try:
tci_path = tci_... | Return the path to the granules TrueColorImage. |
def cloud_percent(self):
image_content_qi = self._metadata.findtext(
(
"""n1:Quality_Indicators_Info/Image_Content_QI/"""
"""CLOUDY_PIXEL_PERCENTAGE"""
),
namespaces=self._nsmap)
return float(image_content_qi) | Return percentage of cloud coverage. |
def footprint(self):
# Check whether product or granule footprint needs to be calculated.
tile_geocoding = self._metadata.iter("Tile_Geocoding").next()
resolution = 10
searchstring = ".//*[@resolution='%s']" % resolution
size, geoposition = tile_geocoding.findall(searchs... | Find and return footprint as Shapely Polygon. |
def cloudmask(self):
polys = list(self._get_mask(mask_type="MSK_CLOUDS"))
return MultiPolygon([
poly["geometry"]
for poly in polys
if poly["attributes"]["maskType"] == "OPAQUE"
]).buffer(0) | Return cloudmask as a shapely geometry. |
def ground_resolution(lat, level):
lat = TileSystem.clip(lat, TileSystem.LATITUDE_RANGE)
return cos(lat * pi / 180) * 2 * pi * TileSystem.EARTH_RADIUS / TileSystem.map_size(level) | Gets ground res in meters / pixel |
def geo_to_pixel(geo, level):
lat, lon = float(geo[0]), float(geo[1])
lat = TileSystem.clip(lat, TileSystem.LATITUDE_RANGE)
lon = TileSystem.clip(lon, TileSystem.LONGITUDE_RANGE)
x = (lon + 180) / 360
sin_lat = sin(lat * pi / 180)
y = 0.5 - log((1 + sin_lat) / (1... | Transform from geo coordinates to pixel coordinates |
def pixel_to_geo(pixel, level):
pixel_x = pixel[0]
pixel_y = pixel[1]
map_size = float(TileSystem.map_size(level))
x = (TileSystem.clip(pixel_x, (0, map_size - 1)) / map_size) - 0.5
y = 0.5 - (TileSystem.clip(pixel_y, (0, map_size - 1)) / map_size)
lat = 90 - 360... | Transform from pixel to geo coordinates |
def tile_to_pixel(tile, centered=False):
pixel = [tile[0] * 256, tile[1] * 256]
if centered:
# should clip on max map size
pixel = [pix + 128 for pix in pixel]
return pixel[0], pixel[1] | Transform tile to pixel coordinates |
def tile_to_quadkey(tile, level):
tile_x = tile[0]
tile_y = tile[1]
quadkey = ""
for i in xrange(level):
bit = level - i
digit = ord('0')
mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1)
if (tile_x & mask) is not 0:
... | Transform tile coordinates to a quadkey |
def quadkey_to_tile(quadkey):
tile_x, tile_y = (0, 0)
level = len(quadkey)
for i in xrange(level):
bit = level - i
mask = 1 << (bit - 1)
if quadkey[level - bit] == '1':
tile_x |= mask
if quadkey[level - bit] == '2':
... | Transform quadkey to tile coordinates |
def authorize_url(self, state=''):
url = 'https://openapi.youku.com/v2/oauth2/authorize?'
params = {
'client_id': self.client_id,
'response_type': 'code',
'state': state,
'redirect_uri': self.redirect_uri
}
return url + urlencode(p... | return user authorize url |
def get_token_by_code(self, code):
'''return origin json'''
url = 'https://openapi.youku.com/v2/oauth2/token'
data = {'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'code': code,
... | return origin json |
def refresh_token(self, refresh_token):
'''return origin json'''
url = 'https://api.youku.com/oauth2/token.json'
data = {'client_id': self.client_id,
'grant_type': 'refresh_token',
'refresh_token': refresh_token}
r = requests.post(url, data=data)
c... | return origin json |
def check_error(response, expect_status=200):
json = None
try:
json = response.json()
except:
pass
if (response.status_code != expect_status or
response.status_code == 400 or
'error' in json):
if json:
error = json['error']
rai... | Youku error should return in json form, like:
HTTP 400
{
"error":{
"code":120010223,
"type":"UploadsException",
"description":"Expired upload token"
}
}
But error also maybe in response url params or response booy.
Content-Type maybe application/... |
def remove_none_value(data):
return dict((k, v) for k, v in data.items() if v is not None) | remove item from dict if value is None.
return new dict. |
def find_person_by_id(self, person_id):
url = 'https://openapi.youku.com/v2/persons/show.json'
params = {
'client_id': self.client_id,
'person_id': person_id
}
r = requests.get(url, params=params)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/docs?id=87 |
def find_persons_by_ids(self, person_ids):
url = 'https://openapi.youku.com/v2/persons/show_batch.json'
params = {
'client_id': self.client_id,
'person_ids': person_ids
}
r = requests.get(url, params=params)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/docs?id=88 |
def find_persons_by_type(self, type, nationality=None, gender=None,
firstletter=None, orderby='view-week-count',
page=1, count=20):
url = 'https://openapi.youku.com/v2/persons/by_type.json'
params = {
'client_id': self.client... | doc: http://open.youku.com/docs/docs?id=89 |
def my_info(self, access_token):
url = 'https://openapi.youku.com/v2/users/myinfo.json'
data = {'client_id': self.client_id,
'access_token': access_token}
r = requests.post(url, data=data)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/doc?id=23 |
def friendship_followings(self, user_id=None, user_name=None,
page=1, count=20):
url = 'https://openapi.youku.com/v2/users/friendship/followings.json'
data = {
'client_id': self.client_id,
'page': page,
'count': count,
... | doc: http://open.youku.com/docs/doc?id=26 |
def create_friendship(self, access_token,
user_id=None, user_name=None):
url = 'https://openapi.youku.com/v2/users/friendship/create.json'
data = {
'client_id': self.client_id,
'access_token': access_token,
'user_id': user_id,
... | doc: http://open.youku.com/docs/doc?id=28 |
def create_subscribe(self, access_token, show_id):
url = 'https://openapi.youku.com/v2/users/subscribe/create.json'
params = {
'client_id': self.client_id,
'access_token': access_token,
'show_id': show_id
}
r = requests.get(url, params=params)... | doc: http://open.youku.com/docs/doc?id=29 |
def cancel_subscribe(self, access_token, show_id):
url = 'https://openapi.youku.com/v2/users/subscribe/cancel.json'
params = {
'client_id': self.client_id,
'access_token': access_token,
'show_id': show_id
}
r = requests.post(url, data=params)
... | doc: ?? |
def subscribe_get(self, access_token, page=1, count=20):
url = 'https://openapi.youku.com/v2/users/subscribe/get.json'
params = {
'client_id': self.client_id,
'access_token': access_token,
'page': page,
'count': count
}
r = request... | doc: http://open.youku.com/docs/doc?id=30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.