text:
require 'rubygems'
require 'sinatra'
require 'data_mapper'
require 'dm-core'
require 'dm-timestamps'
require 'dm-validations'
require 'dm-migrations'
require 'date'
require 'json'

# Setup database.
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/dev.db")

# Creates User class and database representation.
class User
  include DataMapper::Resource
  property :id,                     Serial
  property :name,                   String, {
    required: true,
    length: 5..50
  }
  property :password,               String, {
    required: true,
    length: 5..50
  }
  property :login,                  String, {
    unique: true,
    required: true,
    length: 5..50
  }
  property :credit_card_num,        String, {
    required: true,
    length: 8,
    format: /^\d{8}$/
  }
  property :credit_card_type,       String, {
    required: true,
    format: /(^Visa$)|(^MasterCard$)/
  }
  property :credit_card_val,        Date, {
    required: true
  }
  has n, :tickets
end

# Creates Ticket class and database representation.
class Ticket
  include DataMapper::Resource
  property :id, Serial
  property :bus_mac_address,        String, {
    format: /^([0-9A-F]{2}:){5}[0-9A-F]{2}$/,
    length: 17
  }
  property :validated_at,           DateTime
  property :validity_time,          Integer, {
    :required => true
  }
  belongs_to :user
end

# Update database scheme if needed.
DataMapper.finalize.auto_upgrade!

# Disable access protection.
disable :protection

# Parse parameters list before every action.
before do
  request.body.rewind
  @p = JSON.parse(request.body.read, {symbolize_names: true}) rescue @p = {}
  @prices = { ticket_15: 2, ticket_30: 3, ticket_60: 5 }
end

post '/register' do
  @p[:credit_card_val] = Time.at(@p[:credit_card_val]).utc.to_date rescue nil
  user = User.new @p rescue user = User.new
  return {success: true, user: user }.to_json if user.save
  return {success: false, errors: user.errors.to_h}.to_json
end

post '/login' do
  user = User.first(:login => @p[:login], :password => @p[:password]) rescue user = nil
  return { success: true, user: user }.to_json if user
  return { success: false }.to_json
end

get '/tickets/:login' do |login|
  user = User.first(:login => login)
  return { success: true, tickets: user.tickets.all(:validated_at => nil) }.to_json if user
  return { success: false }.to_json
end

# {"ticket_15":0,"ticket_30":0,"ticket_60":0}
post '/tickets/:login/price' do |login|
  # Parameter checks.
  user = User.first(:login => login)
  return { success: false, error: 'User nonexistent' }.to_json unless user
  @p = @p.select { |k, v| !([k] & [:ticket_15, :ticket_30, :ticket_60]).empty? }
  return { success: false, error: 'Bad request' }.to_json unless @p.keys.count == 3 && @p.values.all? { |x| x.class == Fixnum }
  return { success: false, error: 'You must buy at least one ticket.' }.to_json unless @p.values.inject(:+) > 0
  return { success: false, error: "You can't have more than 10 tickets of each type." }.to_json unless
    @p.keys.all? { |k| @p[k] == 0 || (user.tickets.all(:validity_time => k.to_s[/\d+$/].to_i, :validated_at => nil).count + @p[k]) <= 10 }
  res = { success: true, price: 0 }.merge @p
  @p.each { |k, v| res[:price] += v * @prices[k] }
  [:ticket_15, :ticket_30, :ticket_60].each do |t|
    (res[t] += 1; break;) if res[t] > 0
  end if @p.values.inject(:+) >= 10
  return res.to_json
end

# {"ticket_15":0,"ticket_30":0,"ticket_60":0}
post '/tickets/:login/buy' do |login|
  # Parameter checks.
  user = User.first(:login => login)
  return { success: false, error: 'User nonexistent' }.to_json unless user
  @p = @p.select { |k, v| !([k] & [:ticket_15, :ticket_30, :ticket_60]).empty? }
  return { success: false, error: 'Bad request' }.to_json unless @p.keys.count == 3 && @p.values.all? { |x| x.class == Fixnum }
  return { success: false, error: 'You must buy at least one ticket.' }.to_json unless @p.values.inject(:+) > 0
  return { success: false, error: "You can't have more than 10 tickets of each type." }.to_json unless
    @p.keys.all? { |k| @p[k] == 0 || (user.tickets.all(:validity_time => k.to_s[/\d+$/].to_i, :validated_at => nil).count + @p[k]) <= 10 }

  # Create tickets.
  tickets = []
  @p.keys.each do |t|
    @p[t].times { tickets << user.tickets.new(validity_time: t.to_s[/\d+$/].to_i) }
  end
  tickets << user.tickets.new({ validity_time: (tickets.map { |ts| ts.validity_time }).min }) if tickets.count >= 10
  return { success: false, error: 'Error buying tickets.' } unless tickets.all? { |ts| ts.valid? }
  tickets.each { |ts| ts.save }
  {success: true, tickets: user.tickets.all(:validated_at => nil), extra: @p.values.inject(:+) < tickets.count }.to_json
end

# {"bus":"00:00:00:00:00:00"}
post '/tickets/:login/validate/:id' do |login, id|
  ticket = User.first(login: login).tickets.get(id) rescue nil
  if !ticket || ticket.validated_at || ticket.bus_mac_address || !((@p[:bus] || '').upcase =~ /^([0-9A-F]{2}:){5}[0-9A-F]{2}$/)
     return { success: false, error: 'Failed to validate.' }.to_json
  end
  return { success: true, ticket: ticket }.to_json if ticket.update({ bus_mac_address: @p[:bus].upcase, validated_at: Time.now })
  return { success: false, error: 'Failed to validate.' }.to_json
end

post '/tickets/list' do
  tickets = Ticket.all(:bus_mac_address => @p[:bus].upcase, :validated_at.gte => Time.now - 90 * 60) rescue nil
  { success: true, tickets: tickets }.to_json
end


text:
module.exports = {
    API_NAME: "YourNamespaceComponent"
};

redpajama_set_name: RedPajamaGithub


text:
void setUp(void)
{
}

void tearDown(void)
{
}

//helper functions
void list_count_is(int count, allergen_list_t * list)
{
   TEST_ASSERT_EQUAL(count, list->count);
}

void list_contains(allergen_t allergen, allergen_list_t * list)
{
   bool allergen_found = false;

   for (int i = 0; i < list->count; i++) {
      if (list->allergens[i] == allergen) {
         allergen_found = true;
         break;
      }
   }

   TEST_ASSERT_TRUE(allergen_found);
}

//Tests start here
void test_no_allergies_means_not_allergic(void)
{
   int score = 0;

   TEST_ASSERT_FALSE(is_allergic_to(ALLERGEN_PEANUTS, score));
   TEST_ASSERT_FALSE(is_allergic_to(ALLERGEN_CATS, score));
   TEST_ASSERT_FALSE(is_allergic_to(ALLERGEN_STRAWBERRIES, score));
}

void test_is_allergic_to_eggs(void)
{
   TEST_IGNORE();               // delete this line to run test
   int score = 1;

   TEST_ASSERT_TRUE(is_allergic_to(ALLERGEN_EGGS, score));
}

void test_is_allergic_to_eggs_in_addition_to_other_stuff(void)
{
   TEST_IGNORE();
   int score = 5;

   TEST_ASSERT_TRUE(is_allergic_to(ALLERGEN_EGGS, score));
   TEST_ASSERT_TRUE(is_allergic_to(ALLERGEN_SHELLFISH, score));
   TEST_ASSERT_FALSE(is_allergic_to(ALLERGEN_STRAWBERRIES, score));
}

void test_no_allergies_at_all(void)
{
   TEST_IGNORE();
   int score = 0;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(0, &list);

   free(list.allergens);
}

void test_allergic_to_just_eggs(void)
{
   TEST_IGNORE();
   int score = 1;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(1, &list);
   list_contains(ALLERGEN_EGGS, &list);

   free(list.allergens);
}

void test_allergic_to_just_peanuts(void)
{
   TEST_IGNORE();
   int score = 2;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(1, &list);
   list_contains(ALLERGEN_PEANUTS, &list);

   free(list.allergens);
}

void test_allergic_to_just_strawberries(void)
{
   TEST_IGNORE();
   int score = 8;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(1, &list);
   list_contains(ALLERGEN_STRAWBERRIES, &list);

   free(list.allergens);
}

void test_allergic_to_eggs_and_peanuts(void)
{
   TEST_IGNORE();
   int score = 3;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(2, &list);
   list_contains(ALLERGEN_EGGS, &list);
   list_contains(ALLERGEN_PEANUTS, &list);

   free(list.allergens);
}

void test_allergic_to_more_than_eggs_but_not_peanuts(void)
{
   TEST_IGNORE();
   int score = 5;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(2, &list);
   list_contains(ALLERGEN_EGGS, &list);
   list_contains(ALLERGEN_SHELLFISH, &list);

   free(list.allergens);
}

void test_allergic_to_lots_of_stuff(void)
{
   TEST_IGNORE();
   int score = 248;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(5, &list);
   list_contains(ALLERGEN_STRAWBERRIES, &list);
   list_contains(ALLERGEN_TOMATOES, &list);
   list_contains(ALLERGEN_CHOCOLATE, &list);
   list_contains(ALLERGEN_POLLEN, &list);
   list_contains(ALLERGEN_CATS, &list);

   free(list.allergens);
}

void test_allergic_to_everything(void)
{
   TEST_IGNORE();
   int score = 255;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(8, &list);
   list_contains(ALLERGEN_EGGS, &list);
   list_contains(ALLERGEN_PEANUTS, &list);
   list_contains(ALLERGEN_SHELLFISH, &list);
   list_contains(ALLERGEN_STRAWBERRIES, &list);
   list_contains(ALLERGEN_TOMATOES, &list);
   list_contains(ALLERGEN_CHOCOLATE, &list);
   list_contains(ALLERGEN_POLLEN, &list);
   list_contains(ALLERGEN_CATS, &list);

   free(list.allergens);
}

void test_ignore_non_allergen_score_parts(void)
{
   TEST_IGNORE();
   int score = 509;
   allergen_list_t list;

   get_allergens(score, &list);

   list_count_is(7, &list);
   list_contains(ALLERGEN_EGGS, &list);
   list_contains(ALLERGEN_SHELLFISH, &list);
   list_contains(ALLERGEN_STRAWBERRIES, &list);
   list_contains(ALLERGEN_TOMATOES, &list);
   list_contains(ALLERGEN_CHOCOLATE, &list);
   list_contains(ALLERGEN_POLLEN, &list);
   list_contains(ALLERGEN_CATS, &list);

   free(list.allergens);
}

int main(void)
{
   UnityBegin("test/test_allergies.c");

   RUN_TEST(test_no_allergies_means_not_allergic);
   RUN_TEST(test_is_allergic_to_eggs);
   RUN_TEST(test_is_allergic_to_eggs_in_addition_to_other_stuff);
   RUN_TEST(test_no_allergies_at_all);
   RUN_TEST(test_allergic_to_just_eggs);
   RUN_TEST(test_allergic_to_just_peanuts);
   RUN_TEST(test_allergic_to_just_strawberries);
   RUN_TEST(test_allergic_to_eggs_and_peanuts);
   RUN_TEST(test_allergic_to_more_than_eggs_but_not_peanuts);
   RUN_TEST(test_allergic_to_lots_of_stuff);
   RUN_TEST(test_allergic_to_everything);
   RUN_TEST(test_ignore_non_allergen_score_parts);

   UnityEnd();
   return 0;
}


text:
from unittest import TestCase
from unittest import SkipTest
from chatterbot.adapters.storage import MongoDatabaseAdapter
from chatterbot.conversation import Statement

class BaseMongoDatabaseAdapterTestCase(TestCase):

    def setUp(self):
        """
        Instantiate the adapter.
        """
        from pymongo.errors import ServerSelectionTimeoutError
        from pymongo import MongoClient

        database_name = "test_db"

        # Skip these tests if a mongo client is not running.
        try:
            client = MongoClient(
                serverSelectionTimeoutMS=1
            )
            client.server_info()

            self.adapter = MongoDatabaseAdapter(database=database_name)

        except ServerSelectionTimeoutError:
            raise SkipTest("Unable to connect to mongo database.")

    def tearDown(self):
        """
        Remove the test database.
        """
        self.adapter.drop()

class JsonDatabaseAdapterTestCase(BaseMongoDatabaseAdapterTestCase):

    def test_count_returns_zero(self):
        """
        The count method should return a value of 0
        when nothing has been saved to the database.
        """
        self.assertEqual(self.adapter.count(), 0)

    def test_count_returns_value(self):
        """
        The count method should return a value of 1
        when one item has been saved to the database.
        """
        statement = Statement("Test statement")
        self.adapter.update(statement)
        self.assertEqual(self.adapter.count(), 1)

    def test_statement_not_found(self):
        """
        Test that None is returned by the find method
        when a matching statement is not found.
        """
        self.assertEqual(self.adapter.find("Non-existant"), None)

    def test_statement_found(self):
        """
        Test that a matching statement is returned
        when it exists in the database.
        """
        statement = Statement("New statement")
        self.adapter.update(statement)

        found_statement = self.adapter.find("New statement")
        self.assertNotEqual(found_statement, None)
        self.assertEqual(found_statement.text, statement.text)

    def test_update_adds_new_statement(self):
        statement = Statement("New statement")
        self.adapter.update(statement)

        statement_found = self.adapter.find("New statement")
        self.assertNotEqual(statement_found, None)
        self.assertEqual(statement_found.text, statement.text)

    def test_update_modifies_existing_statement(self):
        statement = Statement("New statement")
        self.adapter.update(statement)

        # Check the initial values
        found_statement = self.adapter.find(statement.text)
        self.assertEqual(found_statement.occurrence, 1)

        # Update the statement value
        statement.update_occurrence_count()
        self.adapter.update(statement)

        # CHeck that the values have changed
        found_statement = self.adapter.find(statement.text)
        self.assertEqual(found_statement.occurrence, 2)

    def test_get_random_returns_statement(self):
        statement = Statement("New statement")
        self.adapter.update(statement)

        random_statement = self.adapter.get_random()
        self.assertEqual(random_statement.text, statement.text)

    def test_find_returns_nested_responces(self):
        response_list = [
            "Yes", "No"
        ]
        statement = Statement(
            "Do you like this?",
            in_response_to=response_list
        )
        self.adapter.update(statement)

        result = self.adapter.find(statement.text)

        self.assertIn("Yes", result.in_response_to)
        self.assertIn("No", result.in_response_to)

    def test_filter_no_results(self):
        statement1 = Statement(
            "Testing...",
            occurrence=4
        )
        self.adapter.update(statement1)

        results = self.adapter.filter(occurrence=100)
        self.assertEqual(len(results), 0)

    def test_filter_equal_result(self):
        statement1 = Statement(
            "Testing...",
            occurrence=22
        )
        statement2 = Statement(
            "Testing one, two, three.",
            occurrence=1
        )
        self.adapter.update(statement1)
        self.adapter.update(statement2)

        results = self.adapter.filter(occurrence=22)
        self.assertEqual(len(results), 1)
        self.assertIn(statement1, results)

    def test_filter_equal_multiple_results(self):
        statement1 = Statement(
            "Testing...",
            occurrence=6
        )
        statement2 = Statement(
            "Testing one, two, three.",
            occurrence=1
        )
        statement3 = Statement(
            "Test statement.",
            occurrence=6
        )
        self.adapter.update(statement1)
        self.adapter.update(statement2)
        self.adapter.update(statement3)

        results = self.adapter.filter(occurrence=6)
        self.assertEqual(len(results), 2)
        self.assertIn(statement1, results)
        self.assertIn(statement3, results)

    def test_filter_contains_result(self):
        statement1 = Statement(
            "Testing...",
            in_response_to=[
                "What are you doing?"
            ]
        )
        statement2 = Statement(
            "Testing one, two, three.",
            in_response_to=[
                "Testing..."
            ]
        )
        self.adapter.update(statement1)
        self.adapter.update(statement2)

        results = self.adapter.filter(
            in_response_to__contains="What are you doing?"
        )
        self.assertEqual(len(results), 1)
        self.assertIn(statement1, results)

    def test_filter_contains_no_result(self):
        statement1 = Statement(
            "Testing...",
            in_response_to=[
                "What are you doing?"
            ]
        )
        self.adapter.update(statement1)

        results = self.adapter.filter(
            in_response_to__contains="How do you do?"
        )
        self.assertEqual(len(results), 0)

    def test_filter_multiple_parameters(self):
        statement1 = Statement(
            "Testing...",
            occurrence=6,
            in_response_to=[
                "Why are you counting?"
            ]
        )
        statement2 = Statement(
            "Testing one, two, three.",
            occurrence=6,
            in_response_to=[
                "Testing..."
            ]
        )
        self.adapter.update(statement1)
        self.adapter.update(statement2)

        results = self.adapter.filter(
            occurrence=6,
            in_response_to__contains="Why are you counting?"
        )

        self.assertEqual(len(results), 1)
        self.assertIn(statement1, results)

    def test_filter_multiple_parameters_no_results(self):
        statement1 = Statement(
            "Testing...",
            occurrence=6,
            in_response_to=[
                "Why are you counting?"
            ]
        )
        statement2 = Statement(
            "Testing one, two, three.",
            occurrence=1,
            in_response_to=[
                "Testing..."
            ]
        )
        self.adapter.update(statement1)
        self.adapter.update(statement2)

        results = self.adapter.filter(
            occurrence=6,
            in_response_to__contains="Testing..."
        )

        self.assertEqual(len(results), 0)

    def test_filter_no_parameters(self):
        """
        If not parameters are provided to the filter,
        then all statements should be returned.
        """
        statement1 = Statement("Testing...")
        statement2 = Statement("Testing one, two, three.")
        self.adapter.update(statement1)
        self.adapter.update(statement2)

        results = self.adapter.filter()

        self.assertEqual(len(results), 2)

class ReadOnlyMongoDatabaseAdapterTestCase(BaseMongoDatabaseAdapterTestCase):

    def test_update_does_not_add_new_statement(self):
        self.adapter.read_only = True

        statement = Statement("New statement")
        self.adapter.update(statement)

        statement_found = self.adapter.find("New statement")
        self.assertEqual(statement_found, None)

    def test_update_does_not_modify_existing_statement(self):
        statement = Statement("New statement")
        self.adapter.update(statement)

        self.adapter.read_only = True

        statement.update_occurrence_count()
        self.adapter.update(statement)

        statement_found = self.adapter.find("New statement")
        self.assertEqual(statement_found.text, statement.text)
        self.assertEqual(statement.occurrence, 2)
        self.assertEqual(statement_found.occurrence, 1)


text:
module MakeFlaggable
  module Flagger
    extend ActiveSupport::Concern

    included do
      has_many :flaggings, :class_name => "MakeFlaggable::Flagging", :as => :flagger, :dependent => :destroy
    end

    module ClassMethods
      def flagger?
        true
      end

      # Returns flaggers who have flagged any resource
      # If +flag_type+ is not set, returns flaggers of all resources
      # takes flaggable_klass as an argument
      def flaggers(flag_type = nil)
        res = select("#{self.table_name}.*").joins(:flaggings).group("#{self.table_name}.id")

        flag_type ? res.where('flaggings.flaggable_type LIKE ?', flag_type.to_s) : res
      end
    end

    # Flag a +flaggable+ using the provided +reason+.
    # Raises an +AlreadyFlaggedError+ if the flagger already flagged the flaggable and +:flag_once+ option is set.
    # Raises an +InvalidFlaggableError+ if the flaggable is not a valid flaggable.
    def flag!(flaggable, reason = nil)
      check_flaggable(flaggable)

      if (flaggable_options[:flag_once] && fetch_flaggings(flaggable).try(:first))
        raise MakeFlaggable::Exceptions::AlreadyFlaggedError.new
      end

      Flagging.create(:flaggable => flaggable, :flagger => self, :reason => reason)
    end

    # Flag the +flaggable+, but don't raise an error if the flaggable was already flagged and +:flag_once+ was set.
    # If +:flag_once+ was not set then this method behaves like +flag!+.
    # The flagging is simply ignored then.
    def flag(flaggable, reason = nil)
      begin
        flag!(flaggable, reason)
      rescue Exceptions::AlreadyFlaggedError
      end
    end

    def unflag!(flaggable, reason = nil)
      check_flaggable(flaggable)

      flaggings = fetch_flaggings(flaggable, reason)

      raise Exceptions::NotFlaggedError if flaggings.empty?

      flaggings.destroy_all

      true
    end

    def unflag(flaggable, reason = nil)
      begin
        unflag!(flaggable, reason = nil)
        success = true
      rescue Exceptions::NotFlaggedError
        success = false
      end
      success
    end

    def flagged?(flaggable, reason = nil)
      check_flaggable(flaggable)

      fetch_flaggings(flaggable, reason).try(:first) ? true : false
    end

    private

    def fetch_flaggings(flaggable, reason = nil)
      flagger_flaggins = flaggings.where({
		:flaggable => flaggable
      })
      reason ? flagger_flaggins.where(:reason => reason) : flagger_flaggins
    end

    def check_flaggable(flaggable)
      raise Exceptions::InvalidFlaggableError unless flaggable.class.flaggable?
    end
  end
end


text:
package de.taimos.dvalin.interconnect.model.metamodel.defs;

import de.taimos.dvalin.interconnect.model.metamodel.IGeneratorDefinition;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.BigDecimalMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.BooleanMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.CollectionMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.DateMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.EnumMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.ImplementsDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.IntegerMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.LocalDateMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.LocalTimeMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.LongMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.MapMemberDef;
import de.taimos.dvalin.interconnect.model.metamodel.memberdef.StringMemberDef;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

/**
 * @author psigloch
 */
@XmlRootElement(name = "event")
public class EventDef implements IGeneratorDefinition {
    private String comment;
    private String name;
    private String removalDate;
    private List<Object> children;
    private Integer version;
    private Integer compatibleBaseVersion;
    private String pkgName;
    private String author;
    private String parentName;
    private Integer parentVersion;
    private String parentPkgName;
    private String domain;

    /**
     * @return the comment
     */
    @XmlAttribute(required = true)
    public String getComment() {
        return this.comment;
    }

    /**
     * @param comment the comment to set
     */
    public void setComment(String comment) {
        this.comment = comment;
    }

    /**
     * @return the name
     */
    @XmlAttribute(required = true)
    public String getName() {
        return this.name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the removalDate
     */
    @XmlAttribute
    public String getRemovalDate() {
        return this.removalDate;
    }

    /**
     * @param removalDate the removalDate to set
     */
    public void setRemovalDate(String removalDate) {
        this.removalDate = removalDate;
    }

    /**
     * @return the children
     */
    @XmlElements({//
        @XmlElement(name = "integer", type = IntegerMemberDef.class), //
        @XmlElement(name = "implements", type = ImplementsDef.class), //
        @XmlElement(name = "decimal", type = BigDecimalMemberDef.class), //
        @XmlElement(name = "boolean", type = BooleanMemberDef.class), //
        @XmlElement(name = "date", type = DateMemberDef.class), //
        @XmlElement(name = "enum", type = EnumMemberDef.class), //
        @XmlElement(name = "long", type = LongMemberDef.class), //
        @XmlElement(name = "string", type = StringMemberDef.class), //
        @XmlElement(name = "map", type = MapMemberDef.class), //
        @XmlElement(name = "collection", type = CollectionMemberDef.class), //
        @XmlElement(name = "localDate", type = LocalDateMemberDef.class), //
        @XmlElement(name = "localTime", type = LocalTimeMemberDef.class)})
    public List<Object> getChildren() {
        return this.children;
    }

    /**
     * @param children the children to set
     */
    public void setChildren(List<Object> children) {
        this.children = children;
    }

    @Override
    public String getPackageName() {
        return this.getPkgName();
    }

    /**
     * @return the version
     */
    @XmlAttribute(required = true)
    public Integer getVersion() {
        return this.version;
    }

    /**
     * @param version the version to set
     */
    public void setVersion(Integer version) {
        this.version = version;
    }

    /**
     * @return the compatibleBaseVersion
     */
    @XmlAttribute
    public Integer getCompatibleBaseVersion() {
        return this.compatibleBaseVersion;
    }

    /**
     * @param compatibleBaseVersion the compatibleBaseVersion to set
     */
    public void setCompatibleBaseVersion(Integer compatibleBaseVersion) {
        this.compatibleBaseVersion = compatibleBaseVersion;
    }

    /**
     * @return the pkgName
     */
    @XmlAttribute(required = true)
    public String getPkgName() {
        return this.pkgName;
    }

    /**
     * @param pkgName the pkgName to set
     */
    public void setPkgName(String pkgName) {
        this.pkgName = pkgName;
    }

    /**
     * @return the author
     */
    @XmlAttribute(required = true)
    public String getAuthor() {
        return this.author;
    }

    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }

    /**
     * @return the domain
     */
    @XmlAttribute(required = true)
    public String getDomain() {
        return this.domain;
    }

    /**
     * @param domain the domain to set
     */
    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     * @return the parentName
     */
    @XmlAttribute
    public String getParentName() {
        return this.parentName;
    }

    /**
     * @param parentName the parentName to set
     */
    public void setParentName(String parentName) {
        this.parentName = parentName;
    }

    /**
     * @return the parentVersion
     */
    @XmlAttribute
    public Integer getParentVersion() {
        return this.parentVersion;
    }

    /**
     * @param parentVersion the parentVersion to set
     */
    public void setParentVersion(Integer parentVersion) {
        this.parentVersion = parentVersion;
    }

    /**
     * @return the parentPkgName
     */
    @XmlAttribute
    public String getParentPkgName() {
        return this.parentPkgName;
    }

    /**
     * @param parentPkgName the parentPkgName to set
     */
    public void setParentPkgName(String parentPkgName) {
        this.parentPkgName = parentPkgName;
    }
}


text:
package fun.docker.sample.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class Hello {

    private String        name;
    private String        location;
    private LocalDate     birthDate;
    private LocalDateTime now;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }

    public LocalDateTime getNow() {
        return now;
    }

    public void setNow(LocalDateTime now) {
        this.now = now;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (!(o instanceof Hello)) return false;

        Hello hello = (Hello) o;

        return new EqualsBuilder()
                .append(name, hello.name)
                .append(location, hello.location)
                .append(birthDate, hello.birthDate)
                .append(now, hello.now)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(name)
                .append(location)
                .append(birthDate)
                .append(now)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("name", name)
                .append("location", location)
                .append("birthDate", birthDate)
                .append("now", now)
                .toString();
    }
}


text:
module Atmosphere
  module NicProvider
    class NullNicProvider
      def initialize(_config = nil); end

      def get(_appl)
        nil
      end
    end
  end
end


text:
<?php

/**
 * @file
 * Contains \Drupal\custom_block\CustomBlockTypeListController.
 */

namespace Drupal\custom_block;

use Drupal\Core\Config\Entity\ConfigEntityListController;
use Drupal\Core\Entity\EntityInterface;

/**
 * Provides a listing of custom block types.
 */
class CustomBlockTypeListController extends ConfigEntityListController {

  /**
   * {@inheritdoc}
   */
  public function getOperations(EntityInterface $entity) {
    $operations = parent::getOperations($entity);
    // Place the edit operation after the operations added by field_ui.module
    // which have the weights 15, 20, 25.
    if (isset($operations['edit'])) {
      $operations['edit']['weight'] = 30;
    }
    return $operations;
  }

  /**
   * Overrides \Drupal\Core\Entity\EntityListController::buildHeader().
   */
  public function buildHeader() {
    $header['type'] = t('Block type');
    $header['description'] = t('Description');
    return $header + parent::buildHeader();
  }

  /**
   * Overrides \Drupal\Core\Entity\EntityListController::buildRow().
   */
  public function buildRow(EntityInterface $entity) {
    $uri = $entity->uri();
    $row['type'] = l($entity->label(), $uri['path'], $uri['options']);
    $row['description'] = filter_xss_admin($entity->description);
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    // @todo Remove this once https://drupal.org/node/2032535 is in.
    drupal_set_title(t('Custom block types'));
    return parent::render();
  }

}


text:
var ok = require('assert').ok;
var strictEqual = require('assert').strictEqual;
var startsWith = require('../startsWith');

test('#startsWith', function() {
  ok(startsWith('foobar', 'foo'), 'foobar starts with foo');
  ok(!startsWith('oobar', 'foo'), 'oobar does not start with foo');
  ok(startsWith('oobar', 'o'), 'oobar starts with o');
  ok(startsWith(12345, 123), '12345 starts with 123');
  ok(!startsWith(2345, 123), '2345 does not start with 123');
  ok(startsWith('', ''), 'empty string starts with empty string');
  ok(startsWith(null, ''), 'null starts with empty string');
  ok(!startsWith(null, 'foo'), 'null starts with foo');
  ok(startsWith('-foobar', 'foo', 1), 'foobar starts with foo at position 1');
  ok(startsWith('foobar', 'foo', 0), 'foobar starts with foo at position 0');
  ok(!startsWith('foobar', 'foo', 1), 'foobar starts not with foo at position 1');
  ok(startsWith('Äpfel', 'Ä'), 'string starts with a unicode');

  strictEqual(startsWith('hello', 'hell'), true);
  strictEqual(startsWith('HELLO', 'HELL'), true);
  strictEqual(startsWith('HELLO', 'hell'), false);
  strictEqual(startsWith('HELLO', 'hell'), false);
  strictEqual(startsWith('hello', 'hell', 0), true);
  strictEqual(startsWith('HELLO', 'HELL', 0), true);
  strictEqual(startsWith('HELLO', 'hell', 0), false);
  strictEqual(startsWith('HELLO', 'hell', 0), false);
  strictEqual(startsWith('HELLO'), false);
  strictEqual(startsWith('undefined'), true);
  strictEqual(startsWith('null', null), true);
  strictEqual(startsWith('hello', 'hell', -20), true);
  strictEqual(startsWith('hello', 'hell', 1), false);
  strictEqual(startsWith('hello', 'hell', 2), false);
  strictEqual(startsWith('hello', 'hell', 3), false);
  strictEqual(startsWith('hello', 'hell', 4), false);
  strictEqual(startsWith('hello', 'hell', 5), false);
  strictEqual(startsWith('hello', 'hell', 20), false);
});


text:
title: Punga Cove

listing-type: accommodation
island: south
region: marlborough
destination: Marlborough Sounds
sub-region: Marlborough Sounds

order: c
image-path: punga-cove-resort.jpg
image-alt: Punga Cove
refer-url: http://www.pungacove.co.nz/
---
Nestled amongst native bush in remote Queen Charlotte Sound, offering a range of accommodation including chalets, luxury apartments and budget lodgings.


text:
using System;

namespace MenuBuddy
{
	public interface ITree<T> : ILayout, IStackLayout, IBackgroundable, ITransitionable
	{
		event EventHandler<SelectionChangeEventArgs<T>> OnSelectedItemChange;

		T SelectedItem { get; set; }

		TreeItem<T> SelectedTreeItem { set; }

		StackLayout Stack
		{
			get;
		}
	}
}


text:
namespace NbuReservationSystem.Services.Web
{
    using System;

    using NbuReservationSystem.Web.Models.Requests.Reservations;
    using NbuReservationSystem.Web.Models.Responses.Reservations;

    public interface IReservationsService
    {
        MonthlyReservationsViewModel GetReservations(int year, int month, int hallId);

        DayViewModel GetReservations(DateTime date, int hallId);

        int AddReservations(ReservationViewModel reservationViewModel, string ip);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.gradle.api.plugins.antlr (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style">

org.gradle.api.plugins.antlr

Interfaces

AntlrSourceVirtualDirectory

Classes

AntlrPlugin

AntlrTask


text:
\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{tikz}
\usepackage{enumerate}
\usetikzlibrary{arrows,automata,shapes}
\tikzstyle{block} = [rectangle, draw, fill=blue!20,
    text width=5em, text centered, rounded corners, minimum height=2em]
\tikzstyle{bt} = [rectangle, draw, fill=blue!20,
    text width=4em, text centered, rounded corners, minimum height=2em]

\newtheorem{defn}{Definition}
\newtheorem{crit}{Criterion}

\newcommand{\handout}[5]{
  \noindent
  \begin{center}
  \framebox{
    \vbox{
      \hbox to 5.78in { {\bf Software Testing, Quality Assurance and Maintenance } \hfill #2 }
      \vspace{4mm}
      \hbox to 5.78in { {\Large \hfill #5  \hfill} }
      \vspace{2mm}
      \hbox to 5.78in { {\em #3 \hfill #4} }
    }
  }
  \end{center}
  \vspace*{4mm}
}

\newcommand{\lecture}[4]{\handout{#1}{#2}{#3}{#4}{Lecture #1}}
% 1-inch margins, from fullpage.sty by H.Partl, Version 2, Dec. 15, 1988.
\topmargin 0pt
\advance \topmargin by -\headheight
\advance \topmargin by -\headsep
\textheight 8.9in
\oddsidemargin 0pt
\evensidemargin \oddsidemargin
\marginparwidth 0.5in
\textwidth 6.5in

\parindent 0in
\parskip 1.5ex
%\renewcommand{\baselinestretch}{1.25}

% http://gurmeet.net/2008/09/20/latex-tips-n-tricks-for-conference-papers/
\newcommand{\squishlist}{
 \begin{list}{$\bullet$}
  { \setlength{\itemsep}{0pt}
     \setlength{\parsep}{3pt}
     \setlength{\topsep}{3pt}
     \setlength{\partopsep}{0pt}
     \setlength{\leftmargin}{1.5em}
     \setlength{\labelwidth}{1em}
     \setlength{\labelsep}{0.5em} } }
\newcommand{\squishlisttwo}{
 \begin{list}{$\bullet$}
  { \setlength{\itemsep}{0pt}
     \setlength{\parsep}{0pt}
    \setlength{\topsep}{0pt}
    \setlength{\partopsep}{0pt}
    \setlength{\leftmargin}{2em}
    \setlength{\labelwidth}{1.5em}
    \setlength{\labelsep}{0.5em} } }
\newcommand{\squishend}{
  \end{list}  }

\lstset{numbers=left,numberstyle=\scriptsize,basicstyle=\ttfamily}
\begin{document}

\lecture{9 --- January 23, 2015}{Winter 2015}{Patrick Lam}{version 1}

\section*{Graph Coverage for Source Code}

So far, we've seen a number of coverage criteria for
graphs, but I've been vague about how to actually
construct graphs. For the most part, it's fairly obvious.

%Let's see formal definitions. Remember that we first defined
%the structural criteria: NC, EC, EPC, PPC, SPC, CPC.
%{\sf (Why are ADC, AUC, ADUPC, CRTC, SRTC inapplicable?)}\\[1em]

\subsection*{Structural Graph Coverage for Source Code}

Fundamental graph for source code: \emph{Control-Flow Graph} (CFG).

\begin{itemize}
\item CFG nodes: zero or more statements;
\item CFG edges: an edge $(s_1, s_2)$ indicates that $s_1$ may
  be followed by $s_2$ in an execution.
\end{itemize}

\paragraph{Basic Blocks.} We can simplify a CFG by grouping together
statements which always execute together (in sequential programs):

\begin{tabular}{ll}
\begin{minipage}{.4\textwidth}
\begin{lstlisting}
    x = 5
    z = 2
q0: if (z < 17) goto q1
    z = z + 1
    print (x)
    goto q0
q1: nop
\end{lstlisting}
\end{minipage} &
\begin{minipage}{.5\textwidth}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (L1-2)};
  \node[bt]           (2) [below of=1] {2 (L3)};
  \node[bt]           (3) [below left of=2,yshift=-1em] {3 (L4-6)};
  \node[bt]           (4) [below right of=3] {4 (L7)};

  \path (1) edge node {} (2)
        (2) edge node[left] {F} (3)
            edge [bend left] node {T} (4)
        (3) edge [bend left] node {} (2.west);
\end{tikzpicture}
\end{center}

\end{minipage}
\end{tabular}

We use the following definition:
\begin{defn}
A basic block has one entry point and one exit point.
\end{defn}
Note that a basic block may have multiple successors. However, there
may not be any jumps into the middle of a basic block (which is
why statement {\tt l0} has its own basic block.)

\subsection*{Some Examples} We'll now see how to construct
control-flow graph fragments for various program constructs.

{\bf if statements:} The book puts the conditions
(and hence uses) on the control-flow edges, rather than in the
{\tt if} node. I prefer putting the condition in the node.

\begin{tabular}{ll|ll}
\begin{minipage}{.15\textwidth}
\begin{lstlisting}
if (z < 17)
  print (x);
else
  print (y);
\end{lstlisting}
\end{minipage} &
\begin{minipage}{.3\textwidth}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (L1)};
  \node[bt]           (2) [below left of=1,yshift=-0.5em] {2 (L2)};
  \node[bt]           (3) [below right of=1,yshift=-0.5em] {3 (L4)};
  \node[bt]           (4) [below left of=3] {4};

  \path (1) edge node[left] {\tiny T} (2)
        (1) edge node[right] {\tiny F} (3)
        (2) edge node {} (4)
        (3) edge node {} (4);
\end{tikzpicture}
\end{center}
\end{minipage}&
\begin{minipage}{.3\textwidth}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (L1)};
  \node[bt]           (2) [below left of=1,yshift=-0.5em] {2 (L2)};
  \node[bt]           (4) [below left of=3] {3};

  \path (1) edge node[left] {\tiny T} (2)
        (1) edge node[right] {\tiny F} (4)
        (2) edge node {} (4);
\end{tikzpicture}
\end{center}
\end{minipage}
& \begin{minipage}{.1\textwidth}
\begin{lstlisting}
if (z < 17)
  print(x);
\end{lstlisting}
\end{minipage}
\end{tabular}

Short-circuit {\tt if} evaluation is more complicated; I recommend working it out yourself.

(Recall that node coverage does not imply edge coverage.)

{\bf case / switch statements:}

\begin{tabular}{ll}
\begin{minipage}{.45\textwidth}
\begin{lstlisting}
switch (n) {
  case `I': ...; break;
  case `J': ...; /* fall thru */
  case `K': ...; break;
}
// ...
\end{lstlisting}
\end{minipage} &
\begin{minipage}{.4\textwidth}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (L1)};
  \node[bt, text width=3em]           (2) [below left of=1,xshift=-2em,yshift=-1em]  {2 (L2)};
  \node[bt, text width=3em]           (3) [below of=1]   {3 (L3)};
  \node[bt, text width=3em]           (4) [below right of=1,xshift=2em,yshift=-1em]   {4 (L4)};
  \node[bt, text width=3em]           (5) [below of=2]  {5 (L2')};
  \node[bt, text width=3em]           (6) [below of=3]  {6 (L3')};
  \node[bt, text width=3em]           (7) [below of=4]  {7 (L4')};
  \node[bt, text width=3em]           (8) [below of=6]  {8 (L6)};

  \path
  (1) edge node[left,yshift=0.7em] {i} (2)
  (1) edge node {j} (3)
  (1) edge node {k} (4)
  (2) edge node {} (5)
  (3) edge node {} (6)
  (4) edge node {} (7)
  (6) edge node {} (7)
  (5) edge node {} (8)
  (7) edge node {} (8);
\end{tikzpicture}
\end{center}
\end{minipage}
\end{tabular}

{\bf while statements:}

\begin{tabular}{ll}
\begin{minipage}{.2\textwidth}
\begin{lstlisting}
x = 0; y = 20;
while (x < y) {
  x ++; y --;
}
\end{lstlisting}
\end{minipage} &
\begin{minipage}{.4\textwidth}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (x = 0; y = 20)};
  \node[bt]           (2) [below of=1]        {2 (L2)};
  \node[bt]           (3) [below right of=2,xshift=1em]  {3 (L3)};
  \node[bt]           (4) [below of=2,yshift=-2em]   {4};

  \path (1) edge node {} (2)
  (2) edge [bend left] node {$x < y$} (3)
  (3) edge [bend left] node {} (2)
  (2) edge node[left] {$\neg (x < y)$} (4);
\end{tikzpicture}
\end{center}
\end{minipage}
\end{tabular}

Note that arbitrarily complicated structures may occur inside
the loop body.

{\bf for statements:}

\begin{tabular}{ll}
\begin{minipage}{.5\textwidth}
\begin{lstlisting}
for (int i = 0; i < 57; i++) {
  if (i % 3 == 0) {
    print (i);
  }
}
\end{lstlisting}
\end{minipage} & \begin{minipage}{.4\textwidth}
  (an exercise for the reader!)
\end{minipage}
\end{tabular}

\newpage
This example uses Java's enhanced for loops, which iterates over all of the elements
in the {\tt widgetList}:

\begin{lstlisting}[basicstyle=\scriptsize \ttfamily]
for (Widget w : widgetList) {
  decorate(w);
}
// ...
\end{lstlisting}

I will accept the simplified CFG or the more useful one on the right:

\begin{tabular}{ll}
\begin{minipage}{.4\textwidth}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt]   (1)                     {1 (L1)};
  \node[bt]           (3) [below right of=1,xshift=1em]  {2 (L2)};
  \node[bt]           (4) [below of=1,yshift=-2em]   {3 (L4)};

  \path
  (1) edge [bend left] node {$w \in \mbox{\tt widgetList}$} (3)
  (3) edge [bend left] node {} (1)
  (1) edge node[left] {} (4);
\end{tikzpicture}
\end{minipage} &
\begin{minipage}{.5\textwidth}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=1.5cm,
                    semithick,initial text=]

  \node[initial,bt,text width=8em]   (1)                     {it = wL.iterator()};
  \node[bt,text width=5.5em]            (2) [below of=1,yshift=.5em] {it.hasNext()};
  \node[bt,text width=7.5em]           (3) [below right of=2,xshift=2em,yshift=-.5em]  {w = it.next(); decorate(w);};
  \node[bt]           (4) [below of=2,yshift=-3em]   {3 (L4)};

  \path (1) edge node {} (2)
        (2) edge node[right] {\tiny T} (3)
        (3.north) edge [bend right] node {} (2.east)
        (2) edge node[left] {F} (4);
%  (1) edge [bend left] node {$w \in \mbox{\tt widgetList}$} (3)
%  (3) edge [bend left] node {} (1)
%  (1) edge node[left] {} (4);
\end{tikzpicture}
\end{minipage}
\end{tabular}

All of these graphs admit the notions of node coverage (statement
coverage, basic block coverage) and edge coverage (branch coverage).

\paragraph{Larger example.} You can draw a 7-node CFG for this program:

\begin{lstlisting}[basicstyle=\scriptsize\ttfamily]
  /** Binary search for target in sorted subarray a[low..high] */
  int binary_search(int[] a, int low, int high, int target) {
    while (low <= high) {
      int middle = low + (high-low)/2;
      if (target < a[middle)
        high = middle - 1;
      else if (target > a[middle])
        low = middle + 1;
      else
        return middle;
    }
    return -1; /* not found in a[low..high] */
  }
\end{lstlisting}

\vspace*{-2em}
\begin{center}
\begin{tikzpicture}[->,>=stealth',shorten >=1pt,auto,node distance=2cm,
                    semithick,initial text=]
  \node[initial,bt,text width=12em]   (1)                     {\verb+1. if (low <= high)+ (L3)};
  \node[bt, accepting,text width=10em]          (8) [below right of=1,yshift=-1em,xshift=3em]  {\verb+8. return middle+ (L12)};
  \node[bt]           (2) [below of=1, yshift=-4em]  {2 (L4--5)};
  \node[bt]           (4) [below left of=2] {4 (L6)};
  \node[bt]           (5) [below right of=2] {5 (L7)};
  \node[bt]           (6) [below left of=5] {6 (L9)};
  \node[bt,text width=12em,accepting,xshift=3em]           (7) [below right of=5] {\verb+7. return middle (L9)+};

  \path (1) edge node[left] {T} (2)
  (1) edge node[right,xshift=.5em] {F} (8)
  (2) edge node[left,xshift=-.5em] {T} (4)
  (2) edge node[right,xshift=.5em]{F} (5)
  (4.west) edge [bend left] (1)
  (5) edge node {T} (6)
  (5) edge node {F} (7)
  (6.south west) edge [bend left=80] (1);
\end{tikzpicture}
\end{center}

\newpage
\section*{Exercises}
Here are more exercise programs that you can draw CFGs for.
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily]
/* effects: if x==null, throw NullPointerException
            otherwise, return number of elements in x that are odd, positive or both. */
int oddOrPos(int[] x) {
  int count = 0;
  for (int i = 0; i < x.length; i++) {
    if (x[i]%2 == 1 || x[i] > 0) {
      count++;
    }
  }
  return count;
}

// example test case: input: x=[-3, -2, 0, 1, 4]; output: 3
\end{lstlisting}

Next, we have a really poorly-designed API (I'd give it a D at most,
maybe an F) because it's impossible to succinctly describe what it
does. {\bf Do not design functions with interfaces like this.} But we
can still draw a CFG, no matter how bad the code is.
\begin{lstlisting}[basicstyle=\scriptsize\ttfamily]
  /** Returns the mean of the first maxSize numbers in the array,
      if they are between min and max. Otherwise, skip the numbers. */
  double computeMean(int[] value, int maxSize, int min, int max) {
    int i, ti, tv, sum;

    i = 0; ti = 0; tv = 0; sum = 0;
    while (ti < maxSize) {
      ti++;
      if (value[i] >= min && value[i] <= max) {
        tv++;
        sum += value[i];
      }
      i++;
    }
    if (tv > 0)
      return (double)sum/tv;
    else
      throw new IllegalArgumentException();
  }
\end{lstlisting}

\end{document}


text:
shared_context 'users helper' do
  include_context 'database configuration'

  before(:each) do
    CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true)
  end

  before(:all) do
    @user1 = FactoryGirl.create(:valid_user, private_tables_enabled: true)
    @carto_user1 = Carto::User.find(@user1.id)
    @user2 = FactoryGirl.create(:valid_user, private_tables_enabled: true)
    @carto_user2 = Carto::User.find(@user2.id)
  end

  before(:each) do
    bypass_named_maps
    delete_user_data @user1
    delete_user_data @user2
  end

  after(:all) do
    bypass_named_maps
    @user1.destroy if @user1
    @user2.destroy if @user2
  end
end

shared_context 'user helper' do
  before(:all) do
    @user = FactoryGirl.create(:valid_user)
    @carto_user = Carto::User.find(@user.id)
  end

  after(:all) do
    bypass_named_maps
    @user.destroy
  end

  before(:each) do
    bypass_named_maps
    delete_user_data(@user)
  end
end


text:
(function($){

	module("methods");

	test("open", function(){
		expect(2);

		el = $("select").multiselect().multiselect("open");
			ok( el.multiselect("isOpen"), "isOpen parameter true" );
			equals( menu().css("display"), "block", "Test display CSS property" );
		el.multiselect("destroy");
	});

	test("close", function(){
		expect(2);

		el = $("select").multiselect().multiselect("open").multiselect("close");
			ok( !el.multiselect("isOpen"), "isOpen parameter false" );
			equals( menu().css("display"), "none", "Test display CSS property" );
		el.multiselect("destroy");
	});

	test("enable", function(){
		expect(2);

		el = $("select").multiselect().multiselect("disable").multiselect("enable");
			ok( !widget().is(":disabled"), "Widget is enabled" );
			ok( !el.is(":disabled"), "Original select is enabled" );
		el.multiselect("destroy");
	});

	test("disable", function(){
		expect(2);

	 	// clone this one so the original is not affected
		el = $("select").clone(true).insertAfter(body).multiselect().multiselect("disable");
			ok( widget().prev().is(":disabled"), 'Widget is disabled');
			ok( el.is(":disabled"), 'Original select is disabled');
		el.multiselect("destroy").remove();
	});

	test("widget", function(){
		expect(2);

		el = $("select").multiselect();
			ok( widget().is("div.ui-multiselect-menu"), 'Widget is the menu element');
			ok( widget().prev().is("button"), 'multiselect("button") is the button element');
		el.multiselect("destroy");
	});

	test("checkAll", function(){
		expect(1);

		el = $("select").multiselect().multiselect("checkAll");
		var inputs = menu().find("input");
			ok( inputs.filter(":checked").length === inputs.length, 'All inputs selected on the widget?');
		el.multiselect("destroy");
	});

	test("uncheckAll", function(){
		expect(1);

		el = $("select").multiselect().multiselect("checkAll").multiselect("uncheckAll");
			ok( menu().find("input:checked").length === 0, 'All inputs unchecked on the widget?');
		el.multiselect("destroy");
	});

	test("isOpen", function(){
		expect(2);

		el = $("select").multiselect().multiselect("open");
			ok( el.multiselect("isOpen"), 'Testing isOpen method after calling open method');
		el = $("select").multiselect("close");
			ok( !el.multiselect("isOpen"), 'Testing isOpen method after calling close method');
		el.multiselect("destroy");
	});

	test("destroy", function(){
		expect(2);

		el = $("select").multiselect().multiselect("destroy");
			ok( !$(".ui-multiselect").length , 'button.ui-multiselect removed from the DOM');
			ok( !el.data("multiselect") , 'no more multiselect obj attached to elem');
	});

	test("getChecked", function(){
		expect(2);

		el = $("select").multiselect().multiselect("checkAll");
			equals( el.multiselect("getChecked").length, 7, 'number of checkboxes returned after checking all and calling getChecked');
		el.multiselect("uncheckAll");
			equals( el.multiselect("getChecked").length, 0, 'number of checkboxes returned after unchecking all and calling getChecked');
		el.multiselect("destroy");
	});

	test("refresh", function(){
		expect(4);

		el = $("select").clone().appendTo(body).multiselect();
		el.empty().html('<option value="foo">foo</option><option value="bar">bar</option>');
		el.multiselect('refresh');

		var checkboxes, getCheckboxes = (function hai(){
			checkboxes = menu().find('input[type="checkbox"]');
			return hai;
		})();

		equals( checkboxes.length, 2, "After clearing the select, adding 2 options, and refresh(), only 2 checkboxes exist");
		equals( checkboxes.eq(0).val(), 'foo', 'first is foo' );
		equals( checkboxes.eq(1).val(), 'bar', 'second is foo' );

		// add one more w/ append, just for safety's sake
		el.append('<option value="baz">baz</option>');
		el.multiselect('refresh');
		getCheckboxes();
		equals( checkboxes.eq(2).val(), 'baz', 'after an append() call, the third option is now' );

		el.multiselect("destroy").remove();
	});
})(jQuery);


text:
@protocol SRWebSocketDelegate;

@protocol SRWebSocketProtocol <NSObject>

- (NSInteger)readyState;

- (void)open;

- (void)close;
- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;

// Send a UTF8 String or Data.
- (void)send:(id)data;

-(id<SRWebSocketDelegate>)delegate;
-(void)setDelegate:(id<SRWebSocketDelegate>)value;

@end


text:
package org.apache.ambari.server.checks;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.controller.PrereqCheckRequest;
import org.apache.ambari.server.orm.models.HostComponentSummary;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.ComponentInfo;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.MaintenanceState;
import org.apache.ambari.server.state.Service;
import org.apache.ambari.server.state.ServiceComponent;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.State;
import org.apache.ambari.server.state.stack.PrereqCheckStatus;
import org.apache.ambari.server.state.stack.PrerequisiteCheck;
import org.apache.ambari.server.state.stack.upgrade.UpgradeType;
import org.apache.commons.lang.StringUtils;

import com.google.inject.Singleton;

/**
 * The {@link ServicesUpCheck} class is used to ensure that services are up
 * "enough" before an upgrade begins. This class uses the following rules:
 *

 *
If the component is a CLIENT, it will skip it

 *
If the component is a MASTER then it must be online and not in MM

 *
If the component is a SLAVE
 *

 *
If the cardinality is 1+, then determine if {@value #SLAVE_THRESHOLD} %
 * are running. Hosts in MM are counted as being "up" since they are not part of
 * the upgrade.

 *
If the cardinality is 0, then all instances must be online. Hosts in MM
 * are counted as being "up" since they are not part of the upgrade.

 *

 *

 * It seems counter-intuitive to have a liveliness check which allows a
 * percentage of the slaves to be down. The goal is to be able to start an
 * upgrade, even if some slave components on healthy hosts are down. We still
 * want hosts to be scehdule for upgrade of their other components.
 */
@Singleton
@UpgradeCheck(
    group = UpgradeCheckGroup.LIVELINESS,
    order = 2.0f,
    required = { UpgradeType.ROLLING, UpgradeType.NON_ROLLING, UpgradeType.HOST_ORDERED })
public class ServicesUpCheck extends AbstractCheckDescriptor {

  private static final float SLAVE_THRESHOLD = 0.5f;

  /**
   * Constructor.
   */
  public ServicesUpCheck() {
    super(CheckDescription.SERVICES_UP);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void perform(PrerequisiteCheck prerequisiteCheck, PrereqCheckRequest request)
      throws AmbariException {

    final String clusterName = request.getClusterName();
    final Cluster cluster = clustersProvider.get().getCluster(clusterName);
    List<String> errorMessages = new ArrayList<String>();
    Set<String> failedServiceNames = new HashSet<String>();

    StackId stackId = cluster.getCurrentStackVersion();

    for (Map.Entry<String, Service> serviceEntry : cluster.getServices().entrySet()) {
      final Service service = serviceEntry.getValue();

      // Ignore services like Tez that are clientOnly.
      if (service.isClientOnlyService()) {
        continue;
      }

      Map<String, ServiceComponent> serviceComponents = service.getServiceComponents();
      for (Map.Entry<String, ServiceComponent> component : serviceComponents.entrySet()) {

        ServiceComponent serviceComponent = component.getValue();
        // In Services like HDFS, ignore components like HDFS Client
        if (serviceComponent.isClientComponent()) {
          continue;
        }

        // skip if the component is not part of the finalization version check
        if (!serviceComponent.isVersionAdvertised()) {
          continue;
        }

        // TODO, add more logic that checks the Upgrade Pack.
        // These components are not in the upgrade pack and do not advertise a
        // version:
        // ZKFC, Ambari Metrics, Kerberos, Atlas (right now).
        // Generally, if it advertises a version => in the upgrade pack.
        // So it can be in the Upgrade Pack but not advertise a version.
        List<HostComponentSummary> hostComponentSummaries = HostComponentSummary.getHostComponentSummaries(
            service.getName(), serviceComponent.getName());

        // not installed, nothing to do
        if (hostComponentSummaries.isEmpty()) {
          continue;
        }

        // non-master, "true" slaves with cardinality 1+
        boolean checkThreshold = false;
        if (!serviceComponent.isMasterComponent()) {
          ComponentInfo componentInfo = ambariMetaInfo.get().getComponent(stackId.getStackName(),
              stackId.getStackVersion(), serviceComponent.getServiceName(),
              serviceComponent.getName());

          String cardinality = componentInfo.getCardinality();
          // !!! check if there can be more than one. This will match, say,
          // datanodes but not ZKFC
          if (null != cardinality
              && (cardinality.equals("ALL") || cardinality.matches("[1-9].*"))) {
            checkThreshold = true;
          }
        }

        // check threshold for slaves which have a non-0 cardinality
        if (checkThreshold) {
          int total = hostComponentSummaries.size();
          int up = 0;
          int down = 0;

          for (HostComponentSummary summary : hostComponentSummaries) {
            if (isConsideredDown(cluster, serviceComponent, summary)) {
              down++;
            } else {
              up++;
            }
          }

          if ((float) down / total > SLAVE_THRESHOLD) { // arbitrary
            failedServiceNames.add(service.getName());
            String message = MessageFormat.format(
                "{0}: {1} out of {2} {3} are started; there should be {4,number,percent} started before upgrading.",
                service.getName(), up, total, serviceComponent.getName(), SLAVE_THRESHOLD);
            errorMessages.add(message);
          }
        } else {
          for (HostComponentSummary summary : hostComponentSummaries) {
            if (isConsideredDown(cluster, serviceComponent, summary)) {
              failedServiceNames.add(service.getName());
              String message = MessageFormat.format("{0}: {1} (in {2} on host {3})",
                  service.getName(), serviceComponent.getName(), summary.getCurrentState(),
                  summary.getHostName());
              errorMessages.add(message);
              break;
            }
          }
        }
      }
    }

    if (!errorMessages.isEmpty()) {
      prerequisiteCheck.setFailedOn(new LinkedHashSet<String>(failedServiceNames));
      prerequisiteCheck.setStatus(PrereqCheckStatus.FAIL);
      prerequisiteCheck.setFailReason(
          "The following Service Components should be in a started state.  Please invoke a service Stop and full Start and try again. "
              + StringUtils.join(errorMessages, ", "));
    }
  }

  /**
   * Gets whether this component should be considered as being "down" for the
   * purposes of this check. Component type, maintenance mode, and state are
   * taken into account.
   *
   * @param clusters
   *          the clusters instance
   * @param cluster
   *          the cluster
   * @param serviceComponent
   *          the component
   * @param summary
   *          a summary of the state of the component on a host
   * @return {@code true} if the host component should be considered as failing
   *         this test.
   * @throws AmbariException
   */
  private boolean isConsideredDown(Cluster cluster, ServiceComponent serviceComponent,
      HostComponentSummary summary) throws AmbariException {
    Host host = clustersProvider.get().getHostById(summary.getHostId());
    MaintenanceState maintenanceState = host.getMaintenanceState(cluster.getClusterId());

    // non-MASTER components in maintenance mode should not count
    if (maintenanceState == MaintenanceState.ON && !serviceComponent.isMasterComponent()) {
      return false;
    }

    State desiredState = summary.getDesiredState();
    State currentState = summary.getCurrentState();

    switch (desiredState) {
      case INSTALLED:
      case STARTED:
        return currentState != State.STARTED;
      default:
        return false;
    }
  }
}


text:
//// [derivedUninitializedPropertyDeclaration.ts]
class A {
    property = 'x';
    m() { return 1 }
}
class B extends A {
    property: any; // error
}
class BD extends A {
    declare property: any; // ok because it's implicitly initialised
}
class BDBang extends A {
    declare property!: any; // ! is not allowed, this is an ambient declaration
}
class BOther extends A {
    declare m() { return 2 } // not allowed on methods
    declare nonce: any; // ok, even though it's not in the base
    declare property = 'y' // initialiser not allowed with declare
}
class U {
    declare nonce: any; // ok, even though there's no base
}

class C {
    p: string;
}
class D extends C {
    p: 'hi'; // error
}
class DD extends C {
    declare p: 'bye'; // ok
}

declare class E {
    p1: string
    p2: string
}
class F extends E {
    p1!: 'z'
    declare p2: 'alpha'
}

class G extends E {
    p1: 'z'
    constructor() {
        super()
        this.p1 = 'z'
    }
}

abstract class H extends E {
    abstract p1: 'a' | 'b' | 'c'
    declare abstract p2: 'a' | 'b' | 'c'
}

interface I {
    q: number
}
interface J extends I { }
class J {
    r = 5
}
class K extends J {
    q!: 1 | 2 | 3 // ok, extends a property from an interface
    r!: 4 | 5 // error, from class
}

// #35327
class L {
    a: any;
    constructor(arg: any) {
        this.a = arg;
    }
}
class M extends L {
    declare a: number;
    constructor(arg: number) {
        super(arg);
        console.log(this.a);  // should be OK, M.a is ambient
    }
}

//// [derivedUninitializedPropertyDeclaration.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var A = /** @class */ (function () {
    function A() {
        this.property = 'x';
    }
    A.prototype.m = function () { return 1; };
    return A;
}());
var B = /** @class */ (function (_super) {
    __extends(B, _super);
    function B() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return B;
}(A));
var BD = /** @class */ (function (_super) {
    __extends(BD, _super);
    function BD() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return BD;
}(A));
var BDBang = /** @class */ (function (_super) {
    __extends(BDBang, _super);
    function BDBang() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return BDBang;
}(A));
var BOther = /** @class */ (function (_super) {
    __extends(BOther, _super);
    function BOther() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BOther.prototype.m = function () { return 2; }; // not allowed on methods
    return BOther;
}(A));
var U = /** @class */ (function () {
    function U() {
    }
    return U;
}());
var C = /** @class */ (function () {
    function C() {
    }
    return C;
}());
var D = /** @class */ (function (_super) {
    __extends(D, _super);
    function D() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return D;
}(C));
var DD = /** @class */ (function (_super) {
    __extends(DD, _super);
    function DD() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return DD;
}(C));
var F = /** @class */ (function (_super) {
    __extends(F, _super);
    function F() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return F;
}(E));
var G = /** @class */ (function (_super) {
    __extends(G, _super);
    function G() {
        var _this = _super.call(this) || this;
        _this.p1 = 'z';
        return _this;
    }
    return G;
}(E));
var H = /** @class */ (function (_super) {
    __extends(H, _super);
    function H() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return H;
}(E));
var J = /** @class */ (function () {
    function J() {
        this.r = 5;
    }
    return J;
}());
var K = /** @class */ (function (_super) {
    __extends(K, _super);
    function K() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return K;
}(J));
// #35327
var L = /** @class */ (function () {
    function L(arg) {
        this.a = arg;
    }
    return L;
}());
var M = /** @class */ (function (_super) {
    __extends(M, _super);
    function M(arg) {
        var _this = _super.call(this, arg) || this;
        console.log(_this.a); // should be OK, M.a is ambient
        return _this;
    }
    return M;
}(L));


text:
using System.Collections.Generic;

namespace Sample01.Models
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public virtual ICollection<BlogPost> BlogPosts { get; set; }
    }
}


text:
"""
This is the main executable of the mesos-cli unit tests.
"""

import unittest

from termcolor import colored

if __name__ == '__main__':
    print colored("Running the Mesos CLI unit tests", "yellow")
    unittest.main(verbosity=2, testRunner=unittest.TextTestRunner)