code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from .http import JsonResponse
response = {}
response["error"] = exception.error
response["error_description"] = exception.reason
return JsonResponse(response, status=getattr(exception, 'code', 400)) | def render_exception_js(self, exception) | Return a response with the body containing a JSON-formatter version of the exception. | 5.406857 | 4.561251 | 1.185389 |
for arg in args:
setattr(self, arg, dict.get(arg, None))
if hasattr(self, "verify_" + arg):
func = getattr(self, "verify_" + arg)
func() | def verify_dictionary(self, dict, *args) | Based on a provided `dict`, validate all of the contents of that dictionary that are
provided.
For each argument provided that isn't the dictionary, this will set the raw value of
that key as the instance variable of the same name. It will then call the verification
function named `ver... | 3.233978 | 2.47174 | 1.308381 |
from .models import Client
from .exceptions.invalid_client import ClientDoesNotExist
from .exceptions.invalid_request import ClientNotProvided
if self.client_id:
try:
self.client = Client.objects.for_id(self.client_id)
# Catching also Va... | def verify_client_id(self) | Verify a provided client id against the database and set the `Client` object that is
associated with it to `self.client`.
TODO: Document all of the thrown exceptions. | 4.654906 | 4.005681 | 1.162076 |
if self.stream.closed():
return False
if isinstance(data, self.app.box_class):
# 打包
data = data.pack()
elif isinstance(data, dict):
data = self.app.box_class(data).pack()
self.app.events.before_response(self, data)
for bp... | def write(self, data) | 发送数据 True: 成功 else: 失败 | 3.084325 | 2.927308 | 1.053639 |
request = self.app.request_class(self, data)
self._handle_request(request) | def _on_read_complete(self, data) | 数据获取结束 | 8.152254 | 7.421925 | 1.098402 |
if self.timer:
if force:
# 如果已经存在,那么先要把现在的清空
self.clear()
else:
# 已经存在的话,就返回了
return
def callback_wrapper():
# 必须要确定,这次调用就是这个timer引起的
if self.timer == timer:
self.ti... | def set(self, interval, callback, repeat=False, force=True) | 添加timer | 6.87667 | 6.537861 | 1.051823 |
length = self.length()
if length > 0:
self.X /= length
self.Y /= length
else:
print "Length 0, cannot normalize." | def normalize(self) | Gets the normalized Vector | 4.758176 | 4.320819 | 1.101221 |
vlength = self.length()
#Make sure the length isn't 0
if vlength > 0:
self.x /= vlength
self.y /= vlength
self.z /= vlength
else:
return Vector3(0, 0, 0) | def normalize(self) | Normalizes this Vector | 3.497949 | 2.816528 | 1.241936 |
for index, row in enumerate(self.dta):
if row[index] == 1:
for num, element in enumerate(row):
if num != index:
if element != 0:
return False
else:
return False
retur... | def is_identity() | Check to see if this matrix is an identity matrix. | 3.975598 | 3.549854 | 1.119933 |
global world
self.__is_running = True
while(self.__is_running):
#Our game loop
#Catch our events
self.__handle_events()
#Update our clock
self.__clock.tick(self.preferred_fps)
elapsed_milliseconds = self.__clock.get_... | def run(self) | Start the game loop | 4.735122 | 4.496468 | 1.053076 |
obj_to_return = None
if self.queue.count > 0:
obj_to_return = self.__dequeue()
else:
#The queue is empty, generate a new item.
self.__init_object()
object_to_return = self.__dequeue()
self.active_objects += 1
return obj_to_... | def request_object(self) | Grab an object from the pool. If the pool is empty, a new object will be generated and returned. | 5.002933 | 3.743857 | 1.336304 |
self.image = image.convert_alpha()
self.untransformed_image = self.image.copy()
## self.rect.x = 0
## self.rect.y = 0
## self.rect.width = self.image.get_width()
## self.rect.height = self.image.get_height()
self.source.x = 0
self.source.y = 0
... | def apply_texture(self, image) | Place a preexisting texture as the sprite's texture. | 2.006609 | 1.978256 | 1.014332 |
#Set the new location of the origin, as the surface size may increase with rotation
self.__origin.X = self.image.get_width() * self.__untransformed_nor_origin.X
self.__origin.Y = self.image.get_height() * self.__untransformed_nor_origin.Y
## #Update the size of the rectangle
## ... | def __resize_surface_extents(self) | Handles surface cleanup once a scale or rotation operation has been performed. | 5.422318 | 5.251556 | 1.032516 |
x = size_to_scale_from[0] * self.__scale[0]
y = size_to_scale_from[1] * self.__scale[1]
scaled_value = (int(x), int(y))
## #Find out what scaling technique we should use.
## if self.image.get_bitsize >= 24:
## #We have sufficient bit depth to run smooth scale
#... | def __execute_scale(self, surface, size_to_scale_from) | Execute the scaling operation | 4.150411 | 4.068653 | 1.020094 |
if isinstance(other, BoundingCircle):
#Calculate the distance between two circles.
distance = Vector2.distance(self.coords, other.coords)
#Check to see if the sum of thier radi are greater than or equal to the distance.
radi_sum = self.radius + other.rad... | def is_colliding(self, other) | Check to see if two circles are colliding. | 4.07096 | 3.724484 | 1.093026 |
global collidable_objects
colliding = []
for obj in collidable_objects:
#Make sure we don't check ourself against ourself.
if obj is not collision_object:
if collision_object.is_colliding(obj):
#A collision has been detected. A... | def query_all_collisions(collision_object) | Check for and return the full list of objects colliding with collision_object | 3.857249 | 3.616672 | 1.066519 |
global collidable_objects
if self.collision_depth == self.SHALLOW_DEPTH:
for obj in collidable_objects:
collision = self.query_collision(obj)
if collision is not None:
#Execute the reactions for both of the colliding objects.
... | def run_brute(self) | A nightmare if looked at by a performance standpoint, but it gets the job done,
at least for now.
Checks everything against everything and handles all collision reactions. | 2.916941 | 2.697887 | 1.081195 |
self.input_focus = StateTypes.KEYBOARD
self.move_up_button = move_up
self.move_down_button = move_down
self.select_button = select | def set_keyboard_focus(self, move_up, move_down, select) | Set the keyboard as the object that controls the menu.
move_up is from the pygame.KEYS enum that defines what button causes the menu selection to move up.
move_down is from the pygame.KEYS enum that defines what button causes the menu selection to move down.
select is from the pygame.KEYS enum t... | 3.256376 | 3.425255 | 0.950696 |
for button in self.gui_buttons:
was_hovering = button.is_mouse_hovering
button.update(milliseconds)
#Provides capibilities for the mouse to select a button if the mouse is the focus of input.
if was_hovering == False and button.is_mouse_hovering:
... | def __update_mouse(self, milliseconds) | Use the mouse to control selection of the buttons. | 6.272583 | 5.795328 | 1.082352 |
print "Collision"
if tileMapObj.can_warp:
#Check to see if we need to load a different tile map
if self.map_association != self.exitWarp.map_association:
#Load the new tile map.
TileMapManager.load(exitWarp.map_association)
ti... | def warp_object(self, tileMapObj) | Warp the tile map object from one warp to another. | 9.126462 | 8.40486 | 1.085855 |
fs = open(self.collisionmap_path, "r")
self.collisionmap = fs.readlines()
fs.close()
x_index = 0
y_index = 0
for line in self.collisionmap:
if line[0] is "#":
continue
for char in line:
if char is "":
... | def parse_collisions(self) | Parses the collision map and sets the tile states as necessary. | 3.766253 | 3.448075 | 1.092277 |
collisions = []
top_left = self.pixels_to_tiles(coords)
collisions.append(self.tiles[top_left.Y][top_left.X])
#Check to see if we are perfectly aligned with a tile
tile_width = int(self.spritesheet[0].width)
tile_height = int(self.spritesheet[0].width)
x... | def grab_collisions(self, coords) | Return all the tiles the position is colliding with.
Tiles returned in this order:
Top Left
Top Right
Bottom Left
Bottom Right | 2.112811 | 2.05599 | 1.027636 |
self.drawn_rects = []
cam = Ragnarok.get_world().Camera
cX, cY, cXMax, cYMax = cam.get_cam_bounds()
#Draw out only the tiles visible to the camera.
start_pos = self.pixels_to_tiles( (cX, cY) )
start_pos -= Vector2(1, 1)
end_pos = self.pixels_to_tiles( (c... | def draw(self, milliseconds, surface) | Draw out the tilemap. | 2.760798 | 2.621452 | 1.053156 |
if self.__do_need_sort_up:
self.__up_objects.sort(self.__up_cmp)
self.__do_need_sort_up = False | def __sort_up(self) | Sort the updatable objects according to ascending order | 4.79866 | 3.614987 | 1.327435 |
if self.__do_need_sort_draw:
self.__draw_objects.sort(self.__draw_cmp)
self.__do_need_sort_draw = False | def __sort_draw(self) | Sort the drawable objects according to ascending order | 4.423028 | 3.609058 | 1.225535 |
cam = Ragnarok.get_world().Camera
camPos = cam.get_world_pos()
self.__sort_draw()
self.clear_backbuffer()
for obj in self.__draw_objects:
#Check to see if the object is visible to the camera before doing anything to it.
if obj.is_static or obj.is_... | def draw(self, milliseconds) | Draws all of the objects in our world. | 4.810495 | 4.267996 | 1.127109 |
try:
import IPython
except ImportError:
debug = None
else:
old_excepthook = sys.excepthook
def debug(frame=None):
if IPython.__version__ >= '0.11':
from IPython.core.debugger import Pdb
try:
ip = get_ipy... | def get_debug() | Utility function providing ``debug()`` function. | 2.954329 | 2.865929 | 1.030845 |
tt = time.clock()
times.append(tt)
if (msg is not None) and (len(times) > 1):
print msg, times[-1] - times[-2] | def mark_time(times, msg=None) | Time measurement utility.
Measures times of execution between subsequent calls using
time.clock(). The time is printed if the msg argument is not None.
Examples
--------
>>> times = []
>>> mark_time(times)
... do something
>>> mark_time(times, 'elapsed')
elapsed 0.1
... do som... | 3.079854 | 4.039089 | 0.762512 |
path = os.path.dirname(filename)
if not path in sys.path:
sys.path.append( path )
remove_path = True
else:
remove_path = False
name = os.path.splitext(os.path.basename(filename))[0]
if name in sys.modules:
force_reload = True
else:
force_reload = ... | def import_file(filename, package_name=None) | Import a file as a module. The module is explicitly reloaded to
prevent undesirable interactions. | 2.267785 | 2.281036 | 0.994191 |
msgs = []
for imp in imports:
try:
exec imp
break
except Exception, inst:
msgs.append(str(inst))
else:
if fail_msg is not None:
msgs.append(fail_msg)
raise ValueError('\n'.join(msgs))
return locals() | def try_imports(imports, fail_msg=None) | Try import statements until one succeeds.
Parameters
----------
imports : list
The list of import statements.
fail_msg : str
If not None and no statement succeeds, a `ValueError` is raised with
the given message, appended to all failed messages.
Returns
-------
loca... | 3.428867 | 3.845044 | 0.891763 |
f = sys._getframe(1)
ff = f.f_code
if (msg):
print '%s, %d: %s(), %d: %s' % (ff.co_filename, ff.co_firstlineno,
ff.co_name, f.f_lineno, msg)
else:
print '%s, %d: %s(), %d' % (ff.co_filename, ff.co_firstlineno,
... | def pause( msg = None ) | Prints the line number and waits for a keypress.
If you press:
"q" ............. it will call sys.exit()
any other key ... it will continue execution of the program
This is useful for debugging. | 2.449776 | 2.484888 | 0.98587 |
try:
out = self[ii]
except (IndexError, ValueError):
if default is not None:
out = default
else:
if msg_if_none is not None:
raise ValueError(msg_if_none)
else:
raise
... | def get(self, ii, default=None, msg_if_none=None) | Get an item from Container - a wrapper around
Container.__getitem__() with defaults and custom error message.
Parameters
----------
ii : int or str
The index or name of the item.
default : any, optional
The default value returned in case the item `ii` doe... | 2.358412 | 2.331882 | 1.011377 |
out = getattr(self, key, default)
if (out is None) and (msg_if_none is not None):
raise ValueError(msg_if_none)
return out | def get(self, key, default=None, msg_if_none=None) | A dict-like get() for Struct attributes. | 2.823879 | 2.434294 | 1.16004 |
if other is None: return
if not isinstance(other, dict):
other = other.to_dict()
self.__dict__.update(other, **kwargs) | def update(self, other, **kwargs) | A dict-like update for Struct attributes. | 3.694022 | 3.321515 | 1.11215 |
if deep:
other = deepcopy(self)
else:
other = copy(self)
if hasattr(self, 'name'):
other.name = get_default(name, self.name + '_copy')
return other | def copy(self, deep=False, name=None) | Make a (deep) copy of self.
Parameters:
deep : bool
Make a deep copy.
name : str
Name of the copy, with default self.name + '_copy'. | 3.596876 | 3.461658 | 1.039062 |
# Type check
self.assert_user_is_social_auth_user(social_auth_user)
# Get friend finder backend
friends_provider = SocialFriendsFinderBackendFactory.get_backend(social_auth_user.provider)
# Get friend ids
friend_ids = friends_provider.fetch_friend_ids(social_a... | def fetch_social_friend_ids(self, social_auth_user) | fetches the user's social friends from its provider
user is an instance of UserSocialAuth
returns collection of ids
this method can be used asynchronously as a background process (celery) | 3.994409 | 4.004547 | 0.997468 |
# Type check
self.assert_user_is_social_auth_user(user_social_auth)
if not friend_ids:
friend_ids = self.fetch_social_friend_ids(user_social_auth)
# Convert comma sepearated string to the list
if isinstance(friend_ids, basestring):
friend_ids = ... | def existing_social_friends(self, user_social_auth=None, friend_ids=None) | fetches and matches social friends
if friend_ids is None, then fetches them from social network
Return:
User collection | 3.914421 | 3.727349 | 1.050189 |
# Type check
self.assert_user_is_social_auth_user(social_auth)
# Fetch the record
try:
social_friend_list = self.filter(user_social_auth=social_auth).get()
except:
# if no record found, create a new one
friend_ids = self.fetch_social_... | def get_or_create_with_social_auth(self, social_auth) | creates and saves model instance with collection of UserSocialAuth
Raise:
NotImplemetedError | 3.309002 | 3.21157 | 1.030338 |
social_friend_coll = []
for sa in social_auths:
try:
social_friend = self.get_or_create_with_social_auth(sa)
except NotImplementedError:
continue
social_friend_coll.append(social_friend)
return social_friend_coll | def get_or_create_with_social_auths(self, social_auths) | creates and saves model instance with collection of UserSocialAuth
Raise:
NotImplemetedError | 2.906299 | 3.054832 | 0.951378 |
if settings.PODCAST_SINGULAR:
show = get_object_or_404(Show, id=settings.PODCAST_ID)
else:
show = get_object_or_404(Show, slug=self.kwargs['show_slug'])
obj = get_object_or_404(Episode, show=show, slug=self.kwargs['slug'])
index = Episode.objects.is_publi... | def get_object(self, queryset=None) | Return object with episode number attached to episode. | 2.936088 | 2.722084 | 1.078618 |
"df_data format is a dataframe with columns x, y, z (required), and style, filter (optional)"
data = df_data.to_json(orient='records')
options = self.to_dict()
return plot(data, options, center=center, save=save,
save_name=save_name, save_path=save_path, dated=dated, ... | def plot(self, df_data, center=False, save=False,
save_name=None, save_path='saved', dated=True, notebook=True) | df_data format is a dataframe with columns x, y, z (required), and style, filter (optional) | 4.351817 | 2.366109 | 1.83923 |
if backend_name == 'twitter':
from social_friends_finder.backends.twitter_backend import TwitterFriendsProvider
friends_provider = TwitterFriendsProvider()
elif backend_name == 'facebook':
from social_friends_finder.backends.facebook_backend import FacebookFr... | def get_backend(self, backend_name) | returns the given backend instance | 2.397191 | 2.399299 | 0.999121 |
path = environ['PATH_INFO']
if re.match(self.path_pattern, path):
ws = environ['wsgi.websocket']
address = (environ.get('REMOTE_ADDR'), environ.get('REMOTE_PORT'))
self._handle_stream(ws, address)
else:
if self.merge_wsgi_app:
... | def wsgi_app(self, environ, start_response) | 将原始的app,包装为包括websocket的app | 2.970837 | 2.951476 | 1.00656 |
if USING_ALLAUTH:
raise NotImplementedError("VKontakte support is not implemented for django-allauth")
#social_app = SocialApp.objects.get_current('vkontakte')
#oauth_token = SocialToken.objects.get(account=user, app=social_app).token
else:
socia... | def fetch_friends(self, user) | fethces friends from VKontakte using the access_token
fethched by django-social-auth.
Note - user isn't a user - it's a UserSocialAuth if using social auth, or a SocialAccount if using allauth
Returns:
collection of friend objects fetched from VKontakte | 4.480359 | 4.053348 | 1.105348 |
if attrs is None:
attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents, escape=escape, cdata=cdata)
self.endElement(name) | def addQuickElement(self, name, contents=None, attrs=None, escape=True, cdata=False) | Convenience method for adding an element with no children. | 1.932229 | 1.817347 | 1.063214 |
table = self
key_so_far = tuple()
for key in key_seq[:-1]:
key_so_far += (key,)
self._make_sure_table_exists(key_so_far)
table = table[key]
table[key_seq[-1]] = value | def _setitem_with_key_seq(self, key_seq, value) | Sets a the value in the TOML file located by the given key sequence.
Example:
self._setitem(('key1', 'key2', 'key3'), 'text_value')
is equivalent to doing
self['key1']['key2']['key3'] = 'text_value' | 3.17854 | 3.309992 | 0.960286 |
table = self.array(array_name)[index]
key_so_far = tuple()
for key in key_seq[:-1]:
key_so_far += (key,)
new_table = self._array_make_sure_table_exists(array_name, index, key_so_far)
if new_table is not None:
table = new_table
... | def _array_setitem_with_key_seq(self, array_name, index, key_seq, value) | Sets a the array value in the TOML file located by the given key sequence.
Example:
self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value')
is equivalent to doing
self.array(array_name)[index]['key1']['key2']['key3'] = 'text_value' | 2.838643 | 2.65221 | 1.070294 |
t = self
for key in name_seq[:-1]:
t = t[key]
name = name_seq[-1]
if name not in t:
self.append_elements([element_factory.create_table_header_element(name_seq),
element_factory.create_table({})]) | def _make_sure_table_exists(self, name_seq) | Makes sure the table with the full name comprising of name_seq exists. | 4.970424 | 4.597223 | 1.08118 |
t = self[array_name][index]
for key in name_seq[:-1]:
t = t[key]
name = name_seq[-1]
if name not in t:
new_table = element_factory.create_table({})
self.append_elements([element_factory.create_table_header_element((array_name,) + name_seq), ne... | def _array_make_sure_table_exists(self, array_name, index, name_seq) | Makes sure the table with the full name comprising of name_seq exists. | 4.35057 | 4.09017 | 1.063665 |
return tuple(e for e in toplevels.identify(self.elements) if isinstance(e, toplevels.Table)) | def _detect_toplevels(self) | Returns a sequence of TopLevel instances for the current state of this table. | 18.636719 | 11.719497 | 1.590232 |
if len(self.elements) <= 1:
return
def parent_of(toplevel):
# Returns an TopLevel parent of the given entry, or None.
for parent_toplevel in table_toplevels:
if toplevel.name.sub_names[:-1] == parent_toplevel.name.sub_names:
... | def _update_table_fallbacks(self, table_toplevels) | Updates the fallbacks on all the table elements to make relative table access possible.
Raises DuplicateKeysError if appropriate. | 4.599234 | 4.228478 | 1.087681 |
if name in self._navigable:
if isinstance(self._navigable[name], (list, tuple)):
return self[name]
else:
raise NoArrayFoundError
else:
return ArrayOfTables(toml_file=self, name=name) | def array(self, name) | Returns the array of tables with the given name. | 7.417235 | 6.859138 | 1.081365 |
self._elements = self._elements + list(elements)
self._on_element_change() | def append_elements(self, elements) | Appends more elements to the contained internal elements. | 6.090076 | 5.896873 | 1.032764 |
self._elements = list(elements) + self._elements
self._on_element_change() | def prepend_elements(self, elements) | Prepends more elements to the contained internal elements. | 6.019014 | 5.585949 | 1.077527 |
raw_container = raw.to_raw(self._navigable)
# Collapsing the anonymous table onto the top-level container is present
if '' in raw_container:
raw_container.update(raw_container[''])
del raw_container['']
return raw_container | def primitive(self) | Returns a primitive object representation for this container (which is a dict).
WARNING: The returned container does not contain any markup or formatting metadata. | 12.262394 | 11.13581 | 1.101168 |
if fresh_table.name:
elements = []
if fresh_table.is_array:
elements += [element_factory.create_array_of_tables_header_element(fresh_table.name)]
else:
elements += [element_factory.create_table_header_element(fresh_table.name)]
... | def append_fresh_table(self, fresh_table) | Gets called by FreshTable instances when they get written to. | 3.131337 | 3.084778 | 1.015093 |
while not self.closing:
try:
xid, zxid, response = yield self.read_response()
except iostream.StreamClosedError:
return
except Exception:
log.exception("Error reading response.")
self.abort()
... | def read_loop(self) | Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate callback on the
I/O loop via the `connect()` method. | 4.387733 | 4.291462 | 1.022433 |
log.warn("Aborting connection to %s:%s", self.host, self.port)
def abort_pending(f):
exc_info = sys.exc_info()
if any(exc_info):
f.set_exc_info(exc_info)
else:
f.set_exception(exception(self.host, self.port))
for pend... | def abort(self, exception=exc.ConnectError) | Aborts a connection and puts all pending futures into an error state.
If ``sys.exc_info()`` is set (i.e. this is being called in an exception
handler) then pending futures will have that exc info set. Otherwise
the given ``exception`` parameter is used (defaults to
``ConnectError``). | 3.374642 | 3.023041 | 1.116307 |
try:
os.rmdir(path)
except OSError as exc:
print(str(exc)) | def rmdir(path) | Safe rmdir (non-recursive) which doesn't throw if the directory is not empty. | 3.083433 | 3.594583 | 0.8578 |
out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
return out.decode('utf-8') | def shell_exec(command) | Executes the given shell command and returns its output. | 2.166823 | 2.269588 | 0.954721 |
locales = [x[0] for x in
current_app.extensions['invenio-i18n'].get_languages()]
# In the case of the user specifies a language for the resource.
if 'ln' in request.args:
language = request.args.get('ln')
if language in locales:
return language
# In the ... | def get_locale() | Get locale.
Searches for locale in the following the order:
- User has specified a concrete language in the query string.
- Current session has a language set.
- User has a language set in the profile.
- Headers of the HTTP request.
- Default language from ``BABEL_DEFAULT_LOCALE``.
Will o... | 2.801931 | 2.702544 | 1.036775 |
if isinstance(searchpath, (str, unicode, int)):
searchpath = [searchpath]
if not isinstance(searchpath, (list, tuple)):
return False
for d in searchpath:
if isinstance(searchtree, dict):
if not d in searchtree.keys():
return False
elif isin... | def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False) | Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dtype | 2.280923 | 2.314976 | 0.98529 |
if is_data_value(searchpath, searchtree, dtype):
if isinstance(searchpath, (str, unicode, int)):
searchpath = [searchpath]
for d in searchpath:
searchtree = searchtree[d]
else:
searchtree = None
if searchtree == None:
if default != None:
... | def data_value(searchpath, searchtree, dtype = None, default = None) | Follow searchpath through the datatree in searchtree
and return if it exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
If it is not found return default or if dtype is set to
a string, list or dict, an empty one | 3.253768 | 3.365492 | 0.966803 |
data = DBVuln.load_from_json(db_file, language=language)
return cls(**data) | def from_file(cls, db_file, language=DEFAULT_LANG) | This is an alternative "constructor" for the DBVuln class which loads
the data from a file.
:param db_file: Contents of a json file from the DB
:param language: The user's language (en, es, etc.) | 7.162956 | 6.161822 | 1.162474 |
db_file = DBVuln.get_file_for_id(_id, language=language)
data = DBVuln.load_from_json(db_file, language=language)
return cls(**data) | def from_id(cls, _id, language=DEFAULT_LANG) | This is an alternative "constructor" for the DBVuln class which searches
the db directory to find the right file for the provided _id | 4.378834 | 2.673811 | 1.637675 |
file_start = '%s-' % _id
json_path = DBVuln.get_json_path(language=language)
for _file in os.listdir(json_path):
if _file.startswith(file_start):
return os.path.join(json_path, _file)
raise NotFoundException('No data for ID %s' % _id) | def get_file_for_id(_id, language=DEFAULT_LANG) | Given _id, search the DB for the file which contains the data
:param _id: The id to search (int)
:param language: The user's language (en, es, etc.)
:return: The filename | 4.123221 | 4.662759 | 0.884288 |
_ids = []
json_path = DBVuln.get_json_path(language=language)
for _file in os.listdir(json_path):
if not _file.endswith('.json'):
continue
_id = _file.split('-')[0]
_ids.append(_id)
return _ids | def get_all_db_ids(language=DEFAULT_LANG) | :return: A list with all the database IDs as integers | 3.744619 | 3.673409 | 1.019385 |
ref = attr.get('$ref', None)
if ref is None:
raise NotFoundException('No $ref in attribute')
_, files, _type, _id = ref.split('/')
if 'files' != files:
raise NotFoundException('Mandatory "files" path was not found in $ref')
if _type not in ('fi... | def handle_ref(attr, language=DEFAULT_LANG) | Receives something like:
{
"$ref": "#/files/description/1"
},
Or:
{
"$ref": "#/files/fix/39"
}
And returns the contents of the description or fix file.
:param attr: A dict containing a reference
:param language: T... | 4.5861 | 3.778601 | 1.213703 |
# There are a couple of things I don't do here, and are on purpose:
# - I want to fail if the file doesn't exist
# - I want to fail if the file doesn't contain valid JSON
raw = json.loads(file(db_file).read())
# Here I don't do any error handling either, I expect th... | def load_from_json(db_file, language=DEFAULT_LANG) | Parses the JSON data and returns it
:param db_file: File and path pointing to the JSON file to parse
:param language: The user's language (en, es, etc.)
:raises: All kind of exceptions if the file doesn't exist or JSON is
invalid.
:return: None | 3.886304 | 3.90178 | 0.996034 |
owasp_version = int(owasp_version)
# Just return one of them, 2013 release has priority over 2010
if owasp_version == 2013:
return OWASP_TOP10_2013_URL_FMT % risk_id
if owasp_version == 2010:
return OWASP_TOP10_2010_URL_FMT % risk_id | def get_owasp_top_10_url(owasp_version, risk_id) | Similar to get_wasc_url() but for OWASP Top 10 | 3.016746 | 2.950754 | 1.022364 |
reference_list = []
for reference_dict in json_references:
reference_list.append(Reference(reference_dict['url'],
reference_dict['title']))
return reference_list | def handle_references(json_references) | Create a list of reference objects that represent this part of the JSON
data:
"references": [
{"url": "http://foo.com/xss", "title": "First reference to ..."},
{"url": "http://asp.net/xss", "title": "How to fix ..."},
{"url": "http://owasp.org/xss", "title": ... | 3.240233 | 2.942638 | 1.101132 |
failures = []
if not os.access(self.mount_path_base, os.W_OK):
msg = ("Mount path `{path}` doesn't exist or is not writable"
" by the current user.")
failures.append(msg.format(
path = self.mount_path_base
))
if whic... | def perform_preflight_check(self) | Performs checks to see if we have everything needed to mount
sshfs filesystems.
:return: two-tuple (boolean checks_pass, list failure messages) | 3.836103 | 3.201822 | 1.1981 |
fields = ['id', 'host', 'port', 'user']
out = {}
for field in fields:
out[field] = getattr(self, field, None)
out['mountOptions'] = self.mount_opts
out['mountPoint'] = self.mount_point
out['beforeMount'] = self.cmd_before_mount
out['authType']... | def export(self) | Serializes to JSON. | 3.341478 | 3.122698 | 1.070061 |
if self.mounted:
return
self._mount_point_local_create()
if len(self.system.mount_opts) == 0:
sshfs_opts = ""
else:
sshfs_opts = " -o %s" % " -o ".join(self.system.mount_opts)
if self.system.auth_method == self.system.AUTH_METHOD_PU... | def mount(self) | Mounts the sftp system if it's not already mounted. | 2.781542 | 2.704441 | 1.028509 |
if not self.mounted:
return
# Try to unmount properly.
cmd = 'fusermount -u %s' % self.mount_point_local
shell_exec(cmd)
# The filesystem is probably still in use.
# kill sshfs and re-run this same command (which will work then).
if self.mou... | def unmount(self) | Unmounts the sftp system if it's currently mounted. | 8.515426 | 8.233801 | 1.034203 |
if book not in self.order_books:
raise InvalidOrderBookError(
'Invalid order book \'{}\'. Choose from {}.'
.format(book, tuple(self.order_books))
) | def _validate_order_book(self, book) | Check if the given order book is valid.
:param book: Order book name.
:type book: str | unicode
:raise InvalidOrderBookError: If an invalid order book is given. | 4.292829 | 3.425726 | 1.253115 |
if currency not in self.major_currencies:
raise InvalidCurrencyError(
'Invalid major currency \'{}\'. Choose from {}.'
.format(currency, tuple(self.major_currencies))
) | def _validate_currency(self, currency) | Check if the given order book is valid.
:param currency: Major currency name in lowercase.
:type currency: str | unicode
:raise InvalidCurrencyError: If an invalid major currency is given. | 4.82053 | 3.762626 | 1.281161 |
self._validate_order_book(name)
return OrderBook(name, self._rest_client, self._logger) | def book(self, name) | Return an API wrapper for the given order book.
:param name: Order book name (e.g. "btc_cad").
:type name: str | unicode
:return: Order book API wrapper.
:rtype: quadriga.book.OrderBook
:raise InvalidOrderBookError: If an invalid order book is given.
**Example**:
... | 7.891514 | 13.025032 | 0.605873 |
self._log('look up order(s) {}'.format(order_id))
return self._rest_client.post(
endpoint='/lookup_order',
payload={'id': order_id}
) | def lookup_order(self, order_id) | Look up one or more orders by ID (64 hexadecmial characters).
:param order_id: Order ID or list of order IDs.
:type order_id: str | unicode | [str | unicode]
:return: Order details.
:rtype: [dict] | 5.625014 | 5.08052 | 1.107173 |
self._log('cancel order {}'.format(order_id))
result = self._rest_client.post(
endpoint='/cancel_order',
payload={'id': order_id}
)
return result == 'true' | def cancel_order(self, order_id) | Cancel an open order by ID (64 hexadecmial characters).
:param order_id: Order ID.
:type order_id: str | unicode
:return: True if the order was cancelled successfully.
:rtype: bool | 4.796871 | 4.501473 | 1.065622 |
self._validate_currency(currency)
self._log('get deposit address for {}'.format(currency))
coin_name = self.major_currencies[currency]
return self._rest_client.post(
endpoint='/{}_deposit_address'.format(coin_name)
) | def get_deposit_address(self, currency) | Return the deposit address for the given major currency.
:param currency: Major currency name in lowercase (e.g. "btc", "eth").
:type currency: str | unicode
:return: Deposit address.
:rtype: str | unicode | 5.505412 | 4.997324 | 1.101672 |
self._validate_currency(currency)
self._log('withdraw {} {} to {}'.format(amount, currency, address))
coin_name = self.major_currencies[currency]
return self._rest_client.post(
endpoint='/{}_withdrawal'.format(coin_name)
) | def withdraw(self, currency, amount, address) | Withdraw a major currency from QuadrigaCX to the given wallet.
:param currency: Major currency name in lowercase (e.g. "btc", "eth").
:type currency: str | unicode
:param amount: Withdrawal amount.
:type amount: int | float | str | unicode | decimal.Decimal
:param address: Walle... | 5.583968 | 5.673049 | 0.984298 |
'''The format of node is similar to add_node.
If node contains a key 'cluster_node'
whose value is an instance of ClusterNode,
it will be used directly.
'''
new_nodes, master_map = self._add_nodes_as_master(nodes)
for n in new_nodes:
if n.name not in ... | def add_nodes(self, nodes) | The format of node is similar to add_node.
If node contains a key 'cluster_node'
whose value is an instance of ClusterNode,
it will be used directly. | 4.982483 | 2.800151 | 1.779362 |
'''This is almost the same with `add_nodes`. The difference is that
it will add slaves in two slower way.
This is mainly used to avoid huge overhead caused by full sync
when large amount of slaves are added to cluster.
If fast_mode is False, there is only one master node doing
... | def add_slaves(self, new_slaves, fast_mode=False) | This is almost the same with `add_nodes`. The difference is that
it will add slaves in two slower way.
This is mainly used to avoid huge overhead caused by full sync
when large amount of slaves are added to cluster.
If fast_mode is False, there is only one master node doing
repli... | 4.626037 | 2.909114 | 1.590188 |
'''Sometimes even cluster_member has responded new_node.meet,
cluster_memeber.nodes() are still not updated
'''
while True:
known_nodes = [n['name'] for n in cluster_member.nodes()]
added_nodes = [n.name for n in new_nodes]
if len(set(known_nodes) & se... | def _wait_nodes_updated(self, cluster_member, new_nodes) | Sometimes even cluster_member has responded new_node.meet,
cluster_memeber.nodes() are still not updated | 7.016817 | 2.902492 | 2.417515 |
new = ClusterNode.from_uri(node["addr"])
cluster_member = self.nodes[0]
check_new_nodes([new], [cluster_member])
new.meet(cluster_member.host, cluster_member.port)
self.nodes.append(new)
self.wait()
if node["role"] != "slave":
return
... | def add_node(self, node) | Add a node to cluster.
:param node: should be formated like this
`{"addr": "", "role": "slave", "master": "master_node_id"} | 4.704393 | 4.55031 | 1.033862 |
'func = "(" parameters ")" _ "->" expr'
_, params, _, _, _, expr = node
params = map(self.eval, params)
def func(*args):
env = dict(self.env.items() + zip(params, args))
return Mini(env).eval(expr)
return func | def func(self, node) | func = "(" parameters ")" _ "->" expr | 9.690094 | 5.835648 | 1.6605 |
'ifelse = "if" expr "then" expr "else" expr'
_, cond, _, cons, _, alt = node
return self.eval(cons) if self.eval(cond) else self.eval(alt) | def ifelse(self, node) | ifelse = "if" expr "then" expr "else" expr | 5.614393 | 4.336069 | 1.294812 |
'call = name "(" arguments ")"'
name, _, arguments, _ = children
return name(*arguments) | def call(self, node, children) | call = name "(" arguments ")" | 21.420742 | 12.177487 | 1.759044 |
'infix = "(" expr operator expr ")"'
_, expr1, operator, expr2, _ = children
return operator(expr1, expr2) | def infix(self, node, children) | infix = "(" expr operator expr ")" | 9.870836 | 5.49051 | 1.7978 |
'operator = "+" / "-" / "*" / "/"'
operators = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.div}
return operators[node.text] | def operator(self, node, children) | operator = "+" / "-" / "*" / "/" | 4.260841 | 3.726994 | 1.143238 |
'assignment = lvalue "=" expr'
lvalue, _, expr = children
self.env[lvalue] = expr
return expr | def assignment(self, node, children) | assignment = lvalue "=" expr | 11.119398 | 6.51622 | 1.706418 |
'name = ~"[a-z]+" _'
return self.env.get(node.text.strip(), -1) | def name(self, node, children) | name = ~"[a-z]+" _ | 20.83172 | 8.987147 | 2.317946 |
ctx = _request_ctx_stack.top
if ctx is None:
raise RuntimeError('Working outside of request context.')
new_locale = current_app.extensions['babel'].load_locale(ln)
old_locale = getattr(ctx, 'babel_locale', None)
setattr(ctx, 'babel_locale', new_locale)
yield
setattr(ctx, 'babel_... | def set_locale(ln) | Set Babel localization in request context.
:param ln: Language identifier. | 3.029811 | 3.161818 | 0.95825 |
for ep in iter_entry_points(group=entry_point_group):
if not resource_isdir(ep.module_name, 'translations'):
continue
dirname = resource_filename(ep.module_name, 'translations')
self.add_path(dirname) | def add_entrypoint(self, entry_point_group) | Load translations from an entry point. | 4.148641 | 3.036599 | 1.366213 |
if not os.path.exists(path):
raise RuntimeError('Path does not exists: %s.' % path)
self.paths.append(path) | def add_path(self, path) | Load translations from an existing path. | 3.057403 | 2.974065 | 1.028022 |
translations = None
for dirname in self.paths:
# Load a single catalog.
catalog = Translations.load(dirname, [locale], domain=self.domain)
if translations is None:
if isinstance(catalog, Translations):
translations = catal... | def _get_translation_for_locale(self, locale) | Get translation for a specific locale. | 5.610267 | 5.612089 | 0.999675 |
ctx = _request_ctx_stack.top
if ctx is None:
return NullTranslations()
locale = get_locale()
cache = self.get_translations_cache(ctx)
translations = cache.get(str(locale))
if translations is None:
translations = self._get_translation_f... | def get_translations(self) | Return the correct gettext translations for a request.
This will never fail and return a dummy translation object if used
outside of the request or if a translation cannot be found. | 3.488256 | 3.078537 | 1.133089 |
from speaklater import _LazyString
class JSONEncoder(app.json_encoder):
def default(self, o):
if isinstance(o, _LazyString):
return text_type(o)
return super(JSONEncoder, self).default(o)
return JSONEncoder | def get_lazystring_encoder(app) | Return a JSONEncoder for handling lazy strings from Babel.
Installed on Flask application by default by :class:`InvenioI18N`. | 2.771442 | 3.214402 | 0.862195 |
self.init_config(app)
# Initialize Flask-BabelEx
self.babel.init_app(app)
self.babel.localeselector(self.localeselector or get_locale)
self.babel.timezoneselector(self.timezoneselector or get_timezone)
# 1. Paths listed in I18N_TRANSLATIONS_PATHS
for p ... | def init_app(self, app) | Flask application initialization.
The initialization will:
* Set default values for the configuration variables.
* Load translations from paths specified in
``I18N_TRANSLATIONS_PATHS``.
* Load translations from ``app.root_path>/translations`` if it exists.
* Load... | 3.204644 | 2.917791 | 1.098312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.