repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
deeplook/svglib
svglib/svglib.py
AttributeConverter.getAllAttributes
python
def getAllAttributes(self, svgNode): "Return a dictionary of all attributes of svgNode or those inherited by it." dict = {} if node_name(svgNode.getparent()) == 'g': dict.update(self.getAllAttributes(svgNode.getparent())) style = svgNode.attrib.get("style") if styl...
Return a dictionary of all attributes of svgNode or those inherited by it.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L225-L242
[ "def node_name(node):\n \"\"\"Return lxml node name without the namespace prefix.\"\"\"\n\n try:\n return node.tag.split('}')[-1]\n except AttributeError:\n pass\n", "def getAllAttributes(self, svgNode):\n \"Return a dictionary of all attributes of svgNode or those inherited by it.\"\n\n...
class AttributeConverter(object): "An abstract class to locate and convert attributes in a DOM instance." def __init__(self): self.css_rules = None def parseMultiAttributes(self, line): """Try parsing compound attribute string. Return a dictionary with single attributes in 'line'....
deeplook/svglib
svglib/svglib.py
AttributeConverter.convertTransform
python
def convertTransform(self, svgAttr): line = svgAttr.strip() ops = line[:] brackets = [] indices = [] for i, lin in enumerate(line): if lin in "()": brackets.append(i) for i in range(0, len(brackets), 2): bi, bj = brackets[i], brac...
Parse transform attribute string. E.g. "scale(2) translate(10,20)" -> [("scale", 2), ("translate", (10,20))]
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L248-L287
null
class AttributeConverter(object): "An abstract class to locate and convert attributes in a DOM instance." def __init__(self): self.css_rules = None def parseMultiAttributes(self, line): """Try parsing compound attribute string. Return a dictionary with single attributes in 'line'....
deeplook/svglib
svglib/svglib.py
Svg2RlgAttributeConverter.convertLength
python
def convertLength(self, svgAttr, percentOf=100, em_base=12): "Convert length to points." text = svgAttr if not text: return 0.0 if ' ' in text.replace(',', ' ').strip(): logger.debug("Only getting first value of %s" % text) text = text.replace(',', ' ...
Convert length to points.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L305-L334
null
class Svg2RlgAttributeConverter(AttributeConverter): "A concrete SVG to RLG attribute converter." def __init__(self, color_converter=None): super(Svg2RlgAttributeConverter, self).__init__() self.color_converter = color_converter or self.identity_color_converter @staticmethod def identi...
deeplook/svglib
svglib/svglib.py
Svg2RlgAttributeConverter.convertLengthList
python
def convertLengthList(self, svgAttr): return [self.convertLength(a) for a in self.split_attr_list(svgAttr)]
Convert a list of lengths.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L336-L338
[ "def split_attr_list(attr):\n return shlex.split(attr.strip().replace(',', ' '))\n" ]
class Svg2RlgAttributeConverter(AttributeConverter): "A concrete SVG to RLG attribute converter." def __init__(self, color_converter=None): super(Svg2RlgAttributeConverter, self).__init__() self.color_converter = color_converter or self.identity_color_converter @staticmethod def identi...
deeplook/svglib
svglib/svglib.py
Svg2RlgAttributeConverter.convertColor
python
def convertColor(self, svgAttr): "Convert string to a RL color object." # fix it: most likely all "web colors" are allowed predefined = "aqua black blue fuchsia gray green lime maroon navy " predefined = predefined + "olive orange purple red silver teal white yellow " predefined...
Convert string to a RL color object.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L349-L384
null
class Svg2RlgAttributeConverter(AttributeConverter): "A concrete SVG to RLG attribute converter." def __init__(self, color_converter=None): super(Svg2RlgAttributeConverter, self).__init__() self.color_converter = color_converter or self.identity_color_converter @staticmethod def identi...
deeplook/svglib
svglib/svglib.py
SvgRenderer.get_clippath
python
def get_clippath(self, node): def get_path_from_node(node): for child in node.getchildren(): if node_name(child) == 'path': group = self.shape_converter.convertShape('path', NodeTracker(child)) return group.contents[-1] else: ...
Return the clipping Path object referenced by the node 'clip-path' attribute, if any.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L626-L648
[ "def get_path_from_node(node):\n for child in node.getchildren():\n if node_name(child) == 'path':\n group = self.shape_converter.convertShape('path', NodeTracker(child))\n return group.contents[-1]\n else:\n return get_path_from_node(child)\n" ]
class SvgRenderer: """Renderer that renders an SVG file on a ReportLab Drawing instance. This is the base class for walking over an SVG DOM document and transforming it into a ReportLab Drawing instance. """ def __init__(self, path, color_converter=None, parent_svgs=None): self.source_path...
deeplook/svglib
svglib/svglib.py
SvgRenderer.xlink_href_target
python
def xlink_href_target(self, node, group=None): xlink_href = node.attrib.get('{http://www.w3.org/1999/xlink}href') if not xlink_href: return None # First handle any raster embedded image data match = re.match(r"^data:image/(jpeg|png);base64", xlink_href) if match: ...
Return either: - a tuple (renderer, node) when the the xlink:href attribute targets a vector file or node - the path to an image file for any raster image targets - None if any problem occurs
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L666-L744
null
class SvgRenderer: """Renderer that renders an SVG file on a ReportLab Drawing instance. This is the base class for walking over an SVG DOM document and transforming it into a ReportLab Drawing instance. """ def __init__(self, path, color_converter=None, parent_svgs=None): self.source_path...
deeplook/svglib
svglib/svglib.py
Svg2RlgShapeConverter.clean_text
python
def clean_text(self, text, preserve_space): if text is None: return if preserve_space: text = text.replace('\r\n', ' ').replace('\n', ' ').replace('\t', ' ') else: text = text.replace('\r\n', '').replace('\n', '').replace('\t', ' ') text = text.str...
Text cleaning as per https://www.w3.org/TR/SVG/text.html#WhiteSpace
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L977-L989
null
class Svg2RlgShapeConverter(SvgShapeConverter): """Converter from SVG shapes to RLG (ReportLab Graphics) shapes.""" def convertShape(self, name, node, clipping=None): method_name = "convert%s" % name.capitalize() shape = getattr(self, method_name)(node) if not shape: return ...
deeplook/svglib
svglib/svglib.py
Svg2RlgShapeConverter.applyTransformOnGroup
python
def applyTransformOnGroup(self, transform, group): tr = self.attrConverter.convertTransform(transform) for op, values in tr: if op == "scale": if not isinstance(values, tuple): values = (values, values) group.scale(*values) eli...
Apply an SVG transformation to a RL Group shape. The transformation is the value of an SVG transform attribute like transform="scale(1, -1) translate(10, 30)". rotate(<angle> [<cx> <cy>]) is equivalent to: translate(<cx> <cy>) rotate(<angle>) translate(-<cx> -<cy>)
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L1231-L1267
null
class Svg2RlgShapeConverter(SvgShapeConverter): """Converter from SVG shapes to RLG (ReportLab Graphics) shapes.""" def convertShape(self, name, node, clipping=None): method_name = "convert%s" % name.capitalize() shape = getattr(self, method_name)(node) if not shape: return ...
deeplook/svglib
svglib/svglib.py
Svg2RlgShapeConverter.applyStyleOnShape
python
def applyStyleOnShape(self, shape, node, only_explicit=False): # RLG-specific: all RLG shapes "Apply style attributes of a sequence of nodes to an RL shape." # tuple format: (svgAttr, rlgAttr, converter, default) mappingN = ( ("fill", "fillColor", "convertColor", "black"), ...
Apply styles from an SVG element to an RLG shape. If only_explicit is True, only attributes really present are applied.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/svglib.py#L1269-L1321
[ "def applyStyleOnShape(self, shape, node, only_explicit=False):\n \"\"\"\n Apply styles from an SVG element to an RLG shape.\n If only_explicit is True, only attributes really present are applied.\n \"\"\"\n\n # RLG-specific: all RLG shapes\n \"Apply style attributes of a sequence of nodes to an R...
class Svg2RlgShapeConverter(SvgShapeConverter): """Converter from SVG shapes to RLG (ReportLab Graphics) shapes.""" def convertShape(self, name, node, clipping=None): method_name = "convert%s" % name.capitalize() shape = getattr(self, method_name)(node) if not shape: return ...
deeplook/svglib
svglib/utils.py
split_floats
python
def split_floats(op, min_num, value): floats = [float(seq) for seq in re.findall(r'(-?\d*\.?\d*(?:e[+-]\d+)?)', value) if seq] res = [] for i in range(0, len(floats), min_num): if i > 0 and op in {'m', 'M'}: op = 'l' if op == 'm' else 'L' res.extend([op, floats[i:i + min_num]]) ...
Split `value`, a list of numbers as a string, to a list of float numbers. Also optionally insert a `l` or `L` operation depending on the operation and the length of values. Example: with op='m' and value='10,20 30,40,' the returned value will be ['m', [10.0, 20.0], 'l', [30.0, 40.0]]
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/utils.py#L11-L25
null
""" This is a collection of utilities used by the ``svglib`` code module. """ import re from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt from reportlab.graphics.shapes import mmult, rotate, translate, transformPoint def normalise_svg_path(attr): """Normalise SVG path. T...
deeplook/svglib
svglib/utils.py
normalise_svg_path
python
def normalise_svg_path(attr): # operator codes mapped to the minimum number of expected arguments ops = { 'A': 7, 'a': 7, 'Q': 4, 'q': 4, 'T': 2, 't': 2, 'S': 4, 's': 4, 'M': 2, 'L': 2, 'm': 2, 'l': 2, 'H': 1, 'V': 1, 'h': 1, 'v': 1, 'C': 6, 'c': 6, 'Z': 0, 'z': 0, } op_...
Normalise SVG path. This basically introduces operator codes for multi-argument parameters. Also, it fixes sequences of consecutive M or m operators to MLLL... and mlll... operators. It adds an empty list as argument for Z and z only in order to make the resul- ting list easier to iterate over. ...
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/utils.py#L28-L72
[ "def split_floats(op, min_num, value):\n \"\"\"Split `value`, a list of numbers as a string, to a list of float numbers.\n\n Also optionally insert a `l` or `L` operation depending on the operation\n and the length of values.\n Example: with op='m' and value='10,20 30,40,' the returned value will be\n ...
""" This is a collection of utilities used by the ``svglib`` code module. """ import re from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt from reportlab.graphics.shapes import mmult, rotate, translate, transformPoint def split_floats(op, min_num, value): """Split `value`, a li...
deeplook/svglib
svglib/utils.py
convert_quadratic_to_cubic_path
python
def convert_quadratic_to_cubic_path(q0, q1, q2): c0 = q0 c1 = (q0[0] + 2. / 3 * (q1[0] - q0[0]), q0[1] + 2. / 3 * (q1[1] - q0[1])) c2 = (c1[0] + 1. / 3 * (q2[0] - q0[0]), c1[1] + 1. / 3 * (q2[1] - q0[1])) c3 = q2 return c0, c1, c2, c3
Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one.
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/utils.py#L75-L83
null
""" This is a collection of utilities used by the ``svglib`` code module. """ import re from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt from reportlab.graphics.shapes import mmult, rotate, translate, transformPoint def split_floats(op, min_num, value): """Split `value`, a li...
deeplook/svglib
svglib/utils.py
end_point_to_center_parameters
python
def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0): ''' See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 note that we reduce phi to zero outside this routine ''' rx = fabs(rx) ry = fabs(ry) # step 1 if phi: phi_rad = radians(phi) ...
See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 note that we reduce phi to zero outside this routine
train
https://github.com/deeplook/svglib/blob/859f9f461f1041018af3e6f507bb4c0616b04fbb/svglib/utils.py#L103-L178
[ "def vector_angle(u, v):\n d = hypot(*u) * hypot(*v)\n if d == 0:\n return 0\n c = (u[0] * v[0] + u[1] * v[1]) / d\n if c < -1:\n c = -1\n elif c > 1:\n c = 1\n s = u[0] * v[1] - u[1] * v[0]\n return degrees(copysign(acos(c), s))\n" ]
""" This is a collection of utilities used by the ``svglib`` code module. """ import re from math import acos, ceil, copysign, cos, degrees, fabs, hypot, radians, sin, sqrt from reportlab.graphics.shapes import mmult, rotate, translate, transformPoint def split_floats(op, min_num, value): """Split `value`, a li...
stephenmcd/django-socketio
django_socketio/views.py
socketio
python
def socketio(request): context = {} socket = SocketIOChannelProxy(request.environ["socketio"]) client_start(request, socket, context) try: if socket.on_connect(): events.on_connect.send(request, socket, context) while True: messages = socket.recv() if ...
Socket.IO handler - maintains the lifecycle of a Socket.IO request, sending the each of the events. Also handles adding/removing request/socket pairs to the CLIENTS dict which is used for sending on_finish events when the server stops.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/views.py#L10-L62
[ "def client_start(request, socket, context):\n \"\"\"\n Adds the client triple to CLIENTS.\n \"\"\"\n CLIENTS[socket.session.session_id] = (request, socket, context)\n", "def client_end(request, socket, context):\n \"\"\"\n Handles cleanup when a session ends for the given client triple.\n Se...
from django.http import HttpResponse from django_socketio import events from django_socketio.channels import SocketIOChannelProxy from django_socketio.clients import client_start, client_end from django_socketio.utils import format_log
stephenmcd/django-socketio
django_socketio/clients.py
client_start
python
def client_start(request, socket, context): CLIENTS[socket.session.session_id] = (request, socket, context)
Adds the client triple to CLIENTS.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/clients.py#L11-L15
null
from django_socketio import events # Maps open Socket.IO session IDs to request/socket pairs for # running cleanup code and events when the server is shut down # or reloaded. CLIENTS = {} def client_end(request, socket, context): """ Handles cleanup when a session ends for the given client triple. Sen...
stephenmcd/django-socketio
django_socketio/clients.py
client_end
python
def client_end(request, socket, context): # Send the unsubscribe event prior to actually unsubscribing, so # that the finish event can still match channels if applicable. for channel in socket.channels: events.on_unsubscribe.send(request, socket, context, channel) events.on_finish.send(request, ...
Handles cleanup when a session ends for the given client triple. Sends unsubscribe and finish events, actually unsubscribes from any channels subscribed to, and removes the client triple from CLIENTS.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/clients.py#L18-L34
[ "def unsubscribe(self, channel):\n \"\"\"\n Remove the channel from this socket's channels, and from the\n list of subscribed session IDs for the channel. Return False\n if not subscribed, otherwise True.\n \"\"\"\n try:\n CHANNELS[channel].remove(self.socket.session.session_id)\n se...
from django_socketio import events # Maps open Socket.IO session IDs to request/socket pairs for # running cleanup code and events when the server is shut down # or reloaded. CLIENTS = {} def client_start(request, socket, context): """ Adds the client triple to CLIENTS. """ CLIENTS[socket.session.s...
stephenmcd/django-socketio
django_socketio/clients.py
client_end_all
python
def client_end_all(): for request, socket, context in CLIENTS.values()[:]: client_end(request, socket, context)
Performs cleanup on all clients - called by runserver_socketio when the server is shut down or reloaded.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/clients.py#L37-L43
[ "def client_end(request, socket, context):\n \"\"\"\n Handles cleanup when a session ends for the given client triple.\n Sends unsubscribe and finish events, actually unsubscribes from\n any channels subscribed to, and removes the client triple from\n CLIENTS.\n \"\"\"\n # Send the unsubscribe ...
from django_socketio import events # Maps open Socket.IO session IDs to request/socket pairs for # running cleanup code and events when the server is shut down # or reloaded. CLIENTS = {} def client_start(request, socket, context): """ Adds the client triple to CLIENTS. """ CLIENTS[socket.session.s...
stephenmcd/django-socketio
django_socketio/channels.py
SocketIOChannelProxy.subscribe
python
def subscribe(self, channel): if channel in self.channels: return False CHANNELS[channel].append(self.socket.session.session_id) self.channels.append(channel) return True
Add the channel to this socket's channels, and to the list of subscribed session IDs for the channel. Return False if already subscribed, otherwise True.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/channels.py#L22-L32
null
class SocketIOChannelProxy(object): """ Proxy object for SocketIOProtocol that adds channel subscription and broadcast. """ def __init__(self, socket): """ Store the original socket protocol object. """ self.socket = socket self.channels = [] # store our subs...
stephenmcd/django-socketio
django_socketio/channels.py
SocketIOChannelProxy.unsubscribe
python
def unsubscribe(self, channel): try: CHANNELS[channel].remove(self.socket.session.session_id) self.channels.remove(channel) except ValueError: return False return True
Remove the channel from this socket's channels, and from the list of subscribed session IDs for the channel. Return False if not subscribed, otherwise True.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/channels.py#L34-L45
null
class SocketIOChannelProxy(object): """ Proxy object for SocketIOProtocol that adds channel subscription and broadcast. """ def __init__(self, socket): """ Store the original socket protocol object. """ self.socket = socket self.channels = [] # store our subs...
stephenmcd/django-socketio
django_socketio/channels.py
SocketIOChannelProxy.broadcast_channel
python
def broadcast_channel(self, message, channel=None): if channel is None: channels = self.channels else: channels = [channel] for channel in channels: for subscriber in CHANNELS[channel]: if subscriber != self.socket.session.session_id: ...
Send the given message to all subscribers for the channel given. If no channel is given, send to the subscribers for all the channels that this socket is subscribed to.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/channels.py#L47-L61
null
class SocketIOChannelProxy(object): """ Proxy object for SocketIOProtocol that adds channel subscription and broadcast. """ def __init__(self, socket): """ Store the original socket protocol object. """ self.socket = socket self.channels = [] # store our subs...
stephenmcd/django-socketio
django_socketio/channels.py
SocketIOChannelProxy.send_and_broadcast_channel
python
def send_and_broadcast_channel(self, message, channel=None): self.send(message) self.broadcast_channel(message, channel)
Shortcut for a socket to broadcast to all sockets subscribed to a channel, and itself.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/channels.py#L70-L76
[ "def broadcast_channel(self, message, channel=None):\n \"\"\"\n Send the given message to all subscribers for the channel\n given. If no channel is given, send to the subscribers for\n all the channels that this socket is subscribed to.\n \"\"\"\n if channel is None:\n channels = self.chann...
class SocketIOChannelProxy(object): """ Proxy object for SocketIOProtocol that adds channel subscription and broadcast. """ def __init__(self, socket): """ Store the original socket protocol object. """ self.socket = socket self.channels = [] # store our subs...
stephenmcd/django-socketio
django_socketio/example_project/chat/events.py
message
python
def message(request, socket, context, message): room = get_object_or_404(ChatRoom, id=message["room"]) if message["action"] == "start": name = strip_tags(message["name"]) user, created = room.users.get_or_create(name=name) if not created: socket.send({"action": "in-use"}) ...
Event handler for a room receiving a message. First validates a joining user's name and sends them the list of users.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/events.py#L10-L37
null
from django.shortcuts import get_object_or_404 from django.utils.html import strip_tags from django_socketio import events from chat.models import ChatRoom @events.on_message(channel="^room-") @events.on_finish(channel="^room-") def finish(request, socket, context): """ Event handler for a socket session...
stephenmcd/django-socketio
django_socketio/example_project/chat/events.py
finish
python
def finish(request, socket, context): try: user = context["user"] except KeyError: return left = {"action": "leave", "name": user.name, "id": user.id} socket.broadcast_channel(left) user.delete()
Event handler for a socket session ending in a room. Broadcast the user leaving and delete them from the DB.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/events.py#L41-L52
null
from django.shortcuts import get_object_or_404 from django.utils.html import strip_tags from django_socketio import events from chat.models import ChatRoom @events.on_message(channel="^room-") def message(request, socket, context, message): """ Event handler for a room receiving a message. First validates a...
stephenmcd/django-socketio
django_socketio/utils.py
send
python
def send(session_id, message): try: socket = CLIENTS[session_id][1] except KeyError: raise NoSocket("There is no socket with the session ID: " + session_id) socket.send(message)
Send a message to the socket for the given session ID.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/utils.py#L14-L22
null
from datetime import datetime from django_socketio.channels import CHANNELS from django_socketio.clients import CLIENTS class NoSocket(Exception): """ Raised when no clients are available to broadcast to. """ def broadcast(message): """ Find the first socket and use it to broadcast to all soc...
stephenmcd/django-socketio
django_socketio/utils.py
broadcast
python
def broadcast(message): try: socket = CLIENTS.values()[0][1] except IndexError: raise NoSocket("There are no clients.") socket.send_and_broadcast(message)
Find the first socket and use it to broadcast to all sockets including the socket itself.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/utils.py#L25-L34
null
from datetime import datetime from django_socketio.channels import CHANNELS from django_socketio.clients import CLIENTS class NoSocket(Exception): """ Raised when no clients are available to broadcast to. """ def send(session_id, message): """ Send a message to the socket for the given session...
stephenmcd/django-socketio
django_socketio/utils.py
broadcast_channel
python
def broadcast_channel(message, channel): try: socket = CLIENTS[CHANNELS.get(channel, [])[0]][1] except (IndexError, KeyError): raise NoSocket("There are no clients on the channel: " + channel) socket.send_and_broadcast_channel(message, channel)
Find the first socket for the given channel, and use it to broadcast to the channel, including the socket itself.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/utils.py#L37-L46
null
from datetime import datetime from django_socketio.channels import CHANNELS from django_socketio.clients import CLIENTS class NoSocket(Exception): """ Raised when no clients are available to broadcast to. """ def send(session_id, message): """ Send a message to the socket for the given session...
stephenmcd/django-socketio
django_socketio/utils.py
format_log
python
def format_log(request, message_type, message): from django_socketio.settings import MESSAGE_LOG_FORMAT if MESSAGE_LOG_FORMAT is None: return None now = datetime.now().replace(microsecond=0) args = dict(request.META, TYPE=message_type, MESSAGE=message, TIME=now) return (MESSAGE_LOG_FORMAT % ...
Formats a log message similar to gevent's pywsgi request logging.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/utils.py#L49-L58
null
from datetime import datetime from django_socketio.channels import CHANNELS from django_socketio.clients import CLIENTS class NoSocket(Exception): """ Raised when no clients are available to broadcast to. """ def send(session_id, message): """ Send a message to the socket for the given session...
stephenmcd/django-socketio
django_socketio/management/commands/runserver_socketio.py
Command.get_handler
python
def get_handler(self, *args, **options): handler = WSGIHandler() try: from django.contrib.staticfiles.handlers import StaticFilesHandler except ImportError: return handler use_static_handler = options.get('use_static_handler', True) insecure_serving = opti...
Returns the django.contrib.staticfiles handler.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/management/commands/runserver_socketio.py#L72-L86
null
class Command(BaseCommand): def handle(self, addrport="", *args, **options): if not addrport: self.addr = HOST self.port = PORT else: m = match(naiveip_re, addrport) if m is None: raise CommandError('"%s" is not a valid port number ' ...
stephenmcd/django-socketio
django_socketio/events.py
Event.send
python
def send(self, request, socket, context, *args): for handler, pattern in self.handlers: no_channel = not pattern and not socket.channels if self.name.endswith("subscribe") and pattern: matches = [pattern.match(args[0])] else: matches = [pattern...
When an event is sent, run all relevant handlers. Relevant handlers are those without a channel pattern when the given socket is not subscribed to any particular channel, or the handlers with a channel pattern that matches any of the channels that the given socket is subscribed to. ...
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/events.py#L53-L71
null
class Event(object): """ Signal-like object for Socket.IO events that supports filtering on channels. Registering event handlers is performed by using the Event instance as a decorator:: @on_message def message(request, socket, message): ... Event handlers can also be r...
stephenmcd/django-socketio
django_socketio/example_project/chat/views.py
rooms
python
def rooms(request, template="rooms.html"): context = {"rooms": ChatRoom.objects.all()} return render(request, template, context)
Homepage - lists all rooms.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/views.py#L9-L14
null
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404, render, redirect from django_socketio import broadcast, broadcast_channel, NoSocket from chat.models import ChatRoom def room(request, slug, template="room.html"): """ Show a room. """ contex...
stephenmcd/django-socketio
django_socketio/example_project/chat/views.py
room
python
def room(request, slug, template="room.html"): context = {"room": get_object_or_404(ChatRoom, slug=slug)} return render(request, template, context)
Show a room.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/views.py#L17-L22
null
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404, render, redirect from django_socketio import broadcast, broadcast_channel, NoSocket from chat.models import ChatRoom def rooms(request, template="rooms.html"): """ Homepage - lists all rooms. """ ...
stephenmcd/django-socketio
django_socketio/example_project/chat/views.py
create
python
def create(request): name = request.POST.get("name") if name: room, created = ChatRoom.objects.get_or_create(name=name) return redirect(room) return redirect(rooms)
Handles post from the "Add room" form on the homepage, and redirects to the new room.
train
https://github.com/stephenmcd/django-socketio/blob/b704f912551829a3bcf15872ba0e1baf81dea106/django_socketio/example_project/chat/views.py#L25-L34
null
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404, render, redirect from django_socketio import broadcast, broadcast_channel, NoSocket from chat.models import ChatRoom def rooms(request, template="rooms.html"): """ Homepage - lists all rooms. """ ...
brean/python-pathfinding
pathfinding/core/util.py
backtrace
python
def backtrace(node): path = [(node.x, node.y)] while node.parent: node = node.parent path.append((node.x, node.y)) path.reverse() return path
Backtrace according to the parent records and return the path. (including both start and end nodes)
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L10-L20
null
# -*- coding: utf-8 -*- import math import copy # square root of 2 for diagonal distance SQRT2 = math.sqrt(2) def bi_backtrace(node_a, node_b): """ Backtrace from start and end node, returns the path for bi-directional A* (including both start and end nodes) """ path_a = backtrace(node_a) p...
brean/python-pathfinding
pathfinding/core/util.py
bi_backtrace
python
def bi_backtrace(node_a, node_b): path_a = backtrace(node_a) path_b = backtrace(node_b) path_b.reverse() return path_a + path_b
Backtrace from start and end node, returns the path for bi-directional A* (including both start and end nodes)
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L23-L31
[ "def backtrace(node):\n \"\"\"\n Backtrace according to the parent records and return the path.\n (including both start and end nodes)\n \"\"\"\n path = [(node.x, node.y)]\n while node.parent:\n node = node.parent\n path.append((node.x, node.y))\n path.reverse()\n return path\n...
# -*- coding: utf-8 -*- import math import copy # square root of 2 for diagonal distance SQRT2 = math.sqrt(2) def backtrace(node): """ Backtrace according to the parent records and return the path. (including both start and end nodes) """ path = [(node.x, node.y)] while node.parent: ...
brean/python-pathfinding
pathfinding/core/util.py
bresenham
python
def bresenham(coords_a, coords_b): ''' Given the start and end coordinates, return all the coordinates lying on the line formed by these coordinates, based on Bresenham's algorithm. http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification ''' line = [] x0, y0 = coords_a x1,...
Given the start and end coordinates, return all the coordinates lying on the line formed by these coordinates, based on Bresenham's algorithm. http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L67-L94
null
# -*- coding: utf-8 -*- import math import copy # square root of 2 for diagonal distance SQRT2 = math.sqrt(2) def backtrace(node): """ Backtrace according to the parent records and return the path. (including both start and end nodes) """ path = [(node.x, node.y)] while node.parent: ...
brean/python-pathfinding
pathfinding/core/util.py
expand_path
python
def expand_path(path): ''' Given a compressed path, return a new path that has all the segments in it interpolated. ''' expanded = [] if len(path) < 2: return expanded for i in range(len(path)-1): expanded += bresenham(path[i], path[i + 1]) expanded += [path[:-1]] ret...
Given a compressed path, return a new path that has all the segments in it interpolated.
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L97-L108
[ "def bresenham(coords_a, coords_b):\n '''\n Given the start and end coordinates, return all the coordinates lying\n on the line formed by these coordinates, based on Bresenham's algorithm.\n http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification\n '''\n line = []\n x0, y0 = coor...
# -*- coding: utf-8 -*- import math import copy # square root of 2 for diagonal distance SQRT2 = math.sqrt(2) def backtrace(node): """ Backtrace according to the parent records and return the path. (including both start and end nodes) """ path = [(node.x, node.y)] while node.parent: ...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.calc_cost
python
def calc_cost(self, node_a, node_b): if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0: # direct neighbor - distance is 1 ng = 1 else: # not a direct neighbor - diagonal movement ng = SQRT2 # weight for weighted algorithms if self.we...
get the distance between current node and the neighbor (cost)
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L57-L72
null
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.apply_heuristic
python
def apply_heuristic(self, node_a, node_b, heuristic=None): if not heuristic: heuristic = self.heuristic return heuristic( abs(node_a.x - node_b.x), abs(node_a.y - node_b.y))
helper function to apply heuristic
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L74-L82
null
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.find_neighbors
python
def find_neighbors(self, grid, node, diagonal_movement=None): ''' find neighbor, same for Djikstra, A*, Bi-A*, IDA* ''' if not diagonal_movement: diagonal_movement = self.diagonal_movement return grid.neighbors(node, diagonal_movement=diagonal_movement)
find neighbor, same for Djikstra, A*, Bi-A*, IDA*
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L84-L90
null
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.keep_running
python
def keep_running(self): if self.runs >= self.max_runs: raise ExecutionRunsException( '{} run into barrier of {} iterations without ' 'finding the destination'.format( self.__class__.__name__, self.max_runs)) if time.time() - self.start_tim...
check, if we run into time or iteration constrains. :returns: True if we keep running and False if we run into a constraint
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L92-L106
null
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.process_node
python
def process_node(self, node, parent, end, open_list, open_value=True): ''' we check if the given node is path of the path by calculating its cost and add or remove it from our path :param node: the node we like to test (the neighbor in A* or jump-node in JumpPointSearch) ...
we check if the given node is path of the path by calculating its cost and add or remove it from our path :param node: the node we like to test (the neighbor in A* or jump-node in JumpPointSearch) :param parent: the parent node (the current node we like to test) :param end: t...
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L108-L140
[ "def calc_cost(self, node_a, node_b):\n \"\"\"\n get the distance between current node and the neighbor (cost)\n \"\"\"\n if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0:\n # direct neighbor - distance is 1\n ng = 1\n else:\n # not a direct neighbor - diagonal movement\n ...
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/finder.py
Finder.find_path
python
def find_path(self, start, end, grid): self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start.opened = True open_list = [start] while len(open_list) > 0: self.runs += 1 self.keep_running() ...
find a path from start to end node on grid by iterating over all neighbors of a node (see check_neighbors) :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L142-L166
[ "def check_neighbors(self, start, end, grid, open_list,\n open_value=True, backtrace_by=None):\n \"\"\"\n find next path segment based on given node\n (or return path if we found the end)\n \"\"\"\n # pop node with minimum 'f' value\n node = heapq.nsmallest(1, open_list)[0]\n ...
class Finder(object): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, weighted=True, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path :param heuristic: heuristic used t...
brean/python-pathfinding
pathfinding/finder/bi_a_star.py
BiAStarFinder.find_path
python
def find_path(self, start, end, grid): self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start_open_list = [start] start.g = 0 start.f = 0 start.opened = BY_START end_open_list = [end] end.g = 0 ...
find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/bi_a_star.py#L38-L77
[ "def check_neighbors(self, start, end, grid, open_list,\n open_value=True, backtrace_by=None):\n \"\"\"\n find next path segment based on given node\n (or return path if we found the end)\n \"\"\"\n # pop node with minimum 'f' value\n node = heapq.nsmallest(1, open_list)[0]\n ...
class BiAStarFinder(AStarFinder): """ Similar to the default A* algorithm from a_star. """ def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortes...
brean/python-pathfinding
pathfinding/core/node.py
Node.cleanup
python
def cleanup(self): # cost from this node to the goal self.h = 0.0 # cost from the start node to this node self.g = 0.0 # distance from start to this point (f = g + h ) self.f = 0.0 self.opened = 0 self.closed = False # used for backtracking to ...
reset all calculated values, fresh start for pathfinding
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/node.py#L30-L52
null
class Node(object): """ basic node, saves X and Y coordinates on some grid and determine if it is walkable. """ def __init__(self, x=0, y=0, walkable=True, weight=1): # Coordinates self.x = x self.y = y # Whether this node can be walked through. self.walkable...
brean/python-pathfinding
pathfinding/core/grid.py
build_nodes
python
def build_nodes(width, height, matrix=None, inverse=False): nodes = [] use_matrix = (isinstance(matrix, (tuple, list))) or \ (USE_NUMPY and isinstance(matrix, np.ndarray) and matrix.size > 0) for y in range(height): nodes.append([]) for x in range(width): # 1, '1', True ...
create nodes according to grid size. If a matrix is given it will be used to determine what nodes are walkable. :rtype : list
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L11-L32
null
# -*- coding: utf-8 -*- from .node import Node try: import numpy as np USE_NUMPY = True except ImportError: USE_NUMPY = False from pathfinding.core.diagonal_movement import DiagonalMovement class Grid(object): def __init__(self, width=0, height=0, matrix=None, inverse=False): """ a gr...
brean/python-pathfinding
pathfinding/core/grid.py
Grid.inside
python
def inside(self, x, y): return 0 <= x < self.width and 0 <= y < self.height
check, if field position is inside map :param x: x pos :param y: y pos :return:
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L61-L68
null
class Grid(object): def __init__(self, width=0, height=0, matrix=None, inverse=False): """ a grid represents the map (as 2d-list of nodes). """ self.width = width self.height = height if isinstance(matrix, (tuple, list)) or ( USE_NUMPY and isinstance(m...
brean/python-pathfinding
pathfinding/core/grid.py
Grid.walkable
python
def walkable(self, x, y): return self.inside(x, y) and self.nodes[y][x].walkable
check, if the tile is inside grid and if it is set as walkable
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L70-L74
[ "def inside(self, x, y):\n \"\"\"\n check, if field position is inside map\n :param x: x pos\n :param y: y pos\n :return:\n \"\"\"\n return 0 <= x < self.width and 0 <= y < self.height\n" ]
class Grid(object): def __init__(self, width=0, height=0, matrix=None, inverse=False): """ a grid represents the map (as 2d-list of nodes). """ self.width = width self.height = height if isinstance(matrix, (tuple, list)) or ( USE_NUMPY and isinstance(m...
brean/python-pathfinding
pathfinding/core/grid.py
Grid.neighbors
python
def neighbors(self, node, diagonal_movement=DiagonalMovement.never): x = node.x y = node.y neighbors = [] s0 = d0 = s1 = d1 = s2 = d2 = s3 = d3 = False # ↑ if self.walkable(x, y - 1): neighbors.append(self.nodes[y - 1][x]) s0 = True # → ...
get all neighbors of one node :param node: node
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L76-L135
[ "def walkable(self, x, y):\n \"\"\"\n check, if the tile is inside grid and if it is set as walkable\n \"\"\"\n return self.inside(x, y) and self.nodes[y][x].walkable\n" ]
class Grid(object): def __init__(self, width=0, height=0, matrix=None, inverse=False): """ a grid represents the map (as 2d-list of nodes). """ self.width = width self.height = height if isinstance(matrix, (tuple, list)) or ( USE_NUMPY and isinstance(m...
brean/python-pathfinding
pathfinding/core/grid.py
Grid.grid_str
python
def grid_str(self, path=None, start=None, end=None, border=True, start_chr='s', end_chr='e', path_chr='x', empty_chr=' ', block_chr='#', show_weight=False): data = '' if border: data = '+{}+'.format('-'*len(self.nodes[0])) for y in r...
create a printable string from the grid using ASCII characters :param path: list of nodes that show the path :param start: start node :param end: end node :param border: create a border around the grid :param start_chr: character for the start (default "s") :param end_ch...
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L142-L188
null
class Grid(object): def __init__(self, width=0, height=0, matrix=None, inverse=False): """ a grid represents the map (as 2d-list of nodes). """ self.width = width self.height = height if isinstance(matrix, (tuple, list)) or ( USE_NUMPY and isinstance(m...
brean/python-pathfinding
pathfinding/finder/a_star.py
AStarFinder.check_neighbors
python
def check_neighbors(self, start, end, grid, open_list, open_value=True, backtrace_by=None): # pop node with minimum 'f' value node = heapq.nsmallest(1, open_list)[0] open_list.remove(node) node.closed = True # if reached the end position, construct the pa...
find next path segment based on given node (or return path if we found the end)
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/a_star.py#L42-L77
[ "def backtrace(node):\n \"\"\"\n Backtrace according to the parent records and return the path.\n (including both start and end nodes)\n \"\"\"\n path = [(node.x, node.y)]\n while node.parent:\n node = node.parent\n path.append((node.x, node.y))\n path.reverse()\n return path\n...
class AStarFinder(Finder): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path using A* algorithm :param heuristic: heuristic used to calcul...
brean/python-pathfinding
pathfinding/finder/a_star.py
AStarFinder.find_path
python
def find_path(self, start, end, grid): start.g = 0 start.f = 0 return super(AStarFinder, self).find_path(start, end, grid)
find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/a_star.py#L79-L89
[ "def find_path(self, start, end, grid):\n \"\"\"\n find a path from start to end node on grid by iterating over\n all neighbors of a node (see check_neighbors)\n :param start: start node\n :param end: end node\n :param grid: grid that stores all possible steps/tiles as 2D-list\n :return:\n \...
class AStarFinder(Finder): def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path using A* algorithm :param heuristic: heuristic used to calcul...
anthill/koala
koala/utils.py
max_dimension
python
def max_dimension(cellmap, sheet = None): cells = list(cellmap.values()) rows = 0 cols = 0 for cell in cells: if sheet is None or cell.sheet == sheet: rows = max(rows, int(cell.row)) cols = max(cols, int(col2num(cell.col))) return (rows, cols)
This function calculates the maximum dimension of the workbook or optionally the worksheet. It returns a tupple of two integers, the first being the rows and the second being the columns. :param cellmap: all the cells that should be used to calculate the maximum. :param sheet: (optionally) a string with t...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/utils.py#L103-L121
[ "def col2num(col):\n\n if col in col2num_cache:\n return col2num_cache[col]\n else:\n if not col:\n raise Exception(\"Column may not be empty\")\n\n tot = 0\n for i,c in enumerate([c for c in col[::-1] if c != \"$\"]):\n if c == '$': continue\n tot ...
# cython: profile=True from __future__ import absolute_import, division import collections import numbers import re import datetime as dt from six import string_types from openpyxl.compat import unicode from .ExcelError import ExcelError ASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # source: https://github.com/dgorissen/...
anthill/koala
koala/excellib.py
rows
python
def rows(array): if isinstance(array, (float, int)): rows = 1 # special case for A1:A1 type ranges which for some reason only return an int/float elif array is None: rows = 1 # some A1:A1 ranges return None (issue with ref cell) else: rows = len(array.values) return rows
Function to find the number of rows in an array. Excel reference: https://support.office.com/en-ie/article/rows-function-b592593e-3fc2-47f2-bec1-bda493811597 :param array: the array of which the rows should be counted. :return: the number of rows.
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L410-L426
null
# cython: profile=True ''' Python equivalents of various excel functions ''' # source: https://github.com/dgorissen/pycel/blob/master/src/pycel/excellib.py from __future__ import absolute_import, division import numpy as np import scipy.optimize import datetime from math import log, ceil from decimal import Decimal...
anthill/koala
koala/excellib.py
irr
python
def irr(values, guess = None): if isinstance(values, Range): values = values.values if guess is not None and guess != 0: raise ValueError('guess value for excellib.irr() is %s and not 0' % guess) else: try: return np.irr(values) except Exception as e: ...
Function to calculate the internal rate of return (IRR) using payments and periodic dates. It resembles the excel function IRR(). Excel reference: https://support.office.com/en-us/article/IRR-function-64925eaa-9988-495b-b290-3ad0c163c1bc :param values: the payments of which at least one has to be negative...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L947-L967
null
# cython: profile=True ''' Python equivalents of various excel functions ''' # source: https://github.com/dgorissen/pycel/blob/master/src/pycel/excellib.py from __future__ import absolute_import, division import numpy as np import scipy.optimize import datetime from math import log, ceil from decimal import Decimal...
anthill/koala
koala/excellib.py
xirr
python
def xirr(values, dates, guess=0): if isinstance(values, Range): values = values.values if isinstance(dates, Range): dates = dates.values if guess is not None and guess != 0: raise ValueError('guess value for excellib.irr() is %s and not 0' % guess) else: try: ...
Function to calculate the internal rate of return (IRR) using payments and non-periodic dates. It resembles the excel function XIRR(). Excel reference: https://support.office.com/en-ie/article/xirr-function-de1242ec-6477-445b-b11b-a303ad9adc9d :param values: the payments of which at least one has to be ne...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L970-L995
null
# cython: profile=True ''' Python equivalents of various excel functions ''' # source: https://github.com/dgorissen/pycel/blob/master/src/pycel/excellib.py from __future__ import absolute_import, division import numpy as np import scipy.optimize import datetime from math import log, ceil from decimal import Decimal...
anthill/koala
koala/excellib.py
xnpv
python
def xnpv(rate, values, dates, lim_rate = True): # Excel reference: https://support.office.com/en-us/article/XNPV-function-1b42bbf6-370f-4532-a0eb-d67c16b664b7 if isinstance(values, Range): values = values.values if isinstance(dates, Range): dates = dates.values if len(values) != len(dates...
Function to calculate the net present value (NPV) using payments and non-periodic dates. It resembles the excel function XPNV(). :param rate: the discount rate. :param values: the payments of which at least one has to be negative. :param dates: the dates as excel dates (e.g. 43571 for 16/04/2019). :ret...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L1131-L1156
null
# cython: profile=True ''' Python equivalents of various excel functions ''' # source: https://github.com/dgorissen/pycel/blob/master/src/pycel/excellib.py from __future__ import absolute_import, division import numpy as np import scipy.optimize import datetime from math import log, ceil from decimal import Decimal...
anthill/koala
koala/excellib.py
today
python
def today(): reference_date = datetime.datetime.today().date() days_since_epoch = reference_date - EXCEL_EPOCH # why +2 ? # 1 based from 1900-01-01 # I think it is "inclusive" / to the _end_ of the day. # https://support.office.com/en-us/article/date-function-e36c0c8c-4104-49da-ab83-82328b832349...
Note: Excel stores dates as sequential serial numbers so that they can be used in calculations. January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900. You will need to change the number format (Format Cells) in order to display a proper d...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/excellib.py#L1190-L1200
null
# cython: profile=True ''' Python equivalents of various excel functions ''' # source: https://github.com/dgorissen/pycel/blob/master/src/pycel/excellib.py from __future__ import absolute_import, division import numpy as np import scipy.optimize import datetime from math import log, ceil from decimal import Decimal...
anthill/koala
koala/reader.py
repair_central_directory
python
def repair_central_directory(zipFile, is_file_instance): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/reader/excel.py?at=default&fileviewer=file-view-default ''' trims trailing data from the central directory code taken from http://stackoverflow.com/a/7...
trims trailing data from the central directory code taken from http://stackoverflow.com/a/7457686/570216, courtesy of Uri Cohen
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L41-L56
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
_cast_number
python
def _cast_number(value): # source: https://bitbucket.org/openpyxl/openpyxl/src/93604327bce7aac5e8270674579af76d390e09c0/openpyxl/cell/read_only.py?at=default&fileviewer=file-view-default "Convert numbers as string to an int or float" m = FLOAT_REGEX.search(value) if m is not None: return float(value...
Convert numbers as string to an int or float
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L74-L79
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
read_rels
python
def read_rels(archive): xml_source = archive.read(ARC_WORKBOOK_RELS) tree = fromstring(xml_source) for element in safe_iterator(tree, '{%s}Relationship' % PKG_REL_NS): rId = element.get('Id') pth = element.get("Target") typ = element.get('Type') # normalise path if pt...
Read relationships for a workbook
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L231-L244
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
read_content_types
python
def read_content_types(archive): xml_source = archive.read(ARC_CONTENT_TYPES) root = fromstring(xml_source) contents_root = root.findall('{%s}Override' % CONTYPES_NS) for type in contents_root: yield type.get('ContentType'), type.get('PartName')
Read content types.
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L246-L252
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
read_sheets
python
def read_sheets(archive): xml_source = archive.read(ARC_WORKBOOK) tree = fromstring(xml_source) for element in safe_iterator(tree, '{%s}sheet' % SHEET_MAIN_NS): attrib = element.attrib attrib['id'] = attrib["{%s}id" % REL_NS] del attrib["{%s}id" % REL_NS] if attrib['id']: ...
Read worksheet titles and ids for a workbook
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L256-L265
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
detect_worksheets
python
def detect_worksheets(archive): # content types has a list of paths but no titles # workbook has a list of titles and relIds but no paths # workbook_rels has a list of relIds and paths but no titles # rels = {'id':{'title':'', 'path':''} } content_types = read_content_types(archive) valid_sheets...
Return a list of worksheets
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L267-L283
[ "def read_content_types(archive):\n \"\"\"Read content types.\"\"\"\n xml_source = archive.read(ARC_CONTENT_TYPES)\n root = fromstring(xml_source)\n contents_root = root.findall('{%s}Override' % CONTYPES_NS)\n for type in contents_root:\n yield type.get('ContentType'), type.get('PartName')\n",...
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
read_string_table
python
def read_string_table(xml_source): strings = [] src = _get_xml_iter(xml_source) for _, node in iterparse(src): if node.tag == '{%s}si' % SHEET_MAIN_NS: text = Text.from_tree(node).content text = text.replace('x005F_', '') strings.append(text) node.c...
Read in all shared strings in the table
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L285-L299
[ "def _get_xml_iter(xml_source):\n \"\"\"\n Possible inputs: strings, bytes, members of zipfile, temporary file\n Always return a file like object\n \"\"\"\n if not hasattr(xml_source, 'read'):\n try:\n xml_source = xml_source.encode(\"utf-8\")\n except (AttributeError, Unicod...
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/reader.py
_get_xml_iter
python
def _get_xml_iter(xml_source): if not hasattr(xml_source, 'read'): try: xml_source = xml_source.encode("utf-8") except (AttributeError, UnicodeDecodeError): pass return BytesIO(xml_source) else: try: xml_source.seek(0) except: ...
Possible inputs: strings, bytes, members of zipfile, temporary file Always return a file like object
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/reader.py#L302-L319
null
from __future__ import print_function from io import BytesIO import re import os import json from openpyxl.formula.translate import Translator from openpyxl.cell.text import Text from openpyxl.utils.indexed_list import IndexedList from openpyxl.xml.functions import iterparse, fromstring, safe_iterator try: from x...
anthill/koala
koala/ast/__init__.py
create_node
python
def create_node(t, ref = None, debug = False): if t.ttype == "operand": if t.tsubtype in ["range", "named_range", "pointer"] : # print 'Creating Node', t.tvalue, t.tsubtype return RangeNode(t, ref, debug = debug) else: return OperandNode(t) elif t.ttype == "fu...
Simple factory function
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L18-L31
null
from __future__ import absolute_import # cython: profile=True import collections import six import networkx from networkx.classes.digraph import DiGraph from openpyxl.compat import unicode from koala.utils import uniqueify, flatten, max_dimension, col2num, resolve_range from koala.Cell import Cell from koala.Range i...
anthill/koala
koala/ast/__init__.py
shunting_yard
python
def shunting_yard(expression, named_ranges, ref = None, tokenize_range = False): #remove leading = if expression.startswith('='): expression = expression[1:] p = ExcelParser(tokenize_range = tokenize_range); p.parse(expression) # insert tokens for '(' and ')', to make things clearer below...
Tokenize an excel formula expression into reverse polish notation Core algorithm taken from wikipedia with varargs extensions from http://www.kallisti.net.nz/blog/2008/02/extension-to-the-shunting-yard-algorithm-to-allow-variable-numbers-of-arguments-to-functions/ The ref is the cell address which is pas...
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L42-L269
[ "def create_node(t, ref = None, debug = False):\n \"\"\"Simple factory function\"\"\"\n if t.ttype == \"operand\":\n if t.tsubtype in [\"range\", \"named_range\", \"pointer\"] :\n # print 'Creating Node', t.tvalue, t.tsubtype\n return RangeNode(t, ref, debug = debug)\n else...
from __future__ import absolute_import # cython: profile=True import collections import six import networkx from networkx.classes.digraph import DiGraph from openpyxl.compat import unicode from koala.utils import uniqueify, flatten, max_dimension, col2num, resolve_range from koala.Cell import Cell from koala.Range i...
anthill/koala
koala/ast/__init__.py
build_ast
python
def build_ast(expression, debug = False): #use a directed graph to store the tree G = DiGraph() stack = [] for n in expression: # Since the graph does not maintain the order of adding nodes/edges # add an extra attribute 'pos' so we can always sort to the correct order if isins...
build an AST from an Excel formula expression in reverse polish notation
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L271-L320
null
from __future__ import absolute_import # cython: profile=True import collections import six import networkx from networkx.classes.digraph import DiGraph from openpyxl.compat import unicode from koala.utils import uniqueify, flatten, max_dimension, col2num, resolve_range from koala.Cell import Cell from koala.Range i...
anthill/koala
koala/ast/__init__.py
cell2code
python
def cell2code(cell, named_ranges): if cell.formula: debug = False # if 'OFFSET' in cell.formula or 'INDEX' in cell.formula: # debug = True # if debug: # print 'FORMULA', cell.formula ref = parse_cell_address(cell.address()) if not cell.is_named_range else No...
Generate python code for the given cell
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L358-L386
[ "def shunting_yard(expression, named_ranges, ref = None, tokenize_range = False):\n \"\"\"\n Tokenize an excel formula expression into reverse polish notation\n\n Core algorithm taken from wikipedia with varargs extensions from\n http://www.kallisti.net.nz/blog/2008/02/extension-to-the-shunting-yard-alg...
from __future__ import absolute_import # cython: profile=True import collections import six import networkx from networkx.classes.digraph import DiGraph from openpyxl.compat import unicode from koala.utils import uniqueify, flatten, max_dimension, col2num, resolve_range from koala.Cell import Cell from koala.Range i...
anthill/koala
koala/ast/__init__.py
graph_from_seeds
python
def graph_from_seeds(seeds, cell_source): # when called from Spreadsheet instance, use the Spreadsheet cellmap and graph if hasattr(cell_source, 'G'): # ~ cell_source is a Spreadsheet cellmap = cell_source.cellmap cells = cellmap G = cell_source.G for c in seeds: G.a...
This creates/updates a networkx graph from a list of cells. The graph is created when the cell_source is an instance of ExcelCompiler The graph is updated when the cell_source is an instance of Spreadsheet
train
https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L435-L655
[ "def is_range(address):\n if isinstance(address, Exception):\n return address\n return address.find(':') > 0\n", "def split_address(address):\n\n if address in split_address_cache:\n return split_address_cache[address]\n\n else:\n sheet = None\n if address.find('!') > 0:\n ...
from __future__ import absolute_import # cython: profile=True import collections import six import networkx from networkx.classes.digraph import DiGraph from openpyxl.compat import unicode from koala.utils import uniqueify, flatten, max_dimension, col2num, resolve_range from koala.Cell import Cell from koala.Range i...
bheinzerling/pyrouge
pyrouge/utils/sentence_splitter.py
PunktSentenceSplitter.split
python
def split(self, text): text = cleanup(text) return self.sent_detector.tokenize(text.strip())
Splits text and returns a list of the resulting sentences.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/utils/sentence_splitter.py#L37-L40
[ "def cleanup(s):\n return remove_newlines(s)\n" ]
class PunktSentenceSplitter: """ Splits sentences using the NLTK Punkt sentence tokenizer. If installed, PunktSentenceSplitter can use the default NLTK data for English, otherwise custom trained data has to be provided. """ def __init__(self, language="en", punkt_data_path=None): self....
bheinzerling/pyrouge
pyrouge/utils/file_utils.py
str_from_file
python
def str_from_file(path): with open(path) as f: s = f.read().strip() return s
Return file contents as string.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/utils/file_utils.py#L37-L44
null
from __future__ import print_function, unicode_literals, division import os import re import codecs import xml.etree.ElementTree as et from pyrouge.utils import log class DirectoryProcessor: @staticmethod def process(input_dir, output_dir, function): """ Apply function to all files in input...
bheinzerling/pyrouge
pyrouge/utils/file_utils.py
xml_equal
python
def xml_equal(xml_file1, xml_file2): def canonical(xml_file): # poor man's canonicalization, since we don't want to install # external packages just for unittesting s = et.tostring(et.parse(xml_file).getroot()).decode("UTF-8") s = re.sub("[\n|\t]*", "", s) s = re.sub("\s+", "...
Parse xml and convert to a canonical string representation so we don't have to worry about semantically meaningless differences
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/utils/file_utils.py#L47-L62
[ "def canonical(xml_file):\n # poor man's canonicalization, since we don't want to install\n # external packages just for unittesting\n s = et.tostring(et.parse(xml_file).getroot()).decode(\"UTF-8\")\n s = re.sub(\"[\\n|\\t]*\", \"\", s)\n s = re.sub(\"\\s+\", \" \", s)\n s = \"\".join(sorted(s)).s...
from __future__ import print_function, unicode_literals, division import os import re import codecs import xml.etree.ElementTree as et from pyrouge.utils import log class DirectoryProcessor: @staticmethod def process(input_dir, output_dir, function): """ Apply function to all files in input...
bheinzerling/pyrouge
pyrouge/utils/file_utils.py
list_files
python
def list_files(dir_path, recursive=True): for root, dirs, files in os.walk(dir_path): file_list = [os.path.join(root, f) for f in files] if recursive: for dir in dirs: dir = os.path.join(root, dir) file_list.extend(list_files(dir, recursive=True)) ...
Return a list of files in dir_path.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/utils/file_utils.py#L65-L77
[ "def list_files(dir_path, recursive=True):\n \"\"\"\n Return a list of files in dir_path.\n\n \"\"\"\n\n for root, dirs, files in os.walk(dir_path):\n file_list = [os.path.join(root, f) for f in files]\n if recursive:\n for dir in dirs:\n dir = os.path.join(root, ...
from __future__ import print_function, unicode_literals, division import os import re import codecs import xml.etree.ElementTree as et from pyrouge.utils import log class DirectoryProcessor: @staticmethod def process(input_dir, output_dir, function): """ Apply function to all files in input...
bheinzerling/pyrouge
pyrouge/utils/file_utils.py
DirectoryProcessor.process
python
def process(input_dir, output_dir, function): if not os.path.exists(output_dir): os.makedirs(output_dir) logger = log.get_global_console_logger() logger.info("Processing files in {}.".format(input_dir)) input_file_names = os.listdir(input_dir) for input_file_name in i...
Apply function to all files in input_dir and save the resulting ouput files in output_dir.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/utils/file_utils.py#L14-L34
[ "def get_global_console_logger(level=logging.INFO):\n return get_console_logger('global', level)\n", "def from_html(html):\n\tsoup = BeautifulSoup(html)\n\tsentences = [elem.text for elem in soup.find_all(\"a\") if 'id' in elem.attrs]\n\ttext = \"\\n\".join(sentences)\n\treturn text\n", " def convert_text...
class DirectoryProcessor: @staticmethod
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.split_sentences
python
def split_sentences(self): from pyrouge.utils.sentence_splitter import PunktSentenceSplitter self.log.info("Splitting sentences.") ss = PunktSentenceSplitter() sent_split_to_string = lambda s: "\n".join(ss.split(s)) process_func = partial( DirectoryProcessor.process, ...
ROUGE requires texts split into sentences. In case the texts are not already split, this method can be used.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L178-L190
[ "def __process_summaries(self, process_func):\n \"\"\"\n Helper method that applies process_func to the files in the\n system and model folders and saves the resulting files to new\n system and model folders.\n\n \"\"\"\n temp_dir = mkdtemp()\n new_system_dir = os.path.join(temp_dir, \"system\"...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.convert_text_to_rouge_format
python
def convert_text_to_rouge_format(text, title="dummy title"): sentences = text.split("\n") sent_elems = [ "<a name=\"{i}\">[{i}]</a> <a href=\"#{i}\" id={i}>" "{text}</a>".format(i=i, text=sent) for i, sent in enumerate(sentences, start=1)] html = """<html> <he...
Convert a text to a format ROUGE understands. The text is assumed to contain one sentence per line. text: The text to convert, containg one sentence per line. title: Optional title for the text. The title will appear in the converted file, but doesn't seem to have...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L208-L235
null
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.write_config_static
python
def write_config_static(system_dir, system_filename_pattern, model_dir, model_filename_pattern, config_file_path, system_id=None): system_filenames = [f for f in os.listdir(system_dir)] system_models_tuples = [] system_filename_pattern = r...
Write the ROUGE configuration file, which is basically a list of system summary files and their corresponding model summary files. pyrouge uses regular expressions to automatically find the matching model summary files for a given system summary file (cf. docstrings for system_f...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L238-L292
[ " def __get_eval_string(\n task_id, system_id,\n system_dir, system_filename,\n model_dir, model_filenames):\n \"\"\"\n ROUGE can evaluate several system summaries for a given text\n against several model summaries, i.e. there is an m-to-n\n relation b...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.write_config
python
def write_config(self, config_file_path=None, system_id=None): if not system_id: system_id = 1 if (not config_file_path) or (not self._config_dir): self._config_dir = mkdtemp() config_filename = "rouge_conf.xml" else: config_dir, config_filename = ...
Write the ROUGE configuration file, which is basically a list of system summary files and their matching model summary files. This is a non-static version of write_config_file_static(). config_file_path: Path of the configuration file. system_id: Optional system ID s...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L294-L320
[ "def verify_dir(path, name=None):\n if name:\n name_str = \"Cannot set {} directory because t\".format(name)\n else:\n name_str = \"T\"\n msg = \"{}he path {} does not exist.\".format(name_str, path)\n if not os.path.exists(path):\n raise Exception(msg)\n", "def write_config_stati...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.evaluate
python
def evaluate(self, system_id=1, rouge_args=None): self.write_config(system_id=system_id) options = self.__get_options(rouge_args) command = [self._bin_path] + options env = None if hasattr(self, "_home_dir") and self._home_dir: env = {'ROUGE_EVAL_HOME': self._home_dir...
Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID which will be printed in ROUGE's output. ...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L322-L343
[ "def write_config(self, config_file_path=None, system_id=None):\n \"\"\"\n Write the ROUGE configuration file, which is basically a list\n of system summary files and their matching model summary files.\n\n This is a non-static version of write_config_file_static().\n\n config_file_path: Path o...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.convert_and_evaluate
python
def convert_and_evaluate(self, system_id=1, split_sentences=False, rouge_args=None): if split_sentences: self.split_sentences() self.__write_summaries() rouge_output = self.evaluate(system_id, rouge_args) return rouge_output
Convert plain text summaries to ROUGE format and run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. Optionally split texts into sentences in case they aren't already. This is just a convenience method combining convert_summaries_to...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L345-L368
[ "def split_sentences(self):\n \"\"\"\n ROUGE requires texts split into sentences. In case the texts\n are not already split, this method can be used.\n\n \"\"\"\n from pyrouge.utils.sentence_splitter import PunktSentenceSplitter\n self.log.info(\"Splitting sentences.\")\n ss = PunktSentenceSpli...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.output_to_dict
python
def output_to_dict(self, output): #0 ROUGE-1 Average_R: 0.02632 (95%-conf.int. 0.02632 - 0.02632) pattern = re.compile( r"(\d+) (ROUGE-\S+) (Average_\w): (\d.\d+) " r"\(95%-conf.int. (\d.\d+) - (\d.\d+)\)") results = {} for line in output.split("\n"): ...
Convert the ROUGE output into python dictionary for further processing.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L370-L396
null
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__set_rouge_dir
python
def __set_rouge_dir(self, home_dir=None): if not home_dir: self._home_dir = self.__get_rouge_home_dir_from_settings() else: self._home_dir = home_dir self.save_home_dir() self._bin_path = os.path.join(self._home_dir, 'ROUGE-1.5.5.pl') self.data_dir = o...
Verfify presence of ROUGE-1.5.5.pl and data folder, and set those paths.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L401-L418
[ "def save_home_dir(self):\n config = ConfigParser()\n section = 'pyrouge settings'\n config.add_section(section)\n config.set(section, 'home_dir', self._home_dir)\n with open(self._settings_file, 'w') as f:\n config.write(f)\n self.log.info(\"Set ROUGE home directory to {}.\".format(self._h...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__get_eval_string
python
def __get_eval_string( task_id, system_id, system_dir, system_filename, model_dir, model_filenames): peer_elems = "<P ID=\"{id}\">{name}</P>".format( id=system_id, name=system_filename) model_elems = ["<M ID=\"{id}\">{name}</M>".format( id=chr...
ROUGE can evaluate several system summaries for a given text against several model summaries, i.e. there is an m-to-n relation between system and model summaries. The system summaries are listed in the <PEERS> tag and the model summaries in the <MODELS> tag. pyrouge currently only suppor...
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L432-L471
null
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__process_summaries
python
def __process_summaries(self, process_func): temp_dir = mkdtemp() new_system_dir = os.path.join(temp_dir, "system") os.mkdir(new_system_dir) new_model_dir = os.path.join(temp_dir, "model") os.mkdir(new_model_dir) self.log.info( "Processing summaries. Saving sy...
Helper method that applies process_func to the files in the system and model folders and saves the resulting files to new system and model folders.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L473-L491
[ "def convert_summaries_to_rouge_format(input_dir, output_dir):\n \"\"\"\n Convert all files in input_dir into a format ROUGE understands\n and saves the files to output_dir. The input files are assumed\n to be plain text with one sentence per line.\n\n input_dir: Path of directory containing the...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__get_options
python
def __get_options(self, rouge_args=None): if self.args: options = self.args.split() elif rouge_args: options = rouge_args.split() else: options = [ '-e', self._data_dir, '-c', 95, '-2', '-1', ...
Get supplied command line arguments for ROUGE or use default ones.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L509-L534
[ "def __add_config_option(self, options):\n return options + ['-m'] + [self._config_file]\n" ]
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__create_dir_property
python
def __create_dir_property(self, dir_name, docstring): property_name = "{}_dir".format(dir_name) private_name = "_" + property_name setattr(self, private_name, None) def fget(self): return getattr(self, private_name) def fset(self, path): verify_dir(path,...
Generate getter and setter for a directory property.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L536-L553
null
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__set_dir_properties
python
def __set_dir_properties(self): directories = [ ("home", "The ROUGE home directory."), ("data", "The path of the ROUGE 'data' directory."), ("system", "Path of the directory containing system summaries."), ("model", "Path of the directory containing model summarie...
Automatically generate the properties for directories.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L555-L567
[ "def __create_dir_property(self, dir_name, docstring):\n \"\"\"\n Generate getter and setter for a directory property.\n\n \"\"\"\n property_name = \"{}_dir\".format(dir_name)\n private_name = \"_\" + property_name\n setattr(self, private_name, None)\n\n def fget(self):\n return getattr(...
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
bheinzerling/pyrouge
pyrouge/Rouge155.py
Rouge155.__clean_rouge_args
python
def __clean_rouge_args(self, rouge_args): if not rouge_args: return quot_mark_pattern = re.compile('"(.+)"') match = quot_mark_pattern.match(rouge_args) if match: cleaned_args = match.group(1) return cleaned_args else: return rouge_...
Remove enclosing quotation marks, if any.
train
https://github.com/bheinzerling/pyrouge/blob/afeb37dd2608f1399e2fb24a4ee2fe10a2a18603/pyrouge/Rouge155.py#L569-L582
null
class Rouge155(object): """ This is a wrapper for the ROUGE 1.5.5 summary evaluation package. This class is designed to simplify the evaluation process by: 1) Converting summaries into a format ROUGE understands. 2) Generating the ROUGE configuration file automatically based on ...
ottogroup/palladium
palladium/util.py
apply_kwargs
python
def apply_kwargs(func, **kwargs): new_kwargs = {} params = signature(func).parameters for param_name in params.keys(): if param_name in kwargs: new_kwargs[param_name] = kwargs[param_name] return func(**new_kwargs)
Call *func* with kwargs, but only those kwargs that it accepts.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L51-L59
null
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
args_from_config
python
def args_from_config(func): func_args = signature(func).parameters @wraps(func) def wrapper(*args, **kwargs): config = get_config() for i, argname in enumerate(func_args): if len(args) > i or argname in kwargs: continue elif argname in config: ...
Decorator that injects parameters from the configuration.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L62-L84
null
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
memory_usage_psutil
python
def memory_usage_psutil(): process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) mem_vms = process.memory_info()[1] / float(2 ** 20) return mem, mem_vms
Return the current process memory usage in MB.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L196-L202
null
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
version_cmd
python
def version_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(version_cmd.__doc__, argv=argv) print(__version__)
\ Print the version number of Palladium. Usage: pld-version [options] Options: -h --help Show this screen.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L205-L216
null
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
upgrade_cmd
python
def upgrade_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(upgrade_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') upgrade(from_version=arguments['--from'], to_version=arguments['--to'])
\ Upgrade the database to the latest version. Usage: pld-ugprade [options] Options: --from=<v> Upgrade from a specific version, overriding the version stored in the database. --to=<v> Upgrade to a specific version instead of the ...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L227-L245
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
export_cmd
python
def export_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(export_cmd.__doc__, argv=argv) model_version = export( model_version=arguments['--version'], activate=not arguments['--no-activate'], ) logger.info("Exported model. New version number: {}".format(model_version)...
\ Export a model from one model persister to another. The model persister to export to is supposed to be available in the configuration file under the 'model_persister_export' key. Usage: pld-export [options] Options: --version=<v> Export a specific version rather than the active ...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L262-L286
null
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/util.py
Partial
python
def Partial(func, **kwargs): if isinstance(func, str): func = resolve_dotted_name(func) partial_func = partial(func, **kwargs) update_wrapper(partial_func, func) return partial_func
Allows the use of partially applied functions in the configuration.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/util.py#L333-L341
[ "def resolve_dotted_name(dotted_name):\n if ':' in dotted_name:\n module, name = dotted_name.split(':')\n elif '.' in dotted_name:\n module, name = dotted_name.rsplit('.', 1)\n else:\n module, name = dotted_name, None\n\n attr = import_module(module)\n if name:\n for name ...
"""Assorted utilties. """ from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import update_wrapper from functools import wraps import logging from importlib import import_module from inspect import signature from inspect imp...
ottogroup/palladium
palladium/server.py
make_ujson_response
python
def make_ujson_response(obj, status_code=200): json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1) resp = make_response(json_encoded) resp.mimetype = 'application/json' resp.content_type = 'application/json; charset=utf-8' resp.status_code = status_code return resp
Encodes the given *obj* to json and wraps it in a response. :return: A Flask response.
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L32-L43
null
"""HTTP API implementation. """ import sys from docopt import docopt from flask import Flask from flask import make_response from flask import request import numpy as np import ujson from werkzeug.exceptions import BadRequest from . import __version__ from .fit import activate as activate_base from .fit import fit a...
ottogroup/palladium
palladium/server.py
create_predict_function
python
def create_predict_function( route, predict_service, decorator_list_name, config): model_persister = config.get('model_persister') @app.route(route, methods=['GET', 'POST'], endpoint=route) @PluggableDecorator(decorator_list_name) def predict_func(): return predict(model_persister, pred...
Creates a predict function and registers it to the Flask app using the route decorator. :param str route: Path of the entry point. :param palladium.interfaces.PredictService predict_service: The predict service to be registered to this entry point. :param str decorator_list_name: Th...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L270-L296
null
"""HTTP API implementation. """ import sys from docopt import docopt from flask import Flask from flask import make_response from flask import request import numpy as np import ujson from werkzeug.exceptions import BadRequest from . import __version__ from .fit import activate as activate_base from .fit import fit a...
ottogroup/palladium
palladium/server.py
devserver_cmd
python
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(devserver_cmd.__doc__, argv=argv) initialize_config() app.run( host=arguments['--host'], port=int(arguments['--port']), debug=int(arguments['--debug']), )
\ Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --debug=<debug> Whether or not to use debug mode [default: 0]...
train
https://github.com/ottogroup/palladium/blob/f3a4372fba809efbd8da7c979a8c6faff04684dd/palladium/server.py#L299-L321
[ "def initialize_config(**extra):\n if _config.initialized:\n raise RuntimeError(\"Configuration was already initialized\")\n return get_config(**extra)\n" ]
"""HTTP API implementation. """ import sys from docopt import docopt from flask import Flask from flask import make_response from flask import request import numpy as np import ujson from werkzeug.exceptions import BadRequest from . import __version__ from .fit import activate as activate_base from .fit import fit a...