signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def set_title(title): | if not _rootinitialized:<EOL><INDENT>raise TDLError('<STR_LIT>')<EOL><DEDENT>_lib.TCOD_console_set_window_title(_encodeString(title))<EOL> | Change the window title.
Args:
title (Text): The new title text. | f3164:m11 |
def screenshot(path=None): | if not _rootinitialized:<EOL><INDENT>raise TDLError('<STR_LIT>')<EOL><DEDENT>if isinstance(path, str):<EOL><INDENT>_lib.TCOD_sys_save_screenshot(_encodeString(path))<EOL><DEDENT>elif path is None: <EOL><INDENT>filelist = _os.listdir('<STR_LIT:.>')<EOL>n = <NUM_LIT:1><EOL>filename = '<STR_LIT>' % n<EOL>while filename in... | Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot. | f3164:m12 |
def set_fps(fps): | _lib.TCOD_sys_set_fps(fps or <NUM_LIT:0>)<EOL> | Set the maximum frame rate.
Further calls to :any:`tdl.flush` will limit the speed of
the program to run at `fps` frames per second. This can
also be set to None to remove the frame rate limit.
Args:
fps (optional[int]): The frames per second limit, or None. | f3164:m13 |
def get_fps(): | return _lib.TCOD_sys_get_fps()<EOL> | Return the current frames per second of the running program set by
:any:`set_fps`
Returns:
int: The frame rate set by :any:`set_fps`.
If there is no current limit, this will return 0. | f3164:m14 |
def force_resolution(width, height): | _lib.TCOD_sys_force_fullscreen_resolution(width, height)<EOL> | Change the fullscreen resoulution.
Args:
width (int): Width in pixels.
height (int): Height in pixels. | f3164:m15 |
def _normalizePoint(self, x, y): | <EOL>x = int(x)<EOL>y = int(y)<EOL>assert (-self.width <= x < self.width) and(-self.height <= y < self.height),('<STR_LIT>' % (x, y, self))<EOL>return (x % self.width, y % self.height)<EOL> | Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function | f3164:c1:m1 |
def _normalizeRect(self, x, y, width, height): | x, y = self._normalizePoint(x, y) <EOL>assert width is None or isinstance(width, _INTTYPES), '<STR_LIT>' % repr(width)<EOL>assert height is None or isinstance(height, _INTTYPES), '<STR_LIT>' % repr(height)<EOL>if width is None:<EOL><INDENT>width = self.width - x<EOL><DEDENT>elif width < <NUM_LIT:0>: <EOL><INDENT>width ... | Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems | f3164:c1:m2 |
def _normalizeCursor(self, x, y): | width, height = self.get_size()<EOL>assert width != <NUM_LIT:0> and height != <NUM_LIT:0>, '<STR_LIT>'<EOL>while x >= width:<EOL><INDENT>x -= width<EOL>y += <NUM_LIT:1><EOL><DEDENT>while y >= height:<EOL><INDENT>if self._scrollMode == '<STR_LIT>':<EOL><INDENT>y -= <NUM_LIT:1><EOL>self.scroll(<NUM_LIT:0>, -<NUM_LIT:1>)<... | return the normalized the cursor position. | f3164:c1:m3 |
def set_mode(self, mode): | MODES = ['<STR_LIT:error>', '<STR_LIT>']<EOL>if mode.lower() not in MODES:<EOL><INDENT>raise TDLError('<STR_LIT>' % (MODES, repr(mode)))<EOL><DEDENT>self._scrollMode = mode.lower()<EOL> | Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError wil... | f3164:c1:m4 |
def set_colors(self, fg=None, bg=None): | if fg is not None:<EOL><INDENT>self._fg = _format_color(fg, self._fg)<EOL><DEDENT>if bg is not None:<EOL><INDENT>self._bg = _format_color(bg, self._bg)<EOL><DEDENT> | Sets the colors to be used with the L{print_str} and draw_* methods.
Values of None will only leave the current values unchanged.
Args:
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
.. seealso:: :any:... | f3164:c1:m5 |
def print_str(self, string): | x, y = self._cursor<EOL>for char in string:<EOL><INDENT>if char == '<STR_LIT:\n>': <EOL><INDENT>x = <NUM_LIT:0><EOL>y += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if char == '<STR_LIT:\r>': <EOL><INDENT>x = <NUM_LIT:0><EOL>continue<EOL><DEDENT>x, y = self._normalizeCursor(x, y)<EOL>self.draw_char(x, y, char, self._fg, self.... | Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved w... | f3164:c1:m6 |
def write(self, string): | <EOL>x, y = self._normalizeCursor(*self._cursor)<EOL>width, height = self.get_size()<EOL>wrapper = _textwrap.TextWrapper(initial_indent=('<STR_LIT:U+0020>'*x), width=width)<EOL>writeLines = []<EOL>for line in string.split('<STR_LIT:\n>'):<EOL><INDENT>if line:<EOL><INDENT>writeLines += wrapper.wrap(line)<EOL>wrapper.ini... | This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
str... | f3164:c1:m7 |
def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis): | <EOL>_put_char_ex(self.console_c, x, y, _format_char(char),<EOL>_format_color(fg, self._fg), _format_color(bg, self._bg), <NUM_LIT:1>)<EOL> | Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to ch... | f3164:c1:m8 |
def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis): | x, y = self._normalizePoint(x, y)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>width, height = self.get_size()<EOL>def _drawStrGen(x=x, y=y, string=string, width=width, height=height):<EOL><INDENT>"""<STR_LIT>"""<EOL>for char in _format_str(string):<EOL><INDENT>if y == height:<EOL><INDENT>r... | Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine ... | f3164:c1:m9 |
def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis): | x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>char = _format_char(string)<EOL>grid = _itertools.product((x for x in range(x, x + width)),<EOL>(y for y in range(y, y + height)))<EOL>batch = zip(grid, _itertools.repeat(char, width ... | Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
widt... | f3164:c1:m10 |
def draw_frame(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis): | x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)<EOL>char = _format_char(string)<EOL>if width == <NUM_LIT:1> or height == <NUM_LIT:1>: <EOL><INDENT>return self.draw_rect(x, y, width, height, char, fg, bg)<EOL><DEDENT>self.draw_rect(x, y... | Similar to L{draw_rect} but only draws the outline of the rectangle.
`width or `height` can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
Args:
x (int): The x-coordinate to start on.
... | f3164:c1:m11 |
def blit(self, source, x=<NUM_LIT:0>, y=<NUM_LIT:0>, width=None, height=None, srcX=<NUM_LIT:0>, srcY=<NUM_LIT:0>,<EOL>fg_alpha=<NUM_LIT:1.0>, bg_alpha=<NUM_LIT:1.0>): | assert isinstance(source, (Console, Window)), "<STR_LIT>"<EOL>x, y, width, height = self._normalizeRect(x, y, width, height)<EOL>srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)<EOL>srcX, srcY = source._translate(srcX, srcY)<EOL>source = source.console<EOL>x, y = self._translate(x, y)<EOL>se... | Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of ... | f3164:c1:m12 |
def get_cursor(self): | x, y = self._cursor<EOL>width, height = self.parent.get_size()<EOL>while x >= width:<EOL><INDENT>x -= width<EOL>y += <NUM_LIT:1><EOL><DEDENT>if y >= height and self.scrollMode == '<STR_LIT>':<EOL><INDENT>y = height - <NUM_LIT:1><EOL><DEDENT>return x, y<EOL> | Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move` | f3164:c1:m13 |
def get_size(self): | return self.width, self.height<EOL> | Return the size of the console as (width, height)
Returns:
Tuple[int, int]: A (width, height) tuple. | f3164:c1:m14 |
def __iter__(self): | return _itertools.product(range(self.width), range(self.height))<EOL> | Return an iterator with every possible (x, y) value for this console.
It goes without saying that working on the console this way is a
slow process, especially for Python, and should be minimized.
Returns:
Iterator[Tuple[int, int]]: An ((x, y), ...) iterator. | f3164:c1:m15 |
def move(self, x, y): | self._cursor = self._normalizePoint(x, y)<EOL> | Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write` | f3164:c1:m16 |
def scroll(self, x, y): | assert isinstance(x, _INTTYPES), "<STR_LIT>" % repr(x)<EOL>assert isinstance(y, _INTTYPES), "<STR_LIT>" % repr(x)<EOL>def getSlide(x, length):<EOL><INDENT>"""<STR_LIT>"""<EOL>if x > <NUM_LIT:0>:<EOL><INDENT>srcx = <NUM_LIT:0><EOL>length -= x<EOL><DEDENT>elif x < <NUM_LIT:0>:<EOL><INDENT>srcx = abs(x)<EOL>x = <NUM_LIT:0... | Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Retu... | f3164:c1:m17 |
def clear(self, fg=Ellipsis, bg=Ellipsis): | raise NotImplementedError('<STR_LIT>')<EOL> | Clears the entire L{Console}/L{Window}.
Unlike other drawing functions, fg and bg can not be None.
Args:
fg (Union[Tuple[int, int, int], int, Ellipsis])
bg (Union[Tuple[int, int, int], int, Ellipsis])
.. seealso:: :any:`draw_rect` | f3164:c1:m18 |
def get_char(self, x, y): | raise NotImplementedError('<STR_LIT>')<EOL> | Return the character and colors of a tile as (ch, fg, bg)
This method runs very slowly as is not recommended to be called
frequently.
Args:
x (int): The x-coordinate to pick.
y (int): The y-coordinate to pick.
Returns:
Tuple[int, Tuple[int, int, int... | f3164:c1:m19 |
def __contains__(self, position): | x, y = position<EOL>return (<NUM_LIT:0> <= x < self.width) and (<NUM_LIT:0> <= y < self.height)<EOL> | Use ``((x, y) in console)`` to check if a position is drawable on
this console. | f3164:c1:m20 |
@classmethod<EOL><INDENT>def _newConsole(cls, console):<DEDENT> | self = cls.__new__(cls)<EOL>_BaseConsole.__init__(self)<EOL>self.console_c = console<EOL>self.console = self<EOL>self.width = _lib.TCOD_console_get_width(console)<EOL>self.height = _lib.TCOD_console_get_height(console)<EOL>return self<EOL> | Make a Console instance, from a console ctype | f3164:c2:m3 |
def _root_unhook(self): | global _rootinitialized, _rootConsoleRef<EOL>if(_rootConsoleRef and _rootConsoleRef() is self):<EOL><INDENT>unhooked = _lib.TCOD_console_new(self.width, self.height)<EOL>_lib.TCOD_console_blit(self.console_c,<EOL><NUM_LIT:0>, <NUM_LIT:0>, self.width, self.height,<EOL>unhooked, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NU... | Change this root console into a normal Console object and
delete the root console from TCOD | f3164:c2:m4 |
def __del__(self): | if self.console_c is None:<EOL><INDENT>return <EOL><DEDENT>if self.console_c is _ffi.NULL:<EOL><INDENT>self._root_unhook() <EOL>return<EOL><DEDENT>_lib.TCOD_console_delete(self.console_c)<EOL>self.console_c = None<EOL> | If the main console is garbage collected then the window will be closed as well | f3164:c2:m5 |
@staticmethod<EOL><INDENT>def _translate(x, y):<DEDENT> | return x, y<EOL> | Convertion x and y to their position on the root Console for this Window
Because this is a Console instead of a Window we return the paramaters
untouched | f3164:c2:m9 |
def _set_char(self, x, y, char, fg=None, bg=None,<EOL>bgblend=_lib.TCOD_BKGND_SET): | <EOL>return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend)<EOL> | Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this. | f3164:c2:m11 |
def _set_batch(self, batch, fg, bg, bgblend=<NUM_LIT:1>, nullChar=False): | for (x, y), char in batch:<EOL><INDENT>self._set_char(x, y, char, fg, bg, bgblend)<EOL><DEDENT> | Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items | f3164:c2:m12 |
def _translate(self, x, y): | <EOL>return self.parent._translate((x + self.x), (y + self.y))<EOL> | Convertion x and y to their position on the root Console | f3164:c3:m1 |
def get_point(self, *position): | <EOL>array = _ffi.new(self._arrayType, position)<EOL>if self._useOctaves:<EOL><INDENT>return (self._noiseFunc(self._noise, array, self._octaves) + <NUM_LIT:1>) * <NUM_LIT:0.5><EOL><DEDENT>return (self._noiseFunc(self._noise, array) + <NUM_LIT:1>) * <NUM_LIT:0.5><EOL> | Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range. | f3165:c0:m4 |
def _parseKeyNames(lib): | _keyNames = {}<EOL>for attr in dir(lib): <EOL><INDENT>if attr[:<NUM_LIT:6>] == '<STR_LIT>': <EOL><INDENT>_keyNames[getattr(lib, attr)] = attr[<NUM_LIT:6>:] <EOL><DEDENT><DEDENT>return _keyNames<EOL> | returns a dictionary mapping of human readable key names to their keycodes
this parses constants with the names of K_* and makes code=name pairs
this is for KeyEvent.key variable and that enables things like:
if (event.key == 'PAGEUP'): | f3166:m0 |
def _processEvents(): | global _mousel, _mousem, _mouser, _eventsflushed, _pushedEvents<EOL>_eventsflushed = True<EOL>events = _pushedEvents <EOL>_pushedEvents = [] <EOL>mouse = _ffi.new('<STR_LIT>')<EOL>libkey = _ffi.new('<STR_LIT>')<EOL>while <NUM_LIT:1>:<EOL><INDENT>libevent = _lib.TCOD_sys_check_for_event(_lib.TCOD_EVENT_ANY, libkey, mous... | Flushes the event queue from libtcod into the global list _eventQueue | f3166:m1 |
def get(): | _processEvents()<EOL>return _event_generator()<EOL> | Flushes the event queue and returns the list of events.
This function returns :any:`Event` objects that can be identified by their
type attribute or their class.
Returns: Iterator[Type[Event]]: An iterable of Events or anything
put in a :any:`push` call.
If the iterator is deleted or othe... | f3166:m2 |
def wait(timeout=None, flush=True): | if timeout is not None:<EOL><INDENT>timeout = timeout + _time.clock() <EOL><DEDENT>while True:<EOL><INDENT>if _eventQueue:<EOL><INDENT>return _eventQueue.pop(<NUM_LIT:0>)<EOL><DEDENT>if flush:<EOL><INDENT>_tdl.flush()<EOL><DEDENT>if timeout and _time.clock() >= timeout:<EOL><INDENT>return None <EOL><DEDENT>_time.sleep(... | Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
... | f3166:m4 |
def push(event): | _pushedEvents.append(event)<EOL> | Push an event into the event buffer.
Args:
event (Any): This event will be available on the next call to
:any:`event.get`.
An event pushed in the middle of a :any:`get` will not show until
the next time :any:`get` called preventing push related
infinite loop... | f3166:m5 |
def key_wait(): | while <NUM_LIT:1>:<EOL><INDENT>for event in get():<EOL><INDENT>if event.type == '<STR_LIT>':<EOL><INDENT>return event<EOL><DEDENT>if event.type == '<STR_LIT>':<EOL><INDENT>return KeyDown('<STR_LIT>', '<STR_LIT>', True, False, True, False, False)<EOL><DEDENT><DEDENT>_time.sleep(<NUM_LIT>)<EOL><DEDENT> | Waits until the user presses a key.
Then returns a :any:`KeyDown` event.
Key events will repeat if held down.
A click to close the window will be converted into an Alt+F4 KeyDown event.
Returns:
tdl.event.KeyDown: The pressed key. | f3166:m6 |
def set_key_repeat(delay=<NUM_LIT>, interval=<NUM_LIT:0>): | pass<EOL> | Does nothing. | f3166:m7 |
def is_window_closed(): | return _lib.TCOD_console_is_window_closed()<EOL> | Returns True if the exit button on the window has been clicked and
stays True afterwards.
Returns: bool: | f3166:m8 |
def __repr__(self): | attrdict = {}<EOL>for varname in dir(self):<EOL><INDENT>if '<STR_LIT:_>' == varname[<NUM_LIT:0>]:<EOL><INDENT>continue<EOL><DEDENT>attrdict[varname] = self.__getattribute__(varname)<EOL><DEDENT>return '<STR_LIT>' % (self.__class__.__name__, repr(attrdict))<EOL> | List an events public attributes when printed. | f3166:c0:m0 |
def ev_QUIT(self, event): | raise SystemExit()<EOL> | Unless overridden this method raises a SystemExit exception closing
the program. | f3166:c9:m0 |
def ev_KEYDOWN(self, event): | Override this method to handle a :any:`KeyDown` event. | f3166:c9:m1 | |
def ev_KEYUP(self, event): | Override this method to handle a :any:`KeyUp` event. | f3166:c9:m2 | |
def ev_MOUSEDOWN(self, event): | Override this method to handle a :any:`MouseDown` event. | f3166:c9:m3 | |
def ev_MOUSEUP(self, event): | Override this method to handle a :any:`MouseUp` event. | f3166:c9:m4 | |
def ev_MOUSEMOTION(self, event): | Override this method to handle a :any:`MouseMotion` event. | f3166:c9:m5 | |
def update(self, deltaTime): | pass<EOL> | Override this method to handle per frame logic and drawing.
Args:
deltaTime (float):
This parameter tells the amount of time passed since
the last call measured in seconds as a floating point
number.
You can use this variable to make ... | f3166:c9:m6 |
def suspend(self): | self.__running = False<EOL> | When called the App will begin to return control to where
:any:`App.run` was called.
Some further events are processed and the :any:`App.update` method
will be called one last time before exiting
(unless suspended during a call to :any:`App.update`.) | f3166:c9:m7 |
def run(self): | if getattr(self, '<STR_LIT>', False):<EOL><INDENT>raise _tdl.TDLError('<STR_LIT>')<EOL><DEDENT>self.__running = True<EOL>while self.__running:<EOL><INDENT>self.runOnce()<EOL><DEDENT> | Delegate control over to this App instance. This function will
process all events and send them to the special methods ev_* and key_*.
A call to :any:`App.suspend` will return the control flow back to where
this function is called. And then the App can be run again.
But a single App i... | f3166:c9:m8 |
def run_once(self): | if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.__prevTime = _time.clock() <EOL><DEDENT>for event in get():<EOL><INDENT>if event.type: <EOL><INDENT>method = '<STR_LIT>' % event.type <EOL>getattr(self, method)(event)<EOL><DEDENT>if event.type == '<STR_LIT>':<EOL><INDENT>method = '<STR_LIT>' % event.key <EOL>if hasat... | Pump events to this App instance and then return.
This works in the way described in :any:`App.run` except it immediately
returns after the first :any:`update` call.
Having multiple :any:`App` instances and selectively calling runOnce on
them is a decent way to create a state machine. | f3166:c9:m9 |
def __init__(self, data, bbox): | if verbose:<EOL><INDENT>print(data)<EOL><DEDENT>self.encoding = int(re.search('<STR_LIT>', data).groups()[<NUM_LIT:0>])<EOL>if self.encoding < <NUM_LIT:0>:<EOL><INDENT>self.encoding += <NUM_LIT> <EOL><DEDENT>match = re.search('<STR_LIT>', data)<EOL>if match:<EOL><INDENT>gbbox = [int(i) for i in match.groups()]<EOL><DED... | Make a new glyph with the data between STARTCHAR and ENDCHAR | f3167:c0:m0 |
def sizeAdjust(self): | font_width, font_height = self.font_bbox[:<NUM_LIT:2>]<EOL>self.width = min(self.width, font_width)<EOL>self.height = min(self.height, font_height)<EOL>self.bbox[:<NUM_LIT:2>] = self.width, self.height<EOL>self.crop()<EOL> | If the glyph is bigger than the font (because the user set it smaller)
this should be able to shorten the size | f3167:c0:m1 |
def blit(self, image, x, y): | <EOL>x += self.font_bbox[<NUM_LIT:2>] - self.bbox[<NUM_LIT:2>]<EOL>y += self.font_bbox[<NUM_LIT:3>] - self.bbox[<NUM_LIT:3>]<EOL>x += self.font_bbox[<NUM_LIT:0>] - self.bbox[<NUM_LIT:0>]<EOL>y += self.font_bbox[<NUM_LIT:1>] - self.bbox[<NUM_LIT:1>]<EOL>image[y:y+self.height, x:x+self.width] = self.bitmap * <NUM_LIT:255... | blit to the image array | f3167:c0:m4 |
def parseBits(self, hexcode, width): | bitarray = []<EOL>for byte in hexcode[::-<NUM_LIT:1>]:<EOL><INDENT>bits = int(byte, <NUM_LIT:16>)<EOL>for x in range(<NUM_LIT:4>):<EOL><INDENT>bitarray.append(bool((<NUM_LIT:2> ** x) & bits))<EOL><DEDENT><DEDENT>bitarray = bitarray[::-<NUM_LIT:1>]<EOL>return enumerate(bitarray[:width])<EOL> | enumerate over bits in a line of data | f3167:c0:m5 |
def seen_nonce(id, nonce, timestamp): | key = '<STR_LIT>'.format(id=id, n=nonce, ts=timestamp)<EOL>if cache.get(key):<EOL><INDENT>log.warning('<STR_LIT>'<EOL>.format(k=key))<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>'.format(k=key))<EOL>cache.set(key, True,<EOL>timeout=getattr(settings, '<STR_LIT>',<EOL>default_message_expiration) + <... | Returns True if the Hawk nonce has been seen already. | f3178:m2 |
def __init__(self, word, acc): | self.word = self.__work_word = word.lower().strip()<EOL>if not self.word:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>_sylls = self.get_sylls()<EOL>if not _sylls:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.acc = int(acc)<EOL>if not (<NUM_LIT:0> < self.acc <= _sylls):<EOL><INDENT>raise Exception(... | :word: Слово для разбора.
:acc: Номер ударного слога. | f3184:c0:m0 |
def __init__(self, letter, prev_letter=None, shock=False): | if prev_letter is not None:<EOL><INDENT>if not isinstance(prev_letter, self.__class__):<EOL><INDENT>raise Exception(<EOL>(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(self.__class__, prev_letter.__class__)<EOL>)<EOL><DEDENT><DEDENT>self.__letter = letter.lower().strip()<EOL>self.__prev_letter = prev_letter<EOL>if len(... | :letter:
Сама буква.
:prev_letter:
Предыдущая буква в слове, если есть.
:shock:
Если гласная, то ударная ли. | f3184:c1:m0 |
def set_prev_sonorus(self): | prev = self.get_prev_letter()<EOL>if not prev:<EOL><INDENT>return<EOL><DEDENT>if not (self.is_consonant() and prev.is_consonant()):<EOL><INDENT>return<EOL><DEDENT>if self.is_sonorus() and self.is_paired_consonant():<EOL><INDENT>if self._get_sound(False) != '<STR_LIT>':<EOL><INDENT>prev.set_sonorus(True)<EOL><DEDENT>ret... | Выставляет параметры звонкости/глухости, для предыдущих согласных. | f3184:c1:m2 |
def set_prev_hard(self): | prev = self.get_prev_letter()<EOL>if not prev:<EOL><INDENT>return<EOL><DEDENT>if not prev.is_consonant():<EOL><INDENT>return<EOL><DEDENT>if self.is_softener(prev):<EOL><INDENT>prev.set_hard(False)<EOL><DEDENT>elif self.letter in self.vovels_set_hard:<EOL><INDENT>prev.set_hard(True)<EOL><DEDENT> | Выставляет параметры твёрдости/мягкости, для предыдущих согласных. | f3184:c1:m3 |
def is_after_acc(self): | prev = self._prev_letter()<EOL>while True:<EOL><INDENT>if not prev:<EOL><INDENT>return False<EOL><DEDENT>if prev.is_shock():<EOL><INDENT>return True<EOL><DEDENT>prev = prev._prev_letter()<EOL><DEDENT> | Буква распологается после ударения. | f3184:c1:m4 |
def get_prev_letter(self): | prev = self._prev_letter()<EOL>while True:<EOL><INDENT>if not prev:<EOL><INDENT>return prev<EOL><DEDENT>if prev.letter in prev.marks:<EOL><INDENT>prev = prev._prev_letter()<EOL>continue<EOL><DEDENT>return prev<EOL><DEDENT> | Возвращает предыдущий объект буквы, если она не является знаком.
Если знак, то рекурсивно спускается, до ближайшей. | f3184:c1:m11 |
def _prev_letter(self): | return self.__prev_letter<EOL> | Возвращает предыдущую букву, без особых указаний. | f3184:c1:m12 |
def get_variant(self, return_deaf): | return_deaf = bool(return_deaf)<EOL>for variants in self.sonorus_deaf_pairs:<EOL><INDENT>if self.__letter in variants:<EOL><INDENT>return variants[return_deaf]<EOL><DEDENT><DEDENT>return self.__letter<EOL> | Возвращает вариант буквы.
:return_deaf:
True - вернуть глухой вариант. Если False - звонкий. | f3184:c1:m13 |
def is_paired_consonant(self): | if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>for variants in self.sonorus_deaf_pairs:<EOL><INDENT>if self.letter in variants:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Парная ли согласная. | f3184:c1:m14 |
def is_sonorus(self): | if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.forever_sonorus:<EOL><INDENT>return True<EOL><DEDENT>if self.letter in self.forever_deaf:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus:<EOL><INDENT>return True<EOL><DEDENT>if self.__forsed_sonorus is False:<EOL><IND... | Звонкая ли согласная. | f3184:c1:m15 |
def is_deaf(self): | if not self.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.forever_deaf:<EOL><INDENT>return True<EOL><DEDENT>if self.letter in self.forever_sonorus:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus:<EOL><INDENT>return False<EOL><DEDENT>if self.__forsed_sonorus is False:<EOL><IN... | Глухая ли согласная. | f3184:c1:m16 |
def end(self, string): | prev = self._prev_letter()<EOL>for s in reversed(string):<EOL><INDENT>if prev.letter != s:<EOL><INDENT>return False<EOL><DEDENT>if not prev:<EOL><INDENT>return False<EOL><DEDENT>prev = prev._prev_letter()<EOL><DEDENT>return True<EOL> | Проверяет, заканчивается ли последовательность букв переданной строкой.
Скан производится, без учёта текущей. | f3184:c1:m19 |
def is_softener(self, let): | if let.letter in let.forever_hard:<EOL><INDENT>return False<EOL><DEDENT>if not let.is_consonant():<EOL><INDENT>return False<EOL><DEDENT>if self.letter in self.vovels_set_soft:<EOL><INDENT>return True<EOL><DEDENT>if self.letter == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>if self.is_soft() and (let.letter in "<ST... | Является ли символ смягчающим.
:let: Объект буквы, которую пытаемся смягчить. | f3184:c1:m20 |
def encrypt(data, key): | data = __tobytes(data)<EOL>data_len = len(data)<EOL>data = ffi.from_buffer(data)<EOL>key = ffi.from_buffer(__tobytes(key))<EOL>out_len = ffi.new('<STR_LIT>')<EOL>result = lib.xxtea_encrypt(data, data_len, key, out_len)<EOL>ret = ffi.buffer(result, out_len[<NUM_LIT:0>])[:]<EOL>lib.free(result)<EOL>return ret<EOL> | encrypt the data with the key | f3188:m0 |
def decrypt(data, key): | data_len = len(data)<EOL>data = ffi.from_buffer(data)<EOL>key = ffi.from_buffer(__tobytes(key))<EOL>out_len = ffi.new('<STR_LIT>')<EOL>result = lib.xxtea_decrypt(data, data_len, key, out_len)<EOL>ret = ffi.buffer(result, out_len[<NUM_LIT:0>])[:]<EOL>lib.free(result)<EOL>return ret<EOL> | decrypt the data with the key | f3188:m1 |
def decrypt_utf8(data, key): | return decrypt(data, key).decode('<STR_LIT:utf-8>')<EOL> | decrypt the data with the key to string | f3188:m2 |
def eq(self, lilypond, answer): | result = parse(lilypond)<EOL>self.assertEqual(len(answer), len(result))<EOL>for i, event in enumerate(answer):<EOL><INDENT>r = result[i].tuple(OFFSET_64, MIDI_PITCH, DURATION_64)<EOL>self.assertEqual(event, r)<EOL><DEDENT> | The first is a lilypond fragment. The second is
the intended interpretation, a sequence of (offset, pitch, duration) tuples
where offset and duration are in multiples of a 64th note and pitch is MIDI
note number. | f3195:c0:m0 |
def alberti(triad): | return HSeq(triad[i] for i in [<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>])<EOL> | takes a VSeq of 3 notes and returns an HSeq of those notes in an
alberti figuration. | f3197:m0 |
@transform_sequence<EOL>def arpeggio(pattern, point): | point['<STR_LIT>'] = HSeq(point['<STR_LIT>'][i] for i in pattern)<EOL>return point<EOL> | turns each subsequence into an arpeggio matching the given ``pattern``. | f3204:m2 |
@transform_sequence<EOL>def fill(duration, point): | point['<STR_LIT>'] = point['<STR_LIT>'] * (point[DURATION_64] / (<NUM_LIT:8> * duration)) | add({DURATION_64: duration})<EOL>return point<EOL> | fills the subsequence of the point with repetitions of its subsequence and
sets the ``duration`` of each point. | f3204:m3 |
def expand(sequence): | expanse = []<EOL>for point in sequence:<EOL><INDENT>if '<STR_LIT>' in point:<EOL><INDENT>expanse.extend(expand(point['<STR_LIT>']))<EOL><DEDENT>else:<EOL><INDENT>expanse.append(point)<EOL><DEDENT><DEDENT>return sequence.__class__(expanse)<EOL> | expands a tree of sequences into a single, flat sequence, recursively. | f3204:m4 |
def debug(sequence): | points = []<EOL>for i, p in enumerate(sequence):<EOL><INDENT>copy = Point(p)<EOL>copy['<STR_LIT:index>'] = i<EOL>points.append(copy)<EOL><DEDENT>return sequence.__class__(points)<EOL> | adds information to the sequence for better debugging, currently only
an index property on each point in the sequence. | f3204:m5 |
def transform_sequence(f): | @wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return lambda seq: seq.map_points(partial(f, *args, **kwargs))<EOL><DEDENT>return wrapper<EOL> | A decorator to take a function operating on a point and
turn it into a function returning a callable operating on a sequence.
The functions passed to this decorator must define a kwarg called "point",
or have point be the last positional argument | f3210:m0 |
@transform_sequence<EOL>def transpose(interval, point): | if "<STR_LIT>" in point:<EOL><INDENT>point["<STR_LIT>"] = point["<STR_LIT>"] + interval<EOL><DEDENT>return point<EOL> | Transpose a point by an interval, using the Sebastian interval system | f3210:m4 |
def subseq(start_offset=<NUM_LIT:0>, end_offset=None): | def _(sequence):<EOL><INDENT>return sequence.subseq(start_offset, end_offset)<EOL><DEDENT>return _<EOL> | Return a portion of the input sequence | f3210:m8 |
@transform_sequence<EOL>def lilypond(point): | <EOL>if "<STR_LIT>" in point:<EOL><INDENT>return point<EOL><DEDENT>pitch_string = "<STR_LIT>"<EOL>octave_string = "<STR_LIT>"<EOL>duration_string = "<STR_LIT>"<EOL>preamble = "<STR_LIT>"<EOL>dynamic_string = "<STR_LIT>"<EOL>if "<STR_LIT>" in point:<EOL><INDENT>octave = point["<STR_LIT>"]<EOL>pitch = point["<STR_LIT>"]<... | Generate lilypond representation for a point | f3210:m11 |
def dynamics(start, end=None): | def _(sequence):<EOL><INDENT>if start in _dynamic_markers_to_velocity:<EOL><INDENT>start_velocity = _dynamic_markers_to_velocity[start]<EOL>start_marker = start<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % (start, _dynamic_markers_to_velocity.keys()))<EOL><DEDENT>if end is None:<EOL><INDENT>end_velocity... | Apply dynamics to a sequence. If end is specified, it will crescendo or diminuendo linearly from start to end dynamics.
You can pass any of these strings as dynamic markers: ['pppppp', 'ppppp', 'pppp', 'ppp', 'pp', 'p', 'mp', 'mf', 'f', 'ff', 'fff', ''ffff]
Args:
start: beginning dynamic marker, if no end is spec... | f3210:m12 |
def transform(self, func): | return func(self)<EOL> | applies function to a sequence to produce a new sequence | f3212:c2:m7 |
def zip(self, other): | return self.__class__(p1 % p2 for p1, p2 in zip(self, other))<EOL> | zips two sequences unifying the corresponding points. | f3212:c2:m8 |
def display(self, format="<STR_LIT>"): | from sebastian.core.transforms import lilypond<EOL>seq = HSeq(self) | lilypond()<EOL>lily_output = write_lilypond.lily_format(seq)<EOL>if not lily_output.strip():<EOL><INDENT>return self<EOL><DEDENT>if format == "<STR_LIT>":<EOL><INDENT>suffix = "<STR_LIT>"<EOL>args = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"... | Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg" | f3212:c2:m9 |
def append(self, point): | point = Point(point)<EOL>self._elements.append(point)<EOL> | appends a copy of the given point to this sequence | f3212:c3:m0 |
def concatenate(self, next_seq): | return HSeq(self._elements + next_seq._elements)<EOL> | concatenates two sequences to produce a new sequence | f3212:c3:m1 |
def repeat(self, count): | x = HSeq()<EOL>for i in range(count):<EOL><INDENT>x = x.concatenate(self)<EOL><DEDENT>return x<EOL> | repeat sequence given number of times to produce a new sequence | f3212:c3:m2 |
def subseq(self, start_offset=<NUM_LIT:0>, end_offset=None): | from sebastian.core import DURATION_64<EOL>def subseq_iter(start_offset, end_offset):<EOL><INDENT>cur_offset = <NUM_LIT:0><EOL>for point in self._elements:<EOL><INDENT>try:<EOL><INDENT>cur_offset += point[DURATION_64]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % DURATION_64)<EOL><DEDENT>if cu... | Return a subset of the sequence
starting at start_offset (defaulting to the beginning)
ending at end_offset (None representing the end, whih is the default)
Raises ValueError if duration_64 is missing on any element | f3212:c3:m3 |
def append(self, point): | point = Point(point)<EOL>self._elements.append(point)<EOL> | appends a copy of the given point to this sequence | f3212:c4:m0 |
def merge(self, parallel_seq): | return VSeq(self._elements + parallel_seq._elements)<EOL> | combine the points in two sequences | f3212:c4:m1 |
def write_meta_info(self, byte1, byte2, data): | write_varlen(self.data, <NUM_LIT:0>) <EOL>write_byte(self.data, byte1)<EOL>write_byte(self.data, byte2)<EOL>write_varlen(self.data, len(data))<EOL>write_chars(self.data, data)<EOL> | Worker method for writing meta info | f3217:c2:m1 |
def instrument(self, inst): | self.write_meta_info(<NUM_LIT>, <NUM_LIT>, inst)<EOL> | This works, but does not affect the 'instrument' used. | f3217:c2:m2 |
def set_range(self, accel=<NUM_LIT:1>, gyro=<NUM_LIT:1>): | self.i2c_write_register(<NUM_LIT>, accel)<EOL>self.i2c_write_register(<NUM_LIT>, gyro)<EOL>self.accel_range = accel<EOL>self.gyro_range = gyro<EOL> | Set the measurement range for the accel and gyro MEMS. Higher range means less resolution.
:param accel: a RANGE_ACCEL_* constant
:param gyro: a RANGE_GYRO_* constant
:Example:
.. code-block:: python
sensor = MPU6050I2C(gateway_class_instance)
sensor.set_range... | f3219:c0:m1 |
def set_slave_bus_bypass(self, enable): | current = self.i2c_read_register(<NUM_LIT>, <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if enable:<EOL><INDENT>current |= <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>current &= <NUM_LIT><EOL><DEDENT>self.i2c_write_register(<NUM_LIT>, current)<EOL> | Put the aux i2c bus on the MPU-6050 in bypass mode, thus connecting it to the main i2c bus directly
Dont forget to use wakeup() or else the slave bus is unavailable
:param enable:
:return: | f3219:c0:m2 |
def wakeup(self): | self.i2c_write_register(<NUM_LIT>, <NUM_LIT>)<EOL>self.awake = True<EOL> | Wake the sensor from sleep. | f3219:c0:m3 |
def sleep(self): | self.i2c_write_register(<NUM_LIT>, <NUM_LIT>)<EOL>self.awake = False<EOL> | Put the sensor back to sleep. | f3219:c0:m4 |
def temperature(self): | if not self.awake:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>raw = self.i2c_read_register(<NUM_LIT>, <NUM_LIT:2>)<EOL>raw = struct.unpack('<STR_LIT>', raw)[<NUM_LIT:0>]<EOL>return round((raw / <NUM_LIT>) + <NUM_LIT>, <NUM_LIT:2>)<EOL> | Read the value for the internal temperature sensor.
:returns: Temperature in degree celcius as float
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.temperature()
49.38 | f3219:c0:m5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.