text:
"""
Test for ecommerce functions
"""
# pylint: disable=too-many-lines
from base64 import b64encode
from datetime import datetime, timedelta
from decimal import Decimal
import hashlib
import hmac
from pathlib import Path
from types import SimpleNamespace

from django.contrib.auth import get_user_model
from django.core.mail import EmailMessage
from django.core.management.base import CommandError
import pytest
import pytz
from rest_framework.exceptions import ValidationError
from mitol.common.pytest_utils import any_instance_of

from applications.constants import AppStates
from applications.factories import BootcampApplicationFactory
from applications.models import BootcampApplication
from ecommerce.api import (
    generate_cybersource_sa_payload,
    generate_cybersource_sa_signature,
    get_new_order_by_reference_number,
    import_wire_transfers,
    import_wire_transfer,
    ISO_8601_FORMAT,
    make_reference_id,
    parse_wire_transfer_csv,
    serialize_user_bootcamp_run,
    serialize_user_bootcamp_runs,
    send_receipt_email,
    create_refund_order,
    complete_successful_order,
    process_refund,
    WireTransfer,
)
from ecommerce.exceptions import (
    EcommerceException,
    ParseException,
    WireTransferImportException,
)
from ecommerce.factories import LineFactory, OrderFactory
from ecommerce.models import Line, Order, WireTransferReceipt
from ecommerce.serializers import LineSerializer
from ecommerce.test_utils import create_test_application, create_test_order
from klasses.constants import ENROLL_CHANGE_STATUS_REFUNDED
from klasses.factories import (
    BootcampRunFactory,
    InstallmentFactory,
    BootcampRunEnrollmentFactory,
)
from klasses.models import BootcampRun, BootcampRunEnrollment
from klasses.serializers import InstallmentSerializer
from profiles.factories import ProfileFactory

pytestmark = pytest.mark.django_db
User = get_user_model()

# pylint: disable=redefined-outer-name, unused-argument
@pytest.fixture
def application():
    """An application for testing"""
    yield create_test_application()

@pytest.fixture
def user(application):
    """A user with social auth"""
    yield application.user

@pytest.fixture
def bootcamp_run(application):
    """
    Creates a purchasable bootcamp run. Bootcamp run price is at least $200, in two installments
    """
    yield application.bootcamp_run

@pytest.fixture
def paid_order_elements():
    """
    Sets up a scenario where a fully-paid order has been created for a bootcamp application
    """
    installment = InstallmentFactory.create()
    application = BootcampApplicationFactory.create(
        bootcamp_run=installment.bootcamp_run, state=AppStates.AWAITING_PAYMENT
    )
    order = OrderFactory.create(
        status=Order.CREATED,
        total_price_paid=installment.amount,
        application=application,
        user=application.user,
    )
    line = LineFactory.create(
        order=order, price=installment.amount, bootcamp_run=application.bootcamp_run
    )
    return SimpleNamespace(
        order=order,
        line=line,
        run=installment.bootcamp_run,
        application=application,
        user=application.user,
    )

@pytest.fixture()
def patched_novoed_tasks(mocker):
    """Patched novoed-related tasks"""
    return mocker.patch("klasses.api.novoed_tasks")

@pytest.mark.parametrize("payment_amount", [0, -1.23])
def test_less_or_equal_to_zero(application, payment_amount):
    """
    An order may not have a negative or zero price
    """
    with pytest.raises(ValidationError) as ex:
        create_test_order(application, payment_amount, fulfilled=False)

    assert ex.value.args[0] == "Payment is less than or equal to zero"

CYBERSOURCE_ACCESS_KEY = "access"
CYBERSOURCE_PROFILE_ID = "profile"
CYBERSOURCE_SECURITY_KEY = "security"
CYBERSOURCE_REFERENCE_PREFIX = "prefix"

@pytest.fixture(autouse=True)
def cybersource_settings(settings):
    """
    Set some Cybersource settings
    """
    settings.CYBERSOURCE_ACCESS_KEY = CYBERSOURCE_ACCESS_KEY
    settings.CYBERSOURCE_PROFILE_ID = CYBERSOURCE_PROFILE_ID
    settings.CYBERSOURCE_SECURITY_KEY = CYBERSOURCE_SECURITY_KEY
    settings.CYBERSOURCE_REFERENCE_PREFIX = CYBERSOURCE_REFERENCE_PREFIX

def test_valid_signature():
    """
    Signature is made up of a ordered key value list signed using HMAC 256 with a security key
    """
    payload = {"x": "y", "abc": "def", "key": "value", "signed_field_names": "abc,x"}
    signature = generate_cybersource_sa_signature(payload)

    message = ",".join("{}={}".format(key, payload[key]) for key in ["abc", "x"])

    digest = hmac.new(
        CYBERSOURCE_SECURITY_KEY.encode("utf-8"),
        msg=message.encode("utf-8"),
        digestmod=hashlib.sha256,
    ).digest()

    assert b64encode(digest).decode("utf-8") == signature

@pytest.mark.parametrize("user_ip", ["194.100.0.1", "", None])
def test_signed_payload(mocker, application, bootcamp_run, user_ip):
    """
    A valid payload should be signed appropriately
    """
    payment = 123.45
    order = create_test_order(application, payment, fulfilled=False)
    transaction_uuid = "hex"

    now = datetime.now(tz=pytz.UTC)
    now_mock = mocker.MagicMock(return_value=now)

    mocker.patch("ecommerce.api.datetime", autospec=True, now=now_mock)
    mocker.patch(
        "ecommerce.api.uuid.uuid4",
        autospec=True,
        return_value=mocker.MagicMock(hex=transaction_uuid),
    )

    payload = generate_cybersource_sa_payload(
        order, "dashboard_url", ip_address=user_ip
    )
    signature = payload.pop("signature")
    assert generate_cybersource_sa_signature(payload) == signature
    signed_field_names = payload["signed_field_names"].split(",")
    assert signed_field_names == sorted(payload.keys())

    expected_payload = {
        "access_key": CYBERSOURCE_ACCESS_KEY,
        "amount": str(order.total_price_paid),
        "currency": "USD",
        "item_0_code": "klass",
        "item_0_name": "{}".format(bootcamp_run.title),
        "item_0_quantity": 1,
        "item_0_sku": "{}".format(bootcamp_run.run_key),
        "item_0_tax_amount": "0",
        "item_0_unit_price": str(order.total_price_paid),
        "line_item_count": 1,
        "locale": "en-us",
        "override_custom_cancel_page": "dashboard_url?status=cancel",
        "override_custom_receipt_page": "dashboard_url?status=receipt&order={}&award={}".format(
            order.id, bootcamp_run.run_key
        ),
        "reference_number": make_reference_id(order),
        "profile_id": CYBERSOURCE_PROFILE_ID,
        "signed_date_time": now.strftime(ISO_8601_FORMAT),
        "signed_field_names": ",".join(signed_field_names),
        "transaction_type": "sale",
        "transaction_uuid": transaction_uuid,
        "unsigned_field_names": "",
        "merchant_defined_data1": "bootcamp",
        "merchant_defined_data2": "{}".format(bootcamp_run.bootcamp.title),
        "merchant_defined_data3": "klass",
        "merchant_defined_data4": "{}".format(bootcamp_run.title),
        "merchant_defined_data5": "{}".format(bootcamp_run.run_key),
        "merchant_defined_data6": "learner",
        "merchant_defined_data7": "{}".format(order.user.profile.name),
        "merchant_defined_data8": "{}".format(order.user.email),
    }
    if user_ip:
        expected_payload["customer_ip_address"] = user_ip
    assert payload == expected_payload
    now_mock.assert_called_with(tz=pytz.UTC)

@pytest.mark.parametrize("invalid_title", ["", "

"])
def test_with_empty_or_html_run_title(application, bootcamp_run, invalid_title):
    """Verify that Validation error raises if title of bootcamp run has only HTML or empty."""
    bootcamp_run.title = invalid_title
    bootcamp_run.save()
    order = create_test_order(application, "123.45", fulfilled=False)
    with pytest.raises(ValidationError) as ex:
        generate_cybersource_sa_payload(order, "dashboard_url")

    assert ex.value.args[
        0
    ] == "Bootcamp run {run_key} title is either empty or contains only HTML.".format(
        run_key=bootcamp_run.run_key
    )

@pytest.mark.parametrize("invalid_title", ["", "

"])
def test_with_empty_or_html_bootcamp_title(application, bootcamp_run, invalid_title):
    """Verify that Validation error raises if title of bootcamp has only HTML or empty."""
    bootcamp_run.bootcamp.title = invalid_title
    bootcamp_run.bootcamp.save()
    order = create_test_order(application, "123.45", fulfilled=False)
    with pytest.raises(ValidationError) as ex:
        generate_cybersource_sa_payload(order, "dashboard_url")

    assert ex.value.args[
        0
    ] == "Bootcamp {bootcamp_id} title is either empty or contains only HTML.".format(
        bootcamp_id=bootcamp_run.bootcamp.id
    )

def test_make_reference_id(application):
    """
    make_reference_id should concatenate the reference prefix and the order id
    """
    order = create_test_order(application, 123, fulfilled=False)
    assert "BOOTCAMP-{}-{}".format(
        CYBERSOURCE_REFERENCE_PREFIX, order.id
    ) == make_reference_id(order)

def test_get_new_order_by_reference_number(application):
    """
    get_new_order_by_reference_number returns an Order with status created
    """
    order = create_test_order(application, 123, fulfilled=False)
    same_order = get_new_order_by_reference_number(make_reference_id(order))
    assert same_order.id == order.id

@pytest.mark.parametrize(
    "reference_number, exception_message",
    [
        ("XYZ-1-3", "Reference number must start with BOOTCAMP-"),
        ("BOOTCAMP-no_dashes_here", "Unable to find order number in reference number"),
        ("BOOTCAMP-something-NaN", "Unable to parse order number"),
        ("BOOTCAMP-not_matching-3", "CyberSource prefix doesn't match"),
    ],
)
def test_parse(reference_number, exception_message):
    """
    Test parse errors are handled well
    """
    with pytest.raises(ParseException) as ex:
        get_new_order_by_reference_number(reference_number)
    assert ex.value.args[0] == exception_message

def test_status(application):
    """
    get_order_by_reference_number should only get orders with status=CREATED
    """
    order = create_test_order(application, 123, fulfilled=False)
    order.status = Order.FAILED
    order.save()

    with pytest.raises(EcommerceException) as ex:
        # change order number to something not likely to already exist in database
        order.id = 98_765_432
        assert not Order.objects.filter(id=order.id).exists()
        get_new_order_by_reference_number(make_reference_id(order))
    assert ex.value.args[0] == "Unable to find order {}".format(order.id)

@pytest.fixture()
def test_data():
    """
    Sets up the data for all the tests in this module
    """
    profile = ProfileFactory.create()
    run_paid = BootcampRunFactory.create()
    BootcampApplicationFactory.create(
        bootcamp_run=run_paid, user=profile.user, state=AppStates.AWAITING_PAYMENT.value
    )
    run_not_paid = BootcampRunFactory.create()
    BootcampApplicationFactory.create(
        bootcamp_run=run_not_paid,
        user=profile.user,
        state=AppStates.AWAITING_PAYMENT.value,
    )

    InstallmentFactory.create(bootcamp_run=run_paid)
    InstallmentFactory.create(bootcamp_run=run_not_paid)

    order = OrderFactory.create(user=profile.user, status=Order.FULFILLED)
    LineFactory.create(order=order, bootcamp_run=run_paid, price=627.34)

    return profile.user, run_paid, run_not_paid

def test_serialize_user_run_paid(test_data):
    """
    Test for serialize_user_bootcamp_run for a paid bootcamp run
    """
    user, run_paid, _ = test_data

    expected_ret = {
        "run_key": run_paid.run_key,
        "bootcamp_run_name": run_paid.title,
        "display_title": run_paid.display_title,
        "start_date": run_paid.start_date,
        "end_date": run_paid.end_date,
        "price": run_paid.personal_price(user),
        "total_paid": Decimal("627.34"),
        "payments": LineSerializer(
            Line.for_user_bootcamp_run(user, run_paid), many=True
        ).data,
        "installments": InstallmentSerializer(
            run_paid.installment_set.order_by("deadline"), many=True
        ).data,
    }
    assert expected_ret == serialize_user_bootcamp_run(user, run_paid)

def test_serialize_user_run_not_paid(test_data):
    """
    Test for serialize_user_bootcamp_run for a not paid bootcamp run
    """
    user, _, run_not_paid = test_data

    expected_ret = {
        "run_key": run_not_paid.run_key,
        "bootcamp_run_name": run_not_paid.title,
        "display_title": run_not_paid.display_title,
        "start_date": run_not_paid.start_date,
        "end_date": run_not_paid.end_date,
        "price": run_not_paid.personal_price(user),
        "total_paid": Decimal("0.00"),
        "payments": [],
        "installments": InstallmentSerializer(
            run_not_paid.installment_set.order_by("deadline"), many=True
        ).data,
    }
    assert expected_ret == serialize_user_bootcamp_run(user, run_not_paid)

def test_serialize_user_bootcamp_runs(test_data):
    """
    Test for serialize_user_bootcamp_runs in normal case
    """
    user, run_paid, run_not_paid = test_data
    expected_ret = [
        {
            "run_key": run_paid.run_key,
            "bootcamp_run_name": run_paid.title,
            "display_title": run_paid.display_title,
            "start_date": run_paid.start_date,
            "end_date": run_paid.end_date,
            "price": run_paid.price,
            "total_paid": Decimal("627.34"),
            "payments": LineSerializer(
                Line.for_user_bootcamp_run(user, run_paid), many=True
            ).data,
            "installments": InstallmentSerializer(
                run_paid.installment_set.order_by("deadline"), many=True
            ).data,
        },
        {
            "run_key": run_not_paid.run_key,
            "bootcamp_run_name": run_not_paid.title,
            "display_title": run_not_paid.display_title,
            "start_date": run_not_paid.start_date,
            "end_date": run_not_paid.end_date,
            "price": run_not_paid.price,
            "total_paid": Decimal("0.00"),
            "payments": [],
            "installments": InstallmentSerializer(
                run_not_paid.installment_set.order_by("deadline"), many=True
            ).data,
        },
    ]
    assert sorted(
        expected_ret, key=lambda x: x["run_key"]
    ) == serialize_user_bootcamp_runs(user)

def test_send_verify_email_change_email(mocker, user):
    """Test send_receipt_email sends a receipt email"""
    application = BootcampApplicationFactory.create()
    OrderFactory.create(
        application=application, user=application.user, status=Order.FULFILLED
    )

    send_messages_mock = mocker.patch("mail.v2.api.send_messages")

    send_receipt_email(application.id)

    send_messages_mock.assert_called_once_with([any_instance_of(EmailMessage)])

    email = send_messages_mock.call_args[0][0][0]
    assert application.bootcamp_run.title in email.body

@pytest.mark.parametrize("has_enrollment", [True, False])
@pytest.mark.parametrize("has_application", [True, False])
def test_refund_enrollment(patched_novoed_tasks, has_enrollment, has_application, user):
    """
    Test that deactivate_run_enrollment creates a refund order and
    updates enrollment and application objects
    """
    bootcamp_run = BootcampRunFactory.create(novoed_course_stub=None)
    if has_enrollment:
        BootcampRunEnrollmentFactory.create(bootcamp_run=bootcamp_run, user=user)
    application = (
        BootcampApplicationFactory.create(
            user=user, bootcamp_run=bootcamp_run, state=AppStates.COMPLETE
        )
        if has_application
        else None
    )
    refund_amount = 1.50
    LineFactory.create(
        price=3,
        bootcamp_run=bootcamp_run,
        order=OrderFactory(
            user=user,
            application=application,
            status=Order.FULFILLED,
            total_price_paid=3,
        ),
    )
    process_refund(user=user, bootcamp_run=bootcamp_run, amount=refund_amount)
    enrollment = BootcampRunEnrollment.objects.filter(
        user=user, bootcamp_run=bootcamp_run
    ).first()
    if has_enrollment:
        assert enrollment is not None
        assert enrollment.active is False
        assert enrollment.change_status == ENROLL_CHANGE_STATUS_REFUNDED
    else:
        assert enrollment is None
    order = Order.objects.get(
        total_price_paid=-refund_amount, application=application, user=user
    )
    assert order.status == Order.FULFILLED
    assert Line.objects.filter(
        order=order,
        price=-refund_amount,
        description="Refund for {}".format(bootcamp_run.title),
    ).exists()
    if has_application:
        assert (
            BootcampApplication.objects.get(id=application.id).state
            == AppStates.REFUNDED.value
        )

@pytest.mark.parametrize("has_application", [True, False])
def test_refund_exceeds_payment(has_application, user):
    """
    Test that refunded amount cannot exceed total paid
    """
    bootcamp_run = BootcampRunFactory.create()
    application = (
        BootcampApplicationFactory.create(
            user=user, bootcamp_run=bootcamp_run, state=AppStates.COMPLETE
        )
        if has_application
        else None
    )
    # Create 3 orders totalling $30 in payments
    orders = OrderFactory.create_batch(
        3,
        user=user,
        application=application,
        status=Order.FULFILLED,
        total_price_paid=10,
    )
    for order in orders:
        LineFactory.create(price=10, bootcamp_run=bootcamp_run, order=order)

    with pytest.raises(EcommerceException) as exc:
        process_refund(user=user, bootcamp_run=bootcamp_run, amount=45.50)
    assert exc.value.args[0] == "Refund exceeds total payment of $30.00"
    process_refund(user=user, bootcamp_run=bootcamp_run, amount=11)
    process_refund(user=user, bootcamp_run=bootcamp_run, amount=11)
    with pytest.raises(EcommerceException) as exc:
        process_refund(user=user, bootcamp_run=bootcamp_run, amount=11)
    assert exc.value.args[0] == "Refund exceeds total payment of $8.00"

@pytest.mark.parametrize("amount", [-5, 0])
def test_bad_refund_amount(amount):
    """Test that an invalid refund amount raises an exception"""
    enrollment = BootcampRunEnrollmentFactory.create()
    with pytest.raises(EcommerceException) as exc:
        create_refund_order(
            user=enrollment.user, bootcamp_run=enrollment.bootcamp_run, amount=amount
        )
    assert exc.value.args[0] == "Amount to refund must be greater than zero"

@pytest.mark.parametrize("enrollment_exists", [True, False])
def test_complete_successful_order(paid_order_elements, enrollment_exists):
    """Test that enrollment, application values updated correctly on successful order"""
    if enrollment_exists:
        BootcampRunEnrollmentFactory.create(
            user=paid_order_elements.user,
            bootcamp_run=paid_order_elements.run,
            active=False,
            change_status=ENROLL_CHANGE_STATUS_REFUNDED,
        )
    complete_successful_order(paid_order_elements.order)
    assert (
        BootcampApplication.objects.filter(
            id=paid_order_elements.application.id, state=AppStates.COMPLETE.value
        ).exists()
        is True
    )
    enrollment = BootcampRunEnrollment.objects.get(
        user=paid_order_elements.user, bootcamp_run=paid_order_elements.run
    )
    assert enrollment.active is True
    assert enrollment.change_status is None

@pytest.mark.parametrize(
    "feature_flag,has_stub",
    [[True, True], [True, False], [False, True], [False, False]],
)
def test_complete_successful_order_novoed(
    mocker, settings, paid_order_elements, feature_flag, has_stub
):
    """
    complete_successful_order should call a task that enrolls the given user in a NovoEd course
    """
    patched_novoed_tasks = mocker.patch("klasses.api.novoed_tasks")
    settings.FEATURES["NOVOED_INTEGRATION"] = feature_flag
    if not has_stub:
        paid_order_elements.run.novoed_course_stub = None
        paid_order_elements.run.save()
    complete_successful_order(paid_order_elements.order)
    if feature_flag and has_stub:
        patched_novoed_tasks.enroll_users_in_novoed_course.delay.assert_called_once_with(
            user_ids=[paid_order_elements.user.id],
            novoed_course_stub=paid_order_elements.run.novoed_course_stub,
        )
    else:
        patched_novoed_tasks.enroll_users_in_novoed_course.delay.assert_not_called()

@pytest.mark.parametrize(
    "feature_flag,has_stub",
    [[True, True], [True, False], [False, True], [False, False]],
)
def test_refund_novoed(
    settings, paid_order_elements, patched_novoed_tasks, feature_flag, has_stub
):
    """
    process_refund should call a task that unenrolls the user from a NovoEd course
    """
    settings.FEATURES["NOVOED_INTEGRATION"] = feature_flag
    if not has_stub:
        paid_order_elements.run.novoed_course_stub = None
        paid_order_elements.run.save()
    paid_order_elements.order.status = Order.FULFILLED
    paid_order_elements.order.save()
    BootcampRunEnrollmentFactory.create(
        user=paid_order_elements.user, bootcamp_run=paid_order_elements.run
    )
    process_refund(
        user=paid_order_elements.user,
        bootcamp_run=paid_order_elements.run,
        amount=paid_order_elements.line.price,
    )
    if feature_flag and has_stub:
        patched_novoed_tasks.unenroll_user_from_novoed_course.delay.assert_called_once_with(
            user_id=paid_order_elements.user.id,
            novoed_course_stub=paid_order_elements.run.novoed_course_stub,
        )
    else:
        patched_novoed_tasks.unenroll_user_from_novoed_course.delay.assert_not_called()

def test_parse_wire_transfer_csv():
    """parse_wire_transfer_csv should convert CSV input to WireTransfer objects"""
    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)
    assert header_row == [
        "Id",
        "Date transfers requested ",
        "Learner Email",
        "Zendesk Ticket",
        "Bootcamp ID",
        "Payor Name",
        "Learner email",
        "Payment Date",
        "Bootcamp Name",
        "Bootcamp Start Date",
        "Amount",
        "Transfer Type",
        "SAP doc # - Cash Application",
        "Order Updated By",
        "Refund Order ID",
        "Order Completed Date",
        "Errors",
        "Ignore?",
    ]
    assert wire_transfers == [
        WireTransfer(
            id=2,
            learner_email="hdoof@odl.mit.edu",
            amount=Decimal(100),
            bootcamp_start_date=datetime(2019, 12, 21),
            bootcamp_name="How to be Evil",
            row=[
                "2",
                "11/1/1973",
                "hdoof@odl.mit.edu",
                "",
                "1",
                "Heinz Doofenschmirtz",
                "hdoof@odl.mit.edu",
                "Oct 20, 2019",
                "How to be Evil",
                "Dec 21, 2019",
                "100",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
            ],
        ),
        WireTransfer(
            id=3,
            learner_email="pplatypus@odl.mit.edu",
            amount=Decimal(50),
            bootcamp_start_date=datetime(2019, 12, 21),
            bootcamp_name="How to be Evil",
            row=[
                "3",
                "11/1/1944",
                "pplatypus@odl.mit.edu",
                "",
                "1",
                "Perry the Platypus",
                "pplatypus@odl.mit.edu",
                "Oct 20, 2019",
                "How to be Evil",
                "Dec 21, 2019",
                "50",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
            ],
        ),
    ]

def test_parse_wire_transfer_csv_no_header(tmp_path):
    """parse_wire_transfer_csv should error if no header is found"""
    path = tmp_path / "test.csv"
    open(path, "w")  # create file
    with pytest.raises(WireTransferImportException) as ex:
        parse_wire_transfer_csv(path)

    assert ex.value.args[0] == "Unable to find header row"

def test_parse_wire_transfer_csv_missing_header(tmp_path):
    """parse_wire_transfer_csv should error if not all fields are present"""
    path = tmp_path / "test.csv"
    with open(path, "w") as f:
        f.write("Learner Email,Id\n")
        f.write("hdoof@odl.mit.edu,20\n")

    with pytest.raises(WireTransferImportException) as ex:
        parse_wire_transfer_csv(path)

    assert ex.value.args[0] == "Unable to find column header Amount"

@pytest.mark.parametrize(
    "with_bootcamp_title,with_run_title",
    [
        [True, True],
        [True, False],
        [False, True],  # False, False is an error handled in a separate test
    ],
)
def test_import_wire_transfer(with_bootcamp_title, with_run_title):
    """import_wire_transfer should store a wire transfer in the database and create an order for it"""
    user = User.objects.create(email="hdoof@odl.mit.edu")
    title = "How to be Evil"
    run = BootcampRunFactory.create(
        **{"title": title} if with_run_title else {},
        **{"bootcamp__title": title} if with_bootcamp_title else {},
    )
    application = BootcampApplicationFactory.create(bootcamp_run=run, user=user)
    wire_transfer = WireTransfer(
        id=2,
        learner_email=user.email,
        amount=Decimal(100),
        bootcamp_start_date=run.start_date,
        bootcamp_name=run.bootcamp.title,
        row=[],
    )
    import_wire_transfer(wire_transfer, [])
    receipt = WireTransferReceipt.objects.get(wire_transfer_id=wire_transfer.id)
    assert receipt.data == {}
    order = receipt.order
    assert order.status == Order.FULFILLED
    assert order.total_price_paid == wire_transfer.amount
    assert order.application == application
    assert order.user == user
    assert order.payment_type == Order.WIRE_TRANSFER_TYPE
    line = order.line_set.get()
    assert line.price == wire_transfer.amount
    assert line.bootcamp_run == run
    assert order.orderaudit_set.count() == 1

    # function should handle importing twice by skipping the second import attempt
    import_wire_transfer(wire_transfer, [])
    assert WireTransferReceipt.objects.count() == 1
    assert Order.objects.count() == 1
    assert Line.objects.count() == 1

def test_import_wire_transfer_missing_user():
    """import_wire_transfer should error if a user does not exist"""
    wire_transfer = WireTransfer(
        id=2,
        learner_email="hdoof@odl.mit.edu",
        amount=Decimal(100),
        bootcamp_start_date=datetime(2019, 12, 21),
        bootcamp_name="How to be Evil",
        row=[],
    )
    with pytest.raises(User.DoesNotExist):
        import_wire_transfer(wire_transfer, [])

def test_import_wire_transfers_missing_run():
    """import_wire_transfer should error if a run doesn't match up with anything in the database"""
    doof_email = "hdoof@odl.mit.edu"
    User.objects.create(email=doof_email)
    wire_transfer = WireTransfer(
        id=2,
        learner_email=doof_email,
        amount=Decimal(100),
        bootcamp_start_date=datetime(2019, 12, 21),
        bootcamp_name="How to be Evil",
        row=[],
    )
    with pytest.raises(BootcampRun.DoesNotExist):
        import_wire_transfer(wire_transfer, [])

def test_import_wire_transfers_duplicate_run():
    """import_wire_transfer should error if a title matches two separate runs"""
    doof_email = "hdoof@odl.mit.edu"
    title = "How to be Evil"
    run = BootcampRunFactory.create(bootcamp__title=title)
    BootcampRunFactory.create(title=title, start_date=run.start_date)
    User.objects.create(email=doof_email)
    wire_transfer = WireTransfer(
        id=2,
        learner_email=doof_email,
        amount=Decimal(100),
        bootcamp_start_date=run.start_date,
        bootcamp_name=title,
        row=[],
    )
    with pytest.raises(BootcampRun.MultipleObjectsReturned):
        import_wire_transfer(wire_transfer, [])

@pytest.mark.parametrize("delta", [timedelta(days=2), timedelta(days=-2)])
def test_import_wire_transfers_run_out_of_bounds_date(delta):
    """import_wire_transfer should error if the given starting date for a bootcamp doesn't match any run"""
    doof_email = "hdoof@odl.mit.edu"
    run = BootcampRunFactory.create(bootcamp__title="How to be Evil")
    User.objects.create(email=doof_email)
    wire_transfer = WireTransfer(
        id=2,
        learner_email=doof_email,
        amount=Decimal(100),
        bootcamp_start_date=run.start_date + delta,
        bootcamp_name=run.bootcamp.title,
        row=[...],
    )
    with pytest.raises(BootcampRun.DoesNotExist):
        import_wire_transfer(wire_transfer, [])

def test_import_wire_transfers_missing_application():
    """import_wire_transfer should error if a user hasn't created an application yet"""
    doof_email = "hdoof@odl.mit.edu"
    User.objects.create(email=doof_email)
    run = BootcampRunFactory.create(bootcamp__title="How to be Evil")
    wire_transfer = WireTransfer(
        id=2,
        learner_email=doof_email,
        amount=Decimal(100),
        bootcamp_start_date=run.start_date,
        bootcamp_name=run.bootcamp.title,
        row=[],
    )
    with pytest.raises(BootcampApplication.DoesNotExist):
        import_wire_transfer(wire_transfer, [])

def test_import_wire_transfers_update_receipt(mocker):
    """check for update receipt"""
    mocker.patch("ecommerce.api.tasks.send_receipt_email")
    doof_email = "hdoof@odl.mit.edu"
    user = User.objects.create(email=doof_email)
    run = BootcampRunFactory.create(
        bootcamp__title="How to be Evil", start_date=datetime(2019, 12, 21)
    )
    BootcampApplicationFactory.create(
        bootcamp_run=run, user=user, state=AppStates.AWAITING_PAYMENT.value
    )

    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)
    import_wire_transfer(wire_transfers[0], header_row, False)
    receipt = WireTransferReceipt.objects.get(wire_transfer_id=2)
    assert receipt.data["SAP doc # - Cash Application"] == ""
    wire_transfers[0].row[12] = "TBD"
    import_wire_transfer(wire_transfers[0], header_row, False)
    receipt.refresh_from_db()
    assert receipt.data["SAP doc # - Cash Application"] == "TBD"

def test_import_wire_transfers_update_existing_order_amount(mocker):
    """check for update order amount and receipt"""
    mocker.patch("ecommerce.api.tasks.send_receipt_email")
    doof_email = "hdoof@odl.mit.edu"
    user = User.objects.create(email=doof_email)
    run = BootcampRunFactory.create(
        bootcamp__title="How to be Evil", start_date=datetime(2019, 12, 21)
    )
    BootcampApplicationFactory.create(
        bootcamp_run=run, user=user, state=AppStates.AWAITING_PAYMENT.value
    )

    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)

    import_wire_transfer(wire_transfers[0], header_row, False)
    receipt = WireTransferReceipt.objects.get(wire_transfer_id=2)
    assert receipt.data["Amount"] == "100"
    assert receipt.order.total_price_paid == 100.00
    wire_transfers[0].row[10] = "50"
    wire_transfer = WireTransfer(
        id=wire_transfers[0].id,
        learner_email=wire_transfers[0].learner_email,
        amount=Decimal(50),
        bootcamp_start_date=wire_transfers[0].bootcamp_start_date,
        bootcamp_name=wire_transfers[0].bootcamp_name,
        row=wire_transfers[0].row,
    )
    with pytest.raises(CommandError):
        import_wire_transfer(wire_transfer, header_row, False)
    import_wire_transfer(wire_transfer, header_row, True)
    receipt.refresh_from_db()
    assert receipt.data["Amount"] == "50"
    assert receipt.order.total_price_paid == 50.00

def test_import_wire_transfers_update_existing_order_user(mocker):
    """check for update order user and receipt"""
    mocker.patch("ecommerce.api.tasks.send_receipt_email")
    doof_email = "hdoof@odl.mit.edu"
    pretty_platypus_email = "pplatypus@odl.mit.edu"
    user = User.objects.create(email=doof_email)
    pretty_platypus = User.objects.create(
        email=pretty_platypus_email, username="pplatypus"
    )
    run = BootcampRunFactory.create(
        bootcamp__title="How to be Evil", start_date=datetime(2019, 12, 21)
    )
    for _user in [user, pretty_platypus]:
        BootcampApplicationFactory.create(
            bootcamp_run=run, user=_user, state=AppStates.AWAITING_PAYMENT.value
        )

    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)

    import_wire_transfer(wire_transfers[0], header_row, False)
    receipt = WireTransferReceipt.objects.get(wire_transfer_id=2)
    assert receipt.data["Learner Email"] == doof_email
    assert receipt.order.user.email == doof_email
    wire_transfers[0].row[2] = wire_transfers[0].row[6] = pretty_platypus_email
    wire_transfer = WireTransfer(
        id=wire_transfers[0].id,
        learner_email=pretty_platypus_email,
        amount=wire_transfers[0].amount,
        bootcamp_start_date=wire_transfers[0].bootcamp_start_date,
        bootcamp_name=wire_transfers[0].bootcamp_name,
        row=wire_transfers[0].row,
    )
    with pytest.raises(CommandError):
        import_wire_transfer(wire_transfer, header_row, False)
    import_wire_transfer(wire_transfer, header_row, True)
    receipt.refresh_from_db()
    assert receipt.data["Learner Email"] == pretty_platypus_email
    assert receipt.order.user.email == pretty_platypus_email

def test_import_wire_transfers_update_existing_order_bootcamp(mocker):
    """check for update order bootcamp and receipt"""
    mocker.patch("ecommerce.api.tasks.send_receipt_email")
    doof_email = "hdoof@odl.mit.edu"
    user = User.objects.create(email=doof_email)
    run = BootcampRunFactory.create(
        bootcamp__title="How to be Evil", start_date=datetime(2019, 12, 21)
    )
    bootcamp_run = BootcampRunFactory.create(
        bootcamp__title="How to be Good", start_date=datetime(2019, 12, 21)
    )
    for _run in [run, bootcamp_run]:
        BootcampApplicationFactory.create(
            bootcamp_run=_run, user=user, state=AppStates.AWAITING_PAYMENT.value
        )

    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)

    import_wire_transfer(wire_transfers[0], header_row, False)
    receipt = WireTransferReceipt.objects.get(wire_transfer_id=2)
    assert receipt.data["Bootcamp Name"] == "How to be Evil"
    assert receipt.order.application.bootcamp_run == run
    wire_transfers[0].row[8] = "How to be Good"
    wire_transfer = WireTransfer(
        id=wire_transfers[0].id,
        learner_email=wire_transfers[0].learner_email,
        amount=Decimal(50),
        bootcamp_start_date=wire_transfers[0].bootcamp_start_date,
        bootcamp_name="How to be Good",
        row=wire_transfers[0].row,
    )
    with pytest.raises(CommandError):
        import_wire_transfer(wire_transfer, header_row, False)
    import_wire_transfer(wire_transfer, header_row, True)
    receipt.refresh_from_db()
    assert receipt.data["Bootcamp Name"] == "How to be Good"
    assert receipt.order.application.bootcamp_run == bootcamp_run

def test_import_wire_transfers(mocker):
    """import_wire_transfers should iterate through the list of wire transfers, processing one at a time"""
    import_mock = mocker.patch("ecommerce.api.import_wire_transfer")
    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    import_wire_transfers(csv_path)
    wire_transfers, header_row = parse_wire_transfer_csv(csv_path)
    for wire_transfer in wire_transfers:
        import_mock.assert_any_call(wire_transfer, header_row, False)

def test_import_wire_transfers_error(mocker):
    """import_wire_transfers should reraise errors"""
    mocker.patch("ecommerce.api.import_wire_transfer", side_effect=ZeroDivisionError)
    csv_path = Path(__file__).parent / "testdata" / "example_wire_transfers.csv"
    with pytest.raises(WireTransferImportException):
        import_wire_transfers(csv_path)


text:
from flask import Blueprint, jsonify, request

class Model(object):
    def __init__(self, model=None, db=None):
        self.model = None
        self.db = None
        if model is not None:
            self.init_model(model)
        if db is not None:
            self.init_db(db)

    def init_db(self, db):
        self.db = db

    def init_model(self, model):
        if model is None:
            raise ValueError("Invalid value None for model init")
        self.model = model
        self.alias = str(model.__table__)
        self.fields = model.__table__.columns.keys()
        self.fields_type = {}
        for column in model.__table__.columns:
            self.fields_type[column.name] = column.type.python_type

    def make_blueprint(self):
        if self.model is None or self.db is None:
            raise ValueError("Model or db not initiated.")
        blueprint = Blueprint(self.alias, __name__, url_prefix='/')

        @blueprint.route('/' + self.alias, methods=['GET', 'POST'])
        def collection_methods():
            if request.method == 'POST':
                data = self.get_data(request)
                if data is None:
                    return "Unsupported media type", 415
                return self.post(data)
            else:
                return self.get_all()

        @blueprint.route('/' + self.alias + '/<item_id>', methods=['GET', 'PUT', 'DELETE'])
        def resource_methods(item_id):
            entry = self.model.query.get_or_404(item_id)
            if request.method == 'GET':
                return self.get(entry)
            elif request.method == 'PUT':
                data = self.get_data(request)
                if data is None:
                    return "Unsupported media type", 415
                return self.put(data, entry)
            else:
                return self.delete(entry)

        return blueprint

    def post(self, data):
        params = {}
        for field in self.fields:
            params[field] = self.cast(field, data[field])
        new_item = self.model(**params)
        # TODO: add try/except
        self.db.session.add(new_item)
        self.db.session.commit()

        return jsonify(params), 201

    def get_all(self):
        all_items = self.model.query.all()
        results = []
        for item in all_items:
            entry = {}
            for field in self.fields:
                entry[field] = getattr(item, field)
            results.append(entry)

        return jsonify(results), 200

    def get(self, entry):
        result = {}
        for field in self.fields:
            result[field] = getattr(entry, field)

        return jsonify(result), 200

    def put(self, data, entry):
        result = {}
        for field in self.fields:
            value = self.cast(field, data[field])
            setattr(entry, field, value)
            result[field] = value
        self.db.session.commit()

        return jsonify(result), 201

    def delete(self, entry):
        self.db.session.delete(entry)
        self.db.session.commit()
        return '', 204

    def cast(self, field, value):
        if not self.fields_type:
            raise ValueError("Model not initialized")
        if value is None:
            raise ValueError(
                "Expected value but found None for field: %s" % field)
        return (self.fields_type[field])(value)

    def get_data(self, request):
        if "multipart/form-data" in request.content_type:
            return request.form.to_dict()
        if request.content_type == "application/json":
            return request.get_json()
        return

redpajama_set_name: RedPajamaGithub


text:
*Created by: André Tarnowsky*

### Commits
  - [`87d4fc17c7`] - readd move background (André Tarnowsky)


text:
package com.twitter.storehaus.cache

import com.twitter.util.Duration

/**
 * Companion object to Cache. Contains a number of methods for
 * generating various cache implementations.
 */
object Cache {
  /**
   * Generate a Cache from the supplied Map. (Caveat emptor: this
   * will never evict keys!)
   */
  def fromMap[K, V](m: Map[K, V]) = MapCache(m)

  /* Returns an LRUCache configured with the supplied maxSize. */
  def lru[K, V](maxSize: Long) = LRUCache(maxSize, Map.empty[K, (Long, V)])

  /* Returns an immutable TTLCache configured with the supplied ttl in
   * milliseconds. */
  @deprecated("Use com.twitter.storehaus.cache.Cache#ttl", "0.6.1")
  def ttl[K, V](ttlInMillis: Long) = TTLCache(Duration.fromMilliseconds(ttlInMillis), Map.empty[K, (Long, V)])

  def ttl[K, V](ttl: Duration) = TTLCache(ttl, Map.empty[K, (Long, V)])

  def toMutable[K, V](cache: Cache[K, V])(exhaustFn: Set[K] => Unit): MutableCache[K, V] =
    new MutableFromImmutableCache(cache)(exhaustFn)
}

/**
 * Immutable Cache trait for use with Storehaus stores.
 *
 * Inspired by clojure's core.cache:
 * https://github.com/clojure/core.cache/blob/master/src/main/clojure/clojure/core/cache.clj
 *
 * @author Oscar Boykin
 * @author Sam Ritchie
 */

trait Cache[K, V] {
  /**
   * Returns an option containing the value stored for the supplied
   * key or None if the key is not present in the cache. (A call to
   * get should not change the underlying cache in any way.)
   */
  def get(k: K): Option[V]

  /* Returns a pair of Option[K] (representing a key possibly evicted by
   * new key-value pair) and a new cache containing the supplied
   * key-value pair. */
  def put(kv: (K, V)): (Set[K], Cache[K, V])

  /* Returns a new cache with the supplied Promotes the supplied key
   * within the cache. */
  def hit(k: K): Cache[K, V]

  /* Returns an option of the evicted value and the new cache state. */
  def evict(k: K): (Option[V], Cache[K, V])

  /**
   * Returns an iterator of all key-value pairs inside of this
   * cache.
   */
  def iterator: Iterator[(K, V)]

  /** Returns an empty version of this specific cache implementation. */
  def empty: Cache[K, V]

  /**
   * Returns true if the cache contains a value for the supplied key,
   * false otherwise.
   */
  def contains(k: K): Boolean = get(k).isDefined

  /* Returns this cache's key-value pairs as an immutable Map. */
  def toMap: Map[K, V] = iterator.toMap

  /* Returns a new cache containing the supplied key-value pair (and
   * possibly evicting some other key). */
  def +(kv: (K, V)): Cache[K, V] = put(kv)._2

  /* Returns a new Cache with this key evicted. */
  def -(k: K): Cache[K, V] = evict(k)._2

  /* Returns a new Cache with this key evicted. */
  def --(ks: Set[K]): Cache[K, V] = ks.foldLeft(this)(_ - _)

  /* Returns a new cache seeded with the kv-pairs in the supplied
   * map. */
  def seed(m: Map[K, V]): Cache[K, V] = m.foldLeft(empty)(_ + _)

  /**
   * Touches the cache with the supplied key. If the key is present
   * in the cache, the cache calls "hit" on the key. If the key is
   * missing, the cache adds fn(k) to itself.
   */
  def touch(k: K, v: => V): Cache[K, V] =
    if (contains(k))
      hit(k)
    else
      this + (k -> v)

  def toMutable(exhaustFn: Set[K] => Unit = _ => ()): MutableCache[K, V] = Cache.toMutable(this)(exhaustFn)
}


text:
from flask import Flask, redirect, url_for
from flask import request
from flask import render_template
from blog.forms import BlogEntryForm
from blog.models import BlogEntry
from blog import utils
from settings import *
from flask_pagedown import PageDown
from flaskext.markdown import Markdown
from google.appengine.api import users

app = Flask(__name__, static_url_path='/static')
app.config['DEBUG'] = True
app.secret_key = "salmanwahed"
pagedown = PageDown(app)
Markdown(app)

# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

@app.route('/')
def index():
    """Return a friendly HTTP greeting."""
    blog_query = BlogEntry.query(ancestor=utils.get_parent_key())
    bolgs = blog_query.fetch(5)
    return render_template('index.html', blogs=bolgs)

@app.route('/salman/')
def admin():
    blog_query = BlogEntry.query(ancestor=utils.get_parent_key())
    blogs = blog_query.fetch()
    return render_template('admin.html', blogs=blogs)

@app.route('/about/')
def about():
    return render_template('about.html')

@app.route('/blog/')
def blog():
    return render_template('full-width.html')

@app.route('/contact/')
def contact():
    return render_template('contact.html')

@app.route('/post/<string:blog_id>/<string:slug>/')
@app.route('/post/<string:blog_id>/')
@app.route('/post/preview/<string:blog_id>')
def single_page(blog_id, slug=None):
    blog = BlogEntry.get_by_id(int(blog_id), parent=utils.get_parent_key())
    return render_template('single.html', blog=blog)

@app.route('/new_post/', methods=['GET', 'POST'])
def new_post():
    form = BlogEntryForm(request.form)
    if request.method == 'POST' and form.validate():
        blog_entry = BlogEntry(parent=utils.get_parent_key())
        blog_entry.title = form.title.data
        blog_entry.body = form.body.data
        tag_str = form.tags.data
        blog_entry.tags = map(lambda x: x.strip(), tag_str.split(','))
        blog_entry.save()
        return redirect(url_for('index'))

    return render_template('new_post.html', form=form)

@app.route('/post/update/<string:blog_id>', methods=['GET', 'POST'])
def update_post(blog_id):
    blog = BlogEntry.get_by_id(int(blog_id), parent=utils.get_parent_key())
    return render_template('single.html', blog=blog)

@app.route('/post/delete/<string:blog_id>', methods=['GET', 'DELETE'])
def delete_post(blog_id):
    blog = BlogEntry.get_by_id(int(blog_id), parent=utils.get_parent_key())
    return render_template('single.html', blog=blog)

@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, nothing at this URL.', 404


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;

namespace Miracle.Settings
{
    public partial class SettingsLoader
    {
        /// <summary>
        /// List of value providers that are searched until a value is found.
        /// </summary>
        public List<Func<string,string>> PathProviders { get; }

	    private string GetFullPath(string path)
	    {
		    foreach (var pathProvider in PathProviders)
		    {
			    var result = pathProvider(path);
			    if (!string.IsNullOrEmpty(result))
			    {
				    return result;
			    }
		    }

		    return path;
	    }

	    private List<Func<string, string>> GetDefaultPathConverters()
	    {
		    return new List<Func<string, string>>()
		    {
#if NETFULL
				System.Web.Hosting.HostingEnvironment.MapPath,
#endif
				Path.GetFullPath,
		    };
	    }

		/// <summary>
		/// Add value provider to list of value providers
		/// </summary>
		/// <param name="provider"></param>
		/// <returns></returns>
		public SettingsLoader AddPathProvider(Func<string, string> provider)
        {
            PathProviders.Add(provider);
            return this;
        }
	}
}


text:
Accessible via 'Pinter' menu.

#### Tasks
Build a Pinterest Clone
similar to [this](https://midnight-dust.hyperdev.space)

- User Story: As an unauthenticated user, I can login with Twitter.
- User Story: As an authenticated user, I can link to images.
- User Story: As an authenticated user, I can delete images that I've linked to.
- User Story: As an authenticated user, I can see a Pinterest-style wall of all the images I've linked to.
- User Story: As an unauthenticated user, I can browse other users' walls of images.
- User Story: As an authenticated user, if I upload an image that is broken, it will be replaced by a placeholder image. (can use jQuery broken image detection)
- Hint: Masonry.js is a library that allows for Pinterest-style image grids.


text:
echo -n $$ > /var/awslogs/state/awslogs.pid

source "/etc/profile.d/proxy.sh"
source "/opt/wgen/bin/user-data.sh"

CONFIG_FILE='/var/awslogs/etc/awslogs.conf'

sed -e "s/{env}/$environment_name/g" -e "s/{hostclass}/$hostclass/g" -i $CONFIG_FILE

AWS_CONFIG_FILE=/var/awslogs/etc/aws.conf HOME=/root /bin/nice -n 4 /var/awslogs/bin/aws logs push --config-file $CONFIG_FILE >> /var/log/awslogs.log 2>&1


text:
/**
 * \file extensions.h
 * Extension handling.
 *
 * \if subset
 * (No-op)
 *
 * \endif
 */

/*
 * Mesa 3-D graphics library
 * Version:  6.5.1
 *
 * Copyright (C) 1999-2006  Brian Paul   All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef _EXTENSIONS_H_
#define _EXTENSIONS_H_

#include "glheader.h"
#include "mfeatures.h"

struct gl_context;

#if _HAVE_FULL_GL

extern void _mesa_enable_sw_extensions(struct gl_context *ctx);

extern void _mesa_enable_1_3_extensions(struct gl_context *ctx);

extern void _mesa_enable_1_4_extensions(struct gl_context *ctx);

extern void _mesa_enable_1_5_extensions(struct gl_context *ctx);

extern void _mesa_enable_2_0_extensions(struct gl_context *ctx);

extern void _mesa_enable_2_1_extensions(struct gl_context *ctx);

extern void _mesa_enable_extension(struct gl_context *ctx, const char *name);

extern void _mesa_disable_extension(struct gl_context *ctx, const char *name);

extern GLboolean _mesa_extension_is_enabled(struct gl_context *ctx, const char *name);

extern void _mesa_init_extensions(struct gl_context *ctx);

extern GLubyte *_mesa_make_extension_string(struct gl_context *ctx);

extern GLuint
_mesa_get_extension_count(struct gl_context *ctx);

extern const GLubyte *
_mesa_get_enabled_extension(struct gl_context *ctx, GLuint index);

#else

/** No-op */
#define _mesa_extensions_dtr( ctx ) ((void)0)

/** No-op */
#define _mesa_extensions_ctr( ctx ) ((void)0)

/** No-op */
#define _mesa_extensions_get_string( ctx ) "GL_EXT_texture_object"

/** No-op */
#define _mesa_enable_extension( c, n ) ((void)0)

#endif

#endif


text:
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.application;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * Defines a scheduler that runs tasks that load data from Druid periodically or in one-off fashion.
 */
public class TaskScheduler extends ScheduledThreadPoolExecutor {
    private static final Logger LOG = LoggerFactory.getLogger(TaskScheduler.class);

    /**
     * Creates a new scheduler for loaders with the given thread pool size.
     *
     * @param poolSize  The number of threads available in the pool of this scheduler.
     */
    public TaskScheduler(int poolSize) {
        super(poolSize);
        super.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        super.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        LOG.info("Started task scheduler with thread pool size: {}", poolSize);
    }

    @Override
    protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) {
        return new SchedulableTask<>(runnable, null, task);
    }

    @Override
    protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) {
        return new SchedulableTask<>(callable, task);
    }

    @Override
    public void shutdown() {
        LOG.info("Shutting down task scheduler with thread pool size: {}", getCorePoolSize());
        super.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        LOG.info("Immediately shutting down task scheduler with thread pool size: {}", getCorePoolSize());
        return super.shutdownNow();
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.drools.iot;

import com.pi4j.component.motor.impl.GpioStepperMotorComponent;
import com.pi4j.component.temperature.impl.Tmp102;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import java.io.IOException;
import org.drools.retebuilder.CanonicalKieBase;
import org.kie.api.runtime.KieSession;

/**
 *
 * @author salaboy
 */
public class Main {
    public static void main(String[] args) throws IOException {
        CanonicalKieBase kieBase = new CanonicalKieBase();
//        kieBase.addRules(toModule(HardwareModule.class));

        KieSession ksession = kieBase.newKieSession();
        GpioPinDigitalOutput[] pins = null;

        ksession.insert(new GpioStepperMotorComponent(pins));

        ksession.insert(new Tmp102(0, 0));

        int fired = ksession.fireAllRules();

        System.out.println("Fired: "+ fired);

    }
}


text:
namespace media {

PipelineController::PipelineController(std::unique_ptr<Pipeline> pipeline,
                                       SeekedCB seeked_cb,
                                       SuspendedCB suspended_cb,
                                       BeforeResumeCB before_resume_cb,
                                       ResumedCB resumed_cb,
                                       PipelineStatusCB error_cb)
    : pipeline_(std::move(pipeline)),
      seeked_cb_(std::move(seeked_cb)),
      suspended_cb_(std::move(suspended_cb)),
      before_resume_cb_(std::move(before_resume_cb)),
      resumed_cb_(std::move(resumed_cb)),
      error_cb_(std::move(error_cb)) {
  DCHECK(pipeline_);
  DCHECK(seeked_cb_);
  DCHECK(suspended_cb_);
  DCHECK(before_resume_cb_);
  DCHECK(resumed_cb_);
  DCHECK(error_cb_);
}

PipelineController::~PipelineController() {
  DCHECK(thread_checker_.CalledOnValidThread());
}

void PipelineController::Start(Pipeline::StartType start_type,
                               Demuxer* demuxer,
                               Pipeline::Client* client,
                               bool is_streaming,
                               bool is_static) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK_EQ(state_, State::STOPPED);
  DCHECK(demuxer);

  // Once the pipeline is started, we want to call the seeked callback but
  // without a time update.
  pending_startup_ = true;
  pending_seeked_cb_ = true;
  state_ = State::STARTING;

  demuxer_ = demuxer;
  is_streaming_ = is_streaming;
  is_static_ = is_static;
  pipeline_->Start(start_type, demuxer, client,
                   base::BindOnce(&PipelineController::OnPipelineStatus,
                                  weak_factory_.GetWeakPtr(),
                                  start_type == Pipeline::StartType::kNormal
                                      ? State::PLAYING
                                      : State::PLAYING_OR_SUSPENDED));
}

void PipelineController::Seek(base::TimeDelta time, bool time_updated) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // It would be slightly more clear to set this in Dispatch(), but we want to
  // be sure it gets updated even if the seek is elided.
  if (time_updated)
    pending_time_updated_ = true;
  pending_seeked_cb_ = true;
  pending_seek_except_start_ = true;

  // If we are already seeking to |time|, and the media is static, elide the
  // seek.
  if ((state_ == State::SEEKING || state_ == State::RESUMING) &&
      seek_time_ == time && is_static_) {
    pending_seek_ = false;
    return;
  }

  pending_seek_time_ = time;
  pending_seek_ = true;
  Dispatch();
}

// TODO(sandersd): It may be easier to use this interface if |suspended_cb_| is
// executed when Suspend() is called while already suspended.
void PipelineController::Suspend() {
  DCHECK(thread_checker_.CalledOnValidThread());
  pending_resume_ = false;
  if (state_ != State::SUSPENDING && state_ != State::SUSPENDED) {
    pending_suspend_ = true;
    Dispatch();
  }
}

void PipelineController::Resume() {
  DCHECK(thread_checker_.CalledOnValidThread());
  pending_suspend_ = false;
  // TODO(sandersd) fix resume during suspended start.
  if (state_ == State::SUSPENDING || state_ == State::SUSPENDED ||
      (state_ == State::SWITCHING_TRACKS &&
       previous_track_change_state_ == State::SUSPENDED)) {
    pending_resume_ = true;
    Dispatch();
    return;
  }
}

void PipelineController::OnDecoderStateLost() {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Note: |time_updated| and |pending_seeked_cb_| are both false.
  pending_seek_except_start_ = true;

  // If we are already seeking or resuming, or if there's already a seek
  // pending,elide the seek. This is okay for decoder state lost since it just
  // needs one seek to recover (the decoder is reset and the next decode starts
  // from a key frame).
  //
  // Note on potential race condition: When the seek is elided, it's possible
  // that the decoder state loss happens before or after the previous seek
  // (decoder Reset()):
  // 1. Decoder state loss happens before Decoder::Reset() during the previous
  // seek. In this case we are fine since we just need a Reset().
  // 2. Decoder state loss happens after Decoder::Reset() during a previous
  // seek:
  // 2.1 If state loss happens before any Decode() we are still fine, since the
  // decoder is in a clean state.
  // 2.2 If state loss happens after a Decode(), then here we should not be in
  // the SEEKING state.
  if (state_ == State::SEEKING || state_ == State::RESUMING || pending_seek_)
    return;

  // Force a seek to the current time.
  pending_seek_time_ = pipeline_->GetMediaTime();
  pending_seek_ = true;

  Dispatch();
}

bool PipelineController::IsStable() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return state_ == State::PLAYING;
}

bool PipelineController::IsPendingSeek() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return pending_seek_except_start_;
}

bool PipelineController::IsSuspended() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return (pending_suspend_ || state_ == State::SUSPENDING ||
          state_ == State::SUSPENDED) &&
         !pending_resume_;
}

bool PipelineController::IsPipelineSuspended() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return state_ == State::SUSPENDED;
}

void PipelineController::OnPipelineStatus(State expected_state,
                                          PipelineStatus pipeline_status) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (pipeline_status != PIPELINE_OK) {
    error_cb_.Run(pipeline_status);
    return;
  }

  State old_state = state_;
  state_ = expected_state;

  // Resolve ambiguity of the current state if we may have suspended in startup.
  if (state_ == State::PLAYING_OR_SUSPENDED) {
    waiting_for_seek_ = false;
    state_ = pipeline_->IsSuspended() ? State::SUSPENDED : State::PLAYING;

    // It's possible for a Suspend() call to come in during startup. If we've
    // completed a suspended startup, we should clear that now.
    if (state_ == State::SUSPENDED)
      pending_suspend_ = false;
  }

  if (state_ == State::PLAYING) {
    // Start(), Seek(), or Resume() completed; we can be sure that
    // |demuxer_| got the seek it was waiting for.
    waiting_for_seek_ = false;

    // TODO(avayvod): Remove resumed callback after https://crbug.com/678374 is
    // properly fixed.
    if (old_state == State::RESUMING) {
      DCHECK(!pipeline_->IsSuspended());
      DCHECK(!pending_resume_);

      resumed_cb_.Run();
    }
  }

  if (state_ == State::SUSPENDED) {
    DCHECK(pipeline_->IsSuspended());
    DCHECK(!pending_suspend_);

    // Warning: possibly reentrant. The state may change inside this callback.
    // It must be safe to call Dispatch() twice in a row here.
    suspended_cb_.Run();
  }

  Dispatch();
}

// Note: Dispatch() may be called re-entrantly (by callbacks internally) or
// twice in a row (by OnPipelineStatus()).
void PipelineController::Dispatch() {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Suspend/resume transitions take priority because seeks before a suspend
  // are wasted, and seeks after can be merged into the resume operation.
  if (pending_suspend_ && state_ == State::PLAYING) {
    pending_suspend_ = false;
    state_ = State::SUSPENDING;
    pipeline_->Suspend(base::BindOnce(&PipelineController::OnPipelineStatus,
                                      weak_factory_.GetWeakPtr(),
                                      State::SUSPENDED));
    return;
  }

  // In additional to the standard |pending_resume_| case, if we completed a
  // suspended startup, but a Seek() came in, we need to resume the pipeline to
  // complete the seek before calling |seeked_cb_|.
  if ((pending_resume_ || (pending_startup_ && pending_seek_)) &&
      state_ == State::SUSPENDED) {
    // If there is a pending seek, resume to that time instead...
    if (pending_seek_) {
      seek_time_ = pending_seek_time_;
      pending_seek_ = false;
    } else {
      seek_time_ = pipeline_->GetMediaTime();
    }

    // ...unless the media is streaming, in which case we resume at the start
    // because seeking doesn't work well.
    if (is_streaming_ && !seek_time_.is_zero()) {
      seek_time_ = base::TimeDelta();

      // In this case we want to make sure that the controls get updated
      // immediately, so we don't try to hide the seek.
      pending_time_updated_ = true;
    }

    // Tell |demuxer_| to expect our resume.
    DCHECK(!waiting_for_seek_);
    waiting_for_seek_ = true;
    demuxer_->StartWaitingForSeek(seek_time_);

    pending_resume_ = false;
    state_ = State::RESUMING;
    before_resume_cb_.Run();
    pipeline_->Resume(
        seek_time_, base::BindOnce(&PipelineController::OnPipelineStatus,
                                   weak_factory_.GetWeakPtr(), State::PLAYING));
    return;
  }

  // If we have pending operations, and a seek is ongoing, abort it.
  if ((pending_seek_ || pending_suspend_ || pending_audio_track_change_ ||
       pending_video_track_change_) &&
      waiting_for_seek_) {
    // If there is no pending seek, return the current seek to pending status.
    if (!pending_seek_) {
      pending_seek_time_ = seek_time_;
      pending_seek_ = true;
    }

    // CancelPendingSeek() may be reentrant, so update state first and return
    // immediately.
    waiting_for_seek_ = false;
    demuxer_->CancelPendingSeek(pending_seek_time_);
    return;
  }

  // We can only switch tracks if we are not in a transitioning state already.
  if ((pending_audio_track_change_ || pending_video_track_change_) &&
      (state_ == State::PLAYING || state_ == State::SUSPENDED)) {
    previous_track_change_state_ = state_;
    state_ = State::SWITCHING_TRACKS;

    // Attempt to do a track change _before_ attempting a seek operation,
    // otherwise the seek will apply to the old tracks instead of the new
    // one(s). Also attempt audio before video.
    if (pending_audio_track_change_) {
      pending_audio_track_change_ = false;
      pipeline_->OnEnabledAudioTracksChanged(
          pending_audio_track_change_ids_,
          base::BindOnce(&PipelineController::OnTrackChangeComplete,
                         weak_factory_.GetWeakPtr()));
      return;
    }

    if (pending_video_track_change_) {
      pending_video_track_change_ = false;
      pipeline_->OnSelectedVideoTrackChanged(
          pending_video_track_change_id_,
          base::BindOnce(&PipelineController::OnTrackChangeComplete,
                         weak_factory_.GetWeakPtr()));
      return;
    }
  }

  // Ordinary seeking.
  if (pending_seek_ && state_ == State::PLAYING) {
    seek_time_ = pending_seek_time_;

    // Tell |demuxer_| to expect our seek.
    DCHECK(!waiting_for_seek_);
    waiting_for_seek_ = true;
    demuxer_->StartWaitingForSeek(seek_time_);

    pending_seek_ = false;
    state_ = State::SEEKING;
    pipeline_->Seek(seek_time_,
                    base::BindOnce(&PipelineController::OnPipelineStatus,
                                   weak_factory_.GetWeakPtr(), State::PLAYING));
    return;
  }

  // If |state_| is PLAYING and we didn't trigger an operation above then we
  // are in a stable state. If there is a seeked callback pending, emit it.
  //
  // We also need to emit it if we completed suspended startup.
  if (pending_seeked_cb_ &&
      (state_ == State::PLAYING ||
       (state_ == State::SUSPENDED && pending_startup_))) {
    // |seeked_cb_| may be reentrant, so update state first and return
    // immediately.
    pending_startup_ = false;
    pending_seeked_cb_ = false;
    pending_seek_except_start_ = false;
    bool was_pending_time_updated = pending_time_updated_;
    pending_time_updated_ = false;
    seeked_cb_.Run(was_pending_time_updated);
    return;
  }
}

void PipelineController::Stop() {
  if (state_ == State::STOPPED)
    return;

  demuxer_ = nullptr;
  waiting_for_seek_ = false;
  pending_seeked_cb_ = false;
  pending_seek_except_start_ = false;
  pending_time_updated_ = false;
  pending_seek_ = false;
  pending_suspend_ = false;
  pending_resume_ = false;
  pending_audio_track_change_ = false;
  pending_video_track_change_ = false;
  state_ = State::STOPPED;

  pipeline_->Stop();
}

bool PipelineController::IsPipelineRunning() const {
  return pipeline_->IsRunning();
}

double PipelineController::GetPlaybackRate() const {
  return pipeline_->GetPlaybackRate();
}

void PipelineController::SetPlaybackRate(double playback_rate) {
  pipeline_->SetPlaybackRate(playback_rate);
}

float PipelineController::GetVolume() const {
  return pipeline_->GetVolume();
}

void PipelineController::SetVolume(float volume) {
  pipeline_->SetVolume(volume);
}

void PipelineController::SetLatencyHint(
    absl::optional<base::TimeDelta> latency_hint) {
  DCHECK(!latency_hint || (*latency_hint >= base::TimeDelta()));
  pipeline_->SetLatencyHint(latency_hint);
}

void PipelineController::SetPreservesPitch(bool preserves_pitch) {
  pipeline_->SetPreservesPitch(preserves_pitch);
}

void PipelineController::SetWasPlayedWithUserActivation(
    bool was_played_with_user_activation) {
  pipeline_->SetWasPlayedWithUserActivation(was_played_with_user_activation);
}

base::TimeDelta PipelineController::GetMediaTime() const {
  return pipeline_->GetMediaTime();
}

Ranges<base::TimeDelta> PipelineController::GetBufferedTimeRanges() const {
  return pipeline_->GetBufferedTimeRanges();
}

base::TimeDelta PipelineController::GetMediaDuration() const {
  return pipeline_->GetMediaDuration();
}

bool PipelineController::DidLoadingProgress() {
  return pipeline_->DidLoadingProgress();
}

PipelineStatistics PipelineController::GetStatistics() const {
  return pipeline_->GetStatistics();
}

void PipelineController::SetCdm(CdmContext* cdm_context,
                                CdmAttachedCB cdm_attached_cb) {
  pipeline_->SetCdm(cdm_context, std::move(cdm_attached_cb));
}

void PipelineController::OnEnabledAudioTracksChanged(
    const std::vector<MediaTrack::Id>& enabled_track_ids) {
  DCHECK(thread_checker_.CalledOnValidThread());

  pending_audio_track_change_ = true;
  pending_audio_track_change_ids_ = enabled_track_ids;

  Dispatch();
}

void PipelineController::OnSelectedVideoTrackChanged(
    absl::optional<MediaTrack::Id> selected_track_id) {
  DCHECK(thread_checker_.CalledOnValidThread());

  pending_video_track_change_ = true;
  pending_video_track_change_id_ = selected_track_id;

  Dispatch();
}

void PipelineController::FireOnTrackChangeCompleteForTesting(State set_to) {
  previous_track_change_state_ = set_to;
  OnTrackChangeComplete();
}

void PipelineController::OnTrackChangeComplete() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (state_ == State::SWITCHING_TRACKS)
    state_ = previous_track_change_state_;

  // Other track changed or seek/suspend/resume, etc may be waiting.
  Dispatch();
}

}  // namespace media


text:
"""
sample code that deploys a VM.
"""

import os
import sys
import time

from zvmconnector import connector

client = connector.ZVMConnector(connection_type = 'rest', port = 8080)

def delete_guest(userid):
    """ Destroy a virtual machine.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    """
    # Check if the guest exists.
    guest_list_info = client.send_request('guest_list')
    # the string 'userid' need to be coded as 'u'userid' in case of py2 interpreter.
    userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)

    if userid_1 not in guest_list_info['output']:
        RuntimeError("Userid %s does not exist!" % userid)

    # Delete the guest.
    guest_delete_info = client.send_request('guest_delete', userid)

    if guest_delete_info['overallRC']:
        print("\nFailed to delete guest %s!" % userid)
    else:
        print("\nSucceeded to delete guest %s!" % userid)

def describe_guest(userid):
    """ Get the basic information of virtual machine.

    Input parameters:
    :userid:    USERID of the guest, last 8 if length > 8
    """
    # Check if the guest exists.
    guest_list_info = client.send_request('guest_list')
    userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)

    if userid_1 not in guest_list_info['output']:
        raise RuntimeError("Guest %s does not exist!" % userid)

    guest_describe_info = client.send_request('guest_get_definition_info', userid)
    print("\nThe created guest %s's info are: \n%s\n" % (userid, guest_describe_info))

def import_image(image_path, os_version):
    """ Import the specific image.

    Input parameters:
    :image_path:    Image file name
    :os_version:    Operation System version. e.g. rhel7.4
    """
    image_name = os.path.basename(image_path)
    print("\nChecking if image %s exists ..." % image_name)

    image_query_info = client.send_request('image_query', imagename = image_name)
    if image_query_info['overallRC']:
        print("Importing image %s ..." % image_name)
        url = "file://" + image_path
        image_import_info = client.send_request('image_import', image_name, url,
                                                {'os_version': os_version})
        if image_import_info['overallRC']:
            raise RuntimeError("Failed to import image %s!\n%s" %
                               (image_name, image_import_info))
        else:
            print("Succeeded to import image %s!" % image_name)
    else:
        print("Image %s already exists!" % image_name)

def create_guest(userid, cpu, memory, disks_list, profile):
    """ Create the userid.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    :cpu:               the number of vcpus
    :memory:            memory
    :disks_list:        list of disks to add
    :profile:           profile of the userid
    """
    # Check if the userid already exists.
    guest_list_info = client.send_request('guest_list')
    userid_1 = (unicode(userid, "utf-8") if sys.version[0] == '2' else userid)

    if userid_1 in guest_list_info['output']:
        raise RuntimeError("Guest %s already exists!" % userid)

    # Create the guest.
    print("\nCreating guest: %s ..." % userid)
    guest_create_info = client.send_request('guest_create', userid, cpu, memory,
                                            disk_list = disks_list,
                                            user_profile = profile)

    if guest_create_info['overallRC']:
        raise RuntimeError("Failed to create guest %s!\n%s" %
                           (userid, guest_create_info))
    else:
        print("Succeeded to create guest %s!" % userid)

def deploy_guest(userid, image_name):
    """ Deploy image to root disk.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    :image_path:        Image file name
    """
    print("\nDeploying %s to %s ..." % (image_name, userid))
    guest_deploy_info = client.send_request('guest_deploy', userid, image_name)

    # if failed to deploy, then delete the guest.
    if guest_deploy_info['overallRC']:
        print("\nFailed to deploy guest %s!\n%s" % (userid, guest_deploy_info))
        print("\nDeleting the guest %s that failed to deploy..." % userid)

        # call terminage_guest() to delete the guest that failed to deploy.
        delete_guest(userid)
        os._exit(0)
    else:
        print("Succeeded to deploy %s!" % userid)

def create_network(userid, os_version, network_info):
    """ Create network device and configure network interface.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    :os_version:        os version of the image file
    :network_info:      dict of network info
    """
    print("\nConfiguring network interface for %s ..." % userid)
    network_create_info = client.send_request('guest_create_network_interface',
                                              userid, os_version, network_info)

    if network_create_info['overallRC']:
        raise RuntimeError("Failed to create network for guest %s!\n%s" %
                           (userid, network_create_info))
    else:
        print("Succeeded to create network for guest %s!" % userid)

def coupleTo_vswitch(userid, vswitch_name):
    """ Couple to vswitch.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    :network_info:      dict of network info
    """
    print("\nCoupleing to vswitch for %s ..." % userid)
    vswitch_info = client.send_request('guest_nic_couple_to_vswitch',
                                       userid, '1000', vswitch_name)

    if vswitch_info['overallRC']:
        raise RuntimeError("Failed to couple to vswitch for guest %s!\n%s" %
                           (userid, vswitch_info))
    else:
        print("Succeeded to couple to vswitch for guest %s!" % userid)

def grant_user(userid, vswitch_name):
    """ Grant user.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    :network_info:      dict of network info
    """
    print("\nGranting user %s ..." % userid)
    user_grant_info = client.send_request('vswitch_grant_user', vswitch_name, userid)

    if user_grant_info['overallRC']:
        raise RuntimeError("Failed to grant user %s!" %userid)
    else:
        print("Succeeded to grant user %s!" % userid)

def start_guest(userid):
    """ Power on the vm.

    Input parameters:
    :userid:            USERID of the guest, last 8 if length > 8
    """
    # Check the power state before starting guest.
    power_state_info = client.send_request('guest_get_power_state', userid)
    print("\nPower state is: %s." % power_state_info['output'])

    # start guest.
    guest_start_info = client.send_request('guest_start', userid)

    if guest_start_info['overallRC']:
        raise RuntimeError('Failed to start guest %s!\n%s' %
                           (userid, guest_start_info))
    else:
        print("Succeeded to start guest %s!" % userid)

    # Check the power state after starting guest.
    power_state_info = client.send_request('guest_get_power_state', userid)
    print("Power state is: %s." % power_state_info['output'])

    if guest_start_info['overallRC']:
        print("Guest_start error: %s" % guest_start_info)

def _run_guest(userid, image_path, os_version, profile,
               cpu, memory, network_info, vswitch_name, disks_list):
    """ Deploy and provide a virtual machine.

    Input parameters:
    :userid:                USERID of the guest, no more than 8
    :image_path:            image file path
    :os_version:            os version of the image file
    :profile:               profile of the userid
    :cpu:                   the number of vcpus
    :memory:                memory
    :network_info:          dict of network info. Members are:
        :ip_addr:               ip address of vm
        :gateway:               gateway of network
        :cidr:                  CIDR
    :vswitch_name:          vswitch name
    :disks_list:            list of disks to add. For example:
        disks_list = [{'size': '3g',
        'is_boot_disk': True,
        'disk_pool': 'ECDK: xcateckd'}]
    """
    print("Start deploying a virtual machine:")

    # Import image if not exists.
    import_image(image_path, os_version)

    # Start time.
    spawn_start = time.time()

    # Create guest.
    create_guest(userid, cpu, memory, disks_list, profile)

    # Deploy image to root disk.
    image_name = os.path.basename(image_path)
    deploy_guest(userid, image_name)

    # Create network device and configure network interface.
    create_network(userid, os_version, network_info)

    # Couple to vswitch.
    coupleTo_vswitch(userid, vswitch_name)

    # Grant user.
    grant_user(userid, vswitch_name)

    # Power on the vm.
    start_guest(userid)

    # End the time.
    spawn_time = time.time() - spawn_start
    print("Instance-%s spawned succeeded in %s seconds!" %
          (userid, spawn_time))

    # Describe guest.
    describe_guest(userid)

def _user_input_properties():
    """ User input the properties of guest, image, and network. """
    global GUEST_USERID
    global GUEST_PROFILE
    global GUEST_VCPUS
    global GUEST_MEMORY
    global GUEST_ROOT_DISK_SIZE
    global DISK_POOL
    global IMAGE_PATH
    global IMAGE_OS_VERSION
    global GUEST_IP_ADDR
    global GATEWAY
    global CIDR
    global VSWITCH_NAME
    global NETWORK_INFO
    global DISKS_LIST

    pythonVersion = sys.version[0]
    print("Your python interpreter's version is %s." % pythonVersion)

    if pythonVersion == '2':
        print("Input properties with string type in ''.")
    else:
        print("Input properties without ''.")

    print("Please input guest properties:")

    GUEST_USERID = input("guest_userid = ")
    GUEST_PROFILE = input("guest_profile = ")
    GUEST_VCPUS = int(input("guest_vcpus = "))
    GUEST_MEMORY = int(input("guest_memory (in Megabytes) = "))
    GUEST_ROOT_DISK_SIZE = int(input("guest_root_disk_size (in Gigabytes) = "))
    GUEST_POOL = input("disk_pool = ")
    print("\n")

    IMAGE_PATH = input("image_path = ")
    IMAGE_OS_VERSION = input("image_os_version = ")
    print("\n")

    GUEST_IP_ADDR = input("guest_ip_addr = ")
    GATEWAY = input("gateway = ")
    CIDR = input("cidr = ")
    VSWITCH_NAME = input("vswitch_name = ")

    NETWORK_INFO = [{'ip_addr': GUEST_IP_ADDR, 'gateway_addr': GATEWAY, 'cidr': CIDR}]
    DISKS_LIST = [{'size': '%dg' % GUEST_ROOT_DISK_SIZE,
                   'is_boot_disk': True, 'disk_pool': GUEST_POOL}]

def run_guest():
    """
    A sample for quickly deploy and start a virtual guest.
    """

    # user input the properties of guest, image and network.
    _user_input_properties()

    # run a guest.
    _run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
               GUEST_VCPUS, GUEST_MEMORY, NETWORK_INFO, VSWITCH_NAME, DISKS_LIST)


text:
package logger

import "go.uber.org/zap"

func Load() *zap.Logger {
	logger, _ := zap.NewProduction()
	defer logger.Sync()
	return logger
}


text:
<?php

require_once './bdd/ArrMock.php';

// --------- Mocking Methods ----------
echo "
Mocking Methods
";
$mongoMock = ArrMock::create('Mongo');
$mongoMock->method('getHost')
          ->returns('127.0.0.1');

$mongoMock->method('getHost')
          ->args('slaves')
          ->returns(array('192.168.1.2', '192.168.1.5'));

$mongoMock->staticMethod('getPath')
          ->returns('/var/db/');

$mongoMock->method('findOne')
          ->args(array('username'=>'leng'), array('username', 'email'))
          ->returns(array('_id'=>md5('leng'), 'username'=>'leng', 'email'=>'leng@asd.com'));

$mongoMock->method('findOne')
          ->args(array('username'=>'kyle'), array('username', 'email'))
          ->returns(array('_id'=>md5('kyle'), 'username'=>'kyle', 'email'=>'kyle@asd.com'));

//Test mock method
var_dump( $mongoMock->getHost() );

//Test mock method with arguments
var_dump( $mongoMock->getHost('slaves') );

//Test mock static method
var_dump( $mongoMock::getPath() );

//Test mock method with arguments
$rs = $mongoMock->findOne(array('username'=>'leng'), array('username', 'email') );
var_dump($rs);

//Test mock method with arguments
$rs = $mongoMock->findOne( array('username'=>'kyle'), array('username', 'email') );
var_dump($rs);

//Test __toString() mock
$mongoMock->toString('Mongo object __toString() test');
echo "
$mongoMock
";

// Another Mock
$anotherNewMock = ArrMock::create('Another');

$anotherNewMock->staticMethod('foo')
               ->returns('bar');

$anotherNewMock->staticMethod('foo2')
               ->returns('bar2');

$anotherNewMock->staticMethod('getPath')
               ->returns('/var/logs');

//make non existing calls
#var_dump( $mongoMock::getPaths() );
#var_dump( $anotherNewMock::getPaths() );
#var_dump( $anotherNewMock->getPathxx() );

// ------------ Mocking non-static and static attributes --------------
echo "
Mocking non-static and static attributes
";

$mock = ArrMock::create('Example', array('staticVar1', 'staticVar2'));
$mock->abc = '999';
$mock::$staticVar1 = 100;
$mock::$staticVar2 = 200;

var_dump( $mock->abc );
var_dump( $mock::$staticVar1 );
var_dump( $mock::$staticVar2 );

// ------------ Using handler function for mocking methods --------------
echo "
Using handler function for mocking methods
";

$calcHandler = function($args){
    list($a, $b) = $args;
    return ($a + $b);
};

$mock->method('amount')->args(1, 5)->returns(6);
$mock->method('amount')->args(6, 7)->returns(13);
$mock->method('amount')->handle($calcHandler);

var_dump( $mock->amount(1, 5) );         // 6
var_dump( $mock->amount(6, 7) );         // 13
var_dump( $mock->amount(100, 200) );     // 300 handler
var_dump( $mock->amount(100, 500) );     // 600 handler
var_dump( $mock->amount(6, 7) );         // 13

//static
$mock->staticMethod('amount2')->args(1, 3)->returns(4);
$mock->staticMethod('amount2')->args(2, 4)->returns(6);
$mock->staticMethod('amount2')->handle($calcHandler);

var_dump( $mock::amount2(1, 3) );         // 4
var_dump( $mock::amount2(2, 4) );         // 6

// ------------ Counting method calls --------------
echo "
Counting method calls
";

// Total calls for $mock->amount() method
var_dump( $mock->totalCalls('amount') );
var_dump( $mock->totalCalls('amount', 6, 7) );      // total calls with this arguments 6 and 7
var_dump( $mock->totalCalls('amount', 1, 5) );      // total calls with this arguments 1 and 5
var_dump( $mock->totalCalls('amount', 1, 2, 3) );   // This has not been called

// Total calls for $mock::amount2()
var_dump( $mock->totalCalls('amount2') );
var_dump( $mock->totalCalls('amount2', 1, 3) );
var_dump( $mock->totalCalls('amount2', 2, 4) );

// ------------ Return values http://code.google.com/p/arr-bdd/issues/detail?id=2--------------
echo "
Return values sequence
";

$mock->method('amount')->returns(1)
                       ->returns(10, 3)         // return value 10 on 3rd call onwards
                       ->returns(100, 5)        // return value 10 on 5th call onwards
                       ->returns(999);

$mock->method('amount')->args('foo')
                       ->returns('bar')
                       ->returns('bar 2');

var_dump( $mock->amount() );        // 1
var_dump( $mock->amount() );        // 1
var_dump( $mock->amount() );        // 10
var_dump( $mock->amount() );        // 10
var_dump( $mock->amount() );        // 100
var_dump( $mock->amount() );        // 999
var_dump( $mock->amount('foo') );   // bar
var_dump( $mock->amount() );        // 999
var_dump( $mock->amount() );        // 999
var_dump( $mock->amount('foo') );   // bar 2
var_dump( $mock->amount('foo') );   // bar 2

// Static
$mock->staticMethod('test')->returns(10)
                           ->returns(100, 3)
                           ->returns('Done!');

$mock->staticMethod('test')->args(9)->returns(999);

echo "\nStatics\n";
var_dump( $mock::test() );    // 10
var_dump( $mock::test() );    // 10
var_dump( $mock::test() );    // 100
var_dump( $mock::test() );    // 100
var_dump( $mock::test() );    // Done!
var_dump( $mock::test() );    // Done!
var_dump( $mock::test(9) );   // 999


text:
dx --dex --no-strict --output=bin/classes.dex bin/org/cf/demosmali
baksmali --sequential-labels --code-offsets --use-locals bin/classes.dex -o resources/


text:
require 'example_test_helper'

class CoffeeScriptTest < ExampleTestCase

  def test_coffee_script
    assert_render_equals <<-INPUT, <<-OUTPUT
      @coffee-script
      alert "Hello world!"
    INPUT

        alert "Hello world!"

    OUTPUT
  end

end


text:
'use strict';

const five = require('johnny-five');
const PiIO = require('..');

const board = new five.Board({
  io: new PiIO()
});

board.on('ready', function() {
  const led = new five.Led('GPIO17');

  led.blink(500);
});


text:
import wyautl.core.Automaton;

public class Parser {
	private String input;
	private int index;

	public Parser(String input) {
		this.input = input;
		this.index = 0;
	}

	public int parse(Automaton automaton) {
		skipWhiteSpace();
		char lookahead = input.charAt(index);

		int lhs;

		if(lookahead == '(') {
			lhs = parseBracketed(automaton);
		} else if(lookahead == '!') {
			match("!");
			return Logic.Not(automaton, parse(automaton));
		} else {
			String word = readWord();
			if(word.equals("true")) {
				lhs = automaton.add(Logic.True);
			} else if(word.equals("false")) {
				lhs = automaton.add(Logic.False);
			} else {
				lhs = Logic.Var(automaton, word);
			}
		}

		skipWhiteSpace();

		if(index < input.length()) {
			lookahead = input.charAt(index);

			if(lookahead == '&') {
				match("&&");
				int rhs = parse(automaton);
				lhs = Logic.And(automaton, lhs, rhs);
			} else if(lookahead == '|') {
				match("||");
				int rhs = parse(automaton);
				lhs = Logic.Or(automaton, lhs, rhs);
			}
		}

		return lhs;
	}

	private int parseBracketed(Automaton automaton) {
		match("(");
		int root = parse(automaton);
		match(")");
		return root;
	}

	private String readWord() {
		int start = index;
		while (index < input.length()
				&& Character.isLetter(input.charAt(index))) {
			index++;
		}
		return input.substring(start, index);
	}

	private int readNumber() {
		int start = index;
		while (index < input.length() && Character.isDigit(input.charAt(index))) {
			index = index + 1;
		}
		return Integer.parseInt(input.substring(start, index));
	}

	private void match(String text) {
		skipWhiteSpace();
		if(input.startsWith(text,index)) {
			index += text.length();
		} else {
			error();
		}
	}

	private void skipWhiteSpace() {
		while (index < input.length()
				&& (input.charAt(index) == ' ' || input.charAt(index) == '\n')) {
			index = index + 1;
		}
	}

	private void error() {
		final String msg = "Cannot parse character '"
			+ input.charAt(index)
		    + "' at position " + index + " of input '" + input + "'\n";
		throw new RuntimeException(msg);
	}
}