text:
module Hexp
  module CssSelector
    # A parser of CSS selectors
    #
    # This is a wrapper around the SASS parser. This way we are isolated from
    # changes in SASS. It also makes things easier should we decide to switch
    # to a different parsing library or roll our own parser. We only use a
    # fraction of the functionality of SASS so this might be worth it, although
    # at this point I want to avoid reinventing that wheel.
    #
    # The classes that make up the parse tree largely mimic the ones from SASS,
    # like CommaSequence, SimpleSequence, Class, Id, etc. By having them in our
    # own namespace however we can easily add Hexp-specific functionality to them.
    #
    class Parser
      # Initialize the parser with the selector to parse
      #
      # @param [String] selector
      #
      # @api private
      def initialize(selector)
        @selector = selector.freeze
      end

      # Parse the selector
      #
      # @return [Hexp::CssSelector::CommaSequence]
      #
      # @api private
      def parse
        CommaSequence.new(
          ::Nokogiri::CSS.parse(@selector).map do |node|
            node.accept(self)
          end
        )
      end

      # Parse a CSS selector in one go
      #
      # @param [String] selector
      # @return [Hexp::CssSelector::CommaSequence]
      #
      # @api private
      def self.call(selector)
        new(selector).parse
      end

      def visit_descendant_selector(node)
        Sequence.new(
          node.value.map {|child| child.accept(self) }
        )
      end

      # div.caption
      def visit_conditional_selector(node)
        head, tail = node.value
        children = [head]
        while tail.type == :COMBINATOR
          head, tail = tail.value
          children << head
        end
        children << tail

        SimpleSequence.new(
          children.map {|child| child.accept(self) }
        )
      end

      # p
      def visit_element_name(node)
        if node.value == ["*"]
          Universal.new
        else
          Element.new(node.value.first)
        end
      end

      # .error
      def visit_class_condition(node)
        Class.new(node.value.first)
      end

      # #cover
      def visit_id(node)
        Id.new(node.value.first.sub(/^#/, ''))
      end

      # ul > li
      def visit_child_selector(node)
        raise "not implemented"
      end

      # [href^="http://"]
      def visit_attribute_condition(node)
        element, operator, value = node.value
        name = element.value.first
        Attribute.new(name.sub(/^@/, ''), operator, value)
      end

      # li:first / li:nth-child(3n)
      def visit_pseudo_class(node)
        PseudoClass.new(node.value)
      end

    end
  end
end


text:
#include "CmdLineParams.h"

#include <iostream>
#include <cstring>

#include "versioninfo.h"

using namespace std;

CmdLineParams::CmdLineParams() : inputs(vector<string> ()), info_only(false), use_stdout(false), create_config(false), output() {}

const vector<string> & CmdLineParams::get_inputs() {
    return inputs;
}

const string & CmdLineParams::get_output() { return output; }
bool CmdLineParams::get_info_only() { return info_only; }
bool CmdLineParams::get_use_stdout() { return use_stdout; }
bool CmdLineParams::get_create_config() { return create_config; }

bool CmdLineParams::is_valid() {
    return (create_config && inputs.size() == 0) || (inputs.size() > 0 && ((output.empty() && !use_stdout) || inputs.size() == 1));
}

void CmdLineParams::print_usage(string programName) {
    cout << Project_NAME << " version " << Project_VERSION_STRING << endl << endl;
    cout << "Usage: " << programName << " ([-i|--info] [-o|--output <output file>] [-s|--stdout] <gcode file> [<gcode file> ...] | --create-config)" << endl;
    cout << "  -i, --info: Only print the estimated time for each file, do not generate gcode" << endl;
    cout << "  -o, --output: Sets the output filename. Can only be used with a single input file" << endl;
    cout << "  -s, --stdout: Prints the generated gcode to stdout instead of saving it to a file." << endl
            << "                   Can only be used with a single input file. -o will be ignored" << endl;
    cout << "  --create-config: Generates or completes the config file with any missing defaults" << endl;
    cout << endl;
    cout << "If -o is not specified, the program will create a file of the new name with a '.timed' suffix" << endl
            << "  for each input file" << endl;
}

void CmdLineParams::parse(int argc, char **argv) {
    int state = STATE_MAIN;

    for (int i = 1; i < argc; i++) {
        switch (state) {
            case STATE_MAIN:
                if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) {
                    state = STATE_OUTPUT;
                } else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--info") == 0) {
                    info_only = true;
                } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--stdout") == 0) {
                    use_stdout = true;
                } else if (strcmp(argv[i], "--create-config") == 0) {
                    create_config = true;
                } else {
                    inputs.push_back(string(argv[i]));
                }
                break;
            case STATE_OUTPUT:
                output = string(argv[i]);
                state = STATE_MAIN;
                break;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function(JsSIP) {

var Request = function(session) {
  var events = [
  'progress',
  'succeeded',
  'failed'
  ];

  this.owner = session;

  this.logger = session.ua.getLogger('jssip.rtcsession.request', session.id);
  this.initEvents(events);
};
Request.prototype = new JsSIP.EventEmitter();

Request.prototype.send = function(method, options) {
  options = options || {};

  var event,
    extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
    eventHandlers = options.eventHandlers || {},
    body = options.body || null;

  if (method === undefined) {
    throw new TypeError('Not enough arguments');
  }

  // Check RTCSession Status
  if (this.owner.status !== JsSIP.RTCSession.C.STATUS_1XX_RECEIVED &&
    this.owner.status !== JsSIP.RTCSession.C.STATUS_WAITING_FOR_ANSWER &&
    this.owner.status !== JsSIP.RTCSession.C.STATUS_WAITING_FOR_ACK &&
    this.owner.status !== JsSIP.RTCSession.C.STATUS_CONFIRMED &&
    this.owner.status !== JsSIP.RTCSession.C.STATUS_TERMINATED) {
    throw new JsSIP.Exceptions.InvalidStateError(this.owner.status);
  }

  /*
   * Allow sending BYE in TERMINATED status since the RTCSession
   * could had been terminated before the ACK had arrived.
   * RFC3261 Section 15, Paragraph 2
   */
  else if (this.owner.status === JsSIP.RTCSession.C.STATUS_TERMINATED && method !== JsSIP.C.BYE) {
    throw new JsSIP.Exceptions.InvalidStateError(this.owner.status);
  }

  // Set event handlers
  for (event in eventHandlers) {
    this.on(event, eventHandlers[event]);
  }

  this.owner.dialog.sendRequest(this, method, {
    extraHeaders: extraHeaders,
    body: body
  });
};

Request.prototype.receiveResponse = function(response) {
  var cause;

  switch(true) {
    case /^1[0-9]{2}$/.test(response.status_code):
      this.emit('progress', this, {
        originator: 'remote',
        response: response
      });
      break;

    case /^2[0-9]{2}$/.test(response.status_code):
      this.emit('succeeded', this, {
        originator: 'remote',
        response: response
      });
      break;

    default:
      cause = JsSIP.Utils.sipErrorCause(response.status_code);
      this.emit('failed', this, {
        originator: 'remote',
        response: response,
        cause: cause
      });
      break;
  }
};

Request.prototype.onRequestTimeout = function() {
  this.emit('failed', this, {
    originator: 'system',
    cause: JsSIP.C.causes.REQUEST_TIMEOUT
  });
  this.owner.onRequestTimeout();
};

Request.prototype.onTransportError = function() {
  this.emit('failed', this, {
    originator: 'system',
    cause: JsSIP.C.causes.CONNECTION_ERROR
  });
  this.owner.onTransportError();
};

Request.prototype.onDialogError = function(response) {
  this.emit('failed', this, {
    originator: 'remote',
    response: response,
    cause: JsSIP.C.causes.DIALOG_ERROR
  });
  this.owner.onDialogError(response);
};

JsSIP.RTCSession.Request = Request;
}(JsSIP));


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pcate',
  templateUrl: './pcate.component.html',
  styleUrls: ['./pcate.component.less']
})
export class PcateComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
require 'test_helper'

module News
  class ItemsControllerTest < ActionController::TestCase
    setup do
      @item = items(:one)
    end

    test "should get index" do
      get :index
      assert_response :success
      assert_not_nil assigns(:items)
    end

    test "should get new" do
      get :new
      assert_response :success
    end

    test "should create item" do
      assert_difference('Item.count') do
        post :create, item: { text: @item.text, title: @item.title }
      end

      assert_redirected_to item_path(assigns(:item))
    end

    test "should show item" do
      get :show, id: @item
      assert_response :success
    end

    test "should get edit" do
      get :edit, id: @item
      assert_response :success
    end

    test "should update item" do
      put :update, id: @item, item: { text: @item.text, title: @item.title }
      assert_redirected_to item_path(assigns(:item))
    end

    test "should destroy item" do
      assert_difference('Item.count', -1) do
        delete :destroy, id: @item
      end

      assert_redirected_to items_path
    end
  end
end


text:
package com.Litterfeldt.AStory.dbConnector;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.Litterfeldt.AStory.models.SaveState;

public class dbSave {
    public static void setSave(Context c,SaveState s){
        dbConnector.getInstance(c).write().execSQL("DELETE FROM "+dbConnector.TABLE_NAME_SAVED_STATE+";");
        ContentValues initialValues = new ContentValues();
        initialValues.put(dbConnector.COLUMN_SAVED_STATE_BOOK_ID,s.bookId());
        initialValues.put(dbConnector.COLUMN_SAVED_STATE_CHAPTER_ID,s.chapterId());
        initialValues.put(dbConnector.COLUMN_SAVED_STATE_CURRENT_TIME_POS,s.time_pos());
        dbConnector.getInstance(c).write().insert(dbConnector.TABLE_NAME_SAVED_STATE, null, initialValues);

    }
    public static SaveState getSave(Context c){
        Cursor cursor = dbConnector.getInstance(c).read().query(dbConnector.TABLE_NAME_SAVED_STATE,
                new String[]{dbConnector.COLUMN_SAVED_STATE_BOOK_ID,
                        dbConnector.COLUMN_SAVED_STATE_CHAPTER_ID,
                        dbConnector.COLUMN_SAVED_STATE_CURRENT_TIME_POS},
                null,null,null,null,null);
        boolean notEmpty = cursor.moveToLast();
        if (notEmpty){
            return new SaveState(cursor.getInt(0),cursor.getInt(1),cursor.getInt(2));
        }else{
            return null;
        }
    }
}


text:
#include <stdint.h>
#include <string>

#include "gtest/gtest.h"
#include "utils/shared_ptr.h"
#include "smart_objects/smart_object.h"
#include "application_manager/smart_object_keys.h"
#include "commands/commands_test.h"
#include "application_manager/application.h"
#include "application_manager/commands/hmi/sdl_activate_app_response.h"

namespace test {
namespace components {
namespace commands_test {
namespace hmi_commands_test {
namespace sdl_activate_app_response {

using ::utils::SharedPtr;
namespace am = ::application_manager;
namespace strings = ::application_manager::strings;
using am::commands::SDLActivateAppResponse;
using am::commands::CommandImpl;

typedef SharedPtr<SDLActivateAppResponse> SDLActivateAppResponsePtr;

namespace {
const uint32_t kConnectionKey = 2u;
const std::string kStrNumber = "123";
}  // namespace

class SDLActivateAppResponseTest
    : public CommandsTest<CommandsTestMocks::kIsNice> {};

TEST_F(SDLActivateAppResponseTest, RUN_SendRequest_SUCCESS) {
  MessageSharedPtr command_msg(CreateMessage(smart_objects::SmartType_Map));
  (*command_msg)[strings::msg_params][strings::number] = kStrNumber;
  (*command_msg)[strings::params][strings::connection_key] = kConnectionKey;

  SDLActivateAppResponsePtr command(
      CreateCommand<SDLActivateAppResponse>(command_msg));

  EXPECT_CALL(app_mngr_, SendMessageToHMI(command_msg));

  command->Run();

  EXPECT_EQ((*command_msg)[strings::params][strings::protocol_type].asInt(),
            CommandImpl::hmi_protocol_type_);
  EXPECT_EQ((*command_msg)[strings::params][strings::protocol_version].asInt(),
            CommandImpl::protocol_version_);
}

}  // namespace sdl_activate_app_response
}  // namespace hmi_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test


text:
package Nov2020_GoogPrep;

import java.util.Stack;

public class _039DecodeString {

	public static void main(String[] args) {
		System.out.println(decodeString("3[a]2[bc]"));
		System.out.println(decodeString("3[a2[c]]"));
		System.out.println(decodeString("2[abc]3[cd]ef"));
		System.out.println(decodeString("abc3[cd]xyz"));
		System.out.println(decodeString("100[leetcode]"));
	}

	public static String decodeString(String s) {
		Stack<String> stack = new Stack<String>();
		StringBuilder outputString = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c == ']') {
				// pop stack until we get a [
				// and then pop again the next one to get a number
				String str = "";
				while (!stack.isEmpty() && !stack.peek().equals("[")) {
					str += stack.pop();
				}
				// remove the [
				stack.pop();
				StringBuilder noOfTimes = new StringBuilder();
				while (!stack.isEmpty() && Character.isDigit(stack.peek().charAt(0))) {
					noOfTimes.append(stack.pop());
				}

				int count = Integer.parseInt(noOfTimes.reverse().toString());
				String currString = "";
				for (int j = 0; j < count; j++) {
					currString += str;
				}
				stack.push(currString);
			} else {
				stack.push(c + "");
			}
		}

		while (!stack.isEmpty()) {
			outputString.append(stack.pop());
		}

		return outputString.reverse().toString();
	}
}


text:
package timeout.slang.com.model.scraper.common.handlers;

import timeout.slang.com.model.scraper.common.CharStream;

/**
 * Created by MrLenovo on 17/02/2016.
 */
public abstract class HandlerBase implements CharStream.ICharHandler {

    protected HandlerBase mFollowingState;

    public abstract HandlerBase handleChar(char c, CharStream cpp);

    public abstract void setActiveHandler();

    public HandlerBase setFollowingState(HandlerBase followingState) {
        mFollowingState = followingState;
        return followingState;
    }
}


text:
module Spree
  module Analytics
    class GoogleAnalyticsService < Spree::Preferences::Configuration
      preference :view_id, :string, :default => ""
      preference :key_file, :string, :default => ""
      preference :key_secret, :string, :default => ""
      preference :service_account_email, :string, :default => ""

      def initialize
        @client = SpreePageAnalytics::GoogleAnalytics::Client.new(
          preferred_service_account_email,
          preferred_key_file,
          preferred_key_secret,
          preferred_view_id
        )
      end

      def create_snapshots(start_date=nil, end_date=nil)
        if !@client.authorized?
          @client.authorize
        end
        start_date ||= begin
          newest_snapshot = Spree::PageTrafficSnapshot.order("begin DESC").first
          newest_snapshot_start = newest_snapshot ? newest_snapshot.begin.beginning_of_day + 1.day : nil
          four_months_ago = Time.now.beginning_of_day - 4.months
          if newest_snapshot_start
            [newest_snapshot_start, four_months_ago].max
          else
            four_months_ago
          end
        end
        end_date ||= Time.now.end_of_day - 1.day
        date = start_date
        while date < end_date
          create_snapshots_for_date(date)
          date += 1.day
        end
      end

      def create_snapshots_for_date(date)
        dimensions = "ga:landingPagePath"
        metrics = "ga:sessions,ga:transactions,ga:transactionRevenue"
        sort = "ga:landingPagePath"
        filters = "ga:landingPagePath=@/t/,ga:landingPagePath=@/products/,ga:landingPagePath==/"
        result = @client.get_data(date.beginning_of_day, date.end_of_day, dimensions, metrics, filters, sort)
        result[:rows].each do |row|
          Spree::PageTrafficSnapshot.create(
            :page => row[0],
            :sessions => row[1],
            :transactions => row[2],
            :revenue => row[3],
            :begin => date.beginning_of_day,
            :end => date.end_of_day
          )
        end
      end
    end
  end
end


text:
package io.cloudevents.http.restful.ws;

import io.cloudevents.CloudEvent;
import io.cloudevents.core.mock.CSVFormat;
import io.cloudevents.core.test.Data;
import org.junit.jupiter.api.Test;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import static org.assertj.core.api.Assertions.assertThat;

public abstract class BaseTest {

    protected abstract WebTarget getWebTarget();

    @Test
    void getMinEvent() {
        Response res = getWebTarget().path("getMinEvent").request().buildGet().invoke();

        assertThat(res.getHeaderString("ce-specversion"))
            .isEqualTo("1.0");

        CloudEvent outEvent = res.readEntity(CloudEvent.class);
        assertThat(outEvent)
            .isEqualTo(Data.V1_MIN);
    }

    @Test
    void getStructuredEvent() {
        Response res = getWebTarget().path("getStructuredEvent").request().buildGet().invoke();

        CloudEvent outEvent = res.readEntity(CloudEvent.class);
        assertThat(outEvent)
            .isEqualTo(Data.V1_MIN);
        assertThat(res.getHeaderString(HttpHeaders.CONTENT_TYPE))
            .isEqualTo(CSVFormat.INSTANCE.serializedContentType());
    }

    @Test
    void getEvent() {
        Response res = getWebTarget().path("getEvent").request().buildGet().invoke();

        CloudEvent outEvent = res.readEntity(CloudEvent.class);
        assertThat(outEvent)
            .isEqualTo(Data.V1_WITH_JSON_DATA_WITH_EXT_STRING);
    }

    @Test
    void postEventWithoutBody() {
        Response res = getWebTarget()
            .path("postEventWithoutBody")
            .request()
            .buildPost(Entity.entity(Data.V1_MIN, CloudEventsProvider.CLOUDEVENT_TYPE))
            .invoke();

        assertThat(res.getStatus())
            .isEqualTo(200);
    }

    @Test
    void postEventStructured() {
        Response res = getWebTarget()
            .path("postEventWithoutBody")
            .request()
            .buildPost(Entity.entity(Data.V1_MIN, "application/cloudevents+csv"))
            .invoke();

        assertThat(res.getStatus())
            .isEqualTo(200);
    }

    @Test
    void postEvent() {
        Response res = getWebTarget()
            .path("postEvent")
            .request()
            .buildPost(Entity.entity(Data.V1_WITH_JSON_DATA_WITH_EXT_STRING, CloudEventsProvider.CLOUDEVENT_TYPE))
            .invoke();

        assertThat(res.getStatus())
            .isEqualTo(200);
    }
}


text:
use strict; use warnings;
package YAML::Any;
our $VERSION = '1.15';

use Exporter ();

@YAML::Any::ISA       = 'Exporter';
@YAML::Any::EXPORT    = qw(Dump Load);
@YAML::Any::EXPORT_OK = qw(DumpFile LoadFile);

my @dump_options = qw(
    UseCode
    DumpCode
    SpecVersion
    Indent
    UseHeader
    UseVersion
    SortKeys
    AnchorPrefix
    UseBlock
    UseFold
    CompressSeries
    InlineSeries
    UseAliases
    Purity
    Stringify
);

my @load_options = qw(
    UseCode
    LoadCode
);

my @implementations = qw(
    YAML::XS
    YAML::Syck
    YAML::Old
    YAML
    YAML::Tiny
);

sub import {
    __PACKAGE__->implementation;
    goto &Exporter::import;
}

sub Dump {
    no strict 'refs';
    no warnings 'once';
    my $implementation = __PACKAGE__->implementation;
    for my $option (@dump_options) {
        my $var = "$implementation\::$option";
        my $value = $$var;
        local $$var;
        $$var = defined $value ? $value : ${"YAML::$option"};
    }
    return &{"$implementation\::Dump"}(@_);
}

sub DumpFile {
    no strict 'refs';
    no warnings 'once';
    my $implementation = __PACKAGE__->implementation;
    for my $option (@dump_options) {
        my $var = "$implementation\::$option";
        my $value = $$var;
        local $$var;
        $$var = defined $value ? $value : ${"YAML::$option"};
    }
    return &{"$implementation\::DumpFile"}(@_);
}

sub Load {
    no strict 'refs';
    no warnings 'once';
    my $implementation = __PACKAGE__->implementation;
    for my $option (@load_options) {
        my $var = "$implementation\::$option";
        my $value = $$var;
        local $$var;
        $$var = defined $value ? $value : ${"YAML::$option"};
    }
    return &{"$implementation\::Load"}(@_);
}

sub LoadFile {
    no strict 'refs';
    no warnings 'once';
    my $implementation = __PACKAGE__->implementation;
    for my $option (@load_options) {
        my $var = "$implementation\::$option";
        my $value = $$var;
        local $$var;
        $$var = defined $value ? $value : ${"YAML::$option"};
    }
    return &{"$implementation\::LoadFile"}(@_);
}

sub order {
    return @YAML::Any::_TEST_ORDER
        if @YAML::Any::_TEST_ORDER;
    return @implementations;
}

sub implementation {
    my @order = __PACKAGE__->order;
    for my $module (@order) {
        my $path = $module;
        $path =~ s/::/\//g;
        $path .= '.pm';
        return $module if exists $INC{$path};
        eval "require $module; 1" and return $module;
    }
    croak("YAML::Any couldn't find any of these YAML implementations: @order");
}

sub croak {
    require Carp;
    Carp::croak(@_);
}

1;


text: document.writeln('<script src="foam.js"></script>');


text:
<% if name_details[:ledger_item][:underscore_singular] != 'ledger_item' -%>
acts_as_line_item :ledger_item => :<%= name_details[:ledger_item][:underscore_singular] %>
<% else -%>
acts_as_line_item
<% end -%>

belongs_to :<%= name_details[:ledger_item][:underscore_singular] %>, :class_name => '<%= name_details[:ledger_item][:class_name_full] %>'


text:
<?php

/*
 * This file is part of the Silex framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Silex\Tests\Provider;

use Silex\Application;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\ValidatorServiceProvider;
use Silex\Provider\FormServiceProvider;
use Symfony\Component\Translation\Exception\NotFoundResourceException;
use Symfony\Component\Validator\Constraints as Assert;
use Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\Custom;
use Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\CustomValidator;

/**
 * ValidatorServiceProvider.
 *
 * Javier Lopez <f12loalf@gmail.com>
 */
class ValidatorServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $app = new Application();

        $app->register(new ValidatorServiceProvider());

        return $app;
    }

    public function testRegisterWithCustomValidators()
    {
        $app = new Application();

        $app['custom.validator'] = $app->share(function () {
            return new CustomValidator();
        });

        $app->register(new ValidatorServiceProvider(), array(
            'validator.validator_service_ids' => array(
                'test.custom.validator' => 'custom.validator',
            ),
        ));

        return $app;
    }

    /**
     * @depends testRegisterWithCustomValidators
     */
    public function testConstraintValidatorFactory($app)
    {
        $this->assertInstanceOf('Silex\ConstraintValidatorFactory', $app['validator.validator_factory']);

        $validator = $app['validator.validator_factory']->getInstance(new Custom());
        $this->assertInstanceOf('Silex\Tests\Provider\ValidatorServiceProviderTest\Constraint\CustomValidator', $validator);
    }

    /**
     * @depends testRegister
     */
    public function testConstraintValidatorFactoryWithExpression($app)
    {
        if (!class_exists('Symfony\Component\Validator\Constraints\Expression')) {
            $this->markTestSkipped('Expression are not supported by this version of Symfony');
        }

        $constraint = new Assert\Expression('true');
        $validator = $app['validator.validator_factory']->getInstance($constraint);
        $this->assertInstanceOf('Symfony\Component\Validator\Constraints\ExpressionValidator', $validator);
    }

    /**
     * @depends testRegister
     */
    public function testValidatorServiceIsAValidator($app)
    {
        $this->assertInstanceOf('Symfony\Component\Validator\ValidatorInterface', $app['validator']);
    }

    /**
     * @depends testRegister
     * @dataProvider testValidatorConstraintProvider
     */
    public function testValidatorConstraint($email, $isValid, $nbGlobalError, $nbEmailError, $app)
    {
        $app->register(new ValidatorServiceProvider());
        $app->register(new FormServiceProvider());

        $constraints = new Assert\Collection(array(
            'email' => array(
                new Assert\NotBlank(),
                new Assert\Email(),
            ),
        ));

        $builder = $app['form.factory']->createBuilder('form', array(), array(
            'constraints' => $constraints,
            'csrf_protection' => false,
        ));

        $form = $builder
            ->add('email', 'email', array('label' => 'Email'))
            ->getForm()
        ;

        $form->submit(array('email' => $email));

        $this->assertEquals($isValid, $form->isValid());
        $this->assertEquals($nbGlobalError, count($form->getErrors()));
        $this->assertEquals($nbEmailError, count($form->offsetGet('email')->getErrors()));
    }

    public function testValidatorWillNotAddNonexistentTranslationFiles()
    {
        $app = new Application(array(
            'locale' => 'nonexistent',
        ));

        $app->register(new ValidatorServiceProvider());
        $app->register(new TranslationServiceProvider(), array(
            'locale_fallbacks' => array(),
        ));

        $app['validator'];
        $translator = $app['translator'];

        try {
            $translator->trans('test');
        } catch (NotFoundResourceException $e) {
            $this->fail('Validator should not add a translation resource that does not exist');
        }
    }

    public function testValidatorConstraintProvider()
    {
        // Email, form is valid , nb global error, nb email error
        return array(
            array('', false, 0, 1),
            array('not an email', false, 0, 1),
            array('email@sample.com', true, 0, 0),
        );
    }

    public function testAddResource()
    {
        $app = new Application();
        $app['locale'] = 'fr';

        $app->register(new ValidatorServiceProvider());
        $app->register(new TranslationServiceProvider());
        $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) {
            $translator->addResource('array', array('This value should not be blank.' => 'Pas vide'), 'fr', 'validators');

            return $translator;
        }));

        $app['validator'];

        $this->assertEquals('Pas vide', $app['translator']->trans('This value should not be blank.', array(), 'validators', 'fr'));
    }

    public function testAddResourceAlternate()
    {
        $app = new Application();
        $app['locale'] = 'fr';

        $app->register(new ValidatorServiceProvider());
        $app->register(new TranslationServiceProvider());
        $app->extend('translator.resources', function ($resources, $app) {
            $resources = array_merge($resources, array(
                array('array', array('This value should not be blank.' => 'Pas vide'), 'fr', 'validators'),
            ));

            return $resources;
        });

        $app['validator'];

        $this->assertEquals('Pas vide', $app['translator']->trans('This value should not be blank.', array(), 'validators', 'fr'));
    }
}


text:
#ifndef _PALETTECOLORDEFINES_H
#define _PALETTECOLORDEFINES_H

#include "GraphicsConfig.h"

/*********************************************************************
* Overview: Some basic colors definitions.
*********************************************************************/
#ifdef USE_PALETTE

    #define BLACK               0
    #define BRIGHTBLUE          1
    #define BRIGHTGREEN         2
    #define BRIGHTCYAN          3
    #define BRIGHTRED           4
    #define BRIGHTMAGENTA       5
    #define BRIGHTYELLOW        6
    #define BLUE                7
    #define GREEN               8
    #define CYAN                9
    #define RED                 10
    #define MAGENTA             11
    #define BROWN               12
    #define LIGHTGRAY           13
    #define DARKGRAY            14
    #define LIGHTBLUE           15
    #define LIGHTGREEN          16
    #define LIGHTCYAN           17
    #define LIGHTRED            18
    #define LIGHTMAGENTA        19
    #define YELLOW              20
    #define WHITE               21

    #define GRAY0       	    22
    #define GRAY1         	    23
    #define GRAY2               24
    #define GRAY3               25
    #define GRAY4               26
    #define GRAY5               27
    #define GRAY6	            28

    #define GRAY20              29
    #define GRAY40              30
    #define GRAY80              31
    #define GRAY90              32
    #define GRAY95              33
    #define RED4                34
    #define FIREBRICK1          35
    #define DARKGREEN           36
    #define PALEGREEN           37
    #define LIGHTYELLOW         38
    #define GOLD                39
    #define DARKORANGE          40

    // Brown color scheme
    #define SADDLEBROWN         41
    #define SIENNA              42
    #define PERU                43
    #define BURLYWOOD           44
    #define WHEAT               45
    #define TAN                 46
    #define GRAY80              31
    #define GRAY90              32
    #define GRAY95              33

    /* default settings for TRULY display */

// Emboss dark color default value.
    #define EMBOSSDKCOLORDEFAULT            61

// Emboss light color default value.
    #define EMBOSSLTCOLORDEFAULT            62

// Text color 0 default value.
    #define TEXTCOLOR0DEFAULT               63

// Text color 1 default value.
    #define TEXTCOLOR1DEFAULT               WHITE

// Text color disabled default value.
    #define TEXTCOLORDISABLEDDEFAULT        WHEAT

// Color 0 default value.
    #define COLOR0DEFAULT                   64

// Color 1 default value.
    #define COLOR1DEFAULT                   65

// Disabled color default value.
    #define COLORDISABLEDDEFAULT            66

// Common background color default value.
    #define COMMONBACKGROUNDCOLORDEFAULT    67

// Chart color definitions
    #define CH_CLR0             68
    #define CH_CLR1             69
    #define CH_CLR2             70
    #define CH_CLR3             71
    #define CH_CLR4             72
    #define CH_CLR5             73
    #define CH_CLR6             74
    #define CH_CLR7             75
    #define CH_CLR8             76
    #define CH_CLR9             77
    #define CH_CLR10            78
    #define CH_CLR11            79
    #define CH_CLR12            80
    #define CH_CLR13            81
    #define CH_CLR14            82
    #define CH_CLR15            83

#endif // USE_PALETTE

#endif // _PALETTECOLORDEFINES_H


text:
class IntrinsicEdManagerWindowMesh : public IntrinsicEdManagerWindowBase
{
  Q_OBJECT

public:
  IntrinsicEdManagerWindowMesh(QWidget* parent);

private slots:
  void onResourceTreePopulated();
};


text:
package com.greenpepper.server.rpc.runner;

import java.util.Locale;

import org.jmock.Expectations;

import com.greenpepper.repository.DocumentNode;
import com.greenpepper.server.domain.Execution;
import com.greenpepper.server.domain.Repository;
import com.greenpepper.server.domain.SystemUnderTest;

public class RemoteSuiteRunnerTest
		extends AbstractRunnerTest
{

	private RemoteSuiteRunner runner;

	@Override
	protected void setUp()
			throws Exception
	{
		super.setUp();

		runner = new RemoteSuiteRunner();
		runner.setLocale(Locale.ENGLISH);
		runner.setMonitor(monitor);
		runner.setProject("project");
		runner.setReportGenerator(reportGenerator);
		runner.setRepositoryId("repositoryId");
		runner.setSystemUnderTest("sut");
		runner.setXmlRpcRemoteRunner(xmlRpcRemoteRunner);
	}

	@Override
	protected void tearDown()
			throws Exception
	{
		super.tearDown();
	}

	public void testWithEmptySpecificationResultList()
			throws Exception
	{
		context.checking(new Expectations()
		{
			{
				one(xmlRpcRemoteRunner).getSpecificationHierarchy(with(any(Repository.class)), with(any(SystemUnderTest.class)));
				will(returnValue(new DocumentNode("test")));

				one(monitor).testRunning("repositoryId/a");
				one(monitor).testDone(0, 0, 0, 0);
			}
		});

		runner.run("a", "b");
	}

	public void testWithSpecificationHierarchyFailure()
			throws Exception
	{
		final Throwable exception = createException();

		context.checking(new Expectations()
		{
			{
				one(xmlRpcRemoteRunner).getSpecificationHierarchy(with(any(Repository.class)), with(any(SystemUnderTest.class)));
				will(throwException(exception));

				one(monitor).exceptionOccured(exception);
			}
		});

		runner.run("a", "b");
	}

	public void testASuccessfullExecution()
			throws Exception
	{
		final Execution execution = createExecution();
		final DocumentNode documentNode = createDocumentNode();

		context.checking(new Expectations()
		{
			{
				one(xmlRpcRemoteRunner).getSpecificationHierarchy(with(any(Repository.class)), with(any(SystemUnderTest.class)));
				will(returnValue(documentNode));

				one(monitor).testRunning("repositoryId/A");

				one(xmlRpcRemoteRunner).runSpecification("project", "sut", "repositoryId", "A", false, "en");
				will(returnValue(execution));

				one(reportGenerator).openReport("repositoryId-A");
				will(returnValue(report));

				one(report).generate(execution);

				one(monitor).testDone(4, 3, 2, 1);

				one(reportGenerator).closeReport(report);
			}
		});

		runner.run("a", "b");
	}

	private DocumentNode createDocumentNode()
	{
		final DocumentNode documentNode = new DocumentNode("test");

		DocumentNode childNodeA = new DocumentNode("A");
		childNodeA.setIsExecutable(true);

		documentNode.addChildren(childNodeA);
		return documentNode;
	}
}