code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
table_toplevels = tuple(table_toplevels) obj = NamedDict() last_array_of_tables = None # The Name of the last array-of-tables header for toplevel in table_toplevels: if isinstance(toplevel, toplevels.AnonymousTable): obj[''] = toplevel.table_element elif isi...
def structure(table_toplevels)
Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the TOML file.
2.61859
2.555209
1.024805
from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete()
def prune_old_authorization_codes()
Removes all unused and expired authorization codes from the database.
11.74785
9.558575
1.229038
from .conf import options handlers = options.handlers for handler in handlers: handler_path = handler.split(".") name = handler_path[-2] if handler_name == name: handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1]...
def get_handler(handler_name)
Imports the module for a DOAC handler based on the string representation of the module path that is provided.
3.519675
3.326463
1.058084
from .conf import options header = "Bearer realm=\"%s\"" % (options.realm, ) if hasattr(exception, "error"): header = header + ", error=\"%s\"" % (exception.error, ) if hasattr(exception, "reason"): header = header + ", error_description=\"%s\"" % (exception.reason, ...
def request_error_header(exception)
Generates the error header for a request using a Bearer token based on a given OAuth exception.
3.291092
2.594626
1.268426
merge_func = store[style] metaclass = _DocInheritorBase metaclass.class_doc_inherit = staticmethod(merge_func) metaclass.attr_doc_inherit = staticmethod(merge_func) return metaclass if not abstract_base_class else type("abc" + metaclass.__name__, (_ABCMeta, metaclass), {})
def DocInheritMeta(style="parent", abstract_base_class=False)
A metaclass that merges the respective docstrings of a parent class and of its child, along with their properties, methods (including classmethod, staticmethod, decorated methods). Parameters ---------- style: Union[Any, Callable[[str, str], str]], optional (default: "parent") ...
5.870747
6.005009
0.977642
merge_func = store[style] decorator = _DocInheritDecorator decorator.doc_merger = staticmethod(merge_func) return decorator(parent)
def doc_inherit(parent, style="parent")
Returns a function/method decorator that, given `parent`, updates the docstring of the decorated function/method based on the specified style and the corresponding attribute of `parent`. Parameters ---------- parent : Union[str, Any] The docstring, or object of which the doc...
13.780519
16.724178
0.823988
if len(args) < 3: return self._store.pop(*args) else: raise TypeError("pop expected at most 2 arguments, got {}".format(len(args)))
def pop(self, *args)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
3.518212
3.480918
1.010714
if len(args) > 1: raise TypeError("update expected at most 1 arguments, got %d" % len(args)) for key, value in dict(*args, **kwargs).items(): self[key] = value
def update(self, *args, **kwargs)
D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
2.194251
2.328535
0.942331
self.coords = defaultPos self.velocity = r.Vector2() self.desired_position = defaultPos r.Ragnarok.get_world().Camera.pan = self.coords r.Ragnarok.get_world().Camera.desired_pan = self.coords
def set_default_pos(self, defaultPos)
Set the default starting location of our character.
6.263393
5.786743
1.082369
screen_width = world.get_backbuffer_size().X self.movement_speed = random.randrange(10, 25) # This line of code places the cloud to the right of the viewable screen, so it appears to # gradually move in from the right instead of randomally appearing on some portion of the viewa...
def __generate_location(self)
Reset the location of the cloud once it has left the viewable area of the screen.
11.76234
9.216323
1.276251
self.app = app # 注册上 self.app.blueprints.append(self)
def register_to_app(self, app)
注册到app上
11.552271
7.973296
1.44887
return bool(line) and line[0] in punctuation and line[0]*len(line) == line
def is_delimiter(line)
True if a line consists only of a single punctuation character.
9.320645
6.486969
1.436826
class Section(object): def __init__(self, header=None, body=None): self.header = header # str self.body = body # str doc_sections = OrderedDict([('', Section(header=''))]) if not doc: return doc_sections doc = cleandoc(doc) lines = iter(doc.splitline...
def parse_rest_doc(doc)
Extract the headers, delimiters, and text from reST-formatted docstrings. Parameters ---------- doc: Union[str, None] Returns ------- Dict[str, Section]
3.041027
3.027942
1.004321
prnt_sections = parse_rest_doc(prnt_doc) child_sections = parse_rest_doc(child_doc) header = prnt_sections[''] prnt_sections.update(child_sections) if not child_sections[''].body: prnt_sections[''] = header if not header.body: prnt_sections.popitem(last=False) ...
def merge_rest_docs(prnt_doc=None, child_doc=None)
See custom_inherit.style_store.reST for details.
3.200465
3.076704
1.040225
try: return func(*args, **kwargs) except Exception as e: logger.error('exc occur. e: %s, func: %s', e, func, exc_info=True) # 调用方可以通过 isinstance(e, BaseException) 来判断是否发生了异常 return e
def safe_call(func, *args, **kwargs)
安全调用
4.880692
4.602473
1.06045
@functools.wraps(func) def func_wrapper(*args, **kwargs): return safe_call(func, *args, **kwargs) return func_wrapper
def safe_func(func)
把函数变为安全的
2.028286
2.147921
0.944302
if filename is not None: content = _get_content(filename=filename) stringset = [] f = content if f.startswith(u'\ufeff'): f = f.lstrip(u'\ufeff') #regex for finding all comments in a file cp = r'(?:/\*(?P<comment>(?:[^*]|(?:\*+[^*/]))*\**)\*/)' p = re.compile(r'(?:%s[ \...
def parse_strings(content="", filename=None)
Parse an apple .strings file and create a stringset with all entries in the file. See http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPInternational/Articles/StringsFiles.html for details.
3.33124
3.330463
1.000233
self.interrupted = True if data is not None: return self.write(data) else: return True
def interrupt(self, data=None)
中断处理 :param data: 要响应的数据,不传即不响应 :return:
4.449657
4.635122
0.959987
if not file_elements: return _validate_file_elements(file_elements) # An iterator over enumerate(the non-metadata) elements iterator = PeekableIterator((element_i, element) for (element_i, element) in enumerate(file_elements) if element.type != elements.TY...
def identify(file_elements)
Outputs an ordered sequence of instances of TopLevel types. Elements start with an optional TableElement, followed by zero or more pairs of (TableHeaderElement, TableElement).
4.388095
4.101592
1.069852
tile_obj = thc.TileHeroCharacter(tile_map, gamescreen) tile_obj.load_texture("..//Textures//character.png") tile_obj.origin = r.Vector2(0, 0) tile_obj.hazard_touched_method = hazard_touched_method tile_obj.special_touched_method = special_touched_method return tile_obj
def load_character(tile_map, gamescreen)
Create an instance of the main character and return it.
6.371234
6.295156
1.012085
if not LOGBOOK_INSTALLED: return # validate log level logbook.get_level_name(log_level) if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level
def set_log_level(log_level)
Set logging level of this module. Using `logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``...
4.773522
3.922247
1.217038
if refresh_token: try: self.oauth.request_token(grant_type="refresh_token", refresh_token=refresh_token) self.refresh_token = self.oauth.refresh_token except HTTPError as e: if e.code == 401: raise Deviantart...
def auth(self, code="", refresh_token="")
Authenticates user and retrieves (and refreshes) access token :param code: code provided after redirect (authorization_code only) :param refresh_token: the refresh_token to update access_token without authorization
1.677764
1.729022
0.970354
return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope)
def auth_uri(self)
The authorzation URL that should be provided to the user
5.706229
6.010166
0.94943
response = self._req('/browse/dailydeviations') deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) return deviations
def browse_dailydeviations(self)
Retrieves Daily Deviations
4.078072
3.920099
1.040298
response = self._req('/browse/user/journals', { "username":username, "featured":featured, "offset":offset, "limit":limit }) deviations = [] for item in response['results']: d = Deviation() d.from_dict(it...
def browse_userjournals(self, username, featured=False, offset=0, limit=10)
Fetch user journals from user :param username: name of user to retrieve journals from :param featured: fetch only featured or not :param offset: the pagination offset :param limit: the pagination limit
2.721246
2.85997
0.951495
response = self._req('/browse/morelikethis/preview', { "seed":seed }) returned_seed = response['seed'] author = User() author.from_dict(response['author']) more_from_artist = [] for item in response['more_from_artist']: d = D...
def browse_morelikethis_preview(self, seed)
Fetch More Like This preview result for a seed deviation :param seed: The deviationid to fetch more like
2.405449
2.455201
0.979736
if endpoint == "hot": response = self._req('/browse/hot', { "category_path":category_path, "offset":offset, "limit":limit }) elif endpoint == "morelikethis": if seed: response = self._req('/bro...
def browse(self, endpoint="hot", category_path="", seed="", q="", timerange="24hr", tag="", offset=0, limit=10)
Fetch deviations from public endpoints :param endpoint: The endpoint from which the deviations will be fetched (hot/morelikethis/newest/undiscovered/popular/tags) :param category_path: category path to fetch from :param q: Search query term :param timerange: The timerange :param...
1.730258
1.546499
1.118822
response = self._req('/browse/categorytree', { "catpath":catpath }) categories = response['categories'] return categories
def get_categories(self, catpath="/")
Fetch the categorytree :param catpath: The category to list children of
10.168727
10.123016
1.004516
response = self._req('/browse/tags/search', { "tag_name":tag_name }) tags = list() for item in response['results']: tags.append(item['tag_name']) return tags
def search_tags(self, tag_name)
Searches for tags :param tag_name: Partial tag name to get autocomplete suggestions for
4.598573
5.533702
0.831012
response = self._req('/deviation/{}'.format(deviationid)) d = Deviation() d.from_dict(response) return d
def get_deviation(self, deviationid)
Fetch a single deviation :param deviationid: The deviationid you want to fetch
5.418353
6.334142
0.85542
response = self._req('/deviation/whofaved', get_data={ 'deviationid' : deviationid, 'offset' : offset, 'limit' : limit }) users = [] for item in response['results']: u = {} u['user'] = User() u['user'].f...
def whofaved_deviation(self, deviationid, offset=0, limit=10)
Fetch a list of users who faved the deviation :param deviationid: The deviationid you want to fetch :param offset: the pagination offset :param limit: the pagination limit
2.610846
2.631727
0.992065
response = self._req('/deviation/metadata', { 'ext_submission' : ext_submission, 'ext_camera' : ext_camera, 'ext_stats' : ext_stats, 'ext_collection' : ext_collection }, post_data={ 'deviationids[]' : deviationids }) ...
def get_deviation_metadata(self, deviationids, ext_submission=False, ext_camera=False, ext_stats=False, ext_collection=False)
Fetch deviation metadata for a set of deviations :param deviationid: The deviationid you want to fetch :param ext_submission: Return extended information - submission information :param ext_camera: Return extended information - EXIF information (if available) :param ext_stats: Return ex...
2.109568
2.153198
0.979737
response = self._req('/deviation/embeddedcontent', { 'deviationid' : deviationid, 'offset_deviationid' : offset_deviationid, 'offset' : 0, 'limit' : 0 }) deviations = [] for item in response['results']: d =...
def get_deviation_embeddedcontent(self, deviationid, offset_deviationid="", offset=0, limit=10)
Fetch content embedded in a deviation :param deviationid: The deviationid of container deviation :param offset_deviationid: UUID of embedded deviation to use as an offset :param offset: the pagination offset :param limit: the pagination limit
2.410268
2.563499
0.940226
response = self._req('/deviation/content', { 'deviationid':deviationid }) content = {} if "html" in response: content['html'] = response['html'] if "css" in response: content['css'] = response['css'] if "css_fonts...
def get_deviation_content(self, deviationid)
Fetch full data that is not included in the main devaition object The endpoint works with journals and literatures. Deviation objects returned from API contain only excerpt of a journal, use this endpoint to load full content. Any custom CSS rules and fonts applied to journal are also returned. ...
2.959788
2.745167
1.078181
response = self._req('/deviation/download/{}'.format(deviationid)) return { 'src' : response['src'], 'width' : response['width'], 'height' : response['height'], 'filesize' : response['filesize'] }
def download_deviation(self, deviationid)
Get the original file download (if allowed) :param deviationid: The deviationid you want download info for
3.432996
3.904185
0.879312
if not username and self.standard_grant_type == "authorization_code": response = self._req('/collections/folders', { "calculate_size":calculate_size, "ext_preload":ext_preload, "offset":offset, "limit":limit }) ...
def get_collections(self, username="", calculate_size=False, ext_preload=False, offset=0, limit=10)
Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each collection folder :param ext_preload: Include first 5 deviations from the folder :param offset: the p...
2.474029
2.426034
1.019783
if not username and self.standard_grant_type == "authorization_code": response = self._req('/collections/{}'.format(folderid), { "offset":offset, "limit":limit }) else: if not username: raise DeviantartError("...
def get_collection(self, folderid, username="", offset=0, limit=10)
Fetch collection folder contents :param folderid: UUID of the folder to list :param username: The user to list folders for, if omitted the authenticated user is used :param offset: the pagination offset :param limit: the pagination limit
2.939404
3.218253
0.913354
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") post_data = {} post_data['deviationid'] = deviationid if folderid: ...
def fave(self, deviationid, folderid="")
Add deviation to favourites :param deviationid: Id of the Deviation to favourite :param folderid: Optional UUID of the Collection folder to add the favourite into
6.15992
6.360134
0.968521
if not username: raise DeviantartError('No username defined.') response = self._req('/gallery/all', {'username': username, 'offset': offset, 'limit': limit}) deviations = [] ...
def get_gallery_all(self, username='', offset=0, limit=10)
Get all of a user's deviations :param username: The user to query, defaults to current user :param offset: the pagination offset :param limit: the pagination limit
3.027037
2.822588
1.072433
if not username and self.standard_grant_type == "authorization_code": response = self._req('/user/whoami') u = User() u.from_dict(response) else: if not username: raise DeviantartError("No username defined.") else: ...
def get_user(self, username="", ext_collections=False, ext_galleries=False)
Get user profile information :param username: username to lookup profile of :param ext_collections: Include collection folder info :param ext_galleries: Include gallery folder info
3.839431
3.860699
0.994491
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/whois', post_data={ "usernames":usernames }) ...
def get_users(self, usernames)
Fetch user info for given usernames :param username: The usernames you want metadata for (max. 50)
6.799578
7.157298
0.95002
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/friends/watch/{}'.format(username), post_data={ "watc...
def watch( self, username, watch={ "friend":True, "deviations":True, "journals":True, "forum_threads":True, "critiques":True, "scraps":True, "activity":True, "collections":True } )
Watch a user :param username: The username you want to watch
2.762601
3.022079
0.91414
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/friends/unwatch/{}'.format(username)) return response['s...
def unwatch(self, username)
Unwatch a user :param username: The username you want to unwatch
13.273944
14.697993
0.903113
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/friends/watching/{}'.format(username)) return response['...
def is_watching(self, username)
Check if user is being watched by the given user :param username: Check if username is watching you
12.392835
11.969934
1.03533
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") post_data = {} if user_is_artist: post_data["user_is_artist"] = user_i...
def update_user(self, user_is_artist="", artist_level="", artist_specialty="", real_name="", tagline="", countryid="", website="", bio="")
Update the users profile information :param user_is_artist: Is the user an artist? :param artist_level: If the user is an artist, what level are they :param artist_specialty: If the user is an artist, what is their specialty :param real_name: The users real name :param tagline: ...
2.263618
2.237098
1.011855
response = self._req('/user/watchers/{}'.format(username), { 'offset' : offset, 'limit' : limit }) watchers = [] for item in response['results']: w = {} w['user'] = User() w['user'].from_dict(item['user']) ...
def get_watchers(self, username, offset=0, limit=10)
Get the user's list of watchers :param username: The username you want to get a list of watchers of :param offset: the pagination offset :param limit: the pagination limit
2.581131
2.67703
0.964177
response = self._req('/user/friends/{}'.format(username), { 'offset' : offset, 'limit' : limit }) friends = [] for item in response['results']: f = {} f['user'] = User() f['user'].from_dict(item['user']) ...
def get_friends(self, username, offset=0, limit=10)
Get the users list of friends :param username: The username you want to get a list of friends of :param offset: the pagination offset :param limit: the pagination limit
2.634905
2.756473
0.955897
response = self._req('/user/statuses/', { "username" : username, 'offset' : offset, 'limit' : limit }) statuses = [] for item in response['results']: s = Status() s.from_dict(item) statuses.append(s) ...
def get_statuses(self, username, offset=0, limit=10)
Fetch status updates of a user :param username: The username you want to get a list of status updates from :param offset: the pagination offset :param limit: the pagination limit
2.727467
2.833266
0.962658
response = self._req('/user/statuses/{}'.format(statusid)) s = Status() s.from_dict(response) return s
def get_status(self, statusid)
Fetch the status :param statusid: Status uuid
6.409762
9.423888
0.680161
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/statuses/post', post_data={ "body":body, ...
def post_status(self, body="", id="", parentid="", stashid="")
Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you wish to add to the status
6.835485
6.829356
1.000897
if endpoint == "privacy": response = self._req('/data/privacy') elif endpoint == "submission": response = self._req('/data/submission') elif endpoint == "tos": response = self._req('/data/tos') else: raise DeviantartError("Unknow...
def get_data(self, endpoint="privacy")
Returns policies of DeviantArt
3.896693
3.38352
1.151668
if endpoint == "deviation": if deviationid: response = self._req('/comments/{}/{}'.format(endpoint, deviationid), { "commentid" : commentid, 'offset' : offset, 'limit' : limit, 'maxdepth' : max...
def get_comments(self, endpoint="deviation", deviationid="", commentid="", username="", statusid="", ext_item=False, offset=0, limit=10, maxdepth=0)
Fetch comments :param endpoint: The source/endpoint you want to fetch comments from (deviation/profile/status/siblings) :param deviationid: The deviationid you want to fetch :param commentid: The commentid you want to fetch :param username: The username you want to get a list of status ...
1.752208
1.686804
1.038774
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") if comment_type == "profile": response = self._req('/comments/post/profile/{}'.fo...
def post_comment(self, target, body, comment_type="profile", commentid="")
Post comment :param target: The target you want to post the comment to (username/deviation UUID/status UUID) :param body: The comment text :param comment_type: The type of entry you want to post your comment to :param commentid: The commentid you are replying to
2.785425
2.587328
1.076564
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feed', { 'folderid' : folderid, 'stac...
def get_messages(self, folderid="", stack=1, cursor="")
Feed of all messages :param folderid: The folder to fetch messages from, defaults to inbox :param stack: True to use stacked mode, false to use flat mode
4.327664
4.402337
0.983038
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/delete', post_data={ 'folderid' : folderid, ...
def delete_message(self, messageid="", folderid="", stackid="")
Delete a message or a message stack :param folderid: The folder to delete the message from, defaults to inbox :param messageid: The message to delete :param stackid: The stack to delete
7.039477
7.737648
0.90977
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feedback', { 'type' : feedbacktype, '...
def get_feedback(self, feedbacktype="comments", folderid="", stack=1, offset=0, limit=10)
Fetch feedback messages :param feedbacktype: Type of feedback messages to fetch (comments/replies/activity) :param folderid: The folder to fetch messages from, defaults to inbox :param stack: True to use stacked mode, false to use flat mode :param offset: the pagination offset :...
3.765706
3.786927
0.994396
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feedback/{}'.format(stackid), { 'offset' : offset...
def get_feedback_in_stack(self, stackid, offset=0, limit=10)
Fetch feedback messages in a stack :param stackid: Id of the stack :param offset: the pagination offset :param limit: the pagination limit
4.687982
4.950949
0.946886
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes', { 'folderid' : folderid, 'offset' : of...
def get_notes(self, folderid="", offset=0, limit=10)
Fetch notes :param folderid: The UUID of the folder to fetch notes from :param offset: the pagination offset :param limit: the pagination limit
2.754641
2.826348
0.974629
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/{}'.format(noteid)) return response
def get_note(self, noteid)
Fetch a single note :param folderid: The UUID of the note
13.34232
15.596909
0.855446
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/send', post_data={ 'to[]' : to, 'subject...
def send_note(self, to, subject="", body="", noetid="")
Send a note :param to: The username(s) that this note is to :param subject: The subject of the note :param body: The body of the note :param noetid: The UUID of the note that is being responded to
4.658154
4.554914
1.022666
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/move', post_data={ 'noteids[]' : noteids, ...
def move_notes(self, noteids, folderid)
Move notes to a folder :param noteids: The noteids to move :param folderid: The folderid to move notes to
8.544167
9.160262
0.932743
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/delete', post_data={ 'noteids[]' : noteids }...
def delete_notes(self, noteids)
Delete a note or notes :param noteids: The noteids to delete
11.159041
11.693683
0.954279
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/mark', post_data={ 'noteids[]' : noteids, ...
def mark_notes(self, noteids, mark_as)
Mark notes :param noteids: The noteids to delete :param mark_as: Mark notes as (read/unread/starred/notstarred/spam)
8.324338
8.332228
0.999053
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/folders/create', post_data={ 'title' : title, ...
def create_notes_folder(self, title, parentid="")
Create new folder :param title: The title of the folder to create :param parentid: The UUID of the parent folder
9.387401
9.624487
0.975366
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/folders/rename/{}'.format(folderid), post_data={ 'ti...
def rename_notes_folder(self, title, folderid)
Rename a folder :param title: New title of the folder :param folderid: The UUID of the folder to rename
10.223471
10.977588
0.931304
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/folders/remove/{}'.format(folderid)) return response
def delete_notes_folder(self, folderid)
Delete note folder :param folderid: The UUID of the folder to delete
13.400003
15.008411
0.892833
if get_data: request_parameter = "{}?{}".format(endpoint, urlencode(get_data)) else: request_parameter = endpoint try: encdata = urlencode(post_data, True).encode('utf-8') response = self.oauth.request(request_parameter, data=encdata) ...
def _req(self, endpoint, get_data=dict(), post_data=dict())
Helper method to make API calls :param endpoint: The endpoint to make the API call to :param get_data: data send through GET :param post_data: data send through POST
3.841492
3.964431
0.96899
self.is_active = False self.save() self.refresh_token.revoke_tokens()
def revoke_tokens(self)
Revoke the authorization token and all tokens that were generated using it.
8.797563
6.517264
1.349886
self.is_active = False self.save() for access_token in self.access_tokens.all(): access_token.revoke()
def revoke_tokens(self)
Revokes the refresh token and all access tokens that were generated using it.
4.242587
3.5562
1.193011
try: handler = EscapeFriendlyXMLGenerator(outfile, encoding, short_empty_elements=True) except TypeError: # Python 2 handler = EscapeFriendlyXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement('rss', self.rss_attributes()) ...
def write(self, outfile, encoding)
Method override to create self-closing elements. https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.feedgenerator.SyndicationFeed.write https://github.com/django/django/blob/2.0/django/utils/feedgenerator.py#L216
3.365349
2.935475
1.146441
request.auth_type = None http_authorization = request.META.get("HTTP_AUTHORIZATION", None) if not http_authorization: return auth = http_authorization.split() self.auth_type = auth[0].lower() self.auth_value = " "....
def process_request(self, request)
Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` variable, similar to the standard Django authentication.
2.769662
2.765899
1.00136
handler_path = self.handler_name.split(".") handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1])) self.handler = getattr(handler_module, handler_path[-1])()
def load_handler(self)
Load the detected handler.
3.522991
3.076707
1.145053
for handler in HANDLERS: handler_type = handler.split(".")[-2] if handler_type == self.auth_type: self.handler_name = handler return self.handler_name = None
def validate_auth_type(self)
Validate the detected authorization type against the list of handlers. This will return the full module path to the detected handler.
5.287835
3.69683
1.43037
if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) request = context['request'] current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'],...
def show_url(context, **kwargs)
Return the show feed URL with different protocol.
3.470025
3.348972
1.036147
from prettytoml.parser import parse_tokens from prettytoml.lexer import tokenize as lexer from .file import TOMLFile tokens = tuple(lexer(text, is_top_level=True)) elements = parse_tokens(tokens) return TOMLFile(elements)
def loads(text)
Parses TOML text into a dict-like object and returns it.
5.658474
5.185497
1.091212
from contoml.file.file import TOMLFile if not isinstance(value, TOMLFile): raise RuntimeError("Can only dump a TOMLFile instance loaded by load() or loads()") return value.dumps()
def dumps(value)
Dumps a data structure to TOML source code. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module.
10.162794
8.331888
1.219747
with open(file_path, 'w') as fp: fp.write(dumps(obj))
def dump(obj, file_path, prettify=False)
Dumps a data structure to the filesystem as TOML. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module.
3.312424
3.763677
0.880103
self._validate_cmds() if host is None: host = constants.SERVER_HOST if port is None: port = constants.SERVER_PORT if debug is not None: self.debug = debug workers = workers if workers is not None else 1 logger.info('Running ...
def run(self, host=None, port=None, debug=None, workers=None)
启动 :param host: 监听IP :param port: 监听端口 :param debug: 是否debug :param workers: workers数量 :return:
4.76606
5.00912
0.951476
if base == target: return decimal.Decimal(1.00) services = [yahoo, fixer, ecb] if error_log is None: error_log = _error_log for fn in services: try: return fn(base, target) except Exception as e: error_log(e) return None
def rate(base, target, error_log=None)
Get current exchange rate. :param base: A base currency :param target: Convert to the target currency :param error_log: A callable function to track the exception It parses current exchange rate from these services: 1) Yahoo finance 2) fixer.io 3) European Central Bank It...
4.533936
3.525093
1.286189
api_url = 'http://download.finance.yahoo.com/d/quotes.csv' resp = requests.get( api_url, params={ 'e': '.csv', 'f': 'sl1d1t1', 's': '{0}{1}=X'.format(base, target) }, timeout=1, ) value = resp.text.split(',', 2)[1] return decim...
def yahoo(base, target)
Parse data from Yahoo.
2.879424
2.891801
0.99572
api_url = 'http://api.fixer.io/latest' resp = requests.get( api_url, params={ 'base': base, 'symbols': target, }, timeout=1, ) data = resp.json() return decimal.Decimal(data['rates'][target])
def fixer(base, target)
Parse data from fixer.io.
2.645695
2.418136
1.094105
api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' resp = requests.get(api_url, timeout=1) text = resp.text def _find_rate(symbol): if symbol == 'EUR': return decimal.Decimal(1.00) m = re.findall(r"currency='%s' rate='([0-9\.]+)'" % symbol, text) ...
def ecb(base, target)
Parse data from European Central Bank.
3.0571
2.838427
1.07704
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) elif isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) + (vec1.w * vec2.w) else: r...
def dot(vec1, vec2)
Returns the dot product of two Vectors
1.473442
1.454921
1.01273
dot_vec = dot(vec1, vec2) mag1 = vec1.length() mag2 = vec2.length() result = dot_vec / (mag1 * mag2) return math.acos(result)
def angle(vec1, vec2)
Returns the angle between two vectors
2.552286
2.66814
0.956579
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3) \ or isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return dot(vec1, vec2) / vec2.length() * vec2.normalize_copy() else: raise ValueError("vec1 and vec2 must be Vector3 or Vector4 objects.")
def project(vec1, vec2)
Project vector1 onto vector2.
3.046323
2.83199
1.075683
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): addVec = Vector3() addVec.x = vec1.x + vec2.x addVec.y = vec1.y + vec2.y addVec.z = vec1.z + vec2.z return addVec if isinstance(vec1, Vector4) and isinstance(vec2, Vector4): addVec = Vector4() ...
def component_add(vec1, vec2)
Add each of the components of vec1 and vec2 together and return a new vector.
1.342505
1.314471
1.021327
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3) \ or isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return 2 * dot(vec1, vec2) * vec2 - vec2 else: raise ValueError("vec1 and vec2 must both be a Vector type")
def reflect(vec1, vec2)
Take vec1 and reflect it about vec2.
2.934184
2.666376
1.100439
new_vec = Vector2() new_vec.X = self.X new_vec.Y = self.Y return new_vec
def copy(self)
Create a copy of this Vector
3.509703
2.910883
1.205717
return math.sqrt((self.X * self.X) + (self.Y * self.Y))
def length(self)
Gets the length of this Vector
4.332028
3.470105
1.248385
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): dist_vec = vec2 - vec1 return dist_vec.length() else: raise TypeError("vec1 and vec2 must be Vector2's")
def distance(vec1, vec2)
Calculate the distance between two Vectors
3.149298
3.050956
1.032233
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): return ((vec1.X * vec2.X) + (vec1.Y * vec2.Y)) else: raise TypeError("vec1 and vec2 must be Vector2's")
def dot(vec1, vec2)
Calculate the dot product between two Vectors
2.567919
2.446546
1.04961
dotp = Vector2.dot(vec1, vec2) mag1 = vec1.length() mag2 = vec2.length() result = dotp / (mag1 * mag2) return math.acos(result)
def angle(vec1, vec2)
Calculate the angle between two Vector2's
2.707922
2.458863
1.10129
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): # Clamp the time value into the 0-1 range. if time < 0: time = 0 elif time > 1: time = 1 x_lerp = vec1[0] + time * (vec2[0] - vec1[0]) ...
def lerp(vec1, vec2, time)
Lerp between vec1 to vec2 based on time. Time is clamped between 0 and 1.
2.022671
2.051712
0.985845
vec = Vector2() vec.X = math.cos(math.radians(degrees)) * magnitude # Negate because y in screen coordinates points down, oppisite from what is # expected in traditional mathematics. vec.Y = -math.sin(math.radians(degrees)) * magnitude return vec
def from_polar(degrees, magnitude)
Convert polar coordinates to Carteasian Coordinates
6.637385
6.551587
1.013096
new_vec = Vector2() new_vec.X = vec1.X * vec2.X new_vec.Y = vec1.Y * vec2.Y return new_vec
def component_mul(vec1, vec2)
Multiply the components of the vectors and return the result.
2.334796
2.040229
1.144379
new_vec = Vector2() new_vec.X = vec1.X / vec2.X new_vec.Y = vec1.Y / vec2.Y return new_vec
def component_div(vec1, vec2)
Divide the components of the vectors and return the result.
2.473784
2.035852
1.21511
cpy_vec = Vector3() cpy_vec.x = self.x cpy_vec.y = self.y cpy_vec.z = self.z return cpy_vec
def copy(self)
Create a copy of the Vector
2.305276
2.043632
1.128029
vec4 = Vector4() vec4.x = self.x vec4.y = self.y vec4.z = self.z if isPoint: vec4.w = 1 else: vec4.w = 0 return vec4
def to_vec4(self, isPoint)
Converts this vector3 into a vector4 instance.
1.860839
1.650778
1.12725
vec = Vector3() vec[0] = xyz[0] vec[1] = xyz[1] vec[2] = xyz[2] return vec
def tuple_as_vec(xyz)
Generates a Vector3 from a tuple or list.
2.221395
1.732266
1.282364
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): vec3 = Vector3() vec3.x = (vec1.y * vec2.z) - (vec1.z * vec2.y) vec3.y = (vec1.z * vec2.x) - (vec1.x * vec2.z) vec3.z = (vec1.x * vec2.y) - (vec1.y * vec2.x) return vec3 else:...
def cross(vec1, vec2)
Returns the cross product of two Vectors
1.51944
1.446653
1.050314