text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_obj_processors(self, obj_processors): """ Object processors are callables that will be called after each successful model object construction. Those callables receive model object as its parameter. Registration of new object processors will replace previous. Args: obj_processors(dict): A dictionary where key=class name, value=callable """
self.obj_processors = obj_processors self.type_convertors.update(obj_processors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(self): """ Main interpreter loop. """
self.print_menu() while True: try: event = input() if event == 'q': return event = int(event) event = self.model.events[event-1] except Exception: print('Invalid input') self.event(event) self.print_menu()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_font(font_name): """Return the font and a Boolean indicating if the match is exact."""
if font_name in STANDARD_FONT_NAMES: return font_name, True elif font_name in _registered_fonts: return font_name, _registered_fonts[font_name] NOT_FOUND = (None, False) try: # Try first to register the font if it exists as ttf, # based on ReportLab font search. registerFont(TTFont(font_name, '%s.ttf' % font_name)) _registered_fonts[font_name] = True return font_name, True except TTFError: # Try searching with Fontconfig try: pipe = subprocess.Popen( ['fc-match', '-s', '--format=%{file}\\n', font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) output = pipe.communicate()[0].decode(sys.getfilesystemencoding()) font_path = output.split('\n')[0] except OSError: return NOT_FOUND try: registerFont(TTFont(font_name, font_path)) except TTFError: return NOT_FOUND # Fontconfig may return a default font totally unrelated with font_name exact = font_name.lower() in os.path.basename(font_path).lower() _registered_fonts[font_name] = exact return font_name, exact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def svg2rlg(path, **kwargs): "Convert an SVG file to an RLG Drawing object." # unzip .svgz file into .svg unzipped = False if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz": with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out: shutil.copyfileobj(f_in, f_out) path = path[:-1] unzipped = True svg_root = load_svg_file(path) if svg_root is None: return # convert to a RLG drawing svgRenderer = SvgRenderer(path, **kwargs) drawing = svgRenderer.render(svg_root) # remove unzipped .svgz file (.svg) if unzipped: os.remove(path) return drawing
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseMultiAttributes(self, line): """Try parsing compound attribute string. Return a dictionary with single attributes in 'line'. """
attrs = line.split(';') attrs = [a.strip() for a in attrs] attrs = filter(lambda a:len(a)>0, attrs) new_attrs = {} for a in attrs: k, v = a.split(':') k, v = [s.strip() for s in (k, v)] new_attrs[k] = v return new_attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findAttr(self, svgNode, name): """Search an attribute with some name in some node or above. First the node is searched, then its style attribute, then the search continues in the node's parent node. If no such attribute is found, '' is returned. """
# This needs also to lookup values like "url(#SomeName)"... if self.css_rules is not None and not svgNode.attrib.get('__rules_applied', False): if isinstance(svgNode, NodeTracker): svgNode.apply_rules(self.css_rules) else: ElementWrapper(svgNode).apply_rules(self.css_rules) attr_value = svgNode.attrib.get(name, '').strip() if attr_value and attr_value != "inherit": return attr_value elif svgNode.attrib.get("style"): dict = self.parseMultiAttributes(svgNode.attrib.get("style")) if name in dict: return dict[name] if svgNode.getparent() is not None: return self.findAttr(svgNode.getparent(), name) return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 style: d = self.parseMultiAttributes(style) dict.update(d) for key, value in svgNode.attrib.items(): if key != "style": dict[key] = value return dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertTransform(self, svgAttr): """Parse transform attribute string. E.g. "scale(2) translate(10,20)" -> [("scale", 2), ("translate", (10,20))] """
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], brackets[i+1] subline = line[bi+1:bj] subline = subline.strip() subline = subline.replace(',', ' ') subline = re.sub("[ ]+", ',', subline) try: if ',' in subline: indices.append(tuple(float(num) for num in subline.split(','))) else: indices.append(float(subline)) except ValueError: continue ops = ops[:bi] + ' '*(bj-bi+1) + ops[bj+1:] ops = ops.replace(',', ' ').split() if len(ops) != len(indices): logger.warning("Unable to parse transform expression '%s'" % svgAttr) return [] result = [] for i, op in enumerate(ops): result.append((op, indices[i])) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(',', ' ').split()[0] if text.endswith('%'): logger.debug("Fiddling length unit: %") return float(text[:-1]) / 100 * percentOf elif text.endswith("pc"): return float(text[:-2]) * pica elif text.endswith("pt"): return float(text[:-2]) * 1.25 elif text.endswith("em"): return float(text[:-2]) * em_base elif text.endswith("px"): return float(text[:-2]) if "ex" in text: logger.warning("Ignoring unit ex") text = text.replace("ex", '') text = text.strip() length = toLength(text) # this does the default measurements such as mm and cm return length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertLengthList(self, svgAttr): """Convert a list of lengths."""
return [self.convertLength(a) for a in self.split_attr_list(svgAttr)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = predefined + "lawngreen indianred aquamarine lightgreen brown" # This needs also to lookup values like "url(#SomeName)"... text = svgAttr if not text or text == "none": return None if text in predefined.split(): return self.color_converter(getattr(colors, text)) elif text == "currentColor": return "currentColor" elif len(text) == 7 and text[0] == '#': return self.color_converter(colors.HexColor(text)) elif len(text) == 4 and text[0] == '#': return self.color_converter(colors.HexColor('#' + 2*text[1] + 2*text[2] + 2*text[3])) elif text.startswith('rgb') and '%' not in text: t = text[3:].strip('()') tup = [h[2:] for h in [hex(int(num)) for num in t.split(',')]] tup = [(2 - len(h)) * '0' + h for h in tup] col = "#%s%s%s" % tuple(tup) return self.color_converter(colors.HexColor(col)) elif text.startswith('rgb') and '%' in text: t = text[3:].replace('%', '').strip('()') tup = (float(val)/100.0 for val in t.split(',')) return self.color_converter(colors.Color(*tup)) logger.warning("Can't handle color: %s" % text) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_clippath(self, node): """ Return the clipping Path object referenced by the node 'clip-path' attribute, if any. """
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 get_path_from_node(child) clip_path = node.getAttribute('clip-path') if clip_path: m = re.match(r'url\(#([^\)]*)\)', clip_path) if m: ref = m.groups()[0] if ref in self.definitions: path = get_path_from_node(self.definitions[ref]) if path: path = ClippingPath(copy_from=path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applyTransformOnGroup(self, transform, group): """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>) """
tr = self.attrConverter.convertTransform(transform) for op, values in tr: if op == "scale": if not isinstance(values, tuple): values = (values, values) group.scale(*values) elif op == "translate": if isinstance(values, (int, float)): # From the SVG spec: If <ty> is not provided, it is assumed to be zero. values = values, 0 group.translate(*values) elif op == "rotate": if not isinstance(values, tuple) or len(values) == 1: group.rotate(values) elif len(values) == 3: angle, cx, cy = values group.translate(cx, cy) group.rotate(angle) group.translate(-cx, -cy) elif op == "skewX": group.skew(values, 0) elif op == "skewY": group.skew(0, values) elif op == "matrix": group.transform = values else: logger.debug("Ignoring transform: %s %s" % (op, values))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applyStyleOnShape(self, shape, node, only_explicit=False): """ Apply styles from an SVG element to an RLG shape. If only_explicit is True, only attributes really present are applied. """
# 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"), ("fill-opacity", "fillOpacity", "convertOpacity", 1), ("fill-rule", "_fillRule", "convertFillRule", "nonzero"), ("stroke", "strokeColor", "convertColor", "none"), ("stroke-width", "strokeWidth", "convertLength", "1"), ("stroke-opacity", "strokeOpacity", "convertOpacity", 1), ("stroke-linejoin", "strokeLineJoin", "convertLineJoin", "0"), ("stroke-linecap", "strokeLineCap", "convertLineCap", "0"), ("stroke-dasharray", "strokeDashArray", "convertDashArray", "none"), ) mappingF = ( ("font-family", "fontName", "convertFontFamily", DEFAULT_FONT_NAME), ("font-size", "fontSize", "convertLength", "12"), ("text-anchor", "textAnchor", "id", "start"), ) if shape.__class__ == Group: # Recursively apply style on Group subelements for subshape in shape.contents: self.applyStyleOnShape(subshape, node, only_explicit=only_explicit) return ac = self.attrConverter for mapping in (mappingN, mappingF): if shape.__class__ != String and mapping == mappingF: continue for (svgAttrName, rlgAttr, func, default) in mapping: svgAttrValue = ac.findAttr(node, svgAttrName) if svgAttrValue == '': if only_explicit: continue else: svgAttrValue = default if svgAttrValue == "currentColor": svgAttrValue = ac.findAttr(node.getparent(), "color") or default try: meth = getattr(ac, func) setattr(shape, rlgAttr, meth(svgAttrValue)) except (AttributeError, KeyError, ValueError): pass if getattr(shape, 'fillOpacity', None) is not None and shape.fillColor: shape.fillColor.alpha = shape.fillOpacity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_floats(op, min_num, value): """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]] """
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]]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalise_svg_path(attr): """Normalise SVG path. This basically introduces operator codes for multi-argument parameters. Also, it fixes sequences of consecutive M or m list as argument for Z and z only in order to make the resul- ting list easier to iterate over. E.g. "M 10 20, M 20 20, L 30 40, 40 40, Z" -> ['M', [10, 20], 'L', [20, 20], 'L', [30, 40], 'L', [40, 40], 'Z', []] """
# 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_keys = ops.keys() # do some preprocessing result = [] groups = re.split('([achlmqstvz])', attr.strip(), flags=re.I) op = None for item in groups: if item.strip() == '': continue if item in op_keys: # fix sequences of M to one M plus a sequence of L operators, # same for m and l. if item == 'M' and item == op: op = 'L' elif item == 'm' and item == op: op = 'l' else: op = item if ops[op] == 0: # Z, z result.extend([op, []]) else: result.extend(split_floats(op, ops[op], item)) op = result[-2] # Remember last op return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_quadratic_to_cubic_path(q0, q1, q2): """ Convert a quadratic Bezier curve through q0, q1, q2 to a cubic one. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def client_start(request, socket, context): """ Adds the client triple to CLIENTS. """
CLIENTS[socket.session.session_id] = (request, socket, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def client_end(request, socket, context): """ 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. """
# 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, socket, context) # Actually unsubscribe to cleanup channel data. for channel in socket.channels[:]: socket.unsubscribe(channel) # Remove the client. del CLIENTS[socket.session.session_id]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def client_end_all(): """ Performs cleanup on all clients - called by runserver_socketio when the server is shut down or reloaded. """
for request, socket, context in CLIENTS.values()[:]: client_end(request, socket, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribe(self, channel): """ 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. """
if channel in self.channels: return False CHANNELS[channel].append(self.socket.session.session_id) self.channels.append(channel) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsubscribe(self, channel): """ 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. """
try: CHANNELS[channel].remove(self.socket.session.session_id) self.channels.remove(channel) except ValueError: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast_channel(self, message, channel=None): """ 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. """
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: session = self.socket.handler.server.sessions[subscriber] self._write(message, session)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_and_broadcast_channel(self, message, channel=None): """ Shortcut for a socket to broadcast to all sockets subscribed to a channel, and itself. """
self.send(message) self.broadcast_channel(message, channel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(request, socket, context, message): """ Event handler for a room receiving a message. First validates a joining user's name and sends them the list of users. """
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"}) else: context["user"] = user users = [u.name for u in room.users.exclude(id=user.id)] socket.send({"action": "started", "users": users}) user.session = socket.session.session_id user.save() joined = {"action": "join", "name": user.name, "id": user.id} socket.send_and_broadcast_channel(joined) else: try: user = context["user"] except KeyError: return if message["action"] == "message": message["message"] = strip_tags(message["message"]) message["name"] = user.name socket.send_and_broadcast_channel(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(request, socket, context): """ Event handler for a socket session ending in a room. Broadcast the user leaving and delete them from the DB. """
try: user = context["user"] except KeyError: return left = {"action": "leave", "name": user.name, "id": user.id} socket.broadcast_channel(left) user.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(session_id, message): """ Send a message to the socket for the given session ID. """
try: socket = CLIENTS[session_id][1] except KeyError: raise NoSocket("There is no socket with the session ID: " + session_id) socket.send(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast(message): """ Find the first socket and use it to broadcast to all sockets including the socket itself. """
try: socket = CLIENTS.values()[0][1] except IndexError: raise NoSocket("There are no clients.") socket.send_and_broadcast(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast_channel(message, channel): """ Find the first socket for the given channel, and use it to broadcast to the channel, including the socket itself. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_log(request, message_type, message): """ Formats a log message similar to gevent's pywsgi request logging. """
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 % args) + "\n"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_handler(self, *args, **options): """ Returns the django.contrib.staticfiles handler. """
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 = options.get('insecure_serving', False) if (settings.DEBUG and use_static_handler or (use_static_handler and insecure_serving)): handler = StaticFilesHandler(handler) return handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, request, socket, context, *args): """ 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. In the case of subscribe/unsubscribe, match the channel arg being sent to the channel pattern. """
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.match(c) for c in socket.channels if pattern] if no_channel or filter(None, matches): handler(request, socket, context, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rooms(request, template="rooms.html"): """ Homepage - lists all rooms. """
context = {"rooms": ChatRoom.objects.all()} return render(request, template, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def room(request, slug, template="room.html"): """ Show a room. """
context = {"room": get_object_or_404(ChatRoom, slug=slug)} return render(request, template, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(request): """ Handles post from the "Add room" form on the homepage, and redirects to the new room. """
name = request.POST.get("name") if name: room, created = ChatRoom.objects.get_or_create(name=name) return redirect(room) return redirect(rooms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_outer_solar_system(sim): """ Add the planet of the outer Solar System as a test problem. Data taken from NASA Horizons. """
Gfac = 1./0.01720209895 # Gaussian constant if sim.G is not None: Gfac *= math.sqrt(sim.G) sim.add( m=1.00000597682, x=-4.06428567034226e-3, y=-6.08813756435987e-3, z=-1.66162304225834e-6, vx=+6.69048890636161e-6*Gfac, vy=-6.33922479583593e-6*Gfac, vz=-3.13202145590767e-9*Gfac ) # Sun sim.add( m=1./1047.355, x=+3.40546614227466e+0, y=+3.62978190075864e+0, z=+3.42386261766577e-2, vx=-5.59797969310664e-3*Gfac, vy=+5.51815399480116e-3*Gfac, vz=-2.66711392865591e-6*Gfac ) # Jupiter sim.add( m=1./3501.6, x=+6.60801554403466e+0, y=+6.38084674585064e+0, z=-1.36145963724542e-1, vx=-4.17354020307064e-3*Gfac, vy=+3.99723751748116e-3*Gfac, vz=+1.67206320571441e-5*Gfac ) # Saturn sim.add( m=1./22869., x=+1.11636331405597e+1, y=+1.60373479057256e+1, z=+3.61783279369958e-1, vx=-3.25884806151064e-3*Gfac, vy=+2.06438412905916e-3*Gfac, vz=-2.17699042180559e-5*Gfac ) # Uranus sim.add( m=1./19314., x=-3.01777243405203e+1, y=+1.91155314998064e+0, z=-1.53887595621042e-1, vx=-2.17471785045538e-4*Gfac, vy=-3.11361111025884e-3*Gfac, vz=+3.58344705491441e-5*Gfac ) # Neptune sim.add( m=7.4074074e-09, x=-2.13858977531573e+1, y=+3.20719104739886e+1, z=+2.49245689556096e+0, vx=-1.76936577252484e-3*Gfac, vy=-2.06720938381724e-3*Gfac, vz=+6.58091931493844e-4*Gfac )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_color(color): """ Takes a string for a color name defined in matplotlib and returns of a 3-tuple of RGB values. Will simply return passed value if it's a tuple of length three. Parameters color : str Name of matplotlib color to calculate RGB values for. """
if isinstance(color, tuple) and len(color) == 3: # already a tuple of RGB values return color try: import matplotlib.colors as mplcolors except: raise ImportError("Error importing matplotlib. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand.") try: hexcolor = mplcolors.cnames[color] except KeyError: raise AttributeError("Color not recognized in matplotlib.") hexcolor = hexcolor.lstrip('#') lv = len(hexcolor) return tuple(int(hexcolor[i:i + lv // 3], 16)/255. for i in range(0, lv, lv // 3))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fading_line(x, y, color='black', alpha_initial=1., alpha_final=0., glow=False, **kwargs): """ Returns a matplotlib LineCollection connecting the points in the x and y lists, with a single color and alpha varying from alpha_initial to alpha_final along the line. Can pass any kwargs you can pass to LineCollection, like linewidgth. Parameters x : list or array of floats for the positions on the (plot's) x axis y : list or array of floats for the positions on the (plot's) y axis color : matplotlib color for the line. Can also pass a 3-tuple of RGB values (default: 'black') alpha_initial: Limiting value of alpha to use at the beginning of the arrays. alpha_final: Limiting value of alpha to use at the end of the arrays. """
try: from matplotlib.collections import LineCollection from matplotlib.colors import LinearSegmentedColormap import numpy as np except: raise ImportError("Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand.") if glow: glow = False kwargs["lw"] = 1 fl1 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) kwargs["lw"] = 2 alpha_initial *= 0.5 alpha_final *= 0.5 fl2 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) kwargs["lw"] = 6 alpha_initial *= 0.5 alpha_final *= 0.5 fl3 = fading_line(x, y, color, alpha_initial, alpha_final, glow=False, **kwargs) return [fl3,fl2,fl1] color = get_color(color) cdict = {'red': ((0.,color[0],color[0]),(1.,color[0],color[0])), 'green': ((0.,color[1],color[1]),(1.,color[1],color[1])), 'blue': ((0.,color[2],color[2]),(1.,color[2],color[2])), 'alpha': ((0.,alpha_initial, alpha_initial), (1., alpha_final, alpha_final))} Npts = len(x) if len(y) != Npts: raise AttributeError("x and y must have same dimension.") segments = np.zeros((Npts-1,2,2)) segments[0][0] = [x[0], y[0]] for i in range(1,Npts-1): pt = [x[i], y[i]] segments[i-1][1] = pt segments[i][0] = pt segments[-1][1] = [x[-1], y[-1]] individual_cm = LinearSegmentedColormap('indv1', cdict) lc = LineCollection(segments, cmap=individual_cm, **kwargs) lc.set_array(np.linspace(0.,1.,len(segments))) return lc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSnapshotIndex(self, t): """ Return the index for the snapshot just before t """
if t>self.tmax or t<self.tmin: raise ValueError("Requested time outside of baseline stored in binary file.") # Bisection method l = 0 r = len(self) while True: bi = l+(r-l)//2 if self.t[bi]>t: r = bi else: l = bi if r-1<=l: bi = l break return bi, self.t[bi]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSimulations(self, times, **kwargs): """ A generator to quickly access many simulations. The arguments are the same as for `getSimulation`. """
for t in times: yield self.getSimulation(t, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Returns a deep copy of the particle. The particle is not added to any simulation by default. """
np = Particle() memmove(byref(np), byref(self), sizeof(self)) return np
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def takeScreenshot(self, times=None, prefix="./screenshot", resetCounter=False, archive=None,mode="snapshot"): """ Take one or more screenshots of the widget and save the images to a file. The images can be used to create a video. This function cannot be called multiple times within one cell. Note: this is a new feature and might not work on all systems. It was tested on python 2.7.10 and 3.5.2 on MacOSX. Parameters times : (float, list), optional If this argument is not given a screenshot of the widget will be made as it is (without integrating the simulation). If a float is given, then the simulation will be integrated to that time and then a screenshot will be taken. If a list of floats is given, the simulation will be integrated to each time specified in the array. A separate screenshot for each time will be saved. prefix : (str), optional This string will be part of the output filename for each image. Follow by a five digit integer and the suffix .png. By default the prefix is './screenshot' which outputs images in the current Note that the prefix can include a directory. resetCounter : (bool), optional Resets the output counter to 0. archive : (rebound.SimulationArchive), optional Use a REBOUND SimulationArchive. Thus, instead of integratating the Simulation from the current time, it will use the SimulationArchive to load a snapshot. See examples for usage. mode : (string), optional Mode to use when querying the SimulationArchive. See SimulationArchive documentation for details. By default the value is "snapshot". Examples -------- First, create a simulation and widget. All of the following can go in one cell. The widget should show up. To take a screenshot, simply call A new file with the name screenshot00000.png will appear in the current directory. Note that the takeScreenshot command needs to be in a separate cell, i.e. after you see the widget. You can pass an array of times to the function. This allows you to take multiple screenshots, for example to create a movie, """
self.archive = archive if resetCounter: self.screenshotcountall = 0 self.screenshotprefix = prefix self.screenshotcount = 0 self.overlay = "REBOUND" self.screenshot = "" if archive is None: if times is None: times = self.simp.contents.t try: # List len(times) except: # Float: times = [times] self.times = times self.observe(savescreenshot,names="screenshot") self.simp.contents.integrate(times[0]) self.screenshotcount += 1 # triggers first screenshot else: if times is None: raise ValueError("Need times argument for archive mode.") try: len(times) except: raise ValueError("Need a list of times for archive mode.") self.times = times self.mode = mode self.observe(savescreenshot,names="screenshot") sim = archive.getSimulation(times[0],mode=mode) self.refresh(pointer(sim)) self.screenshotcount += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coordinates(self): """ Get or set the internal coordinate system. Available coordinate systems are: - ``'jacobi'`` (default) - ``'democraticheliocentric'`` - ``'whds'`` """
i = self._coordinates for name, _i in COORDINATES.items(): if i==_i: return name return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getWidget(self,**kwargs): """ Wrapper function that returns a new widget attached to this simulation. Widgets provide real-time 3D visualizations from within an Jupyter notebook. See the Widget class for more details on the possible arguments. Arguments --------- All arguments passed to this wrapper function will be passed to /Widget class. Returns ------- A rebound.Widget object. Examples -------- """
from .widget import Widget # ondemand from ipywidgets import DOMWidget from IPython.display import display, HTML if not hasattr(self, '_widgets'): self._widgets = [] def display_heartbeat(simp): for w in self._widgets: w.refresh(simp,isauto=1) self.visualization = VISUALIZATIONS["webgl"] clibrebound.reb_display_init_data(byref(self)); self._dhbf = AFF(display_heartbeat) self._display_heartbeat = self._dhbf display(HTML(Widget.getClientCode())) # HACK! Javascript should go into custom.js newWidget = Widget(self,**kwargs) self._widgets.append(newWidget) newWidget.refresh(isauto=0) return newWidget
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refreshWidgets(self): """ This function manually refreshed all widgets attached to this simulation. You want to call this function if any particle data has been manually changed. """
if hasattr(self, '_widgets'): for w in self._widgets: w.refresh(isauto=0) else: raise RuntimeError("No widgets found")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self): """ Prints a summary of the current status of the simulation. """
from rebound import __version__, __build__ s= "" s += "---------------------------------\n" s += "REBOUND version: \t%s\n" %__version__ s += "REBOUND built on: \t%s\n" %__build__ s += "Number of particles: \t%d\n" %self.N s += "Selected integrator: \t" + self.integrator + "\n" s += "Simulation time: \t%.16e\n" %self.t s += "Current timestep: \t%f\n" %self.dt if self.N>0: s += "---------------------------------\n" for p in self.particles: s += str(p) + "\n" s += "---------------------------------" print(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrator(self): """ Get or set the intergrator module. Available integrators are: - ``'ias15'`` (default) - ``'whfast'`` - ``'sei'`` - ``'leapfrog'`` - ``'janus'`` - ``'mercurius'`` - ``'bs'`` - ``'none'`` Check the online documentation for a full description of each of the integrators. """
i = self._integrator for name, _i in INTEGRATORS.items(): if i==_i: return name return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boundary(self): """ Get or set the boundary module. Available boundary modules are: - ``'none'`` (default) - ``'open'`` - ``'periodic'`` - ``'shear'`` Check the online documentation for a full description of each of the modules. """
i = self._boundary for name, _i in BOUNDARIES.items(): if i==_i: return name return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gravity(self): """ Get or set the gravity module. Available gravity modules are: - ``'none'`` - ``'basic'`` (default) - ``'compensated'`` - ``'tree'`` Check the online documentation for a full description of each of the modules. """
i = self._gravity for name, _i in GRAVITIES.items(): if i==_i: return name return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collision(self): """ Get or set the collision module. Available collision modules are: - ``'none'`` (default) - ``'direct'`` - ``'tree'`` - ``'mercurius'`` - ``'direct'`` Check the online documentation for a full description of each of the modules. """
i = self._collision for name, _i in COLLISIONS.items(): if i==_i: return name return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_variation(self,order=1,first_order=None, first_order_2=None, testparticle=-1): """ This function adds a set of variational particles to the simulation. If there are N real particles in the simulation, this functions adds N additional variational particles. To see how many particles (real and variational) are in a simulation, use ``'sim.N'``. To see how many variational particles are in a simulation use ``'sim.N_var'``. Currently Leapfrog, WHFast and IAS15 support first order variational equations. IAS15 also supports second order variational equations. Parameters order : integer, optional By default the function adds a set of first order variational particles to the simulation. Set this flag to 2 for second order. first_order : Variation, optional Second order variational equations depend on their corresponding first order variational equations. This parameter expects the Variation object corresponding to the first order variational equations. first_order_2 : Variation, optional Same as first_order. But allows to set two different indicies to calculate off-diagonal elements. If omitted, then first_order will be used for both first order equations. testparticle : int, optional If set to a value >= 0, then only one variational particle will be added and be treated as a test particle. Returns ------- Returns Variation object (a copy--you can only modify it through its particles property or vary method). """
cur_var_config_N = self.var_config_N if order==1: index = clibrebound.reb_add_var_1st_order(byref(self),c_int(testparticle)) elif order==2: if first_order is None: raise AttributeError("Please specify corresponding first order variational equations when initializing second order variational equations.") if first_order_2 is None: first_order_2 = first_order index = clibrebound.reb_add_var_2nd_order(byref(self),c_int(testparticle),c_int(first_order.index),c_int(first_order_2.index)) else: raise AttributeError("Only variational equations of first and second order are supported.") # Need a copy because location of original might shift if more variations added s = Variation.from_buffer_copy(self.var_config[cur_var_config_N]) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_megno(self, seed=None): """ This function initialises the chaos indicator MEGNO particles and enables their integration. MEGNO is short for Mean Exponential Growth of Nearby orbits. It can be used to test if a system is chaotic or not. In the backend, the integrator is integrating an additional set of particles using the variational equation. Note that variational equations are better suited for this than shadow particles. MEGNO is currently only supported in the IAS15 and WHFast integrators. This function also needs to be called if you are interested in the Lyapunov exponent as it is calculate with the help of MEGNO. See Rein and Tamayo 2015 for details on the implementation. For more information on MENGO see e.g. http://dx.doi.org/10.1051/0004-6361:20011189 """
if seed is None: clibrebound.reb_tools_megno_init(byref(self)) else: clibrebound.reb_tools_megno_init_seed(byref(self), c_uint(seed))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, index=None, hash=None, keepSorted=True): """ Removes a particle from the simulation. Parameters index : int, optional Specify particle to remove by index. hash : c_uint32 or string, optional Specifiy particle to remove by hash (if a string is passed, the corresponding hash is calculated). keepSorted : bool, optional By default, remove preserves the order of particles in the particles array. Might set it to zero in cases with many particles and many removals to speed things up. """
if index is not None: clibrebound.reb_remove(byref(self), index, keepSorted) if hash is not None: hash_types = c_uint32, c_uint, c_ulong PY3 = sys.version_info[0] == 3 if PY3: string_types = str, int_types = int, else: string_types = basestring, int_types = int, long if isinstance(hash, string_types): clibrebound.reb_remove_by_hash(byref(self), rebhash(hash), keepSorted) elif isinstance(hash, int_types): clibrebound.reb_remove_by_hash(byref(self), c_uint32(hash), keepSorted) elif isinstance(hash, hash_types): clibrebound.reb_remove_by_hash(byref(self), hash, keepSorted) if hasattr(self, '_widgets'): self._display_heartbeat(pointer(self)) self.process_messages()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def particles_ascii(self, prec=8): """ Returns an ASCII string with all particles' masses, radii, positions and velocities. Parameters prec : int, optional Number of digits after decimal point. Default 8. """
s = "" for p in self.particles: s += (("%%.%de "%prec) * 8)%(p.m, p.r, p.x, p.y, p.z, p.vx, p.vy, p.vz) + "\n" if len(s): s = s[:-1] return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_particles_ascii(self, s): """ Adds particles from an ASCII string. Parameters s : string One particle per line. Each line should include particle's mass, radius, position and velocity. """
for l in s.split("\n"): r = l.split() if len(r): try: r = [float(x) for x in r] p = Particle(simulation=self, m=r[0], r=r[1], x=r[2], y=r[3], z=r[4], vx=r[5], vy=r[6], vz=r[7]) self.add(p) except: raise AttributeError("Each line requires 8 floats corresponding to mass, radius, position (x,y,z) and velocity (x,y,z).")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_orbits(self, primary=None, jacobi_masses=False, heliocentric=None, barycentric=None): """ Calculate orbital parameters for all partices in the simulation. By default this functions returns the orbits in Jacobi coordinates. If MEGNO is enabled, variational particles will be ignored. Parameters primary : rebound.Particle, optional Set the primary against which to reference the osculating orbit. Default(use Jacobi center of mass) jacobi_masses: bool Whether to use jacobi primary mass in orbit calculation. (Default: False) heliocentric: bool, DEPRECATED To calculate heliocentric elements, pass primary=sim.particles[0] barycentric : bool, DEPRECATED To calculate barycentric elements, pass primary=sim.calculate_com() Returns ------- Returns an array of Orbits of length N-1. """
orbits = [] if heliocentric is not None or barycentric is not None: raise AttributeError('heliocentric and barycentric keywords in calculate_orbits are deprecated. Pass primary keyword instead (sim.particles[0] for heliocentric and sim.calculate_com() for barycentric)') if primary is None: jacobi = True primary = self.particles[0] clibrebound.reb_get_com_of_pair.restype = Particle else: jacobi = False for p in self.particles[1:self.N_real]: if jacobi_masses is True: interior_mass = primary.m # orbit conversion uses mu=G*(p.m+primary.m) so set prim.m=Mjac-m so mu=G*Mjac primary.m = self.particles[0].m*(p.m + interior_mass)/interior_mass - p.m orbits.append(p.calculate_orbit(primary=primary)) primary.m = interior_mass # back to total mass of interior bodies to update com else: orbits.append(p.calculate_orbit(primary=primary)) if jacobi is True: # update com to include current particle for next iteration primary = clibrebound.reb_get_com_of_pair(primary, p) return orbits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_com(self, first=0, last=None): """ Returns the center of momentum for all particles in the simulation. Parameters first: int, optional If ``first`` is specified, only calculate the center of momentum starting from index=``first``. last : int or None, optional If ``last`` is specified only calculate the center of momentum up to (but excluding) index=``last``. Same behavior as Python's range function. Examples -------- 0.0 5.0 """
if last is None: last = self.N_real clibrebound.reb_get_com_range.restype = Particle return clibrebound.reb_get_com_range(byref(self), c_int(first), c_int(last))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_particle_data(self,**kwargs): """ Fast way to access serialized particle data via numpy arrays. This function can directly set the values of numpy arrays to current particle data. This is significantly faster than accessing particle data via `sim.particles` as all the copying is done on the C side. No memory is allocated by this function. It expects correctly sized numpy arrays as arguments. The argument name indicates what kind of particle data is written to the array. Possible argument names are "hash", "m", "r", "xyz", "vxvyvz", and "xyzvxvyvz". The datatype for the "hash" array needs to be uint32. The other arrays expect a datatype of float64. The lengths of "hash", "m", "r" arrays need to be at least sim.N. The lengths of xyz and vxvyvz need to be at least 3*sim.N. The length of "xyzvxvyvz" arrays need to be 6*sim.N. Exceptions are raised otherwise. Note that this routine is only intended for special use cases where speed is an issue. For normal use, it is recommended to access particle data via the `sim.particles` array. Be aware of potential issues that arrise by directly accesing the memory of numpy arrays (see numpy documentation for more details). Examples -------- This sets an array to the xyz positions of all particles: To get all current radii of particles: To get all current radii and hashes of particles: """
N = self.N possible_keys = ["hash","m","r","xyz","vxvyvz","xyzvxvyvz"] d = {x:None for x in possible_keys} for k,v in kwargs.items(): if k in d: if k == "hash": if v.dtype!= "uint32": raise AttributeError("Expected 'uint32' data type for '%s' array."%k) if v.size<N: raise AttributeError("Array '%s' is not large enough."%k) d[k] = v.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) else: if v.dtype!= "float64": raise AttributeError("Expected 'float64' data type for %s array."%k) if k in ["xyz", "vxvyvz"]: minsize = 3*N elif k in ["xyzvxvyvz"]: minsize = 6*N else: minsize = N if v.size<minsize: raise AttributeError("Array '%s' is not large enough."%k) d[k] = v.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) else: raise AttributeError("Only '%s' are currently supported attributes for serialization." % "', '".join(d.keys())) clibrebound.reb_serialize_particle_data(byref(self), d["hash"], d["m"], d["r"], d["xyz"], d["vxvyvz"], d["xyzvxvyvz"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_energy(self): """ Returns the sum of potential and kinetic energy of all particles in the simulation. """
clibrebound.reb_tools_energy.restype = c_double return clibrebound.reb_tools_energy(byref(self))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_box(self, boxsize, root_nx=1, root_ny=1, root_nz=1): """ Initialize the simulation box. This function only needs to be called it boundary conditions other than "none" are used. In such a case the boxsize must be known and is set with this function. Parameters boxsize : float, optional The size of one root box. root_nx, root_ny, root_nz : int, optional The number of root boxes in each direction. The total size of the simulation box will be ``root_nx * boxsize``, ``root_ny * boxsize`` and ``root_nz * boxsize``. By default there will be exactly one root box in each direction. """
clibrebound.reb_configure_box(byref(self), c_double(boxsize), c_int(root_nx), c_int(root_ny), c_int(root_nz)) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_ghostboxes(self, nghostx=0, nghosty=0, nghostz=0): """ Initialize the ghost boxes. This function only needs to be called it boundary conditions other than "none" or "open" are used. In such a case the number of ghostboxes must be known and is set with this function. Parameters nghostx, nghosty, nghostz : int The number of ghost boxes in each direction. All values default to 0 (no ghost boxes). """
clibrebound.nghostx = c_int(nghostx) clibrebound.nghosty = c_int(nghosty) clibrebound.nghostz = c_int(nghostz) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filename): """ Save the entire REBOUND simulation to a binary file. """
clibrebound.reb_output_binary(byref(self), c_char_p(filename.encode("ascii")))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def particles(self): """ Access the variational particles corresponding to this set of variational equations. The function returns a list of particles which are sorted in the same way as those in sim.particles The particles are pointers and thus can be modified. If there are N real particles, this function will also return a list of N particles (all of which are variational particles). """
sim = self._sim.contents ps = [] if self.testparticle>=0: N = 1 else: N = sim.N-sim.N_var ParticleList = Particle*N ps = ParticleList.from_address(ctypes.addressof(sim._particles.contents)+self.index*ctypes.sizeof(Particle)) return ps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_link_object(serializer, data, instance): """Add a 'links' attribute to the data that maps field names to URLs. NOTE: This is the format that Ember Data supports, but alternative implementations are possible to support other formats. """
link_object = {} if not getattr(instance, 'pk', None): # If instance doesn't have a `pk` field, we'll assume it doesn't # have a canonical resource URL to hang a link off of. # This generally only affectes Ephemeral Objects. return data link_fields = serializer.get_link_fields() for name, field in six.iteritems(link_fields): # For included fields, omit link if there's no data. if name in data and not data[name]: continue link = getattr(field, 'link', None) if link is None: base_url = '' if settings.ENABLE_HOST_RELATIVE_LINKS: # if the resource isn't registered, this will default back to # using resource-relative urls for links. base_url = DynamicRouter.get_canonical_path( serializer.get_resource_key(), instance.pk ) or '' link = '%s%s/' % (base_url, name) # Default to DREST-generated relation endpoints. elif callable(link): link = link(name, field, data, instance) link_object[name] = link if link_object: data['links'] = link_object return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_post_processor(func): """ Register a post processor function to be run as the final step in serialization. The data passed in will already have gone through the sideloading processor. Usage: @register_post_processor def my_post_processor(data): # do stuff with `data` return data """
global POST_PROCESSORS key = func.__name__ POST_PROCESSORS[key] = func return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process(self, obj, parent=None, parent_key=None, depth=0): """Recursively process the data for sideloading. Converts the nested representation into a sideloaded representation. """
if isinstance(obj, list): for key, o in enumerate(obj): # traverse into lists of objects self.process(o, parent=obj, parent_key=key, depth=depth) elif isinstance(obj, dict): dynamic = self.is_dynamic(obj) returned = isinstance(obj, ReturnDict) if dynamic or returned: # recursively check all fields for key, o in six.iteritems(obj): if isinstance(o, list) or isinstance(o, dict): # lists or dicts indicate a relation self.process( o, parent=obj, parent_key=key, depth=depth + 1 ) if not dynamic or getattr(obj, 'embed', False): return serializer = obj.serializer name = serializer.get_plural_name() instance = getattr(obj, 'instance', serializer.instance) instance_pk = instance.pk if instance else None pk = getattr(obj, 'pk_value', instance_pk) or instance_pk # For polymorphic relations, `pk` can be a dict, so use the # string representation (dict isn't hashable). pk_key = repr(pk) # sideloading seen = True # if this object has not yet been seen if pk_key not in self.seen[name]: seen = False self.seen[name].add(pk_key) # prevent sideloading the primary objects if depth == 0: return # TODO: spec out the exact behavior for secondary instances of # the primary resource # if the primary resource is embedded, add it to a prefixed key if name == self.plural_name: name = '%s%s' % ( settings.ADDITIONAL_PRIMARY_RESOURCE_PREFIX, name ) if not seen: # allocate a top-level key in the data for this resource # type if name not in self.data: self.data[name] = [] # move the object into a new top-level bucket # and mark it as seen self.data[name].append(obj) else: # obj sideloaded, but maybe with other fields for o in self.data.get(name, []): if o.instance.pk == pk: o.update(obj) break # replace the object with a reference if parent is not None and parent_key is not None: parent[parent_key] = pk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_request_fields_from_parent(self): """Get request fields from the parent serializer."""
if not self.parent: return None if not getattr(self.parent, 'request_fields'): return None if not isinstance(self.parent.request_fields, dict): return None return self.parent.request_fields.get(self.field_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_metadata(self, request, view): """Adds `properties` and `features` to the metadata response."""
metadata = super( DynamicMetadata, self).determine_metadata( request, view) metadata['features'] = getattr(view, 'features', []) if hasattr(view, 'get_serializer'): serializer = view.get_serializer(dynamic=False) if hasattr(serializer, 'get_name'): metadata['resource_name'] = serializer.get_name() if hasattr(serializer, 'get_plural_name'): metadata['resource_name_plural'] = serializer.get_plural_name() metadata['properties'] = self.get_serializer_info(serializer) return metadata
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_info(self, field): """Adds `related_to` and `nullable` to the metadata response."""
field_info = OrderedDict() for attr in ('required', 'read_only', 'default', 'label'): field_info[attr] = getattr(field, attr) if field_info['default'] is empty: field_info['default'] = None if hasattr(field, 'immutable'): field_info['immutable'] = field.immutable field_info['nullable'] = field.allow_null if hasattr(field, 'choices'): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_text(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] many = False if isinstance(field, DynamicRelationField): field = field.serializer if isinstance(field, ListSerializer): field = field.child many = True if isinstance(field, ModelSerializer): type = 'many' if many else 'one' field_info['related_to'] = field.get_plural_name() else: type = self.label_lookup[field] field_info['type'] = type return field_info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_model_field(model, field_name): """Return a field given a model and field name. Arguments: model: a Django model field_name: the name of a field Returns: A Django field if `field_name` is a valid field for `model`, None otherwise. """
meta = model._meta try: if DJANGO19: field = meta.get_field(field_name) else: field = meta.get_field_by_name(field_name)[0] return field except: if DJANGO19: related_objs = ( f for f in meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete ) related_m2m_objs = ( f for f in meta.get_fields(include_hidden=True) if f.many_to_many and f.auto_created ) else: related_objs = meta.get_all_related_objects() related_m2m_objs = meta.get_all_related_many_to_many_objects() related_objects = { o.get_accessor_name(): o for o in chain(related_objs, related_m2m_objs) } if field_name in related_objects: return related_objects[field_name] else: # check virtual fields (1.7) if hasattr(meta, 'virtual_fields'): for field in meta.virtual_fields: if field.name == field_name: return field raise AttributeError( '%s is not a valid field for %s' % (field_name, model) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_field_remote(model, field_name): """Check whether a given model field is a remote field. A remote field is the inverse of a one-to-many or a many-to-many relationship. Arguments: model: a Django model field_name: the name of a field Returns: True if `field_name` is a remote field, False otherwise. """
if not hasattr(model, '_meta'): # ephemeral model with no metaclass return False model_field = get_model_field(model, field_name) return isinstance(model_field, (ManyToManyField, RelatedObject))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resettable_cached_property(func): """Decorator to add cached computed properties to an object. Similar to Django's `cached_property` decorator, except stores all the data under a single well-known key so that it can easily be blown away. """
def wrapper(self): if not hasattr(self, '_resettable_cached_properties'): self._resettable_cached_properties = {} if func.__name__ not in self._resettable_cached_properties: self._resettable_cached_properties[func.__name__] = func(self) return self._resettable_cached_properties[func.__name__] # Returns a property whose getter is the 'wrapper' function return property(wrapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _settings_changed(self, *args, **kwargs): """Handle changes to core settings."""
setting, value = kwargs['setting'], kwargs['value'] if setting == self.name: self._reload(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, *args, **kwargs): """Bind to the parent serializer."""
if self.bound: # Prevent double-binding return super(DynamicRelationField, self).bind(*args, **kwargs) self.bound = True parent_model = getattr(self.parent.Meta, 'model', None) remote = is_field_remote(parent_model, self.source) try: model_field = get_model_field(parent_model, self.source) except: # model field may not be available for m2o fields with no # related_name model_field = None # Infer `required` and `allow_null` if 'required' not in self.kwargs and ( remote or ( model_field and ( model_field.has_default() or model_field.null ) ) ): self.required = False if 'allow_null' not in self.kwargs and getattr( model_field, 'null', False ): self.allow_null = True self.model_field = model_field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _inherit_parent_kwargs(self, kwargs): """Extract any necessary attributes from parent serializer to propagate down to child serializer. """
if not self.parent or not self._is_dynamic: return kwargs if 'request_fields' not in kwargs: # If 'request_fields' isn't explicitly set, pull it from the # parent serializer. request_fields = self._get_request_fields_from_parent() if request_fields is None: # Default to 'id_only' for nested serializers. request_fields = True kwargs['request_fields'] = request_fields if self.embed and kwargs.get('request_fields') is True: # If 'embed' then make sure we fetch the full object. kwargs['request_fields'] = {} if hasattr(self.parent, 'sideloading'): kwargs['sideloading'] = self.parent.sideloading if hasattr(self.parent, 'debug'): kwargs['debug'] = self.parent.debug return kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_serializer(self, *args, **kwargs): """Get an instance of the child serializer."""
init_args = { k: v for k, v in six.iteritems(self.kwargs) if k in self.SERIALIZER_KWARGS } kwargs = self._inherit_parent_kwargs(kwargs) init_args.update(kwargs) if self.embed and self._is_dynamic: init_args['embed'] = True return self._get_cached_serializer(args, init_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_representation(self, instance): """Represent the relationship, either as an ID or object."""
serializer = self.serializer model = serializer.get_model() source = self.source if not self.kwargs['many'] and serializer.id_only(): # attempt to optimize by reading the related ID directly # from the current instance rather than from the related object source_id = '%s_id' % source # try the faster way first: if hasattr(instance, source_id): return getattr(instance, source_id) elif model is not None: # this is probably a one-to-one field, or a reverse related # lookup, so let's look it up the slow way and let the # serializer handle the id dereferencing try: instance = getattr(instance, source) except model.DoesNotExist: instance = None # dereference ephemeral objects if model is None: instance = getattr(instance, source) if instance is None: return None return serializer.to_representation(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_internal_value_single(self, data, serializer): """Return the underlying object, given the serialized form."""
related_model = serializer.Meta.model if isinstance(data, related_model): return data try: instance = related_model.objects.get(pk=data) except related_model.DoesNotExist: raise ValidationError( "Invalid value for '%s': %s object with ID=%s not found" % (self.field_name, related_model.__name__, data) ) return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serializer_class(self): """Get the class of the child serializer. Resolves string imports. """
serializer_class = self._serializer_class if not isinstance(serializer_class, six.string_types): return serializer_class parts = serializer_class.split('.') module_path = '.'.join(parts[:-1]) if not module_path: if getattr(self, 'parent', None) is None: raise Exception( "Can not load serializer '%s'" % serializer_class + ' before binding or without specifying full path') # try the module of the parent class module_path = self.parent.__module__ module = importlib.import_module(module_path) serializer_class = getattr(module, parts[-1]) self._serializer_class = serializer_class return serializer_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_django_queryset(self): """Return Django QuerySet with prefetches properly configured."""
prefetches = [] for field, fprefetch in self.prefetches.items(): has_query = hasattr(fprefetch, 'query') qs = fprefetch.query.queryset if has_query else None prefetches.append( Prefetch(field, queryset=qs) ) queryset = self.queryset if prefetches: queryset = queryset.prefetch_related(*prefetches) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_renderers(self): """Optionally block Browsable API rendering. """
renderers = super(WithDynamicViewSetMixin, self).get_renderers() if settings.ENABLE_BROWSABLE_API is False: return [ r for r in renderers if not isinstance(r, BrowsableAPIRenderer) ] else: return renderers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_request_feature(self, name): """Parses the request for a particular feature. Arguments: name: A feature name. Returns: A feature parsed from the URL if the feature is supported, or None. """
if '[]' in name: # array-type return self.request.query_params.getlist( name) if name in self.features else None elif '{}' in name: # object-type (keys are not consistent) return self._extract_object_params( name) if name in self.features else {} else: # single-type return self.request.query_params.get( name) if name in self.features else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_object_params(self, name): """ Extract object params, return as dict """
params = self.request.query_params.lists() params_map = {} prefix = name[:-1] offset = len(prefix) for name, value in params: if name.startswith(prefix): if name.endswith('}'): name = name[offset:-1] elif name.endswith('}[]'): # strip off trailing [] # this fixes an Ember queryparams issue name = name[offset:-3] else: # malformed argument like: # filter{foo=bar raise exceptions.ParseError( '"%s" is not a well-formed filter key.' % name ) else: continue params_map[name] = value return params_map
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_queryset(self, queryset=None): """ Returns a queryset for this request. Arguments: queryset: Optional root-level queryset. """
serializer = self.get_serializer() return getattr(self, 'queryset', serializer.Meta.model.objects.all())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_request_fields(self): """Parses the INCLUDE and EXCLUDE features. Extracts the dynamic field features from the request parameters into a field map that can be passed to a serializer. Returns: A nested dict mapping serializer keys to True (include) or False (exclude). """
if hasattr(self, '_request_fields'): return self._request_fields include_fields = self.get_request_feature(self.INCLUDE) exclude_fields = self.get_request_feature(self.EXCLUDE) request_fields = {} for fields, include in( (include_fields, True), (exclude_fields, False)): if fields is None: continue for field in fields: field_segments = field.split('.') num_segments = len(field_segments) current_fields = request_fields for i, segment in enumerate(field_segments): last = i == num_segments - 1 if segment: if last: current_fields[segment] = include else: if segment not in current_fields: current_fields[segment] = {} current_fields = current_fields[segment] elif not last: # empty segment must be the last segment raise exceptions.ParseError( '"%s" is not a valid field.' % field ) self._request_fields = request_fields return request_fields
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, request, *args, **kwargs): """Update one or more model instances. If ENABLE_BULK_UPDATE is set, multiple previously-fetched records may be updated in a single call, provided their IDs. If ENABLE_PATCH_ALL is set, multiple records may be updated in a single PATCH call, even without knowing their IDs. *WARNING*: ENABLE_PATCH_ALL should be considered an advanced feature and used with caution. This feature must be enabled at the viewset level and must also be requested explicitly by the client via the "patch-all" query parameter. This parameter can have one of the following values: true (or 1): records will be fetched and then updated in a transaction loop - The `Model.save` method will be called and model signals will run - This can be slow if there are too many signals or many records in the query - This is considered the more safe and default behavior query: records will be updated in a single query - The `QuerySet.update` method will be called and model signals will not run - This will be fast, but may break data constraints that are controlled by signals - This is considered unsafe but useful in certain situations The server's successful response to a patch-all request will NOT include any individual records. Instead, the response content will contain a "meta" object with an "updated" count of updated records. Examples: Update one dog: PATCH /dogs/1/ { 'fur': 'white' } Update many dogs by ID: PATCH /dogs/ [ {'id': 1, 'fur': 'white'}, {'id': 2, 'fur': 'black'}, {'id': 3, 'fur': 'yellow'} ] Update all dogs in a query: PATCH /dogs/?filter{fur.contains}=brown&patch-all=true { 'fur': 'gold' } """
# noqa if self.ENABLE_BULK_UPDATE: patch_all = self.get_request_patch_all() if self.ENABLE_PATCH_ALL and patch_all: # patch-all update data = request.data return self._patch_all( data, query=(patch_all == 'query') ) else: # bulk payload update partial = 'partial' in kwargs bulk_payload = self._get_bulk_payload(request) if bulk_payload: return self._bulk_update(bulk_payload, partial) # singular update try: return super(DynamicModelViewSet, self).update(request, *args, **kwargs) except AssertionError as e: err = str(e) if 'Fix your URL conf' in err: # this error is returned by DRF if a client # makes an update request (PUT or PATCH) without an ID # since DREST supports bulk updates with IDs contained in data, # we return a 400 instead of a 500 for this case, # as this is not considered a misconfiguration raise exceptions.ValidationError(err) else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, request, *args, **kwargs): """ Either create a single or many model instances in bulk using the Serializer's many=True ability from Django REST >= 2.2.5. The data can be represented by the serializer name (single or plural forms), dict or list. Examples: POST /dogs/ { "name": "Fido", "age": 2 } POST /dogs/ { "dog": { "name": "Lucky", "age": 3 } } POST /dogs/ { "dogs": [ {"name": "Fido", "age": 2}, {"name": "Lucky", "age": 3} ] } POST /dogs/ [ {"name": "Fido", "age": 2}, {"name": "Lucky", "age": 3} ] """
bulk_payload = self._get_bulk_payload(request) if bulk_payload: return self._create_many(bulk_payload) return super(DynamicModelViewSet, self).create( request, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self, request, *args, **kwargs): """ Either delete a single or many model instances in bulk DELETE /dogs/ { "dogs": [ {"id": 1}, {"id": 2} ] } DELETE /dogs/ [ {"id": 1}, {"id": 2} ] """
bulk_payload = self._get_bulk_payload(request) if bulk_payload: return self._destroy_many(bulk_payload) lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field if lookup_url_kwarg not in kwargs: # assume that it is a poorly formatted bulk request return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) return super(DynamicModelViewSet, self).destroy( request, *args, **kwargs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_resource_key(self): """Return canonical resource key, usually the DB table name."""
model = self.get_model() if model: return get_model_table(model) else: return self.get_name()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """Get the data, after performing post-processing if necessary."""
data = super(DynamicListSerializer, self).data processed_data = ReturnDict( SideloadingProcessor(self, data).data, serializer=self ) if self.child.envelope else ReturnList( data, serializer=self ) processed_data = post_process(processed_data) return processed_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dynamic_init(self, only_fields, include_fields, exclude_fields): """ Modifies `request_fields` via higher-level dynamic field interfaces. Arguments: only_fields: List of field names to render. All other fields will be deferred (respects sideloads). include_fields: List of field names to include. Adds to default field set, (respects sideloads). `*` means include all fields. exclude_fields: List of field names to exclude. Removes from default field set. If set to '*', all fields are removed, except for ones that are explicitly included. """
if not self.dynamic: return if (isinstance(self.request_fields, dict) and self.request_fields.pop('*', None) is False): exclude_fields = '*' only_fields = set(only_fields or []) include_fields = include_fields or [] exclude_fields = exclude_fields or [] if only_fields: exclude_fields = '*' include_fields = only_fields if exclude_fields == '*': # First exclude all, then add back in explicitly included fields. include_fields = set( list(include_fields) + [ field for field, val in six.iteritems(self.request_fields) if val or val == {} ] ) all_fields = set(self.get_all_fields().keys()) # this is slow exclude_fields = all_fields - include_fields elif include_fields == '*': all_fields = set(self.get_all_fields().keys()) # this is slow include_fields = all_fields for name in exclude_fields: self.request_fields[name] = False for name in include_fields: if not isinstance(self.request_fields.get(name), dict): # not sideloading this field self.request_fields[name] = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_name(cls): """Get the serializer name. The name can be defined on the Meta class or will be generated automatically from the model name. """
if not hasattr(cls.Meta, 'name'): class_name = getattr(cls.get_model(), '__name__', None) setattr( cls.Meta, 'name', inflection.underscore(class_name) if class_name else None ) return cls.Meta.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_plural_name(cls): """Get the serializer's plural name. The plural name may be defined on the Meta class. If the plural name is not defined, the pluralized form of the name will be returned. """
if not hasattr(cls.Meta, 'plural_name'): setattr( cls.Meta, 'plural_name', inflection.pluralize(cls.get_name()) ) return cls.Meta.plural_name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _all_fields(self): """Returns the entire serializer field set. Does not respect dynamic field inclusions/exclusions. """
if ( not settings.ENABLE_FIELDS_CACHE or not self.ENABLE_FIELDS_CACHE or self.__class__ not in FIELDS_CACHE ): all_fields = super( WithDynamicSerializerMixin, self ).get_fields() if ( settings.ENABLE_FIELDS_CACHE and self.ENABLE_FIELDS_CACHE ): FIELDS_CACHE[self.__class__] = all_fields else: all_fields = copy.copy(FIELDS_CACHE[self.__class__]) for k, field in six.iteritems(all_fields): if hasattr(field, 'reset'): field.reset() for k, field in six.iteritems(all_fields): field.field_name = k field.parent = self return all_fields
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fields(self): """Returns the serializer's field set. If `dynamic` is True, respects field inclusions/exlcusions. Otherwise, reverts back to standard DRF behavior. """
all_fields = self.get_all_fields() if self.dynamic is False: return all_fields if self.id_only(): return {} serializer_fields = copy.deepcopy(all_fields) request_fields = self.request_fields deferred = self._get_deferred_field_names(serializer_fields) # apply request overrides if request_fields: for name, include in six.iteritems(request_fields): if name not in serializer_fields: raise exceptions.ParseError( '"%s" is not a valid field name for "%s".' % (name, self.get_name()) ) if include is not False and name in deferred: deferred.remove(name) elif include is False: deferred.add(name) for name in deferred: serializer_fields.pop(name) # Set read_only flags based on read_only_fields meta list. # Here to cover DynamicFields not covered by DRF. ro_fields = getattr(self.Meta, 'read_only_fields', []) self.flag_fields(serializer_fields, ro_fields, 'read_only', True) pw_fields = getattr(self.Meta, 'untrimmed_fields', []) self.flag_fields( serializer_fields, pw_fields, 'trim_whitespace', False, ) # Toggle read_only flags for immutable fields. # Note: This overrides `read_only` if both are set, to allow # inferred DRF fields to be made immutable. immutable_field_names = self._get_flagged_field_names( serializer_fields, 'immutable' ) self.flag_fields( serializer_fields, immutable_field_names, 'read_only', value=False if self.get_request_method() == 'POST' else True ) return serializer_fields
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _faster_to_representation(self, instance): """Modified to_representation with optimizations. 1) Returns a plain old dict as opposed to OrderedDict. (Constructing ordered dict is ~100x slower than `{}`.) 2) Ensure we use a cached list of fields (this optimization exists in DRF 3.2 but not 3.1) Arguments: instance: a model instance or data object Returns: Dict of primitive datatypes. """
ret = {} fields = self._readable_fields is_fast = isinstance(instance, prefetch.FastObject) id_fields = self._readable_id_fields for field in fields: attribute = None # we exclude dynamic fields here because the proper fastquery # dereferencing happens in the `get_attribute` method now if ( is_fast and not isinstance( field, (DynamicGenericRelationField, DynamicRelationField) ) ): if field in id_fields and field.source not in instance: # TODO - make better. attribute = instance.get(field.source + '_id') ret[field.field_name] = attribute continue else: try: attribute = instance[field.source] except KeyError: # slower, but does more stuff # Also, some temp debugging if hasattr(instance, field.source): attribute = getattr(instance, field.source) else: # Fall back on DRF behavior attribute = field.get_attribute(instance) print( 'Missing %s from %s' % ( field.field_name, self.__class__.__name__ ) ) else: try: attribute = field.get_attribute(instance) except SkipField: continue if attribute is None: # We skip `to_representation` for `None` values so that # fields do not have to explicitly deal with that case. ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_representation(self, instance): """Uncached `to_representation`."""
if self.enable_optimization: representation = self._faster_to_representation(instance) else: representation = super( WithDynamicSerializerMixin, self ).to_representation(instance) if settings.ENABLE_LINKS: # TODO: Make this function configurable to support other # formats like JSON API link objects. representation = merge_link_object( self, representation, instance ) if self.debug: representation['_meta'] = { 'id': instance.pk, 'type': self.get_plural_name() } # tag the representation with the serializer and instance return tag_dict( representation, serializer=self, instance=instance, embed=self.embed )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_representation(self, instance): """Modified to_representation method. Optionally may cache objects. Arguments: instance: A model instance or data object. Returns: Instance ID if the serializer is meant to represent its ID. Otherwise, a tagged data dict representation. """
if self.id_only(): return instance.pk pk = getattr(instance, 'pk', None) if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None: return self._to_representation(instance) else: if pk not in self.obj_cache: self.obj_cache[pk] = self._to_representation(instance) return self.obj_cache[pk]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None instance = super( WithDynamicSerializerMixin, self ).save( *args, **kwargs ) view = self._context.get('view') if view and update: if int(DRF_VERSION[0]) <= 3 and int(DRF_VERSION[1]) < 5: # Reload the object on update # to get around prefetch cache issues # Fixed in DRF in 3.5.0 instance = self.instance = view.get_object() return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_representation(self, instance): """ Provides post processing. Sub-classes should implement their own to_representation method, but pass the resulting dict through this function to get tagging and field selection. Arguments: instance: Serialized dict, or object. If object, it will be serialized by the super class's to_representation() method. """
if not isinstance(instance, dict): data = super( DynamicEphemeralSerializer, self ).to_representation(instance) else: data = instance instance = EphemeralObject(data) if self.id_only(): return data else: return tag_dict(data, serializer=self, instance=instance)