INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Refresh the screen. You don t need to override this except to update only small portins of the screen. | 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() |
The run loop. Returns self. destroy () | def run(self):
"""The run loop. Returns self.destroy()"""
while self.running:
self.update()
self.render()
self.update_screen()
return self.destroy() |
Makes a new screen with a size of SCREEN_SIZE and VIDEO_OPTION as flags. Sets the windows name to NAME. | 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
... |
Return the smallest rect containning two rects | 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) |
Return a vecor noraml to this one with a norm of one | 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) |
Draws an antialiased line on the surface. | 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)... |
Draw an antialiased filled circle on the given surface | 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 ... |
Draws a ring | 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 er... |
Draw an antialiased round rectangle on the surface. | def roundrect(surface, rect, color, rounding=5, unit=PIXEL):
"""
Draw an antialiased round rectangle on the surface.
surface : destination
rect : rectangle
color : rgb or rgba
radius : 0 <= radius <= 1
:source: http://pygame.org/project-AAfilledRoundedRect-2349-.html
"""
if u... |
Draw an antialiased filled polygon on a surface | 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 ... |
Call when the button is pressed. This start the callback function in a thread If: milis is given will release the button after: milis miliseconds | def click(self, force_no_call=False, milis=None):
"""
Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds
"""
if self.clicked:
return False
if not force_no_call an... |
Return the color of the button depending on its state | 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... |
Return the offset of the colored part. | 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:
... |
Update the button with the events. | 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)
... |
Render the button on a surface. | 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:
... |
Draw the button on the surface. | 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.c... |
Returns an icon 80% more dark | def get_darker_image(self):
"""Returns an icon 80% more dark"""
icon_pressed = self.icon.copy()
for x in range(self.w):
for y in range(self.h):
r, g, b, *_ = tuple(self.icon.get_at((x, y)))
const = 0.8
r = int(const * r)
... |
Render the button | def render(self, surf):
"""Render the button"""
if self.clicked:
icon = self.icon_pressed
else:
icon = self.icon
surf.blit(icon, self) |
Set the value of the bar. If the value is out of bound sets it to an extremum | 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(),)) |
Starts checking if the SB is shifted | 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]
... |
The position in pixels of the cursor | 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) |
Renders the bar on the display | 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), s... |
This is called each time an attribute is asked to be sure every params are updated beceause of callbacks. | 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(BaseW... |
Make a compatible version of pip importable. Raise a RuntimeError if we couldn t. | 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 ol... |
Return the path and line number of the file from which an InstallRequirement came. | 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) |
Yield hashes from contiguous comment lines before line line_number. | 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... |
Delegate to pip the given args ( starting with the subcommand ) and raise PipException if something goes wrong. | def run_pip(initial_args):
"""Delegate to pip the given args (starting with the subcommand), and raise
``PipException`` if something goes wrong."""
status_code = pip.main(initial_args)
# Clear out the registrations in the pip "logger" singleton. Otherwise,
# loggers keep getting appended to it with... |
Return the hash of a downloaded file. | 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) |
Return an iterable of filtered arguments. | def requirement_args(argv, want_paths=False, want_other=False):
"""Return an iterable of filtered arguments.
:arg argv: Arguments, starting after the subcommand
:arg want_paths: If True, the returned iterable includes the paths to any
requirements files following a ``-r`` or ``--requirement`` optio... |
Return the peep hash of one or more files returning a shell status code or raising a PipException. | 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, starting after the subcommand
"""
parser = OptionParser(
usage='usage: %prog hash file [file ...]',
description='Print a peep... |
Memoize a method that should return the same result every time on a given instance. | 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__] = f... |
Return a PackageFinder respecting command - line options. | 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 a... |
Return a map of key - > list of things. | 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 |
Execute something before the first item of iter something else for each item and a third thing after the last. | 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 last.
If there are no items in the iterable, don't execute anything.
"""
did_first = False
for item in iterable:
if not did_... |
Return a list of DownloadedReqs representing the requirements parsed out of a given requirements file. | def downloaded_reqs_from_path(path, argv):
"""Return a list of DownloadedReqs representing the requirements parsed
out of a given requirements file.
:arg path: The path to the requirements file
:arg argv: The commandline args, starting after the subcommand
"""
finder = package_finder(argv)
... |
Perform the peep install subcommand returning a shell status code or raising a PipException. | def peep_install(argv):
"""Perform the ``peep install`` subcommand, returning a shell status code
or raising a PipException.
:arg argv: The commandline args, starting after the subcommand
"""
output = []
out = output.append
reqs = []
try:
req_paths = list(requirement_args(argv,... |
Convert a peep requirements file to one compatble with pip - 8 hashing. | 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 little manual
massaging, but the hard part--the hash conversion--is done for you.
"""
if not paths:
print('Please specify one or more ... |
Be the top - level entrypoint. Return a shell status code. | 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:
... |
Deduce the version number of the downloaded package from its filename. | 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, ... |
Returns whether this requirement is always unsatisfied | 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 the filename.
"""
# If this is a github sha tarball, then it is always unsatisfied
# because the url has a co... |
Download a file and return its name within my temp dir. | 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 that largely unimportant. It would be nice to be able to use the
requests lib, which can verify certs, but it is guaranteed to b... |
Download the package s archive if necessary and return its filename. | 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 that would
ordinarily do dependency resolution.
"""
# Peep doesn't support requirements that don't come down ... |
Install the package I represent without dependencies. | 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())
... |
Return the inner Requirement s unsafe name. | 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 the class I should be spanning a continuum of goodness. | 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():
re... |
Logic extracted from: http:// developer. oanda. com/ rest - live/ orders/ #createNewOrder | def check(self):
"""
Logic extracted from:
http://developer.oanda.com/rest-live/orders/#createNewOrder
"""
for k in iter(self.__dict__.keys()):
if k not in self.__allowed:
raise TypeError("Parameter not allowed {}".format(k))
for k in self.__r... |
Main function | def gui():
"""Main function"""
global SCREEN_SIZE
# #######
# setup all objects
# #######
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = new_widow()
pygame.display.set_caption('Client swag')
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN])
clock = pygame.time.Clock(... |
Main function | def gui():
"""Main function"""
global SCREEN_SIZE
# #######
# setup all objects
# #######
os.environ['SDL_VIDEO_CENTERED'] = '1' # centers the windows
screen = new_screen()
pygame.display.set_caption('Empty project')
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN])
... |
Creates a response object with the given params and option | 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 full URL to request.
params: dict
A list of parameters to ... |
Only returns the response nor the status_code | 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:
... |
Returns an stream response | 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... |
See more: http:// developer. oanda. com/ rest - live/ rates/ #getInstrumentList | def get_instruments(self):
"""
See more:
http://developer.oanda.com/rest-live/rates/#getInstrumentList
"""
url = "{0}/{1}/instruments".format(self.domain, self.API_VERSION)
params = {"accountId": self.account_id}
try:
response = self._Client__c... |
See more: http:// developer. oanda. com/ rest - live/ rates/ #getCurrentPrices | def get_prices(self, instruments, stream=True):
"""
See more:
http://developer.oanda.com/rest-live/rates/#getCurrentPrices
"""
url = "{0}/{1}/prices".format(
self.domain_stream if stream else self.domain,
self.API_VERSION
)
params =... |
See more: http:// developer. oanda. com/ rest - live/ rates/ #retrieveInstrumentHistory | def get_instrument_history(self, instrument, candle_format="bidask",
granularity='S5', count=500,
daily_alignment=None, alignment_timezone=None,
weekly_alignment="Monday", start=None,
end=None):
... |
See more: http:// developer. oanda. com/ rest - live/ orders/ #getOrdersForAnAccount | def get_orders(self, instrument=None, count=50):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount
"""
url = "{0}/{1}/accounts/{2}/orders".format(
self.domain,
self.API_VERSION,
self.account_id
)
... |
See more: http:// developer. oanda. com/ rest - live/ orders/ #getInformationForAnOrder | def get_order(self, order_id):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
order_id
... |
See more: http:// developer. oanda. com/ rest - live/ orders/ #createNewOrder | def create_order(self, order):
"""
See more:
http://developer.oanda.com/rest-live/orders/#createNewOrder
"""
url = "{0}/{1}/accounts/{2}/orders".format(
self.domain,
self.API_VERSION,
self.account_id
)
try:
r... |
Get a list of open trades | 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 with id less than or equal
to this, in descending order (for pagination)
... |
Modify an existing trade. | 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 be modified. All
other parameters will remain unchanged. To remove an
... |
Request full account history. | def request_transaction_history(self):
""" Request full account history.
Submit a request for a full transaction history. A
successfully accepted submission results in a response
containing a URL in the Location header to a file that will
be available once the r... |
Download full account history. | def get_transaction_history(self, max_wait=5.0):
""" Download full account history.
Uses request_transaction_history to get the transaction
history URL, then polls the given URL until it's ready (or
the max_wait time is reached) and provides the decoded
response.... |
Create a new account. | def create_account(self, currency=None):
""" Create a new account.
This call is only available on the sandbox system. Please
create accounts on fxtrade.oanda.com on our production
system.
See more:
http://developer.oanda.com/rest-sandbox/accounts/#-a... |
Get a list of accounts owned by the user. | 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 required on the
sandbox, on production systems your access token will
... |
Marks the item as the one the user is in. | 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) |
Marks the item as the one the user is not in. | 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) |
The color of the clicked version of the MenuElement. Darker than the normal one. | 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 =... |
Renders the MenuElement | def render(self, screen):
"""Renders the MenuElement"""
self.rect.render(screen)
super(MenuElement, self).render(screen) |
Main function | def gui():
"""Main function"""
# #######
# setup all objects
# #######
zones = [ALL]
last_zones = []
COLORS.remove(WHITE)
screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF)
pygame.display.set_caption('Bezier simulator')
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTT... |
Main function | def gui():
"""Main function"""
# #######
# setup all objects
# #######
os.environ['SDL_VIDEO_CENTERED'] = '1'
clock = pygame.time.Clock()
screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF | NOFRAME)
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN])
game = Morpion()
... |
Convert a size in pxel to a size in points. | 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 |
Set the size of the font in px or pt. | 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 big numbers (like 503)
but the size is never over-estimated. It makes almost the good value.
"""
assert (pt,... |
Return the string to render. | def text(self):
"""Return the string to render."""
if callable(self._text):
return str(self._text())
return str(self._text) |
Set the color to a new value ( tuple ). Renders the text if needed. | def color(self, value):
"""Set the color to a new value (tuple). Renders the text if needed."""
if value != self.color:
self._color = value
self._render() |
Sets the color to a new value ( tuple ). Renders the text if needed. | def bg_color(self, value):
"""Sets the color to a new value (tuple). Renders the text if needed."""
if value != self.bg_color:
self._bg_color = value
self._render() |
Set the font size to the desired size in pt or px. | 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() |
Render the text. | def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... |
Render basicly the text. | def render(self, display):
"""Render basicly the text."""
# to handle changing objects / callable
if self.text != self._last_text:
self._render()
display.blit(self._surface, (self.topleft, self.size)) |
The position of the cursor in the text. | def cursor(self):
"""The position of the cursor in the text."""
if self._cursor < 0:
self.cursor = 0
if self._cursor > len(self):
self.cursor = len(self)
return self._cursor |
Move the cursor of one letter to the right ( 1 ) or the the left. | def move_cursor_one_letter(self, letter=RIGHT):
"""Move the cursor of one letter to the right (1) or the the left."""
assert letter in (self.RIGHT, self.LEFT)
if letter == self.RIGHT:
self.cursor += 1
if self.cursor > len(self.text):
self.cursor -= 1
... |
Move the cursor of one word to the right ( 1 ) or the the left ( - 1 ). | def move_cursor_one_word(self, word=LEFT):
"""Move the cursor of one word to the right (1) or the the left (-1)."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self)
... |
Delete one letter the right or the the left of the cursor. | def delete_one_letter(self, letter=RIGHT):
"""Delete one letter the right or the the left of the cursor."""
assert letter in (self.RIGHT, self.LEFT)
if letter == self.LEFT:
papy = self.cursor
self.text = self.text[:self.cursor - 1] + self.text[self.cursor:]
... |
Delete one word the right or the the left of the cursor. | def delete_one_word(self, word=RIGHT):
"""Delete one word the right or the the left of the cursor."""
assert word in (self.RIGHT, self.LEFT)
if word == self.RIGHT:
papy = self.text.find(' ', self.cursor) + 1
if not papy:
papy = len(self.text)
... |
Add a letter at the cursor pos. | def add_letter(self, letter):
"""Add a letter at the cursor pos."""
assert isinstance(letter, str)
assert len(letter) == 1
self.text = self.text[:self.cursor] + letter + self.text[self.cursor:]
self.cursor += 1 |
Update the text and position of cursor according to the event passed. | def update(self, event_or_list):
"""Update the text and position of cursor according to the event passed."""
event_or_list = super().update(event_or_list)
for e in event_or_list:
if e.type == KEYDOWN:
if e.key == K_RIGHT:
if e.mod * KMOD_CTRL:
... |
Render the text. | def _render(self):
"""
Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
size = self.wid... |
The text displayed instead of the real one. | def shawn_text(self):
"""The text displayed instead of the real one."""
if len(self._shawn_text) == len(self):
return self._shawn_text
if self.style == self.DOTS:
return chr(0x2022) * len(self)
ranges = [
(902, 1366),
(192, 683),
... |
The cursor position in pixels. | def cursor_pos(self):
"""The cursor position in pixels."""
if len(self) == 0:
return self.left + self.default_text.get_width()
papy = self._surface.get_width()
if papy > self.w:
shift = papy - self.width
else:
shift = 0
return self.le... |
Render the text. | def _render(self):
"""
Render the text.
Avoid using this fonction too many times as it is slow as it is slow to render text and blit it.
"""
self._last_text = self.shawn_text
self._surface = self.font.render(self.shawn_text, True, self.color, self.bg_color)
siz... |
Render basicly the text. | def render(self, display):
"""Render basicly the text."""
# to handle changing objects / callable
if self.shawn_text != self._last_text:
self._render()
if self.text:
papy = self._surface.get_width()
if papy <= self.width:
display.blit... |
Return a pygame image from a latex template. | def latex_to_img(tex):
"""Return a pygame image from a latex template."""
with tempfile.TemporaryDirectory() as tmpdirname:
with open(tmpdirname + r'\tex.tex', 'w') as f:
f.write(tex)
os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-in... |
Return the mix of two colors at a state of: pos: | def mix(color1, color2, pos=0.5):
"""
Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos)
"""
opp_pos = 1 - pos
red = color1[0] * pos + color2[0] * opp_pos
green = color1[1] * pos + color2[1] * opp_pos
blue = color1[2] * pos + color2[2] * opp_pos
... |
Convert the name of a color into its RGB value | def name2rgb(name):
"""Convert the name of a color into its RGB value"""
try:
import colour
except ImportError:
raise ImportError('You need colour to be installed: pip install colour')
c = colour.Color(name)
color = int(c.red * 255), int(c.green * 255), int(c.blue * 255)
return ... |
Parse the command man page. | def parse_page(page):
"""Parse the command man page."""
colors = get_config()['colors']
with io.open(page, encoding='utf-8') as f:
lines = f.readlines()
output_lines = []
for line in lines[1:]:
if is_headline(line):
continue
elif is_description(line):
... |
Configure the module logging engine. | def configure_logging(level=logging.DEBUG):
"""Configure the module logging engine."""
if level == logging.DEBUG:
# For debugging purposes, log from everyone!
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
re... |
Wrapper around os. path. join. Makes sure to join paths of the same type ( bytes ). | def path_join(*args):
"""
Wrapper around `os.path.join`.
Makes sure to join paths of the same type (bytes).
"""
args = (paramiko.py3compat.u(arg) for arg in args)
return os.path.join(*args) |
Parse a command line string and return username password remote hostname and remote path. | def parse_username_password_hostname(remote_url):
"""
Parse a command line string and return username, password, remote hostname and remote path.
:param remote_url: A command line string.
:return: A tuple, containing username, password, remote hostname and remote path.
"""
assert remote_url
... |
Ask the SSH agent for a list of keys and return it. | def get_ssh_agent_keys(logger):
"""
Ask the SSH agent for a list of keys, and return it.
:return: A reference to the SSH agent and a list of keys.
"""
agent, agent_keys = None, None
try:
agent = paramiko.agent.Agent()
_agent_keys = agent.get_keys()
if not _agent_keys:
... |
Create the CLI argument parser. | def create_parser():
"""Create the CLI argument parser."""
parser = argparse.ArgumentParser(
description='Sync a local and a remote folder through SFTP.'
)
parser.add_argument(
"path",
type=str,
metavar="local-path",
help="the path of the local folder",
)
... |
The main. | def main(args=None):
"""The main."""
parser = create_parser()
args = vars(parser.parse_args(args))
log_mapping = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': lo... |
Return True if the remote correspondent of local_path has to be deleted. | def _must_be_deleted(local_path, r_st):
"""Return True if the remote correspondent of local_path has to be deleted.
i.e. if it doesn't exists locally or if it has a different type from the remote one."""
# if the file doesn't exists
if not os.path.lexists(local_path):
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.