code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
args = tuple(getattr(src, field.attname) for field in src._meta.fields) return to(*args)
def copy_fields(src, to)
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.
4.679114
4.118893
1.136013
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() result = self.inspect.active() ...
def active_status(self, request)
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...
3.00743
2.832711
1.061679
left = set() right = set() self._numdirs += 1 excl_patterns = set(self._exclude).union(self._ignore) for cwd, dirs, files in os.walk(dir1): self._numdirs += len(dirs) for f in dirs + files: path = os.path.relpath(os.path.join(c...
def _compare(self, dir1, dir2)
Compare contents of two directories
2.844744
2.802012
1.01525
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) self._numn...
def do_work(self)
Do work
4.813282
4.761199
1.010939
if self._verbose: self.log('Source directory: %s:' % dir1) self._dcmp = self._compare(dir1, dir2) # Files & directories only in target directory if self._purge: for f2 in self._dcmp.right_only: fullf2 = os.path.join(self._dir2, f2) ...
def _dowork(self, dir1, dir2, copyfunc=None, updatefunc=None)
Private attribute for doing work
2.118184
2.115153
1.001433
# NOTE: dir1 is source & dir2 is target if self._copyfiles: rel_path = filename.replace('\\', '/').split('/') rel_dir = '/'.join(rel_path[:-1]) filename = rel_path[-1] dir2_root = dir2 dir1 = os.path.join(dir1, rel_dir) ...
def _copy(self, filename, dir1, dir2)
Private function for copying a file
1.891049
1.887242
1.002017
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
def _cmptimestamps(self, filest1, filest2)
Compare time stamps of two files and return True if file1 (source) is more recent than file2 (target)
2.758911
2.627749
1.049914
# NOTE: dir1 is source & dir2 is target if self._updatefiles: file1 = os.path.join(dir1, filename) file2 = os.path.join(dir2, filename) try: st1 = os.stat(file1) st2 = os.stat(file2) except os.error: ...
def _update(self, filename, dir1, dir2)
Private function for updating a file based on last time stamp of modification
2.292096
2.273679
1.0081
self._dowork(dir1, dir2, self._copy)
def _dirdiffandcopy(self, dir1, dir2)
Private function which does directory diff & copy
8.627191
8.245364
1.046308
self._dowork(dir1, dir2, None, self._update)
def _dirdiffandupdate(self, dir1, dir2)
Private function which does directory diff & update
9.922303
8.853859
1.120676
self._dowork(dir1, dir2, self._copy, self._update)
def _dirdiffcopyandupdate(self, dir1, dir2)
Private function which does directory diff, copy and update (synchro)
6.656199
6.00637
1.10819
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: self.log('Only in %s' % di...
def _diff(self, dir1, dir2)
Private function which only does directory diff
2.063755
1.999587
1.032091
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._dirdiffcopyandupdate(self._dir1, ...
def sync(self)
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...
6.54249
5.419968
1.207109
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._dir1, self._dir2)
def update(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
7.033034
5.486645
1.281846
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, self._dir2)
def diff(self)
Only report difference in content between two directories
6.063162
5.121884
1.183776
# 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)) if self._nu...
def report(self)
Print report of work at the end
2.743062
2.681257
1.023051
data = { key: value for key, value in { 'on': on, 'bri': bri, 'hue': hue, 'sat': sat, 'xy': xy, 'ct': ct, 'alert': alert, 'effect': effect, 'transi...
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)
Change action of a group.
1.421222
1.415375
1.004131
self.flushdb = options.get('flushdb') self._pre_tasks() self._create_users() self._create_badges() self._create_awards()
def handle(self, **options)
Command handler.
7.743496
7.691075
1.006816
if self.flushdb: management.call_command('flush', verbosity=0, interactive=False) logger.info('Flushed database')
def _pre_tasks(self)
Pre-tasks handler.
6.918441
6.002519
1.15259
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, password='se...
def _create_users(self)
Creates users.
4.245604
3.990095
1.064036
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 adipisicing elit') log...
def _create_badges(self)
Creates badges.
4.320676
4.003339
1.079268
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 = Award.objects.create(user=us...
def _create_awards(self)
Creates awards.
3.318944
3.193153
1.039394
for i in _range(0, len(l), n): yield l[i:i + n]
def chunks(l, n)
Yields successive n-sized chunks from l.
2.858716
2.56848
1.112999
logger.debug( '⚐ Badge %s: SQL queries time %.2f second(s)', recipe.slug, sum([float(q['time']) for q in connection.queries]))
def log_queries(recipe)
Logs recipe instance SQL queries (actually, only time).
13.701487
11.933222
1.14818
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
def sanitize_command_options(options)
Sanitizes command options.
4.240405
4.108383
1.032135
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
def register(self, recipe)
Registers a new recipe class.
4.294601
3.971215
1.081433
recipe = self.get_recipe_instance_from_class(recipe) if recipe.slug in self._registry: del self._registry[recipe.slug]
def unregister(self, recipe)
Unregisters a given recipe class.
4.384211
3.808038
1.151304
from .exceptions import BadgeNotFound if badge in self._registry: return self.recipes[badge] raise BadgeNotFound()
def get_recipe_instance(self, badge)
Returns the recipe instance for the given badge slug. If badge has not been registered, raises ``exceptions.BadgeNotFound``.
9.992679
5.532296
1.806244
if badges: if not isinstance(badges, (list, tuple)): badges = [badges] if excluded: if not isinstance(excluded, (list, tuple)): excluded = [excluded] badges = list(set(self.registered) - set(excluded)) if badges: ...
def get_recipe_instances(self, badges=None, excluded=None)
Returns all recipe instances or just those for the given badges.
2.848671
2.621344
1.086722
from .exceptions import BadgeNotFound valid, invalid = [], [] if not isinstance(badges, (list, tuple)): badges = [badges] for badge in badges: try: recipe = self.get_recipe_instance(badge) valid.append(recipe) ...
def get_recipe_instances_for_badges(self, badges)
Takes a list of badge slugs and returns a tuple: ``(valid, invalid)``.
3.314534
2.660806
1.245688
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 dir_ = os.path.dirname(p) if os.pat...
def _init_taskqueue_stub(self, **stub_kwargs)
Initializes the taskqueue stub using nosegae config magic
3.73961
3.638547
1.027776
task_args = dict(datastore_file=self._data_path) task_args.update(stub_kwargs) self.testbed.init_datastore_v3_stub(**task_args)
def _init_datastore_v3_stub(self, **stub_kwargs)
Initializes the datastore stub using nosegae config magic
4.559632
4.110718
1.109206
# 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 unexpected keyword argument 'USER_IS_ADMIN...
def _init_user_stub(self, **stub_kwargs)
Initializes the user stub using nosegae config magic
4.977947
4.736704
1.05093
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_versions} m2h = {} # {m: {def_ver...
def _init_modules_stub(self, **_)
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
4.463746
4.355068
1.024954
getattr(self.testbed, stub_init, lambda **kwargs: None)(**stub_kwargs)
def _init_stub(self, stub_init, **stub_kwargs)
Initializes all other stubs for consistency's sake
9.355189
8.007054
1.168368
value = os.getenv(key) return KEY_VALUE_TEMPLATE.format(key, value)
def html_for_env_var(key)
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.
5.716466
9.401762
0.608021
value = form[argument].value if argument in form else None return KEY_VALUE_TEMPLATE.format(argument, value)
def html_for_cgi_argument(argument, form)
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.
5.855155
9.722761
0.602211
method = getattr(modules, method_name) value = method(*args, **kwargs) return KEY_VALUE_TEMPLATE.format(method_name, value)
def html_for_modules_method(method_name, *args, **kwargs)
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...
4.052939
5.165847
0.784564
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 will still sometim...
def get(self)
GET handler that serves environment data.
3.042132
3.005329
1.012246
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(badge) log_queries(ins...
def sync_badges(**kwargs)
Iterates over registered recipes and creates missing badges.
5.403523
4.365646
1.237737
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 = instance.update_badge_users_c...
def sync_counts(**kwargs)
Iterates over registered recipes and denormalizes ``Badge.users.count()`` into ``Badge.users_count`` field.
4.709721
3.878792
1.214224
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: settings.AUTO_DENORMALIZE = False ...
def sync_awards(**kwargs)
Iterates over registered recipes and possibly creates awards.
4.491918
3.85752
1.164457
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('{:<20} {:>10} users awarde...
def show_stats(**kwargs)
Shows badges stats.
4.888203
4.319981
1.131534
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.disconnect(sender=Award, ...
def reset_awards(**kwargs)
Resets badges stats.
2.192611
2.163881
1.013277
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: signals.post_save.send(sender=obj.__class__, instance=obj, created=True) ...
def bulk_create_awards(objects, batch_size=500, post_save_signal=True)
Saves award objects.
2.899979
2.884239
1.005457
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
def get_badge(self)
The related ``Badge`` object.
5.44388
5.125309
1.062156
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'): attr = getattr(self, field) ...
def create_badge(self, update=False)
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).
2.313964
2.366196
0.977926
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 exist in the database (run badgify_s...
def can_perform_awarding(self)
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``.
7.848454
5.166618
1.51907
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.slug) return (self.slug, up...
def update_badge_users_count(self)
Denormalizes ``Badge.users.count()`` into ``Bagdes.users_count`` field.
3.008474
2.939197
1.02357
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( "→ Badge %s: %d users already awarded (fetched from...
def get_already_awarded_user_ids(self, db_read=None, show_log=True)
Returns already awarded user ids and the count.
3.264299
3.035855
1.075249
db_read = db_read or self.db_read return self.user_ids.using(db_read)
def get_current_user_ids(self, db_read=None)
Returns current user ids and the count.
5.91951
4.821415
1.227754
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)) unawarded_ids_count = len(unawarded_ids)...
def get_unawarded_user_ids(self, db_read=None)
Returns unawarded user ids (need to be saved) and the count.
2.33039
2.13022
1.093967
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(current_ids)) obsolete_ids_count = len(...
def get_obsolete_user_ids(self, db_read=None)
Returns obsolete users IDs to unaward.
2.991543
2.618381
1.142516
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_ids, unawarded_ids_count = self.get_unawarded_user_ids(db_read=db_read) obsolete_ids, obsolete...
def create_awards(self, db_read=None, batch_size=None, post_save_signal=True)
Create awards.
2.433058
2.456415
0.990491
super(Command, self).add_arguments(parser) parser.add_argument('--badges', action='store', dest='badges', type=str) parser.add_argument('--db-read', action='store', ...
def add_arguments(self, parser)
Command arguments.
2.115585
2.034209
1.040004
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))
def handle_label(self, label, **options)
Command handler.
5.334638
5.107932
1.044383
# 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) suffix, degree = self.e...
def extract_suffix(self, 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.
8.74413
7.665274
1.140746
# 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 we have at least 2 name parts and t...
def reverse_last_first(self, name)
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.
7.7344
7.312753
1.057659
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 'et al' elif ',' in subject....
def compare(cls, match, subject)
Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match.
13.662296
12.23998
1.116203
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.objects.filter(user=user).select_re...
def badgify_badges(**kwargs)
Returns all badges or only awarded badges for the given user.
2.160947
1.972793
1.095375
# 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.sub(r'\bet al\b', '', name) ...
def without_extra_phrases(self)
Removes parenthethical and dashed phrases
6.260717
6.11437
1.023935
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 # amongst ou...
def kernel(self)
The 'kernel' is an attempt to get at just the most pithy words in the name
8.707442
7.767029
1.121078
if kwargs.get('allow_quoted_nicknames'): args = [ x.strip() for x in args if not re.match(r'^[(]', x) ] else: args = [ x.strip() for x in args if not re.match(r'^[("]', x) ] if len(args) > 2: self.detect_and_fix_two_part_surname(args) # set...
def new_from_tokens(self, *args, **kwargs)
Takes in a name that has been split by spaces. Names which are in [last, first] format need to be preprocessed. The nickname must be in double quotes to be recognized as such. This can take name parts in in these orders: first, middle, last, nick, suffix, honorific ...
3.395625
3.1348
1.083203
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
def detect_and_fix_two_part_surname(self, args)
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.
2.531947
2.092138
1.21022
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 = self.capitalize_and_punc...
def case_name_parts(self)
Convert all the parts of the name to the proper case... carefully!
3.432134
3.237262
1.060196
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: with s2reader.open...
def main(args=None)
Print metadata as JSON strings.
2.465989
2.396912
1.028819
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)
def open(safe_file)
Return a SentinelDataSet object.
3.428102
2.210996
1.550479
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 \ pvi_path in granule.da...
def _pvi_path(granule)
Determine the PreView Image (PVI) path inside the SAFE pkg.
3.004695
3.038995
0.988714
# 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() # Stitch string list together, adding the previously removed un...
def _granule_identifier_to_xml_name(granule_identifier)
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
5.023751
4.781621
1.050637
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 ((float(i[0]), float(i[1]))) for i in reshaped.tolist() ] ...
def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2)
Return Shapely Polygon from coordinates. - coords: list of alterating latitude / longitude coordinates - fix_geom: automatically fix geometry
2.533494
2.592911
0.977085
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.relpath( data...
def product_metadata_path(self)
Return path to product metadata XML file.
4.627635
4.27776
1.081789
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"): co...
def footprint(self)
Return product footprint.
7.120544
6.465371
1.101336
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 product_organisation....
def granules(self)
Return list of SentinelGranule objects.
4.626423
4.130805
1.119981
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 [ granule.band_...
def granule_paths(self, band_id)
Return the path of all granules of a given band.
3.527194
3.23007
1.091987
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() except AssertionError: ...
def metadata_path(self)
Determine the metadata path.
4.651969
4.360828
1.066763
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_paths[0] exc...
def tci_path(self)
Return the path to the granules TrueColorImage.
4.401165
3.985113
1.104401
image_content_qi = self._metadata.findtext( ( ), namespaces=self._nsmap) return float(image_content_qi)
def cloud_percent(self)
Return percentage of cloud coverage.
22.179291
17.898739
1.239154
# 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(searchstring) nrows,...
def footprint(self)
Find and return footprint as Shapely Polygon.
4.286966
4.082403
1.050109
polys = list(self._get_mask(mask_type="MSK_CLOUDS")) return MultiPolygon([ poly["geometry"] for poly in polys if poly["attributes"]["maskType"] == "OPAQUE" ]).buffer(0)
def cloudmask(self)
Return cloudmask as a shapely geometry.
8.158743
6.798236
1.200126
band_id = str(band_id).zfill(2) if not isinstance(band_id, str) or band_id not in BAND_IDS: raise ValueError("band ID not valid: %s" % band_id) if self.dataset.is_zip and for_gdal: zip_prefix = "/vsizip/" if absolute: granule_basepath ...
def band_path(self, band_id, for_gdal=False, absolute=False)
Return paths of given band's jp2 files for all granules.
3.212096
3.151722
1.019156
lat = TileSystem.clip(lat, TileSystem.LATITUDE_RANGE) return cos(lat * pi / 180) * 2 * pi * TileSystem.EARTH_RADIUS / TileSystem.map_size(level)
def ground_resolution(lat, level)
Gets ground res in meters / pixel
5.076504
5.017322
1.011795
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 - sin_lat)) / (4 * pi) ...
def geo_to_pixel(geo, level)
Transform from geo coordinates to pixel coordinates
2.400702
2.361874
1.01644
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 * atan(exp(-y * 2 * pi)) / pi ...
def pixel_to_geo(pixel, level)
Transform from pixel to geo coordinates
2.349746
2.30083
1.02126
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]
def tile_to_pixel(tile, centered=False)
Transform tile to pixel coordinates
4.422498
4.239505
1.043164
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: digit += 1 ...
def tile_to_quadkey(tile, level)
Transform tile coordinates to a quadkey
2.3669
2.349033
1.007606
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': tile_y |= mask ...
def quadkey_to_tile(quadkey)
Transform quadkey to tile coordinates
2.251097
2.223044
1.012619
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(params)
def authorize_url(self, state='')
return user authorize url
2.045751
1.903805
1.074559
'''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, 'redirect_uri': self.redirect_uri...
def get_token_by_code(self, code)
return origin json
2.278519
1.955733
1.165046
'''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) check_error(r) return r.json()
def refresh_token(self, refresh_token)
return origin json
3.236008
2.634183
1.228467
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'] raise YoukuError(error['code'], error['type'], ...
def check_error(response, expect_status=200)
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/...
2.467375
2.383408
1.03523
return dict((k, v) for k, v in data.items() if v is not None)
def remove_none_value(data)
remove item from dict if value is None. return new dict.
2.301556
2.658061
0.865878
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()
def find_person_by_id(self, person_id)
doc: http://open.youku.com/docs/docs?id=87
2.640742
2.213191
1.193183
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()
def find_persons_by_ids(self, person_ids)
doc: http://open.youku.com/docs/docs?id=88
2.79402
2.370008
1.178907
url = 'https://openapi.youku.com/v2/persons/by_type.json' params = { 'client_id': self.client_id, 'type': type, 'nationality': nationality, 'gender': gender, 'firstletter': firstletter, 'orderby': orderby, 'page...
def find_persons_by_type(self, type, nationality=None, gender=None, firstletter=None, orderby='view-week-count', page=1, count=20)
doc: http://open.youku.com/docs/docs?id=89
1.956747
1.803364
1.085054
#Convert input ds to string incase it is put in via function ds = str(ds) #The final character of the dataset can be a letter lettersuffix='' if re.search('[A-Za-z]$',ds): lettersuffix = ds[-1] ds = ds[:-1] openfMRI_dataset_string = '{0:06d}'.format(int(ds)) + lettersuffix ...
def get_dataset(ds,dataDir,removecompressed=1)
A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset. PARAMETERS :ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn't need to be 000212). :dataDir: where to save the data. Will get saved in 'dataDir/ope...
5.207391
4.854726
1.072644
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()
def my_info(self, access_token)
doc: http://open.youku.com/docs/doc?id=23
2.54546
2.274786
1.118989
url = 'https://openapi.youku.com/v2/users/friendship/followings.json' data = { 'client_id': self.client_id, 'page': page, 'count': count, 'user_id': user_id, 'user_name': user_name } data = remove_none_value(data) ...
def friendship_followings(self, user_id=None, user_name=None, page=1, count=20)
doc: http://open.youku.com/docs/doc?id=26
2.189891
2.097277
1.044159
url = 'https://openapi.youku.com/v2/users/friendship/create.json' data = { 'client_id': self.client_id, 'access_token': access_token, 'user_id': user_id, 'user_name': user_name } data = remove_none_value(data) r = requests....
def create_friendship(self, access_token, user_id=None, user_name=None)
doc: http://open.youku.com/docs/doc?id=28
2.044918
1.928044
1.060618
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) check_error(r) return r.json()['re...
def create_subscribe(self, access_token, show_id)
doc: http://open.youku.com/docs/doc?id=29
2.346564
2.164156
1.084286
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) check_error(r) return r.json()['res...
def cancel_subscribe(self, access_token, show_id)
doc: ??
2.369593
2.343804
1.011003