text:
"""
CommandLineInterface for reading Python input.
This can be used for creation of Python REPLs.

::

    cli = PythonCommandLineInterface()
    cli.run()
"""
from __future__ import unicode_literals

from prompt_toolkit import AbortAction
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory, ConditionalAutoSuggest
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
from prompt_toolkit.filters import Condition, Always
from prompt_toolkit.history import FileHistory, InMemoryHistory
from prompt_toolkit.interface import CommandLineInterface, Application, AcceptAction
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.shortcuts import create_output
from prompt_toolkit.styles import DynamicStyle
from prompt_toolkit.utils import is_windows
from prompt_toolkit.validation import ConditionalValidator

from .completer import PythonCompleter
from .history_browser import create_history_application
from .key_bindings import load_python_bindings, load_sidebar_bindings, load_confirm_exit_bindings
from .layout import create_layout, CompletionVisualisation
from .prompt_style import IPythonPrompt, ClassicPrompt
from .style import get_all_code_styles, get_all_ui_styles, generate_style
from .utils import get_jedi_script_from_document, document_is_multiline_python
from .validator import PythonValidator

from functools import partial

import six
import __future__

if six.PY2:
    from pygments.lexers import PythonLexer
else:
    from pygments.lexers import Python3Lexer as PythonLexer

__all__ = (
    'PythonInput',
    'PythonCommandLineInterface',
)

class OptionCategory(object):
    def __init__(self, title, options):
        assert isinstance(title, six.text_type)
        assert isinstance(options, list)

        self.title = title
        self.options = options

class Option(object):
    """
    Ptpython configuration option that can be shown and modified from the
    sidebar.

    :param title: Text.
    :param description: Text.
    :param get_values: Callable that returns a dictionary mapping the
            possible values to callbacks that activate these value.
    :param get_current_value: Callable that returns the current, active value.
    """
    def __init__(self, title, description, get_current_value, get_values):
        assert isinstance(title, six.text_type)
        assert isinstance(description, six.text_type)
        assert callable(get_current_value)
        assert callable(get_values)

        self.title = title
        self.description = description
        self.get_current_value = get_current_value
        self.get_values = get_values

    @property
    def values(self):
        return self.get_values()

    def activate_next(self, _previous=False):
        """
        Activate next value.
        """
        current = self.get_current_value()
        options = sorted(self.values.keys())

        # Get current index.
        try:
            index = options.index(current)
        except ValueError:
            index = 0

        # Go to previous/next index.
        if _previous:
            index -= 1
        else:
            index += 1

        # Call handler for this option.
        next_option = options[index % len(options)]
        self.values[next_option]()

    def activate_previous(self):
        """
        Activate previous value.
        """
        self.activate_next(_previous=True)

class PythonInput(object):
    """
    Prompt for reading Python input.

    ::

        python_input = PythonInput(...)
        application = python_input.create_application()
        cli = PythonCommandLineInterface(application=application)
        python_code = cli.run()
    """
    def __init__(self,
                 get_globals=None, get_locals=None, history_filename=None,
                 vi_mode=False,

                 # For internal use.
                 _completer=None, _validator=None,
                 _lexer=None, _extra_buffers=None, _extra_buffer_processors=None,
                 _on_start=None,
                 _extra_layout_body=None, _extra_toolbars=None,
                 _input_buffer_height=None,
                 _accept_action=AcceptAction.RETURN_DOCUMENT,
                 _on_exit=AbortAction.RAISE_EXCEPTION):

        self.get_globals = get_globals or (lambda: {})
        self.get_locals = get_locals or self.get_globals

        self._completer = _completer or PythonCompleter(self.get_globals, self.get_locals)
        self._validator = _validator or PythonValidator(self.get_compiler_flags)
        self.history = FileHistory(history_filename) if history_filename else InMemoryHistory()
        self._lexer = _lexer or PygmentsLexer(PythonLexer)
        self._extra_buffers = _extra_buffers
        self._accept_action = _accept_action
        self._on_exit = _on_exit
        self._on_start = _on_start

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        # Settings.
        self.show_signature = False
        self.show_docstring = False
        self.show_meta_enter_message = True
        self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset = 1

        self.show_line_numbers = False
        self.show_status_bar = True
        self.wrap_lines = True
        self.complete_while_typing = True
        self.vi_mode = vi_mode
        self.paste_mode = False  # When True, don't insert whitespace after newline.
        self.confirm_exit = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter = 2  # Accept when pressing Enter 'n' times.
                                        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor = True
        self.enable_system_bindings = True
        self.enable_input_validation = True
        self.enable_auto_suggest = False
        self.enable_mouse_support = False
        self.enable_history_search = False  # When True, like readline, going
                                            # back in history will filter the
                                            # history on the records starting
                                            # with the current input.

        self.highlight_matching_parenthesis = False
        self.show_sidebar = False  # Currently show the sidebar.
        self.show_sidebar_help = True # When the sidebar is visible, also show the help text.
        self.show_exit_confirmation = False  # Currently show 'Do you really want to exit?'
        self.terminal_title = None  # The title to be displayed in the terminal. (None or string.)
        self.exit_message = 'Do you really want to exit?'
        self.insert_blank_line_after_output = True  # (For the REPL.)

        # Tokens to be shown at the prompt.
        self.prompt_style = 'classic'  # The currently active style.

        self.all_prompt_styles = {  # Styles selectable from the menu.
            'ipython': IPythonPrompt(self),
            'classic': ClassicPrompt(),
        }

        self.get_input_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].in_tokens(cli)

        self.get_output_prompt_tokens = lambda cli: \
            self.all_prompt_styles[self.prompt_style].out_tokens(cli)

        #: Load styles.
        self.code_styles = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name = 'default'
        self._current_ui_style_name = 'default'

        if is_windows():
            self._current_code_style_name = 'win32'

        self._current_style = self._generate_style()
        self.true_color = False

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures = []

        # Use a KeyBindingManager for loading the key bindings.
        self.key_bindings_manager = KeyBindingManager(
            enable_abort_and_exit_bindings=True,
            enable_search=True,
            enable_vi_mode=Condition(lambda cli: self.vi_mode),
            enable_open_in_editor=Condition(lambda cli: self.enable_open_in_editor),
            enable_system_bindings=Condition(lambda cli: self.enable_system_bindings),
            enable_auto_suggest_bindings=Condition(lambda cli: self.enable_auto_suggest),

            # Disable all default key bindings when the sidebar or the exit confirmation
            # are shown.
            enable_all=Condition(lambda cli: not (self.show_sidebar or self.show_exit_confirmation)))

        load_python_bindings(self.key_bindings_manager, self)
        load_sidebar_bindings(self.key_bindings_manager, self)
        load_confirm_exit_bindings(self.key_bindings_manager, self)

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running = False

    @property
    def option_count(self):
        " Return the total amount of options. (In all categories together.) "
        return sum(len(category.options) for category in self.options)

    @property
    def selected_option(self):
        " Return the currently selected option. "
        i = 0
        for category in self.options:
            for o in category.options:
                if i == self.selected_option_index:
                    return o
                else:
                    i += 1

    def get_compiler_flags(self):
        """
        Give the current compiler flags by looking for _Feature instances
        in the globals.
        """
        flags = 0

        for value in self.get_globals().values():
            if isinstance(value, __future__._Feature):
                flags |= value.compiler_flag

        return flags

    @property
    def key_bindings_registry(self):
        return self.key_bindings_manager.registry

    @property
    def add_key_binding(self):
        """
        Shortcut for adding new key bindings.
        (Mostly useful for a .ptpython/config.py file, that receives
        a PythonInput/Repl instance as input.)

        ::

            @python_input.add_key_binding(Keys.ControlX, filter=...)
            def handler(event):
                ...
        """
        # Extra key bindings should not be active when the sidebar is visible.
        sidebar_visible = Condition(lambda cli: self.show_sidebar)

        def add_binding_decorator(*keys, **kw):
            # Pop default filter keyword argument.
            filter = kw.pop('filter', Always())
            assert not kw

            return self.key_bindings_registry.add_binding(*keys, filter=filter & ~sidebar_visible)
        return add_binding_decorator

    def install_code_colorscheme(self, name, style_dict):
        """
        Install a new code color scheme.
        """
        assert isinstance(name, six.text_type)
        assert isinstance(style_dict, dict)

        self.code_styles[name] = style_dict

    def use_code_colorscheme(self, name):
        """
        Apply new colorscheme. (By name.)
        """
        assert name in self.code_styles

        self._current_code_style_name = name
        self._current_style = self._generate_style()

    def install_ui_colorscheme(self, name, style_dict):
        """
        Install a new UI color scheme.
        """
        assert isinstance(name, six.text_type)
        assert isinstance(style_dict, dict)

        self.ui_styles[name] = style_dict

    def use_ui_colorscheme(self, name):
        """
        Apply new colorscheme. (By name.)
        """
        assert name in self.ui_styles

        self._current_ui_style_name = name
        self._current_style = self._generate_style()

    def _generate_style(self):
        """
        Create new Style instance.
        (We don't want to do this on every key press, because each time the
        renderer receives a new style class, he will redraw everything.)
        """
        return generate_style(self.code_styles[self._current_code_style_name],
                              self.ui_styles[self._current_ui_style_name])

    def _create_options(self):
        """
        Create a list of `Option` instances for the options sidebar.
        """
        def enable(attribute, value=True):
            setattr(self, attribute, value)

            # Return `True`, to be able to chain this in the lambdas below.
            return True

        def disable(attribute):
            setattr(self, attribute, False)
            return True

        def simple_option(title, description, field_name, values=None):
            " Create Simple on/of option. "
            values = values or ['off', 'on']

            def get_current_value():
                return values[bool(getattr(self, field_name))]

            def get_values():
                return {
                    values[1]: lambda: enable(field_name),
                    values[0]: lambda: disable(field_name),
                }

            return Option(title=title, description=description,
                          get_values=get_values,
                          get_current_value=get_current_value)

        return [
            OptionCategory('Input', [
                simple_option(title='Input mode',
                              description='Vi or emacs key bindings.',
                              field_name='vi_mode',
                              values=['emacs', 'vi']),
                simple_option(title='Paste mode',
                              description="When enabled, don't indent automatically.",
                              field_name='paste_mode'),
                Option(title='Complete while typing',
                       description="Generate autocompletions automatically while typing. "
                                   'Don\'t require pressing TAB. (Not compatible with "History search".)',
                       get_current_value=lambda: ['off', 'on'][self.complete_while_typing],
                       get_values=lambda: {
                           'on': lambda: enable('complete_while_typing') and disable('enable_history_search'),
                           'off': lambda: disable('complete_while_typing'),
                       }),
                Option(title='History search',
                       description='When pressing the up-arrow, filter the history on input starting '
                                   'with the current text. (Not compatible with "Complete while typing".)',
                       get_current_value=lambda: ['off', 'on'][self.enable_history_search],
                       get_values=lambda: {
                           'on': lambda: enable('enable_history_search') and disable('complete_while_typing'),
                           'off': lambda: disable('enable_history_search'),
                       }),
                simple_option(title='Mouse support',
                              description='Respond to mouse clicks and scrolling for positioning the cursor, '
                                          'selecting text and scrolling through windows.',
                              field_name='enable_mouse_support'),
                simple_option(title='Confirm on exit',
                              description='Require confirmation when exiting.',
                              field_name='confirm_exit'),
                simple_option(title='Input validation',
                              description='In case of syntax errors, move the cursor to the error '
                                          'instead of showing a traceback of a SyntaxError.',
                              field_name='enable_input_validation'),
                simple_option(title='Auto suggestion',
                              description='Auto suggest inputs by looking at the history. '
                                          'Pressing right arrow or Ctrl-E will complete the entry.',
                              field_name='enable_auto_suggest'),
                Option(title='Accept input on enter',
                       description='Amount of ENTER presses required to execute input when the cursor '
                                   'is at the end of the input. (Note that META+ENTER will always execute.)',
                       get_current_value=lambda: str(self.accept_input_on_enter or 'meta-enter'),
                       get_values=lambda: {
                           '2': lambda: enable('accept_input_on_enter', 2),
                           '3': lambda: enable('accept_input_on_enter', 3),
                           '4': lambda: enable('accept_input_on_enter', 4),
                           'meta-enter': lambda: enable('accept_input_on_enter', None),
                       }),
            ]),
            OptionCategory('Display', [
                Option(title='Completions',
                       description='Visualisation to use for displaying the completions. (Multiple columns, one column, a toolbar or nothing.)',
                       get_current_value=lambda: self.completion_visualisation,
                       get_values=lambda: {
                           CompletionVisualisation.NONE: lambda: enable('completion_visualisation', CompletionVisualisation.NONE),
                           CompletionVisualisation.POP_UP: lambda: enable('completion_visualisation', CompletionVisualisation.POP_UP),
                           CompletionVisualisation.MULTI_COLUMN: lambda: enable('completion_visualisation', CompletionVisualisation.MULTI_COLUMN),
                           CompletionVisualisation.TOOLBAR: lambda: enable('completion_visualisation', CompletionVisualisation.TOOLBAR),
                       }),
                Option(title='Prompt',
                       description="Visualisation of the prompt. ('>>>' or 'In [1]:')",
                       get_current_value=lambda: self.prompt_style,
                       get_values=lambda: dict((s, partial(enable, 'prompt_style', s)) for s in self.all_prompt_styles)),
                simple_option(title='Blank line after output',
                              description='Insert a blank line after the output.',
                              field_name='insert_blank_line_after_output'),
                simple_option(title='Show signature',
                              description='Display function signatures.',
                              field_name='show_signature'),
                simple_option(title='Show docstring',
                              description='Display function docstrings.',
                              field_name='show_docstring'),
                simple_option(title='Show line numbers',
                              description='Show line numbers when the input consists of multiple lines.',
                              field_name='show_line_numbers'),
                simple_option(title='Show Meta+Enter message',
                              description='Show the [Meta+Enter] message when this key combination is required to execute commands. ' +
                                  '(This is the case when a simple [Enter] key press will insert a newline.',
                              field_name='show_meta_enter_message'),
                simple_option(title='Wrap lines',
                              description='Wrap lines instead of scrolling horizontally.',
                              field_name='wrap_lines'),
                simple_option(title='Show status bar',
                              description='Show the status bar at the bottom of the terminal.',
                              field_name='show_status_bar'),
                simple_option(title='Show sidebar help',
                              description='When the sidebar is visible, also show this help text.',
                              field_name='show_sidebar_help'),
                simple_option(title='Highlight parenthesis',
                              description='Highlight matching parenthesis, when the cursor is on or right after one.',
                              field_name='highlight_matching_parenthesis'),
            ]),
            OptionCategory('Colors', [
                Option(title='Code',
                       description='Color scheme to use for the Python code.',
                       get_current_value=lambda: self._current_code_style_name,
                       get_values=lambda: dict(
                            (name, partial(self.use_code_colorscheme, name)) for name in self.code_styles)
                       ),
                Option(title='User interface',
                       description='Color scheme to use for the user interface.',
                       get_current_value=lambda: self._current_ui_style_name,
                       get_values=lambda: dict(
                            (name, partial(self.use_ui_colorscheme, name)) for name in self.ui_styles)
                       ),
                simple_option(title='True color (24 bit)',
                              description='Use 24 bit colors instead of 265 colors',
                              field_name='true_color'),
            ]),
        ]

    def create_application(self):
        """
        Create an `Application` instance for use in a `CommandLineInterface`.
        """
        buffers = {
            'docstring': Buffer(read_only=True),
        }
        buffers.update(self._extra_buffers or {})

        return Application(
            layout=create_layout(
                self,
                self.key_bindings_manager,
                lexer=self._lexer,
                input_buffer_height=self._input_buffer_height,
                extra_buffer_processors=self._extra_buffer_processors,
                extra_body=self._extra_layout_body,
                extra_toolbars=self._extra_toolbars),
            buffer=self._create_buffer(),
            buffers=buffers,
            key_bindings_registry=self.key_bindings_registry,
            paste_mode=Condition(lambda cli: self.paste_mode),
            mouse_support=Condition(lambda cli: self.enable_mouse_support),
            on_abort=AbortAction.RETRY,
            on_exit=self._on_exit,
            style=DynamicStyle(lambda: self._current_style),
            get_title=lambda: self.terminal_title,
            on_initialize=self._on_cli_initialize,
            on_start=self._on_start,
            on_input_timeout=self._on_input_timeout)

    def _create_buffer(self):
        """
        Create the `Buffer` for the Python input.
        """
        def is_buffer_multiline():
            return (self.paste_mode or
                    self.accept_input_on_enter is None or
                    document_is_multiline_python(python_buffer.document))

        python_buffer = Buffer(
            is_multiline=Condition(is_buffer_multiline),
            complete_while_typing=Condition(lambda: self.complete_while_typing),
            enable_history_search=Condition(lambda: self.enable_history_search),
            tempfile_suffix='.py',
            history=self.history,
            completer=self._completer,
            validator=ConditionalValidator(
                self._validator,
                Condition(lambda: self.enable_input_validation)),
            auto_suggest=ConditionalAutoSuggest(
                AutoSuggestFromHistory(),
                Condition(lambda cli: self.enable_auto_suggest)),
            accept_action=self._accept_action)

        return python_buffer

    def _on_cli_initialize(self, cli):
        """
        Called when a CommandLineInterface has been created.
        """
        # Synchronize PythonInput state with the CommandLineInterface.
        def synchronize(_=None):
            if self.vi_mode:
                cli.editing_mode = EditingMode.VI
            else:
                cli.editing_mode = EditingMode.EMACS

        cli.input_processor.beforeKeyPress += synchronize
        cli.input_processor.afterKeyPress += synchronize
        synchronize()

    def _on_input_timeout(self, cli):
        """
        When there is no input activity,
        in another thread, get the signature of the current code.
        """
        if cli.current_buffer_name != DEFAULT_BUFFER:
            return

        # Never run multiple get-signature threads.
        if self._get_signatures_thread_running:
            return
        self._get_signatures_thread_running = True

        buffer = cli.current_buffer
        document = buffer.document

        def run():
            script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())

            # Show signatures in help text.
            if script:
                try:
                    signatures = script.call_signatures()
                except ValueError:
                    # e.g. in case of an invalid \\x escape.
                    signatures = []
                except Exception:
                    # Sometimes we still get an exception (TypeError), because
                    # of probably bugs in jedi. We can silence them.
                    # See: https://github.com/davidhalter/jedi/issues/492
                    signatures = []
                else:
                    # Try to access the params attribute just once. For Jedi
                    # signatures containing the keyword-only argument star,
                    # this will crash when retrieving it the first time with
                    # AttributeError. Every following time it works.
                    # See: https://github.com/jonathanslenders/ptpython/issues/47
                    #      https://github.com/davidhalter/jedi/issues/598
                    try:
                        if signatures:
                            signatures[0].params
                    except AttributeError:
                        pass
            else:
                signatures = []

            self._get_signatures_thread_running = False

            # Set signatures and redraw if the text didn't change in the
            # meantime. Otherwise request new signatures.
            if buffer.text == document.text:
                self.signatures = signatures

                # Set docstring in docstring buffer.
                if signatures:
                    string = signatures[0].docstring()
                    if not isinstance(string, six.text_type):
                        string = string.decode('utf-8')
                    cli.buffers['docstring'].reset(
                        initial_document=Document(string, cursor_position=0))
                else:
                    cli.buffers['docstring'].reset()

                cli.request_redraw()
            else:
                self._on_input_timeout(cli)

        cli.eventloop.run_in_executor(run)

    def on_reset(self, cli):
        self.key_bindings_manager.reset(cli)
        self.signatures = []

    def enter_history(self, cli):
        """
        Display the history.
        """
        cli.vi_state.input_mode = InputMode.NAVIGATION

        def done(result):
            if result is not None:
                cli.buffers[DEFAULT_BUFFER].document = result

            cli.vi_state.input_mode = InputMode.INSERT

        cli.run_sub_application(create_history_application(
            self, cli.buffers[DEFAULT_BUFFER].document), done)

class PythonCommandLineInterface(CommandLineInterface):
    def __init__(self, eventloop=None, python_input=None, input=None, output=None):
        assert python_input is None or isinstance(python_input, PythonInput)

        python_input = python_input or PythonInput()

        # Make sure that the prompt_toolkit 'renderer' knows about the
        # 'true_color' property of PythonInput.
        if output is None:
            output=create_output(true_color=Condition(lambda: python_input.true_color))

        super(PythonCommandLineInterface, self).__init__(
            application=python_input.create_application(),
            eventloop=eventloop,
            input=input,
            output=output)


text:
describe('qcode.actionConfirm plugin',() => {
    let page;

    beforeEach(async () => {
        page = await ready_page('qcode.actionConfirm.test.html');
        await page.setRequestInterception(true);
    });

    afterEach( () => page.close() );

    it('can be confirmed', async () => {
        const result = await page.evaluate(async () => {
            const link = document.getElementById('link');
            qcode.actionConfirm(link);

            link.dispatchEvent(new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                composed: true
            }));

            for (let button of document.getElementsByTagName('button')) {
                if ( button.innerHTML == 'Yes' ) {
                    button.dispatchEvent(
                        new MouseEvent('click', {
                            bubbles: true,
                            cancelable: true,
                            composed: true
                        })
                    );
                    return window.location.hash;
                }
            }
            return "NOT FOUND";
        });

        expect(result).toBe('#test');
    });

    it('can be cancelled', async () => {
        const result = await page.evaluate(() => {
            const link = document.getElementById('link');
            qcode.actionConfirm(link);

            link.dispatchEvent(
                new MouseEvent('click', {
                    bubbles: true,
                    cancelable: true,
                    composed: true
                })
            );

            for (let button of document.getElementsByTagName('button')) {
                if ( button.innerHTML == 'No' ) {
                    button.dispatchEvent(new MouseEvent('click'));
                    return window.location.hash;
                }
            }
            return "NOT FOUND";
        });

        expect(result).toBe('');
    });
});

redpajama_set_name: RedPajamaGithub


text:
using Xunit;

namespace System.Reflection.Tests
{
    // ContainsGenericParameters
    public class MethodBaseContainsGenericParameters
    {
        public class TestClass
        {
            public TestClass()
            {
            }

            public TestClass(int val)
            {
            }

            public void TestGenericMethod<T>(T p1)
            {
            }

            public void TestMethod(int val)
            {
            }

            public void TestMethod2(int val)
            {
            }
            public void TestMethod2(int val1, float val2, string val3)
            {
            }

            public void TestPartialGenericMethod<T>(int val, T p1)
            {
            }

            public T TestGenericReturnTypeMethod<T>()
            {
                T ret = default(T);

                return ret;
            }
        }

        public class TestGenericClass<T>
        {
            public TestGenericClass()
            {
            }

            public TestGenericClass(T val)
            {
            }

            public TestGenericClass(T p, int val)
            {
            }

            public void TestMethod(T p1)
            {
            }

            public void TestMultipleGenericMethod<U>(U p2)
            {
            }

            public void TestVoidMethod()
            {
            }
        }

        // Positive Test 1: ContainsGenericParameters should return true for open generic method
        [Fact]
        public void PosTest1()
        {
            Type type = typeof(TestClass);
            MethodBase methodInfo = type.GetMethod("TestGenericMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for open generic method" + methodInfo);
        }

        // Positive Test 2: ContainsGenericParameters should return false for a closed generic method
        [Fact]
        public void PosTest2()
        {
            Type type = typeof(TestClass);
            MethodInfo methodInfo = type.GetMethod("TestGenericMethod");
            MethodBase genericMethodInfo = methodInfo.MakeGenericMethod(typeof(int));
            Assert.False(genericMethodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for closed generic method");
        }

        // Positive Test 3: ContainsGenericParameters should return false for a non generic method
        [Fact]
        public void PosTest3()
        {
            Type type = typeof(TestClass);
            MethodBase methodInfo = type.GetMethod("TestMethod");
            Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for non generic method");
        }

        // Positive Test 4: ContainsGenericParameters should return true for a generic method contains non generic parameter
        [Fact]
        public void PosTest4()
        {
            Type type = typeof(TestClass);
            MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method contains non generic parameter" + methodInfo);
        }

        // Positive Test 5: ContainsGenericParameters should return true for a generic method only contains generic return type
        [Fact]
        public void PosTest5()
        {
            Type type = typeof(TestClass);
            MethodBase methodInfo = type.GetMethod("TestPartialGenericMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method only contains generic return type" + methodInfo);
        }

        // Positive Test 6: ContainsGenericParameters should return false for a generic method in a closed generic type
        [Fact]
        public void PosTest6()
        {
            Type type = typeof(TestGenericClass<int>);
            MethodBase methodInfo = type.GetMethod("TestMethod");
            Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a generic method in a closed generic type");
        }

        // Positive Test 7: ContainsGenericParameters should return true for a method in a opened generic type
        [Fact]
        public void PosTest7()
        {
            Type type = typeof(TestGenericClass<>);
            MethodBase methodInfo = type.GetMethod("TestMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a method in a opened generic type" + methodInfo);
        }

        // Positive Test 8: ContainsGenericParameters should return true for a generic method in a opened generic type
        [Fact]
        public void PosTest8()
        {
            Type type = typeof(TestGenericClass<>);
            MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a opened generic type" + methodInfo);
        }

        // Positive Test 9: ContainsGenericParameters should return true for a generic method in a closed generic type
        [Fact]
        public void PosTest9()
        {
            Type type = typeof(TestGenericClass<int>);
            MethodBase methodInfo = type.GetMethod("TestMultipleGenericMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a closed generic type" + methodInfo);
        }

        // Positive Test 10: ContainsGenericParameters should return true for a method in a generic type
        [Fact]
        public void PosTest10()
        {
            Type type = typeof(TestGenericClass<>);
            MethodBase methodInfo = type.GetMethod("TestVoidMethod");
            Assert.True(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns false for a generic method in a generic type" + methodInfo);
        }

        // Positive Test 11: ContainsGenericParameters should return false for a method in a closed generic type
        [Fact]
        public void PosTest11()
        {
            Type type = typeof(TestGenericClass<int>);
            MethodBase methodInfo = type.GetMethod("TestVoidMethod");
            Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a generic method in a closed generic type");
        }

        // Positive Test 12: ContainsGenericParameters should return false for a constructor in a non generic type
        [Fact]
        public void PosTest12()
        {
            Type type = typeof(TestClass);
            MethodBase methodInfo = type.GetConstructor(new Type[] { });
            Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type");

            methodInfo = type.GetConstructor(new Type[] { typeof(int) });
            Assert.False(methodInfo.ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor in a non generic type");
        }

        // Positive Test 13: ContainsGenericParameters should return false for a constructor in a open generic type
        [Fact]
        public void PosTest13()
        {
            Type type = typeof(TestGenericClass<>);
            MethodBase[] ctors = type.GetConstructors();
            for (int i = 0; i < ctors.Length; ++i)
            {
                // ContainsGenericParameters should behave same for both methods and constructors.
                // If method/ctor or the declaring type contains uninstantiated open generic parameter,
                // ContainsGenericParameters should return true.  (Which also means we can't invoke that type)
                Assert.True(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns false for a constructor" + ctors[i] + " in a open generic type ");
            }
        }

        // Positive Test 14: ContainsGenericParameters should return false for a constructor in a closed generic type
        [Fact]
        public void PosTest14()
        {
            Type type = typeof(TestGenericClass<int>);
            MethodBase[] ctors = type.GetConstructors();
            for (int i = 0; i < ctors.Length; ++i)
            {
                Assert.False(ctors[i].ContainsGenericParameters, "ContainsGenericParameters returns true for a constructor" + ctors[i] + " in a closed generic type");
            }
        }

        // Positive Test 15: Exercise GetMethod(name, Type [])
        [Fact]
        public void PosTest15()
        {
            Type type = typeof(TestClass);
            MethodInfo specificMethod = type.GetMethod("TestMethod2", new Type[] { typeof(int), typeof(float), typeof(string) });
            Assert.NotNull(specificMethod);
        }
    }
}


text:
package org.gradoop.flink.model.impl.functions.tuple;

import org.apache.flink.api.common.functions.MapFunction;
import org.gradoop.flink.model.impl.tuples.WithCount;

/**
 * (object, count) => object
 * @param <T>
 */
public class ValueOfWithCount<T> implements MapFunction<WithCount<T>, T> {

  @Override
  public T map(WithCount<T> value) throws Exception {
    return value.getObject();
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Alertas</title>
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

Esta es nuestra alerta

Esta es nuestra alerta

Esta es nuestra alerta

Esta es nuestra alerta

					<button class="close" data-dismiss="alert">
						×
					</button>
					Alerta! Esta es nuestra alerta


text:
"""Tests for `DatasetCreator` with `Model.fit` across usages and strategies."""

import numpy as np
import tensorflow.compat.v2 as tf

from keras.distribute import dataset_creator_model_fit_test_base as test_base
from keras.distribute import strategy_combinations
from keras.testing_infra import test_utils
from keras.utils import dataset_creator

# isort: off
from tensorflow.python.framework import (
    test_util as tf_test_utils,
)

# TODO(rchao): Investigate why there cannot be single worker and multi worker
# PS strategies running in the same shard.
@test_utils.run_v2_only
@tf.__internal__.distribute.combinations.generate(
    tf.__internal__.test.combinations.combine(
        strategy=strategy_combinations.all_strategies
        + strategy_combinations.multi_worker_mirrored_strategies
        + strategy_combinations.parameter_server_strategies_multi_worker,
        mode="eager",
    )
)
class DatasetCreatorModelFitTest(test_base.DatasetCreatorModelFitTestBase):
    def setUp(self):
        super().setUp()
        if tf_test_utils.is_xla_enabled():
            self.skipTest(
                "model.optimizer.iterations values is not as expected "
                "with XLA: b/184384487"
            )

    def testModelFit(self, strategy):
        model = self._model_fit(strategy)
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitwithStepsPerEpochNegativeOne(self, strategy):
        def dataset_fn(input_context):
            del input_context
            x = tf.random.uniform((10, 10))
            y = tf.random.uniform((10,))
            return (
                tf.data.Dataset.from_tensor_slices((x, y)).shuffle(10).batch(2)
            )

        if strategy._should_use_with_coordinator:
            with self.assertRaises(
                (tf.errors.OutOfRangeError, tf.errors.CancelledError)
            ):
                self._model_fit(
                    strategy,
                    steps_per_epoch=-1,
                    x=dataset_creator.DatasetCreator(dataset_fn),
                    validation_data=dataset_creator.DatasetCreator(dataset_fn),
                )
        else:
            self._model_fit(
                strategy,
                steps_per_epoch=-1,
                x=dataset_creator.DatasetCreator(dataset_fn),
                validation_data=dataset_creator.DatasetCreator(dataset_fn),
            )

    def testModelFitWithNumpyData(self, strategy):
        x = np.random.rand(100, 10)
        y = np.random.rand(100, 1)
        model = self._model_fit(
            strategy,
            x=x,
            y=y,
            batch_size=1,
            validation_data=(x, y),
        )
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitWithTensorData(self, strategy):
        x = tf.random.uniform((100, 10))
        y = tf.random.uniform((100,))
        model = self._model_fit(
            strategy,
            x=x,
            y=y,
            batch_size=1,
            validation_data=(x, y),
        )
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitWithLookupLayer(self, strategy):
        model = self._model_fit(strategy, use_lookup_layer=True)
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitWithNormalizationLayer(self, strategy):
        model = self._model_fit(strategy, with_normalization_layer=True)
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitWithStepsPerExecution(self, strategy):
        model = self._model_fit(strategy, steps_per_execution=10)
        self.assertEqual(model.optimizer.iterations, 100)

    def testModelFitWithNoStepsPerEpoch(self, strategy):
        with self.assertRaisesRegex(
            ValueError,
            "When using a `tf.keras.utils.experimental.DatasetCreator`, "
            "`steps_per_epoch`, `validation_steps` or `steps` argument must be "
            "provided in `Model.fit`, `Model.evaluate`, or `Model.predict`.",
        ):
            self._model_fit(strategy, steps_per_epoch=None)

    def testModelEvaluate(self, strategy):
        self._model_evaluate(strategy)
        self.assertGreaterEqual(self._accuracy_metric.result(), 0.0)

    def testModelEvaluateWithNumpyData(self, strategy):
        x = np.random.rand(100, 10)
        y = np.random.rand(100, 1)
        self._model_evaluate(
            strategy,
            x=x,
            y=y,
            batch_size=1,
        )
        self.assertGreaterEqual(self._accuracy_metric.result(), 0.0)

    def testModelEvaluateWithTensorData(self, strategy):
        x = tf.random.uniform((100, 10))
        y = tf.random.uniform((100,))
        self._model_evaluate(
            strategy,
            x=x,
            y=y,
            batch_size=1,
        )
        self.assertGreaterEqual(self._accuracy_metric.result(), 0.0)

    def testModelEvaluateWithNormalizationLayer(self, strategy):
        self._model_evaluate(strategy, with_normalization_layer=True)
        self.assertGreaterEqual(self._accuracy_metric.result(), 0.0)

    def testModelEvaluateWithStepsPerExecution(self, strategy):
        self._model_evaluate(strategy, steps_per_execution=10)
        self.assertGreaterEqual(self._accuracy_metric.result(), 0.0)

    def testModelEvaluateWithNoStepsPerEpoch(self, strategy):
        with self.assertRaisesRegex(
            ValueError,
            "When using a `tf.keras.utils.experimental.DatasetCreator`, "
            "`steps_per_epoch`, `validation_steps` or `steps` argument must be "
            "provided in `Model.fit`, `Model.evaluate`, or `Model.predict`.",
        ):
            self._model_evaluate(strategy, steps=None)

    def testModelPredict(self, strategy):
        _, predictions = self._model_predict(strategy, steps=3)
        # Check the first (0th index), fourth (3rd index) and the last
        # predictions because the first, fourth and the last input are the same
        # in `model.predict` so there predictions should match.
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )

        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelPredictWithNumpyData(self, strategy):
        x = np.array([[1.0], [2.0], [3.0], [1.0], [5.0], [1.0]])
        _, predictions = self._model_predict(strategy, test_data=x)

        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )
        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelPredictWithTensorData(self, strategy):
        x = tf.constant([[1.0], [2.0], [3.0], [1.0], [5.0], [1.0]])
        _, predictions = self._model_predict(strategy, test_data=x)
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )
        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelPredictWithNormalizationLayer(self, strategy):
        _, predictions = self._model_predict(
            strategy, with_normalization_layer=True, steps=3
        )
        # Check the first (0th index), fourth (3rd index) and the last
        # predictions because the first, fourth and the last input is the same
        # in `model.predict` so there predictions should match.
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )

        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelPredictWithStepsPerExecution(self, strategy):
        _, predictions = self._model_predict(
            strategy, steps_per_execution=3, steps=3
        )

        # Check the first (0th index), fourth (3rd index) and the last
        # predictions because the first, fourth and the last input is the same
        # in `model.predict` so there predictions should match.
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )

        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelFitAndPredict(self, strategy):
        def fit_dataset_fn(input_context):
            del input_context
            x = tf.random.uniform((10, 1))
            y = tf.random.uniform((10,))
            return (
                tf.data.Dataset.from_tensor_slices((x, y))
                .shuffle(10)
                .repeat()
                .batch(2)
            )

        x = dataset_creator.DatasetCreator(fit_dataset_fn)
        validation_data = dataset_creator.DatasetCreator(fit_dataset_fn)

        model = self._model_fit(strategy, x=x, validation_data=validation_data)
        _, predictions = self._model_predict(strategy, model, steps=3)

        # Check the first (0th index), fourth (3rd index) and the last
        # predictions because the first, fourth and the last input is the same
        # in `model.predict` so there predictions should match.
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )

        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelPredictWithDatasetCreator(self, strategy):
        if isinstance(strategy, tf.distribute.MultiWorkerMirroredStrategy):
            self.skipTest("b/189223991")

        def _dataset_fn(input_context):
            del input_context
            x = tf.constant([[1.0], [2.0], [3.0], [1.0], [5.0], [1.0]])
            return tf.data.Dataset.from_tensor_slices(x).repeat().batch(2)

        _, predictions = self._model_predict(
            strategy,
            steps=3,
            test_data=dataset_creator.DatasetCreator(_dataset_fn),
        )

        # Check the first (0th index), fourth (3rd index) and the last
        # predictions because the first, fourth and the last input is the same
        # in `model.predict` so there predictions should match.
        self.assertTrue(
            all(predictions[0] == predictions[i] for i in [0, 3, 5])
        )

        self.assertFalse(
            all(predictions[0] == predictions[i] for i in [0, 1, 2, 4])
        )

    def testModelTrainTFFunction(self, strategy):
        model = self._model_fit(strategy)
        self.assertIsInstance(
            model.train_tf_function, tf.__internal__.function.Function
        )

if __name__ == "__main__":
    tf.__internal__.distribute.multi_process_runner.test_main()


text:
<?php

// Produces: DROP TABLE `table_name` CASCADE
$forge->dropTable('table_name', false, true);


text:
if Role.count == 0
  super_role = Role.create! name: "superuser", title: "Super User"
  Role.create! name: "normal", title: "User"
  Role.create! name: "lecturer", title: "Lecturer"
  Role.create! name: "ta", title: "Teaching Assistant"
  Role.create! name: "student", title: "Student"
end

if Role.count == 5
  Role.create! name: "shared", title: "Previewer"
end

if User.count == 0
  admin = User.create!(name: "Admin", email: "jfdi@academy.com",
                       password: "supersecretpass",
                       password_confirmation: "supersecretpass")
  admin.system_role_id = super_role.id
  admin.skip_confirmation!
  admin.save!
end

if Action.count == 0
  Action.create! text: "attempted", description: "actor attempted obj (assignment)"
  Action.create! text: "commented on", description: "actor commented on object"
  Action.create! text: "created", description: "actor created object (achievement, level)"
  Action.create! text: "earned", description: "actor earned object (achievement, title, level)"
  Action.create! text: "published", description: "actor published object"
  Action.create! text: "replied to", description: "actor replied object"
  Action.create! text: "started", description: "actor started obj (assignment, training)"
end

if ThemeAttribute.count == 0
  ThemeAttribute.create! name: "Background Color",
                         description: "Background color of the page",
                         value_type: "color"
  ThemeAttribute.create! name: "Background Image",
                         description: "Background image. It will be added to the bottom of the page",
                         value_type: "image"
  ThemeAttribute.create! name: "Sidebar Link Color",
                         description: "Color of the navigation links",
                         value_type: "color"
  ThemeAttribute.create! name: "Announcements Icon",
                         description: "Icon for the Announcements navigation link on the sidebar",
                         value_type: "image"
  ThemeAttribute.create! name: "Missions Icon",
                         description: "Icon for the Mission navigation link on the sidebar",
                         value_type: "image"
  ThemeAttribute.create! name: "Trainings Icon",
                         description: "Icon for the Trainings navigation link on the sidebar",
                         value_type: "image"
  ThemeAttribute.create! name: "Submissions Icon",
                         description: "Icon for the Submissions navigation link on the sidebar",
                         value_type: "image"
  ThemeAttribute.create! name: "Leaderboards Icon",
                         description: "Icon for the Leaderboard navigation link on the sidebar",
                         value_type: "image"
end

if ThemeAttribute.count == 8
  ThemeAttribute.create! name: "Custom CSS",
                         description: "Custom style sheet rules",
                         value_type: "text"
end

if PreferableItem.count == 0

  #Missions
  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "title",
                         default_value: "Mission",
                         description:   "Mission title",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "tag",
                         default_value: "Tag",
                         description:   "Mission tags" ,
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "exp",
                         default_value: "Max Exp",
                         description:   "Mission exp gainable",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "award",
                         default_value: "Requirement for",
                         description:   "Requirement for achievement",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "start",
                         default_value: "Start Time",
                         description:   "Mission start time",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Column",
                         name:          "end",
                         default_value: "End Time",
                         description:   "Mission end time",
                         default_display: true

  #Training
  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "title",
                         default_value: "Training",
                         description:   "Training title",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "tag",
                         default_value: "Tag",
                         description:   "Training tags",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "exp",
                         default_value: "Max Exp",
                         description:   "Training exp gainable",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "award",
                         default_value: "Requirement for",
                         description:   "Requirement for achievement",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "start",
                         default_value: "Start Time",
                         description:   "Training start time",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "end",
                         default_value: "End Time",
                         description:   "Training end time",
                         default_display: false

  #SideBar  - students
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "announcements",
                         default_value: "Announcements",
                         description:   "Course announcements",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "missions",
                         default_value: "Missions",
                         description:   "Course missions",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "trainings",
                         default_value: "Trainings",
                         description:   "Course trainings",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "submissions",
                         default_value: "Submissions",
                         description:   "All submissions",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "achievements",
                         default_value: "Achievements",
                         description:   "Show all achievements",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "leaderboard",
                         default_value: "Leaderboard",
                         description:   "Show leaderboard",
                         default_display: true

  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "students",
                         default_value: "Students",
                         description:   "Show all students",
                         default_display: true
end

if PreferableItem.count == 19

  PreferableItem.create! item:          "Training",
                         item_type:     "Time",
                         name:          "time_format",
                         default_value: "%d-%m-%Y",
                         description:   "Training time display format",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Time",
                         name:          "time_format",
                         default_value: "%d-%m-%Y",
                         description:   "Mission time display format",
                         default_display: true

end

if PreferableItem.count == 21
  #notification email preference

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_comment",
                         default_value: "New Comment",
                         description:   "Notify user when someone commented on his/her thread",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_grading",
                         default_value: "New Grading",
                         description:   "Notify student for new available mission grading",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_submission",
                         default_value: "New Submission",
                         description:   "Notify student's tutor for new mission submission",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_student",
                         default_value: "New Student",
                         description:   "Notify students when their enrollment request is approved",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_enroll_request",
                         default_value: "New Enroll Request",
                         description:   "Notify lecturer(s) for new enrollment request",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_announcement",
                         default_value: "New Announcement",
                         description:   "Notify all staff and students for new announcement",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_mission",
                         default_value: "New Mission",
                         description:   "Notify all staff and students for new mission available",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "new_training",
                         default_value: "New Training",
                         description:   "Notify all staff and students for new training available",
                         default_display: true

  PreferableItem.create! item:          "Email",
                         item_type:     "Course",
                         name:          "mission_due",
                         default_value: "Mission Reminder",
                         description:   "Mission due reminder for students who didn't submit yet",
                         default_display: true

end

if PreferableItem.count == 30
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "comments",
                         default_value: "Comments",
                         description:   "Show comments summary",
                         default_display: true
end

if PreferableItem.count == 31
  PreferableItem.create! item:          "Mcq",
                         item_type:     "AutoGrader",
                         name:          "title",
                         default_value: "default",
                         description:   "The Auto Grader used to grade MCQ Question",
                         default_display: true

end

if Action.count == 7
  Action.create! text: "reached",
                 description: "actor reached obj (lvl)"
end

if PreferableItem.count == 32
  PreferableItem.create! item:          "Training",
                         item_type:     "Re-attempt",
                         name:          "title",
                         default_value: "20",
                         description:   "Enable Re-attempt allows students to do training again to get a fraction of the full EXP.",
                         default_display: true
end

if PreferableItem.count == 33
  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "bonus-exp",
                         default_value: "Bonus EXP",
                         description:   "Bonus exp for finishing early",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Column",
                         name:          "bonus-cutoff",
                         default_value: "Bonus Cutoff",
                         description:   "Bonus cutoff time",
                         default_display: true
end

if PreferableItem.count == 35

  PreferableItem.create!  item:          "Leaderboard",
                          item_type:     "Display",
                          name:          "leaders",
                          default_value: "10",
                          description:   "Number of students to show in leaderboard",
                          default_display: true

  PreferableItem.create! item:            "CourseHome",
                         item_type:       "Section",
                         name:            "announcements",
                         default_value:   "Announcements",
                         description:     "Show recent announcements in course home page",
                         default_display: true

  PreferableItem.create! item:            "CourseHome",
                         item_type:       "Section",
                         name:            "activities",
                         default_value:   "Notable Happenings",
                         description:     "Show recent student activities",
                         default_display: true

  PreferableItem.create! item:          "Training",
                         item_type:     "Table",
                         name:          "paging",
                         default_value: "10",
                         description:   "Number of rows to display in training table",
                         default_display: true

  PreferableItem.create! item:          "Mission",
                         item_type:     "Table",
                         name:          "paging",
                         default_value: "10",
                         description:   "Number of rows to display in mission table",
                         default_display: true

end

if PreferableItem.count == 40

  PreferableItem.create! item:            "CourseHome",
                         item_type:       "SectionShow",
                         name:            "announcements_no",
                         default_value:   "3",
                         description:     "No of recent announcements to show in course home page",
                         default_display: true

  PreferableItem.create! item:            "CourseHome",
                         item_type:       "SectionShow",
                         name:            "activities_no",
                         default_value:   "50",
                         description:     "No of recent activities to show in course home page",
                         default_display: true
end

if PreferableItem.count == 42

  PreferableItem.create! item:            "Announcements",
                         item_type:       "List",
                         name:            "paging",
                         default_value:   "10",
                         description:     "Number of announcements to display per page",
                         default_display: true

end

if PreferableItem.count == 43

  PreferableItem.create! item:            "Achievements",
                         item_type:       "Icon",
                         name:            "locked",
                         default_value:   "",
                         description:     "Locked achievements icon display type",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Announcements",
                         name:            "Announcements",
                         default_value:   "50",
                         description:     "Number of announcements to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Missions",
                         name:            "Missions",
                         default_value:   "50",
                         description:     "Number of missions to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "MissionStats",
                         name:            "Mission Statistics",
                         default_value:   "50",
                         description:     "Number of students to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Trainings",
                         name:            "Trainings",
                         default_value:   "50",
                         description:     "Number of trainings to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "TrainingStats",
                         name:            "Training Statistics",
                         default_value:   "50",
                         description:     "Number of students to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "MissionSubmissions",
                         name:            "Mission Submissions",
                         default_value:   "50",
                         description:     "Number of mission submissions to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "TrainingSubmissions",
                         name:            "Training Submissions",
                         default_value:   "50",
                         description:     "Number of training submissions to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Comments",
                         name:            "Comments",
                         default_value:   "50",
                         description:     "Number of topics to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Achievements",
                         name:            "Achievements",
                         default_value:   "50",
                         description:     "Number of achievements to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "Students",
                         name:            "Students",
                         default_value:   "50",
                         description:     "Number of students to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "ManageStudents",
                         name:            "Manage Students",
                         default_value:   "50",
                         description:     "Number of students to display per page",
                         default_display: true

  PreferableItem.create! item:            "Paging",
                         item_type:       "StudentSummary",
                         name:            "Student Summary",
                         default_value:   "50",
                         description:     "Number of students to display per page",
                         default_display: true

end

if PreferableItem.count == 56
  PreferableItem.create! item:          "Mission",
                         item_type:     "Submission",
                         name:          "auto",
                         default_value: "",
                         description:   "Auto create submissions for missions, special feature for courses that just want to take advantage of Coursemology's social features",
                         default_display: false

end

if SurveyQuestionType.count == 0
  SurveyQuestionType.create! title:         "MCQ",
                             description:   "Multiple Choice Question"

  SurveyQuestionType.create! title:         "MRQ",
                             description:   "Multiple Response Question"

  SurveyQuestionType.create! title:         "Essay",
                             description:   "Essay"

end

if PreferableItem.count == 57
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "surveys",
                         default_value: "Surveys",
                         description:   "Course surveys",
                         default_display: true
end

if PreferableItem.count == 58
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "materials",
                         default_value: "Workbin",
                         description:   "All course materials uploaded",
                         default_display: true
end

if PreferableItem.count == 59
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "lesson_plan",
                         default_value: "Lesson Plan",
                         description:   "Lesson Plan",
                         default_display: true
end

if PreferableItem.count == 60
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "forums",
                         default_value: "Forums",
                         description:   "Discussion Forums",
                         default_display: true
end

if PreferableItem.count == 61
  PreferableItem.create! item:            "Paging",
                         item_type:       "Forums",
                         name:            "Forums",
                         default_value:   "20",
                         description:     "Number of topics to display per forum page",
                         default_display: true
end

if PreferableItem.count == 62
  PreferableItem.create! item:            "Sidebar",
                         item_type:       "Other",
                         name:            "ranking",
                         default_value:   "",
                         description:     "Student's level and achievement status",
                         default_display: true
end

if Action.count == 8
  Action.create! text: 'created Forum topic', description: 'actor created Forum topic'
  Action.create! text: 'asked', description: 'actor asked Forum question'
  Action.create! text: 'voted on', description: 'actor voted on Forum post'
end

if AssignmentDisplayMode.count == 0
  AssignmentDisplayMode.create! title: "Single Page", description: 'Put all questions in a single page'
  AssignmentDisplayMode.create! title: "Tab", description: 'Put each question under one tab'
end

if PreferableItem.count == 63
  PreferableItem.create! item:          "Sidebar",
                         item_type:     "Student",
                         name:          "comics",
                         default_value: "Comics",
                         description:   "Comics",
                         default_display: true
end

if NavbarLinkType.count == 0
  NavbarLinkType.create! link_type: 'module'
  NavbarLinkType.create! link_type: 'admin'
end

if NavbarPreferableItem.count == 0
  NavbarPreferableItem.create! item:  "announcements",
                               navbar_link_type_id:  1,
                               name: "Announcements",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course announcements",
                               pos: 1

  NavbarPreferableItem.create! item:  "missions",
                               navbar_link_type_id:  1,
                               name: "Missions",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course missions",
                               pos: 2

  NavbarPreferableItem.create! item:  "trainings",
                               navbar_link_type_id:  1,
                               name: "Trainings",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course trainings",
                               pos: 3

  NavbarPreferableItem.create! item:  "submissions",
                               navbar_link_type_id:  1,
                               name: "Submissions",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course submissions",
                               pos: 4

  NavbarPreferableItem.create! item:  "achievements",
                               navbar_link_type_id:  1,
                               name: "Achievements",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course achievements",
                               pos: 5

  NavbarPreferableItem.create! item:  "comments",
                               navbar_link_type_id:  1,
                               name: "Comments",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course comments",
                               pos: 6

  NavbarPreferableItem.create! item:  "leaderboard",
                               navbar_link_type_id:  1,
                               name: "Leaderboard",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course leaderboard",
                               pos: 7

  NavbarPreferableItem.create! item:  "students",
                               navbar_link_type_id:  1,
                               name: "Students",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course students",
                               pos: 8

  NavbarPreferableItem.create! item:  "lesson_plan",
                               navbar_link_type_id:  1,
                               name: "Lesson Plan",
                               is_displayed: false,
                               is_enabled: false,
                               description: "course lesson plan",
                               pos: 9

  NavbarPreferableItem.create! item:  "materials",
                               navbar_link_type_id:  1,
                               name: "Materials",
                               is_displayed: false,
                               is_enabled: false,
                               description: "course materials",
                               pos: 10

  NavbarPreferableItem.create! item:  "forums",
                               navbar_link_type_id:  1,
                               name: "Forums",
                               is_displayed: false,
                               is_enabled: false,
                               description: "course forums",
                               pos: 11

  NavbarPreferableItem.create! item:  "surveys",
                               navbar_link_type_id:  1,
                               name: "Surveys",
                               is_displayed: false,
                               is_enabled: false,
                               description: "course surveys",
                               pos: 12

end

if NavbarPreferableItem.count == 12
  NavbarPreferableItem.create! item:  "comics",
                               navbar_link_type_id:  1,
                               name: "Comics",
                               is_displayed: false,
                               is_enabled: false,
                               description: "course comics",
                               pos: 13
end

if NavbarPreferableItem.count == 13
  NavbarPreferableItem.create! item:  "topicconcepts",
                               navbar_link_type_id:  1,
                               name: "Topic - Concept",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course topicconcept",
                               pos: 14
end

if NavbarPreferableItem.count == 14
  NavbarPreferableItem.create! item:  "realtime_sessions",
                               navbar_link_type_id:  1,
                               name: "Realtime Session",
                               is_displayed: true,
                               is_enabled: true,
                               description: "course realtime session",
                               pos: 15
end

if ProgrammingLanguage.count == 0
  ProgrammingLanguage.create!({name: "Python",
                              codemirror_mode: "python",
                              version:  "3.3",
                              cmd: "python3.3"}, :without_protection => true)

end

if ProgrammingLanguage.count == 1
  ProgrammingLanguage.create!({name: "Python",
                               codemirror_mode: "python",
                               version:  "3.4",
                               cmd: "python3.4"}, :without_protection => true)

end

if PreferableItem.count == 64
	PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Time",
                         name:          "time_format",
                         default_value: "%d-%m-%Y",
                         description:   "Policy Mission time display format",
                         default_display: true
end

if PreferableItem.count == 65
	PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Table",
                         name:          "paging",
                         default_value: "10",
                         description:   "Number of rows to display in policy mission table",
                         default_display: true
end

if PreferableItem.count == 66
	PreferableItem.create! item:            "Paging",
                         item_type:       "Policy_Missions",
                         name:            "Policy Missions",
                         default_value:   "50",
                         description:     "Number of policy missions to display per page",
                         default_display: true
end

if PreferableItem.count == 67

  #Missions
  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "title",
                         default_value: "Regulated Training",
                         description:   "Policy Mission title",
                         default_display: true

  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "tag",
                         default_value: "Tag",
                         description:   "Policy Mission tags" ,
                         default_display: true

  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "exp",
                         default_value: "Max Exp",
                         description:   "Mission exp gainable",
                         default_display: true

  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "award",
                         default_value: "Requirement for",
                         description:   "Requirement for achievement",
                         default_display: true

  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "start",
                         default_value: "Start Time",
                         description:   "Mission start time",
                         default_display: true

  PreferableItem.create! item:          "Policy Mission",
                         item_type:     "Column",
                         name:          "end",
                         default_value: "End Time",
                         description:   "Mission end time",
                         default_display: true

end

if PreferableItem.count == 73
	PreferableItem.create! item:            "Paging",
                         item_type:       "Questions",
                         name:            "Question bank (related pages)",
                         default_value:   "20",
                         description:     "Number of questions to display per page",
                         default_display: true
end

if PreferableItem.count == 74
	PreferableItem.create! item:            "Login URL",
                         item_type:       "Students",
                         name:            "Student login url",
                         default_value:   "",
                         description:     "Number of questions to display per page",
                         default_display: true
end

if PreferableItem.count == 75

  #Realtime Training
  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "title",
                         default_value: "Realtime Training",
                         description:   "Realtime Training title",
                         default_display: true

  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "tag",
                         default_value: "Tag",
                         description:   "Realtime Training tags" ,
                         default_display: true

  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "exp",
                         default_value: "Max Exp",
                         description:   "Realtime Training exp gainable",
                         default_display: true

  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "award",
                         default_value: "Requirement for",
                         description:   "Requirement for achievement",
                         default_display: true

  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "start",
                         default_value: "Start Time",
                         description:   "Realtime Training start time",
                         default_display: true

  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Column",
                         name:          "end",
                         default_value: "End Time",
                         description:   "Realtime Training end time",
                         default_display: true

end

if PreferableItem.count == 81
  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Time",
                         name:          "time_format",
                         default_value: "%d-%m-%Y",
                         description:   "Realtime Training time display format",
                         default_display: true
end

if PreferableItem.count == 82
  PreferableItem.create! item:          "Realtime Training",
                         item_type:     "Table",
                         name:          "paging",
                         default_value: "10",
                         description:   "Number of rows to display in Realtime Training table",
                         default_display: true
end

if PreferableItem.count == 83
  PreferableItem.create! item:            "Paging",
                         item_type:       "Realtime_Trainings",
                         name:            "Realtime Trainings",
                         default_value:   "50",
                         description:     "Number of Realtime Trainings to display per page",
                         default_display: true
end

if PreferableItem.count == 84

  #Realtime Training
  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "title",
                         default_value: "Realtime Session Group",
                         description:   "Realtime Session Group title",
                         default_display: true

  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "tag",
                         default_value: "Tag",
                         description:   "Realtime Session Group tags" ,
                         default_display: true

  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "exp",
                         default_value: "Max Exp",
                         description:   "Realtime Session Group exp gainable",
                         default_display: true

  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "award",
                         default_value: "Requirement for",
                         description:   "Requirement for achievement",
                         default_display: true

  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "start",
                         default_value: "Start Time",
                         description:   "Realtime Session Group start time",
                         default_display: true

  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Column",
                         name:          "end",
                         default_value: "End Time",
                         description:   "Realtime Session Group end time",
                         default_display: true

end

if PreferableItem.count == 90
  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Time",
                         name:          "time_format",
                         default_value: "%d-%m-%Y",
                         description:   "Realtime Session Group time display format",
                         default_display: true
end

if PreferableItem.count == 91
  PreferableItem.create! item:          "Realtime Session Group",
                         item_type:     "Table",
                         name:          "paging",
                         default_value: "10",
                         description:   "Number of rows to display in Realtime Session Group table",
                         default_display: true
end

if PreferableItem.count == 92
  PreferableItem.create! item:            "Paging",
                         item_type:       "Realtime_Session_Groups",
                         name:            "Realtime Session Groups",
                         default_value:   "50",
                         description:     "Number of Realtime Session Groups to display per page",
                         default_display: true
end


text:
package org.apache.ignite.lang;

import org.apache.ignite.internal.util.typedef.internal.*;
import org.pcollections.*;

import java.util.*;

/**
 *
 */
public class GridImmutableCollectionsPerfomanceTest {
    /** */
    private static final Random RND = new Random();

    /** */
    private static final int ITER_CNT = 100000;

    /**
     * @param args Args.
     */
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 5; j++) {
                // testArrayList();

                testPVector();

                testPVectorRemove();
            }
        }
    }

    /**
     *
     */
    private static void testArrayList() {
        System.gc();

        Collection<Integer> list = new ArrayList<>();

        long start = U.currentTimeMillis();

        for (int i = 0; i < ITER_CNT; i++) {
            Integer[] arr = new Integer[list.size() + 1];

            list.toArray(arr);

            arr[arr.length - 1] = RND.nextInt(100000);

            Collection<Integer> cp = Arrays.asList(arr);

            assert cp.size() - 1 == list.size();

            list = cp;
        }

        assert list.size() == ITER_CNT;

        System.out.println("Array list time: " + (U.currentTimeMillis() - start));
    }

    /**
     *
     */
    private static void testPVector() {
        System.gc();

        long start = U.currentTimeMillis();

        TreePVector<Integer> list = TreePVector.empty();

        for (int i = 0; i < ITER_CNT; i++) {
            TreePVector<Integer> cp = list.plus(RND.nextInt(100000));

            assert cp.size() - 1 == list.size();

            list = cp;
        }

        assert list.size() == ITER_CNT;

        System.out.println("testPVector time: " + (U.currentTimeMillis() - start));
    }

    /**
     *
     */
    private static void testPVectorRemove() {
        System.gc();

        long start = U.currentTimeMillis();

        TreePVector<Integer> list = TreePVector.empty();

        for (int i = 0; i < ITER_CNT; i++)
            list = list.plus(RND.nextInt(100));

        for (int i = 0; i < ITER_CNT; i++)
            list = list.minus(new Integer(RND.nextInt(100)));

        System.out.println("testPVectorRemove time: " + (U.currentTimeMillis() - start));
    }
}