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 CopyToStatTimeTuple(self): """Copies the date time value to a stat timestamp tuple. Returns: tuple[int, int]: a POSIX timestamp in seconds and the remainder ...
normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None if self._precision in ( definitions.PRECISION_1_NANOSECOND, definitions.PRECISION_100_NANOSECONDS, definitions.PRECISION_1_MICROSECOND, definitions.PRECISION_1_MIL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyToDateTimeStringISO8601(self): """Copies the date time value to an ISO 8601 date and time string. Returns: str: date and time value formatted as an ISO 8...
date_time_string = self.CopyToDateTimeString() if date_time_string: date_time_string = date_time_string.replace(' ', 'T') date_time_string = '{0:s}Z'.format(date_time_string) return date_time_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetPlasoTimestamp(self): """Retrieves a timestamp that is compatible with plaso. Returns: int: a POSIX timestamp in microseconds or None if no timestamp is a...
normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None normalized_timestamp *= definitions.MICROSECONDS_PER_SECOND normalized_timestamp = normalized_timestamp.quantize( 1, rounding=decimal.ROUND_HALF_UP) return int(normalized_timestamp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetTimeOfDay(self): """Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, No...
normalized_timestamp = self._GetNormalizedTimestamp() if normalized_timestamp is None: return None, None, None _, hours, minutes, seconds = self._GetTimeValues(normalized_timestamp) return hours, minutes, seconds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyFromDateTimeString(self, time_string): """Copies a fake timestamp from a date and time string. Args: time_string (str): date and time value formatted as...
date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyToDateTimeString(self): """Copies the RFC2579 date-time to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#...
if self._number_of_seconds is None: return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:01d}'.format( self.year, self.month, self.day_of_month, self.hours, self.minutes, self.seconds, self.deciseconds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetNumberOfSeconds(self, fat_date_time): """Retrieves the number of seconds from a FAT date time. Args: fat_date_time (int): FAT date time. Returns: int: n...
day_of_month = (fat_date_time & 0x1f) month = ((fat_date_time >> 5) & 0x0f) year = (fat_date_time >> 9) & 0x7f days_per_month = self._GetDaysPerMonth(year, month) if day_of_month < 1 or day_of_month > days_per_month: raise ValueError('Day of month value out of bounds.') number_of_days =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyToDateTimeString(self): """Copies the FILETIME timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss....
if (self._timestamp is None or self._timestamp < 0 or self._timestamp > self._UINT64_MAX): return None timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND) number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp) year, month, day_of_month = self._GetDat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreatePrecisionHelper(cls, precision): """Creates a precision helper. Args: precision (str): precision of the date and time value, which should be one of th...
precision_helper_class = cls._PRECISION_CLASSES.get(precision, None) if not precision_helper_class: raise ValueError('Unsupported precision: {0!s}'.format(precision)) return precision_helper_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 CopyFromDateTimeString(self, time_string): """Copies a APFS timestamp from a date and time string. Args: time_string (str): date and time value formatted as...
super(APFSTime, self)._CopyFromDateTimeString(time_string) if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): raise ValueError('Date time value not supported.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyToDateTimeString(self): """Copies the APFS timestamp to a date and time string. Returns: str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.####...
if (self._timestamp is None or self._timestamp < self._INT64_MIN or self._timestamp > self._INT64_MAX): return None return super(APFSTime, self)._CopyToDateTimeString()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyToDateTimeString(self): """Copies the Cocoa timestamp to a date and time string. Returns: str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.####...
if self._timestamp is None: return None number_of_days, hours, minutes, seconds = self._GetTimeValues( int(self._timestamp)) year, month, day_of_month = self._GetDateValuesWithEpoch( number_of_days, self._EPOCH) microseconds = int( (self._timestamp % 1) * definitions.MI...
<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_sms_message(sms_message, backend=None, fail_silently=False): """ Send an SMSMessage instance using a connection given by the specified `backend`. """
with get_sms_connection(backend=backend, fail_silently=fail_silently) as connection: result = connection.send_messages([sms_message]) 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 send_messages(self, sms_messages): """ Receives a list of SMSMessage instances and returns a list of RQ `Job` instances. """
results = [] for message in sms_messages: try: assert message.connection is None except AssertionError: if not self.fail_silently: raise backend = self.backend fail_silently = self.fail_silently result = django_rq.enqueue(self._send, message, backend=backend, fail_silently=fail_silently...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CopyDateTimeFromStringISO8601(self, time_string): """Copies a date and time from an ISO 8601 date and time string. Args: time_string (str): time value form...
if not time_string: raise ValueError('Invalid time string.') time_string_length = len(time_string) year, month, day_of_month = self._CopyDateFromString(time_string) if time_string_length <= 10: return { 'year': year, 'month': month, 'day_of_month': day_of_mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CopyFromDateTimeString(self, time_string): """Copies time elements from a date and time string. Args: time_string (str): date and time value formatted as: Y...
date_time_values = self._CopyDateTimeFromString(time_string) self._CopyFromDateTimeValues(date_time_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 CopyFromStringISO8601(self, time_string): """Copies time elements from an ISO 8601 date and time string. Currently not supported: * Week notation "2016-W33" ...
date_time_values = self._CopyDateTimeFromStringISO8601(time_string) self._CopyFromDateTimeValues(date_time_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 CopyFromDateTimeString(self, time_string): """Copies a SYSTEMTIME structure from a date and time string. Args: time_string (str): date and time value format...
date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get('year', 0) month = date_time_values.get('month', 0) day_of_month = date_time_values.get('day_of_month', 0) hours = date_time_values.get('hours', 0) minutes = date_time_values.get('minutes', 0) seconds ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_template(self, obj, needs_request=False): """ This is a copy of CharField.prepare_template, except that it adds a fake request to the context, which...
if self.instance_name is None and self.template_name is None: raise SearchFieldError("This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.") if self.template_name is not None: template_names = ...
<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_value(self, context, obj, field_name): """ gets the translated value of field name. If `FALLBACK`evaluates to `True` and the field has no translation for...
try: language = get_language() value = self.get_translated_value(obj, field_name, language) if value: return value if self.FALLBACK: for lang, lang_name in settings.LANGUAGES: if lang == language: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def customWalker(node, space=''): """ A convenience function to ease debugging. It will print the node structure that's returned from CommonMark The usage would ...
txt = '' try: txt = node.literal except: pass if txt is None or txt == '': print('{}{}'.format(space, node.t)) else: print('{}{}\t{}'.format(space, node.t, txt)) cur = node.first_child if cur: while cur is not None: customWalker(cur, spa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paragraph(node): """ Process a paragraph, which includes all content under it """
text = '' if node.string_content is not None: text = node.string_content o = nodes.paragraph('', ' '.join(text)) o.line = node.sourcepos[0][0] for n in MarkDown(node): o.append(n) return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference(node): """ A hyperlink. Note that alt text doesn't work, since there's no apparent way to do that in docutils """
o = nodes.reference() o['refuri'] = node.destination if node.title: o['name'] = node.title for n in MarkDown(node): o += n return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emphasis(node): """ An italicized section """
o = nodes.emphasis() for n in MarkDown(node): o += n return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strong(node): """ A bolded section """
o = nodes.strong() for n in MarkDown(node): o += n return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def title(node): """ A title node. It has no children """
return nodes.title(node.first_child.literal, node.first_child.literal)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_quote(node): """ A block quote """
o = nodes.block_quote() o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(node): """ An image element The first child is the alt text. reStructuredText can't handle titles """
o = nodes.image(uri=node.destination) if node.first_child is not None: o['alt'] = node.first_child.literal return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listItem(node): """ An item in a list """
o = nodes.list_item() for n in MarkDown(node): o += n return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def MarkDown(node): """ Returns a list of nodes, containing CommonMark nodes converted to docutils nodes """
cur = node.first_child # Go into each child, in turn output = [] while cur is not None: t = cur.t if t == 'paragraph': output.append(paragraph(cur)) elif t == 'text': output.append(text(cur)) elif t == 'softbreak': output.append(softb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalizeSection(section): """ Correct the nxt and parent for each child """
cur = section.first_child last = section.last_child if last is not None: last.nxt = None while cur is not None: cur.parent = section cur = cur.nxt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nestSections(block, level=1): """ Sections aren't handled by CommonMark at the moment. This function adds sections to a block of nodes. 'title' nodes with an...
cur = block.first_child if cur is not None: children = [] # Do we need to do anything? nest = False while cur is not None: if cur.t == 'heading' and cur.level == level: nest = True break cur = cur.nxt if not nest: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseMarkDownBlock(text): """ Parses a block of text, returning a list of docutils nodes [] """
block = Parser().parse(text) # CommonMark can't nest sections, so do it manually nestSections(block) return MarkDown(block)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def renderList(l, markDownHelp, settings=None): """ Given a list of reStructuredText or MarkDown sections, return a docutils node list """
if len(l) == 0: return [] if markDownHelp: from sphinxarg.markdown import parseMarkDownBlock return parseMarkDownBlock('\n\n'.join(l) + '\n') else: all_children = [] for element in l: if isinstance(element, str): if settings is 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 print_action_groups(data, nested_content, markDownHelp=False, settings=None): """ Process all 'action groups', which are also include 'Options' and 'Required...
definitions = map_nested_definitions(nested_content) nodes_list = [] if 'action_groups' in data: for action_group in data['action_groups']: # Every action group is comprised of a section, holding a title, the description, and the option group (members) section = nodes.sectio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensureUniqueIDs(items): """ If action groups are repeated, then links in the table of contents will just go to the first of the repeats. This may not be desi...
s = set() for item in items: for n in item.traverse(descend=True, siblings=True, ascend=False): if isinstance(n, nodes.section): ids = n['ids'] for idx, id in enumerate(ids): if id not in s: s.add(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 select(self, item): """Select an arbitrary item, by possition or by reference."""
self._on_unselect[self._selected]() self.selected().unfocus() if isinstance(item, int): self._selected = item % len(self) else: self._selected = self.items.index(item) self.selected().focus() self._on_select[self._selected]()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_select(self, item, action): """ Add an action to make when an object is selected. Only one action can be stored this way. """
if not isinstance(item, int): item = self.items.index(item) self._on_select[item] = action
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_unselect(self, item, action): """Add an action to make when an object is unfocused."""
if not isinstance(item, int): item = self.items.index(item) self._on_unselect[item] = action
<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(self, widget, condition=lambda: 42): """ Add a widget to the widows. The widget will auto render. You can use the function like that if you want to keep ...
assert callable(condition) assert isinstance(widget, BaseWidget) self._widgets.append((widget, condition)) return widget
<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, widget): """Remove a widget from the window."""
for i, (wid, _) in enumerate(self._widgets): if widget is wid: del self._widgets[i] return True raise ValueError('Widget not in list')
<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_on_event(self, e): """Process a single event."""
if e.type == QUIT: self.running = False elif e.type == KEYDOWN: if e.key == K_ESCAPE: self.running = False elif e.key == K_F4 and e.mod & KMOD_ALT: # Alt+F4 --> quits self.running = False elif e.type == VIDEORESIZE: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self): """Render the screen. Here you must draw everything."""
self.screen.fill(self.BACKGROUND_COLOR) for wid, cond in self._widgets: if cond(): wid.render(self.screen) if self.BORDER_COLOR is not None: pygame.draw.rect(self.screen, self.BORDER_COLOR, ((0, 0), self.SCREEN_SIZE), 1) if self.SHOW_FPS: ...
<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_screen(self): """Refresh the screen. You don't need to override this except to update only small portins of the screen."""
self.clock.tick(self.FPS) pygame.display.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_screen(self): """Makes a new screen with a size of SCREEN_SIZE, and VIDEO_OPTION as flags. Sets the windows name to NAME."""
os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.display.set_caption(self.NAME) screen_s = self.SCREEN_SIZE video_options = self.VIDEO_OPTIONS if FULLSCREEN & self.VIDEO_OPTIONS: video_options ^= FULLSCREEN video_options |= NOFRAME screen_s = (0...
<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_rects(rect1, rect2): """Return the smallest rect containning two rects"""
r = pygame.Rect(rect1) t = pygame.Rect(rect2) right = max(r.right, t.right) bot = max(r.bottom, t.bottom) x = min(t.x, r.x) y = min(t.y, r.y) return pygame.Rect(x, y, right - x, bot - y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normnorm(self): """ Return a vecor noraml to this one with a norm of one :return: V2 """
n = self.norm() return V2(-self.y / n, self.x / 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 line(surf, start, end, color=BLACK, width=1, style=FLAT): """Draws an antialiased line on the surface."""
width = round(width, 1) if width == 1: # return pygame.draw.aaline(surf, color, start, end) return gfxdraw.line(surf, *start, *end, color) start = V2(*start) end = V2(*end) line_vector = end - start half_side = line_vector.normnorm() * width / 2 point1 = start + half_sid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circle(surf, xy, r, color=BLACK): """Draw an antialiased filled circle on the given surface"""
x, y = xy x = round(x) y = round(y) r = round(r) gfxdraw.filled_circle(surf, x, y, r, color) gfxdraw.aacircle(surf, x, y, r, color) r += 1 return pygame.Rect(x - r, y - r, 2 * r, 2 * r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ring(surf, xy, r, width, color): """Draws a ring"""
r2 = r - width x0, y0 = xy x = r2 y = 0 err = 0 # collect points of the inner circle right = {} while x >= y: right[x] = y right[y] = x right[-x] = y right[-y] = x y += 1 if err <= 0: err += 2 * y + 1 if err > 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roundrect(surface, rect, color, rounding=5, unit=PIXEL): """ Draw an antialiased round rectangle on the surface. surface : destination rect : rectangle color...
if unit == PERCENT: rounding = int(min(rect.size) / 2 * rounding / 100) rect = pygame.Rect(rect) color = pygame.Color(*color) alpha = color.a color.a = 0 pos = rect.topleft rect.topleft = 0, 0 rectangle = pygame.Surface(rect.size, SRCALPHA) circle = pygame.Surface([min(re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def polygon(surf, points, color): """Draw an antialiased filled polygon on a surface"""
gfxdraw.aapolygon(surf, points, color) gfxdraw.filled_polygon(surf, points, color) x = min([x for (x, y) in points]) y = min([y for (x, y) in points]) xm = max([x for (x, y) in points]) ym = max([y for (x, y) in points]) return pygame.Rect(x, y, xm - x, ym - y)
<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(self): """Return the color of the button, depending on its state"""
if self.clicked and self.hovered: # the mouse is over the button color = mix(self.color, BLACK, 0.8) elif self.hovered and not self.flags & self.NO_HOVER: color = mix(self.color, BLACK, 0.93) else: color = self.color self.text.bg_color = color ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _front_delta(self): """Return the offset of the colored part."""
if self.flags & self.NO_MOVE: return Separator(0, 0) if self.clicked and self.hovered: # the mouse is over the button delta = 2 elif self.hovered and not self.flags & self.NO_HOVER: delta = 0 else: delta = 0 return Separator(d...
<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, event_or_list): """Update the button with the events."""
for e in super().update(event_or_list): if e.type == MOUSEBUTTONDOWN: if e.pos in self: self.click() else: self.release(force_no_call=True) elif e.type == MOUSEBUTTONUP: self.release(force_no_call=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, surf): """Render the button on a surface."""
pos, size = self.topleft, self.size if not self.flags & self.NO_SHADOW: if self.flags & self.NO_ROUNDING: pygame.draw.rect(surf, LIGHT_GREY, (pos + self._bg_delta, size)) else: roundrect(surf, (pos + self._bg_delta, size), LIGHT_GREY + (100,), 5)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, surf): """Draw the button on the surface."""
if not self.flags & self.NO_SHADOW: circle(surf, self.center + self._bg_delta, self.width / 2, LIGHT_GREY) circle(surf, self.center + self._front_delta, self.width / 2, self._get_color()) self.text.center = self.center + self._front_delta self.text.render(surf)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, surf): """Render the button"""
if self.clicked: icon = self.icon_pressed else: icon = self.icon surf.blit(icon, 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 set(self, value): """Set the value of the bar. If the value is out of bound, sets it to an extremum"""
value = min(self.max, max(self.min, value)) self._value = value start_new_thread(self.func, (self.get(),))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start(self): """Starts checking if the SB is shifted"""
# TODO : make an update method instead last_call = 42 while self._focus: sleep(1 / 100) mouse = pygame.mouse.get_pos() last_value = self.get() self.value_px = mouse[0] # we do not need to do anything when it the same 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 value_px(self): """The position in pixels of the cursor"""
step = self.w / (self.max - self.min) return self.x + step * (self.get() - self.min)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, display): """Renders the bar on the display"""
# the bar bar_rect = pygame.Rect(0, 0, self.width, self.height // 3) bar_rect.center = self.center display.fill(self.bg_color, bar_rect) # the cursor circle(display, (self.value_px, self.centery), self.height // 2, self.color) # the value if self.show_...
<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): """ This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks. """
# I can not set the size attr because it is my property, so I set the width and height separately width, height = self.size super(BaseWidget, self).__setattr__("width", width) super(BaseWidget, self).__setattr__("height", height) super(BaseWidget, self).__setattr__(self.anchor,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate(specifier): """Make a compatible version of pip importable. Raise a RuntimeError if we couldn't."""
try: for distro in require(specifier): distro.activate() except (VersionConflict, DistributionNotFound): raise RuntimeError('The installed version of pip is too old; peep ' 'requires ' + specifier)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_and_line(req): """Return the path and line number of the file from which an InstallRequirement came. """
path, line = (re.match(r'-r (.*) \(line (\d+)\)$', req.comes_from).groups()) return path, int(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hashes_above(path, line_number): """Yield hashes from contiguous comment lines before line ``line_number``. """
def hash_lists(path): """Yield lists of hashes appearing between non-comment lines. The lists will be in order of appearance and, for each non-empty list, their place in the results will coincide with that of the line number of the corresponding result from `parse_requirements` ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_of_file(path): """Return the hash of a downloaded file."""
with open(path, 'rb') as archive: sha = sha256() while True: data = archive.read(2 ** 20) if not data: break sha.update(data) return encoded_hash(sha)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requirement_args(argv, want_paths=False, want_other=False): """Return an iterable of filtered arguments. :arg argv: Arguments, starting after the subcommand ...
was_r = False for arg in argv: # Allow for requirements files named "-r", don't freak out if there's a # trailing "-r", etc. if was_r: if want_paths: yield arg was_r = False elif arg in ['-r', '--requirement']: was_r = 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 peep_hash(argv): """Return the peep hash of one or more files, returning a shell status code or raising a PipException. :arg argv: The commandline args, star...
parser = OptionParser( usage='usage: %prog hash file [file ...]', description='Print a peep hash line for one or more files: for ' 'example, "# sha256: ' 'oz42dZy6Gowxw8AelDtO4gRgTW_xPdooH484k7I5EOY".') _, paths = parser.parse_args(args=argv) if paths...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoize(func): """Memoize a method that should return the same result every time on a given instance. """
@wraps(func) def memoizer(self): if not hasattr(self, '_cache'): self._cache = {} if func.__name__ not in self._cache: self._cache[func.__name__] = func(self) return self._cache[func.__name__] return memoizer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def package_finder(argv): """Return a PackageFinder respecting command-line options. :arg argv: Everything after the subcommand """
# We instantiate an InstallCommand and then use some of its private # machinery--its arg parser--for our own purposes, like a virus. This # approach is portable across many pip versions, where more fine-grained # ones are not. Ignoring options that don't exist on the parser (for # instance, --use-w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bucket(things, key): """Return a map of key -> list of things."""
ret = defaultdict(list) for thing in things: ret[key(thing)].append(thing) 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 first_every_last(iterable, first, every, last): """Execute something before the first item of iter, something else for each item, and a third thing after the...
did_first = False for item in iterable: if not did_first: did_first = True first(item) every(item) if did_first: last(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downloaded_reqs_from_path(path, argv): """Return a list of DownloadedReqs representing the requirements parsed out of a given requirements file. :arg path: T...
finder = package_finder(argv) return [DownloadedReq(req, argv, finder) for req in _parse_requirements(path, finder)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peep_install(argv): """Perform the ``peep install`` subcommand, returning a shell status code or raising a PipException. :arg argv: The commandline args, sta...
output = [] out = output.append reqs = [] try: req_paths = list(requirement_args(argv, want_paths=True)) if not req_paths: out("You have to specify one or more requirements files with the -r option, because\n" "otherwise there's nowhere for peep to look up th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peep_port(paths): """Convert a peep requirements file to one compatble with pip-8 hashing. Loses comments and tromps on URLs, so the result will need a littl...
if not paths: print('Please specify one or more requirements files so I have ' 'something to port.\n') return COMMAND_LINE_ERROR comes_from = None for req in chain.from_iterable( _parse_requirements(path, package_finder(argv)) for path in paths): req_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 main(): """Be the top-level entrypoint. Return a shell status code."""
commands = {'hash': peep_hash, 'install': peep_install, 'port': peep_port} try: if len(argv) >= 2 and argv[1] in commands: return commands[argv[1]](argv[2:]) else: # Fall through to top-level pip main() for everything else: 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 _version(self): """Deduce the version number of the downloaded package from its filename."""
# TODO: Can we delete this method and just print the line from the # reqs file verbatim instead? def version_of_archive(filename, package_name): # Since we know the project_name, we can strip that off the left, strip # any archive extensions off the right, and take the r...
<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_always_unsatisfied(self): """Returns whether this requirement is always unsatisfied This would happen in cases where we can't determine the version from ...
# If this is a github sha tarball, then it is always unsatisfied # because the url has a commit sha in it and not the version # number. url = self._url() if url: filename = filename_from_url(url) if filename.endswith(ARCHIVE_EXTENSIONS): f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _download(self, link): """Download a file, and return its name within my temp dir. This does no verification of HTTPS certs, but our checking hashes makes th...
# Based on pip 1.4.1's URLOpener but with cert verification removed def opener(is_https): if is_https: opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to prevent MITM spoof: for handler in opener.handlers: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _downloaded_filename(self): """Download the package's archive if necessary, and return its filename. --no-deps is implied, as we have reimplemented the bits ...
# Peep doesn't support requirements that don't come down as a single # file, because it can't hash them. Thus, it doesn't support editable # requirements, because pip itself doesn't support editable # requirements except for "local projects or a VCS url". Nor does it # support V...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self): """Install the package I represent, without dependencies. Obey typical pip-install options passed in on the command line. """
other_args = list(requirement_args(self._argv, want_other=True)) archive_path = join(self._temp_path, self._downloaded_filename()) # -U so it installs whether pip deems the requirement "satisfied" or # not. This is necessary for GitHub-sourced zips, which change without # their ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _project_name(self): """Return the inner Requirement's "unsafe name". Raise ValueError if there is no name. """
name = getattr(self._req.req, 'project_name', '') if name: return name name = getattr(self._req.req, 'name', '') if name: return safe_name(name) raise ValueError('Requirement has no project_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 _class(self): """Return the class I should be, spanning a continuum of goodness."""
try: self._project_name() except ValueError: return MalformedReq if self._is_satisfied(): return SatisfiedReq if not self._expected_hashes(): return MissingReq if self._actual_hash() not in self._expected_hashes(): retu...
<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_response(self, uri, params=None, method="get", stream=False): """Creates a response object with the given params and option Parameters url : string The...
if not hasattr(self, "session") or not self.session: self.session = requests.Session() if self.access_token: self.session.headers.update( {'Authorization': 'Bearer {}'.format(self.access_token)} ) # Remove empty params ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __call(self, uri, params=None, method="get"): """Only returns the response, nor the status_code """
try: resp = self.__get_response(uri, params, method, False) rjson = resp.json(**self.json_options) assert resp.ok except AssertionError: msg = "OCode-{}: {}".format(resp.status_code, rjson["message"]) raise BadRequest(msg) except Excep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __call_stream(self, uri, params=None, method="get"): """Returns an stream response """
try: resp = self.__get_response(uri, params, method, True) assert resp.ok except AssertionError: raise BadRequest(resp.status_code) except Exception as e: log.error("Bad response: {}".format(e), exc_info=True) else: return resp
<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_trades(self, max_id=None, count=None, instrument=None, ids=None): """ Get a list of open trades Parameters max_id : int The server will return trades wit...
url = "{0}/{1}/accounts/{2}/trades".format( self.domain, self.API_VERSION, self.account_id ) params = { "maxId": int(max_id) if max_id and max_id > 0 else None, "count": int(count) if count and count > 0 else None, "instrum...
<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_trade( self, trade_id, stop_loss=None, take_profit=None, trailing_stop=None ): """ Modify an existing trade. Note: Only the specified parameters will ...
url = "{0}/{1}/accounts/{2}/trades/{3}".format( self.domain, self.API_VERSION, self.account_id, trade_id ) params = { "stopLoss": stop_loss, "takeProfit": take_profit, "trailingStop": trailing_stop } ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_transaction_history(self): """ Request full account history. Submit a request for a full transaction history. A successfully accepted submission resu...
url = "{0}/{1}/accounts/{2}/alltransactions".format( self.domain, self.API_VERSION, self.account_id ) try: resp = self.__get_response(url) return resp.headers['location'] except RequestException: return False ...
<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_transaction_history(self, max_wait=5.0): """ Download full account history. Uses request_transaction_history to get the transaction history URL, then pol...
url = self.request_transaction_history() if not url: return False ready = False start = time() delay = 0.1 while not ready and delay: response = requests.head(url) ready = response.ok if not ready: sleep(de...
<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_accounts(self, username=None): """ Get a list of accounts owned by the user. Parameters username : string The name of the user. Note: This is only requir...
url = "{0}/{1}/accounts".format(self.domain, self.API_VERSION) params = {"username": username} try: return self._Client__call(uri=url, params=params, method="get") except RequestException: return False except AssertionError: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def choose(self): """Marks the item as the one the user is in."""
if not self.choosed: self.choosed = True self.pos = self.pos + Sep(5, 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_choose(self): """Marks the item as the one the user is not in."""
if self.choosed: self.choosed = False self.pos = self.pos + Sep(-5, 0)
<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_darker_color(self): """The color of the clicked version of the MenuElement. Darker than the normal one."""
# we change a bit the color in one direction if bw_contrasted(self._true_color, 30) == WHITE: color = mix(self._true_color, WHITE, 0.9) else: color = mix(self._true_color, BLACK, 0.9) return color
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, screen): """Renders the MenuElement"""
self.rect.render(screen) super(MenuElement, self).render(screen)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def px_to_pt(self, px): """Convert a size in pxel to a size in points."""
if px < 200: pt = self.PX_TO_PT[px] else: pt = int(floor((px - 1.21) / 1.332)) return pt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_size(self, pt=None, px=None): """ Set the size of the font, in px or pt. The px method is a bit inacurate, there can be one or two px less, and max 4 for...
assert (pt, px) != (None, None) if pt is not None: self.__init__(pt, self.font_name) else: self.__init__(self.px_to_pt(px), self.font_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 text(self): """Return the string to render."""
if callable(self._text): return str(self._text()) return str(self._text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_font_size(self, pt=None, px=None): """Set the font size to the desired size, in pt or px."""
self.font.set_size(pt, px) self._render()