text:
import unittest

from sendgrid.helpers.mail import (Email)

class TestEmailObject(unittest.TestCase):

    def test_add_email_address(self):
        address = "test@example.com"
        email = Email(address)

        self.assertEqual(email.email, "test@example.com")

    def test_add_name(self):
        name = "SomeName"
        email = Email(name=name)

        self.assertEqual(email.name, name)

    def test_add_unicode_name(self):
        name = u"SomeName"
        email = Email(name=name)

        self.assertEqual(email.name, name)

    def test_add_name_email(self):
        name = "SomeName"
        address = "test@example.com"
        email = Email(email=address, name=name)
        self.assertEqual(email.name, name)
        self.assertEqual(email.email, "test@example.com")

    def test_add_unicode_name_email(self):
        name = u"SomeName"
        address = u"test@example.com"
        email = Email(email=address, name=name)
        self.assertEqual(email.name, name)
        self.assertEqual(email.email, u"test@example.com")

    def test_add_rfc_function_finds_name_not_email(self):
        name = "SomeName"
        email = Email(name)

        self.assertEqual(email.name, name)
        self.assertIsNone(email.email)

    def test_add_rfc_email(self):
        name = "SomeName"
        address = "test@example.com"
        name_address = "{} <{}>".format(name, address)
        email = Email(name_address)
        self.assertEqual(email.name, name)
        self.assertEqual(email.email, "test@example.com")

    def test_empty_obj_add_name(self):
        email = Email()
        name = "SomeName"
        email.name = name

        self.assertEqual(email.name, name)

    def test_empty_obj_add_email(self):
        email = Email()
        address = "test@example.com"
        email.email = address

        self.assertEqual(email.email, address)


text:
. "$( dirname "${BASH_SOURCE[0]}" )/_in_container_script_init.sh"

setup_provider_packages

cd "${AIRFLOW_SOURCES}/provider_packages" || exit 1

PREPARE_PROVIDER_PACKAGES_PY="${AIRFLOW_SOURCES}/dev/provider_packages/prepare_provider_packages.py"
REFACTOR_PROVIDER_PACKAGES_PY="${AIRFLOW_SOURCES}/dev/provider_packages/refactor_provider_packages.py"

verify_suffix_versions_for_package_preparation

if [[ ${BACKPORT_PACKAGES} == "true" ]]; then
  list_subcmd="list-backportable-packages"
else
  list_subcmd="list-providers-packages"
fi

function check_missing_providers() {
    PACKAGE_ERROR="false"

    pushd "${AIRFLOW_SOURCES}/airflow/providers" >/dev/null || exit 1

    LIST_OF_DIRS_FILE=$(mktemp)
    find . -type d | sed 's!./!!; s!/!.!g' | grep -E 'hooks|operators|sensors|secrets|utils' \
        > "${LIST_OF_DIRS_FILE}"

    popd >/dev/null

    # Check if all providers are included
    for PACKAGE in "${PROVIDER_PACKAGES[@]}"
    do
        if ! grep -E "^${PACKAGE}" <"${LIST_OF_DIRS_FILE}" >/dev/null; then
            echo "The package ${PACKAGE} is not available in providers dir"
            PACKAGE_ERROR="true"
        fi
        sed -i "/^${PACKAGE}.*/d" "${LIST_OF_DIRS_FILE}"
    done

    if [[ ${PACKAGE_ERROR} == "true" ]]; then
        echo
        echo "ERROR! Some packages from dev/provider_packages/prepare_provider_packages.py are missing in providers dir"
        exit 1
    fi

    if [[ $(wc -l < "${LIST_OF_DIRS_FILE}") != "0" ]]; then
        echo "ERROR! Some folders from providers package are not defined"
        echo "       Please add them to dev/provider_packages/prepare_provider_packages.py:"
        echo
        cat "${LIST_OF_DIRS_FILE}"
        echo

        rm "$LIST_OF_DIRS_FILE"
        exit 1
    fi
    rm "$LIST_OF_DIRS_FILE"
}

if [[ -z "$*" ]]; then
    PROVIDER_PACKAGES=()
    while IFS='' read -r line; do PROVIDER_PACKAGES+=("$line"); done < <(
      python3 "${PREPARE_PROVIDER_PACKAGES_PY}" "$list_subcmd"
    )

    if [[ "$BACKPORT_PACKAGES" != "true" ]]; then
        # Don't check for missing packages when we are building backports -- we have filtered someout, and the
        # non-backport build will check for any missing.
        check_missing_providers
    fi
else
    if [[ "$1" == "--help" ]]; then
        echo
        echo "Builds all provider packages."
        echo
        echo "You can provide list of packages to build out of:"
        echo
        python3 "${PREPARE_PROVIDER_PACKAGES_PY}" list-providers-packages | tr '\n ' ' ' | fold -w 100 -s
        echo
        echo
        exit
    fi
    PROVIDER_PACKAGES=("$@")
fi

if [[ ${BACKPORT_PACKAGES} == "true" ]]; then
    echo "==================================================================================="
    echo " Copying sources and refactoring code for backport provider packages"
    echo "==================================================================================="
else
    echo "==================================================================================="
    echo " Copying sources for provider packages"
    echo "==================================================================================="
fi

python3 "${REFACTOR_PROVIDER_PACKAGES_PY}"

rm -rf dist/*

for PROVIDER_PACKAGE in "${PROVIDER_PACKAGES[@]}"
do
    rm -rf -- *.egg-info build/
    LOG_FILE=$(mktemp)
    python3 "${PREPARE_PROVIDER_PACKAGES_PY}" --version-suffix "${VERSION_SUFFIX_FOR_PYPI}" \
        generate-setup-files "${PROVIDER_PACKAGE}"
    echo "==================================================================================="
    echo " Preparing ${PACKAGE_TYPE} package ${PROVIDER_PACKAGE} format: ${PACKAGE_FORMAT}"
    if [[ "${VERSION_SUFFIX_FOR_PYPI}" == '' && "${VERSION_SUFFIX_FOR_SVN}" == ''
            && ${FILE_VERSION_SUFFIX} == '' ]]; then
        echo
        echo "Preparing official version"
        echo
    elif [[ ${FILE_VERSION_SUFFIX} != '' ]]; then
        echo
        echo " Preparing release candidate with file version suffix only: ${FILE_VERSION_SUFFIX}"
        echo
    elif [[ "${VERSION_SUFFIX_FOR_PYPI}" == '' ]]; then
        echo
        echo " Package Version for SVN release candidate: ${TARGET_VERSION_SUFFIX}"
        echo
    elif [[ "${VERSION_SUFFIX_FOR_SVN}" == '' ]]; then
        echo
        echo " Package Version for PyPI release candidate: ${TARGET_VERSION_SUFFIX}"
        echo
    else
        # Both SV/PYPI are set to the same version here!
        echo
        echo " Pre-release version: ${TARGET_VERSION_SUFFIX}"
        echo
    fi
    echo "-----------------------------------------------------------------------------------"
    set +e
    package_suffix=""
    if [[ ${VERSION_SUFFIX_FOR_SVN} == "" && ${VERSION_SUFFIX_FOR_PYPI} != "" ]]; then
        # only adds suffix to setup.py if version suffix for PyPI is set but the SVN one is not
        package_suffix="${VERSION_SUFFIX_FOR_PYPI}"
    fi
    python3 "${PREPARE_PROVIDER_PACKAGES_PY}" --version-suffix "${package_suffix}" \
        "${PROVIDER_PACKAGE}">"${LOG_FILE}" 2>&1
    RES="${?}"
    set -e
    if [[ ${RES} != "0" ]]; then
        cat "${LOG_FILE}"
        exit "${RES}"
    fi
    echo " Prepared ${PACKAGE_TYPE} package ${PROVIDER_PACKAGE} format ${PACKAGE_FORMAT}"
    echo "==================================================================================="
done

cd "${AIRFLOW_SOURCES}" || exit 1

pushd dist

if [[ ${FILE_VERSION_SUFFIX} != "" ]]; then
    # In case we have FILE_VERSION_SUFFIX we rename prepared files
    if [[ "${PACKAGE_FORMAT}" == "sdist" || "${PACKAGE_FORMAT}" == "both" ]]; then
        for FILE in *.tar.gz
        do
            mv "${FILE}" "${FILE//\.tar\.gz/${FILE_VERSION_SUFFIX}-bin.tar.gz}"
        done
    fi
    if [[ "${PACKAGE_FORMAT}" == "wheel" || "${PACKAGE_FORMAT}" == "both" ]]; then
        for FILE in *.whl
        do
            mv "${FILE}" "${FILE//\-py3/${FILE_VERSION_SUFFIX}-py3}"
        done
    fi
fi

popd
echo
echo "Airflow packages are in dist folder "
echo

redpajama_set_name: RedPajamaGithub


text:
"""Test editable view routes."""

from datetime import datetime, timedelta
import os
import random
import string
from webtest import Upload
from flask_webtest import TestApp

from flask import url_for

from flask_editablesite.extensions import thumb
from flask_editablesite.contentblock.models import (
    ShortTextContentBlock, ImageContentBlock)
from flask_editablesite.event.models import Event
from flask_editablesite.user.models import User

def test_home_textcontentblock_update_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    default_content = ShortTextContentBlock.default_content()
    assert default_content['site-byline'].content in res

    form = res.forms[
        'short-text-form-short_text_content_block-content-site-byline']
    new_byline = 'This is a rather mediocre byline.'
    form['content'] = new_byline

    res = form.submit().follow()
    assert new_byline in res
    assert not(default_content['site-byline'].content in res)

    res = testapp.get(url_for('public.logout')).follow()

def test_home_textcontentblock_update_visible_sessionstore(
        app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        default_content = ShortTextContentBlock.default_content()
        assert default_content['site-byline'].content in res

        form = res.forms[
            'short-text-form-short_text_content_block-content-site-byline']
        new_byline = 'This is a rather mediocre byline.'
        form['content'] = new_byline

        res = form.submit().follow()
        assert new_byline in res
        assert not(default_content['site-byline'].content in res)

        res = testapp.get(url_for('public.logout')).follow()

def test_home_imagecontentblock_update_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    assert (
        (
            '').format(
                url_for('static', filename=thumb.thumbnail(
                    app.config[
                        'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'],
                    size='256x256',
                    crop='fit')),
                app.config['SITE_NAME'])
        in res.text)

    form = res.forms[
        'image-form-image_content_block-image-site-logo']

    old_image_filepath = '{0}/{1}'.format(
        app.config['MEDIA_FOLDER'],
        app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'])
    assert os.path.exists(old_image_filepath)
    old_image_file = open(old_image_filepath, 'rb')

    new_image_filename = ''.join(
        random.choice(string.ascii_lowercase) for _ in range(10))
    new_image_filename += '.jpg'

    form['image'] = Upload(
        new_image_filename,
        old_image_file.read(),
        'image/jpeg')
    old_image_file.close()

    res = form.submit().follow()

    icb = (
        ImageContentBlock.query
                         .filter_by(slug='site-logo')
                         .one())

    new_image_filepath = '{0}/{1}'.format(
        app.config['MEDIA_FOLDER'],
        icb.image)
    assert os.path.exists(new_image_filepath)

    assert (
        (
            '').format(
                url_for('static', filename=thumb.thumbnail(
                    icb.image,
                    size='256x256',
                    crop='fit')),
                app.config['SITE_NAME'])
        in res.text)

    os.remove(new_image_filepath)

    res = testapp.get(url_for('public.logout')).follow()

def test_home_imagecontentblock_update_visible_sessionstore(
        app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        assert (
            (
                '').format(
                    url_for('static', filename=thumb.thumbnail(
                        app.config[
                            'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'],
                        size='256x256',
                        crop='fit')),
                    app.config['SITE_NAME'])
            in res.text)

        form = res.forms[
            'image-form-image_content_block-image-site-logo']

        old_image_filepath = '{0}/{1}'.format(
            app.config['MEDIA_FOLDER'],
            app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'])
        assert os.path.exists(old_image_filepath)
        old_image_file = open(old_image_filepath, 'rb')

        new_image_filename = ''.join(
            random.choice(string.ascii_lowercase) for _ in range(10))
        new_image_filename += '.jpg'

        form['image'] = Upload(
            new_image_filename,
            old_image_file.read(),
            'image/jpeg')
        old_image_file.close()

        res = form.submit().follow()

        assert (
            (
                '').format(
                    url_for('static', filename=thumb.thumbnail(
                        app.config[
                            'EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'],
                        size='256x256',
                        crop='fit')),
                    app.config['SITE_NAME'])
            in res.text)

        res = testapp.get(url_for('public.logout')).follow()

def test_home_event_startdate_update_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    event = Event.query.filter_by(id=1).one()
    old_start_date_str = event.start_date.strftime('%d %b %Y')
    assert ((
        '<input class="datepicker-enable" '
        'id="event-start_date-1" name="content" '
        'placeholder="Pick your start date" required type="text" '
        'value="{0}">').format(
            old_start_date_str)
        in res)

    form = res.forms[
        'date-pick-form-event-start_date-1']
    new_start_date = (event.start_date + timedelta(days=3))
    new_start_date_str = new_start_date.strftime('%d %b %Y')
    form['content'] = new_start_date_str

    res = form.submit().follow()
    assert ((
        '<input class="datepicker-enable" '
        'id="event-start_date-1" name="content" '
        'placeholder="Pick your start date" required type="text" '
        'value="{0}">').format(
            new_start_date_str)
        in res)

    res = testapp.get(url_for('public.logout')).follow()

def test_home_event_startdate_update_visible_sessionstore(
        app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        event = res.session['event'][1]
        old_start_date = datetime.strptime(
            event['start_date'], '%Y-%m-%d')
        old_start_date_str = old_start_date.strftime('%d %b %Y')
        assert ((
            '<input class="datepicker-enable" '
            'id="event-start_date-1" name="content" '
            'placeholder="Pick your start date" required type="text" '
            'value="{0}">').format(
                old_start_date_str)
            in res)

        form = res.forms[
            'date-pick-form-event-start_date-1']
        new_start_date = (old_start_date + timedelta(days=3))
        new_start_date_str = new_start_date.strftime('%d %b %Y')
        form['content'] = new_start_date_str

        res = form.submit().follow()
        assert ((
            '<input class="datepicker-enable" '
            'id="event-start_date-1" name="content" '
            'placeholder="Pick your start date" required type="text" '
            'value="{0}">').format(
                new_start_date_str)
            in res)

        res = testapp.get(url_for('public.logout')).follow()

def test_home_event_starttime_update_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    event = Event.query.filter_by(id=1).one()
    old_start_time_str = (
        event.start_time
        and event.start_time.strftime('%H:%M')
        or '')

    assert ((
        '<input class="timepicker-enable" '
        'id="event-start_time-1" name="content" '
        'placeholder="Pick your start time" type="time" '
        'value="{0}">').format(
            old_start_time_str)
        in res)

    form = res.forms[
        'time-pick-form-event-start_time-1']
    dt_now = datetime.now()
    dt_midnighttoday = datetime(dt_now.year, dt_now.month, dt_now.day)

    rand_delta = timedelta(minutes=(15 * random.randrange(96)))
    new_start_time = (dt_midnighttoday + rand_delta).time()
    new_start_time_str = new_start_time.strftime('%H:%M')

    i = 0
    while i < 3 and new_start_time_str == old_start_time_str:
        rand_delta = timedelta(minutes=(15 * random.randrange(96)))
        new_start_time = (dt_midnighttoday + rand_delta).time()
        new_start_time_str = new_start_time.strftime('%H:%M')

    form['content'] = new_start_time_str

    res = form.submit().follow()
    assert ((
        '<input class="timepicker-enable" '
        'id="event-start_time-1" name="content" '
        'placeholder="Pick your start time" type="time" '
        'value="{0}">').format(
            new_start_time_str)
        in res)

    res = testapp.get(url_for('public.logout')).follow()

def test_home_event_starttime_update_visible_sessionstore(
        app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        event = res.session['event'][1]
        dt_now_str = datetime.now().strftime('%Y-%m-%d')
        old_start_time_str = ''

        if (('start_time') in event) and event['start_time']:
            old_start_time = (
                datetime.strptime(
                    dt_now_str + ' ' + event['start_time'],
                    '%Y-%m-%d %H:%M:%S')
                .time())
            old_start_time_str = old_start_time.strftime('%H:%M')

        assert ((
            '<input class="timepicker-enable" '
            'id="event-start_time-1" name="content" '
            'placeholder="Pick your start time" type="time" '
            'value="{0}">').format(
                old_start_time_str)
            in res)

        form = res.forms[
            'time-pick-form-event-start_time-1']
        dt_now = datetime.now()
        dt_midnighttoday = datetime(dt_now.year, dt_now.month, dt_now.day)

        rand_delta = timedelta(minutes=(15 * random.randrange(96)))
        new_start_time = (dt_midnighttoday + rand_delta).time()
        new_start_time_str = new_start_time.strftime('%H:%M')

        i = 0
        while i < 3 and new_start_time_str == old_start_time_str:
            rand_delta = timedelta(minutes=(15 * random.randrange(96)))
            new_start_time = (dt_midnighttoday + rand_delta).time()
            new_start_time_str = new_start_time.strftime('%H:%M')

        form['content'] = new_start_time_str

        res = form.submit().follow()
        assert ((
            '<input class="timepicker-enable" '
            'id="event-start_time-1" name="content" '
            'placeholder="Pick your start time" type="time" '
            'value="{0}">').format(
                new_start_time_str)
            in res)

        res = testapp.get(url_for('public.logout')).follow()

def test_home_event_add_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    assert Event.query.count() == app.config['EVENT_NUM_DEFAULT_ITEMS']
    assert (
        len(
            res.html.findAll('article', {'class': 'events-item'}))
        == app.config['EVENT_NUM_DEFAULT_ITEMS'])

    form = res.forms['event-add']

    res = form.submit().follow()
    assert (
        Event.query.count() == (
            app.config['EVENT_NUM_DEFAULT_ITEMS'] + 1))
    assert (
        len(
            res.html.findAll('article', {'class': 'events-item'}))
        == (app.config['EVENT_NUM_DEFAULT_ITEMS'] + 1))

    event = Event.query.order_by(Event.id.desc()).first()
    event.delete()

    res = testapp.get(url_for('public.logout')).follow()

def test_home_event_add_visible_sessionstore(app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        assert (len(res.session['event']) - 1) == app.config[
            'EVENT_NUM_DEFAULT_ITEMS']
        assert (
            len(
                res.html.findAll('article', {'class': 'events-item'}))
            == app.config['EVENT_NUM_DEFAULT_ITEMS'])

        form = res.forms['event-add']

        res = form.submit().follow()
        assert (
            (len(res.session['event']) - 1) == (
                app.config['EVENT_NUM_DEFAULT_ITEMS'] + 1))
        assert (
            len(
                res.html.findAll('article', {'class': 'events-item'}))
            == (app.config['EVENT_NUM_DEFAULT_ITEMS'] + 1))

        res.session['event'].pop()

        res = testapp.get(url_for('public.logout')).follow()

def test_home_event_delete_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    assert Event.query.count() == app.config['EVENT_NUM_DEFAULT_ITEMS']
    assert (
        len(
            res.html.findAll('article', {'class': 'events-item'}))
        == app.config['EVENT_NUM_DEFAULT_ITEMS'])

    form = res.forms['event-delete-1']

    res = form.submit().follow()
    assert (
        Event.query.count() == (
            app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1))
    assert (
        len(
            res.html.findAll('article', {'class': 'events-item'}))
        == (app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1))

    form = res.forms['event-add']
    res = form.submit().follow()

    res = testapp.get(url_for('public.logout')).follow()

def test_home_event_delete_visible_sessionstore(app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        assert (
            (len(res.session['event']) - 1)
            == app.config['EVENT_NUM_DEFAULT_ITEMS'])
        assert (
            len(
                res.html.findAll('article', {'class': 'events-item'}))
            == app.config['EVENT_NUM_DEFAULT_ITEMS'])

        form = res.forms['event-delete-1']

        res = form.submit().follow()
        assert (
            (len(res.session['event']) - 1) == (
                app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1))
        assert (
            len(
                res.html.findAll('article', {'class': 'events-item'}))
            == (app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1))

        form = res.forms['event-add']
        res = form.submit().follow()

        res = testapp.get(url_for('public.logout')).follow()

def test_home_gallery_reorder_visible(app, user, testapp):
    # Goes to homepage
    res = testapp.get("/")
    # Fills out login form
    form = res.forms['loginForm']
    form['email'] = user.email
    form['password'] = 'myprecious'
    # Submits
    res = form.submit().follow()

    form = res.forms['gi-reorder']
    assert form['gallery_items-0-identifier'].value == '1'
    assert form['gallery_items-0-weight'].value == '0'
    assert form['gallery_items-1-identifier'].value == '2'
    assert form['gallery_items-1-weight'].value == '1'

    form['gallery_items-0-weight'] = '1'
    form['gallery_items-1-weight'] = '0'

    res = form.submit().follow()

    form = res.forms['gi-reorder']
    assert form['gallery_items-0-identifier'].value == '2'
    assert form['gallery_items-0-weight'].value == '0'
    assert form['gallery_items-1-identifier'].value == '1'
    assert form['gallery_items-1-weight'].value == '1'

def test_home_gallery_reorder_visible_sessionstore(app_sessionstore):
    app = app_sessionstore
    with app.test_request_context():
        testapp = TestApp(app)
        user = User.sessionstore_user()

        # Goes to homepage
        res = testapp.get("/")
        # Fills out login form
        form = res.forms['loginForm']
        form['email'] = user.email
        form['password'] = app.config['SESSIONSTORE_USER_PASSWORD']
        # Submits
        res = form.submit().follow()

        form = res.forms['gi-reorder']
        assert form['gallery_items-0-identifier'].value == '1'
        assert form['gallery_items-0-weight'].value == '0'
        assert form['gallery_items-1-identifier'].value == '2'
        assert form['gallery_items-1-weight'].value == '1'

        form['gallery_items-0-weight'] = '1'
        form['gallery_items-1-weight'] = '0'

        res = form.submit().follow()

        form = res.forms['gi-reorder']
        assert form['gallery_items-0-identifier'].value == '1'
        assert form['gallery_items-0-weight'].value == '0'
        assert form['gallery_items-1-identifier'].value == '2'
        assert form['gallery_items-1-weight'].value == '1'


text:
const path = require('path');
const fs = require('fs-extra');
const ora = require('ora');

const crawler = require('../crawlers/index.js');
const { delay, timeout, classify, merge } = require('../utils.js');

module.exports = async function create({ season, output }) {
  const items = await crawler.syoboi.getSeason(season);
  await items.reduce((sequence, item, idx) => sequence.then(async () => {
    const spinner = ora(`[bangumi][${idx + 1}/${items.length}]Fetching: ${item.title}`).start();
    try {
      const result = await Promise.race([crawler.bangumi.getMeta(item), timeout(10000)]);
      if (result && result.sites) {
        item.sites.push(...result.sites);
        Object.assign(item.titleTranslate, result.titleTranslate);
        Object.assign(item, { type: result.type });
      }
    } catch (err) {
      spinner.fail(err);
    }
    await delay(1000);
    spinner.stop();
  }), Promise.resolve());
  const data = classify(items);
  let sequence = Promise.resolve();
  for (const year in data) {
    for (const month in data[year]) {
      const jsonFile = path.resolve(output, `${year}/${month}.json`);
      sequence = sequence
        .then(() => fs.readJson(jsonFile))
        .catch(() => [])
        .then((origin) => merge(origin, data[year][month], 'title'))
        .then((merged) => fs.outputJson(jsonFile, merged, { spaces: 2 }))
        .then(() => console.log(`Data is outputed to ${jsonFile}`))
        .catch(console.error);
    }
  }
  return sequence;
};


text:
<?php

namespace Doctrine\Tests\Mocks;

use Doctrine\ORM\EntityManager;

/**
 * Mock class for SequenceGenerator.
 */
class SequenceMock extends \Doctrine\ORM\Id\SequenceGenerator
{
    /**
     * @var int
     */
    private $_sequenceNumber = 0;

    /**
     * {@inheritdoc}
     */
    public function generate(EntityManager $em, $entity)
    {
        return $this->_sequenceNumber++;
    }

    /* Mock API */

    /**
     * @return void
     */
    public function reset()
    {
        $this->_sequenceNumber = 0;
    }
}


text:
exports.startup = function (context, done) {
	console.log('Init socket.io');
	var io = require('socket.io')(context.app.server);
	io.on('connection', function(socket){
	  //Gestisco ricezione remote cmd dal Monitor --> invio logiot per aggiornare UniversalAPP e echo su Monitor
	  socket.on('remote', function(msg){
		io.emit('logiot', msg);
	  });
	});

  	//Ritorno la pagina html del Monitor fatto con Socket.IO
  	var path = require('path');
  	context.app.get('/monitor.html', function(req, res) {
		res.sendfile(path.resolve(__dirname, '../public/monitor.html'));
	});

  	//Salvo il contesto Socket.IO per poterlo utilizzare da Insert function sulle tabelle
  	context.io = io;
  	require('../shared/context').setContext(context);
	done();
}


text:
# AWS S3 support for Mina

You can use mina now to deploy static websites to AWS S3.

## Installation

Add this line to your application's Gemfile:

    gem 'mina-s3'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mina-s3

## Usage

Use mina to generate the config file:

    $ bundle exec mina init

Load the S3 task:

```ruby
require 'mina/s3'
```

Add some settings to the `config/deploy.rb` file.

```ruby
set :s3_bucket_name, 'mina'
set :aws_access_key_id, 'YOUR_KEY'
set :aws_secret_access_key, 'YOUR_SECRET'
set :s3_files_pattern, ['assets/**/**', '*.html']
set :s3_region, 'eu-west-1'
```

Update `deploy` task to invoke `aws:s3:deploy` task:

```ruby
task :deploy do
  invoke :'aws:s3:deploy'
end
```

Deploy it!

    $ bundle exec mina deploy

Use `--verbose` flag if you want to see the AWS logger calls.

To clear the bucket, use the `aws:s3:empty` task:

    $ bundle exec mina aws:s3:empty

Thats it.

## Todo

Write some tests.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Thanks and credits

This was inspired from Josh Delsman work on [s3-static-site](https://github.com/voxxit/s3-static-site) gem.

Huge thanks to [mina](https://github.com/nadarei/mina) developers for the awesome tool.


text:
var exec = require('child_process').exec

module.exports = function (config, callback) {
  if (typeof config === 'function') callback = config
  config = config || {}
  config.reloadNginx = config.reloadNginx || 'sudo nginx -s reload'
  return exec(config.reloadNginx, callback)
}


text:
class CreateEnrollments < ActiveRecord::Migration
  def change
    create_table :enrollments do |t|
      t.integer   :student_id, null: false
      t.integer   :section_id, null: false
      t.string    :semester
      t.boolean   :active, default: true
      t.timestamps null: false
    end
  end
end


text:
package com.github.concept.not.found.indented.formatter;

/**
 * Formats the Paragraph into plain text tabbed for each indent level.
 */
public class TabbedFormatter extends TickFormatter {

	/**
	 * Constructor.
	 */
	public TabbedFormatter() {
		super("\t");
	}
}


text:
outer/edge Magento Page Module
============================================

[![Build Status](https://travis-ci.org/outeredge/magento-page-module.svg?branch=master)](https://travis-ci.org/outeredge/magento-page-module)

Advice is to override the core Magento `cms_page_view.xml` in the following location.

`app/design/frontend/[Vendor_Theme]/Magento_Cms/layout/override/base/cms_page_view.xml`

```
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="OuterEdge\Page\Block\Page" name="cms_page" template="content.phtml"/>
        </referenceContainer>
    </body>
</page>
```

http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/layout-override.html


text:
package org.apache.calcite.sql.dialect;

import org.apache.calcite.avatica.util.TimeUnitRange;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.fun.SqlCase;
import org.apache.calcite.sql.fun.SqlFloorFunction;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;

import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A SqlDialect implementation for the Hsqldb database.
 */
public class HsqldbSqlDialect extends SqlDialect {
  public static final SqlDialect.Context DEFAULT_CONTEXT = SqlDialect.EMPTY_CONTEXT
      .withDatabaseProduct(SqlDialect.DatabaseProduct.HSQLDB);

  public static final SqlDialect DEFAULT = new HsqldbSqlDialect(DEFAULT_CONTEXT);

  /** Creates an HsqldbSqlDialect. */
  public HsqldbSqlDialect(Context context) {
    super(context);
  }

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

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

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

  @Override public void unparseCall(SqlWriter writer, SqlCall call,
      int leftPrec, int rightPrec) {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      final String translatedLit = convertTimeUnit(timeUnit);
      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, translatedLit,
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }

  @Override public void unparseOffsetFetch(SqlWriter writer, @Nullable SqlNode offset,
      @Nullable SqlNode fetch) {
    unparseFetchUsingLimit(writer, offset, fetch);
  }

  @Override public SqlNode rewriteSingleValueExpr(SqlNode aggCall) {
    final SqlNode operand = ((SqlBasicCall) aggCall).operand(0);
    final SqlLiteral nullLiteral = SqlLiteral.createNull(SqlParserPos.ZERO);
    final SqlNode unionOperand = SqlStdOperatorTable.VALUES.createCall(SqlParserPos.ZERO,
        SqlLiteral.createApproxNumeric("0", SqlParserPos.ZERO));
    // For hsqldb, generate
    //   CASE COUNT(*)
    //   WHEN 0 THEN NULL
    //   WHEN 1 THEN MIN(<result>)
    //   ELSE (VALUES 1 UNION ALL VALUES 1)
    //   END
    final SqlNode caseExpr =
        new SqlCase(SqlParserPos.ZERO,
            SqlStdOperatorTable.COUNT.createCall(SqlParserPos.ZERO, operand),
            SqlNodeList.of(
                SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO),
                SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO)),
            SqlNodeList.of(
                nullLiteral,
                SqlStdOperatorTable.MIN.createCall(SqlParserPos.ZERO, operand)),
            SqlStdOperatorTable.SCALAR_QUERY.createCall(SqlParserPos.ZERO,
                SqlStdOperatorTable.UNION_ALL
                    .createCall(SqlParserPos.ZERO, unionOperand, unionOperand)));

    LOGGER.debug("SINGLE_VALUE rewritten into [{}]", caseExpr);

    return caseExpr;
  }

  private static String convertTimeUnit(TimeUnitRange unit) {
    switch (unit) {
    case YEAR:
      return "YYYY";
    case MONTH:
      return "MM";
    case DAY:
      return "DD";
    case WEEK:
      return "WW";
    case HOUR:
      return "HH24";
    case MINUTE:
      return "MI";
    case SECOND:
      return "SS";
    default:
      throw new AssertionError("could not convert time unit to HSQLDB equivalent: "
          + unit);
    }
  }
}


text:
import base64

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from OpenSSL import crypto
import testtools
from testtools import testcase

from barbican.tests import keys
from barbican.tests import utils
from functionaltests.api import base
from functionaltests.api.v1.behaviors import container_behaviors
from functionaltests.api.v1.behaviors import order_behaviors
from functionaltests.api.v1.behaviors import secret_behaviors
from functionaltests.api.v1.models import container_models
from functionaltests.api.v1.models import order_models
from functionaltests.api.v1.models import secret_models

def get_private_key_req(payload):
    return {'name': 'myprivatekey',
            'payload_content_type': 'application/octet-stream',
            'payload_content_encoding': 'base64',
            'algorithm': 'rsa',
            'bit_length': 2048,
            'secret_type': 'private',
            'payload': payload}

def get_public_key_req(payload):
    return {'name': 'mypublickey',
            'payload_content_type': 'application/octet-stream',
            'payload_content_encoding': 'base64',
            'algorithm': 'rsa',
            'bit_length': 2048,
            'secret_type': 'public',
            'payload': payload}

def get_passphrase_req(passphrase):
    return {'name': 'mypassphrase',
            'payload_content_type': 'text/plain',
            'secret_type': 'passphrase',
            'payload': passphrase}

def get_container_req(public_key_ref, private_key_ref, passphrase=None):
    request = {"name": "rsacontainer",
               "type": "rsa",
               "secret_refs": [
                   {'name': 'public_key', 'secret_ref': public_key_ref},
                   {'name': 'private_key', 'secret_ref': private_key_ref}]}
    if passphrase:
        request["secret_refs"].append(
            {'name': 'private_key_passphrase', 'secret_ref': passphrase})
    return request

def get_certificate_req(payload):
    return {'name': 'mycertificate',
            'payload_content_type': 'application/octet-stream',
            'payload_content_encoding': 'base64',
            'secret_type': 'certificate',
            'payload': payload}

def get_order_rsa_container():
    return {'type': 'asymmetric',
            "meta": {"name": "ordered rsacontainer",
                     "algorithm": "rsa",
                     "bit_length": 2048,
                     "mode": "cbc"}}

def get_order_rsa_container_with_passphrase():
    return {'type': 'asymmetric',
            "meta": {"name": "ordered rsacontainer",
                     "algorithm": "rsa",
                     "bit_length": 2048,
                     "passphrase": "password",
                     "mode": "cbc"}}

def get_order_certificate(container_ref):
    return {'type': 'certificate',
            'meta': {'request_type': 'stored-key',
                     'container_ref': container_ref,
                     'subject_dn': 'cn=server.example.com,o=example.com',
                     'requestor_name': 'Barbican User',
                     'requestor_email': 'user@example.com',
                     'requestor_phone': '555-1212'}}

def get_order_certificate_simple_cmc(csr):
    return {'type': 'certificate',
            'meta': {'request_type': 'simple-cmc',
                     'requestor_name': 'Barbican User',
                     'requestor_email': 'user@example.com',
                     'requestor_phone': '555-1212',
                     'request_data': csr}}

@utils.parameterized_test_case
class RSATestCase(base.TestCase):
    """Positive test cases for all ways of working with RSA keys

    These tests are meant to be 'real'.  All input is created
    using OpenSSL commands and all results verified by OpenSSL.
    """

    def setUp(self):
        super(RSATestCase, self).setUp()
        self.secret_behaviors = secret_behaviors.SecretBehaviors(self.client)
        self.container_behaviors = container_behaviors.ContainerBehaviors(
            self.client)
        self.order_behaviors = order_behaviors.OrderBehaviors(self.client)

    def tearDown(self):
        self.secret_behaviors.delete_all_created_secrets()
        self.container_behaviors.delete_all_created_containers()
        self.order_behaviors.delete_all_created_orders()
        super(RSATestCase, self).tearDown()

    @testcase.attr('positive')
    def test_rsa_check_input_keys(self):
        """Verify the input keys for test cases"""

        # prove pyOpenSSL can parse the original private key
        pem = keys.get_private_key_pem()
        crypto.load_privatekey(crypto.FILETYPE_PEM, pem)

        # prove cryptography can parse the original public key
        serialization.load_pem_public_key(
            keys.get_public_key_pem(),
            backend=default_backend()
        )

        # prove pyOpenSSL can parse the original encrypted private key
        pem = keys.get_encrypted_private_key_pem()
        passphrase = keys.get_passphrase_txt()
        crypto.load_privatekey(crypto.FILETYPE_PEM,
                               pem,
                               passphrase)

        # prove OpenSSL can parse the original certificate
        pem = keys.get_certificate_pem()
        crypto.load_certificate(crypto.FILETYPE_PEM, pem)

    @testcase.attr('positive')
    def test_rsa_store_and_get_private_key(self):
        """Post and Get for private key"""
        key_ref = self.store_private_key()
        key = self.get_private_key(key_ref)
        self.verify_private_key_equal(key)

    @testcase.attr('positive')
    def test_rsa_store_and_get_public_key(self):
        """Post and Get for public key"""
        key_ref = self.store_public_key()
        key = self.get_public_key(key_ref)
        self.verify_public_key_equal(key)

    @testcase.attr('positive')
    def test_rsa_two_step_store_and_get_private_key(self):
        """Post, Put, and Get for private key"""
        key_ref = self.create_private_key()
        self.update_private_key(key_ref)
        key = self.get_private_key(key_ref)
        self.verify_private_key_equal(key)

    @testcase.attr('positive')
    def test_rsa_two_step_store_and_get_public_key(self):
        """Post, Put, and Get for public key"""
        key_ref = self.create_public_key()
        self.update_public_key(key_ref)
        key = self.get_public_key(key_ref)
        self.verify_public_key_equal(key)

    @testcase.attr('positive')
    def test_rsa_store_and_get_passphrase(self):
        """Post and Get for passphrase"""
        phrase_ref = self.store_passphrase()
        phrase = self.get_passphrase(phrase_ref)
        self.verify_passphrase_equal(phrase)

    @testcase.attr('positive')
    def test_rsa_store_and_get_certificate_secret(self):
        """Post and Get for certificate"""
        cert_ref = self.store_certificate()
        cert = self.get_certificate(cert_ref)
        self.verify_certificate_equal(cert)

    @testcase.attr('positive')
    def test_rsa_two_step_store_and_get_certificate_secret(self):
        """Post, Put, and Get for certificate"""
        cert_ref = self.create_certificate()
        self.update_certificate(cert_ref)
        cert = self.get_certificate(cert_ref)
        self.verify_certificate_equal(cert)

    @testcase.attr('positive')
    def test_rsa_store_and_get_container(self):
        """Post and Get for container"""
        public_ref = self.store_public_key()
        private_ref = self.store_private_key()
        container_ref = self.store_container(public_ref, private_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_equal(secrets)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_kmip_enabled(),
                      "PyKMIP does not support this operation")
    def test_rsa_store_and_get_container_with_passphrase(self):
        """Post and Get for container with passphrase"""
        public_ref = self.store_public_key()
        private_ref = self.store_encrypted_private_key()
        phrase_ref = self.store_passphrase()
        container_ref = self.store_container(public_ref,
                                             private_ref,
                                             phrase_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_equal(secrets, with_passphrase=True)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_vault_enabled() or utils.is_pkcs11_enabled(),
                      "Vault does not support this operation")
    def test_rsa_order_container(self):
        """Post an order for a container"""
        order_ref = self.order_container()
        container_ref = self.get_container_order(order_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_valid(secrets)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_kmip_enabled() or utils.is_vault_enabled()
                      or utils.is_pkcs11_enabled(),
                      "PyKMIP does not support this operation")
    def test_rsa_order_container_with_passphrase(self):
        """Post an order for a container with a passphrase"""
        order_ref = self.order_container(with_passphrase=True)
        container_ref = self.get_container_order(order_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_valid(secrets, with_passphrase=True)

    @testcase.attr('positive')
    def test_rsa_store_container_from_two_step_secrets(self):
        """Post an order for a certificate"""
        public_ref = self.create_public_key()
        self.update_public_key(public_ref)
        private_ref = self.create_private_key()
        self.update_private_key(private_ref)
        container_ref = self.store_container(public_ref, private_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_equal(secrets)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_vault_enabled() or utils.is_pkcs11_enabled(),
                      "Vault does not support this operation")
    def test_rsa_order_certificate_from_ordered_container(self):
        """Post an order for a certificate"""
        order_ref = self.order_container()
        container_ref = self.get_container_order(order_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_valid(secrets)
        order_ref = self.order_certificate(container_ref)
        order_status = self.get_certificate_order(order_ref)
        self.verify_certificate_order_status(order_status)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_kmip_enabled() or utils.is_vault_enabled()
                      or utils.is_pkcs11_enabled(),
                      "PyKMIP does not support this operation")
    def test_rsa_order_certificate_from_ordered_container_with_pass(self):
        """Post an order for a certificate"""
        order_ref = self.order_container(with_passphrase=True)
        container_ref = self.get_container_order(order_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_valid(secrets, with_passphrase=True)
        order_ref = self.order_certificate(container_ref)
        order_status = self.get_certificate_order(order_ref)
        self.verify_certificate_order_status(order_status)

    @testcase.attr('positive')
    def test_rsa_order_certificate_from_stored_container(self):
        """Post an order for a certificate"""
        public_ref = self.create_public_key()
        self.update_public_key(public_ref)
        private_ref = self.create_private_key()
        self.update_private_key(private_ref)
        container_ref = self.store_container(public_ref, private_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_equal(secrets)
        order_ref = self.order_certificate(container_ref)
        order_status = self.get_certificate_order(order_ref)
        self.verify_certificate_order_status(order_status)

    @testcase.attr('positive')
    @testtools.skipIf(utils.is_kmip_enabled(),
                      "PyKMIP does not support this operation")
    def test_rsa_order_certificate_from_stored_container_with_pass(self):
        """Post an order for a certificate"""
        public_ref = self.store_public_key()
        private_ref = self.store_encrypted_private_key()
        phrase_ref = self.store_passphrase()
        container_ref = self.store_container(
            public_ref, private_ref, phrase_ref)
        secrets = self.get_container(container_ref)
        self.verify_container_keys_equal(secrets, with_passphrase=True)
        order_ref = self.order_certificate(container_ref)
        order_status = self.get_certificate_order(order_ref)
        self.verify_certificate_order_status(order_status)

    @testcase.attr('positive')
    def test_rsa_order_certificate_from_csr(self):
        """Post an order for a certificate"""
        order_ref = self.order_certificate_from_csr()
        order_status = self.get_certificate_order(order_ref)
        self.verify_certificate_order_status(order_status)

# ----------------------- Helper Functions ---------------------------
    def store_private_key(self):
        pem = keys.get_private_key_pem()
        test_model = secret_models.SecretModel(
            **get_private_key_req(base64.b64encode(pem)))
        resp, private_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return private_key_secret_ref

    def get_private_key(self, private_key_secret_ref):
        resp = self.secret_behaviors.get_secret(
            private_key_secret_ref, 'application/octet-stream')
        self.assertEqual(200, resp.status_code)
        return resp.content

    def verify_private_key_equal(self, retrieved_private_key):
        pem = keys.get_private_key_pem()
        self.assertEqual(pem, retrieved_private_key)

    def create_private_key(self):
        create_req = get_private_key_req("")
        del create_req['payload']
        del create_req['payload_content_type']
        del create_req['payload_content_encoding']
        test_model = secret_models.SecretModel(**create_req)
        resp, private_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return private_key_secret_ref

    def update_private_key(self, private_key_secret_ref):
        pem = keys.get_private_key_pem()
        update_resp = self.secret_behaviors.update_secret_payload(
            private_key_secret_ref,
            pem,
            'application/octet-stream')
        self.assertEqual(204, update_resp.status_code)

    def store_encrypted_private_key(self):
        pem = keys.get_encrypted_private_key_pem()
        test_model = secret_models.SecretModel(
            **get_private_key_req(base64.b64encode(pem)))
        resp, private_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return private_key_secret_ref

    def get_encrypted_private_key(self, private_key_secret_ref):
        resp = self.secret_behaviors.get_secret(
            private_key_secret_ref, 'application/octet-stream')
        self.assertEqual(200, resp.status_code)
        return resp.content

    def verify_encrypted_private_key_equal(self, retrieved_private_key):
        pem = keys.get_encrypted_private_key_pem()
        self.assertEqual(pem, retrieved_private_key)

    def create_encrypted_private_key(self):
        create_req = get_private_key_req("")
        del create_req['payload']
        del create_req['payload_content_type']
        del create_req['payload_content_encoding']
        test_model = secret_models.SecretModel(**create_req)
        resp, private_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return private_key_secret_ref

    def update_encrypted_private_key(self, private_key_secret_ref):
        pem = keys.get_encrypted_private_key_pem()
        update_resp = self.secret_behaviors.update_secret_payload(
            private_key_secret_ref,
            pem,
            'application/octet-stream')
        self.assertEqual(204, update_resp.status_code)

    def store_public_key(self):
        pem = keys.get_public_key_pem()
        test_model = secret_models.SecretModel(
            **get_public_key_req(base64.b64encode(pem)))
        resp, public_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return public_key_secret_ref

    def get_public_key(self, public_key_secret_ref):
        resp = self.secret_behaviors.get_secret(
            public_key_secret_ref, 'application/octet-stream')
        self.assertEqual(200, resp.status_code)
        return resp.content

    def verify_public_key_equal(self, retrieved_public_key):
        pem = keys.get_public_key_pem()
        self.assertEqual(pem, retrieved_public_key)

    def create_public_key(self):
        create_req = get_public_key_req("")
        del create_req['payload']
        del create_req['payload_content_type']
        del create_req['payload_content_encoding']
        test_model = secret_models.SecretModel(**create_req)
        resp, public_key_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return public_key_secret_ref

    def update_public_key(self, public_key_secret_ref):
        pem = keys.get_public_key_pem()
        resp = self.secret_behaviors.update_secret_payload(
            public_key_secret_ref,
            pem,
            'application/octet-stream')
        self.assertEqual(204, resp.status_code)

    def store_passphrase(self):
        passphrase = keys.get_passphrase_txt()
        test_model = secret_models.SecretModel(
            **get_passphrase_req(passphrase))
        resp, passphrase_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return passphrase_secret_ref

    def get_passphrase(self, passphrase_secret_ref):
        content_type = 'application/octet-stream'
        get_resp = self.secret_behaviors.get_secret(
            passphrase_secret_ref, content_type)
        self.assertEqual(200, get_resp.status_code)
        return get_resp.content

    def verify_passphrase_equal(self, retrieved_passphrase):
        passphrase = keys.get_passphrase_txt()
        self.assertEqual(passphrase, retrieved_passphrase)

    def store_certificate(self):
        pem = keys.get_certificate_pem()
        test_model = secret_models.SecretModel(
            **get_certificate_req(base64.b64encode(pem)))
        resp, certificate_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return certificate_secret_ref

    def get_certificate(self, certificate_secret_ref):
        content_type = 'application/octet-stream'
        resp = self.secret_behaviors.get_secret(
            certificate_secret_ref, content_type)
        self.assertEqual(200, resp.status_code)
        return resp.content

    def verify_certificate_equal(self, retrieved_certificate):
        pem = keys.get_certificate_pem()
        self.assertEqual(pem, retrieved_certificate)

    def create_certificate(self):
        create_req = get_certificate_req("")
        del create_req['payload']
        del create_req['payload_content_type']
        del create_req['payload_content_encoding']
        test_model = secret_models.SecretModel(**create_req)
        resp, certificate_secret_ref = self.secret_behaviors.create_secret(
            test_model)
        self.assertEqual(201, resp.status_code)
        return certificate_secret_ref

    def update_certificate(self, certificate_secret_ref):
        pem = keys.get_certificate_pem()
        resp = self.secret_behaviors.update_secret_payload(
            certificate_secret_ref,
            pem,
            'application/octet-stream')
        self.assertEqual(204, resp.status_code)

    def store_container(self,
                        public_key_secret_ref,
                        private_key_secret_ref,
                        passphrase_secret_ref=None):
        test_model = container_models.ContainerModel(
            **get_container_req(public_key_secret_ref,
                                private_key_secret_ref,
                                passphrase_secret_ref))
        resp, container_ref = self.container_behaviors.create_container(
            test_model)
        self.assertEqual(201, resp.status_code)
        return container_ref

    def make_secret_dict(self, secret_refs):
        """Get the secrets from the container and store in a dict"""
        secret_dict = {}
        for secret in secret_refs:
            self.assertIsNotNone(secret.secret_ref)
            secret_resp = self.secret_behaviors.get_secret(
                secret.secret_ref, "application/octet-stream")
            self.assertIsNotNone(secret_resp)
            secret_dict[secret.name] = secret_resp.content
        return secret_dict

    def get_container(self, container_ref):
        resp = self.container_behaviors.get_container(container_ref)
        self.assertEqual(200, resp.status_code)
        return self.make_secret_dict(resp.model.secret_refs)

    def verify_container_keys_equal(self,
                                    secret_dict,
                                    with_passphrase=False):
        if with_passphrase:
            passphrase = keys.get_passphrase_txt()
            self.assertEqual(passphrase,
                             secret_dict['private_key_passphrase'])
            private_pem = keys.get_encrypted_private_key_pem()
        else:
            self.assertNotIn('private_key_passphrase', secret_dict)
            private_pem = keys.get_private_key_pem()
        self.assertEqual(private_pem, secret_dict['private_key'])
        public_pem = keys.get_public_key_pem()
        self.assertEqual(public_pem, secret_dict['public_key'])

    def verify_container_keys_valid(self,
                                    secret_dict,
                                    with_passphrase=False):
        # verify generated keys can be parsed
        if with_passphrase:
            crypto.load_privatekey(
                crypto.FILETYPE_PEM,
                secret_dict['private_key'],
                secret_dict['private_key_passphrase'])
        else:
            self.assertNotIn('private_key_passphrase', secret_dict)
            crypto.load_privatekey(
                crypto.FILETYPE_PEM,
                secret_dict['private_key'])
        serialization.load_pem_public_key(
            secret_dict['public_key'],
            backend=default_backend()
        )

    def order_container(self, with_passphrase=False):
        if with_passphrase:
            test_model = order_models.OrderModel(
                **get_order_rsa_container_with_passphrase())
        else:
            test_model = order_models.OrderModel(
                **get_order_rsa_container())
        resp, order_ref = self.order_behaviors.create_order(test_model)
        self.assertEqual(202, resp.status_code)
        return order_ref

    def get_container_order(self, order_ref):
        resp = self.order_behaviors.get_order(order_ref)
        self.assertEqual(200, resp.status_code)
        return resp.model.container_ref

    def order_certificate(self, container_ref):
        test_model = order_models.OrderModel(
            **get_order_certificate(container_ref))
        resp, order_ref = self.order_behaviors.create_order(test_model)
        self.assertEqual(202, resp.status_code)
        return order_ref

    def get_certificate_order(self, order_ref):
        resp = self.order_behaviors.get_order(order_ref)
        self.assertEqual(200, resp.status_code)
        order_status = (resp.model.status,
                        resp.model.sub_status)
        return order_status

    def verify_certificate_order_status(self, order_status):
        self.assertEqual(("PENDING", "cert_request_pending"),
                         order_status)

    def order_certificate_from_csr(self):
        csr = keys.get_csr_pem()
        test_model = order_models.OrderModel(
            **get_order_certificate_simple_cmc(base64.b64encode(csr)))
        resp, order_ref = self.order_behaviors.create_order(test_model)
        self.assertEqual(202, resp.status_code)
        return order_ref


text:
namespace mojo {
namespace test {

bool BlockingWrite(const embedder::PlatformHandle& handle,
                   const void* buffer,
                   size_t bytes_to_write,
                   size_t* bytes_written) {
  OVERLAPPED overlapped = { 0 };
  DWORD bytes_written_dword = 0;

  if (!WriteFile(handle.handle, buffer, static_cast<DWORD>(bytes_to_write),
                 &bytes_written_dword, &overlapped)) {
    if (GetLastError() != ERROR_IO_PENDING ||
        !GetOverlappedResult(handle.handle, &overlapped, &bytes_written_dword,
                             TRUE)) {
      return false;
    }
  }

  *bytes_written = bytes_written_dword;
  return true;
}

bool BlockingRead(const embedder::PlatformHandle& handle,
                  void* buffer,
                  size_t buffer_size,
                  size_t* bytes_read) {
  OVERLAPPED overlapped = { 0 };
  DWORD bytes_read_dword = 0;

  if (!ReadFile(handle.handle, buffer, static_cast<DWORD>(buffer_size),
                &bytes_read_dword, &overlapped)) {
    if (GetLastError() != ERROR_IO_PENDING ||
        !GetOverlappedResult(handle.handle, &overlapped, &bytes_read_dword,
                             TRUE)) {
      return false;
    }
  }

  *bytes_read = bytes_read_dword;
  return true;
}

bool NonBlockingRead(const embedder::PlatformHandle& handle,
                     void* buffer,
                     size_t buffer_size,
                     size_t* bytes_read) {
  OVERLAPPED overlapped = { 0 };
  DWORD bytes_read_dword = 0;

  if (!ReadFile(handle.handle, buffer, static_cast<DWORD>(buffer_size),
                &bytes_read_dword, &overlapped)) {
    if (GetLastError() != ERROR_IO_PENDING)
      return false;

    CancelIo(handle.handle);

    if (!GetOverlappedResult(handle.handle, &overlapped, &bytes_read_dword,
                             TRUE)) {
      *bytes_read = 0;
      return true;
    }
  }

  *bytes_read = bytes_read_dword;
  return true;
}

}  // namespace test
}  // namespace mojo


text:
#ifndef wpantund_WPAN_NCPControlInterface_h
#define wpantund_WPAN_NCPControlInterface_h

#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS 1
#endif

#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif

#include <stdint.h>
#include <string>
#include <vector>
#include <boost/signals2/signal.hpp>
#include <boost/any.hpp>
#include <list>
#include <arpa/inet.h>
#include "time-utils.h"

#include <pthread.h>

#include "NetworkInstance.h"
#include "NCPTypes.h"
#include <cstring>
#include "IPv6PacketMatcher.h"
#include "Data.h"
#include "NilReturn.h"
#include "NCPConstants.h"
#include "Callbacks.h"
#include "wpan-properties.h"
#include "ValueMap.h"

namespace nl {
namespace wpantund {

#define USE_DEFAULT_TX_POWER               INT32_MIN
#define USE_DEFAULT_CCA_THRESHOLD          INT32_MIN
#define USE_DEFAULT_TX_POWER_MODE          INT32_MIN
#define USE_DEFAULT_TRANSMIT_HOOK_ACTIVE   INT32_MIN

typedef std::set<int> IntegerSet;

class NCPInstance;

class NCPControlInterface {
public:

	typedef uint32_t ChannelMask;

	enum ExternalRoutePriority {
		ROUTE_LOW_PREFRENCE = -1,
		ROUTE_MEDIUM_PREFERENCE = 0,
		ROUTE_HIGH_PREFERENCE = 1,
	};

public:
	// ========================================================================
	// Static Functions

	static std::string external_route_priority_to_string(ExternalRoutePriority route_priority);

public:
	// ========================================================================
	// Public Virtual Member Functions

	//! Returns the network instance currently associated with the NCP.
	virtual const WPAN::NetworkInstance& get_current_network_instance(void)const = 0;

public:
	// ========================================================================
	// NCP Command Virtual Member Functions

	virtual void join(
		const ValueMap& options,
	    CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void form(
		const ValueMap& options,
	    CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void leave(CallbackWithStatus cb = NilReturn()) = 0;

	//! Deprecated. Set kWPANTUNDProperty_InterfaceUp to true instead.
	virtual void attach(CallbackWithStatus cb = NilReturn()) = 0;

	virtual void reset(CallbackWithStatus cb = NilReturn()) = 0;

	virtual void refresh_state(CallbackWithStatus cb = NilReturn()) = 0;

	virtual void get_property(
	    const std::string& key,
	    CallbackWithStatusArg1 cb
	) = 0;

	virtual void set_property(
	    const std::string& key,
	    const boost::any& value,
	    CallbackWithStatus cb
	) = 0;

	virtual void add_on_mesh_prefix(
		const struct in6_addr *prefix,
		bool defaultRoute,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void remove_on_mesh_prefix(
		const struct in6_addr *prefix,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void add_external_route(
		const struct in6_addr *prefix,
		int prefix_len_in_bits,
		int domain_id,
		ExternalRoutePriority priority,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void remove_external_route(
		const struct in6_addr *prefix,
		int prefix_len_in_bits,
		int domain_id,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void pcap_to_fd(
		int fd,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void pcap_terminate(
		CallbackWithStatus cb = NilReturn()
	) = 0;

public:
	// ========================================================================
	// Scan-related Member Functions

	virtual void netscan_start(const ValueMap& options, CallbackWithStatus cb = NilReturn()) = 0;

	virtual void netscan_stop(CallbackWithStatus cb = NilReturn()) = 0;

	boost::signals2::signal<void(const WPAN::NetworkInstance&)> mOnNetScanBeacon;

public:
	// ========================================================================
	// EnergyScan-related Member Functions

	virtual void energyscan_start(const ValueMap& options, CallbackWithStatus cb = NilReturn()) = 0;

	virtual void energyscan_stop(CallbackWithStatus cb = NilReturn()) = 0;

	boost::signals2::signal<void(const EnergyScanResultEntry&)> mOnEnergyScanResult;

public:
	// ========================================================================
	// Power-related Member Functions

	virtual void begin_low_power(CallbackWithStatus cb = NilReturn()) = 0;

	virtual void host_did_wake(CallbackWithStatus cb = NilReturn()) = 0;

	virtual void data_poll(CallbackWithStatus cb = NilReturn()) = 0;

public:
	// ========================================================================
	// Nest-Specific Member Functions

	virtual void begin_net_wake(
		uint8_t data = 0,
		uint32_t flags = 0,
		CallbackWithStatus cb = NilReturn()
	) = 0;

	virtual void permit_join(
	    int seconds = 15 * 60,
	    uint8_t commissioning_traffic_type = 0xFF,
	    in_port_t commissioning_traffic_port = 0,
	    bool network_wide = false,
	    CallbackWithStatus cb = NilReturn()
	) = 0;

public:
	// ========================================================================
	// Convenience methods

	boost::any get_property(const std::string& key);

	int set_property(const std::string& key, const boost::any& value);

	virtual std::string get_name();

public:
	// ========================================================================
	// Other

	static bool translate_deprecated_property(std::string& key, boost::any& value);

	static bool translate_deprecated_property(std::string& key);

public:
	// ========================================================================
	// Signals

	//! Fires whenever value of certain properties changed (e.g. NodeType).
	boost::signals2::signal<void(const std::string& key, const boost::any& value)> mOnPropertyChanged;

public:
	// ========================================================================
	// Nest-Specific Signals

	//! Fires when the network wake state has changed or been updated.
	boost::signals2::signal<void(uint8_t data, cms_t ms_remaining)> mOnNetWake;

protected:
	// ========================================================================
	// Protected Virtual Member Functions

	virtual ~NCPControlInterface();

	//! Returns the associated NCP instance.
	virtual NCPInstance& get_ncp_instance(void) = 0;
};

}; // namespace wpantund
}; // namespace nl

#endif


text:
import { Component, Input, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms';
import { Test }  from '../models/test.model';
import { Suite }  from '../models/suite.model';
import { Project }  from '../models/project.model';
import { TestService } from '../services/test.service';

@Component({
  selector: 'tcms-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
  @Input() project: Project;
  @Input() suite: Suite;
  tests: Test[];
  input: boolean = false;
  tmpName: string;
  selectedTest: Test;
  errorMessage: string;

  constructor(private testService: TestService) { }

  getTests(projId: string, suiteId: string) {
    this.testService.getTest(projId, suiteId)
      .subscribe(
        tests => {
          this.tests = tests
        }
      );
  }

  updateOrCreate(newTest) {
    if (newTest._id) {
      // update project
      this.testService.update(this.project._id,this.suite._id, this.selectedTest._id, newTest)
        .subscribe(
          tests => this.getTests(this.project._id, this.suite._id),
          error => this.errorMessage = <any>error
        );
    } else {
      // new suite
      this.testService.create(this.project._id, this.suite._id, newTest)
        .subscribe(
          test => this.tests.unshift(test),
          error => this.errorMessage = <any>error
        );
    }
    this.tmpName = null;
  }

  inputSwitch() {
    if (this.input) {
      this.input = false;
    } else {
      this.input = true;
    }
  }

  onSelectTest(test: Test) {
    this.selectedTest = test;
    console.info(this.selectedTest);
  }

  ngOnInit() {
    this.getTests(this.project._id, this.suite._id);
  }
}


text:
"""Methods related to test expectations/expectation files."""

from __future__ import print_function

import collections
import datetime
import logging
import os
import re
import subprocess
import sys
from typing import Iterable, List, Optional, Set, Tuple, Union

import six

from typ import expectations_parser
from unexpected_passes_common import data_types
from unexpected_passes_common import result_output

FINDER_DISABLE_COMMENT_BASE = 'finder:disable'
FINDER_ENABLE_COMMENT_BASE = 'finder:enable'
FINDER_COMMENT_SUFFIX_GENERAL = '-general'
FINDER_COMMENT_SUFFIX_STALE = '-stale'
FINDER_COMMENT_SUFFIX_UNUSED = '-unused'

ALL_FINDER_SUFFIXES = frozenset([
    FINDER_COMMENT_SUFFIX_GENERAL,
    FINDER_COMMENT_SUFFIX_STALE,
    FINDER_COMMENT_SUFFIX_UNUSED,
])

FINDER_DISABLE_COMMENT_GENERAL = (FINDER_DISABLE_COMMENT_BASE +
                                  FINDER_COMMENT_SUFFIX_GENERAL)
FINDER_DISABLE_COMMENT_STALE = (FINDER_DISABLE_COMMENT_BASE +
                                FINDER_COMMENT_SUFFIX_STALE)
FINDER_DISABLE_COMMENT_UNUSED = (FINDER_DISABLE_COMMENT_BASE +
                                 FINDER_COMMENT_SUFFIX_UNUSED)
FINDER_ENABLE_COMMENT_GENERAL = (FINDER_ENABLE_COMMENT_BASE +
                                 FINDER_COMMENT_SUFFIX_GENERAL)
FINDER_ENABLE_COMMENT_STALE = (FINDER_ENABLE_COMMENT_BASE +
                               FINDER_COMMENT_SUFFIX_STALE)
FINDER_ENABLE_COMMENT_UNUSED = (FINDER_ENABLE_COMMENT_BASE +
                                FINDER_COMMENT_SUFFIX_UNUSED)

FINDER_DISABLE_COMMENTS = frozenset([
    FINDER_DISABLE_COMMENT_GENERAL, FINDER_DISABLE_COMMENT_STALE,
    FINDER_DISABLE_COMMENT_UNUSED
])

FINDER_ENABLE_COMMENTS = frozenset([
    FINDER_ENABLE_COMMENT_GENERAL,
    FINDER_ENABLE_COMMENT_STALE,
    FINDER_ENABLE_COMMENT_UNUSED,
])

ALL_FINDER_COMMENTS = frozenset(FINDER_DISABLE_COMMENTS
                                | FINDER_ENABLE_COMMENTS)

GIT_BLAME_REGEX = re.compile(
    r'^[\w\s]+\(.+(?P<date>\d\d\d\d-\d\d-\d\d)[^\)]+\)(?P<content>.*)$',
    re.DOTALL)
EXPECTATION_LINE_REGEX = re.compile(r'^.*\[ .* \] .* \[ \w* \].*$', re.DOTALL)

# pylint: disable=useless-object-inheritance

class RemovalType(object):
  STALE = FINDER_COMMENT_SUFFIX_STALE
  UNUSED = FINDER_COMMENT_SUFFIX_UNUSED

class Expectations(object):
  def CreateTestExpectationMap(
      self, expectation_files: Optional[Union[str, List[str]]],
      tests: Optional[Iterable[str]],
      grace_period: int) -> data_types.TestExpectationMap:
    """Creates an expectation map based off a file or list of tests.

    Args:
      expectation_files: A filepath or list of filepaths to expectation files to
          read from, or None. If a filepath is specified, |tests| must be None.
      tests: An iterable of strings containing test names to check. If
          specified, |expectation_file| must be None.
      grace_period: An int specifying how many days old an expectation must
          be in order to be parsed, i.e. how many days old an expectation must
          be before it is a candidate for removal/modification.

    Returns:
      A data_types.TestExpectationMap, although all its BuilderStepMap contents
      will be empty.
    """

    def AddContentToMap(content: str, ex_map: data_types.TestExpectationMap,
                        expectation_file_name: str) -> None:
      list_parser = expectations_parser.TaggedTestListParser(content)
      expectations_for_file = ex_map.setdefault(
          expectation_file_name, data_types.ExpectationBuilderMap())
      logging.debug('Parsed %d expectations', len(list_parser.expectations))
      for e in list_parser.expectations:
        if 'Skip' in e.raw_results:
          continue
        # Expectations that only have a Pass expectation (usually used to
        # override a broader, failing expectation) are not handled by the
        # unexpected pass finder, so ignore those.
        if e.raw_results == ['Pass']:
          continue
        expectation = data_types.Expectation(e.test, e.tags, e.raw_results,
                                             e.reason)
        assert expectation not in expectations_for_file
        expectations_for_file[expectation] = data_types.BuilderStepMap()

    logging.info('Creating test expectation map')
    assert expectation_files or tests
    assert not (expectation_files and tests)

    expectation_map = data_types.TestExpectationMap()

    if expectation_files:
      if not isinstance(expectation_files, list):
        expectation_files = [expectation_files]
      for ef in expectation_files:
        # Normalize to '/' as the path separator.
        expectation_file_name = os.path.normpath(ef).replace(os.path.sep, '/')
        content = self._GetNonRecentExpectationContent(expectation_file_name,
                                                       grace_period)
        AddContentToMap(content, expectation_map, expectation_file_name)
    else:
      expectation_file_name = ''
      content = '# results: [ RetryOnFailure ]\n'
      for t in tests:
        content += '%s [ RetryOnFailure ]\n' % t
      AddContentToMap(content, expectation_map, expectation_file_name)

    return expectation_map

  def _GetNonRecentExpectationContent(self, expectation_file_path: str,
                                      num_days: int) -> str:
    """Gets content from |expectation_file_path| older than |num_days| days.

    Args:
      expectation_file_path: A string containing a filepath pointing to an
          expectation file.
      num_days: An int containing how old an expectation in the given
          expectation file must be to be included.

    Returns:
      The contents of the expectation file located at |expectation_file_path|
      as a string with any recent expectations removed.
    """
    num_days = datetime.timedelta(days=num_days)
    content = ''
    # `git blame` output is normally in the format:
    # revision optional_filename (author date time timezone lineno) line_content
    # The --porcelain option is meant to be more machine readable, but is much
    # more difficult to parse for what we need to do here. In order to
    # guarantee that the filename won't be included in the output (by default,
    # it will be shown if there is content from a renamed file), pass -c to
    # use the same format as `git annotate`, which is:
    # revision (author date time timezone lineno)line_content
    # (Note the lack of space between the ) and the content).
    cmd = ['git', 'blame', '-c', expectation_file_path]
    with open(os.devnull, 'w') as devnull:
      blame_output = subprocess.check_output(cmd,
                                             stderr=devnull).decode('utf-8')
    for line in blame_output.splitlines(True):
      match = GIT_BLAME_REGEX.match(line)
      assert match
      date = match.groupdict()['date']
      line_content = match.groupdict()['content']
      if EXPECTATION_LINE_REGEX.match(line):
        if six.PY2:
          date_parts = date.split('-')
          date = datetime.date(year=int(date_parts[0]),
                               month=int(date_parts[1]),
                               day=int(date_parts[2]))
        else:
          date = datetime.date.fromisoformat(date)
        date_diff = datetime.date.today() - date
        if date_diff > num_days:
          content += line_content
        else:
          logging.debug('Omitting expectation %s because it is too new',
                        line_content.rstrip())
      else:
        content += line_content
    return content

  def RemoveExpectationsFromFile(self,
                                 expectations: List[data_types.Expectation],
                                 expectation_file: str,
                                 removal_type: str) -> Set[str]:
    """Removes lines corresponding to |expectations| from |expectation_file|.

    Ignores any lines that match but are within a disable block or have an
    inline disable comment.

    Args:
      expectations: A list of data_types.Expectations to remove.
      expectation_file: A filepath pointing to an expectation file to remove
          lines from.
      removal_type: A RemovalType enum corresponding to the type of expectations
          being removed.

    Returns:
      A set of strings containing URLs of bugs associated with the removed
      expectations.
    """

    with open(expectation_file) as f:
      input_contents = f.read()

    output_contents = ''
    in_disable_block = False
    disable_block_reason = ''
    disable_block_suffix = ''
    removed_urls = set()
    for line in input_contents.splitlines(True):
      # Auto-add any comments or empty lines
      stripped_line = line.strip()
      if _IsCommentOrBlankLine(stripped_line):
        output_contents += line
        # Only allow one enable/disable per line.
        assert len([c for c in ALL_FINDER_COMMENTS if c in line]) <= 1
        # Handle disable/enable block comments.
        if _LineContainsDisableComment(line):
          if in_disable_block:
            raise RuntimeError(
                'Invalid expectation file %s - contains a disable comment "%s" '
                'that is in another disable block.' %
                (expectation_file, stripped_line))
          in_disable_block = True
          disable_block_reason = _GetDisableReasonFromComment(line)
          disable_block_suffix = _GetFinderCommentSuffix(line)
        if _LineContainsEnableComment(line):
          if not in_disable_block:
            raise RuntimeError(
                'Invalid expectation file %s - contains an enable comment "%s" '
                'that is outside of a disable block.' %
                (expectation_file, stripped_line))
          in_disable_block = False
        continue

      current_expectation = self._CreateExpectationFromExpectationFileLine(
          line, expectation_file)

      # Add any lines containing expectations that don't match any of the given
      # expectations to remove.
      if any(e for e in expectations if e == current_expectation):
        # Skip any expectations that match if we're in a disable block or there
        # is an inline disable comment.
        if in_disable_block and _DisableSuffixIsRelevant(
            disable_block_suffix, removal_type):
          output_contents += line
          logging.info(
              'Would have removed expectation %s, but inside a disable block '
              'with reason %s', stripped_line, disable_block_reason)
        elif _LineContainsRelevantDisableComment(line, removal_type):
          output_contents += line
          logging.info(
              'Would have removed expectation %s, but it has an inline disable '
              'comment with reason %s',
              stripped_line.split('#')[0], _GetDisableReasonFromComment(line))
        else:
          bug = current_expectation.bug
          if bug:
            # It's possible to have multiple whitespace-separated bugs per
            # expectation, so treat each one separately.
            removed_urls |= set(bug.split())
      else:
        output_contents += line

    with open(expectation_file, 'w') as f:
      f.write(output_contents)

    return removed_urls

  def _CreateExpectationFromExpectationFileLine(self, line: str,
                                                expectation_file: str
                                                ) -> data_types.Expectation:
    """Creates a data_types.Expectation from |line|.

    Args:
      line: A string containing a single line from an expectation file.
      expectation_file: A filepath pointing to an expectation file |line| came
          from.

    Returns:
      A data_types.Expectation containing the same information as |line|.
    """
    header = self._GetExpectationFileTagHeader(expectation_file)
    single_line_content = header + line
    list_parser = expectations_parser.TaggedTestListParser(single_line_content)
    assert len(list_parser.expectations) == 1
    typ_expectation = list_parser.expectations[0]
    return data_types.Expectation(typ_expectation.test, typ_expectation.tags,
                                  typ_expectation.raw_results,
                                  typ_expectation.reason)

  def _GetExpectationFileTagHeader(self, expectation_file: str) -> str:
    """Gets the tag header used for expectation files.

    Args:
      expectation_file: A filepath pointing to an expectation file to get the
          tag header from.

    Returns:
      A string containing an expectation file header, i.e. the comment block at
      the top of the file defining possible tags and expected results.
    """
    raise NotImplementedError()

  def ModifySemiStaleExpectations(
      self, stale_expectation_map: data_types.TestExpectationMap) -> Set[str]:
    """Modifies lines from |stale_expectation_map| in |expectation_file|.

    Prompts the user for each modification and provides debug information since
    semi-stale expectations cannot be blindly removed like fully stale ones.

    Args:
      stale_expectation_map: A data_types.TestExpectationMap containing stale
          expectations.
      file_handle: An optional open file-like object to output to. If not
          specified, stdout will be used.

    Returns:
      A set of strings containing URLs of bugs associated with the modified
      (manually modified by the user or removed by the script) expectations.
    """
    expectations_to_remove = []
    expectations_to_modify = []
    modified_urls = set()
    for expectation_file, e, builder_map in (
        stale_expectation_map.IterBuilderStepMaps()):
      with open(expectation_file) as infile:
        file_contents = infile.read()
      line, line_number = self._GetExpectationLine(e, file_contents,
                                                   expectation_file)
      expectation_str = None
      if not line:
        logging.error(
            'Could not find line corresponding to semi-stale expectation for '
            '%s with tags %s and expected results %s', e.test, e.tags,
            e.expected_results)
        expectation_str = '[ %s ] %s [ %s ]' % (' '.join(
            e.tags), e.test, ' '.join(e.expected_results))
      else:
        expectation_str = '%s (approx. line %d)' % (line, line_number)

      str_dict = result_output.ConvertBuilderMapToPassOrderedStringDict(
          builder_map)
      print('\nSemi-stale expectation:\n%s' % expectation_str)
      result_output.RecursivePrintToFile(str_dict, 1, sys.stdout)

      response = _WaitForUserInputOnModification()
      if response == 'r':
        expectations_to_remove.append(e)
      elif response == 'm':
        expectations_to_modify.append(e)

      # It's possible that the user will introduce a typo while manually
      # modifying an expectation, which will cause a parser error. Catch that
      # now and give them chances to fix it so that they don't lose all of their
      # work due to an early exit.
      while True:
        try:
          with open(expectation_file) as infile:
            file_contents = infile.read()
          _ = expectations_parser.TaggedTestListParser(file_contents)
          break
        except expectations_parser.ParseError as error:
          logging.error('Got parser error: %s', error)
          logging.error(
              'This probably means you introduced a typo, please fix it.')
          _WaitForAnyUserInput()

      modified_urls |= self.RemoveExpectationsFromFile(expectations_to_remove,
                                                       expectation_file,
                                                       RemovalType.STALE)
    for e in expectations_to_modify:
      modified_urls |= set(e.bug.split())
    return modified_urls

  def _GetExpectationLine(self, expectation: data_types.Expectation,
                          file_contents: str, expectation_file: str
                          ) -> Union[Tuple[None, None], Tuple[str, int]]:
    """Gets the line and line number of |expectation| in |file_contents|.

    Args:
      expectation: A data_types.Expectation.
      file_contents: A string containing the contents read from an expectation
          file.
      expectation_file: A string containing the path to the expectation file
          that |file_contents| came from.

    Returns:
      A tuple (line, line_number). |line| is a string containing the exact line
      in |file_contents| corresponding to |expectation|. |line_number| is an int
      corresponding to where |line| is in |file_contents|. |line_number| may be
      off if the file on disk has changed since |file_contents| was read. If a
      corresponding line cannot be found, both |line| and |line_number| are
      None.
    """
    # We have all the information necessary to recreate the expectation line and
    # line number can be pulled during the initial expectation parsing. However,
    # the information we have is not necessarily in the same order as the
    # text file (e.g. tag ordering), and line numbers can change pretty
    # dramatically between the initial parse and now due to stale expectations
    # being removed. So, parse this way in order to improve the user experience.
    file_lines = file_contents.splitlines()
    for line_number, line in enumerate(file_lines):
      if _IsCommentOrBlankLine(line.strip()):
        continue
      current_expectation = self._CreateExpectationFromExpectationFileLine(
          line, expectation_file)
      if expectation == current_expectation:
        return line, line_number + 1
    return None, None

  def FindOrphanedBugs(self, affected_urls: Iterable[str]) -> Set[str]:
    """Finds cases where expectations for bugs no longer exist.

    Args:
      affected_urls: An iterable of affected bug URLs, as returned by functions
          such as RemoveExpectationsFromFile.

    Returns:
      A set containing a subset of |affected_urls| who no longer have any
      associated expectations in any expectation files.
    """
    seen_bugs = set()

    expectation_files = self.GetExpectationFilepaths()

    for ef in expectation_files:
      with open(ef) as infile:
        contents = infile.read()
      for url in affected_urls:
        if url in seen_bugs:
          continue
        if url in contents:
          seen_bugs.add(url)
    return set(affected_urls) - seen_bugs

  def GetExpectationFilepaths(self) -> List[str]:
    """Gets all the filepaths to expectation files of interest.

    Returns:
      A list of strings, each element being a filepath pointing towards an
      expectation file.
    """
    raise NotImplementedError()

def _WaitForAnyUserInput() -> None:
  """Waits for any user input.

  Split out for testing purposes.
  """
  _get_input('Press any key to continue')

def _WaitForUserInputOnModification() -> str:
  """Waits for user input on how to modify a semi-stale expectation.

  Returns:
    One of the following string values:
      i - Expectation should be ignored and left alone.
      m - Expectation will be manually modified by the user.
      r - Expectation should be removed by the script.
  """
  valid_inputs = ['i', 'm', 'r']
  prompt = ('How should this expectation be handled? (i)gnore/(m)anually '
            'modify/(r)emove: ')
  response = _get_input(prompt).lower()
  while response not in valid_inputs:
    print('Invalid input, valid inputs are %s' % (', '.join(valid_inputs)))
    response = _get_input(prompt).lower()
  return response

def _LineContainsDisableComment(line: str) -> bool:
  return FINDER_DISABLE_COMMENT_BASE in line

def _LineContainsEnableComment(line: str) -> bool:
  return FINDER_ENABLE_COMMENT_BASE in line

def _GetFinderCommentSuffix(line: str) -> str:
  """Gets the suffix of the finder comment on the given line.

  Examples:
    'foo  # finder:disable' -> ''
    'foo  # finder:disable-stale some_reason' -> '-stale'
  """
  target_str = None
  if _LineContainsDisableComment(line):
    target_str = FINDER_DISABLE_COMMENT_BASE
  elif _LineContainsEnableComment(line):
    target_str = FINDER_ENABLE_COMMENT_BASE
  else:
    raise RuntimeError('Given line %s did not have a finder comment.' % line)
  line = line[line.find(target_str):]
  line = line.split()[0]
  suffix = line.replace(target_str, '')
  assert suffix in ALL_FINDER_SUFFIXES
  return suffix

def _LineContainsRelevantDisableComment(line: str, removal_type: str) -> bool:
  """Returns whether the given line contains a relevant disable comment.

  Args:
    line: A string containing the line to check.
    removal_type: A RemovalType enum corresponding to the type of expectations
        being removed.

  Returns:
    A bool denoting whether |line| contains a relevant disable comment given
    |removal_type|.
  """
  if FINDER_DISABLE_COMMENT_GENERAL in line:
    return True
  if FINDER_DISABLE_COMMENT_BASE + removal_type in line:
    return True
  return False

def _DisableSuffixIsRelevant(suffix: str, removal_type: str) -> bool:
  """Returns whether the given suffix is relevant given the removal type.

  Args:
    suffix: A string containing a disable comment suffix.
    removal_type: A RemovalType enum corresponding to the type of expectations
        being removed.

  Returns:
    True if suffix is relevant and its disable request should be honored.
  """
  if suffix == FINDER_COMMENT_SUFFIX_GENERAL:
    return True
  if suffix == removal_type:
    return True
  return False

def _GetDisableReasonFromComment(line: str) -> str:
  suffix = _GetFinderCommentSuffix(line)
  return line.split(FINDER_DISABLE_COMMENT_BASE + suffix, 1)[1].strip()

def _IsCommentOrBlankLine(line: str) -> bool:
  return (not line or line.startswith('#'))

def _get_input(prompt: str) -> str:
  if sys.version_info[0] == 2:
    return raw_input(prompt)
  return input(prompt)


text:
#include "libswresample/swresample.h"
#include "libavutil/arm/neontest.h"

wrap(swr_convert(struct SwrContext *s, uint8_t **out, int out_count,
                 const uint8_t **in , int in_count))
{
    testneonclobbers(swr_convert, s, out, out_count, in, in_count);
}


text:
MEAN-ODATA-Template
===================

A MEAN on oData Template.

Source code example for [A simple website in node.js written in Typescript with express, jade and stylus] base copied from (http://www.clock.co.uk/blog/a-simple-website-in-nodejs-with-express-jade-and-stylus) article.

Build
-----

Run this command in console:

```
npm install
tsd install
bower install
```

All dependencies will be downloaded by `npm` to `node_modules` folder.

All typescript definitions will be downloaded by `tsd` to `typings` folder.

Run
---

Run this command in console:

```
npm start
```

Open `http://localhost:3000` to access index site.

Extend Code
-----------

Run this command for installing new node_modules: `npm run i -- <node_module>` (only shell)

Don't forget to check the message in the console, maybe there is no definition file for the given node_module.. You can find the available typescript definitions here: https://github.com/DefinitelyTyped

MongoDB
-------

You need to download Mongodb (https://www.mongodb.org/) and place the extracted folder in the root directory named 'mongodb'.
Finaly you have to start the mongodb as follow (in case you are already in the root folder):

```
cd mongodb/.bin; ./mongodb
```

Testing
-------
Run this command for testing the basic services: `npm test` (only shell)

Next Steps
----------

In the next step i gonna implement the fronted (client-side jaydata, angular, socket-io etc.)

Please let me know, if you have some improvements and have fun ;)


text:
class VariablesTable;
class BodyTable;
class FuncsTable;
class TypesTable;
class InheritanceTable;
class NamespaceTable;
class TemplateParTypesRelation;

class IdentifyVariable {

public:

    IdentifyVariable(
		VariablesTable *vars,
		BodyTable *bodies,
		FuncsTable *funcs,
		TypesTable *types,
		InheritanceTable *inh,
		NamespaceTable *namespaces,
		TemplateParTypesRelation *tp2t);

	~IdentifyVariable();

	std::string findVariable(AbstractTree &tree);
	void setReset();

private:

	void fillVars(AbstractTree &tree);
	std::string findRelativeGlobal(AbstractTree &tree, bool checkNamespaces);
	std::string findAbsoluteGlobal(AbstractTree &tree);
	std::string findRelativeAttribute(AbstractTree &tree,std::string &the_classId);
	std::string findAbsoluteAttribute(AbstractTree &tree);
	std::string findLocal(AbstractTree& tree);
	std::string findParameter();
	std::string eliminateDecoration(std::string &typeId);

	VariablesTable *vars;
	BodyTable *bodies;
	FuncsTable *funcs;
	TypesTable *types;
	InheritanceTable *inh;
	NamespaceTable *namespaces;
	TemplateParTypesRelation *tp2t;

	std::string this_bodyId;
	std::string this_namespace;
	std::string this_classId;

	bool reset;
	Table::RowSet *possibleName;
	Table::RowSet *possibleLocal;
	Table::RowSet *possibleParam;
	Table::RowSet *possibleAttrLoc;
	Table::RowSet *possibleAttr;
	Table::RowSet *possibleGlobal;

};
#endif //IDENTIFYVARIABLE_H