code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
w = cb.width - MENU_WIDTH - 1
h = cb.height - 1
params.plane_w = w
params.plane_h = h
params.resize(w, h)
palette = PALETTES[params.palette][1]
if params.reverse_palette:
palette = palette[::-1]
# draw_gradient(t, 1, 1, w, h, palette, params.dither_type)
generated = ... | def draw_panel(cb, pool, params, plane) | Draws the application's main panel, displaying the current Mandelbrot view.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane | 2.838547 | 2.785504 | 1.019043 |
cb.clear()
draw_panel(cb, pool, params, plane)
update_position(params) # Update Mandelbrot-space coordinates before drawing them
draw_menu(cb, params, qwertz)
cb.refresh() | def update_display(cb, pool, params, plane, qwertz) | Draws everything.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane
:return: | 7.754807 | 9.211398 | 0.841871 |
if is_python3():
import pickle
cPickle = pickle
else:
import cPickle
ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-%M-%S")
if not os.path.exists("saves/"):
os.makedirs("saves/")
with open("saves/almonds_%s.params" % ts, "wb") as f:
... | def save(params) | Saves the current parameters to a file.
:param params: Current application parameters.
:return: | 3.737296 | 4.00181 | 0.933901 |
w, h = screen_resolution()
# Re-adapt dimensions to match current plane ratio
old_ratio = w / h
new_ratio = params.plane_ratio
if old_ratio > new_ratio:
w = int(h * new_ratio)
else:
h = int(w / new_ratio)
image = Image.new("RGB", (w, h), "white")
pixels = image.loa... | def capture(cb, pool, params) | Renders and saves a screen-sized picture of the current position.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params | 3.399529 | 3.436499 | 0.989242 |
step = params.max_iterations // 20
if step == 0:
step = 1
for i in range(0, params.max_iterations, step):
params.palette_offset = i
draw_panel(cb, pool, params, plane)
cb.refresh()
params.palette_offset = 0 | def cycle(cb, pool, params, plane) | Fun function to do a palette cycling animation.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:param plane: Plane containing the current Mandelbrot values.
:type plane: plane.Plane
:return: | 3.878278 | 3.788282 | 1.023756 |
w = cb.width - MENU_WIDTH - 1
h = cb.height - 1
params.plane_w = w
params.plane_h = h
params.resize(w, h)
zoom(params, 1) | def init_coords(cb, params) | Initializes coordinates and zoom for first use.
Loads coordinates from Mandelbrot-space.
:param cb: Cursebox instance.
:type cb: cursebox.Cursebox
:param params: Current application parameters.
:type params: params.Params
:return: | 6.085976 | 6.876446 | 0.885047 |
if lower > upper:
lower, upper = upper, lower
return max(min(upper, n), lower) | def clamp(n, lower, upper) | Restricts the given number to a lower and upper bound (inclusive)
:param n: input number
:param lower: lower bound (inclusive)
:param upper: upper bound (inclusive)
:return: clamped number | 3.287826 | 4.919063 | 0.668385 |
w = 0
h = 0
try:
# Windows
import ctypes
user32 = ctypes.windll.user32
w, h = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
except AttributeError:
try:
# Mac OS X
import AppKit
size = AppKit.NSScreen.screens()[0].f... | def screen_resolution() | Returns the current screen's resolution.
Should be multi-platform.
:return: A tuple containing the width and height of the screen. | 1.738742 | 1.755957 | 0.990196 |
if sys.platform.startswith("darwin"):
subprocess.call(("open", filename))
elif sys.platform == "cygwin":
subprocess.call(("cygstart", filename))
elif os.name == "nt":
os.system("start %s" % filename)
elif os.name == "posix":
subprocess.call(("xdg-open", filename)) | def open_file(filename) | Multi-platform way to make the OS open a file with its default application | 1.876388 | 1.733148 | 1.082647 |
dither = DITHER_TYPES[dither][1]
return dither[int(round(value * (len(dither) - 1)))] | def dither_symbol(value, dither) | Returns the appropriate block drawing symbol for the given intensity.
:param value: intensity of the color, in the range [0.0, 1.0]
:return: dithered symbol representing that intensity | 4.348332 | 5.2286 | 0.831644 |
i = n * (len(palette) - 1) / n_max
c1 = palette[int(math.floor(i))]
c2 = palette[int(math.ceil(i))]
value = i - int(math.floor(i))
symbol = dither_symbol(value, dither)
if crosshairs_coord is not None:
old_symbol = symbol
symbol, crosshairs = get_crosshairs_symbol(x, y, ol... | def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None) | Draws a dithered color block on the terminal, given a palette.
:type cb: cursebox.CurseBox | 3.118499 | 3.460598 | 0.901145 |
w -= 1
h -= 1
corners = [(x0, y0), (x0 + w, y0), (x0, y0 + h), (x0 + w, y0 + h)]
fg = fg()
bg = bg()
for i, c in enumerate(corners):
cb.put(c[0], c[1], BOX_CORNERS[i], fg, bg)
for s in h_seps + [0, h]:
cb.put(x0 + 1, y0 + s, symbols["BOX_HORIZONTAL"] * (w - 1), fg, bg... | def draw_box(cb, x0, y0, w, h, fg=colors.default_fg, bg=colors.default_bg, h_seps=[], v_seps=[]) | Draws a box in the given terminal.
:type cb: cursebox.CurseBox | 2.008811 | 2.068142 | 0.971312 |
m_x = cb.width // 2
m_y = cb.height // 2
w = len(message) + 4
h = 3
draw_box(cb, m_x - w // 2, m_y - 1, w, h)
message = " %s " % message
i = int((value / max_value) * (len(message) + 2))
message = "$" + message[:i] + "$" + message[i:]
draw_text(cb, m_x - w // 2 + 1, m_y, message... | def draw_progress_bar(cb, message, value, max_value) | :type cb: cursebox.Cursebox | 2.820565 | 2.723108 | 1.035789 |
z = c
if julia_seed is not None:
c = julia_seed
for iterations in range(max_iterations):
z = z * z + c
if abs(z) > 1000:
return z, iterations
return z, max_iterations | def mandelbrot_iterate(c, max_iterations, julia_seed=None) | Returns the number of iterations before escaping the Mandelbrot fractal.
:param c: Coordinates as a complex number
:type c: complex
:param max_iterations: Limit of how many tries are attempted.
:return: Tuple containing the last complex number in the sequence and the number of iterations. | 2.963381 | 3.226717 | 0.918389 |
n_x = x * 2.0 / params.plane_w * params.plane_ratio - 1.0
n_y = y * 2.0 / params.plane_h - 1.0
mb_x = params.zoom * n_x
mb_y = params.zoom * n_y
return mb_x, mb_y | def get_coords(x, y, params) | Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary).
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Tuple containing the re-mapped coordinates in Man... | 3.489644 | 3.288277 | 1.061238 |
mb_x, mb_y = get_coords(x, y, params)
mb = mandelbrot_iterate(mb_x + 1j * mb_y, params.max_iterations, params.julia_seed)
return mb[1] | def mandelbrot(x, y, params) | Computes the number of iterations of the given plane-space coordinates.
:param x: X coordinate on the plane.
:param y: Y coordinate on the plane.
:param params: Current application parameters.
:type params: params.Params
:return: Discrete number of iterations. | 5.28529 | 5.935988 | 0.890381 |
# FIXME: Figure out why these corrections are necessary or how to make them perfect
# Viewport is offset compared to window when capturing without these (found empirically)
if params.plane_ratio >= 1.0:
x -= params.plane_w
else:
x += 3.0 * params.plane_w
ratio = w / h
n_x ... | def mandelbrot_capture(x, y, w, h, params) | Computes the number of iterations of the given pixel-space coordinates,
for high-res capture purposes.
Contrary to :func:`mandelbrot`, this function returns a continuous
number of iterations to avoid banding.
:param x: X coordinate on the picture
:param y: Y coordinate on the picture
:param w:... | 5.621243 | 5.387621 | 1.043363 |
cx = params.plane_x0 + params.plane_w / 2.0
cy = params.plane_y0 + params.plane_h / 2.0
params.mb_cx, params.mb_cy = get_coords(cx, cy, params) | def update_position(params) | Computes the center of the viewport's Mandelbrot-space coordinates.
:param params: Current application parameters.
:type params: params.Params | 4.060297 | 3.669543 | 1.106486 |
params.zoom /= factor
n_x = params.mb_cx / params.zoom
n_y = params.mb_cy / params.zoom
params.plane_x0 = int((n_x + 1.0) * params.plane_w / (2.0 * params.plane_ratio)) - params.plane_w // 2
params.plane_y0 = int((n_y + 1.0) * params.plane_h / 2.0) - params.plane_h // 2 | def zoom(params, factor) | Applies a zoom on the current parameters.
Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates.
:param params: Current application parameters.
:param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom) | 3.109484 | 3.141857 | 0.989696 |
self.plane_w = w
self.plane_h = h
self.plane_ratio = self.char_ratio * w / h
if self.crosshairs:
self.crosshairs_coord = ((w + 2) // 2, (h + 2) // 2) | def resize(self, w, h) | Used when resizing the plane, resets the plane ratio factor.
:param w: New width of the visible section of the plane.
:param h: New height of the visible section of the plane. | 4.460327 | 3.893344 | 1.145629 |
if sender_handle != entity_handle:
logger.warning("sender_handle and entity_handle don't match, aborting! sender_handle: %s, entity_handle: %s",
sender_handle, entity_handle)
return False
return True | def check_sender_and_entity_handle_match(sender_handle, entity_handle) | Ensure that sender and entity handles match.
Basically we've already verified the sender is who they say when receiving the payload. However, the sender might
be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers
AND the object. We must ensure they... | 2.583771 | 2.512495 | 1.028369 |
entities = []
cls = MAPPINGS.get(element.tag)
if not cls:
return []
attrs = xml_children_as_dict(element)
transformed = transform_attributes(attrs, cls)
if hasattr(cls, "fill_extra_attributes"):
transformed = cls.fill_extra_attributes(transformed)
entity = cls(**transfo... | def element_to_objects(
element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List | Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:param sender: Payload sender id
:param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched
over netwo... | 4.24306 | 4.24004 | 1.000712 |
doc = etree.fromstring(message)
if doc.tag in TAGS:
return element_to_objects(doc, sender, sender_key_fetcher, user)
return [] | def message_to_objects(
message: str, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List | Takes in a message extracted by a protocol and maps it to entities.
:param message: XML payload
:type message: str
:param sender: Payload sender id
:type message: str
:param sender_key_fetcher: Function to fetch sender public key. If not given, key will always be fetched
over network. The f... | 4.330764 | 4.594588 | 0.942579 |
transformed = {}
for key, value in attrs.items():
if value is None:
value = ""
if key == "text":
transformed["raw_content"] = value
elif key == "author":
if cls == DiasporaProfile:
# Diaspora Profile XML message contains no GUID. W... | def transform_attributes(attrs, cls) | Transform some attribute keys.
:param attrs: Properties from the XML
:type attrs: dict
:param cls: Class of the entity
:type cls: class | 2.475648 | 2.516945 | 0.983592 |
if getattr(entity, "outbound_doc", None):
# If the entity already has an outbound doc, just return the entity as is
return entity
outbound = None
cls = entity.__class__
if cls in [DiasporaPost, DiasporaImage, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction,
... | def get_outbound_entity(entity: BaseEntity, private_key: RsaKey) | Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
... | 3.830079 | 3.6731 | 1.042738 |
props = []
for child in doc:
if child.tag not in ["author_signature", "parent_author_signature"]:
props.append(getattr(child, attr))
return props | def get_element_child_info(doc, attr) | Get information from child elements of this elementas a list since order is important.
Don't include signature tags.
:param doc: XML element
:param attr: Attribute to get from the elements, for example "tag" or "text". | 5.509977 | 5.905345 | 0.933049 |
sig_hash = _create_signature_hash(doc)
cipher = PKCS1_v1_5.new(RSA.importKey(public_key))
return cipher.verify(sig_hash, b64decode(signature)) | def verify_relayable_signature(public_key, doc, signature) | Verify the signed XML elements to have confidence that the claimed
author did actually generate this message. | 3.181701 | 3.14043 | 1.013142 |
resource = request.GET.get("resource")
if not resource:
return HttpResponseBadRequest("No resource found")
if not resource.startswith("acct:"):
return HttpResponseBadRequest("Invalid resource")
handle = resource.replace("acct:", "").lower()
profile_func = get_function_from_conf... | def rfc7033_webfinger_view(request, *args, **kwargs) | Django view to generate an RFC7033 webfinger. | 2.891956 | 2.851101 | 1.01433 |
webfinger = {
"hcard_url": None,
}
try:
doc = json.loads(document)
for link in doc["links"]:
if link["rel"] == "http://microformats.org/profile/hcard":
webfinger["hcard_url"] = link["href"]
break
else:
logger.warnin... | def parse_diaspora_webfinger(document) | Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html | 2.74589 | 2.645767 | 1.037843 |
webfinger = retrieve_and_parse_diaspora_webfinger(handle)
document, code, exception = fetch_document(webfinger.get("hcard_url"))
if exception:
return None
return document | def retrieve_diaspora_hcard(handle) | Retrieve a remote Diaspora hCard document.
:arg handle: Remote handle to retrieve
:return: str (HTML document) | 6.606971 | 7.42382 | 0.889969 |
try:
host = handle.split("@")[1]
except AttributeError:
logger.warning("retrieve_and_parse_diaspora_webfinger: invalid handle given: %s", handle)
return None
document, code, exception = fetch_document(
host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(han... | def retrieve_and_parse_diaspora_webfinger(handle) | Retrieve a and parse a remote Diaspora webfinger document.
:arg handle: Remote handle to retrieve
:returns: dict | 3.492596 | 3.671314 | 0.951321 |
document, code, exception = fetch_document(host=host, path="/.well-known/host-meta")
if exception:
return None
xrd = XRD.parse_xrd(document)
return xrd | def retrieve_diaspora_host_meta(host) | Retrieve a remote Diaspora host-meta document.
:arg host: Host to retrieve from
:returns: ``XRD`` instance | 6.990147 | 6.913632 | 1.011067 |
element = document.cssselect(selector)
if element:
return element[0].text
return None | def _get_element_text_or_none(document, selector) | Using a CSS selector, get the element and return the text, or None if no element.
:arg document: ``HTMLElement`` document
:arg selector: CSS selector
:returns: str or None | 3.072755 | 5.098471 | 0.602682 |
element = document.cssselect(selector)
if element:
return element[0].get(attribute)
return None | def _get_element_attr_or_none(document, selector, attribute) | Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to get from the element | 2.749472 | 5.609079 | 0.490182 |
from federation.entities.diaspora.entities import DiasporaProfile # Circulars
doc = html.fromstring(hcard)
profile = DiasporaProfile(
name=_get_element_text_or_none(doc, ".fn"),
image_urls={
"small": _get_element_attr_or_none(doc, ".entity_photo_small .photo", "src"),
... | def parse_profile_from_hcard(hcard: str, handle: str) | Parse all the fields we can from a hCard document to get a Profile.
:arg hcard: HTML hcard document (str)
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.diaspora.entities.DiasporaProfile`` instance | 2.949608 | 2.734819 | 1.078539 |
if not validate_handle(handle):
return
_username, domain = handle.split("@")
url = get_fetch_content_endpoint(domain, entity_type.lower(), guid)
document, status_code, error = fetch_document(url)
if status_code == 200:
request = RequestType(body=document)
_sender, _proto... | def retrieve_and_parse_content(
guid: str, handle: str, entity_type: str, sender_key_fetcher: Callable[[str], str]=None,
) | Retrieve remote content and return an Entity class instance.
This is basically the inverse of receiving an entity. Instead, we fetch it, then call "handle_receive".
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the ke... | 4.442579 | 4.27579 | 1.039008 |
hcard = retrieve_diaspora_hcard(handle)
if not hcard:
return None
profile = parse_profile_from_hcard(hcard, handle)
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
... | def retrieve_and_parse_profile(handle) | Retrieve the remote user and return a Profile object.
:arg handle: User handle in username@domain.tld format
:returns: ``federation.entities.Profile`` instance or None | 4.160697 | 4.76439 | 0.873291 |
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | def get_private_endpoint(id: str, guid: str) -> str | Get remote endpoint for delivering private payloads. | 12.037344 | 8.204505 | 1.467163 |
if dt.tzinfo is None:
return dt.replace(tzinfo=tz or tzlocal())
else:
return dt | def ensure_timezone(dt, tz=None) | Make sure the datetime <dt> has a timezone set, using timezone <tz> if it
doesn't. <tz> defaults to the local timezone. | 2.848695 | 2.934924 | 0.970619 |
for obj in struct:
for k, v in obj.items():
etree.SubElement(node, k).text = v | def struct_to_xml(node, struct) | Turn a list of dicts into XML nodes with tag names taken from the dict
keys and element text taken from dict values. This is a list of dicts
so that the XML nodes can be ordered in the XML output. | 4.00261 | 3.493994 | 1.145569 |
from federation.entities.diaspora.mappers import get_outbound_entity
diaspora_entity = get_outbound_entity(entity, private_key)
xml = diaspora_entity.to_xml()
return "<XML><post>%s</post></XML>" % etree.tostring(xml).decode("utf-8") | def get_full_xml_representation(entity, private_key) | Get full XML representation of an entity.
This contains the <XML><post>..</post></XML> wrapper.
Accepts either a Base entity or a Diaspora entity.
Author `private_key` must be given so that certain entities can be signed. | 4.898499 | 3.712374 | 1.319506 |
element = doc.find(".//%s" % tag)
if element is None:
element = etree.SubElement(doc, tag)
element.text = value | def add_element_to_doc(doc, tag, value) | Set text value of an etree.Element of tag, appending a new element with given tag if it doesn't exist. | 2.470879 | 1.97485 | 1.251173 |
if template == "diaspora":
hostmeta = DiasporaHostMeta(*args, **kwargs)
else:
hostmeta = BaseHostMeta(*args, **kwargs)
return hostmeta.render() | def generate_host_meta(template=None, *args, **kwargs) | Generate a host-meta XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str) | 3.520036 | 3.235153 | 1.088059 |
if template == "diaspora":
webfinger = DiasporaWebFinger(*args, **kwargs)
else:
webfinger = BaseLegacyWebFinger(*args, **kwargs)
return webfinger.render() | def generate_legacy_webfinger(template=None, *args, **kwargs) | Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str) | 3.211378 | 2.978874 | 1.078051 |
return {
"version": "1.0",
"server": {
"baseUrl": kwargs['server']['baseUrl'],
"name": kwargs['server']['name'],
"software": kwargs['server']['software'],
"version": kwargs['server']['version'],
},
"organization": {
"na... | def generate_nodeinfo2_document(**kwargs) | Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
version
}
openRegistrations
... | 2.180421 | 1.865224 | 1.168986 |
if template == "diaspora":
hcard = DiasporaHCard(**kwargs)
else:
raise NotImplementedError()
return hcard.render() | def generate_hcard(template=None, **kwargs) | Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str) | 4.236336 | 4.286415 | 0.988317 |
# TODO add support for AP
protocol_name = "diaspora"
if not guid:
guid = id
utils = importlib.import_module("federation.utils.%s" % protocol_name)
return utils.retrieve_and_parse_content(
guid=guid, handle=handle, entity_type=entity_type, sender_key_fetcher=sender_key_fetcher,
... | def retrieve_remote_content(
id: str, guid: str=None, handle: str=None, entity_type: str=None, sender_key_fetcher: Callable[[str], str]=None,
) | Retrieve remote content and return an Entity object.
Currently, due to no other protocols supported, always use the Diaspora protocol.
:param sender_key_fetcher: Function to use to fetch sender public key. If not given, network will be used
to fetch the profile and the key. Function must take handle a... | 4.603902 | 4.447706 | 1.035118 |
protocol = identify_protocol_by_id(id)
utils = importlib.import_module(f"federation.utils.{protocol.PROTOCOL_NAME}")
return utils.retrieve_and_parse_profile(id) | def retrieve_remote_profile(id: str) -> Optional[Profile] | High level retrieve profile method.
Retrieve the profile from a remote location, using protocol based on the given ID. | 6.700922 | 6.262103 | 1.070075 |
logger.debug("handle_receive: processing request: %s", request)
found_protocol = identify_protocol_by_request(request)
logger.debug("handle_receive: using protocol %s", found_protocol.PROTOCOL_NAME)
protocol = found_protocol.Protocol()
sender, message = protocol.receive(
request, user,... | def handle_receive(
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False
) -> Tuple[str, str, List] | Takes a request and passes it to the correct protocol.
Returns a tuple of:
- sender id
- protocol name
- list of entities
NOTE! The returned sender is NOT necessarily the *author* of the entity. By sender here we're
talking about the sender of the *request*. If this object is being relay... | 3.153197 | 2.683699 | 1.174944 |
return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None | def identify_id(id: str) -> bool | Try to identify whether this is an ActivityPub ID. | 4.938891 | 3.106537 | 1.589838 |
# noinspection PyBroadException
try:
data = json.loads(decode_if_bytes(request.body))
if "@context" in data:
return True
except Exception:
pass
return False | def identify_request(request: RequestType) -> bool | Try to identify whether this is an ActivityPub request. | 4.332961 | 3.511626 | 1.23389 |
if hasattr(entity, "outbound_doc") and entity.outbound_doc is not None:
# Use pregenerated outbound document
rendered = entity.outbound_doc
else:
rendered = entity.to_as2()
return rendered | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict] | Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
... | 8.173697 | 9.078632 | 0.900323 |
self.user = user
self.get_contact_key = sender_key_fetcher
self.payload = json.loads(decode_if_bytes(request.body))
self.request = request
self.extract_actor()
# Verify the message is from who it claims to be
if not skip_author_verification:
s... | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict] | Receive a request.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. | 4.935153 | 4.810794 | 1.02585 |
configuration = {
"get_object_function": None,
"hcard_path": "/hcard/users/",
"nodeinfo2_function": None,
"process_payload_function": None,
"search_path": None,
# TODO remove or default to True once AP support is more ready
"activitypub": False,
}
... | def get_configuration() | Combine defaults with the Django configuration. | 7.649868 | 7.334478 | 1.043001 |
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return func | def get_function_from_config(item) | Import the function to get profile by handle. | 2.23515 | 2.055894 | 1.087191 |
from federation.utils.activitypub import retrieve_and_parse_profile # Circulars
try:
from federation.utils.django import get_function_from_config
except ImportError:
logger.warning("ActivitypubFollow.post_receive - Unable to send automatic Accept back, only supp... | def post_receive(self) -> None | Post receive hook - send back follow ack. | 4.747478 | 4.559222 | 1.041291 |
document, status_code, ex = fetch_document(fid, extra_headers={'accept': 'application/activity+json'})
if document:
document = json.loads(decode_if_bytes(document))
entities = message_to_objects(document, fid)
if entities:
return entities[0] | def retrieve_and_parse_document(fid: str) -> Optional[Any] | Retrieve remote document by ID and return the entity. | 6.963616 | 6.104089 | 1.140812 |
profile = retrieve_and_parse_document(fid)
if not profile:
return
try:
profile.validate()
except ValueError as ex:
logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
profile, ex)
return
return profile | def retrieve_and_parse_profile(fid: str) -> Optional[ActivitypubProfile] | Retrieve the remote fid and return a Profile object. | 4.193529 | 4.011246 | 1.045443 |
# type: (str, Union[str, RequestType]) -> str
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
if getattr(protocol, f"identify_{method}")(value):
return protocol
else:
raise NoSuitableProtocolFoundEr... | def identify_protocol(method, value) | Loop through protocols, import the protocol module and try to identify the id or request. | 4.559424 | 4.122902 | 1.105877 |
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "encrypted_magic_envelope" in data:
return True
except Exception:
pass
# Public XML payload
try:
xml = etree.fromstring(encode_if_text(request.body))
if ... | def identify_request(request: RequestType) | Try to identify whether this is a Diaspora request.
Try first public message. Then private message. The check if this is a legacy payload. | 5.219907 | 4.481296 | 1.164821 |
private_key = self._get_user_key()
return EncryptedPayload.decrypt(payload=payload, private_key=private_key) | def get_json_payload_magic_envelope(self, payload) | Encrypted JSON payload | 7.228609 | 5.91897 | 1.221261 |
try:
json_payload = json.loads(decode_if_bytes(payload))
except ValueError:
# XML payload
xml = unquote(decode_if_bytes(payload))
xml = xml.lstrip().encode("utf-8")
logger.debug("diaspora.protocol.store_magic_envelope_doc: xml payload:... | def store_magic_envelope_doc(self, payload) | Get the Magic Envelope, trying JSON first. | 3.040919 | 2.928366 | 1.038435 |
self.user = user
self.get_contact_key = sender_key_fetcher
self.store_magic_envelope_doc(request.body)
# Open payload and get actual message
self.content = self.get_message_content()
# Get sender handle
self.sender_handle = self.get_sender()
# Ver... | def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, str] | Receive a payload.
For testing purposes, `skip_author_verification` can be passed. Authorship will not be verified. | 6.027648 | 5.917463 | 1.01862 |
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_content: %s", body)
return body | def get_message_content(self) | Given the Slap XML, extract out the payload. | 9.804121 | 8.134549 | 1.205245 |
if self.get_contact_key:
sender_key = self.get_contact_key(self.sender_handle)
else:
sender_key = fetch_public_key(self.sender_handle)
if not sender_key:
raise NoSenderKeyFoundError("Could not find a sender contact to retrieve key")
MagicEnvel... | def verify_signature(self) | Verify the signed XML elements to have confidence that the claimed
author did actually generate this message. | 6.241685 | 5.719914 | 1.09122 |
if entity.outbound_doc is not None:
# Use pregenerated outbound document
xml = entity.outbound_doc
else:
xml = entity.to_xml()
me = MagicEnvelope(etree.tostring(xml), private_key=from_user.private_key, author_handle=from_user.handle)
rendered ... | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict] | Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
... | 6.179458 | 6.033902 | 1.024123 |
if self.reaction not in self._reaction_valid_values:
raise ValueError("reaction should be one of: {valid}".format(
valid=", ".join(self._reaction_valid_values)
)) | def validate_reaction(self) | Ensure reaction is of a certain type.
Mainly for future expansion. | 3.865012 | 3.568503 | 1.083091 |
if self.relationship not in self._relationship_valid_values:
raise ValueError("relationship should be one of: {valid}".format(
valid=", ".join(self._relationship_valid_values)
)) | def validate_relationship(self) | Ensure relationship is of a certain type. | 3.588706 | 2.882423 | 1.245031 |
def inner(request, *args, **kwargs):
def get(request, *args, **kwargs):
# TODO remove once AP support is more ready
config = get_configuration()
if not config.get("activitypub"):
return func(request, *args, **kwargs)
fallback = True
... | def activitypub_object_view(func) | Generic ActivityPub object view decorator.
Takes an ID and fetches it using the provided function. Renders the ActivityPub object
in JSON if the object is found. Falls back to decorated view, if the content
type doesn't match. | 2.654415 | 2.70106 | 0.982731 |
entities = []
cls = MAPPINGS.get(payload.get('type'))
if not cls:
return []
transformed = transform_attributes(payload, cls)
entity = cls(**transformed)
if hasattr(entity, "post_receive"):
entity.post_receive()
entities.append(entity)
return entities | def element_to_objects(payload: Dict) -> List | Transform an Element to a list of entities recursively. | 5.170859 | 4.726573 | 1.093998 |
if getattr(entity, "outbound_doc", None):
# If the entity already has an outbound doc, just return the entity as is
return entity
outbound = None
cls = entity.__class__
if cls in [ActivitypubAccept, ActivitypubFollow, ActivitypubProfile]:
# Already fine
outbound = en... | def get_outbound_entity(entity: BaseEntity, private_key) | Get the correct outbound entity for this protocol.
We might have to look at entity values to decide the correct outbound entity.
If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol.
Private key of author is needed to be passed for signing the outbound entity.
... | 6.421063 | 6.08176 | 1.05579 |
# We only really expect one element here for ActivityPub.
return element_to_objects(message) | def message_to_objects(
message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List | Takes in a message extracted by a protocol and maps it to entities. | 54.12751 | 41.565632 | 1.302218 |
attributes = []
validates = []
# Collect attributes and validation methods
for attr in dir(self):
if not attr.startswith("_"):
attr_type = type(getattr(self, attr))
if attr_type != "method":
if getattr(self, "valida... | def validate(self) | Do validation.
1) Check `_required` have been given
2) Make sure all attrs in required have a non-empty value
3) Loop through attributes and call their `validate_<attr>` methods, if any.
4) Validate allowed children
5) Validate signatures | 3.20788 | 2.657452 | 1.207126 |
required_fulfilled = set(self._required).issubset(set(attributes))
if not required_fulfilled:
raise ValueError(
"Not all required attributes fulfilled. Required: {required}".format(required=set(self._required))
) | def _validate_required(self, attributes) | Ensure required attributes are present. | 4.183239 | 3.736502 | 1.11956 |
attrs_to_check = set(self._required) & set(attributes)
for attr in attrs_to_check:
value = getattr(self, attr) # We should always have a value here
if value is None or value == "":
raise ValueError(
"Attribute %s cannot be None or an ... | def _validate_empty_attributes(self, attributes) | Check that required attributes are not empty. | 3.876076 | 3.446497 | 1.124642 |
for child in self._children:
if child.__class__ not in self._allowed_children:
raise ValueError(
"Child %s is not allowed as a children for this %s type entity." % (
child, self.__class__
)
) | def _validate_children(self) | Check that the children we have are allowed here. | 4.21513 | 3.362582 | 1.253539 |
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)) | def validate_participation(self) | Ensure participation is of a certain type. | 3.536795 | 2.831213 | 1.249215 |
if not self.raw_content:
return set()
return {word.strip("#").lower() for word in self.raw_content.split() if word.startswith("#") and len(word) > 1} | def tags(self) | Returns a `set` of unique tags contained in `raw_content`. | 3.947916 | 2.433268 | 1.622475 |
mappers = importlib.import_module(f"federation.entities.{protocol_name}.mappers")
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
protocol = protocol.Protocol()
outbound_entity = mappers.get_outbound_entity(entity, author_user.private_key)
if parent_user:
... | def handle_create_payload(
entity: BaseEntity,
author_user: UserType,
protocol_name: str,
to_user_key: RsaKey = None,
parent_user: UserType = None,
) -> str | Create a payload with the given protocol.
Any given user arguments must have ``private_key`` and ``handle`` attributes.
:arg entity: Entity object to send. Can be a base entity or a protocol specific one.
:arg author_user: User authoring the object.
:arg protocol_name: Protocol to create payload for.
... | 3.269735 | 3.097732 | 1.055525 |
key_id = doc.find(".//{%s}sig" % NAMESPACE).get("key_id")
return urlsafe_b64decode(key_id).decode("utf-8") | def get_sender(doc) | Get the key_id from the `sig` element which contains urlsafe_b64encoded Diaspora handle.
:param doc: ElementTree document
:returns: Diaspora handle | 7.303446 | 3.790582 | 1.926735 |
doc = etree.fromstring(self.message)
self.payload = etree.tostring(doc, encoding="utf-8")
self.payload = urlsafe_b64encode(self.payload).decode("ascii")
return self.payload | def create_payload(self) | Create the payload doc.
Returns:
str | 3.368608 | 4.010933 | 0.839856 |
sig_contents = \
self.payload + "." + \
b64encode(b"application/xml").decode("ascii") + "." + \
b64encode(b"base64url").decode("ascii") + "." + \
b64encode(b"RSA-SHA256").decode("ascii")
sig_hash = SHA256.new(sig_contents.encode("ascii"))
... | def _build_signature(self) | Create the signature using the private key. | 2.967874 | 2.84388 | 1.0436 |
if not self.public_key:
self.fetch_public_key()
data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text
sig_contents = '.'.join([
data,
b64encode... | def verify(self) | Verify Magic Envelope document against public key. | 3.250741 | 2.961211 | 1.097774 |
if not hasattr(self, "raw_content"):
return set()
mentions = re.findall(r'@{[^;]+; [\w.-]+@[^}]+}', self.raw_content)
if not mentions:
return set()
mentions = {s.split(';')[1].strip(' }') for s in mentions}
mentions = {s for s in mentions}
... | def extract_mentions(self) | Extract mentions from an entity with ``raw_content``.
:return: set | 4.635924 | 4.397446 | 1.054231 |
iplookup = ipdata.ipdata()
data = iplookup.lookup(ip)
if data.get('status') != 200:
return ''
return data.get('response', {}).get('country_code', '') | def fetch_country_by_ip(ip) | Fetches country code by IP
Returns empty string if the request fails in non-200 code.
Uses the ipdata.co service which has the following rules:
* Max 1500 requests per day
See: https://ipdata.co/docs.html#python-library | 4.321236 | 3.580608 | 1.206844 |
if not url and not host:
raise ValueError("Need url or host.")
logger.debug("fetch_document: url=%s, host=%s, path=%s, timeout=%s, raise_ssl_errors=%s",
url, host, path, timeout, raise_ssl_errors)
headers = {'user-agent': USER_AGENT}
if extra_headers:
headers.updat... | def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None) | Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `path` will be added to it. Will fall back to http on non-success status code.
:arg url: Full url to fetch, inc... | 1.739863 | 1.693833 | 1.027175 |
try:
ip = socket.gethostbyname(host)
except socket.gaierror:
return ''
return ip | def fetch_host_ip(host: str) -> str | Fetch ip by host | 3.48891 | 2.691251 | 1.296389 |
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | def fetch_host_ip_and_country(host: str) -> Tuple | Fetch ip and country by host | 4.646923 | 3.492777 | 1.330438 |
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
__D = r'(?P<day>\d{2})'
__D2 = r'(?P<day>[ \d]\d)'
__M = r'(?P<mon>\w{3})'
__Y = r'(?P<year>\d{4})'
__Y2 = r'(?P<year>\d{2})'
__T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
RFC1123_DATE = re.compile(r'^\w{3},... | def parse_http_date(date) | Parse a date format as specified by HTTP RFC7231 section 7.1.1.1.
The three formats allowed by the RFC are accepted, even if only the first
one is still in widespread use.
Return an integer expressed in seconds since the epoch, in UTC.
Implementation copied from Django.
https://github.com/django/... | 2.049644 | 2.055692 | 0.997058 |
logger.debug("send_document: url=%s, data=%s, timeout=%s", url, data, timeout)
headers = CaseInsensitiveDict({
'User-Agent': USER_AGENT,
})
if "headers" in kwargs:
# Update from kwargs
headers.update(kwargs.get("headers"))
kwargs.update({
"data": data, "timeout":... | def send_document(url, data, timeout=10, *args, **kwargs) | Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: Dictionary (will be form-encoded), bytes, or file-like object to send in the body
:arg timeout: Seconds to wait for resp... | 2.368992 | 2.325772 | 1.018583 |
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(
headers=["(request-target)", "user-agent", "host", "date"],
algorithm="rsa-sha256",
key=key,
key_id=private_key_id,
) | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth | Get HTTP signature authentication for a request. | 3.269014 | 3.211924 | 1.017774 |
key = encode_if_text(public_key)
date_header = request.headers.get("Date")
if not date_header:
raise ValueError("Rquest Date header is missing")
ts = parse_http_date(date_header)
dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
delta = datetime.timedelta(seconds... | def verify_request_signature(request: RequestType, public_key: Union[str, bytes]) | Verify HTTP signature in request against a public key. | 3.548759 | 3.281456 | 1.081459 |
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"text": self.raw_content},
{"guid": self.guid},
{"author": self.handle},
{"public": "true" if self.public else "false"},
{"created_at": format_dt(self.created_at)},
... | def to_xml(self) | Convert to XML message. | 4.565282 | 4.427685 | 1.031077 |
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"recipient": self.target_handle},
{"following": "true" if self.following else "false"},
{"sharing": "true" if self.following else "false"},
])
... | def to_xml(self) | Convert to XML message. | 6.197326 | 5.629129 | 1.100939 |
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"first_name": self.name},
{"last_name": ""}, # We only have one field - splitting it would be artificial
{"image_url": self.image_urls["large"]},
... | def to_xml(self) | Convert to XML message. | 4.194446 | 4.139926 | 1.013169 |
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"target_guid": self.target_guid},
{"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)},
])
return element | def to_xml(self) | Convert to XML message. | 9.366492 | 8.998362 | 1.040911 |
if value in DiasporaRetraction.mapped.values():
values = list(DiasporaRetraction.mapped.values())
index = values.index(value)
return list(DiasporaRetraction.mapped.keys())[index]
return value | def entity_type_to_remote(value) | Convert entity type between our Entity names and Diaspora names. | 4.962214 | 3.663752 | 1.354408 |
attributes = {}
cls = entity.__class__
for attr, _ in inspect.getmembers(cls, lambda o: not isinstance(o, property) and not inspect.isroutine(o)):
if not attr.startswith("_"):
attributes[attr] = getattr(entity, attr)
return attributes | def get_base_attributes(entity) | Build a dict of attributes of an entity.
Returns attributes and their values, ignoring any properties, functions and anything that starts
with an underscore. | 2.680027 | 2.585156 | 1.036698 |
val = block_size - len(inp) % block_size
if val == 0:
return inp + (bytes([block_size]) * block_size)
else:
return inp + (bytes([val]) * val) | def pkcs7_pad(inp, block_size) | Using the PKCS#7 padding scheme, pad <inp> to be a multiple of
<block_size> bytes. Ruby's AES encryption pads with this scheme, but
pycrypto doesn't support it.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 | 2.522226 | 3.009272 | 0.838151 |
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
return data[0:-data[-1]] | def pkcs7_unpad(data) | Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 | 2.530672 | 2.583324 | 0.979618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.