text:
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
# Copyright (c) bpython authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

# Modified by Brandon Navra
# Notes for Windows
# Prerequsites
#  - Curses
#  - pyreadline
#
# Added
#
# - Support for running on windows command prompt
# - input from numpad keys
#
# Issues
#
# - Suspend doesn't work nor does detection of resizing of screen
# - Instead the suspend key exits the program
# - View source doesn't work on windows unless you install the less program (From GnuUtils or Cygwin)

from __future__ import absolute_import
from __future__ import division, with_statement

import platform
import os
import sys
import curses
import math
import re
import time

import struct
if platform.system() != 'Windows':
    import signal  # Windows does not have job control
    import termios  # Windows uses curses
    import fcntl  # Windows uses curses
import unicodedata
import errno

import locale
from types import ModuleType

# These are used for syntax highlighting
from pygments import format
from pygments.formatters import TerminalFormatter
from pygments.lexers import PythonLexer
from bpython.formatter import BPythonFormatter

# This for completion
from bpython import importcompletion

# This for config
from bpython.config import Struct

# This for keys
from bpython.keys import cli_key_dispatch as key_dispatch

# This for i18n
from bpython import translations
from bpython.translations import _

from bpython import repl
from bpython._py3compat import py3
from bpython.pager import page
from bpython import autocomplete
import bpython.args

if not py3:
    import inspect

try:
    unicode
except NameError:
    unicode = str

# --- module globals ---
stdscr = None
colors = None

DO_RESIZE = False
# ---

def getpreferredencoding():
    return locale.getpreferredencoding() or sys.getdefaultencoding()

class FakeStream(object):

    """Provide a fake file object which calls functions on the interface
    provided."""

    def __init__(self, interface):
        self.encoding = getpreferredencoding()
        self.interface = interface

    def write(self, s):
        self.interface.write(s)

    def writelines(self, l):
        for s in l:
            self.write(s)

    def isatty(self):
        # some third party (amongst them mercurial) depend on this
        return True

class FakeStdin(object):

    """Provide a fake stdin type for things like raw_input() etc."""

    def __init__(self, interface):
        """Take the curses Repl on init and assume it provides a get_key method
        which, fortunately, it does."""

        self.encoding = getpreferredencoding()
        self.interface = interface
        self.buffer = list()

    def __iter__(self):
        return iter(self.readlines())

    def flush(self):
        """Flush the internal buffer.

        This is a no-op. Flushing stdin
        doesn't make any sense anyway.

        """

    def write(self, value):
        # XXX IPython expects sys.stdin.write to exist, there will no doubt be
        # others, so here's a hack to keep them happy
        raise IOError(errno.EBADF, 'sys.stdin is read-only')

    def isatty(self):
        return True

    def readline(self, size=-1):
        """I can't think of any reason why anything other than readline would
        be useful in the context of an interactive interpreter so this is the
        only one I've done anything with.

        The others are just there in case someone does something weird
        to stop it from blowing up.

        """

        if not size:
            return ''
        elif self.buffer:
            buffer = self.buffer.pop(0)
        else:
            buffer = ''

        curses.raw(True)
        try:
            while not buffer.endswith(('\n', '\r')):
                key = self.interface.get_key()
                if key in [curses.erasechar(), 'KEY_BACKSPACE']:
                    y, x = self.interface.scr.getyx()
                    if buffer:
                        self.interface.scr.delch(y, x - 1)
                        buffer = buffer[:-1]
                    continue
                elif key == chr(4) and not buffer:
                    # C-d
                    return ''
                elif (key not in ('\n', '\r') and
                     (len(key) > 1 or unicodedata.category(key) == 'Cc')):
                    continue
                sys.stdout.write(key)
                # Include the \n in the buffer - raw_input() seems to deal with trailing
                # linebreaks and will break if it gets an empty string.
                buffer += key
        finally:
            curses.raw(False)

        if size > 0:
            rest = buffer[size:]
            if rest:
                self.buffer.append(rest)
            buffer = buffer[:size]

        if py3:
            return buffer
        else:
            return buffer.encode(getpreferredencoding())

    def read(self, size=None):
        if size == 0:
            return ''

        data = list()
        while size is None or size > 0:
            line = self.readline(size or -1)
            if not line:
                break
            if size is not None:
                size -= len(line)
            data.append(line)

        return ''.join(data)

    def readlines(self, size=-1):
        return list(iter(self.readline, ''))

# TODO:
#
# Tab completion does not work if not at the end of the line.
#
# Numerous optimisations can be made but it seems to do all the lookup stuff
# fast enough on even my crappy server so I'm not too bothered about that
# at the moment.
#
# The popup window that displays the argspecs and completion suggestions
# needs to be an instance of a ListWin class or something so I can wrap
# the addstr stuff to a higher level.
#

def get_color(config, name):
    global colors
    return colors[config.color_scheme[name].lower()]

def get_colpair(config, name):
    return curses.color_pair(get_color(config, name) + 1)

def make_colors(config):
    """Init all the colours in curses and bang them into a dictionary."""

    # blacK, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default:
    c = {
        'k': 0,
        'r': 1,
        'g': 2,
        'y': 3,
        'b': 4,
        'm': 5,
        'c': 6,
        'w': 7,
        'd': -1,
    }

    if platform.system() == 'Windows':
        c = dict(c.items() +
                 [
                     ('K', 8),
                     ('R', 9),
                     ('G', 10),
                     ('Y', 11),
                     ('B', 12),
                     ('M', 13),
                     ('C', 14),
                     ('W', 15),
                 ]
                 )

    for i in range(63):
        if i > 7:
            j = i // 8
        else:
            j = c[config.color_scheme['background']]
        curses.init_pair(i + 1, i % 8, j)

    return c

class CLIInteraction(repl.Interaction):

    def __init__(self, config, statusbar=None):
        repl.Interaction.__init__(self, config, statusbar)

    def confirm(self, q):
        """Ask for yes or no and return boolean."""
        try:
            reply = self.statusbar.prompt(q)
        except ValueError:
            return False

        return reply.lower() in (_('y'), _('yes'))

    def notify(self, s, n=10):
        return self.statusbar.message(s, n)

    def file_prompt(self, s):
        return self.statusbar.prompt(s)

class CLIRepl(repl.Repl):

    def __init__(self, scr, interp, statusbar, config, idle=None):
        repl.Repl.__init__(self, interp, config)
        self.interp.writetb = self.writetb
        self.scr = scr
        self.stdout_hist = ''
        self.list_win = newwin(get_colpair(config, 'background'), 1, 1, 1, 1)
        self.cpos = 0
        self.do_exit = False
        self.exit_value = ()
        self.f_string = ''
        self.idle = idle
        self.in_hist = False
        self.paste_mode = False
        self.last_key_press = time.time()
        self.s = ''
        self.statusbar = statusbar
        self.formatter = BPythonFormatter(config.color_scheme)
        self.interact = CLIInteraction(self.config, statusbar=self.statusbar)

        if config.cli_suggestion_width <= 0 or config.cli_suggestion_width > 1:
            config.cli_suggestion_width = 0.8

    def addstr(self, s):
        """Add a string to the current input line and figure out where it
        should go, depending on the cursor position."""
        self.rl_history.reset()
        if not self.cpos:
            self.s += s
        else:
            l = len(self.s)
            self.s = self.s[:l - self.cpos] + s + self.s[l - self.cpos:]

        self.complete()

    def atbol(self):
        """Return True or False accordingly if the cursor is at the beginning
        of the line (whitespace is ignored). This exists so that p_key() knows.

        how to handle the tab key being pressed - if there is nothing but white
        space before the cursor then process it as a normal tab otherwise
        attempt tab completion.

        """

        return not self.s.lstrip()

    def bs(self, delete_tabs=True):
        """Process a backspace."""

        self.rl_history.reset()
        y, x = self.scr.getyx()

        if not self.s:
            return

        if x == self.ix and y == self.iy:
            return

        n = 1

        self.clear_wrapped_lines()

        if not self.cpos:
            # I know the nested if blocks look nasty. :(
            if self.atbol() and delete_tabs:
                n = len(self.s) % self.config.tab_length
                if not n:
                    n = self.config.tab_length

            self.s = self.s[:-n]
        else:
            self.s = self.s[:-self.cpos - 1] + self.s[-self.cpos:]

        self.print_line(self.s, clr=True)

        return n

    def bs_word(self):
        self.rl_history.reset()
        pos = len(self.s) - self.cpos - 1
        deleted = []
        # First we delete any space to the left of the cursor.
        while pos >= 0 and self.s[pos] == ' ':
            deleted.append(self.s[pos])
            pos -= self.bs()
        # Then we delete a full word.
        while pos >= 0 and self.s[pos] != ' ':
            deleted.append(self.s[pos])
            pos -= self.bs()

        return ''.join(reversed(deleted))

    def check(self):
        """Check if paste mode should still be active and, if not, deactivate
        it and force syntax highlighting."""

        if (self.paste_mode
            and time.time() - self.last_key_press > self.config.paste_time):
            self.paste_mode = False
            self.print_line(self.s)

    def clear_current_line(self):
        """Called when a SyntaxError occurred in the interpreter.

        It is used to prevent autoindentation from occurring after a
        traceback.

        """
        repl.Repl.clear_current_line(self)
        self.s = ''

    def clear_wrapped_lines(self):
        """Clear the wrapped lines of the current input."""
        # curses does not handle this on its own. Sad.
        height, width = self.scr.getmaxyx()
        max_y = min(self.iy + (self.ix + len(self.s)) // width + 1, height)
        for y in range(self.iy + 1, max_y):
            self.scr.move(y, 0)
            self.scr.clrtoeol()

    def complete(self, tab=False):
        """Get Autcomplete list and window."""
        if self.paste_mode and self.list_win_visible:
            self.scr.touchwin()

        if self.paste_mode:
            return

        if self.list_win_visible and not self.config.auto_display_list:
            self.scr.touchwin()
            self.list_win_visible = False
            self.matches_iter.update()
            return

        if self.config.auto_display_list or tab:
            self.list_win_visible = repl.Repl.complete(self, tab)
            if self.list_win_visible:
                try:
                    self.show_list(self.matches, self.argspec)
                except curses.error:
                    # XXX: This is a massive hack, it will go away when I get
                    # cusswords into a good enough state that we can start
                    # using it.
                    self.list_win.border()
                    self.list_win.refresh()
                    self.list_win_visible = False
            if not self.list_win_visible:
                self.scr.redrawwin()
                self.scr.refresh()

    def clrtobol(self):
        """Clear from cursor to beginning of line; usual C-u behaviour"""
        self.clear_wrapped_lines()

        if not self.cpos:
            self.s = ''
        else:
            self.s = self.s[-self.cpos:]

        self.print_line(self.s, clr=True)
        self.scr.redrawwin()
        self.scr.refresh()

    def current_line(self):
        """Return the current line."""
        return self.s

    def cut_to_buffer(self):
        """Clear from cursor to end of line, placing into cut buffer."""
        self.cut_buffer = self.s[-self.cpos:]
        self.s = self.s[:-self.cpos]
        self.cpos = 0
        self.print_line(self.s, clr=True)
        self.scr.redrawwin()
        self.scr.refresh()

    def cw(self):
        """Return the current word, i.e. the (incomplete) word directly to the
        left of the cursor."""

        # I don't know if autocomplete should be disabled if the cursor
        # isn't at the end of the line, but that's what this does for now.
        if self.cpos:
            return

        # look from right to left for a bad method character
        l = len(self.s)
        is_method_char = lambda c: c.isalnum() or c in ('.', '_')

        if not self.s or not is_method_char(self.s[l - 1]):
            return

        for i in range(1, l + 1):
            if not is_method_char(self.s[-i]):
                i -= 1
                break

        return self.s[-i:]

    def delete(self):
        """Process a del."""
        if not self.s:
            return

        if self.mvc(-1):
            self.bs(False)

    def echo(self, s, redraw=True):
        """Parse and echo a formatted string with appropriate attributes.

        It uses the formatting method as defined in formatter.py to
        parse the srings. It won't update the screen if it's
        reevaluating the code (as it does with undo).

        """
        if not py3 and isinstance(s, unicode):
            s = s.encode(getpreferredencoding())

        a = get_colpair(self.config, 'output')
        if '\x01' in s:
            rx = re.search('\x01([A-Za-z])([A-Za-z]?)', s)
            if rx:
                fg = rx.groups()[0]
                bg = rx.groups()[1]
                col_num = self._C[fg.lower()]
                if bg and bg != 'I':
                    col_num *= self._C[bg.lower()]

                a = curses.color_pair(int(col_num) + 1)
                if bg == 'I':
                    a = a | curses.A_REVERSE
                s = re.sub('\x01[A-Za-z][A-Za-z]?', '', s)
                if fg.isupper():
                    a = a | curses.A_BOLD
        s = s.replace('\x03', '')
        s = s.replace('\x01', '')

        # Replace NUL bytes, as addstr raises an exception otherwise
        s = s.replace('\0', '')
        # Replace \r\n bytes, as addstr remove the current line otherwise
        s = s.replace('\r\n', '\n')

        self.scr.addstr(s, a)

        if redraw and not self.evaluating:
            self.scr.refresh()

    def end(self, refresh=True):
        self.cpos = 0
        h, w = gethw()
        y, x = divmod(len(self.s) + self.ix, w)
        y += self.iy
        self.scr.move(y, x)
        if refresh:
            self.scr.refresh()

        return True

    def hbegin(self):
        """Replace the active line with first line in history and increment the
        index to keep track."""
        self.cpos = 0
        self.clear_wrapped_lines()
        self.rl_history.enter(self.s)
        self.s = self.rl_history.first()
        self.print_line(self.s, clr=True)

    def hend(self):
        """Same as hbegin() but, well, forward."""
        self.cpos = 0
        self.clear_wrapped_lines()
        self.rl_history.enter(self.s)
        self.s = self.rl_history.last()
        self.print_line(self.s, clr=True)

    def back(self):
        """Replace the active line with previous line in history and increment
        the index to keep track."""

        self.cpos = 0
        self.clear_wrapped_lines()
        self.rl_history.enter(self.s)
        self.s = self.rl_history.back()
        self.print_line(self.s, clr=True)

    def fwd(self):
        """Same as back() but, well, forward."""

        self.cpos = 0
        self.clear_wrapped_lines()
        self.rl_history.enter(self.s)
        self.s = self.rl_history.forward()
        self.print_line(self.s, clr=True)

    def search(self):
        """Search with the partial matches from the history object."""

        self.cpo = 0
        self.clear_wrapped_lines()
        self.rl_history.enter(self.s)
        self.s = self.rl_history.back(start=False, search=True)
        self.print_line(self.s, clr=True)

    def get_key(self):
        key = ''
        while True:
            try:
                key += self.scr.getkey()
                if py3:
                    # Seems like we get a in the locale's encoding
                    # encoded string in Python 3 as well, but of
                    # type str instead of bytes, hence convert it to
                    # bytes first and decode then
                    key = key.encode('latin-1').decode(getpreferredencoding())
                else:
                    key = key.decode(getpreferredencoding())
                self.scr.nodelay(False)
            except UnicodeDecodeError:
                # Yes, that actually kind of sucks, but I don't see another way to get
                # input right
                self.scr.nodelay(True)
            except curses.error:
                # I'm quite annoyed with the ambiguity of this exception handler. I previously
                # caught "curses.error, x" and accessed x.message and checked that it was "no
                # input", which seemed a crappy way of doing it. But then I ran it on a
                # different computer and the exception seems to have entirely different
                # attributes. So let's hope getkey() doesn't raise any other crazy curses
                # exceptions. :)
                self.scr.nodelay(False)
                # XXX What to do here? Raise an exception?
                if key:
                    return key
            else:
                if key != '\x00':
                    t = time.time()
                    self.paste_mode = (
                        t - self.last_key_press <= self.config.paste_time
                    )
                    self.last_key_press = t
                    return key
                else:
                    key = ''
            finally:
                if self.idle:
                    self.idle(self)

    def get_line(self):
        """Get a line of text and return it This function initialises an empty
        string and gets the curses cursor position on the screen and stores it
        for the echo() function to use later (I think).

        Then it waits for key presses and passes them to p_key(), which
        returns None if Enter is pressed (that means "Return", idiot).

        """

        self.s = ''
        self.rl_history.reset()
        self.iy, self.ix = self.scr.getyx()

        if not self.paste_mode:
            for _ in range(self.next_indentation()):
                self.p_key('\t')

        self.cpos = 0

        while True:
            key = self.get_key()
            if self.p_key(key) is None:
                if self.config.cli_trim_prompts and self.s.startswith('>>> '):
                    self.s = self.s[4:]
                return self.s

    def home(self, refresh=True):
        self.scr.move(self.iy, self.ix)
        self.cpos = len(self.s)
        if refresh:
            self.scr.refresh()
        return True

    def lf(self):
        """Process a linefeed character; it only needs to check the cursor
        position and move appropriately so it doesn't clear the current line
        after the cursor."""
        if self.cpos:
            for _ in range(self.cpos):
                self.mvc(-1)

        # Reprint the line (as there was maybe a highlighted paren in it)
        self.print_line(self.s, newline=True)
        self.echo('\n')

    def mkargspec(self, topline, down):
        """This figures out what to do with the argspec and puts it nicely into
        the list window.

        It returns the number of lines used to display the argspec.
        It's also kind of messy due to it having to call so many
        addstr() to get the colouring right, but it seems to be pretty
        sturdy.

        """

        r = 3
        fn = topline[0]
        args = topline[1][0]
        kwargs = topline[1][3]
        _args = topline[1][1]
        _kwargs = topline[1][2]
        is_bound_method = topline[2]
        in_arg = topline[3]
        if py3:
            kwonly = topline[1][4]
            kwonly_defaults = topline[1][5] or dict()
        max_w = int(self.scr.getmaxyx()[1] * 0.6)
        self.list_win.erase()
        self.list_win.resize(3, max_w)
        h, w = self.list_win.getmaxyx()

        self.list_win.addstr('\n  ')
        self.list_win.addstr(fn,
                             get_colpair(self.config, 'name') | curses.A_BOLD)
        self.list_win.addstr(': (', get_colpair(self.config, 'name'))
        maxh = self.scr.getmaxyx()[0]

        if is_bound_method and isinstance(in_arg, int):
            in_arg += 1

        punctuation_colpair = get_colpair(self.config, 'punctuation')

        for k, i in enumerate(args):
            y, x = self.list_win.getyx()
            ln = len(str(i))
            kw = None
            if kwargs and k + 1 > len(args) - len(kwargs):
                kw = repr(kwargs[k - (len(args) - len(kwargs))])
                ln += len(kw) + 1

            if ln + x >= w:
                ty = self.list_win.getbegyx()[0]
                if not down and ty > 0:
                    h += 1
                    self.list_win.mvwin(ty - 1, 1)
                    self.list_win.resize(h, w)
                elif down and h + r < maxh - ty:
                    h += 1
                    self.list_win.resize(h, w)
                else:
                    break
                r += 1
                self.list_win.addstr('\n\t')

            if str(i) == 'self' and k == 0:
                color = get_colpair(self.config, 'name')
            else:
                color = get_colpair(self.config, 'token')

            if k == in_arg or i == in_arg:
                color |= curses.A_BOLD

            if not py3:
                # See issue #138: We need to format tuple unpacking correctly
                # We use the undocumented function inspection.strseq() for
                # that. Fortunately, that madness is gone in Python 3.
                self.list_win.addstr(inspect.strseq(i, str), color)
            else:
                self.list_win.addstr(str(i), color)
            if kw is not None:
                self.list_win.addstr('=', punctuation_colpair)
                self.list_win.addstr(kw, get_colpair(self.config, 'token'))
            if k != len(args) - 1:
                self.list_win.addstr(', ', punctuation_colpair)

        if _args:
            if args:
                self.list_win.addstr(', ', punctuation_colpair)
            self.list_win.addstr('*%s' % (_args, ),
                                 get_colpair(self.config, 'token'))

        if py3 and kwonly:
            if not _args:
                if args:
                    self.list_win.addstr(', ', punctuation_colpair)
                self.list_win.addstr('*', punctuation_colpair)
            marker = object()
            for arg in kwonly:
                self.list_win.addstr(', ', punctuation_colpair)
                color = get_colpair(self.config, 'token')
                if arg == in_arg:
                    color |= curses.A_BOLD
                self.list_win.addstr(arg, color)
                default = kwonly_defaults.get(arg, marker)
                if default is not marker:
                    self.list_win.addstr('=', punctuation_colpair)
                    self.list_win.addstr(repr(default),
                                         get_colpair(self.config, 'token'))

        if _kwargs:
            if args or _args or (py3 and kwonly):
                self.list_win.addstr(', ', punctuation_colpair)
            self.list_win.addstr('**%s' % (_kwargs, ),
                                 get_colpair(self.config, 'token'))
        self.list_win.addstr(')', punctuation_colpair)

        return r

    def mvc(self, i, refresh=True):
        """This method moves the cursor relatively from the current
        position, where:
            0 == (right) end of current line
            length of current line len(self.s) == beginning of current line
        and:
            current cursor position + i
            for positive values of i the cursor will move towards the beginning
            of the line, negative values the opposite."""
        y, x = self.scr.getyx()

        if self.cpos == 0 and i < 0:
            return False

        if x == self.ix and y == self.iy and i >= 1:
            return False

        h, w = gethw()
        if x - i < 0:
            y -= 1
            x = w

        if x - i >= w:
            y += 1
            x = 0 + i

        self.cpos += i
        self.scr.move(y, x - i)
        if refresh:
            self.scr.refresh()

        return True

    def p_key(self, key):
        """Process a keypress."""

        if key is None:
            return ''

        config = self.config

        if platform.system() == 'Windows':
            C_BACK = chr(127)
            BACKSP = chr(8)
        else:
            C_BACK = chr(8)
            BACKSP = chr(127)

        if key == C_BACK:  # C-Backspace (on my computer anyway!)
            self.clrtobol()
            key = '\n'
            # Don't return; let it get handled

        if key == chr(27):  # Escape Key
            return ''

        if key in (BACKSP, 'KEY_BACKSPACE'):
            self.bs()
            self.complete()
            return ''

        elif key in key_dispatch[config.delete_key] and not self.s:
            # Delete on empty line exits
            self.do_exit = True
            return None

        elif key in ('KEY_DC', ) + key_dispatch[config.delete_key]:
            self.delete()
            self.complete()
            # Redraw (as there might have been highlighted parens)
            self.print_line(self.s)
            return ''

        elif key in key_dispatch[config.undo_key]:  # C-r
            self.undo()
            return ''

        elif key in key_dispatch[config.search_key]:
            self.search()
            return ''

        elif key in ('KEY_UP', ) + key_dispatch[config.up_one_line_key]:
            # Cursor Up/C-p
            self.back()
            return ''

        elif key in ('KEY_DOWN', ) + key_dispatch[config.down_one_line_key]:
            # Cursor Down/C-n
            self.fwd()
            return ''

        elif key in ('KEY_LEFT', ' ^B', chr(2)):  # Cursor Left or ^B
            self.mvc(1)
            # Redraw (as there might have been highlighted parens)
            self.print_line(self.s)

        elif key in ('KEY_RIGHT', '^F', chr(6)):  # Cursor Right or ^F
            self.mvc(-1)
            # Redraw (as there might have been highlighted parens)
            self.print_line(self.s)

        elif key in ('KEY_HOME', '^A', chr(1)):  # home or ^A
            self.home()
            # Redraw (as there might have been highlighted parens)
            self.print_line(self.s)

        elif key in ('KEY_END', '^E', chr(5)):  # end or ^E
            self.end()
            # Redraw (as there might have been highlighted parens)
            self.print_line(self.s)

        elif key in ('KEY_NPAGE', '\T'):  # page_down or \T
            self.hend()
            self.print_line(self.s)

        elif key in ('KEY_PPAGE', '\S'):  # page_up or \S
            self.hbegin()
            self.print_line(self.s)

        elif key in key_dispatch[config.cut_to_buffer_key]:  # cut to buffer
            self.cut_to_buffer()
            return ''

        elif key in key_dispatch[config.yank_from_buffer_key]:
            # yank from buffer
            self.yank_from_buffer()
            return ''

        elif key in key_dispatch[config.clear_word_key]:
            self.cut_buffer = self.bs_word()
            self.complete()
            return ''

        elif key in key_dispatch[config.clear_line_key]:
            self.clrtobol()
            return ''

        elif key in key_dispatch[config.clear_screen_key]:
            self.s_hist = [self.s_hist[-1]]
            self.highlighted_paren = None
            self.redraw()
            return ''

        elif key in key_dispatch[config.exit_key]:
            if not self.s:
                self.do_exit = True
                return None
            else:
                return ''

        elif key in key_dispatch[config.save_key]:
            self.write2file()
            return ''

        elif key in key_dispatch[config.pastebin_key]:
            self.pastebin()
            return ''

        elif key in key_dispatch[config.last_output_key]:
            page(self.stdout_hist[self.prev_block_finished:-4])
            return ''

        elif key in key_dispatch[config.show_source_key]:
            source = self.get_source_of_current_name()
            if source is not None:
                if config.highlight_show_source:
                    source = format(PythonLexer().get_tokens(source),
                                    TerminalFormatter())
                page(source)
            else:
                self.statusbar.message(_('Cannot show source.'))
            return ''

        elif key in ('\n', '\r', 'PADENTER'):
            self.lf()
            return None

        elif key == '\t':
            return self.tab()

        elif key == 'KEY_BTAB':
            return self.tab(back=True)

        elif key in key_dispatch[config.suspend_key]:
            if platform.system() != 'Windows':
                self.suspend()
                return ''
            else:
                self.do_exit = True
                return None

        elif key[0:3] == 'PAD' and not key in ('PAD0', 'PADSTOP'):
            pad_keys = {
                'PADMINUS': '-',
                'PADPLUS': '+',
                'PADSLASH': '/',
                'PADSTAR': '*',
            }
            try:
                self.addstr(pad_keys[key])
                self.print_line(self.s)
            except KeyError:
                return ''
        elif len(key) == 1 and not unicodedata.category(key) == 'Cc':
            self.addstr(key)
            self.print_line(self.s)

        else:
            return ''

        return True

    def print_line(self, s, clr=False, newline=False):
        """Chuck a line of text through the highlighter, move the cursor to the
        beginning of the line and output it to the screen."""

        if not s:
            clr = True

        if self.highlighted_paren is not None:
            # Clear previous highlighted paren
            self.reprint_line(*self.highlighted_paren)
            self.highlighted_paren = None

        if self.config.syntax and (not self.paste_mode or newline):
            o = format(self.tokenize(s, newline), self.formatter)
        else:
            o = s

        self.f_string = o
        self.scr.move(self.iy, self.ix)

        if clr:
            self.scr.clrtoeol()

        if clr and not s:
            self.scr.refresh()

        if o:
            for t in o.split('\x04'):
                self.echo(t.rstrip('\n'))

        if self.cpos:
            t = self.cpos
            for _ in range(self.cpos):
                self.mvc(1)
            self.cpos = t

    def prompt(self, more):
        """Show the appropriate Python prompt."""
        if not more:
            self.echo(
                '\x01%s\x03%s' %
                (self.config.color_scheme['prompt'], self.ps1))
            self.stdout_hist += self.ps1
            self.s_hist.append('\x01%s\x03%s\x04' %
                               (self.config.color_scheme['prompt'], self.ps1))
        else:
            prompt_more_color = self.config.color_scheme['prompt_more']
            self.echo('\x01%s\x03%s' % (prompt_more_color, self.ps2))
            self.stdout_hist += self.ps2
            self.s_hist.append(
                '\x01%s\x03%s\x04' %
                (prompt_more_color, self.ps2))

    def push(self, s, insert_into_history=True):
        # curses.raw(True) prevents C-c from causing a SIGINT
        curses.raw(False)
        try:
            return repl.Repl.push(self, s, insert_into_history)
        except SystemExit as e:
            # Avoid a traceback on e.g. quit()
            self.do_exit = True
            self.exit_value = e.args
            return False
        finally:
            curses.raw(True)

    def redraw(self):
        """Redraw the screen."""
        self.scr.erase()
        for k, s in enumerate(self.s_hist):
            if not s:
                continue
            self.iy, self.ix = self.scr.getyx()
            for i in s.split('\x04'):
                self.echo(i, redraw=False)
            if k < len(self.s_hist) - 1:
                self.scr.addstr('\n')
        self.iy, self.ix = self.scr.getyx()
        self.print_line(self.s)
        self.scr.refresh()
        self.statusbar.refresh()

    def repl(self):
        """Initialise the repl and jump into the loop.

        This method also has to keep a stack of lines entered for the
        horrible "undo" feature. It also tracks everything that would
        normally go to stdout in the normal Python interpreter so it can
        quickly write it to stdout on exit after curses.endwin(), as
        well as a history of lines entered for using up/down to go back
        and forth (which has to be separate to the evaluation history,
        which will be truncated when undoing.

        """

        # Use our own helper function because Python's will use real stdin and
        # stdout instead of our wrapped
        self.push('from bpython._internal import _help as help\n', False)

        self.iy, self.ix = self.scr.getyx()
        more = False
        while not self.do_exit:
            self.f_string = ''
            self.prompt(more)
            try:
                inp = self.get_line()
            except KeyboardInterrupt:
                self.statusbar.message('KeyboardInterrupt')
                self.scr.addstr('\n')
                self.scr.touchwin()
                self.scr.refresh()
                continue

            self.scr.redrawwin()
            if self.do_exit:
                return self.exit_value

            self.history.append(inp)
            self.s_hist[-1] += self.f_string
            if py3:
                self.stdout_hist += inp + '\n'
            else:
                self.stdout_hist += inp.encode(getpreferredencoding()) + '\n'
            stdout_position = len(self.stdout_hist)
            more = self.push(inp)
            if not more:
                self.prev_block_finished = stdout_position
                self.s = ''
        return self.exit_value

    def reprint_line(self, lineno, tokens):
        """Helper function for paren highlighting: Reprint line at offset
        `lineno` in current input buffer."""
        if not self.buffer or lineno == len(self.buffer):
            return

        real_lineno = self.iy
        height, width = self.scr.getmaxyx()
        for i in range(lineno, len(self.buffer)):
            string = self.buffer[i]
            # 4 = length of prompt
            length = len(string.encode(getpreferredencoding())) + 4
            real_lineno -= int(math.ceil(length / width))
        if real_lineno < 0:
            return

        self.scr.move(real_lineno,
                      len(self.ps1) if lineno == 0 else len(self.ps2))
        line = format(tokens, BPythonFormatter(self.config.color_scheme))
        for string in line.split('\x04'):
            self.echo(string)

    def resize(self):
        """This method exists simply to keep it straight forward when
        initialising a window and resizing it."""
        self.size()
        self.scr.erase()
        self.scr.resize(self.h, self.w)
        self.scr.mvwin(self.y, self.x)
        self.statusbar.resize(refresh=False)
        self.redraw()

    def getstdout(self):
        """This method returns the 'spoofed' stdout buffer, for writing to a
        file or sending to a pastebin or whatever."""

        return self.stdout_hist + '\n'

    def reevaluate(self):
        """Clear the buffer, redraw the screen and re-evaluate the history"""

        self.evaluating = True
        self.stdout_hist = ''
        self.f_string = ''
        self.buffer = []
        self.scr.erase()
        self.s_hist = []
        # Set cursor position to -1 to prevent paren matching
        self.cpos = -1

        self.prompt(False)

        self.iy, self.ix = self.scr.getyx()
        for line in self.history:
            if py3:
                self.stdout_hist += line + '\n'
            else:
                self.stdout_hist += line.encode(getpreferredencoding()) + '\n'
            self.print_line(line)
            self.s_hist[-1] += self.f_string
            # I decided it was easier to just do this manually
            # than to make the print_line and history stuff more flexible.
            self.scr.addstr('\n')
            more = self.push(line)
            self.prompt(more)
            self.iy, self.ix = self.scr.getyx()

        self.cpos = 0
        indent = repl.next_indentation(self.s, self.config.tab_length)
        self.s = ''
        self.scr.refresh()

        if self.buffer:
            for _ in range(indent):
                self.tab()

        self.evaluating = False

    def write(self, s):
        """For overriding stdout defaults."""
        if '\x04' in s:
            for block in s.split('\x04'):
                self.write(block)
            return
        if s.rstrip() and '\x03' in s:
            t = s.split('\x03')[1]
        else:
            t = s

        if not py3 and isinstance(t, unicode):
            t = t.encode(getpreferredencoding())

        if not self.stdout_hist:
            self.stdout_hist = t
        else:
            self.stdout_hist += t

        self.echo(s)
        self.s_hist.append(s.rstrip())

    def show_list(self, items, topline=None, current_item=None):
        shared = Struct()
        shared.cols = 0
        shared.rows = 0
        shared.wl = 0
        y = self.scr.getyx()[0]
        h, w = self.scr.getmaxyx()
        down = (y < h // 2)
        if down:
            max_h = h - y
        else:
            max_h = y + 1
        max_w = int(w * self.config.cli_suggestion_width)
        self.list_win.erase()
        if items:
            sep = '.'
            if os.path.sep in items[0]:
                # Filename completion
                sep = os.path.sep
            if sep in items[0]:
                items = [x.rstrip(sep).rsplit(sep)[-1] for x in items]
                if current_item:
                    current_item = current_item.rstrip(sep).rsplit(sep)[-1]

        if topline:
            height_offset = self.mkargspec(topline, down) + 1
        else:
            height_offset = 0

        def lsize():
            wl = max(len(i) for i in v_items) + 1
            if not wl:
                wl = 1
            cols = ((max_w - 2) // wl) or 1
            rows = len(v_items) // cols

            if cols * rows < len(v_items):
                rows += 1

            if rows + 2 >= max_h:
                rows = max_h - 2
                return False

            shared.rows = rows
            shared.cols = cols
            shared.wl = wl
            return True

        if items:
            # visible items (we'll append until we can't fit any more in)
            v_items = [items[0][:max_w - 3]]
            lsize()
        else:
            v_items = []

        for i in items[1:]:
            v_items.append(i[:max_w - 3])
            if not lsize():
                del v_items[-1]
                v_items[-1] = '...'
                break

        rows = shared.rows
        if rows + height_offset < max_h:
            rows += height_offset
            display_rows = rows
        else:
            display_rows = rows + height_offset

        cols = shared.cols
        wl = shared.wl

        if topline and not v_items:
            w = max_w
        elif wl + 3 > max_w:
            w = max_w
        else:
            t = (cols + 1) * wl + 3
            if t > max_w:
                t = max_w
            w = t

        if height_offset and display_rows + 5 >= max_h:
            del v_items[-(cols * (height_offset)):]

        if self.docstring is None:
            self.list_win.resize(rows + 2, w)
        else:
            docstring = self.format_docstring(self.docstring, max_w - 2,
                                              max_h - height_offset)
            docstring_string = ''.join(docstring)
            rows += len(docstring)
            self.list_win.resize(rows, max_w)

        if down:
            self.list_win.mvwin(y + 1, 0)
        else:
            self.list_win.mvwin(y - rows - 2, 0)

        if v_items:
            self.list_win.addstr('\n ')

        if not py3:
            encoding = getpreferredencoding()
        for ix, i in enumerate(v_items):
            padding = (wl - len(i)) * ' '
            if i == current_item:
                color = get_colpair(self.config, 'operator')
            else:
                color = get_colpair(self.config, 'main')
            if not py3:
                i = i.encode(encoding)
            self.list_win.addstr(i + padding, color)
            if ((cols == 1 or (ix and not (ix + 1) % cols))
                    and ix + 1 < len(v_items)):
                self.list_win.addstr('\n ')

        if self.docstring is not None:
            if not py3 and isinstance(docstring_string, unicode):
                docstring_string = docstring_string.encode(encoding, 'ignore')
            self.list_win.addstr('\n' + docstring_string,
                                 get_colpair(self.config, 'comment'))
            # XXX: After all the trouble I had with sizing the list box (I'm not very good
            # at that type of thing) I decided to do this bit of tidying up here just to
            # make sure there's no unnececessary blank lines, it makes things
            # look nicer.

        y = self.list_win.getyx()[0]
        self.list_win.resize(y + 2, w)

        self.statusbar.win.touchwin()
        self.statusbar.win.noutrefresh()
        self.list_win.attron(get_colpair(self.config, 'main'))
        self.list_win.border()
        self.scr.touchwin()
        self.scr.cursyncup()
        self.scr.noutrefresh()

        # This looks a little odd, but I can't figure a better way to stick the cursor
        # back where it belongs (refreshing the window hides the list_win)

        self.scr.move(*self.scr.getyx())
        self.list_win.refresh()

    def size(self):
        """Set instance attributes for x and y top left corner coordinates and
        width and heigth for the window."""
        global stdscr
        h, w = stdscr.getmaxyx()
        self.y = 0
        self.w = w
        self.h = h - 1
        self.x = 0

    def suspend(self):
        """Suspend the current process for shell job control."""
        if platform.system() != 'Windows':
            curses.endwin()
            os.kill(os.getpid(), signal.SIGSTOP)

    def tab(self, back=False):
        """Process the tab key being hit.

        If there's only whitespace
        in the line or the line is blank then process a normal tab,
        otherwise attempt to autocomplete to the best match of possible
        choices in the match list.

        If `back` is True, walk backwards through the list of suggestions
        and don't indent if there are only whitespace in the line.

        """

        mode = self.config.autocomplete_mode

        # 1. check if we should add a tab character
        if self.atbol() and not back:
            x_pos = len(self.s) - self.cpos
            num_spaces = x_pos % self.config.tab_length
            if not num_spaces:
                num_spaces = self.config.tab_length

            self.addstr(' ' * num_spaces)
            self.print_line(self.s)
            return True

        # 2. get the current word
        if not self.matches_iter:
            self.complete(tab=True)
            if not self.config.auto_display_list and not self.list_win_visible:
                return True

            cw = self.current_string() or self.cw()
            if not cw:
                return True
        else:
            cw = self.matches_iter.current_word

        # 3. check to see if we can expand the current word
        cseq = None
        if mode == autocomplete.SUBSTRING:
            if all([len(match.split(cw)) == 2 for match in self.matches]):
                seq = [cw + match.split(cw)[1] for match in self.matches]
                cseq = os.path.commonprefix(seq)
        else:
            seq = self.matches
            cseq = os.path.commonprefix(seq)

        if cseq and mode != autocomplete.FUZZY:
            expanded_string = cseq[len(cw):]
            self.s += expanded_string
            expanded = bool(expanded_string)
            self.print_line(self.s)
            if len(self.matches) == 1 and self.config.auto_display_list:
                self.scr.touchwin()
            if expanded:
                self.matches_iter.update(cseq, self.matches)
        else:
            expanded = False

        # 4. swap current word for a match list item
        if not expanded and self.matches:
            # reset s if this is the nth result
            if self.matches_iter:
                self.s = self.s[:-len(self.matches_iter.current())] + cw

            current_match = back and self.matches_iter.previous() \
                or next(self.matches_iter)

            # update s with the new match
            if current_match:
                try:
                    self.show_list(self.matches, self.argspec, current_match)
                except curses.error:
                    # XXX: This is a massive hack, it will go away when I get
                    # cusswords into a good enough state that we can start
                    # using it.
                    self.list_win.border()
                    self.list_win.refresh()

                if self.config.autocomplete_mode == autocomplete.SIMPLE:
                    self.s += current_match[len(cw):]
                else:
                    self.s = self.s[:-len(cw)] + current_match

                self.print_line(self.s, True)
        return True

    def undo(self, n=1):
        repl.Repl.undo(self, n)

        # This will unhighlight highlighted parens
        self.print_line(self.s)

    def writetb(self, lines):
        for line in lines:
            self.write('\x01%s\x03%s' % (self.config.color_scheme['error'],
                                         line))

    def yank_from_buffer(self):
        """Paste the text from the cut buffer at the current cursor
        location."""
        self.addstr(self.cut_buffer)
        self.print_line(self.s, clr=True)

class Statusbar(object):

    """This class provides the status bar at the bottom of the screen. It has
    message() and prompt() methods for user interactivity, as well as settext()
    and clear() methods for changing its appearance.

    The check() method needs to be called repeatedly if the statusbar is
    going to be aware of when it should update its display after a message()
    has been called (it'll display for a couple of seconds and then disappear).

    It should be called as:
        foo = Statusbar(stdscr, scr, 'Initial text to display')
    or, for a blank statusbar:
        foo = Statusbar(stdscr, scr)

    It can also receive the argument 'c' which will be an integer referring
    to a curses colour pair, e.g.:
        foo = Statusbar(stdscr, 'Hello', c=4)

    stdscr should be a curses window object in which to put the status bar.
    pwin should be the parent window. To be honest, this is only really here
    so the cursor can be returned to the window properly.

    """

    def __init__(self, scr, pwin, background, config, s=None, c=None):
        """Initialise the statusbar and display the initial text (if any)"""
        self.size()
        self.win = newwin(background, self.h, self.w, self.y, self.x)

        self.config = config

        self.s = s or ''
        self._s = self.s
        self.c = c
        self.timer = 0
        self.pwin = pwin
        self.settext(s, c)

    def size(self):
        """Set instance attributes for x and y top left corner coordinates and
        width and heigth for the window."""
        h, w = gethw()
        self.y = h - 1
        self.w = w
        self.h = 1
        self.x = 0

    def resize(self, refresh=True):
        """This method exists simply to keep it straight forward when
        initialising a window and resizing it."""
        self.size()
        self.win.mvwin(self.y, self.x)
        self.win.resize(self.h, self.w)
        if refresh:
            self.refresh()

    def refresh(self):
        """This is here to make sure the status bar text is redraw properly
        after a resize."""
        self.settext(self._s)

    def check(self):
        """This is the method that should be called every half second or so to
        see if the status bar needs updating."""
        if not self.timer:
            return

        if time.time() < self.timer:
            return

        self.settext(self._s)

    def message(self, s, n=3):
        """Display a message for a short n seconds on the statusbar and return
        it to its original state."""
        self.timer = time.time() + n
        self.settext(s)

    def prompt(self, s=''):
        """Prompt the user for some input (with the optional prompt 's') and
        return the input text, then restore the statusbar to its original
        value."""

        self.settext(s or '? ', p=True)
        iy, ix = self.win.getyx()

        def bs(s):
            y, x = self.win.getyx()
            if x == ix:
                return s
            s = s[:-1]
            self.win.delch(y, x - 1)
            self.win.move(y, x - 1)
            return s

        o = ''
        while True:
            c = self.win.getch()

            # '\b'
            if c == 127:
                o = bs(o)
            # '\n'
            elif c == 10:
                break
            # ESC
            elif c == 27:
                curses.flushinp()
                raise ValueError
            # literal
            elif 0 < c < 127:
                c = chr(c)
                self.win.addstr(c, get_colpair(self.config, 'prompt'))
                o += c

        self.settext(self._s)
        return o

    def settext(self, s, c=None, p=False):
        """Set the text on the status bar to a new permanent value; this is the
        value that will be set after a prompt or message.

        c is the optional curses colour pair to use (if not specified
        the last specified colour pair will be used).  p is True if the
        cursor is expected to stay in the status window (e.g. when
        prompting).

        """

        self.win.erase()
        if len(s) >= self.w:
            s = s[:self.w - 1]

        self.s = s
        if c:
            self.c = c

        if s:
            if not py3 and isinstance(s, unicode):
                s = s.encode(getpreferredencoding())

            if self.c:
                self.win.addstr(s, self.c)
            else:
                self.win.addstr(s)

        if not p:
            self.win.noutrefresh()
            self.pwin.refresh()
        else:
            self.win.refresh()

    def clear(self):
        """Clear the status bar."""
        self.win.clear()

def init_wins(scr, config):
    """Initialise the two windows (the main repl interface and the little
    status bar at the bottom with some stuff in it)"""
    # TODO: Document better what stuff is on the status bar.

    background = get_colpair(config, 'background')
    h, w = gethw()

    main_win = newwin(background, h - 1, w, 0, 0)
    main_win.scrollok(True)
    main_win.keypad(1)
    # Thanks to Angus Gibson for pointing out this missing line which was causing
    # problems that needed dirty hackery to fix. :)

    menu_string = ''
    for name, key in (
        ('Rewind', config.undo_key),
        ('Save', config.save_key),
        ('Pastebin', config.pastebin_key),
        ('Pager', config.last_output_key),
        ('Show Source', config.show_source_key)
    ):
        if key:
            menu_string += ' <%s> %s ' % (key, name)

    statusbar = Statusbar(scr, main_win, background, config,
                          menu_string,
                          get_colpair(config, 'main'))

    return main_win, statusbar

def sigwinch(unused_scr):
    global DO_RESIZE
    DO_RESIZE = True

def sigcont(unused_scr):
    sigwinch(unused_scr)
    # Forces the redraw
    curses.ungetch('\x00')

def gethw():
    """I found this code on a usenet post, and snipped out the bit I needed, so
    thanks to whoever wrote that, sorry I forgot your name, I'm sure you're a
    great guy.

    It's unfortunately necessary (unless someone has any better ideas) in order
    to allow curses and readline to work together. I looked at the code for
    libreadline and noticed this comment:

        /* This is the stuff that is hard for me.  I never seem to write good
           display routines in C.  Let's see how I do this time. */

    So I'm not going to ask any questions.

    """

    if platform.system() != 'Windows':
        h, w = struct.unpack(
            'hhhh',
            fcntl.ioctl(sys.__stdout__, termios.TIOCGWINSZ, '\000' * 8))[0:2]
    else:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

        if res:
            (bufx, bufy, curx, cury, wattr,
             left, top, right, bottom, maxx, maxy) = struct.unpack('hhhhHhhhhhh', csbi.raw)
            sizex = right - left + 1
            sizey = bottom - top + 1
        else:
            # can't determine actual size - return default values
            sizex, sizey = stdscr.getmaxyx()

        h, w = sizey, sizex
    return h, w

def idle(caller):
    """This is called once every iteration through the getkey() loop (currently
    in the Repl class, see the get_line() method).

    The statusbar check needs to go here to take care of timed messages
    and the resize handlers need to be here to make sure it happens
    conveniently.

    """
    global DO_RESIZE

    if importcompletion.find_coroutine() or caller.paste_mode:
        caller.scr.nodelay(True)
        key = caller.scr.getch()
        caller.scr.nodelay(False)
        if key != -1:
            curses.ungetch(key)
        else:
            curses.ungetch('\x00')
    caller.statusbar.check()
    caller.check()

    if DO_RESIZE:
        do_resize(caller)

def do_resize(caller):
    """This needs to hack around readline and curses not playing nicely
    together.

    See also gethw() above.

    """
    global DO_RESIZE
    h, w = gethw()
    if not h:
    # Hopefully this shouldn't happen. :)
        return

    curses.endwin()
    os.environ['LINES'] = str(h)
    os.environ['COLUMNS'] = str(w)
    curses.doupdate()
    DO_RESIZE = False

    try:
        caller.resize()
    except curses.error:
        pass
    # The list win resizes itself every time it appears so no need to do it
    # here.

class FakeDict(object):

    """Very simple dict-alike that returns a constant value for any key -
    used as a hacky solution to using a colours dict containing colour codes if
    colour initialisation fails."""

    def __init__(self, val):
        self._val = val

    def __getitem__(self, k):
        return self._val

def newwin(background, *args):
    """Wrapper for curses.newwin to automatically set background colour on any
    newly created window."""
    win = curses.newwin(*args)
    win.bkgd(' ', background)
    return win

def curses_wrapper(func, *args, **kwargs):
    """Like curses.wrapper(), but reuses stdscr when called again."""
    global stdscr
    if stdscr is None:
        stdscr = curses.initscr()
    try:
        curses.noecho()
        curses.cbreak()
        stdscr.keypad(1)

        try:
            curses.start_color()
        except curses.error:
            pass

        return func(stdscr, *args, **kwargs)
    finally:
        stdscr.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()

def main_curses(scr, args, config, interactive=True, locals_=None,
                banner=None):
    """main function for the curses convenience wrapper.

    Initialise the two main objects: the interpreter
    and the repl. The repl does what a repl does and lots
    of other cool stuff like syntax highlighting and stuff.
    I've tried to keep it well factored but it needs some
    tidying up, especially in separating the curses stuff
    from the rest of the repl.

    Returns a tuple (exit value, output), where exit value is a tuple
    with arguments passed to SystemExit.

    """
    global stdscr
    global DO_RESIZE
    global colors
    DO_RESIZE = False

    if platform.system() != 'Windows':
        old_sigwinch_handler = signal.signal(signal.SIGWINCH,
                                             lambda *_: sigwinch(scr))
        # redraw window after being suspended
        old_sigcont_handler = signal.signal(
            signal.SIGCONT,
            lambda *_: sigcont(scr))

    stdscr = scr
    try:
        curses.start_color()
        curses.use_default_colors()
        cols = make_colors(config)
    except curses.error:
        cols = FakeDict(-1)

    # FIXME: Gargh, bad design results in using globals without a refactor :(
    colors = cols

    scr.timeout(300)

    curses.raw(True)
    main_win, statusbar = init_wins(scr, config)

    if locals_ is None:
        sys.modules['__main__'] = ModuleType('__main__')
        locals_ = sys.modules['__main__'].__dict__
    interpreter = repl.Interpreter(locals_, getpreferredencoding())

    clirepl = CLIRepl(main_win, interpreter, statusbar, config, idle)
    clirepl._C = cols

    sys.stdin = FakeStdin(clirepl)
    sys.stdout = FakeStream(clirepl)
    sys.stderr = FakeStream(clirepl)

    if args:
        exit_value = 0
        try:
            bpython.args.exec_code(interpreter, args)
        except SystemExit as e:
            # The documentation of code.InteractiveInterpreter.runcode claims
            # that it reraises SystemExit. However, I can't manage to trigger
            # that. To be one the safe side let's catch SystemExit here anyway.
            exit_value = e.args
        if not interactive:
            curses.raw(False)
            return (exit_value, clirepl.getstdout())
    else:
        sys.path.insert(0, '')
        clirepl.startup()

    if banner is not None:
        clirepl.write(banner)
        clirepl.write('\n')
    exit_value = clirepl.repl()

    main_win.erase()
    main_win.refresh()
    statusbar.win.clear()
    statusbar.win.refresh()
    curses.raw(False)

    # Restore signal handlers
    if platform.system() != 'Windows':
        signal.signal(signal.SIGWINCH, old_sigwinch_handler)
        signal.signal(signal.SIGCONT, old_sigcont_handler)

    return (exit_value, clirepl.getstdout())

def main(args=None, locals_=None, banner=None):
    translations.init()

    config, options, exec_args = bpython.args.parse(args)

    # Save stdin, stdout and stderr for later restoration
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    try:
        (exit_value, output) = curses_wrapper(
            main_curses, exec_args, config, options.interactive, locals_,
            banner=banner)
    finally:
        sys.stdin = orig_stdin
        sys.stderr = orig_stderr
        sys.stdout = orig_stdout

    # Fake stdout data so everything's still visible after exiting
    if config.flush_output and not options.quiet:
        sys.stdout.write(output)
    if hasattr(sys.stdout, 'flush'):
        sys.stdout.flush()
    return repl.extract_exit_value(exit_value)

if __name__ == '__main__':
    from bpython.cli import main
    sys.exit(main())

# vim: sw=4 ts=4 sts=4 ai et


text:
package com.k_int.yarm.utils;

import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.BooleanType;
import org.hibernate.type.Type;

import java.util.List;

/**
 *
 * @see : http://grails-dev.blogspot.co.uk/2014/10/adding-custom-operators-in-hql-for.html
 * @see : https://metabroadcast.com/blog/hibernate-and-postgres-fts
 * @see : http://java-talks.blogspot.co.uk/2014/04/use-postgresql-full-text-search-with-hql.html
 */
public class PgFullTextSearchFunction implements SQLFunction {

  @SuppressWarnings("unchecked")
  @Override
  public String render(Type type, List args, SessionFactoryImplementor sessionFactoryImplementor) throws QueryException{
    if (args.size() < 2) {
      throw new IllegalArgumentException( "The function must be passed 2 arguments");
    }

    String field = (String) args.get(0);
    String value = (String) args.get(1);
    String fragment = "";
    fragment += "to_tsvector(" + field + ") @@ ";
    fragment +="to_tsquery("+value+")";

    return fragment;
  }

  @Override
  public Type getReturnType(Type columnType, Mapping mapping) throws QueryException {
    return new BooleanType();
  }

  @Override
  public boolean hasArguments() {
    return true;
  }

  @Override
  public boolean hasParenthesesIfNoArguments() {
    return false;
  }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VendingMachineModels.DTOs.Interfaces;

namespace VendingMachineModels.DTOs
{
    public class CountryDTO : Base.BaseModel
    {
        private int iD;
        private string name;

        public CountryDTO()
        {

        }

        public CountryDTO(int IDParam, string NameParam)
        {
            this.ID = IDParam;
            this.Name = NameParam;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int ID
        {
            get { return iD; }
            set { iD = value; }
        }

    }
}


text:
import Link from 'next/link'
import useSWR from 'swr'
import { Auth, Card, Typography, Space, Button, Icon } from '@supabase/ui'
import { supabase } from '../utils/initSupabase'
import { useEffect, useState } from 'react'

const fetcher = (url, token) =>
  fetch(url, {
    method: 'GET',
    headers: new Headers({ 'Content-Type': 'application/json', token }),
    credentials: 'same-origin',
  }).then((res) => res.json())

const Index = () => {
  const { user, session } = Auth.useUser()
  const { data, error } = useSWR(
    session ? ['/api/getUser', session.access_token] : null,
    fetcher
  )
  const [authView, setAuthView] = useState('sign_in')

  useEffect(() => {
    const { data: authListener } = supabase.auth.onAuthStateChange(
      (event, session) => {
        if (event === 'PASSWORD_RECOVERY') setAuthView('update_password')
        if (event === 'USER_UPDATED')
          setTimeout(() => setAuthView('sign_in'), 1000)
        // Send session to /api/auth route to set the auth cookie.
        // NOTE: this is only needed if you're doing SSR (getServerSideProps)!
        fetch('/api/auth', {
          method: 'POST',
          headers: new Headers({ 'Content-Type': 'application/json' }),
          credentials: 'same-origin',
          body: JSON.stringify({ event, session }),
        }).then((res) => res.json())
      }
    )

    return () => {
      authListener.unsubscribe()
    }
  }, [])

  const View = () => {
    if (!user)
      return (
        <Space direction="vertical" size={8}>

            <Typography.Title level={3}>
              Welcome to Supabase Auth
            </Typography.Title>

          <Auth
            supabaseClient={supabase}
            providers={['google', 'github']}
            view={authView}
            socialLayout="horizontal"
            socialButtonSize="xlarge"
          />
        </Space>
      )

    return (
      <Space direction="vertical" size={6}>
        {authView === 'update_password' && (
          <Auth.UpdatePassword supabaseClient={supabase} />
        )}
        {user && (
          <>
            <Typography.Text>You're signed in</Typography.Text>
            <Typography.Text strong>Email: {user.email}</Typography.Text>

            <Button
              icon={<Icon type="LogOut" />}
              type="outline"
              onClick={() => supabase.auth.signOut()}
            >
              Log out
            </Button>
            {error && (
              <Typography.Text danger>Failed to fetch user!</Typography.Text>
            )}
            {data && !error ? (
              <>
                <Typography.Text type="success">
                  User data retrieved server-side (in API route):
                </Typography.Text>

                <Typography.Text>

{JSON.stringify(data, null, 2)}

                </Typography.Text>
              </>
            ) : (

Loading...

            )}

            <Typography.Text>
              <Link href="/profile">
                SSR example with getServerSideProps
              </Link>
            </Typography.Text>
          </>
        )}
      </Space>
    )
  }

  return (

      <Card>
        <View />
      </Card>

  )
}

export default Index


text:
require File.expand_path(File.dirname(__FILE__)) + "/../lib/superfeedr-blather"

Bundler.require(:test)

RSpec.configure do |config|
  # config.include SpecHelper
end


text:
{% extends "layout.html" %}

{% block stylesheets %}

{% endblock %}

{% block body %}

                    {% if (mode == "sandbox") or (mode == "debug") %}

                            Application ID: {{ app_id }}.

                    {% endif %}

                        {% if assignmentid == "ASSIGNMENT_ID_NOT_AVAILABLE" %}

Call for participants

                                The XXX Lab at XXXXX University is looking for online participants
                                for a brief psychology experiment. The only requirements
                                are that you are at least 18 years old and are a fluent English
                                speaker.  The task will take XXXXX minutes and will pay XXXXX.

                                Please click the "Accept HIT" button on the Amazon site
                                above to begin the task.

                        {% else %}

Thanks for accepting this HIT.

                                By clicking the following URL link, you will be taken to the experiment,
                                including complete instructions and an informed consent agreement.

                                Warning: Please disable pop-up blockers before continuing.

                            <button type="button" class="btn btn-primary btn-lg" onClick="openwindow();">
                              Begin Experiment
                            </button>

                        {% endif %}

{% endblock %}


text:
namespace SilverNeedle.Characters.SpecialAbilities.BloodlinePowers
{
    using SilverNeedle.Utility;

    public class CorruptingTouch : AbilityDisplayAsName, IBloodlinePower, IComponent
    {
        private AbilityScore charisma;
        private ClassLevel sorcererLevels;
        public int UsesPerDay
        {
            get
            {
                return 3 + charisma.TotalModifier;
            }
        }

        public int RoundsDuration
        {
            get
            {
                return (sorcererLevels.Level / 2).AtLeast(1);
            }
        }
        public void Initialize(ComponentContainer components)
        {
            this.charisma = components.Get<AbilityScores>().GetAbility(AbilityScoreTypes.Charisma);
            this.sorcererLevels = components.Get<ClassLevel>();
        }
    }
}


text:
FROM python:3.9.6

# Create `overseer` user and use it's home dir
RUN useradd -m overseer
WORKDIR /home/overseer

# Install Python requirements
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy Python app files
COPY *.py ./

# Ensure Celery startup banner is printed
# See https://www.distributedpython.com/2018/10/01/celery-docker-startup/
ENV PYTHONUNBUFFERED=1

# Run Celery as the user `overseer`
# See https://stackoverflow.com/a/56383736 for reason for empty pidfile option
USER overseer
CMD python3 overseer.py


text:
package org.apache.cassandra.db;

import java.security.MessageDigest;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.ObjectSizes;
import org.apache.cassandra.utils.concurrent.OpOrder;
import org.apache.cassandra.utils.memory.AbstractAllocator;
import org.apache.cassandra.utils.memory.MemoryUtil;
import org.apache.cassandra.utils.memory.MemtableAllocator;
import org.apache.cassandra.utils.memory.NativeAllocator;

public class NativeDeletedCell extends NativeCell implements DeletedCell
{
    private static final long SIZE = ObjectSizes.measure(new NativeDeletedCell());

    private NativeDeletedCell()
    {}

    public NativeDeletedCell(NativeAllocator allocator, OpOrder.Group writeOp, DeletedCell copyOf)
    {
        super(allocator, writeOp, copyOf);
    }

    @Override
    public Cell reconcile(Cell cell)
    {
        if (cell instanceof DeletedCell)
            return super.reconcile(cell);
        return cell.reconcile(this);
    }

    @Override
    public boolean isLive()
    {
        return false;
    }

    @Override
    public boolean isLive(long now)
    {
        return false;
    }

    @Override
    public int getLocalDeletionTime()
    {
        int v = getInt(valueStartOffset());
        return MemoryUtil.INVERTED_ORDER ? Integer.reverseBytes(v) : v;
    }

    @Override
    public int serializationFlags()
    {
        return ColumnSerializer.DELETION_MASK;
    }

    @Override
    public void validateFields(CFMetaData metadata) throws MarshalException
    {
        validateName(metadata);

        if ((int) (internalSize() - valueStartOffset()) != 4)
            throw new MarshalException("A tombstone value should be 4 bytes long");
        if (getLocalDeletionTime() < 0)
            throw new MarshalException("The local deletion time should not be negative");
    }

    @Override
    public void updateDigest(MessageDigest digest)
    {
        updateWithName(digest);
        FBUtilities.updateWithLong(digest, timestamp());
        FBUtilities.updateWithByte(digest, serializationFlags());
    }

    @Override
    public DeletedCell localCopy(CFMetaData metadata, AbstractAllocator allocator)
    {
        return new BufferDeletedCell(copy(metadata, allocator), allocator.clone(value()), timestamp());
    }

    @Override
    public DeletedCell localCopy(CFMetaData metadata, MemtableAllocator allocator, OpOrder.Group opGroup)
    {
        return allocator.clone(this, metadata, opGroup);
    }

    @Override
    public boolean equals(Cell cell)
    {
        return timestamp() == cell.timestamp() && getLocalDeletionTime() == cell.getLocalDeletionTime() && name().equals(cell.name());
    }

    @Override
    public long excessHeapSizeExcludingData()
    {
        return SIZE;
    }

    @Override
    public long unsharedHeapSize()
    {
        return SIZE;
    }
}


text:
#ifndef TENSORFLOW_CORE_FRAMEWORK_TENSOR_SHAPE_H_
#define TENSORFLOW_CORE_FRAMEWORK_TENSOR_SHAPE_H_

#include <string>

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

class TensorShapeIter;  // Declared below

class TensorShape {
 public:
  /// \brief Construct a `TensorShape` from the provided sizes.
  /// REQUIRES: `dim_sizes[i] >= 0`
  explicit TensorShape(gtl::ArraySlice<int64> dim_sizes);
  TensorShape(std::initializer_list<int64> dim_sizes)
      : TensorShape(gtl::ArraySlice<int64>(dim_sizes)) {}

  /// REQUIRES: `IsValid(proto)`
  explicit TensorShape(const TensorShapeProto& proto);

  /// Create a tensor shape with no dimensions and one element, which you can
  /// then call `AddDim()` on.
  TensorShape();

  ~TensorShape();

  /// Copy the specified shape
  TensorShape(const TensorShape& b);
  void operator=(const TensorShape& b);

  /// Returns `true` iff `proto` is a valid tensor shape.
  static bool IsValid(const TensorShapeProto& proto);

  /// Returns `OK` iff `proto` is a valid tensor shape, and a descriptive error
  /// status otherwise.
  static Status IsValidShape(const TensorShapeProto& proto);

  /// Clear a tensor shape
  void Clear();

  /// \brief Add a dimension to the end ("inner-most").
  /// REQUIRES: `size >= 0`
  void AddDim(int64 size);

  /// Appends all the dimensions from `shape`.
  void AppendShape(const TensorShape& shape);

  /// \brief Insert a dimension somewhere in the `TensorShape`.
  /// REQUIRES: `0 <= d <= dims()`
  /// REQUIRES: `size >= 0`
  void InsertDim(int d, int64 size);

  /// \brief Modifies the size of the dimension `d` to be `size`
  /// REQUIRES: `0 <= d < dims()`
  /// REQUIRES: `size >= 0`
  void set_dim(int d, int64 size);

  /// \brief Removes dimension `d` from the `TensorShape`.
  /// REQUIRES: `0 <= d < dims()`
  void RemoveDim(int d);

  /// Return the number of dimensions in the tensor.
  int dims() const {
    return (tag() == REP_OUT_OF_LINE) ? (*as64()->dims_).size() : ndims_byte();
  }

  /// \brief Returns the number of elements in dimension `d`.
  /// REQUIRES: `0 <= d < dims()`
  // TODO(touts): Rename to `dimension()` to match
  // `Eigen::Tensor::dimension()`?
  int64 dim_size(int d) const {
    DCHECK_GE(d, 0);
    DCHECK_LT(d, dims());
    if (tag() == REP16) {
      return as16()->dims_[d];
    } else if (tag() == REP32) {
      return as32()->dims_[d];
    } else {
      return (*as64()->dims_)[d];
    }
  }

  /// Returns sizes of all dimensions.
  gtl::InlinedVector<int64, 4> dim_sizes() const;

  /// \brief Returns the number of elements in the tensor.
  ///
  /// We use `int64` and not `size_t` to be compatible with `Eigen::Tensor`
  /// which uses `ptrdiff_t`.
  int64 num_elements() const { return num_elements_; }

  /// Returns true if `*this` and `b` have the same sizes. Ignores
  /// dimension names.
  bool IsSameSize(const TensorShape& b) const;
  bool operator==(const TensorShape& b) const { return IsSameSize(b); }
  bool operator!=(const TensorShape& b) const { return !IsSameSize(b); }

  /// Fill `*proto` from `*this`.
  void AsProto(TensorShapeProto* proto) const;

  /// Fill `*dsizes` from `*this`.
  template <int NDIMS>
  Eigen::DSizes<Eigen::DenseIndex, NDIMS> AsEigenDSizes() const;

  /// Same as `AsEigenDSizes()` but allows for `NDIMS > dims()` -- in
  /// which case we pad the rest of the sizes with 1.
  template <int NDIMS>
  Eigen::DSizes<Eigen::DenseIndex, NDIMS> AsEigenDSizesWithPadding() const;

  /// For iterating through the dimensions.
  TensorShapeIter begin() const;
  TensorShapeIter end() const;

  /// For error messages.
  string DebugString() const;

  /// Same as `TensorShape(proto).DebugString()` but doesn't crash for
  /// invalid protos.
  static string DebugString(const TensorShapeProto& proto);

  void DumpRep() const;  // XXX
 private:
  void ClearAllButDataType();
  void SlowCopyFrom(const TensorShape& b);

  void RecomputeNumElements();

  // We use 16 bytes to represent a TensorShape.  Because we need to
  // be able to support full 64-bit dimension sizes and an arbitrary
  // number of dimensions for a Tensor, but most tensor dimensions are
  // significantly smaller than 64 bits and most tensors are 1, 2, or 3
  // dimensions, we have several representations.
  // Rep16: Supports up to 6 dimensions where each dimension is < 2^16
  // Rep32: Supports up to 3 dimensions where each dimension is < 2^32
  // Rep64: Supports arbitrary dimensionality, 64-bit dimensions using
  //        an out of line vector.
  struct Rep16 {
    int16 dims_[6];
  };
  struct Rep32 {
    int32 dims_[3];
  };
  struct Rep64 {
    gtl::InlinedVector<int64, 4>* dims_;
  };

  static const int64 kMaxRep16 = 32768;
  static const int64 kMaxRep32 = (1ull << 31) - 1;

  uint8* buf() { return &u_.buf[0]; }
  const uint8* buf() const { return &u_.buf[0]; }

  Rep16* as16() { return reinterpret_cast<Rep16*>(buf()); }
  Rep32* as32() { return reinterpret_cast<Rep32*>(buf()); }
  Rep64* as64() { return reinterpret_cast<Rep64*>(buf()); }

  const Rep16* as16() const { return reinterpret_cast<const Rep16*>(buf()); }
  const Rep32* as32() const { return reinterpret_cast<const Rep32*>(buf()); }
  const Rep64* as64() const { return reinterpret_cast<const Rep64*>(buf()); }

  enum RepTag { REP16 = 0, REP32 = 1, REP_OUT_OF_LINE = 2 };

  // Since we have a convenient extra byte available, we allow the
  // Tensor class to store an 8-bit value in this extra storage.  This
  // allows it to store the Tensor's datatype enum value here and avoid
  // an extra word of storage.
  friend class Tensor;
  friend class TensorShapeTestHelper;
  friend class BitcastOp;
  DataType data_type() const { return static_cast<DataType>(buf()[13]); }
  void set_data_type(DataType dt) {
    // We only have 8 bits available to store DataType, so make sure it fits
    DCHECK_LT(static_cast<uint32>(dt), 256);
    buf()[13] = static_cast<uint8>(dt);
  }

  // We store the number of dimensions in byte 14, and the RepTag in byte 15.
  // Bytes [0..13] vary depending on the representation
  uint8 ndims_byte() const { return buf()[14]; }
  void set_ndims_byte(uint8 nd) { buf()[14] = nd; }

  RepTag tag() const { return static_cast<RepTag>(buf()[15]); }
  void set_tag(RepTag tag) { buf()[15] = static_cast<uint8>(tag); }

  union {
    uint8 buf[16];
    // Force data to be aligned enough for a pointer.
    Rep64* unused_aligner;
  } u_;
  int64 num_elements_;
};

struct TensorShapeDim {
  explicit TensorShapeDim(int64 s) : size(s) {}
  int64 size;
};

class TensorShapeIter {
 public:
  TensorShapeIter(const TensorShape* shape, int d) : shape_(shape), d_(d) {}
  bool operator==(const TensorShapeIter& rhs) {
    DCHECK(shape_ == rhs.shape_);
    return d_ == rhs.d_;
  }
  bool operator!=(const TensorShapeIter& rhs) {
    DCHECK(shape_ == rhs.shape_);
    return d_ != rhs.d_;
  }
  void operator++() { ++d_; }
  TensorShapeDim operator*() { return TensorShapeDim(shape_->dim_size(d_)); }

 private:
  const TensorShape* shape_;
  int d_;
};

/// \brief Static helper routines for `TensorShape`. Includes a few common
/// predicates on a tensor shape.
class TensorShapeUtils {
 public:
  static bool IsScalar(const TensorShape& shape) { return shape.dims() == 0; }

  static bool IsVector(const TensorShape& shape) { return shape.dims() == 1; }

  static bool IsVectorOrHigher(const TensorShape& shape) {
    return shape.dims() >= 1;
  }

  static bool IsMatrix(const TensorShape& shape) { return shape.dims() == 2; }

  static bool IsMatrixOrHigher(const TensorShape& shape) {
    return shape.dims() >= 2;
  }

  /// \brief Returns a `TensorShape` whose dimensions are
  /// `dims[0]`, `dims[1]`, ..., `dims[n-1]`.
  template <typename T>
  static Status MakeShape(const T* dims, int n, TensorShape* out) {
    *out = TensorShape();
    for (int i = 0; i < n; ++i) {
      if (dims[i] >= 0) {
        out->AddDim(dims[i]);
      } else {
        return errors::InvalidArgument("Dimension ", dims[i], " must be >= 0");
      }
    }
    return Status::OK();
  }

  static string ShapeListString(const gtl::ArraySlice<TensorShape>& shapes) {
    string result = "[";
    bool first = true;
    for (const TensorShape& shape : shapes) {
      strings::StrAppend(&result, (first ? "" : ", "), shape.DebugString());
      first = false;
    }
    strings::StrAppend(&result, "]");
    return result;
  }

  static bool StartsWith(const TensorShape& shape0, const TensorShape& shape1);
};

// ----------------------------------------------------------------------------
// Template method implementation details below
// ----------------------------------------------------------------------------

template <int NDIMS>
Eigen::DSizes<Eigen::DenseIndex, NDIMS> TensorShape::AsEigenDSizes() const {
  CHECK_EQ(NDIMS, dims()) << "Asking for tensor of " << NDIMS
                          << " for a tensor of " << dims() << " dimensions";
  return AsEigenDSizesWithPadding<NDIMS>();
}

template <int NDIMS>
Eigen::DSizes<Eigen::DenseIndex, NDIMS> TensorShape::AsEigenDSizesWithPadding()
    const {
  CHECK_GE(NDIMS, dims()) << "Asking for tensor of " << NDIMS
                          << " for a tensor of " << dims() << " dimensions";
  Eigen::DSizes<Eigen::DenseIndex, NDIMS> dsizes;
  for (int d = 0; d < dims(); d++) {
    dsizes[d] = dim_size(d);
  }
  for (int d = dims(); d < NDIMS; d++) {
    dsizes[d] = 1;
  }
  return dsizes;
}

// ----------------------------------------------------------------------------
// Inlining of some performance critical routines
// ----------------------------------------------------------------------------

inline TensorShape::TensorShape(const TensorShape& b) {
  num_elements_ = b.num_elements_;
  if (b.tag() != REP_OUT_OF_LINE) {
    memcpy(buf(), b.buf(), sizeof(u_.buf));
    // memcpy above Implicitly does:
    //   set_ndims_byte(b.ndims_byte());
    //   set_tag(b.tag());
  } else {
    set_tag(REP16);  // So that SlowCopyFrom does not try to deallocate
    SlowCopyFrom(b);
  }
}

inline TensorShape::~TensorShape() {
  if (tag() == REP_OUT_OF_LINE) {
    delete as64()->dims_;
  }
}

inline void TensorShape::operator=(const TensorShape& b) {
  num_elements_ = b.num_elements_;
  if (tag() != REP_OUT_OF_LINE && b.tag() != REP_OUT_OF_LINE) {
    memcpy(buf(), b.buf(), sizeof(u_.buf));
    // memcpy above implicitly also does:
    //   set_tag(b.tag());
    //   set_ndims_byte(b.ndims_byte());
  } else {
    SlowCopyFrom(b);
  }
}

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_FRAMEWORK_TENSOR_SHAPE_H_


text:
<resources>

    <style name="AppBaseTheme" parent="@android:style/Theme.Light" />

    <style name="AppTheme" parent="AppBaseTheme" />

</resources>


text:
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Globalization;
using System.Linq;

namespace NuGetGallery
{
    public class EditPackageService
    {
        public IEntitiesContext EntitiesContext { get; set; }

        public EditPackageService() { }

        public EditPackageService(IEntitiesContext entitiesContext)
        {
            EntitiesContext = entitiesContext;
        }

        /// <summary>
        /// Returns the newest, uncompleted metadata for a package (i.e. a pending edit)
        /// </summary>
        public virtual PackageEdit GetPendingMetadata(Package p)
        {
            return EntitiesContext.Set<PackageEdit>()
                .Where(m => m.PackageKey == p.Key)
                .OrderByDescending(m => m.Timestamp)
                .FirstOrDefault();
        }

        public virtual void StartEditPackageRequest(Package p, EditPackageVersionRequest request, User editingUser)
        {
            PackageEdit edit = new PackageEdit
            {
                // Description
                User = editingUser,
                Authors = request.Authors,
                Copyright = request.Copyright,
                Description = request.Description,
                IconUrl = request.IconUrl,
                LicenseUrl = p.LicenseUrl, // Our current policy is not to allow editing the license URL, so just clone it from its previous value.
                ProjectUrl = request.ProjectUrl,
                ReleaseNotes = request.ReleaseNotes,
                RequiresLicenseAcceptance = request.RequiresLicenseAcceptance,
                Summary = request.Summary,
                Tags = request.Tags,
                Title = request.VersionTitle,

                // Other
                Package = p,
                Timestamp = DateTime.UtcNow,
                TriedCount = 0,
            };

            EntitiesContext.Set<PackageEdit>().Add(edit);
            // Note: EditPackageRequests are completed asynchronously by the worker role.
        }
    }
}


text:
package core.framework.internal.template;

import core.framework.util.Maps;

import java.util.Map;

/**
 * @author neo
 */
public class TemplateMetaContext {
    public final Class<?> rootClass;
    public final Map<String, Class<?>> paramClasses = Maps.newHashMap();
    public CDNManager cdn;
    public MessageProvider message;

    public TemplateMetaContext(Class<?> rootClass) {
        this.rootClass = rootClass;
    }
}


text:
@interface PodsDummy_Pods_RhythmBox_Tests : NSObject
@end
@implementation PodsDummy_Pods_RhythmBox_Tests
@end


text:
title: Client Templates
page_title: Client Templates - RadMenu
description: Check our Web Forms article about Client Templates.
slug: menu/templates/client-templates
tags: client,templates
published: True
position: 1
---

# Client Templates

## Overview

As of Q2 2012 RadMenu provides support for client templates. The template itself contains mark up and binding expressions which are evaluated against a **DataItem** and then rendered as the Item's content on the client. The templates support the following type of expressions which are evaluated at run-time:

* **#=...#** - Evaluates the JavaScript code expression or a string property from the data item and outputs the result in the template.

* **#...#** - Evaluates the JavaScript code expression inside, but doesn't output value.

* **#:...#** - Evaluates the JavaScript code expression or a string property from the data item and outputs the result in the template which is HTML encoeded.

>important Client templates **couldn't** contain server-side controls.
>

## Server side representation

On the server the template will be presented as a string property of the control, named **ClientItemTemplate**. Below a static and dynamic definition of a client template is shown

````ASP.NET
<telerik:RadMenu RenderMode="Lightweight" ID="RadMenu1" runat="server">
    <Items>
        ...
    </Items>
    <ClientItemTemplate>
        <div class="customClass">
            <img src="#= ImagePath #" alt="Photo" />
        </div>
    </ClientItemTemplate>
</telerik:RadMenu>
````

````C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        StringBuilder clientTemplate = new StringBuilder();
        clientTemplate.Append("<div class='customClass'>");
        clientTemplate.Append("<img src='#= ImagePath #' alt='Photo' />");
        clientTemplate.Append("</div>");
        RadMenu1.ClientItemTemplate = clientTemplate.ToString();
    }
}
````
````VB.NET
Protected Sub Default_Vb_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim clientTemplate As New StringBuilder()
        clientTemplate.Append("<div class='customClass'>")
        clientTemplate.Append("<img src='#= ImagePath #' alt='Photo' />")
        clientTemplate.Append("</div>")
        RadMenu1.ClientItemTemplate = clientTemplate.ToString()
    End If
End Sub
````

## Client side representation

The template will be applied automatically to all items loaded through **Web Service**. If an item is added through JavaScript, the template would not be applied, unless its **bindTemplate()** method is explicitly invoked. The method can be called before, as well as after the item is added to the items collection of the control.

Client templates could be applied globally for all RadMenu items or per Item basis allowing a diversity in the look and feel of the different items. This functionality is very useful in case of hierarchy when the root items doesn't have templates, by their children does.

### New client-side methods

There are two new methods of the RadMenu's client-side object which are also available for its items:

* get_clientTemplate() : this method will return the defined client template as a string which include the defined binding expressions.

* set_clientTemplate(value) : this method will set the client template of the RadMenu/RadMenuItem. As a parameter should be passed a string representing the template including the binding expressions.

A new method of the RadMenuItem's client-side object is also introduced:

* bindTemplate() : as a parameter to this method a data item should be passed, if it's called without such paramater it will be automatically created from the basic properties of the item. When the method is called the expressions in the client template will be evaliated.

Sample code for the usage of the new method is demonstrated below.

* Adding item and then binding the Control's template to it:

````ASP.NET
<telerik:RadMenu RenderMode="Lightweight" runat="server" ID="RadMenu1">
    <ClientItemTemplate>
        Template text: #= Text #
    </ClientItemTemplate>
</telerik:RadMenu>
````

````JavaScript
var item = new Telerik.Web.UI.RadMenuItem();
item.set_text("item");
$find("RadMenu1").get_items().add(item);
item.bindTemplate();
````

* Creating item, setting its client template and calling **bindTemplate** method before inserting it into the items collection of the RadMenu:

````JavaScript
var item = new Telerik.Web.UI.RadMenuItem();
item.set_text("item");
item.set_clientTemplate("template text: #= Text #");
item.bindTemplate();
$find("RadMenu1").get_items().add(item);
````

* Creating item, setting it's client template and calling **bindTemplate** method after inserting it into the items colelction of the RadMenu:

````JavaScript
var item = new Telerik.Web.UI.RadMenuItem();
item.set_text("item");
item.set_clientTemplate("template text: #= Text #");
$find("RadMenu1").get_items().add(item);
item.bindTemplate();
````

* Bind the client template to an item rendered on the server:

````ASP.NET
<telerik:RadMenu RenderMode="Lightweight" runat="server" ID="RadMenu1">
    <Items>
        <telerik:RadMenuItem Text="item">
        </telerik:RadMenuItem>
    </Items>
</telerik:RadMenu>
````

````JavaScript
var item = $find("RadMenu1").get_items().getNode(0);
item.set_clientTemplate("template text: #= Text #");
item.bindTemplate();
````

### Client-side event

A new client-side [OnClientTemplateDataBound]({%slug menu/client-side-programming/events/onclienttemplatedatabound-%}) event is introduced.

# See Also

 * [Server Templates]({%slug menu/templates/server-templates%})

 * [Accessing Controls Inside Templates]({%slug menu/templates/accessing-controls-inside-templates%})

 * [Online Demo](https://demos.telerik.com/aspnet-ajax-beta/menu/examples/functionality/clienttemplates/defaultcs.aspx)


text:
using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace Raptor.WebAPI.DataLayer.Entities.Objects.Tables {
    [Table("Levels")]
    public class Levels : BaseTable {
        public string LevelName { get; set; }

        public string LevelDescription { get; set; }

        public string LevelData { get; set; }

        public Guid UserGUID { get; set; }
    }
}


text:
package com.daviancorp.android.data.database;

import android.database.Cursor;
import android.database.CursorWrapper;

import com.daviancorp.android.data.classes.Weapon;

/**
 * A convenience class to wrap a cursor that returns rows from the "weapon"
 * table. The {@link getWeapon()} method will give you a Weapon instance
 * representing the current row.
 */
public class WeaponCursor extends CursorWrapper {

	public WeaponCursor(Cursor c) {
		super(c);
	}

	/**
	 * Returns a Weapon object configured for the current row, or null if the
	 * current row is invalid.
	 */
	public Weapon getWeapon() {
		if (isBeforeFirst() || isAfterLast())
			return null;

		Weapon weapon = new Weapon();

		String wtype = getString(getColumnIndex(S.COLUMN_WEAPONS_WTYPE));
		int creation_cost = getInt(getColumnIndex(S.COLUMN_WEAPONS_CREATION_COST));
		int upgrade_cost = getInt(getColumnIndex(S.COLUMN_WEAPONS_UPGRADE_COST));
		int attack = getInt(getColumnIndex(S.COLUMN_WEAPONS_ATTACK));
		int max_attack = getInt(getColumnIndex(S.COLUMN_WEAPONS_MAX_ATTACK));
		String element = getString(getColumnIndex(S.COLUMN_WEAPONS_ELEMENT));
		String awaken = getString(getColumnIndex(S.COLUMN_WEAPONS_AWAKEN));
        String element_2 = getString(getColumnIndex(S.COLUMN_WEAPONS_ELEMENT_2));
        long element_2_attack = getLong(getColumnIndex(S.COLUMN_WEAPONS_ELEMENT_2_ATTACK));
        long element_attack = getLong(getColumnIndex(S.COLUMN_WEAPONS_ELEMENT_ATTACK));
        long awaken_attack = getLong(getColumnIndex(S.COLUMN_WEAPONS_AWAKEN_ATTACK));
		int defense = getInt(getColumnIndex(S.COLUMN_WEAPONS_DEFENSE));
		String sharpness = getString(getColumnIndex(S.COLUMN_WEAPONS_SHARPNESS));
		String affinity = getString(getColumnIndex(S.COLUMN_WEAPONS_AFFINITY));
		String horn_notes = getString(getColumnIndex(S.COLUMN_WEAPONS_HORN_NOTES));
		String shelling_type = getString(getColumnIndex(S.COLUMN_WEAPONS_SHELLING_TYPE));
		String phial = getString(getColumnIndex(S.COLUMN_WEAPONS_PHIAL));
		String charges = getString(getColumnIndex(S.COLUMN_WEAPONS_CHARGES));
		String coatings = getString(getColumnIndex(S.COLUMN_WEAPONS_COATINGS));
		String recoil = getString(getColumnIndex(S.COLUMN_WEAPONS_RECOIL));
		String reload_speed = getString(getColumnIndex(S.COLUMN_WEAPONS_RELOAD_SPEED));
		String rapid_fire = getString(getColumnIndex(S.COLUMN_WEAPONS_RAPID_FIRE));
		String deviation = getString(getColumnIndex(S.COLUMN_WEAPONS_DEVIATION));
		String ammo = getString(getColumnIndex(S.COLUMN_WEAPONS_AMMO));
		String special_ammo = getString(getColumnIndex(S.COLUMN_WEAPONS_SPECIAL_AMMO));
		int num_slots = getInt(getColumnIndex(S.COLUMN_WEAPONS_NUM_SLOTS));
		int wfinal = getInt(getColumnIndex(S.COLUMN_WEAPONS_FINAL));
        int tree_depth = getInt(getColumnIndex(S.COLUMN_WEAPONS_TREE_DEPTH));
        int parent_id = getInt(getColumnIndex(S.COLUMN_WEAPONS_PARENT_ID));

		weapon.setWtype(wtype);
		weapon.setCreationCost(creation_cost);
		weapon.setUpgradeCost(upgrade_cost);
		weapon.setAttack(attack);
		weapon.setMaxAttack(max_attack);
		weapon.setElement(element);
		weapon.setAwaken(awaken);
        weapon.setElement2(element_2);
        weapon.setElementAttack(element_attack);
        weapon.setElement2Attack(element_2_attack);
        weapon.setAwakenAttack(awaken_attack);
		weapon.setDefense(defense);
		weapon.setSharpness(sharpness);
		weapon.setAffinity(affinity);
		weapon.setHornNotes(horn_notes);
		weapon.setShellingType(shelling_type);
		weapon.setPhial(phial);
        if(weapon.getWtype().equals("Bow")) {
            weapon.setCharges(charges);
            weapon.setCoatings(coatings);
        }
		weapon.setRecoil(recoil);
		weapon.setReloadSpeed(reload_speed);
		weapon.setRapidFire(rapid_fire);
		weapon.setSpecialAmmo(special_ammo);
		weapon.setDeviation(deviation);
		weapon.setAmmo(ammo);
		weapon.setNumSlots(num_slots);
		weapon.setWFinal(wfinal);
        weapon.setTree_Depth(tree_depth);

		long itemId = getLong(getColumnIndex(S.COLUMN_ITEMS_ID));
		String name = getString(getColumnIndex(S.COLUMN_ITEMS_NAME));
		String jpnName = getString(getColumnIndex(S.COLUMN_ITEMS_JPN_NAME));
		String type = getString(getColumnIndex(S.COLUMN_ITEMS_TYPE));
		int rarity = getInt(getColumnIndex(S.COLUMN_ITEMS_RARITY));
		int carry_capacity = getInt(getColumnIndex(S.COLUMN_ITEMS_CARRY_CAPACITY));
		int buy = getInt(getColumnIndex(S.COLUMN_ITEMS_BUY));
		int sell = getInt(getColumnIndex(S.COLUMN_ITEMS_SELL));
		String description = getString(getColumnIndex(S.COLUMN_ITEMS_DESCRIPTION));
		String fileLocation = getString(getColumnIndex(S.COLUMN_ITEMS_ICON_NAME));
		String armor_dupe_name_fix = getString(getColumnIndex(S.COLUMN_ITEMS_ARMOR_DUPE_NAME_FIX));

		weapon.setId(itemId);
		weapon.setName(name);
		weapon.setJpnName(jpnName);
		weapon.setType(type);
		weapon.setRarity(rarity);
		weapon.setCarryCapacity(carry_capacity);
		weapon.setBuy(buy);
		weapon.setSell(sell);
		weapon.setDescription(description);
		weapon.setFileLocation();
		weapon.setArmorDupeNameFix(armor_dupe_name_fix);
        weapon.setParentId(parent_id);

        if (!weapon.getWtype().equals("Bow") && !weapon.getWtype().equals("Light Bowgun")
            && !weapon.getWtype().equals("Heavy Bowgun")) {
            weapon.initializeSharpness();
        }

		return weapon;
	}

}


text:
function Paddle(game, x, y){
  this.game = game

  this.paddle = game.add.sprite(x, y, 'paddle')
  game.physics.enable(this.paddle, Phaser.Physics.ARCADE)
  this.paddle.anchor.setTo(0.5, 0.5)
  this.paddle.body.collideWorldBounds = true
  this.paddle.body.bounce.setTo(1, 1)
  this.paddle.body.immovable = true
}

Paddle.prototype.incrementScore = function(){
  this.score.text = +(this.score.text) + 1;
}