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.workshop.pitfalls;

import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.drools.workshop.model.House;
import org.drools.workshop.model.Person;
import org.drools.workshop.model.Person.Gender;
import org.drools.workshop.model.Room;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.api.KieBase;
import org.kie.api.cdi.KBase;
import org.kie.api.runtime.KieSession;

/**
 *
 * @author salaboy
 */
@RunWith(Arquillian.class)
public class CrossProductRulesJUnitTest {

    public CrossProductRulesJUnitTest() {
    }

    @Deployment
    public static JavaArchive createDeployment() {

        JavaArchive jar = ShrinkWrap.create(JavaArchive.class)
                .addPackages(true, "org.drools.workshop.model")
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
        //System.out.println(jar.toString(true));
        return jar;
    }

    @Inject
    @KBase("crossProductKBase")
    private KieBase kBaseCrossProduct;

    @Inject
    @KBase("crossProductSolutionKBase")
    private KieBase kBaseCrossProductSolution;

    @Test
    public void testHouseWith3Rooms() {
        Assert.assertNotNull(kBaseCrossProduct);
        KieSession kSession = kBaseCrossProduct.newKieSession();
        System.out.println(" ---- Starting testHouseWith3Rooms() Test ---");

        Room livingRoom = new Room("living room", 10);
        kSession.insert(livingRoom);

        Room kitchenRoom = new Room("kitchen", 5);
        kSession.insert(kitchenRoom);

        Room bedRoom = new Room("bedroom", 4);
        kSession.insert(bedRoom);

        House house = new House();
        List<Room> rooms = new ArrayList<Room>();
        rooms.add(livingRoom);
        rooms.add(bedRoom);
        rooms.add(kitchenRoom);
        house.setRooms(rooms);

        kSession.insert(house);

        Assert.assertEquals(3, kSession.fireAllRules());
        System.out.println(" ---- Finished testHouseWith3Rooms() Test ---");
        kSession.dispose();
    }

    @Test
    public void test2HousesWith3Rooms() {
        Assert.assertNotNull(kBaseCrossProduct);
        KieSession kSession = kBaseCrossProduct.newKieSession();
        System.out.println(" ---- Starting test2HousesWith3Rooms() Test ---");

        Room livingRoomA = new Room("living room", 10);
        kSession.insert(livingRoomA);

        Room kitchenRoomA = new Room("kitchen", 5);
        kSession.insert(kitchenRoomA);

        Room bedRoomA = new Room("bedroom", 4);
        kSession.insert(bedRoomA);

        House houseA = new House();
        List<Room> rooms = new ArrayList<Room>();
        rooms.add(livingRoomA);
        rooms.add(bedRoomA);
        rooms.add(kitchenRoomA);
        houseA.setRooms(rooms);

        kSession.insert(houseA);

        Room livingRoomB = new Room("living room", 10);
        kSession.insert(livingRoomB);

        Room kitchenRoomB = new Room("kitchen", 5);
        kSession.insert(kitchenRoomB);

        Room bedRoomB = new Room("bedroom", 4);
        kSession.insert(bedRoomB);

        House houseB = new House();
        List<Room> roomsB = new ArrayList<Room>();
        roomsB.add(livingRoomB);
        roomsB.add(bedRoomB);
        roomsB.add(kitchenRoomB);
        houseB.setRooms(roomsB);

        kSession.insert(houseB);

        Assert.assertEquals(12, kSession.fireAllRules());
        System.out.println(" ---- Finished test2HousesWith3Rooms() Test ---");
        kSession.dispose();
    }

    @Test
    public void test2HousesWith3RoomsChecked() {
        Assert.assertNotNull(kBaseCrossProductSolution);
        KieSession kSession = kBaseCrossProductSolution.newKieSession();
        System.out.println(" ---- Starting test2HousesWith3RoomsChecked() Test ---");

        Room livingRoomA = new Room("living room", 10);
        kSession.insert(livingRoomA);

        Room kitchenRoomA = new Room("kitchen", 5);
        kSession.insert(kitchenRoomA);

        Room bedRoomA = new Room("bedroom", 4);
        kSession.insert(bedRoomA);

        House houseA = new House();
        List<Room> rooms = new ArrayList<Room>();
        rooms.add(livingRoomA);
        rooms.add(bedRoomA);
        rooms.add(kitchenRoomA);
        houseA.setRooms(rooms);

        kSession.insert(houseA);

        Room livingRoomB = new Room("living room", 10);
        kSession.insert(livingRoomB);

        Room kitchenRoomB = new Room("kitchen", 5);
        kSession.insert(kitchenRoomB);

        Room bedRoomB = new Room("bedroom", 4);
        kSession.insert(bedRoomB);

        House houseB = new House();
        List<Room> roomsB = new ArrayList<Room>();
        roomsB.add(livingRoomB);
        roomsB.add(bedRoomB);
        roomsB.add(kitchenRoomB);
        houseB.setRooms(roomsB);

        kSession.insert(houseB);

        Assert.assertEquals(6, kSession.fireAllRules());
        System.out.println(" ---- Finished test2HousesWith3RoomsChecked() Test ---");
        kSession.dispose();
    }

}


text:
module PulseMeter
  module DygraphsVisualize
    module DSL
      class Widget < Base
        MAX_WIDTH = 12

        self.data_class = PulseMeter::DygraphsVisualize::Widget

        def initialize(title)
          super()
          self.title(title)
          self.width(MAX_WIDTH)
        end

        hash_extender :dygraphs_options

        string_setter :title

        int_setter :redraw_interval do |int|
          raise BadWidgetRedrawInterval, int unless int > 0
        end

        int_setter :width do |w|
          raise BadWidgetWidth, w unless w > 0 && w <= MAX_WIDTH
        end

        dsl_array_extender :sensors, :sensor, PulseMeter::DygraphsVisualize::DSL::Sensor

        def method_missing(name, value)
          dygraphs_options(name => value)
        end

      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using Google.GData.Client;
using NUnit.Framework;
using Google.GData.Client.UnitTests;

namespace Google.GData.Client.UnitTests.Core
{

    ///
    ///This is a test class for InvalidCredentialsExceptionTest and is intended
    ///to contain all InvalidCredentialsExceptionTest Unit Tests
    ///
    [TestFixture][Category("CoreClient")]
    public class InvalidCredentialsExceptionTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for InvalidCredentialsException Constructor
        ///
        [Test]
        public void InvalidCredentialsExceptionConstructorTest1()
        {
            InvalidCredentialsException target = new InvalidCredentialsException();
            Assert.IsNotNull(target);
        }

        ///
        ///A test for InvalidCredentialsException Constructor
        ///
        [Test]
        public void InvalidCredentialsExceptionConstructorTest()
        {
            string msg = "TestValue"; // TODO: Initialize to an appropriate value
            InvalidCredentialsException target = new InvalidCredentialsException(msg);
            Assert.IsNotNull(target);
            Assert.AreEqual(msg, target.Message);
        }
    }
}


text:
#include "vice.h"

#include <stdio.h>

#include "romset.h"

const char *machine_romset_resources_list[] = {
    "KernalName",
    "BasicName",
    "FunctionLowName",
    "FunctionHighName",
    "DosName1541",
    "DosName1541ii",
    "DosName1570",
    "DosName1571",
    "DosName1581",
    "DosName2000",
    "DosName4000",
    "DosName1551",
    NULL
};

int machine_romset_file_load(const char *filename)
{
    return romset_file_load(filename);
}

int machine_romset_file_save(const char *filename)
{
    return romset_file_save(filename, machine_romset_resources_list);
}

char *machine_romset_file_list(void)
{
    return romset_file_list(machine_romset_resources_list);
}

int machine_romset_archive_item_create(const char *romset_name)
{
    return romset_archive_item_create(romset_name,
        machine_romset_resources_list);
}

void machine_romset_init(void)
{
}


text:
namespace ts = type_safe;

// we want some kind of handle to an int
struct handle : ts::strong_typedef<handle, int*>,                    // required
                ts::strong_typedef_op::equality_comparision<handle>, // for operator==/operator!=
                ts::strong_typedef_op::dereference<handle, int>      // for operator*/operator->
{
    using strong_typedef::strong_typedef;

    // we also want the operator bool()
    explicit operator bool() const noexcept
    {
        return static_cast<int*>(*this) != nullptr;
    }
};

void use_handle(handle h)
{
    // we can dereference it
    std::cout << *h << '\n';

    // and compare it
    h == handle(nullptr);

    // and reassign
    int a;
    h = handle(&a);
    // or get back
    int* ptr = static_cast<int*>(h);
}

// integer representing a distance
struct distance
    : ts::strong_typedef<distance, unsigned>,                  // required
      ts::strong_typedef_op::equality_comparision<distance>,   // for operator==/operator!=
      ts::strong_typedef_op::relational_comparision<distance>, // for operator< etc.
      ts::strong_typedef_op::
          integer_arithmetic<distance> // all arithmetic operators that make sense for integers
{
    using strong_typedef::strong_typedef;
};

// we want to output it
std::ostream& operator<<(std::ostream& out, const distance& d)
{
    return out << static_cast<unsigned>(d) << " distance";
}

int main()
{
    distance d(4);
    //    int      val = d; // error
    //    d += 3;           // error
    d += distance(3); // works

    std::cout << d << '\n';
}


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_Rendering_ReflectionProbeTimeSlicingMode : LuaObject {
	static public void reg(IntPtr l) {
		getEnumTable(l,"UnityEngine.Rendering.ReflectionProbeTimeSlicingMode");
		addMember(l,0,"AllFacesAtOnce");
		addMember(l,1,"IndividualFaces");
		addMember(l,2,"NoTimeSlicing");
		LuaDLL.lua_pop(l, 1);
	}
}


text:
@interface XBPaypalItem ()
{
    NSMutableDictionary *params;
}

@end

@implementation XBPaypalItem
@synthesize name;
@synthesize desc;
@synthesize quantity;
@synthesize currency;
@synthesize taxRate = _taxRate;
@synthesize amount = _amount;
@synthesize taxAmount;
@synthesize seller;
@synthesize paymentAction;
@synthesize shippingfee;
@synthesize allowNote;
@synthesize noShipping;

@synthesize shipToCity;
@synthesize shipToName;
@synthesize shipToState;
@synthesize shipToStreet;
@synthesize shipToStreet2;
@synthesize shipToCountryCode;
@synthesize shipToCountryName;
@synthesize shipToPhoneNumber;
@synthesize shipToAddressStatus;
@synthesize shipToAddressNormalizationStatus;
@synthesize shipToZip;
@synthesize addressOverride;

- (NSDictionary *)paramsForIndex:(int)index
{
    params = [@{} mutableCopy];

    [params setValue:name forKey:[NSString stringWithFormat:@"L_PAYMENTREQUEST_%d_NAME%d", index,index]];
    [self setNotNullValue:desc forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_DESC", index]];

    [params setValue:@(_amount + shippingfee) forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_AMT", index]];
    [params setValue:@(_amount) forKey:[NSString stringWithFormat:@"L_PAYMENTREQUEST_%d_AMT%d", index,index]];

    [params setValue:@(_amount) forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_ITEMAMT", index]];
    [params setValue:@(shippingfee) forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPPINGAMT", index]];
    [params setValue:currency forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_CURRENCYCODE", index]];

    [params setValue:@(noShipping) forKey:@"NOSHIPPING"];
    [params setValue:@(allowNote) forKey:@"ALLOWNOTE"];
    [params setValue:@(self.addressOverride) forKey:@"ADDROVERRIDE"];

    if (quantity != 0)
    {
        [params setValue:@(quantity) forKey:[NSString stringWithFormat:@"L_PAYMENTREQUEST_%d_QTY%d", index,index]];
    }

    [self setNotNullValue:seller forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SELLERPAYPALACCOUNTID", index]];
    [self setNotNullValue:paymentAction forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_PAYMENTACTION", index]];
    [self setNotNullValue:shipToName forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTONAME", index]];
    [self setNotNullValue:shipToStreet forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOSTREET", index]];
    [self setNotNullValue:shipToStreet2 forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOSTREET2", index]];
    [self setNotNullValue:shipToCity forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOCITY", index]];
    [self setNotNullValue:shipToState forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOSTATE", index]];
    [self setNotNullValue:shipToZip forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOZIP", index]];
    [self setNotNullValue:shipToCountryCode forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOCOUNTRYCODE", index]];
    [self setNotNullValue:shipToCountryName forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOCOUNTRYNAME", index]];
    [self setNotNullValue:shipToPhoneNumber forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_SHIPTOPHONENUM", index]];
    [self setNotNullValue:shipToAddressStatus forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_ADDRESSSTATUS", index]];
    [self setNotNullValue:shipToAddressNormalizationStatus forKey:[NSString stringWithFormat:@"PAYMENTREQUEST_%d_ADDRESSNORMALIZATIONSTATUS", index]];

    return params;
}

- (void)setNotNullValue:(id)object forKey:(NSString *)key
{
    if (object)
    {
        [params setValue:object forKey:key];
    }
}

@end


text: Logout


text:
import requests
import responses
from nose.tools import assert_is_instance, assert_raises

from gocardless_pro import Client
from gocardless_pro import services

access_token = 'access-token-xyz'
client = Client(access_token=access_token, base_url='http://example.com')

def test_requires_valid_environment():
    assert_raises(ValueError, Client, access_token=access_token, environment='invalid')

def test_bank_authorisations_returns_service():
    assert_is_instance(client.bank_authorisations, services.BankAuthorisationsService)

def test_bank_details_lookups_returns_service():
    assert_is_instance(client.bank_details_lookups, services.BankDetailsLookupsService)

def test_billing_requests_returns_service():
    assert_is_instance(client.billing_requests, services.BillingRequestsService)

def test_billing_request_flows_returns_service():
    assert_is_instance(client.billing_request_flows, services.BillingRequestFlowsService)

def test_billing_request_templates_returns_service():
    assert_is_instance(client.billing_request_templates, services.BillingRequestTemplatesService)

def test_blocks_returns_service():
    assert_is_instance(client.blocks, services.BlocksService)

def test_creditors_returns_service():
    assert_is_instance(client.creditors, services.CreditorsService)

def test_creditor_bank_accounts_returns_service():
    assert_is_instance(client.creditor_bank_accounts, services.CreditorBankAccountsService)

def test_currency_exchange_rates_returns_service():
    assert_is_instance(client.currency_exchange_rates, services.CurrencyExchangeRatesService)

def test_customers_returns_service():
    assert_is_instance(client.customers, services.CustomersService)

def test_customer_bank_accounts_returns_service():
    assert_is_instance(client.customer_bank_accounts, services.CustomerBankAccountsService)

def test_customer_notifications_returns_service():
    assert_is_instance(client.customer_notifications, services.CustomerNotificationsService)

def test_events_returns_service():
    assert_is_instance(client.events, services.EventsService)

def test_instalment_schedules_returns_service():
    assert_is_instance(client.instalment_schedules, services.InstalmentSchedulesService)

def test_institutions_returns_service():
    assert_is_instance(client.institutions, services.InstitutionsService)

def test_mandates_returns_service():
    assert_is_instance(client.mandates, services.MandatesService)

def test_mandate_imports_returns_service():
    assert_is_instance(client.mandate_imports, services.MandateImportsService)

def test_mandate_import_entries_returns_service():
    assert_is_instance(client.mandate_import_entries, services.MandateImportEntriesService)

def test_mandate_pdfs_returns_service():
    assert_is_instance(client.mandate_pdfs, services.MandatePdfsService)

def test_payer_authorisations_returns_service():
    assert_is_instance(client.payer_authorisations, services.PayerAuthorisationsService)

def test_payments_returns_service():
    assert_is_instance(client.payments, services.PaymentsService)

def test_payouts_returns_service():
    assert_is_instance(client.payouts, services.PayoutsService)

def test_payout_items_returns_service():
    assert_is_instance(client.payout_items, services.PayoutItemsService)

def test_redirect_flows_returns_service():
    assert_is_instance(client.redirect_flows, services.RedirectFlowsService)

def test_refunds_returns_service():
    assert_is_instance(client.refunds, services.RefundsService)

def test_scenario_simulators_returns_service():
    assert_is_instance(client.scenario_simulators, services.ScenarioSimulatorsService)

def test_subscriptions_returns_service():
    assert_is_instance(client.subscriptions, services.SubscriptionsService)

def test_tax_rates_returns_service():
    assert_is_instance(client.tax_rates, services.TaxRatesService)

def test_webhooks_returns_service():
    assert_is_instance(client.webhooks, services.WebhooksService)


text:
import hmac, base64, struct, hashlib, time, json, os

def get_hotp_token(secret, intervals_no):
	"""This is where the magic happens."""
	key = base64.b32decode(normalize(secret), True) # True is to fold lower into uppercase
	msg = struct.pack(">Q", intervals_no)
	h = bytearray(hmac.new(key, msg, hashlib.sha1).digest())
	o = h[19] & 15
	h = str((struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000)
	return prefix0(h)

def get_totp_token(secret):
	"""The TOTP token is just a HOTP token seeded with every 30 seconds."""
	return get_hotp_token(secret, intervals_no=int(time.time())//30)

def normalize(key):
	"""Normalizes secret by removing spaces and padding with = to a multiple of 8"""
	k2 = key.strip().replace(' ','')
	# k2 = k2.upper()	# skipped b/c b32decode has a foldcase argument
	if len(k2)%8 != 0:
		k2 += '='*(8-len(k2)%8)
	return k2

def prefix0(h):
	"""Prefixes code with leading zeros if missing."""
	if len(h) < 6:
		h = '0'*(6-len(h)) + h
	return h

def main():
	rel = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
	with open(os.path.join(rel,'secrets.json'), 'r') as f:
		secrets = json.load(f)
	for label, key in sorted(list(secrets.items())):
		print("{}:\t{}".format(label, get_totp_token(key)))

if __name__ == "__main__":
    main()


text:
use schema::TextOptions;
use schema::IntOptions;

use std::fmt;
use serde::{Serialize, Deserialize, Serializer, Deserializer};
use serde::ser::SerializeStruct;
use serde::de::{self, Visitor, MapAccess};
use schema::FieldType;

/// A `FieldEntry` represents a field and its configuration.
/// `Schema` are a collection of `FieldEntry`
///
/// It consists of
/// - a field name
/// - a field type, itself wrapping up options describing
/// how the field should be indexed.
#[derive(Clone, Debug)]
pub struct FieldEntry {
    name: String,
    field_type: FieldType,
}

impl FieldEntry {
    /// Creates a new u64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_text(field_name: String, field_type: TextOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::Str(field_type),
        }
    }

    /// Creates a new u64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_u64(field_name: String, field_type: IntOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::U64(field_type),
        }
    }

    /// Creates a new i64 field entry in the schema, given
    /// a name, and some options.
    pub fn new_i64(field_name: String, field_type: IntOptions) -> FieldEntry {
        FieldEntry {
            name: field_name,
            field_type: FieldType::I64(field_type),
        }
    }

    /// Returns the name of the field
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the field type
    pub fn field_type(&self) -> &FieldType {
        &self.field_type
    }

    /// Returns true iff the field is indexed
    pub fn is_indexed(&self) -> bool {
        match self.field_type {
            FieldType::Str(ref options) => options.get_indexing_options().is_indexed(),
            FieldType::U64(ref options) |
            FieldType::I64(ref options) => options.is_indexed(),
        }
    }

    /// Returns true iff the field is a int (signed or unsigned) fast field
    pub fn is_int_fast(&self) -> bool {
        match self.field_type {
            FieldType::U64(ref options) |
            FieldType::I64(ref options) => options.is_fast(),
            _ => false,
        }
    }

    /// Returns true iff the field is stored
    pub fn is_stored(&self) -> bool {
        match self.field_type {
            FieldType::U64(ref options) |
            FieldType::I64(ref options) => options.is_stored(),
            FieldType::Str(ref options) => options.is_stored(),
        }
    }
}

impl Serialize for FieldEntry {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let mut s = serializer.serialize_struct("field_entry", 3)?;
        s.serialize_field("name", &self.name)?;

        match self.field_type {
            FieldType::Str(ref options) => {
                s.serialize_field("type", "text")?;
                s.serialize_field("options", options)?;
            }
            FieldType::U64(ref options) => {
                s.serialize_field("type", "u64")?;
                s.serialize_field("options", options)?;
            }
            FieldType::I64(ref options) => {
                s.serialize_field("type", "i64")?;
                s.serialize_field("options", options)?;
            }
        }

        s.end()
    }
}

impl<'de> Deserialize<'de> for FieldEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "lowercase")]
        enum Field {
            Name,
            Type,
            Options,
        };

        const FIELDS: &'static [&'static str] = &["name", "type", "options"];

        struct FieldEntryVisitor;

        impl<'de> Visitor<'de> for FieldEntryVisitor {
            type Value = FieldEntry;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct FieldEntry")
            }

            fn visit_map<V>(self, mut map: V) -> Result<FieldEntry, V::Error>
                where V: MapAccess<'de>
            {
                let mut name = None;
                let mut ty = None;
                let mut field_type = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Name => {
                            if name.is_some() {
                                return Err(de::Error::duplicate_field("name"));
                            }
                            name = Some(map.next_value()?);
                        }
                        Field::Type => {
                            if ty.is_some() {
                                return Err(de::Error::duplicate_field("type"));
                            }
                            ty = Some(map.next_value()?);
                        }
                        Field::Options => {
                            match ty {
                                None => {
                                    let msg = "The `type` field must be \
                                               specified before `options`";
                                    return Err(de::Error::custom(msg));
                                }
                                Some(ty) => {
                                    match ty {
                                        "text" => {
                                            field_type = Some(FieldType::Str(map.next_value()?))
                                        }
                                        "u64" => {
                                            field_type = Some(FieldType::U64(map.next_value()?))
                                        }
                                        "i64" => {
                                            field_type = Some(FieldType::I64(map.next_value()?))
                                        }
                                        _ => {
                                            let msg = format!("Unrecognised type {}", ty);
                                            return Err(de::Error::custom(msg));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
                ty.ok_or_else(|| de::Error::missing_field("ty"))?;
                let field_type = field_type
                    .ok_or_else(|| de::Error::missing_field("options"))?;

                Ok(FieldEntry {
                       name: name,
                       field_type: field_type,
                   })
            }
        }

        deserializer.deserialize_struct("field_entry", FIELDS, FieldEntryVisitor)
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use schema::TEXT;
    use serde_json;

    #[test]
    fn test_json_serialization() {
        let field_value = FieldEntry::new_text(String::from("title"), TEXT);

        let expected = r#"{
  "name": "title",
  "type": "text",
  "options": {
    "indexing": "position",
    "stored": false
  }
}"#;
        let field_value_json = serde_json::to_string_pretty(&field_value).unwrap();

        assert_eq!(expected, &field_value_json);

        let field_value: FieldEntry = serde_json::from_str(expected).unwrap();

        assert_eq!("title", field_value.name);

        match field_value.field_type {
            FieldType::Str(_) => assert!(true),
            _ => panic!("expected FieldType::Str"),
        }
    }
}


text:
require 'formula'

class UniversalPython < Requirement
  satisfy(:build_env => false) { archs_for_command("python").universal? }

  def message; <<-EOS.undent
    A universal build was requested, but Python is not a universal build

    Boost compiles against the Python it finds in the path; if this Python
    is not a universal build then linking will likely fail.
    EOS
  end
end

class UniversalPython3 < Requirement
  satisfy(:build_env => false) { archs_for_command("python3").universal? }

  def message; <<-EOS.undent
    A universal build was requested, but Python 3 is not a universal build

    Boost compiles against the Python 3 it finds in the path; if this Python
    is not a universal build then linking will likely fail.
    EOS
  end
end

class Boost < Formula
  homepage 'http://www.boost.org'
  url 'https://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.bz2'
  sha1 'cef9a0cc7084b1d639e06cd3bc34e4251524c840'
  revision 2

  head 'https://github.com/boostorg/boost.git'

  bottle do
    cellar :any
    revision 4
    sha1 "81b8843487a6f0017fac77b4bf58bdc20f3298fa" => :mavericks
    sha1 "40089f76eddb25ac418032fa0055b6f0b6d76847" => :mountain_lion
    sha1 "da4fb2a221fd83f50741f757eefe4bc38b5e910c" => :lion
  end

  env :userpaths

  option :universal
  option 'with-icu', 'Build regexp engine with icu support'
  option 'without-single', 'Disable building single-threading variant'
  option 'without-static', 'Disable building static library variant'
  option 'with-mpi', 'Build with MPI support'
  option :cxx11

  depends_on :python => :optional
  depends_on :python3 => :optional
  depends_on UniversalPython if build.universal? and build.with? "python"
  depends_on UniversalPython3 if build.universal? and build.with? "python3"

  if build.with?("python3") && build.with?("python")
    odie "boost: --with-python3 cannot be specified when using --with-python"
  end

  if build.with? 'icu'
    if build.cxx11?
      depends_on 'icu4c' => 'c++11'
    else
      depends_on 'icu4c'
    end
  end

  if build.with? 'mpi'
    if build.cxx11?
      depends_on 'open-mpi' => 'c++11'
    else
      depends_on :mpi => [:cc, :cxx, :optional]
    end
  end

  stable do
    # Patches boost::atomic for LLVM 3.4 as it is used on OS X 10.9 with Xcode 5.1
    # https://github.com/Homebrew/homebrew/issues/27396
    # https://github.com/Homebrew/homebrew/pull/27436
    patch :p2 do
      url "https://github.com/boostorg/atomic/commit/6bb71fdd.diff"
      sha1 "ca8679011d5293a7fd02cb3b97dde3515b8b2b03"
    end

    patch :p2 do
      url "https://github.com/boostorg/atomic/commit/e4bde20f.diff"
      sha1 "b68f5536474c9f543879698299bd4975538a89eb"
    end

    # Patch fixes upstream issue reported here (https://svn.boost.org/trac/boost/ticket/9698).
    # Will be fixed in Boost 1.56 and can be removed once that release is available.
    # See this issue (https://github.com/Homebrew/homebrew/issues/30592) for more details.

    patch :p2 do
      url "https://github.com/boostorg/chrono/commit/143260d.diff"
      sha1 "2600214608e7706116831d6ffc302d099ba09950"
    end

    # Patch boost::serialization for Clang
    # https://svn.boost.org/trac/boost/ticket/8757
    patch :p1 do
      url "https://gist.githubusercontent.com/philacs/375303205d5f8918e700/raw/d6ded52c3a927b6558984d22efe0a5cf9e59cd8c/0005-Boost.S11n-include-missing-algorithm.patch"
      sha1 "a37552d48e5c1c0507ee9d48fb82a3fa5e3bc9fa"
    end
  end

  fails_with :llvm do
    build 2335
    cause "Dropped arguments to functions when linking with boost"
  end

  def install
    # https://svn.boost.org/trac/boost/ticket/8841
    if build.with? 'mpi' and build.with? 'single'
      raise <<-EOS.undent
        Building MPI support for both single and multi-threaded flavors
        is not supported.  Please use '--with-mpi' together with
        '--without-single'.
      EOS
    end

    if build.cxx11? and build.with? 'mpi' and (build.with? 'python' \
                                               or build.with? 'python3')
      raise <<-EOS.undent
        Building MPI support for Python using C++11 mode results in
        failure and hence disabled.  Please don't use this combination
        of options.
      EOS
    end

    ENV.universal_binary if build.universal?

    # Force boost to compile using the appropriate GCC version.
    open("user-config.jam", "a") do |file|
      file.write "using darwin : : #{ENV.cxx} ;\n" if OS.mac?
      file.write "using mpi ;\n" if build.with? 'mpi'

      # Link against correct version of Python if python3 build was requested
      if build.with? 'python3'
        py3executable = `which python3`.strip
        py3version = `python3 -c "import sys; print(sys.version[:3])"`.strip
        py3prefix = `python3 -c "import sys; print(sys.prefix)"`.strip

        file.write <<-EOS.undent
          using python : #{py3version}
                       : #{py3executable}
                       : #{py3prefix}/include/python#{py3version}m
                       : #{py3prefix}/lib ;
        EOS
      end
    end

    # we specify libdir too because the script is apparently broken
    bargs = ["--prefix=#{prefix}", "--libdir=#{lib}"]

    if build.with? 'icu'
      icu4c_prefix = Formula['icu4c'].opt_prefix
      bargs << "--with-icu=#{icu4c_prefix}"
    else
      bargs << '--without-icu'
    end

    # Handle libraries that will not be built.
    without_libraries = []

    # The context library is implemented as x86_64 ASM, so it
    # won't build on PPC or 32-bit builds
    # see https://github.com/Homebrew/homebrew/issues/17646
    if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
      without_libraries << "context"
      # The coroutine library depends on the context library.
      without_libraries << "coroutine"
    end

    # Boost.Log cannot be built using Apple GCC at the moment. Disabled
    # on such systems.
    without_libraries << "log" if ENV.compiler == :gcc || ENV.compiler == :llvm
    without_libraries << "python" if (build.without? 'python' \
                                      and build.without? 'python3')
    without_libraries << "mpi" if build.without? 'mpi'

    bargs << "--without-libraries=#{without_libraries.join(',')}"

    args = ["--prefix=#{prefix}",
            "--libdir=#{lib}",
            "-d2",
            "-j#{ENV.make_jobs}",
            "--layout=tagged",
            "--user-config=user-config.jam",
            "install"]

    if build.with? "single"
      args << "threading=multi,single"
    else
      args << "threading=multi"
    end

    if build.with? "static"
      args << "link=shared,static"
    else
      args << "link=shared"
    end

    args << "address-model=32_64" << "architecture=x86" << "pch=off" if build.universal?

    # Trunk starts using "clang++ -x c" to select C compiler which breaks C++11
    # handling using ENV.cxx11. Using "cxxflags" and "linkflags" still works.
    if build.cxx11?
      args << "cxxflags=-std=c++11"
      if ENV.compiler == :clang
        args << "cxxflags=-stdlib=libc++" << "linkflags=-stdlib=libc++"
      end
    end

    system "./bootstrap.sh", *bargs
    system "./b2", *args
  end

  def caveats
    s = ''
    # ENV.compiler doesn't exist in caveats. Check library availability
    # instead.
    if Dir["#{lib}/libboost_log*"].empty?
      s += <<-EOS.undent

      Building of Boost.Log is disabled because it requires newer GCC or Clang.
      EOS
    end

    if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
      s += <<-EOS.undent

      Building of Boost.Context and Boost.Coroutine is disabled as they are
      only supported on x86_64.
      EOS
    end

    s
  end
end


text:
namespace os {
namespace internal {

inline Try<OSVERSIONINFOEX> os_version()
{
  OSVERSIONINFOEX os_version;
  os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  if (!::GetVersionEx(reinterpret_cast<LPOSVERSIONINFO>(&os_version))) {
    return WindowsError(
        "os::internal::os_version: Call to `GetVersionEx` failed");
  }

  return os_version;
}

inline Try<std::string> nodename()
{
  // Get DNS name of the local computer. First, find the size of the output
  // buffer.
  DWORD size = 0;
  if (!::GetComputerNameEx(ComputerNameDnsHostname, nullptr, &size) &&
      ::GetLastError() != ERROR_MORE_DATA) {
    return WindowsError(
        "os::internal::nodename: Call to `GetComputerNameEx` failed");
  }

  std::unique_ptr<char[]> name(new char[size + 1]);

  if (!::GetComputerNameEx(ComputerNameDnsHostname, name.get(), &size)) {
    return WindowsError(
        "os::internal::nodename: Call to `GetComputerNameEx` failed");
  }

  return std::string(name.get());
}

inline std::string machine()
{
  SYSTEM_INFO system_info;
  ::GetNativeSystemInfo(&system_info);

  switch (system_info.wProcessorArchitecture) {
    case PROCESSOR_ARCHITECTURE_AMD64:
      return "AMD64";
    case PROCESSOR_ARCHITECTURE_ARM:
      return "ARM";
    case PROCESSOR_ARCHITECTURE_IA64:
      return "IA64";
    case PROCESSOR_ARCHITECTURE_INTEL:
      return "x86";
    default:
      return "Unknown";
  }
}

inline std::string sysname(OSVERSIONINFOEX os_version)
{
  switch (os_version.wProductType) {
    case VER_NT_DOMAIN_CONTROLLER:
    case VER_NT_SERVER:
      return "Windows Server";
    default:
      return "Windows";
  }
}

inline std::string release(OSVERSIONINFOEX os_version)
{
  return stringify(
      Version(os_version.dwMajorVersion, os_version.dwMinorVersion, 0));
}

inline std::string version(OSVERSIONINFOEX os_version)
{
  std::string version = std::to_string(os_version.dwBuildNumber);

  if (os_version.szCSDVersion[0] != '\0') {
    version.append(" ");
    version.append(os_version.szCSDVersion);
  }

  return version;
}

} // namespace internal {

// Overload of os::pids for filtering by groups and sessions. A group / session
// id of 0 will fitler on the group / session ID of the calling process.
// NOTE: Windows does not have the concept of a process group, so we need to
// enumerate all processes.
inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session)
{
  DWORD max_items = 4096;
  DWORD bytes_returned;
  std::vector<pid_t> processes;
  size_t size_in_bytes;

  // Attempt to populate `processes` with PIDs. We repeatedly call
  // `EnumProcesses` with increasingly large arrays until it "succeeds" at
  // populating the array with PIDs. The criteria for determining when
  // `EnumProcesses` has succeeded are:
  //   (1) the return value is nonzero.
  //   (2) the `bytes_returned` is less than the number of bytes in the array.
  do {
    // TODO(alexnaparu): Set a limit to the memory that can be used.
    processes.resize(max_items);
    size_in_bytes = processes.size() * sizeof(pid_t);
    BOOL result = ::EnumProcesses(processes.data(), size_in_bytes,
                                  &bytes_returned);

    if (!result) {
      return WindowsError("os::pids: Call to `EnumProcesses` failed");
    }

    max_items *= 2;
  } while (bytes_returned >= size_in_bytes);

  return std::set<pid_t>(processes.begin(), processes.end());
}

inline Try<std::set<pid_t>> pids()
{
  return pids(None(), None());
}

// Sets the value associated with the specified key in the set of
// environment variables.
inline void setenv(
    const std::string& key,
    const std::string& value,
    bool overwrite = true)
{
  // Do not set the variable if already set and `overwrite` was not specified.
  //
  // Per MSDN[1], `GetEnvironmentVariable` returns 0 on error and sets the
  // error code to `ERROR_ENVVAR_NOT_FOUND` if the variable was not found.
  //
  // [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms683188(v=vs.85).aspx
  if (!overwrite &&
      ::GetEnvironmentVariable(key.c_str(), nullptr, 0) != 0 &&
      ::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
    return;
  }

  // `SetEnvironmentVariable` returns an error code, but we can't act on it.
  ::SetEnvironmentVariable(key.c_str(), value.c_str());
}

// Unsets the value associated with the specified key in the set of
// environment variables.
inline void unsetenv(const std::string& key)
{
  // Per MSDN documentation[1], passing `nullptr` as the value will cause
  // `SetEnvironmentVariable` to delete the key from the process's environment.
  ::SetEnvironmentVariable(key.c_str(), nullptr);
}

// Suspends execution of the calling process until a child specified by `pid`
// has changed state. Unlike the POSIX standard function `::waitpid`, this
// function does not use -1 and 0 to signify errors and nonblocking return.
// Instead, we return `Result<pid_t>`:
//   * In case of error, we return `Error` rather than -1. For example, we
//     would return an `Error` in case of `EINVAL`.
//   * In case of nonblocking return, we return `None` rather than 0. For
//     example, if we pass `WNOHANG` in the `options`, we would expect 0 to be
//     returned in the case that children specified by `pid` exist, but have
//     not changed state yet. In this case we return `None` instead.
//
// NOTE: There are important differences between the POSIX and Windows
// implementations of this function:
//   * On POSIX, `pid_t` is a signed number, but on Windows, PIDs are `DWORD`,
//     which is `unsigned long`. Thus, if we use `DWORD` to represent the `pid`
//     argument, passing -1 as the `pid` would (on most modern servers)
//     silently convert to a really large `pid`. This is undesirable.
//   * Since it is important to be able to detect -1 has been passed to
//     `os::waitpid`, as a matter of practicality, we choose to:
//     (1) Use `long` to represent the `pid` argument.
//     (2) Disable using any value <= 0 for `pid` on Windows.
//   * This decision is pragmatic. The reasoning is:
//     (1) The Windows code paths call `os::waitpid` in only a handful of
//         places, and in none of these conditions do we need `-1` as a value.
//     (2) Since PIDs virtually never take on values outside the range of
//         vanilla signed `long` it is likely that an accidental conversion
//         will never happen.
//     (3) Even though it is not formalized in the C specification, the
//         implementation of `long` on the vast majority of production servers
//         is 2's complement, so we expect that when we accidentally do
//         implicitly convert from `unsigned long` to `long`, we will "wrap
//         around" to negative values. And since we've disabled the negative
//         `pid` in the Windows implementation, we should error out.
//   * Finally, on Windows, we currently do not check that the process we are
//     attempting to await is a child process.
inline Result<pid_t> waitpid(long pid, int* status, int options)
{
  const bool wait_for_child = (options & WNOHANG) == 0;

  // NOTE: Windows does not implement pids <= 0.
  if (pid <= 0) {
    errno = ENOSYS;
    return ErrnoError(
        "os::waitpid: Value of pid is '" + stringify(pid) +
        "'; the Windows implementation currently does not allow values <= 0");
  } else if (options != 0 && options != WNOHANG) {
    // NOTE: We only support `options == 0` or `options == WNOHANG`. On Windows
    // no flags other than `WNOHANG` are supported.
    errno = ENOSYS;
    return ErrnoError(
        "os::waitpid: Only flag `WNOHANG` is implemented on Windows");
  }

  // TODO(hausdorff): Check that `pid` is one of the child processes. If not,
  // set `errno` to `ECHILD` and return -1.

  // Open the child process as a safe `SharedHandle`.
  const HANDLE process = ::OpenProcess(
      PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
      FALSE,
      static_cast<DWORD>(pid));

  if (process == nullptr) {
    return WindowsError("os::waitpid: Failed to open process for pid '" +
                        stringify(pid) + "'");
  }

  SharedHandle scoped_process(process, ::CloseHandle);

  // If `WNOHANG` flag is set, don't wait. Otherwise, wait for child to
  // terminate.
  const DWORD wait_time = wait_for_child ? INFINITE : 0;
  const DWORD wait_results = ::WaitForSingleObject(
      scoped_process.get(),
      wait_time);

  // Verify our wait exited correctly.
  const bool state_signaled = wait_results == WAIT_OBJECT_0;
  if (options == 0 && !state_signaled) {
    // If `WNOHANG` is not set, then we should have stopped waiting only for a
    // state change in `scoped_process`.
    errno = ECHILD;
    return WindowsError(
        "os::waitpid: Failed to wait for pid '" + stringify(pid) +
        "'. `::WaitForSingleObject` should have waited for child process to " +
        "exit, but returned code '" + stringify(wait_results) +
        "' instead");
  } else if (wait_for_child && !state_signaled &&
             wait_results != WAIT_TIMEOUT) {
    // If `WNOHANG` is set, then a successful wait should report either a
    // timeout (since we set the time to wait to `0`), or a successful state
    // change of `scoped_process`. Anything else is an error.
    errno = ECHILD;
    return WindowsError(
        "os::waitpid: Failed to wait for pid '" + stringify(pid) +
        "'. `ENOHANG` flag was passed in, so `::WaitForSingleObject` should " +
        "have either returned `WAIT_OBJECT_0` or `WAIT_TIMEOUT` (the " +
        "timeout was set to 0, because we are not waiting for the child), " +
        "but instead returned code '" + stringify(wait_results) + "'");
  }

  if (!wait_for_child && wait_results == WAIT_TIMEOUT) {
    // Success. `ENOHANG` was set and we got a timeout, so return `None` (POSIX
    // `::waitpid` would return 0 here).
    return None();
  }

  // Attempt to retrieve exit code from child process. Store that exit code in
  // the `status` variable if it's `nullptr`.
  DWORD child_exit_code = 0;
  if (!::GetExitCodeProcess(scoped_process.get(), &child_exit_code)) {
    errno = ECHILD;
    return WindowsError(
        "os::waitpid: Successfully waited on child process with pid '" +
        std::to_string(pid) + "', but could not retrieve exit code");
  }

  if (status != nullptr) {
    *status = child_exit_code;
  }

  // Success. Return pid of the child process for which the status is reported.
  return pid;
}

inline std::string hstrerror(int err)
{
  char buffer[1024];
  DWORD format_error = 0;

  // NOTE: Per the Linux documentation[1], `h_errno` can have only one of the
  // following errors.
  switch (err) {
    case WSAHOST_NOT_FOUND:
    case WSANO_DATA:
    case WSANO_RECOVERY:
    case WSATRY_AGAIN: {
      format_error = ::FormatMessage(
          FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
          nullptr,
          err,
          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
          buffer,
          sizeof(buffer),
          nullptr);
      break;
    }
    default: {
      return "Unknown resolver error";
    }
  }

  if (format_error == 0) {
    // If call to `FormatMessage` fails, then we choose to output the error
    // code rather than call `FormatMessage` again.
    return "os::hstrerror: Call to `FormatMessage` failed with error code" +
      std::to_string(GetLastError());
  } else {
    return buffer;
  }
}

// This function is a portable version of execvpe ('p' means searching
// executable from PATH and 'e' means setting environments). We add
// this function because it is not available on all systems.
inline int execvpe(const char* file, char** argv, char** envp) = delete;

inline Try<Nothing> chown(
    uid_t uid,
    gid_t gid,
    const std::string& path,
    bool recursive) = delete;

inline Try<Nothing> chmod(const std::string& path, int mode) = delete;

inline Try<Nothing> mknod(
    const std::string& path,
    mode_t mode,
    dev_t dev) = delete;

// Suspends execution for the given duration.
// NOTE: This implementation features a millisecond-resolution sleep API, while
// the POSIX version uses a nanosecond-resolution sleep API. As of this writing,
// Mesos only requires millisecond resolution, so this is ok for now.
inline Try<Nothing> sleep(const Duration& duration)
{
  ::Sleep(static_cast<DWORD>(duration.ms()));

  return Nothing();
}

// Returns the list of files that match the given (shell) pattern.
// NOTE: Deleted on Windows, as a POSIX-API-compliant `glob` is much more
// trouble than its worth, considering our relatively simple usage.
inline Try<std::list<std::string>> glob(const std::string& pattern) = delete;

// Returns the total number of cpus (cores).
inline Try<long> cpus()
{
  SYSTEM_INFO sysInfo;
  ::GetSystemInfo(&sysInfo);
  return static_cast<long>(sysInfo.dwNumberOfProcessors);
}

// Returns load struct with average system loads for the last
// 1, 5 and 15 minutes respectively.
// Load values should be interpreted as usual average loads from
// uptime(1).
inline Try<Load> loadavg()
{
  // No Windows equivalent, return an error until there is a need. We can
  // construct an approximation of this function by periodically polling
  // `GetSystemTimes` and using a sliding window of statistics.
  return WindowsErrorBase(ERROR_NOT_SUPPORTED,
                          "Failed to determine system load averages");
}

// Returns the total size of main and free memory.
inline Try<Memory> memory()
{
  Memory memory;

  MEMORYSTATUSEX memory_status;
  memory_status.dwLength = sizeof(MEMORYSTATUSEX);
  if (!::GlobalMemoryStatusEx(&memory_status)) {
    return WindowsError("os::memory: Call to `GlobalMemoryStatusEx` failed");
  }

  memory.total = Bytes(memory_status.ullTotalPhys);
  memory.free = Bytes(memory_status.ullAvailPhys);
  memory.totalSwap = Bytes(memory_status.ullTotalPageFile);
  memory.freeSwap = Bytes(memory_status.ullAvailPageFile);

  return memory;
}

inline Try<Version> release()
{
  OSVERSIONINFOEX os_version;
  os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  if (!::GetVersionEx(reinterpret_cast<LPOSVERSIONINFO>(&os_version))) {
    return WindowsError("os::release: Call to `GetVersionEx` failed");
  }

  return Version(os_version.dwMajorVersion, os_version.dwMinorVersion, 0);
}

// Return the system information.
inline Try<UTSInfo> uname()
{
  Try<OSVERSIONINFOEX> os_version = internal::os_version();
  if (os_version.isError()) {
    return Error(os_version.error());
  }

  // Add nodename to `UTSInfo` object.
  Try<std::string> nodename = internal::nodename();
  if (nodename.isError()) {
    return Error(nodename.error());
  }

  // Populate `UTSInfo`.
  UTSInfo info;

  info.sysname = internal::sysname(os_version.get());
  info.release = internal::release(os_version.get());
  info.version = internal::version(os_version.get());
  info.nodename = nodename.get();
  info.machine = internal::machine();

  return info;
}

// Looks in the environment variables for the specified key and
// returns a string representation of its value. If no environment
// variable matching key is found, None() is returned.
inline Option<std::string> getenv(const std::string& key)
{
  DWORD buffer_size = ::GetEnvironmentVariable(key.c_str(), nullptr, 0);
  if (buffer_size == 0) {
    return None();
  }

  std::unique_ptr<char[]> environment(new char[buffer_size]);

  DWORD value_size =
    ::GetEnvironmentVariable(key.c_str(), environment.get(), buffer_size);

  if (value_size == 0) {
    // If `value_size == 0` here, that probably means the environment variable
    // was deleted between when we checked and when we allocated the buffer. We
    // report `None` to indicate the environment variable was not found.
    return None();
  }

  return std::string(environment.get());
}

inline tm* gmtime_r(const time_t* timep, tm* result)
{
  return ::gmtime_s(result, timep) == ERROR_SUCCESS ? result : nullptr;
}

inline Result<PROCESSENTRY32> process_entry(pid_t pid)
{
  // Get a snapshot of the processes in the system. NOTE: We should not check
  // whether the handle is `nullptr`, because this API will always return
  // `INVALID_HANDLE_VALUE` on error.
  HANDLE snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, pid);
  if (snapshot_handle == INVALID_HANDLE_VALUE) {
    return WindowsError(
        "os::process_entry: Call to `CreateToolhelp32Snapshot` failed");
  }

  SharedHandle safe_snapshot_handle(snapshot_handle, ::CloseHandle);

  // Initialize process entry.
  PROCESSENTRY32 process_entry;
  ZeroMemory(&process_entry, sizeof(PROCESSENTRY32));
  process_entry.dwSize = sizeof(PROCESSENTRY32);

  // Get first process so that we can loop through process entries until we
  // find the one we care about.
  SetLastError(ERROR_SUCCESS);
  bool has_next = Process32First(safe_snapshot_handle.get(), &process_entry);
  if (!has_next) {
    // No first process was found. We should never be here; it is arguable we
    // should return `None`, since we won't find the PID we're looking for, but
    // we elect to return `Error` because something terrible has probably
    // happened.
    if (GetLastError() != ERROR_SUCCESS) {
      return WindowsError("os::process_entry: Call to `Process32First` failed");
    } else {
      return Error("os::process_entry: Call to `Process32First` failed");
    }
  }

  // Loop through processes until we find the one we're looking for.
  while (has_next) {
    if (process_entry.th32ProcessID == pid) {
      // Process found.
      return process_entry;
    }

    has_next = Process32Next(safe_snapshot_handle.get(), &process_entry);
    if (!has_next) {
      DWORD last_error = GetLastError();
      if (last_error != ERROR_NO_MORE_FILES && last_error != ERROR_SUCCESS) {
        return WindowsError(
            "os::process_entry: Call to `Process32Next` failed");
      }
    }
  }

  return None();
}

// Generate a `Process` object for the process associated with `pid`. If
// process is not found, we return `None`; error is reserved for the case where
// something went wrong.
inline Result<Process> process(pid_t pid)
{
  // Find process with pid.
  Result<PROCESSENTRY32> entry = process_entry(pid);

  if (entry.isError()) {
    return WindowsError(entry.error());
  } else if (entry.isNone()) {
    return None();
  }

  HANDLE process_handle = ::OpenProcess(
      PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ,
      false,
      pid);

  if (process_handle == INVALID_HANDLE_VALUE) {
    return WindowsError("os::process: Call to `OpenProcess` failed");
  }

  SharedHandle safe_process_handle(process_handle, ::CloseHandle);

  // Get Windows Working set size (Resident set size in linux).
  PROCESS_MEMORY_COUNTERS proc_mem_counters;
  BOOL get_process_memory_info = ::GetProcessMemoryInfo(
      safe_process_handle.get_handle(),
      &proc_mem_counters,
      sizeof(proc_mem_counters));

  if (!get_process_memory_info) {
    return WindowsError("os::process: Call to `GetProcessMemoryInfo` failed");
  }

  // Get session Id.
  pid_t session_id;
  BOOL process_id_to_session_id = ::ProcessIdToSessionId(pid, &session_id);

  if (!process_id_to_session_id) {
    return WindowsError("os::process: Call to `ProcessIdToSessionId` failed");
  }

  // Get Process CPU time.
  FILETIME create_filetime, exit_filetime, kernel_filetime, user_filetime;
  BOOL get_process_times = ::GetProcessTimes(
      safe_process_handle.get_handle(),
      &create_filetime,
      &exit_filetime,
      &kernel_filetime,
      &user_filetime);

  if (!get_process_times) {
    return WindowsError("os::process: Call to `GetProcessTimes` failed");
  }

  // Get utime and stime.
  ULARGE_INTEGER lKernelTime, lUserTime; // In 100 nanoseconds.
  lKernelTime.HighPart = kernel_filetime.dwHighDateTime;
  lKernelTime.LowPart = kernel_filetime.dwLowDateTime;
  lUserTime.HighPart = user_filetime.dwHighDateTime;
  lUserTime.LowPart = user_filetime.dwLowDateTime;

  Try<Duration> utime = Nanoseconds(lKernelTime.QuadPart * 100);
  Try<Duration> stime = Nanoseconds(lUserTime.QuadPart * 100);

  return Process(
      pid,
      entry.get().th32ParentProcessID,         // Parent process id.
      0,                                       // Group id.
      session_id,
      Bytes(proc_mem_counters.WorkingSetSize),
      utime.isSome() ? utime.get() : Option<Duration>::none(),
      stime.isSome() ? stime.get() : Option<Duration>::none(),
      entry.get().szExeFile,                   // Executable filename.
      false);                                  // Is not zombie process.
}

inline int random()
{
  return rand();
}

// `create_job` function creates a job object whose name is derived
// from the `pid` and associates the process with the job object.
// Every process started by the `pid` process which is part of the job
// object becomes part of the job object. The job name should match
// the name used in `kill_job`.
inline Try<HANDLE> create_job(pid_t pid)
{
  Try<std::string> alpha_pid = strings::internal::format("MESOS_JOB_%X", pid);
  if (alpha_pid.isError()) {
    return Error(alpha_pid.error());
  }

  HANDLE process_handle = ::OpenProcess(
      PROCESS_SET_QUOTA | PROCESS_TERMINATE,
      false,
      pid);

  if (process_handle == INVALID_HANDLE_VALUE) {
    return WindowsError("os::create_job: Call to `OpenProcess` failed");
  }

  SharedHandle safe_process_handle(process_handle, ::CloseHandle);

  HANDLE job_handle = ::CreateJobObject(nullptr, alpha_pid.get().c_str());

  if (job_handle == nullptr) {
    return WindowsError("os::create_job: Call to `CreateJobObject` failed");
  }

  JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { { 0 }, 0 };

  jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

  // The job object will be terminated when the job handle closes. This allows
  // the job tree to be terminated in case of errors by closing the handle.
  ::SetInformationJobObject(
      job_handle,
      JobObjectExtendedLimitInformation,
      &jeli,
      sizeof(jeli));

  if (::AssignProcessToJobObject(
          job_handle,
          safe_process_handle.get_handle()) == 0) {
    return WindowsError(
        "os::create_job: Call to `AssignProcessToJobObject` failed");
  };

  return job_handle;
}

// `kill_job` function assumes the process identified by `pid`
// is associated with a job object whose name is derived from it.
// Every process started by the `pid` process which is part of the job
// object becomes part of the job object. Destroying the task
// will close all such processes.
inline Try<Nothing> kill_job(pid_t pid)
{
  Try<std::string> alpha_pid = strings::internal::format("MESOS_JOB_%X", pid);
  if (alpha_pid.isError()) {
    return Error(alpha_pid.error());
  }

  HANDLE job_handle = ::OpenJobObject(
      JOB_OBJECT_TERMINATE,
      FALSE,
      alpha_pid.get().c_str());

  if (job_handle == nullptr) {
    return WindowsError("os::kill_job: Call to `OpenJobObject` failed");
  }

  SharedHandle safe_job_handle(job_handle, ::CloseHandle);

  BOOL result = ::TerminateJobObject(safe_job_handle.get_handle(), 1);
  if (result == 0) {
    return WindowsError();
  }

  return Nothing();
}

inline std::string temp()
{
  // Get temp folder for current user.
  char temp_folder[MAX_PATH + 2];
  if (::GetTempPath(MAX_PATH + 2, temp_folder) == 0) {
    // Failed, try current folder.
    if (::GetCurrentDirectory(MAX_PATH + 2, temp_folder) == 0) {
      // Failed, use relative path.
      return ".";
    }
  }

  return std::string(temp_folder);
}

// Create pipes for interprocess communication. Since the pipes cannot
// be used directly by Posix `read/write' functions they are wrapped
// in file descriptors, a process-local concept.
inline Try<Nothing> pipe(int pipe[2])
{
  // Create inheritable pipe, as described in MSDN[1].
  //
  // [1] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365782(v=vs.85).aspx
  SECURITY_ATTRIBUTES securityAttr;
  securityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  securityAttr.bInheritHandle = TRUE;
  securityAttr.lpSecurityDescriptor = nullptr;

  HANDLE read_handle;
  HANDLE write_handle;

  const BOOL result = ::CreatePipe(
      &read_handle,
      &write_handle,
      &securityAttr,
      0);

  pipe[0] = _open_osfhandle(
      reinterpret_cast<intptr_t>(read_handle),
      _O_RDONLY | _O_TEXT);

  if (pipe[0] == -1) {
    return ErrnoError();
  }

  pipe[1] = _open_osfhandle(reinterpret_cast<intptr_t>(write_handle), _O_TEXT);
  if (pipe[1] == -1) {
    return ErrnoError();
  }

  return Nothing();
}

// Prepare the file descriptors to be shared with a different process.
// Under Windows we have to obtain the underlying handles to be shared
// with a different processs.
inline intptr_t fd_to_handle(int in)
{
  return ::_get_osfhandle(in);
}

// Convert the global file handle into a file descriptor, which on
// Windows is only valid within the current process.
inline int handle_to_fd(intptr_t in, int flags)
{
  return ::_open_osfhandle(in, flags);
}

} // namespace os {

#endif // __STOUT_WINDOWS_OS_HPP__


text:
#ifndef CTKEATIMEOUTEXCEPTION_P_H
#define CTKEATIMEOUTEXCEPTION_P_H

#include <ctkException.h>

/**
 * Thrown by synchronization classes that report
 * timeouts via exceptions.
 **/
class ctkEATimeoutException : public ctkRuntimeException
{

public:

  /**
   * The approximate time that the operation lasted before
   * this timeout exception was thrown.
   **/
  const long duration;

  /**
   * Constructs a TimeoutException with the
   * specified duration value and detail message.
   */
  ctkEATimeoutException(long time, const QString& message = QString());

  ~ctkEATimeoutException() throw();

  /**
   * @see ctkException::name()
   */
  const char* name() const throw();

  /**
   * @see ctkException::clone()
   */
  ctkEATimeoutException* clone() const;

  /**
   * @see ctkException::rethrow()
   */
  void rethrow() const;
};

#endif // CTKEATIMEOUTEXCEPTION_P_H


text:
Thank you for your interest in Museum Manager! If you notice something that needs to be fixed or see a room for improvement, please feel free to contribute. Every contribution will count towards making  Museum Manager a better web application for the users :)

## Raising an Issue
If you notice a problem with the app and would like to notify, please raise a Github issue with a clear description of the problem. Please be as specific as possible. Including relevant snippets or screenshots is definitely encouraged. Issues will be reviewed and addressed promptly.

## Pull Request
If you would like to go ahead and make the changes, please follow the below steps:
* Fork this repo
* Make the change on your fork, with descriptive commits in the standard format
* Open a Pull Request against this repo and it will be reviewed.


text:
import { Embark, EmbarkEvents } from "embark-core";
import { Logger } from 'embark-logger';
export default class BlockchainAPI {
  private embark: Embark;
  private logger: Logger;
  private events: EmbarkEvents;
  private apiPlugins: Map<string, Map<string, (...args: any[]) => void>> = new Map();
  private requestPlugins: Map<string, Map<string, (...args: any[]) => any>> = new Map();
  constructor(embark: Embark) {
    this.embark = embark;
    this.logger = embark.logger;
    this.events = embark.events;

    this.embark.events.setCommandHandler("blockchain:api:register", (blockchainName: string, callName: string, executionCb: () => void) => {
      let apiPlugin = this.apiPlugins.get(blockchainName);
      if (!apiPlugin) {
        apiPlugin = new Map();
        this.apiPlugins.set(blockchainName, apiPlugin);
      }
      if (apiPlugin.has(callName)) {
        this.embark.logger.warn(`${blockchainName} blockchain API for call '${callName}' is being overwritten.`);
      }
      apiPlugin.set(callName, executionCb);
    });
    this.embark.events.setCommandHandler("blockchain:request:register", (blockchainName: string, requestName: string, executionCb: () => void) => {
      let requestPlugin = this.requestPlugins.get(blockchainName);
      if (!requestPlugin) {
        requestPlugin = new Map();
        this.requestPlugins.set(blockchainName, requestPlugin);
      }
      if (requestPlugin.has(requestName)) {
        this.embark.logger.warn(`${blockchainName} blockchain request for '${requestName}' is being overwritten.`);
      }
      requestPlugin.set(requestName, executionCb);
    });
  }

  private getCallForBlockchain(blockchainName: string, callName: string) {
    const apiPlugin = this.apiPlugins.get(blockchainName);
    if (!apiPlugin) {
      throw new Error(`Blockchain '${blockchainName}' does not have any APIs registered.`);
    }
    const apiPluginExecCb = apiPlugin.get(callName);
    if (!apiPluginExecCb) {
      throw new Error(`API call '${callName}' is not registered as an API plugin for the '${blockchainName}' blockchain.`);
    }
    return apiPluginExecCb;
  }

  private getRequestForBlockchain(blockchainName: string, callName: string) {
    const requestPlugin = this.requestPlugins.get(blockchainName);
    if (!requestPlugin) {
      throw new Error(`Blockchain '${blockchainName}' does not have any requests registered.`);
    }
    const requestPluginExecCb = requestPlugin.get(callName);
    if (!requestPluginExecCb) {
      throw new Error(`Request '${callName}' is not registered as a request plugin for the '${blockchainName}' blockchain.`);
    }
    return requestPluginExecCb;
  }

  protected registerRequests(blockchainName: string) {
    // TODO: Re-add blockchain:reset for tests?
    // this.events.setCommandHandler("blockchain:reset", async (cb) => {
    //   const initWeb3 = this.getRequestForBlockchain(blockchainName, "initWeb3");
    //   await initWeb3();
    //   this.events.emit("blockchain:reseted");
    //   cb();
    // });

    this.events.setCommandHandler("blockchain:get", async (cb) => {
      const blockchainObject = await this.getRequestForBlockchain(blockchainName, "blockchainObject");
      cb(blockchainObject);
    });

    this.events.setCommandHandler("blockchain:defaultAccount:get", (cb) => {
      const getDefaultAccount = this.getRequestForBlockchain(blockchainName, "getDefaultAccount");
      cb(null, getDefaultAccount());
    });

    this.events.setCommandHandler("blockchain:defaultAccount:set", (account, cb) => {
      const setDefaultAccount = this.getRequestForBlockchain(blockchainName, "setDefaultAccount");
      setDefaultAccount(account);
      cb();
    });

    this.events.setCommandHandler("blockchain:getAccounts", (cb) => {
      const getAccounts = this.getRequestForBlockchain(blockchainName, "getAccounts");
      getAccounts(cb);
    });

    this.events.setCommandHandler("blockchain:getBalance", (address, cb) => {
      const getBalance = this.getRequestForBlockchain(blockchainName, "getBalance");
      getBalance(address, cb);
    });

    this.events.setCommandHandler("blockchain:block:byNumber", (blockNumber, cb) => {
      const getBlock = this.getRequestForBlockchain(blockchainName, "getBlock");
      getBlock(blockNumber, cb);
    });

    this.events.setCommandHandler("blockchain:block:byHash", (blockHash, cb) => {
      const getBlock = this.getRequestForBlockchain(blockchainName, "getBlock");
      getBlock(blockHash, cb);
    });

    this.events.setCommandHandler("blockchain:gasPrice", (cb) => {
      const getGasPrice = this.getRequestForBlockchain(blockchainName, "getGasPrice");
      getGasPrice(cb);
    });

    this.events.setCommandHandler("blockchain:networkId", (cb) => {
      const getNetworkId = this.getRequestForBlockchain(blockchainName, "getNetworkId");
      getNetworkId(cb);
    });

    this.events.setCommandHandler("blockchain:getTransaction", async (txId, cb) => {
      const getTransaction = this.getRequestForBlockchain(blockchainName, "getTransaction");
      getTransaction(txId, cb);
    });

    this.events.setCommandHandler("blockchain:contract:create", (params, cb) => {
      const contractObject = this.getRequestForBlockchain(blockchainName, "contractObject")(params);
      cb(contractObject);
    });
  }

  protected registerAPIs(blockchainName: string) {
    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/accounts",
      (req, res) => {
        try {
          const getAccountsWithTransactionCount = this.getCallForBlockchain(blockchainName, "getAccountsWithTransactionCount");
          getAccountsWithTransactionCount(res.send.bind(res));
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/accounts/:address",
      (req, res) => {
        try {
          const getAccount = this.getCallForBlockchain(blockchainName, "getAccount");
          getAccount(req.params.address, res.send.bind(res));
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/blocks",
      (req, res) => {
        try {
          const getBlocks = this.getCallForBlockchain(blockchainName, "getBlocks");
          const from = parseInt(req.query.from, 10);
          const limit = req.query.limit || 10;
          getBlocks(from, limit, !!req.query.txObjects, !!req.query.txReceipts, res.send.bind(res));
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/blocks/:blockNumber",
      (req, res) => {
        try {
          const getBlock = this.getCallForBlockchain(blockchainName, "getBlock");
          getBlock(req.params.blockNumber, (err: Error, block: any) => {
            if (err) {
              this.logger.error(err.message);
            }
            res.send(block);
          });
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/transactions",
      (req, res) => {
        try {
          const blockFrom = parseInt(req.query.blockFrom, 10);
          const blockLimit = req.query.blockLimit || 10;
          const getTransactions = this.getCallForBlockchain(blockchainName, "getTransactions");
          getTransactions(blockFrom, blockLimit, res.send.bind(res));
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/transactions/:hash",
      (req, res) => {
        try {
          const getTransactionByHash = this.getCallForBlockchain(blockchainName, "getTransactionByHash");
          const getTransactionByRawTransactionHash = this.getCallForBlockchain(blockchainName, "getTransactionByRawTransactionHash");
          getTransactionByHash(req.params.hash, (err: Error, transaction: any) => {
            if (!err) {
              return res.send(transaction);
            }

            getTransactionByRawTransactionHash(req.params.hash, (errRaw: Error, transactionRaw: any) => {
              if (errRaw) {
                return res.send({ error: "Could not find or decode transaction hash" });
              }
              res.send(transactionRaw);
            });
          });
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "ws",
      "/embark-api/blockchain/blockHeader",
      (ws) => {
        this.events.on("block:header", (block: any) => {
          ws.send(JSON.stringify({ block }), () => { });
        });
      },
    );

    this.embark.registerAPICall(
      "ws",
      "/embark-api/blockchain/contracts/event",
      (ws) => {
        this.events.on("blockchain:contracts:event", (data: any) => {
          ws.send(JSON.stringify(data), () => { });
        });
      },
    );

    this.embark.registerAPICall(
      "get",
      "/embark-api/blockchain/contracts/events",
      async (_req, res) => {
        try {
          const getEvents = this.getCallForBlockchain(blockchainName, "getEvents");
          res.send(await getEvents(true));
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "post",
      "/embark-api/messages/sign",
      async (req, res) => {
        try {
          const signer = req.body.address;
          const message = req.body.message;
          const signMessage = this.getCallForBlockchain(blockchainName, "signMessage");
          const signature = await signMessage(message, signer);
          res.send({ signer, signature, message });
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

    this.embark.registerAPICall(
      "post",
      "/embark-api/messages/verify",
      async (req, res) => {
        try {
          const verifyMessage = this.getCallForBlockchain(blockchainName, "verifyMessage");
          const signature = JSON.parse(req.body.message);
          const address = await verifyMessage(signature.message, signature.signature);
          res.send({ address });
        } catch (error) {
          res.status(500).send({ error });
        }
      },
    );

  }

}


text:
import VectorImpl from "./vectorimpl";
import Vec4 from "./vector4";
import Clonable from "./clonable";

class Size extends VectorImpl<Size> implements Clonable {
	constructor(width:number, height:number) {
		super(2, width, height);
	}
	get width(): number { return this.x; }
	get height(): number { return this.y; }
	set width(v: number) { this.x = v; }
	set height(v: number) { this.y = v; }

	set(s: Size): Size {
		this.width = s.width;
		this.height = s.height;
		return this;
	}
	toVec4(): Vec4 {
		return new Vec4(
			this.width,
			this.height,
			1 / this.width,
			1 / this.height
		);
	}
	equal(s: Size): boolean {
		return this.width === s.width &&
				this.height === s.height;
	}
	clone(): Size {
		return new Size(this.width, this.height);
	}
}
export default Size;


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_dest_char_cpy_72b.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_dest.label.xml
Template File: sources-sink-72b.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using new[] and set data pointer to a small buffer
 * GoodSource: Allocate using new[] and set data pointer to a large buffer
 * Sinks: cpy
 *    BadSink : Copy string to data using strcpy
 * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <vector>

#include <wchar.h>

using namespace std;

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_dest_char_cpy_72
{

#ifndef OMITBAD

void badSink(vector<char *> dataVector)
{
    /* copy data out of dataVector */
    char * data = dataVector[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
        strcpy(data, source);
        printLine(data);
        delete [] data;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<char *> dataVector)
{
    char * data = dataVector[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
        strcpy(data, source);
        printLine(data);
        delete [] data;
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
class LfsObject < ActiveRecord::Base
  has_many :lfs_objects_projects, dependent: :destroy
  has_many :projects, through: :lfs_objects_projects

  validates :oid, presence: true, uniqueness: true

  mount_uploader :file, LfsObjectUploader

  def storage_project(project)
    if project && project.forked?
      storage_project(project.forked_from_project)
    else
      project
    end
  end

  def project_allowed_access?(project)
    projects.exists?(storage_project(project).id)
  end
end


text:
layout: post
title: Kuantum Öğrenme
date: 2012-03-12 21:53
author: admin
comments: true
tags: [Eğitim Bilimleri, Eğitim Bilimleri, kuantum öğrenme nedir]
---
Öğrencilere öğrenmeyi öğretme stratejisinden oluşmaktadır. Stratejinin bir kısmı şöyledir:

1- Öğrenmeyi tekrar etme,

2- Aktif Öğrenme,

3- Not Alma Teknikleri,

4- Uygun Yazma Teknikleri,

5- Hafıza Geliştirme Stratejileri,

6- Mantıklı / Yaratıcı düşünme

- Bu modelde "hata" kaçınılmazdır. Dolayısıyla hatalar öğrenciyi başarıya götürecektir. Yapılan hatalar (kaçınılmaz olarak), bize başarı için neler yapmamız gerektiği hususunda bilgiler verir. (Ders alabilmek adına hata yapılmalıdır).

- Tam anlamıyla öğrenmenin gerçekleşebilmesi için her türlü yaklaşım ve değişmelere açık olmak gerekir. Öğrenen kişiyi sınırlandıracak birtakım harici koşullar ortadan kaldırılmalıdır.

Öğrenme, dengeli gerçekleşmek zorundadır. Bu dengeli öğrenmenin içerisinde ise bireylerin farklı zeka alanlarına sahip olmaları, fiziksel ve ruhsal gelişimlerinin beraberce geliştirilmesi yatmaktadır. Bu açıdan bakıldığı zaman bu öğrenme modeli modern çağın özelliklerine, gelişim hızına daha uygun olabilecek bir model olarak gözükmektedir. Fakat her coğrafyada uygulanabilmesi için birtakım zorluklar da kaçınılmazdır.


text:
package tccrouter.gbl.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 */
abstract class JDBCDataAccessObject {

	protected Connection connection;
	protected Statement stmt;

	public JDBCDataAccessObject() {

	}

	protected void openDataBase() {

		try {

			// Step 1: Load the JDBC driver.
			Class.forName(JDBCProperties.JDBC_DRIVER);

			// Step 2: Establish the connection to the database.
			connection = DriverManager.getConnection(JDBCProperties.JDBC_DRIVER_URL, JDBCProperties.DB_USER, JDBCProperties.DB_PASSWORD);
			stmt = connection.createStatement();

		} catch (ClassNotFoundException cfe) {
			cfe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void closeDataBase() {

		try {

			stmt.close();
			connection.close();

		} catch (SQLException sqe) {
			sqe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void openStatement() {

		try {

			stmt = connection.createStatement();

		} catch (SQLException sqe) {
			sqe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void closeStatement() {

		try {

			stmt.close();

		} catch (SQLException sqe) {
			sqe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void executeBatch() {

		try {

			boolean autoCommit = connection.getAutoCommit();
			connection.setAutoCommit(false);
			stmt.executeBatch();
			connection.commit();
			connection.setAutoCommit(autoCommit);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected String currval(String simpleName) {

		try { // Prepare a statement

			Statement stmt = connection.createStatement();

			String sqlSelect = "select gen_value FROM generic_sequence_generator WHERE gen_key = '" + simpleName + "'";

			// Set the value
			ResultSet rs = stmt.executeQuery(sqlSelect);

			if (rs.next()) {

				// get id
				return new Integer(rs.getInt("gen_value")).toString();
			}

			stmt.close();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	// Retrieves the next Id value for this class and updates Table
	protected String nextval(String string) {
		try { // Prepare a statement

			Statement stmt = connection.createStatement();

			String sqlSelect = "select gen_value FROM generic_sequence_generator WHERE gen_key = '" + string + "'";

			// Set the value
			ResultSet rs = stmt.executeQuery(sqlSelect);

			if (rs.next()) {

				// increment value
				Integer next = (rs.getInt("gen_value") + 1);

				String sqlUpdate = "UPDATE generic_sequence_generator SET gen_value = " + next.toString() + " WHERE gen_key = '" + string + "'";
				Statement stmt2 = connection.createStatement();

				int rowsAffected = stmt2.executeUpdate(sqlUpdate);

				if (rowsAffected <= 0) {
					throw new SQLException("NO ROWS AFFECTED ON UPDATE");
				}

				stmt2.close();
				stmt.close();

				// get id
				return next.toString();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}


text:
<?php

namespace ZendTest\Form\Element;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Form\Element\MultiCheckbox as MultiCheckboxElement;
use Zend\Form\Factory;

class MultiCheckboxTest extends TestCase
{
    public function useHiddenAttributeDataProvider()
    {
        return array(array(true), array(false));
    }

    /**
     * @dataProvider useHiddenAttributeDataProvider
     */
    public function testProvidesInputSpecificationThatIncludesValidatorsBasedOnAttributes($useHiddenElement)
    {
        $element = new MultiCheckboxElement();
        $options = array(
            '1' => 'Option 1',
            '2' => 'Option 2',
            '3' => 'Option 3',
        );
        $element->setAttributes(array(
            'options' => $options,
        ));
        $element->setUseHiddenElement($useHiddenElement);

        $inputSpec = $element->getInputSpecification();
        $this->assertArrayHasKey('validators', $inputSpec);
        $this->assertInternalType('array', $inputSpec['validators']);

        $expectedClasses = array(
            'Zend\Validator\Explode'
        );
        foreach ($inputSpec['validators'] as $validator) {
            $class = get_class($validator);
            $this->assertTrue(in_array($class, $expectedClasses), $class);
            switch ($class) {
                case 'Zend\Validator\Explode':
                    $inArrayValidator = $validator->getValidator();
                    $this->assertInstanceOf('Zend\Validator\InArray', $inArrayValidator);

                    $values = array_values($options);
                    if ($element->useHiddenElement()) {
                        $values[] = $element->getUncheckedValue();
                    }
                    $this->assertEquals($values, $inArrayValidator->getHaystack());
                    break;
                default:
                    break;
            }
        }
    }
}


text:
[RestExpress](http://www.restexpress.org/) - composes tools to form a lightweight, minimalist Java framework for quickly creating RESTful microservices.

Test implementations with MongoDB and MySQL as a backing datastore. MongoDB is using Morphia framework for object persistance.

### Test sources

Which `Controllers` will be instantiated and wired is determined from the existense of the MongoDB or MySQL connection string.

**Important**
 * The build is using a 0.12.0-SNAPSHOT version of the RestExpress. There were problems at startup with the bundled Netty in the 0.11.3 version;
 * The MongoDB repository class is copy-pasted and new argument is introduced to get around the mandatory initialization of MongoDB indexes and collection caps.

### MongoDB
 * [Plaintext](src/main/java/hello/controller/PlaintextController.java)
 * [JSON](src/main/java/hello/controller/JsonController.java)
 * [DB](src/main/java/hello/controller/MongodbController.java)
 * [Queries](src/main/java/hello/controller/QueriesMongodbController.java)

### MySQL

 * [DB](src/main/java/hello/controller/MysqlController.java)
 * [Queries](src/main/java/hello/controller/QueriesMysqlController.java)

## Software Versions

The tests were run with:

 * [Oracle Java 10](https://www.oracle.com/java/)
 * [MySQL 5.7](http://www.mysql.com/)
 * [MongoDB](http://www.mongodb.com/)
 * [Morphia](https://morphia.dev/)

Please check the versions in the install and build scripts of TFB project.

## Test URLs

All implementations use the same URLs.

 * Plaintext - `http://localhost:8080/plaintext`
 * JSON - `http://localhost:8080/json`
 * DB - `http://localhost:8080/db`
 * Queries - `http://localhost:8080/query?queries=`


text:
require 'routemaster/middleware/root_post_only'
require 'routemaster/middleware/authenticate'
require 'routemaster/middleware/parse'
require 'routemaster/middleware/filter'
require 'routemaster/middleware/dirty'
require 'routemaster/middleware/cache'
require 'routemaster/drain/terminator'
require 'rack/builder'
require 'delegate'

module Routemaster
  module Drain
    # Rack application which authenticates, parses, filters, pushes to a dirty map,
    # busts cache, schedules preemptive caching, and finally broadcasts events
    # received from Routemaster.
    #
    # See the various corresponding middleware for details on operation:
    # {Middleware::RootPostOnly}, {Middleware::Authenticate},
    # {Middleware::Parse}, {Middleware::Filter}, {Middleware::Dirty},
    # {Middleware::Cache} and {Terminator}.
    #
    class Caching
      extend Forwardable

      def initialize(options = {})
        @terminator = terminator = Terminator.new
        @app = ::Rack::Builder.new do
          use Middleware::RootPostOnly
          use Middleware::Authenticate, options
          use Middleware::Parse
          use Middleware::Filter,       options
          use Middleware::Dirty,        options
          use Middleware::Cache,        options
          run terminator
        end
      end

      delegate :call => :@app
      delegate [:on, :subscribe] => :@terminator
    end
  end
end


text:
#include <Arduino.h>

enum LOTAAutostartManagerResult {
	OTAAUTOSTARTMNGR_SUCCESS = 0,
	OTAAUTOSTARTMNGR_NONE = 1,
	OTAAUTOSTARTMNGR_FILE_ERROR = 2
};

class LOTAAutostartManagerClass {

public:

	LOTAAutostartManagerResult getAppPath( String& appPath );
	LOTAAutostartManagerResult setAppPath( const String& appPath );

};

extern LOTAAutostartManagerClass LOTAAutostartManager;

#endif // #ifndef LOTAAUTOSTARTMANAGER_H


text:
<as-split unit="percent" [direction]="splitDirection" [gutterSize]="9">
  <as-split-area #directiveForestSplitArea size="60">
    <as-split direction="vertical" [gutterSize]="9" unit="pixel" [disabled]="true">
      <as-split-area size="*">
        <ng-directive-forest
          (selectNode)="handleNodeSelection($event)"
          (selectDomElement)="handleSelectDomElement($event)"
          (setParents)="handleSetParents($event)"
          (highlightComponent)="highlightComponent($event)"
          (removeComponentHighlight)="removeComponentHighlight()"
          (toggleInspector)="toggleInspector.emit()"
          [forest]="forest"
          [currentSelectedElement]="currentSelectedElement"
          [showCommentNodes]="showCommentNodes"
        ></ng-directive-forest>
      </as-split-area>
      <as-split-area size="22">
        <ng-breadcrumbs
          (mouseLeaveNode)="unhighlight()"
          (mouseOverNode)="highlight($event)"
          *ngIf="parents"
          (handleSelect)="handleSelect($event)"
          [parents]="parents"
        >
        </ng-breadcrumbs>
      </as-split-area>
    </as-split>
  </as-split-area>
  <as-split-area size="40" minSize="25">
    <div class="property-tab-wrapper">
      <ng-property-tab
        [currentSelectedElement]="currentSelectedElement"
        (inspect)="inspect($event)"
        (viewSource)="viewSource()"
      ></ng-property-tab>
    </div>
  </as-split-area>
</as-split>


text:
// $Id: DSRT_Direct_Dispatcher_Impl_T.cpp 91670 2010-09-08 18:02:26Z johnnyw $

#ifndef DSRT_DIRECT_DISPATCHER_IMPL_T_CPP
#define DSRT_DIRECT_DISPATCHER_IMPL_T_CPP

#include "DSRT_Direct_Dispatcher_Impl_T.h"

#if !defined (__ACE_INLINE__)
//#include "DSRT_Direct_Dispatcher_Impl_T.i"
#endif /* __ACE_INLINE__ */

namespace Kokyu
{

/*
//@@VS: This is somehow not being recognized by MSVC, which results
//in a link error. For now, the definition has been moved to the .h
//file. Needs further investigation.

template <class DSRT_Scheduler_Traits>
int Comparator_Adapter_Generator<DSRT_Scheduler_Traits>::MoreEligible::
operator ()(const DSRT_Dispatch_Item_var<DSRT_Scheduler_Traits>& item1,
            const DSRT_Dispatch_Item_var<DSRT_Scheduler_Traits>& item2)
{
  int rc = qos_comparator_ (item1->qos (), item2->qos ());

  //more eligible
  if (rc == 1)
    return 1;

  //if equally eligible, then resolve tie with the creation time of
  //the item
  if (rc == 0 && item1->insertion_time () < item2->insertion_time ())
    return 1;

  return 0;
}
*/
template <class DSRT_Scheduler_Traits>
DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
DSRT_Direct_Dispatcher_Impl (ACE_Sched_Params::Policy sched_policy,
                         int sched_scope)
  :DSRT_Dispatcher_Impl<DSRT_Scheduler_Traits>(sched_policy, sched_scope),
   sched_queue_modified_ (0),
   sched_queue_modified_cond_ (sched_queue_modified_cond_lock_)
{
  //Run scheduler thread at highest priority
  if (this->activate (this->rt_thr_flags_, 1, 0, this->executive_prio_) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  "(%t|%T) cannot activate scheduler thread in RT mode."
                  "Trying in non RT mode\n"));
      if (this->activate (this->non_rt_thr_flags_) == -1)
        ACE_ERROR ((LM_ERROR,
                    "(%t|%T) cannot activate scheduler thread\n"));
    }
}

template <class DSRT_Scheduler_Traits> int
DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
init_i (const DSRT_ConfigInfo&)
{
  return 0;
}

template <class DSRT_Scheduler_Traits> int
DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::svc (void)
{
  ACE_hthread_t scheduler_thr_handle;
  ACE_Thread::self (scheduler_thr_handle);

#ifdef KOKYU_DSRT_LOGGING
  int prio;
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("max prio=%d\n")
              ACE_TEXT ("min prio=%d\n")
              ACE_TEXT ("active prio=%d\n")
              ACE_TEXT ("inactive prio=%d\n"),
              max_prio_,
              min_prio_,
              active_prio_,
              inactive_prio_));

  if (ACE_OS::thr_getprio (scheduler_thr_handle, prio) == -1)
    {
      if (errno == ENOTSUP)
        {
          ACE_ERROR((LM_ERROR,
                     ACE_TEXT ("getprio not supported\n")
                     ));
        }
      else
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("%p\n")
                      ACE_TEXT ("thr_getprio failed")));
        }
    }

  ACE_DEBUG ((LM_DEBUG, "(%t): Scheduler thread prio is %d\n", prio));
#endif /*DSRT_LOGGING*/

  while(1)
    {
      ACE_GUARD_RETURN (cond_lock_t,
                        mon,
                        sched_queue_modified_cond_lock_,
                        0);

      if (this->shutdown_flagged_)
        break;

      while (!sched_queue_modified_)
        {
#ifdef KOKYU_DSRT_LOGGING
          ACE_DEBUG ((LM_DEBUG,
                      "(%t|%T): sched thread about to wait on cv\n"));
#endif
          sched_queue_modified_cond_.wait ();
        }

#ifdef KOKYU_DSRT_LOGGING
      ACE_DEBUG ((LM_DEBUG, "(%t|%T): sched thread done waiting on cv\n"));
#endif

      sched_queue_modified_ = 0;

      ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX,
                        synch_lock_mon,
                        this->synch_lock_,
                        0);

      if (this->ready_queue_.current_size () <= 0)
        continue;

#ifdef KOKYU_DSRT_LOGGING
      ACE_DEBUG ((LM_DEBUG, "(%t|%T):Sched Queue contents===>\n"));
      this->ready_queue_.dump ();
#endif
      DSRT_Dispatch_Item_var<DSRT_Scheduler_Traits> item_var;
      this->ready_queue_.most_eligible (item_var);

      ACE_hthread_t most_eligible_thr_handle = item_var->thread_handle ();

#ifdef KOKYU_DSRT_LOGGING
      ACE_DEBUG ((LM_DEBUG,
                  "(%t|%T):curr scheduled thr handle = %d\n",
                  this->curr_scheduled_thr_handle_));
      ACE_DEBUG ((LM_DEBUG,
                  "(%t|%T):most eligible thr handle = %d\n",
                  most_eligible_thr_handle));
#endif

      if (this->curr_scheduled_thr_handle_ != most_eligible_thr_handle)
        {
          if (this->curr_scheduled_thr_handle_ != 0)
            {
              if (ACE_OS::thr_setprio (this->curr_scheduled_thr_handle_,
                                       this->inactive_prio_,
                                       this->sched_policy_) == -1)
                {
                  ACE_ERROR ((LM_ERROR,
                              ACE_TEXT ("%p\n"),
                              ACE_TEXT ("thr_setprio on curr_scheduled_thr_handle_ failed.")));
                  ACE_DEBUG ((LM_DEBUG, "thr_handle = %d, prio = %d\n",
                              this->curr_scheduled_thr_handle_,
                              this->inactive_prio_));
                }
            }

          if (ACE_OS::thr_setprio (most_eligible_thr_handle,
                                   this->active_prio_, this->sched_policy_) == -1)
            {
              ACE_ERROR ((LM_ERROR,
                          ACE_TEXT ("%p\n"),
                          ACE_TEXT ("thr_setprio on most_eligible_thr_handle failed")));
            }

          this->curr_scheduled_thr_handle_ = most_eligible_thr_handle;
          this->curr_scheduled_guid_ = item_var->guid ();
        }
          /*change all threads in blocked_prio_ to inactive_prio_*/
          this->ready_queue_.change_prio(this->blocked_prio_, this->inactive_prio_,this->sched_policy_);
    }

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG, "(%t): sched thread exiting\n"));
#endif

  return 0;
}

template <class DSRT_Scheduler_Traits>
int DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
schedule_i (Guid_t id, const DSRT_QoSDescriptor& qos)
{
  ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->synch_lock_, -1);

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG,
              "(%t|%T):schedule_i enter\n"));
#endif

  DSRT_Dispatch_Item<DSRT_Scheduler_Traits>* item;
  ACE_hthread_t thr_handle;
  ACE_Thread::self (thr_handle);

  ACE_NEW_RETURN (item,
                  DSRT_Dispatch_Item<DSRT_Scheduler_Traits> (id, qos),
                  -1);
  item->thread_handle (thr_handle);

  if (this->ready_queue_.insert (item) == -1)
    return -1;

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG,
              "(%t|%T):schedule_i after ready_q.insert\n"));
#endif

  if (ACE_OS::thr_setprio (thr_handle,
                           this->blocked_prio_,
                           this->sched_policy_) == -1)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("thr_setprio failed")), -1);
    }

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG,
              "(%t|%T):schedule_i after thr_setprio\n"));
#endif

  //ready_queue_.dump ();

  /*first release ready_queue_ lock. Otherwise if the scheduler gets the
  sched_queue_modified_cond_lock first, then try to get the ready_queue_ lock
  just when one thread who gets the ready_queue_ lock first, then try to get
  sched_queue_modified_cond_lock. Deadlock happens.
  */
  guard.release ();

  //@@ Perhaps the lock could be moved further down just before
  //setting the condition variable?
  ACE_GUARD_RETURN (cond_lock_t,
                    mon, this->sched_queue_modified_cond_lock_, 0);

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG,
              "(%t|%T):schedule_i after acquiring cond lock\n"));
#endif

  this->sched_queue_modified_ = 1;
  this->sched_queue_modified_cond_.signal ();

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG,
              "(%t|%T):schedule_i exit\n"));
#endif

  return 0;
}

template <class DSRT_Scheduler_Traits>
int DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
update_schedule_i (Guid_t guid, const DSRT_QoSDescriptor& qos)
{
  return this->schedule (guid, qos);
}

template <class DSRT_Scheduler_Traits>
int DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
update_schedule_i (Guid_t guid, Block_Flag_t flag)
{
  ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->synch_lock_, -1);

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG, "(%t): update schedule for block entered\n"));
#endif

  DSRT_Dispatch_Item_var<DSRT_Scheduler_Traits> dispatch_item;
  ACE_hthread_t thr_handle;

  int found = this->ready_queue_.find (guid, dispatch_item);
  if (found == 0 && flag == BLOCK)
    {
      thr_handle = dispatch_item->thread_handle ();
      if (ACE_OS::thr_setprio (thr_handle,
                               this->blocked_prio_,
                               this->sched_policy_) == -1)
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("%p\n"),
                      ACE_TEXT ("thr_setprio failed")));
        }

      //monitor released because cancel_schedule would acquire the
      //lock. Using recursive mutex creates lock up.
      //
      //@@ Need to investigate this further. Also we can consider
      //using the Thread-Safe interface pattern.
      //mon.release ();
      int rc = this->cancel_schedule (guid);

#ifdef KOKYU_DSRT_LOGGING
      ACE_DEBUG ((LM_DEBUG, "(%t): update schedule for block done\n"));
#endif

      return rc;
    }

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG, "(%t): update schedule for block done\n"));
#endif

  return -1;
}

template <class DSRT_Scheduler_Traits> int
DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
cancel_schedule_i (Guid_t guid)
{
  ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX, guard, this->synch_lock_, -1);

#ifdef KOKYU_DSRT_LOGGING
  ACE_DEBUG ((LM_DEBUG, "(%t): about to remove guid\n"));
#endif

  this->ready_queue_.remove (guid);

#ifdef KOKYU_DSRT_LOGGING
  this->ready_queue_.dump ();
#endif

  if (this->curr_scheduled_guid_ == guid)
    {
      this->curr_scheduled_guid_ = 0;
      this->curr_scheduled_thr_handle_ = 0;
    }

  //release ready_queue_ lock first before getting another lock
  guard.release ();

  ACE_GUARD_RETURN (cond_lock_t,
                    mon, this->sched_queue_modified_cond_lock_, 0);
  this->sched_queue_modified_ = 1;
  this->sched_queue_modified_cond_.signal ();
  return 0;
}

template <class DSRT_Scheduler_Traits> int
DSRT_Direct_Dispatcher_Impl<DSRT_Scheduler_Traits>::
shutdown_i ()
{
  this->shutdown_flagged_ = 1;

  ACE_GUARD_RETURN (cond_lock_t, mon, this->sched_queue_modified_cond_lock_, 0);
  this->sched_queue_modified_ = 1;
  this->sched_queue_modified_cond_.signal ();
  // We have to wait until the scheduler executive thread shuts
  // down. But we have acquired the lock and if we wait without
  // releasing it, the scheduler thread will try to acquire it after
  // it gets woken up by the above signal and it fails to acquire the
  // lock. This will lead to a deadlock. So release the lock before we
  // wait.
  mon.release ();
  this->wait ();
  return 0;
}

}

#endif /* DSRT_DIRECT_DISPATCHER_IMPL_T_CPP */