code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
schema = self.get_schema(request, **kwargs) return schema.dump(data, many=many).data if schema else data
def to_simple(self, request, data, many=False, **kwargs)
Serialize response to simple object (list, dict).
3.984549
3.388711
1.17583
resource = await self.load(request, resource=resource, **kwargs) resource = await self.save(request, resource=resource, **kwargs) return self.to_simple(request, resource, many=isinstance(resource, list), **kwargs)
async def post(self, request, resource=None, **kwargs)
Create a resource.
3.646952
3.332299
1.094425
schema = self.get_schema(request, resource=resource, **kwargs) data = await self.parse(request) resource, errors = schema.load( data, partial=resource is not None, many=isinstance(data, list)) if errors: raise RESTBadRequest(reason='Bad request', json={'e...
async def load(self, request, resource=None, **kwargs)
Load resource from given data.
4.420773
3.79367
1.165302
if resource is None: raise RESTNotFound(reason='Resource not found') return await self.post(request, resource=resource, **kwargs)
async def put(self, request, resource=None, **kwargs)
Update a resource. --- parameters: - name: resource in: path type: string
6.077943
11.745843
0.517455
if resource is None: raise RESTNotFound(reason='Resource not found') self.collection.remove(resource)
async def delete(self, request, resource=None, **kwargs)
Delete a resource.
9.549268
7.826477
1.220123
serializer = PollPublicSerializer(self.object) response = HttpResponse( json.dumps(serializer.data), content_type="application/json" ) if "HTTP_ORIGIN" in self.request.META: response["Access-Control-Allow-Origin"] = self.request.META["HTTP_ORI...
def render_to_response(self, context, **response_kwargs)
This endpoint sets very permiscuous CORS headers. Access-Control-Allow-Origin is set to the request Origin. This allows a page from ANY domain to make a request to this endpoint. Access-Control-Allow-Credentials is set to true. This allows requesting poll data in our authenticated ...
2.510103
2.248993
1.116101
validated_data = [ dict(list(attrs.items()) + list(kwargs.items())) for attrs in self.validated_data ] if "id" in validated_data: ModelClass = self.Meta.model try: self.instance = ModelClass.objects.get(id=validated_data[...
def save(self, **kwargs)
Save and return a list of object instances.
3.732795
3.62379
1.03008
glViewport(0, 0, widthWindow, heightWindow) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(70, 1.0*widthWindow/heightWindow, 0.001, 10000.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def resize(widthWindow, heightWindow)
Setup 3D projection for window
1.629137
1.506149
1.081657
_d = {} for x in l: for k, v in x.items(): _d[k] = v return _d
def to_d(l)
Converts list of dicts to dict.
2.938236
2.368738
1.240422
return TileManager(pattern_or_root, dimensions=dimensions, distributed_dim=distributed_dim, read_only=read_only)
def tailor(pattern_or_root, dimensions=None, distributed_dim='time', read_only=False)
Return a TileManager to wrap the root descriptor and tailor all the dimensions to a specified window. Keyword arguments: root -- a NCObject descriptor. pattern -- a filename string to open a NCObject descriptor. dimensions -- a dictionary to configurate the dimensions limits.
2.75097
3.939065
0.698381
dependants = sorted( get_dependants(options.package.project_name), key=lambda n: n.lower() ) if dependants: print(*dependants, sep='\n')
def command_dependants(options)
Command launched by CLI.
4.72655
4.789702
0.986815
for package in get_installed_distributions(user_only=ENABLE_USER_SITE): if is_dependant(package, project_name): yield package.project_name
def get_dependants(project_name)
Yield dependants of `project_name`.
6.879879
6.328804
1.087074
for requirement in package.requires(): # perform case-insensitive matching if requirement.project_name.lower() == project_name.lower(): return True return False
def is_dependant(package, project_name)
Determine whether `package` is a dependant of `project_name`.
4.099091
3.771278
1.086923
r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter') j = json.loads(r.read().decode('utf-8')) return int(j.get('metadata', {}).get('rate_per_second', 300))
def get_global_rate_limit(self)
Get the global rate limit per client. :rtype: int :returns: The global rate limit for each client.
6.16141
7.196742
0.856139
def decorate(func): def rate_limited_func(self, *args, **kwargs): elapsed = time.monotonic() - self._last_time_called self.left_to_wait = self._min_interval - elapsed if self.left_to_wait > 0: time.sleep(self.left_to_wait) ...
def _rate_limited()
A rate limit decorator for limiting the number of times the decorated :class:`Miner` method can be called. Limits are set in :attr:`Miner._max_per_second`.
2.319251
2.349261
0.987226
# By default, don't cache item metadata in redis. params = {'dontcache': 1} if not params else {} requests = metadata_requests(identifiers, params, callback, self) yield from self.mine(requests)
def mine_items(self, identifiers, params=None, callback=None)
Mine metadata from Archive.org items. :param identifiers: Archive.org identifiers to be mined. :type identifiers: iterable :param params: URL parameters to send with each metadata request. :type params: dict :param callback: A callback function to be cal...
12.092699
14.855171
0.81404
# If mining ids, devote half the workers to search and half to item mining. if mine_ids: self.max_tasks = self.max_tasks/2 # When mining id's, the only field we need returned is "identifier". if mine_ids and params: params = dict((k, v) for k, v in params...
def search_requests(self, query=None, params=None, callback=None, mine_ids=None)
Mine Archive.org search results. :param query: The Archive.org search query to yield results for. Refer to https://archive.org/advancedsearch.php#raw for help formatting your query. :type query: str :param params: The URL parameters to send with each...
4.319088
4.352118
0.992411
logger.debug('Sending %r to LUIS app %s', text, self._url) r = requests.get(self._url, {'q': text}) logger.debug('Request sent to LUIS URL: %s', r.url) logger.debug( 'LUIS returned status %s with text: %s', r.status_code, r.text) r.raise_for_status() ...
def analyze(self, text)
Sends text to LUIS for analysis. Returns a LuisResult.
3.334365
2.915281
1.143755
# Enum values must be hashable to support reverse lookup. if not all(isinstance(val, collections.Hashable) for val in _values(enums)): raise EnumConstructionException('All enum values must be hashable.') # Cheating by maintaining a copy of original dict for iteration b/c iterators are hard. ...
def enum(**enums)
A basic enum implementation. Usage: >>> MY_ENUM = enum(FOO=1, BAR=2) >>> MY_ENUM.FOO 1 >>> MY_ENUM.BAR 2
6.464969
6.994537
0.924288
return [m.choicify(value_field=value_field, display_field=display_field) for m in cls.members()]
def choices(cls, value_field='canonical_name', display_field='display_name')
DEPRECATED Returns a list of 2-tuples to be used as an argument to Django Field.choices Implementation note: choices() can't be a property See: http://www.no-ack.org/2011/03/strange-behavior-with-properties-on.html http://utcc.utoronto.ca/~cks/space/blog/python/UsingMet...
4.413102
5.533419
0.797536
langs = self.get_languages() result = [] # get the previous and actual values # in case it's and "add" operation previous values will be empty previous_values, actual_values = self.get_previous_and_current_values(instance) # extract the differences dif...
def create_translation_tasks(self, instance)
Creates the translations tasks from the instance and its translatable children :param instance: :return:
6.126648
6.136221
0.99844
self.log('differences UPDATING: {}'.format(differences)) object_name = '{} - {}'.format(self.app_label, self.instance.master._meta.verbose_name) lang = self.instance.language_code object_pk = self.instance.master.pk for field in differences: value = getatt...
def update_task(self, differences)
Updates a task as done if we have a new value for this alternative language :param differences: :return:
4.154922
3.899843
1.065407
translated_field_names = self._get_translated_field_names(instance.master) if instance.pk: try: previous_obj = instance._meta.model.objects.get(pk=instance.pk) previous_values = self.get_obj_values(previous_obj, translated_field_names) exc...
def get_previous_and_current_values(self, instance)
Obtain the previous and actual values and compares them in order to detect which fields has changed :param instance: :param translation: :return:
2.235828
2.332931
0.958377
# set of translated fields to list fields = list(translated_field_names) values = {field: getattr(obj, field) for field in fields} return values
def get_obj_values(obj, translated_field_names)
get the translated field values from translatable fields of an object :param obj: :param translated_field_names: :return:
5.157415
5.969195
0.864005
hvad_internal_fields = ['id', 'language_code', 'master', 'master_id', 'master_id'] translated_field_names = set(model_instance._translated_field_names) - set(hvad_internal_fields) return translated_field_names
def _get_translated_field_names(model_instance)
Get the instance translatable fields :return:
4.108313
4.798974
0.856082
if not self.master: raise Exception('TransManager - No master set') item_languages = self.get_languages_from_item(self.ct_master, self.master) languages = self.get_languages_from_model(self.ct_master.app_label, self.ct_master.model) if not languages: l...
def get_languages(self, include_main=False)
Get all the languages except the main. Try to get in order: 1.- item languages 2.- model languages 3.- application model languages # 4.- default languages :param master: :param include_main: :return:
3.441795
2.79286
1.232355
result = {} users = TransUser.objects.filter(active=True).select_related('user') for user in users: for lang in user.languages.all(): if lang.code not in result: result[lang.code] = set() result[lang.code].add(user) ...
def get_users_indexed_by_lang()
Return all the translator users indexed by lang :return:
2.680107
2.572678
1.041758
try: item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get() languages = [lang.code for lang in item_lan.languages.all()] return languages except TransItemLanguage.DoesNotExist: return []
def get_languages_from_item(ct_item, item)
Get the languages configured for the current item :param ct_item: :param item: :return:
3.081271
3.132399
0.983678
try: mod_lan = TransModelLanguage.objects.filter(model='{} - {}'.format(app_label, model_label)).get() languages = [lang.code for lang in mod_lan.languages.all()] return languages except TransModelLanguage.DoesNotExist: return []
def get_languages_from_model(app_label, model_label)
Get the languages configured for the current model :param model_label: :param app_label: :return:
4.052781
4.400704
0.920939
try: mod_lan = TransApplicationLanguage.objects.filter(application=app_label).get() languages = [lang.code for lang in mod_lan.languages.all()] return languages except TransApplicationLanguage.DoesNotExist: return []
def get_languages_from_application(app_label)
Get the languages configured for the current application :param app_label: :return:
4.367692
4.950899
0.882202
try: main_language = TransLanguage.objects.filter(main_language=True).get() return main_language.code except TransLanguage.DoesNotExist: return TM_DEFAULT_LANGUAGE_CODE
def get_main_language()
returns the main language :return:
4.240517
4.845845
0.875083
if self.master_class and self.instance_class: logger.info('{0} - {1} - {2} - {3} - lang: {4} msg: {5}'.format( self.ct_master.app_label, self.ct_master.model, self.instance_class, self.instance.language_code, self.instance.pk, msg) ) elif ...
def log(self, msg)
Log a message information adding the master_class and instance_class if available :param msg: :return:
3.720339
3.222099
1.154632
if not isinstance(item, TranslatableModel): return self.log('gonna parse fields: {}'.format(fields)) with self.lock: result = [] if trans_instance: # get the values from the instance that is being saved, values not saved yet ...
def create_from_item(self, languages, item, fields, trans_instance=None)
Creates tasks from a model instance "item" (master) Used in the api call :param languages: :param item: :param fields: :param trans_instance: determines if we are in bulk mode or not. If it has a value we're processing by the signal trigger, if not we're processi...
3.012391
2.949635
1.021276
try: # get from the instance object_field_label = trans._meta.get_field_by_name(field)[0].verbose_name except Exception: try: # get from the class object_field_label = self.sender._meta.get_field_by_name(field)[0].verbose_name ...
def get_field_label(self, trans, field)
Get the field label from the _meta api of the model :param trans: :param field: :return:
3.406824
3.233032
1.053755
collector = NestedObjects(using='default') collector.collect([obj]) object_list = collector.nested() items = self.get_elements(object_list) # avoid first object because it's the main object return items[1:]
def get_translatable_children(self, obj)
Obtain all the translatable children from "obj" :param obj: :return:
7.688292
8.441141
0.910812
result = [] for item in object_list: if isinstance(item, list): result += self.get_elements(item) elif isinstance(item, TranslatableModel): result.append(item) return result
def get_elements(self, object_list)
Recursive method to iterate the tree of children in order to flatten it :param object_list: :return:
2.62237
2.659344
0.986096
# get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) new_langs = [lang for lang in qs] if not new_langs: return mod_lan, created = TransModelLanguage.objects.get_or_create( model='{} - {}'....
def update_model_languages(self, model_class, languages)
Update the TransModelLanguages model with the selected languages :param model_class: :param languages: :return:
3.237385
3.045692
1.062939
# get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) new_langs = [lang for lang in qs] if not new_langs: return ct_item = ContentType.objects.get_for_model(item) item_lan, created = TransItemL...
def add_item_languages(self, item, languages)
Update the TransItemLanguage model with the selected languages :param item: :param languages: :return:
3.637827
3.291051
1.105369
# get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__in=languages) remove_langs = [lang for lang in qs] if not remove_langs: return ct_item = ContentType.objects.get_for_model(item) item_lan, created = Tran...
def remove_item_languages(self, item, languages)
delete the selected languages from the TransItemLanguage model :param item: :param languages: :return:
3.220462
2.946509
1.092975
try: translation = get_translation(instance, lang) except (AttributeError, ObjectDoesNotExist): translation = None return translation
def get_translation_from_instance(instance, lang)
Get the translation from the instance in a specific language, hits the db :param instance: :param lang: :return:
3.259793
4.04297
0.806287
if not self.master: self.set_master(item) if not languages: languages = self.get_languages() result_ids = [] # first process main object fields = self._get_translated_field_names(item) tasks = self.create_from_item(languages, item, fie...
def create_translations_for_item_and_its_children(self, item, languages=None)
Creates the translations from an item and defined languages and return the id's of the created tasks :param item: (master) :param languages: :return:
2.873161
2.625869
1.094175
self.log('--- Deleting translations ---') if not self.master: self.set_master(item) object_name = '{} - {}'.format(item._meta.app_label.lower(), item._meta.verbose_name) object_class = item.__class__.__name__ object_pk = item.pk filter_by = { ...
def delete_translations_for_item_and_its_children(self, item, languages=None)
deletes the translations task of an item and its children used when a model is not enabled anymore :param item: :param languages: :return:
3.290251
3.251599
1.011887
if request.method == 'POST': form = blast_form(request.POST) if form.is_valid(): query_file_object_tmp = form.cleaned_data['sequence_in_form'] evalue = float(form.cleaned_data['evalue_in_form']) word_size = int(form.cleaned_data['word_size_in_form']) ...
def blast(request, blast_form, template_init, template_result, blast_commandline, sample_fasta_path, extra_context=None)
Process blastn/tblastn (blast+) query or set up initial blast form.
3.311702
3.312361
0.999801
for node in self.node_children(self.root()): yield from self._visit_registry(node, self._rootkey)
def keys(self)
Iterates over the hive's keys. Yields WinRegKey namedtuples containing: path: path of the key "RootKey\\Key\\..." timestamp: date and time of last modification values: list of values (("ValueKey", "ValueType", ValueValue), ... )
15.604317
15.9561
0.977953
return codecs.decode( codecs.encode(self.value_value(value)[1], 'base64'), 'utf8')
def _value_data(self, value)
Parses binary and unidentified values.
8.655084
7.504111
1.153379
if not args: return [] # remove duplicates from first list whilst preserving order base = list(OrderedDict.fromkeys(args[0])) if len(args) == 1: return base else: others = set(args[1]).intersection(*args[2:]) return [e for e in base if e in others]
def intersection(*args)
Return the intersection of lists, using the first list to determine item order
4.029405
3.754003
1.073362
if not args: return [] base = args[0] for other in args[1:]: base.extend(other) return list(OrderedDict.fromkeys(base))
def union(*args)
Return the union of lists, ordering by first seen in any list
3.31742
2.802623
1.183684
# avoid things that could be mistaken ex: 'I' and '1' letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" return "".join([random.choice(letters) for _ in range(length)])
def random_string(length)
Generates a random alphanumeric string
5.040413
5.427019
0.928763
return {k: v for k, v in d.items() if k in keys}
def filter_dict(d, keys)
Creates a new dict from an existing dict that only has the given keys
2.513217
2.648983
0.948748
if not recalculate: cached = cache.get(cache_key) if cached is not None: return json.loads(cached) calculated = calculate() cache.set(cache_key, json.dumps(calculated), cache_ttl) return calculated
def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False)
Gets the result of a method call, using the given key and TTL as a cache
2.012612
2.233653
0.901041
if not recalculate and hasattr(obj, attr_name): return getattr(obj, attr_name) calculated = calculate() setattr(obj, attr_name, calculated) return calculated
def get_obj_cacheable(obj, attr_name, calculate, recalculate=False)
Gets the result of a method call, using the given object and attribute name as a cache
2.198109
2.677843
0.820851
seconds = calendar.timegm(dt.utctimetuple()) return seconds * 1000 + int(dt.microsecond / 1000)
def datetime_to_ms(dt)
Converts a datetime to a millisecond accuracy timestamp
2.581633
2.537732
1.017299
dt = datetime.datetime.utcfromtimestamp(ms / 1000) return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
def ms_to_datetime(ms)
Converts a millisecond accuracy timestamp to a datetime
2.050013
2.014241
1.01776
if not d: d = timezone.now() start = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0) end = start + relativedelta(months=1) return start, end
def get_month_range(d=None)
Gets the start (inclusive) and end (exclusive) datetimes of the current month in the same timezone as the given date
2.003011
1.997001
1.003009
it = iter(iterable) item = list(islice(it, size)) while item: yield item item = list(islice(it, size))
def chunks(iterable, size)
Splits a very large list into evenly sized chunks. Returns an iterator of lists that are no more than the size passed in.
1.995592
2.295728
0.869263
if keys or ignore_none_values: d1 = {k: v for k, v in d1.items() if (keys is None or k in keys) and (v is not None or not ignore_none_values)} d2 = {k: v for k, v in d2.items() if (keys is None or k in keys) and (v is not None or not ignore_none_values)} return d1 == d2
def is_dict_equal(d1, d2, keys=None, ignore_none_values=True)
Compares two dictionaries to see if they are equal :param d1: the first dictionary :param d2: the second dictionary :param keys: the keys to limit the comparison to (optional) :param ignore_none_values: whether to ignore none values :return: true if the dictionaries are equal, else false
1.520397
1.679871
0.905068
matches = find_owners(options.file.name) if matches: print(*matches, sep='\n')
def command_locate(options)
Command launched by CLI.
10.339934
10.495043
0.985221
abspath = os.path.abspath(path) packages = search_packages_info( sorted((d.project_name for d in get_installed_distributions(user_only=ENABLE_USER_SITE)), key=lambda d: d.lower())) return [p['name'] for p in packages if is_owner(p, abspath)]
def find_owners(path)
Return the package(s) that file belongs to.
6.269743
6.235453
1.005499
try: files = package['files'] location = package['location'] except KeyError: return False paths = (os.path.abspath(os.path.join(location, f)) for f in files) return abspath in paths
def is_owner(package, abspath)
Determine whether `abspath` belongs to `package`.
3.848917
3.659816
1.051669
newurl = compat.urljoin(self.url, compat.quote(foldername), False) params = params or {} file_data = file_data or {} # Add the key-value pairs sent in params to query string if they # are so defined. query_dict = {} url_tuple = compat.urlsplit(newurl) ...
def _get_subfolder(self, foldername, returntype, params=None, file_data=None)
Return an object of the requested type with the path relative to the current object's URL. Optionally, query parameters may be set.
5.375353
5.32198
1.010029
urlparts = self._url if self.__post__: urlparts = list(urlparts) urlparts[3] = '' # Clear out query string on POST if self.__token__ is not None: # But not the token urlparts[3] = compat.urlencode({'token': self.__token__}) return comp...
def url(self)
The URL as a string of the resource.
5.588245
5.492411
1.017448
if self.__urldata__ is Ellipsis or self.__cache_request__ is False: if self._file_data: # Special-case: do a multipart upload if there's file data self.__post__ = True boundary = "-"*12+str(uuid.uuid4())+"$" multipart_data = ''...
def _contents(self)
The raw contents of the URL as fetched, this is done lazily. For non-lazy fetching this is accessed in the object constructor.
3.034198
2.959835
1.025124
if self.__has_json__: if self.__cache_request__: if self.__json_struct__ is Ellipsis: if self._contents is not Ellipsis: self.__json_struct__ = json.loads( compat.ensure_string(self._conte...
def _json_struct(self)
The json data structure in the URL contents, it will cache this if it makes sense so it doesn't parse over and over.
5.958145
5.351608
1.113337
"Get this object's parent" if self._parent: return self._parent # auto-compute parent if needed elif getattr(self, '__parent_type__', None): return self._get_subfolder('..' if self._url[2].endswith('/') else '.', self.__...
def parent(self)
Get this object's parent
7.174396
7.273603
0.986361
if hasattr(subclass, '__service_type__'): cls._service_type_mapping[subclass.__service_type__] = subclass if subclass.__service_type__: setattr(subclass, subclass.__service_type__, property(lambda x: x)) ret...
def _register_service_type(cls, subclass)
Registers subclass handlers of various service-type-specific service implementations. Look for classes decorated with @Folder._register_service_type for hints on how this works.
3.51794
3.682371
0.955347
"Give the list of services available in this folder." return set([service['name'].rstrip('/').split('/')[-1] for service in self._json_struct.get('services', [])])
def servicenames(self)
Give the list of services available in this folder.
11.783945
7.74598
1.521298
"Returns a list of Service objects available in this folder" return [self._get_subfolder("%s/%s/" % (s['name'].rstrip('/').split('/')[-1], s['type']), self._service_type_mapping.get(s['type'], Service)) for s in self._json_struct.get('services', [])]
def services(self)
Returns a list of Service objects available in this folder
7.74856
6.325248
1.225021
if not self._url[2].endswith('/'): self._url[2] += '/' return RestURL.url.__get__(self)
def url(self)
The URL as a string of the resource.
8.207268
7.103111
1.155447
if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') outfile.write(self._contents)
def save(self, outfile)
Save the image data to a file or file-like object
4.53427
4.246764
1.0677
if not inSR: if Geometry: inSR = Geometry.spatialReference out = self._get_subfolder("./query", JsonResult, { 'text': text, 'geometry': geometry, ...
def QueryLayer(self, text=None, Geometry=None, inSR=None, spatialRel='esriSpatialRelIntersects', where=None, outFields=None, returnGeometry=None, outSR=None, objectIds=None, time=None, maxAllowableOffset=None, returnIdsOnly=None)
The query operation is performed on a layer resource. The result of this operation is a resultset resource. This resource provides information about query results including the values for the fields requested by the user. If you request geometry information, the geometry of e...
4.029955
4.263172
0.945295
time_info = self._json_struct.get('timeInfo', {}) if not time_info: return None time_info = time_info.copy() if 'timeExtent' in time_info: time_info['timeExtent'] = utils.timetopythonvalue( time_info['ti...
def timeInfo(self)
Return the time info for this Map Service
4.515645
3.726065
1.211907
if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') assert hasattr(outfile, 'write') and callable(outfile.write), \ "Expect a file or file-like object with a .write() method" outfile.write(self.data)
def save(self, outfile)
Save the image data to a file or file-like object
3.256613
2.992198
1.088368
# convert x['location'] to a point from a json point struct def cditer(): for candidate in self._json_struct['candidates']: newcandidate = candidate.copy() newcandidate['location'] = \ geometry.fromJson(newcandidate['location']) ...
def candidates(self)
A list of candidate addresses (as dictionaries) from a geocode operation
10.544249
10.517269
1.002565
"Returns a dict of outputs from the GPTask execution." if self._results is None: results = self._json_struct['results'] def result_iterator(): for result in results: datatype = None conversion = None for ...
def results(self)
Returns a dict of outputs from the GPTask execution.
4.980614
4.039457
1.232991
fp = self.__expandparamstodict(params, kw) return self._get_subfolder('execute/', GPExecutionResult, fp)
def Execute(self, *params, **kw)
Synchronously execute the specified GP task. Parameters are passed in either in order or as keywords.
37.175591
35.39743
1.050234
fp = self.__expandparamstodict(params, kw) return self._get_subfolder('submitJob/', GPJob, fp)._jobstatus
def SubmitJob(self, *params, **kw)
Asynchronously execute the specified GP task. This will return a Geoprocessing Job object. Parameters are passed in either in order or as keywords.
43.215176
40.962959
1.054982
if isinstance(outfile, compat.string_type): outfile = open(outfile, 'wb') outfile.write(compat.urllib2.urlopen(self.href).read())
def save(self, outfile)
Save the image data to a file or file-like object
4.548571
4.401082
1.033512
raise NotImplementedError()
def SolveClosestFacility(self, facilities=None, incidents=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, ...
The solve operation is performed on a network layer resource of type closest facility.
102.538719
273.194031
0.375333
raise NotImplementedError()
def SolveServiceArea(self, facilities=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, defaultBreaks=None, excludeSourcesF...
The solve operation is performed on a network layer resource of type service area (layerType is esriNAServerServiceArea).
82.719658
248.221588
0.333249
def ptlist_as_semilist(lst): if isinstance(lst, geometry.Point): lst = [lst] if isinstance(lst, (list, tuple)): return ";".join(','.join(str(x) for x in pt) for pt in lst) return lst if self.layerType != "esriNAServerRouteLayer...
def Solve(self, stops=None, barriers=None, returnDirections=None, returnRoutes=None, returnStops=None, returnBarriers=None, outSR=None, ignoreInvalidLocations=None, outputLines=None, findBestSequence=None, preserveFirstStop=None, preserveLastStop=None, useTimeWind...
The solve operation is performed on a network layer resource. At 9.3.1, the solve operation is supported only on the route layer. Or specifically, on a network layer whose layerType is esriNAServerRouteLayer. You can provide arguments to the solve route operation as query ...
1.966012
1.873868
1.049173
out = self._get_subfolder("./queryRelatedRecords", JsonResult, { 'objectIds': objectIds, 'relationshipId': ...
def QueryRelatedRecords(self, objectIds=None, relationshipId=None, outFields=None, definitionExpression=None, returnGeometry=None, outSR=None)
The query operation is performed on a feature service layer resource. The result of this operation are featuresets grouped by source layer / table object IDs. Each featureset contains Feature objects including the values for the fields requested by the user. For related layer...
4.723289
5.919334
0.797943
fd = {'features': ",".join(json.dumps( feature._json_struct_for_featureset) for feature in features)} return self._get_subfolder("./updateFeatures", JsonPostResult, fd)
def UpdateFeatures(self, features)
This operation updates features to the associated feature layer or table (POST only). The update features operation is performed on a feature service layer resource. The result of this operation is an array of edit results. Each edit result identifies a single feature and ind...
20.818945
19.365295
1.075065
gt = geometry.__geometry_type__ if sr is None: sr = geometry.spatialReference.wkid geo_json = json.dumps(Geometry._json_struct_without_sr) return self._get_subfolder("./deleteFeatures", JsonPostResult, { 'objectIds'...
def DeleteFeatures(self, objectIds=None, where=None, geometry=None, inSR=None, spatialRel=None)
This operation deletes features in a feature layer or table (POST only). The delete features operation is performed on a feature service layer resource. The result of this operation is an array of edit results. Each edit result identifies a single feature and indicates if the...
7.537293
7.556413
0.99747
add_str, update_str = None, None if adds: add_str = ",".join(json.dumps( feature._json_struct_for_featureset) for feature in adds) if updates: update_str = ",".join(json.dumps( ...
def ApplyEdits(self, adds=None, updates=None, deletes=None)
This operation adds, updates and deletes features to the associated feature layer or table in a single call (POST only). The apply edits operation is performed on a feature service layer resource. The result of this operation are 3 arrays of edit results (for adds, updates an...
5.480461
4.925842
1.112594
try: # result_ids = [] manager = Manager() for item in self.model_class.objects.language(manager.get_main_language()).filter(pk__in=self.ids).all(): create_translations_for_item_and_its_children.delay(self.model_class, item.pk, self.languages, ...
def save(self, **kwargs)
Method that creates the translations tasks for every selected instance :param kwargs: :return:
5.2974
4.830071
1.096754
version_py = os.path.join(os.path.dirname(__file__), 'deepgram', 'version.py') with open(version_py, 'r') as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip().replace('"', '') raise ValueError('Failed to parse version from: {}'.format(version_py))
def get_version()
Gets the current version of the package.
2.346769
2.403863
0.976249
config = {} s = os.environ.get(env, default) if s: config = parse(s) overrides = dict([(k.upper(), v) for k, v in overrides.items()]) config.update(overrides) return config
def config(env=DEFAULT_ENV, default=None, **overrides)
Returns configured REDIS dictionary from REDIS_URL.
3.166415
2.697663
1.173762
config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] # Update with environment configuration. config.update({ "DB": int(path or 0), "PASSWORD": url.password or None, "HOST": url.hostname or "localho...
def parse(url)
Parses a database URL.
4.027837
3.651312
1.103121
try: return dict(filesystem.checksums('/')) except RuntimeError: results = {} logging.warning("Error hashing disk %s contents, iterating over files.", filesystem.disk_path) for path in filesystem.nodes('/'): try: regular ...
def hash_filesystem(filesystem, hashtype='sha1')
Utility function for running the files iterator at once. Returns a dictionary. {'/path/on/filesystem': 'file_hash'}
5.408306
5.444654
0.993324
if self.osname == 'windows': return '{}:\\'.format( self._handler.inspect_get_drive_mappings(self._root)[0][0]) else: return self._handler.inspect_get_mountpoints(self._root)[0][0]
def fsroot(self)
Returns the file system root.
6.495861
5.911174
1.098912
self._handler.add_drive_opts(self.disk_path, readonly=True) self._handler.launch() for mountpoint, device in self._inspect_disk(): if readonly: self._handler.mount_ro(device, mountpoint) else: self._handler.mount(device, mountpoin...
def mount(self, readonly=True)
Mounts the given disk. It must be called before any other method.
5.513901
5.511772
1.000386
roots = self._handler.inspect_os() if roots: self._root = roots[0] return sorted(self._handler.inspect_get_mountpoints(self._root), key=lambda m: len(m[0])) else: raise RuntimeError("No OS found on the given disk image.")
def _inspect_disk(self)
Inspects the disk and returns the mountpoints mapping as a list which order is the supposed one for correct mounting.
7.314198
6.249993
1.170273
self._handler.download(posix_path(source), destination)
def download(self, source, destination)
Downloads the file on the disk at source into destination.
18.410624
16.706312
1.102016
path = posix_path(path) yield from (self.path(path, e) for e in self._handler.find(path))
def nodes(self, path)
Iterates over the files and directories contained within the disk starting from the given path. Yields the path of the nodes.
11.076835
13.416358
0.825622
return self._handler.checksum(hashtype, posix_path(path))
def checksum(self, path, hashtype='sha1')
Returns the checksum of the given path.
15.335713
14.049136
1.091577
with NamedTemporaryFile(buffering=0) as tempfile: self._handler.checksums_out(hashtype, posix_path(path), tempfile.name) yield from ((self.path(f[1].lstrip('.')), f[0]) for f in (l.decode('utf8').strip().split(None...
def checksums(self, path, hashtype='sha1')
Iterates over the files hashes contained within the disk starting from the given path. The hashtype keyword allows to choose the file hashing algorithm. Yields the following values: "C:\\Windows\\System32\\NTUSER.DAT", "hash" for windows "/home/user/text.txt", "hash" f...
6.820632
8.488552
0.803509
self.listening = True try: self.service_backend.listen() except AuthenticationError: self.listening = False raise else: self.listening = False
def listen(self)
Listen/Connect to message service loop to start receiving messages. Do not include in constructor, in this way it can be included in tasks
4.990237
4.413979
1.130553
chats_attended = [] pending_chats = Chat.pending.all() for pending_chat in pending_chats: free_agent = self.strategy.free_agent() if free_agent: pending_chat.attend_pending(free_agent, self) pending_chat.save() cha...
def attend_pendings(self)
Check all chats created with no agent assigned yet. Schedule a timer timeout to call it.
3.651376
3.056797
1.194511
chats_terminated = [] live_chats = Chat.live.all() for live_chat in live_chats: if live_chat.is_obsolete(self.time_obsolete_offset): live_chat.terminate() live_chat.save() chats_terminated.append(live_chat) return chats...
def terminate_obsolete(self)
Check chats can be considered as obsolete to terminate them
3.491609
2.935974
1.189251
try: live_chat = Chat.live.get( Q(agent__id_service=contact_id_service) | Q(asker__id_service=contact_id_service)) except ObjectDoesNotExist: self._new_chat_processing(message_id_service, contact_id_service, content) else: ...
def on_message(self, message_id_service, contact_id_service, content)
To use as callback in message service backend
3.514308
3.686462
0.953301