text:
package cr_ee

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetRepoBuildRecordStatus invokes the cr.GetRepoBuildRecordStatus API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrecordstatus.html
func (client *Client) GetRepoBuildRecordStatus(request *GetRepoBuildRecordStatusRequest) (response *GetRepoBuildRecordStatusResponse, err error) {
	response = CreateGetRepoBuildRecordStatusResponse()
	err = client.DoAction(request, response)
	return
}

// GetRepoBuildRecordStatusWithChan invokes the cr.GetRepoBuildRecordStatus API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrecordstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildRecordStatusWithChan(request *GetRepoBuildRecordStatusRequest) (<-chan *GetRepoBuildRecordStatusResponse, <-chan error) {
	responseChan := make(chan *GetRepoBuildRecordStatusResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetRepoBuildRecordStatus(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetRepoBuildRecordStatusWithCallback invokes the cr.GetRepoBuildRecordStatus API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrecordstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildRecordStatusWithCallback(request *GetRepoBuildRecordStatusRequest, callback func(response *GetRepoBuildRecordStatusResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetRepoBuildRecordStatusResponse
		var err error
		defer close(result)
		response, err = client.GetRepoBuildRecordStatus(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetRepoBuildRecordStatusRequest is the request struct for api GetRepoBuildRecordStatus
type GetRepoBuildRecordStatusRequest struct {
	*requests.RpcRequest
	BuildRecordId string `position:"Query" name:"BuildRecordId"`
	RepoId        string `position:"Query" name:"RepoId"`
	InstanceId    string `position:"Query" name:"InstanceId"`
}

// GetRepoBuildRecordStatusResponse is the response struct for api GetRepoBuildRecordStatus
type GetRepoBuildRecordStatusResponse struct {
	*responses.BaseResponse
	GetRepoBuildRecordStatusIsSuccess bool   `json:"IsSuccess" xml:"IsSuccess"`
	Code                              string `json:"Code" xml:"Code"`
	RequestId                         string `json:"RequestId" xml:"RequestId"`
	BuildStatus                       string `json:"BuildStatus" xml:"BuildStatus"`
}

// CreateGetRepoBuildRecordStatusRequest creates a request to invoke GetRepoBuildRecordStatus API
func CreateGetRepoBuildRecordStatusRequest() (request *GetRepoBuildRecordStatusRequest) {
	request = &GetRepoBuildRecordStatusRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("cr", "2018-12-01", "GetRepoBuildRecordStatus", "acr", "openAPI")
	request.Method = requests.POST
	return
}

// CreateGetRepoBuildRecordStatusResponse creates a response to parse from GetRepoBuildRecordStatus response
func CreateGetRepoBuildRecordStatusResponse() (response *GetRepoBuildRecordStatusResponse) {
	response = &GetRepoBuildRecordStatusResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?php

namespace DABSquared\PushNotificationsBundle\Model;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use InvalidArgumentException;

use DABSquared\PushNotificationsBundle\Events;
use DABSquared\PushNotificationsBundle\Event\DeviceEvent;
use DABSquared\PushNotificationsBundle\Event\DevicePersistEvent;

/**
 * Created by JetBrains PhpStorm.
 * User: daniel_brooks
 * Date: 2/1/13
 * Time: 3:20 PM
 * To change this template use File | Settings | File Templates.
 */
abstract class DeviceManager implements DeviceManagerInterface
{

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    protected $dispatcher;

    /**
     * Constructor
     *
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
     */
    public function __construct(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * Creates an empty device instance
     *
     * @return Device
     */
    public function createDevice()
    {
        $class = $this->getClass();
        $device = new $class;

        $event = new DeviceEvent($device);
        $this->dispatcher->dispatch(Events::DEVICE_CREATE, $event);

        return $device;
    }

    /**
     * Saves a device to the persistence backend used. Each backend
     * must implement the abstract doSaveComment method which will
     * perform the saving of the comment to the backend.
     *
     * @param  DeviceInterface         $device
     * @throws InvalidArgumentException when the comment does not have a thread.
     */
    public function saveDevice(DeviceInterface $device)
    {
        if (null === $device->getDeviceToken()) {
            throw new InvalidArgumentException('The device must have a token');
        }

        $event = new DevicePersistEvent($device);
        $this->dispatcher->dispatch(Events::DEVICE_PRE_PERSIST, $event);

        if ($event->isPersistenceAborted()) {
            return;
        }

        $this->doSaveDevice($device);

        $event = new DeviceEvent($device);
        $this->dispatcher->dispatch(Events::DEVICE_POST_PERSIST, $event);
    }

    /**
     * Performs the persistence of a device.
     *
     * @abstract
     * @param DeviceInterface $device
     */
    abstract protected function doSaveDevice(DeviceInterface $device);

}

redpajama_set_name: RedPajamaGithub


text:
@implementation QBBaseAPI
@synthesize delegate = delegate_;

- (id) init {
    self = [super init];
    if(self) {
        baseWebService_ = [[QBWebService alloc] init];
        baseWebService_.delegate = self;
    }
    return self;
}

#pragma mark - Basewebservice delegate methods
- (void)didReceiveData:(QBBaseResponse *)responseObj {

}
- (void)didReceiveNetworkError:(NSString *)errorMessage{

}
- (void)didDataFetchFailWithError:(NSString *)errorMessage {

}

- (void)dealloc {
    baseWebService_.delegate = nil;
	[baseWebService_ release];
    if (delegate_)
		delegate_ = nil;
    [super dealloc];
}

@end


text:
"""This example shows how to use the OLED Click wrapper of the LetMeCreate library.

It displays some text for three seconds and then, it exits.

The OLED Click must be inserted in Mikrobus 1 before running this program.
In addition, the OLED Click must be configured to use I2C.
"""

from letmecreate.core.common import MIKROBUS_1
from letmecreate.core import i2c
from letmecreate.click import oled
import time

i2c.init()

oled.enable(MIKROBUS_1)
oled.write_text("Hello   Creator!")
time.sleep(3)
oled.disable()

i2c.release()


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Collections.Generic;

namespace Microsoft.CodeAnalysis.Remote
{
    internal interface IRemoteGlobalNotificationDeliveryService
    {
        void OnGlobalOperationStarted();

        void OnGlobalOperationStopped(IReadOnlyList<string> operations, bool cancelled);
    }
}


text:
/*global _:true*/
// Methods are exported explicitly at the end of this file.
var _ = require('underscore');

var users = {};
var last_id = 0;

var User = function User(data) {
	this.id = data.id || 0;
	this.name = data.name || "";
	this.email = data.email || "";
	this.password = data.password || "";
	return this;
};

var create_user = function create_user(params) {
	var user = new User(params);
	user.id = last_id = last_id + 1;
	users[last_id] = user;
	return user;
};

var read_user = function read_user(id) {
	var user = null;

	if (!id) {
		user = _.toArray(users);
	} else if (users[id]) {
		user = users[id];
	}

	return user;
};

var update_user = function update_user(id, params) {
	var user = read_user(id);

	if(!user || user.length) {
		return null;
	}

	user.name = params.name || user.name;
	user.email = params.email || user.email;
	user.password = params.password || user.password;

	return user;
};

var delete_user = function delete_user(id) {
	delete users[id];
	return true;
};

exports.create_user = create_user;
exports.read_user = read_user;
exports.update_user = update_user;
exports.delete_user = delete_user;


text:
package org.bson.codecs;

import org.bson.BsonBinaryReader;
import org.bson.BsonBinaryWriter;
import org.bson.BsonDocument;
import org.bson.BsonDocumentReader;
import org.bson.BsonDocumentWriter;
import org.bson.BsonType;
import org.bson.BsonValue;
import org.bson.BsonWriter;
import org.bson.ByteBufNIO;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.io.BasicOutputBuffer;
import org.bson.io.ByteBufferBsonInput;
import org.bson.io.OutputBuffer;

import java.nio.ByteBuffer;
import java.util.HashMap;

import static java.util.Arrays.asList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.junit.Assert.assertEquals;

abstract class CodecTestCase {

    DocumentCodecProvider getDocumentCodecProvider() {
        return new DocumentCodecProvider();
    }

    CodecRegistry getRegistry() {
        return fromProviders(asList(new ValueCodecProvider(), getDocumentCodecProvider()));
    }

    <T> T getDecodedValue(final BsonValue bsonValue, final Decoder<T> decoder) {
        BsonDocument document = new BsonDocument("val", bsonValue);
        BsonDocumentReader reader = new BsonDocumentReader(document);
        reader.readStartDocument();
        reader.readName("val");
        return decoder.decode(reader, DecoderContext.builder().build());
    }

    <T> BsonValue getEncodedValue(final T value, final Encoder<T> encoder) {
        BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
        writer.writeStartDocument();
        writer.writeName("val");
        encoder.encode(writer, value, EncoderContext.builder().build());
        writer.writeEndDocument();
        return writer.getDocument().get("val");
    }

    <T> void roundTrip(final T value) {
        roundTrip(value, new DefaultComparator<>(value));
    }

    <T> void roundTrip(final T value, final Comparator<T> comparator) {
        roundTripWithRegistry(value, comparator, getRegistry());
    }

    @SuppressWarnings("unchecked")
    <T> void roundTripWithRegistry(final T value, final Comparator<T> comparator, final CodecRegistry codecRegistry) {
        Codec<T> codec = (Codec<T>) codecRegistry.get(value.getClass());
        OutputBuffer encoded = encode(codec, value);
        T decoded = decode(codec, encoded);
        comparator.apply(decoded);
    }

    public void roundTrip(final Document input, final Document expected) {
        roundTrip(input, result -> assertEquals("Codec Round Trip", expected, result));
    }

    <T> OutputBuffer encode(final Codec<T> codec, final T value) {
        OutputBuffer buffer = new BasicOutputBuffer();
        BsonWriter writer = new BsonBinaryWriter(buffer);
        codec.encode(writer, value, EncoderContext.builder().build());
        return buffer;
    }

    <T> T decode(final Codec<T> codec, final OutputBuffer buffer) {
        BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO(ByteBuffer.wrap(buffer.toByteArray()))));
        return codec.decode(reader, DecoderContext.builder().build());
    }

    DocumentCodecProvider getSpecificNumberDocumentCodecProvider(final Class<? extends Number> clazz) {
        HashMap<BsonType, Class<?>> replacements = new HashMap<>();
        replacements.put(BsonType.DOUBLE, clazz);
        replacements.put(BsonType.INT32, clazz);
        replacements.put(BsonType.INT64, clazz);
        replacements.put(BsonType.DECIMAL128, clazz);
        return new DocumentCodecProvider(new BsonTypeClassMap(replacements));
    }

    interface Comparator<T> {
        void apply(T result);
    }

    class DefaultComparator<T> implements Comparator<T> {
        private final T original;

        DefaultComparator(final T original) {
            this.original = original;
        }

        @Override
        public void apply(final T result) {
            assertEquals("Codec Round Trip", original, result);
        }
    }

}


text:
<?php
namespace pyd\testkit\web\exceptions;

use pyd\testkit\AssertionMessage;

/**
 * Exception page displayed when a request is send with an unauthorized method
 * e.g. a request is sent with the GET method but only POST is allowed.
 *
 * @see yii\filters\VerbFilter::beforeAction()
 * @see yii\web\MethodNotAllowedHttpException
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class MethodNotAllowedPage extends Page
{
    /**
     * Verify that the current page is a 'method not allowed' exception page.
     *
     * @return boolean
     */
    public function isDisplayed()
    {
        if (parent::isDisplayed()) {

            if (false !== strpos($this->getMessage(), $this->getExpectedText())) {
                AssertionMessage::set("This is a Not Allowed Exception page.");
                return true;
            } else {
                AssertionMessage::set("This is not a Not Allowed Exception page.");
                return false;
            }

        } else {
            return false;
        }
    }

    /**
     * Extract the allowed method names from the exception message.
     *
     * @return array
     */
    public function getAllowedMethods()
    {
        $message = $this->getMessage();
        $sub = substr($message, strrpos($message, ':') + 1);
        $sub = rtrim($sub, '.');
        $sub = trim($sub);
        return explode(',', $sub);
    }

    /**
     * Return some text that should be present in the exception message to
     * identify this page as a 'method not allowed' exception page.
     *
     * @return string
     */
    public function getExpectedText()
    {
        return "Method Not Allowed";
    }
}


text:
/** Unit Test for AceUnit.
 * Yes, AceUnit can be tested using itself.
 * @author Christian Hujer
 * @file AceUnitTest.c
 */

#include <stdbool.h>
#include <stdio.h>

#include "AceUnitData.h"
#include "AceUnitTest.h"

A_Test void testAssertEquals(void)
{
    assertEqualsM("Expected failure.", 10, 20);
}

A_Test void testAssertNotEquals(void)
{
    assertNotEqualsM("Expected failure.", 10, 10);
}


text:
/*
 * TODO: CHECK IF pause() AND resume() ARE STILL WORKING ON ANDROID
 */

#pragma once

#include "cinder/app/AppNative.h"

#include "chronotext/cinder/CinderSketch.h"

namespace chronotext
{
    class CinderApp : public ci::app::AppNative
    {
    public:
        CinderSketch *sketch;

        CinderApp()
        :
        startCount(0),
        updateCount(0)
        {}

        void setup();
        void shutdown();
        void resize();

        void update();
        void draw();

        void mouseDown(ci::app::MouseEvent event);
        void mouseUp(ci::app::MouseEvent event);
        void mouseDrag(ci::app::MouseEvent event);

        void touchesBegan(ci::app::TouchEvent event);
        void touchesMoved(ci::app::TouchEvent event);
        void touchesEnded(ci::app::TouchEvent event);

        void accelerated(AccelEvent event);

        virtual void receiveMessageFromSketch(int what, const std::string &body) {}
        void sendMessageToSketch(int what, const std::string &body);

#if defined(CINDER_ANDROID)
        void pause();
        void resume(bool renewContext);
#endif

    protected:
        int startCount;
        int updateCount;

        int ticks;
        double t0;
        double elapsed;

        void start();
        void stop();
    };
}

namespace chr = chronotext;


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30205_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans21.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Continental
RESOURCES

    <p class="styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Continental Resources
McKenzie County, ND (NAD 83) Sec4-T152N-R99W Boulder 2-4H

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Wellbore #1 [#1522707

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Survey: Phoenix MWD Surveys

    <p class="styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Standard Survey Report
01 March, 2015

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">( P H 013 N IX TECHNOLOGY SERVICES


text:
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "rtcore_common.h"

RTC_NAMESPACE_BEGIN

/*
 * Structure for transformation respresentation as a matrix decomposition using
 * a quaternion
 */
struct RTC_ALIGN(16) RTCQuaternionDecomposition
{
  float scale_x;
  float scale_y;
  float scale_z;
  float skew_xy;
  float skew_xz;
  float skew_yz;
  float shift_x;
  float shift_y;
  float shift_z;
  float quaternion_r;
  float quaternion_i;
  float quaternion_j;
  float quaternion_k;
  float translation_x;
  float translation_y;
  float translation_z;
};

RTC_FORCEINLINE void rtcInitQuaternionDecomposition(struct RTCQuaternionDecomposition* qdecomp)
{
  qdecomp->scale_x = 1.f;
  qdecomp->scale_y = 1.f;
  qdecomp->scale_z = 1.f;
  qdecomp->skew_xy = 0.f;
  qdecomp->skew_xz = 0.f;
  qdecomp->skew_yz = 0.f;
  qdecomp->shift_x = 0.f;
  qdecomp->shift_y = 0.f;
  qdecomp->shift_z = 0.f;
  qdecomp->quaternion_r = 1.f;
  qdecomp->quaternion_i = 0.f;
  qdecomp->quaternion_j = 0.f;
  qdecomp->quaternion_k = 0.f;
  qdecomp->translation_x = 0.f;
  qdecomp->translation_y = 0.f;
  qdecomp->translation_z = 0.f;
}

RTC_FORCEINLINE void rtcQuaternionDecompositionSetQuaternion(
  struct RTCQuaternionDecomposition* qdecomp,
  float r, float i, float j, float k)
{
  qdecomp->quaternion_r = r;
  qdecomp->quaternion_i = i;
  qdecomp->quaternion_j = j;
  qdecomp->quaternion_k = k;
}

RTC_FORCEINLINE void rtcQuaternionDecompositionSetScale(
  struct RTCQuaternionDecomposition* qdecomp,
  float scale_x, float scale_y, float scale_z)
{
  qdecomp->scale_x = scale_x;
  qdecomp->scale_y = scale_y;
  qdecomp->scale_z = scale_z;
}

RTC_FORCEINLINE void rtcQuaternionDecompositionSetSkew(
  struct RTCQuaternionDecomposition* qdecomp,
  float skew_xy, float skew_xz, float skew_yz)
{
  qdecomp->skew_xy = skew_xy;
  qdecomp->skew_xz = skew_xz;
  qdecomp->skew_yz = skew_yz;
}

RTC_FORCEINLINE void rtcQuaternionDecompositionSetShift(
  struct RTCQuaternionDecomposition* qdecomp,
  float shift_x, float shift_y, float shift_z)
{
  qdecomp->shift_x = shift_x;
  qdecomp->shift_y = shift_y;
  qdecomp->shift_z = shift_z;
}

RTC_FORCEINLINE void rtcQuaternionDecompositionSetTranslation(
  struct RTCQuaternionDecomposition* qdecomp,
  float translation_x, float translation_y, float translation_z)
{
  qdecomp->translation_x = translation_x;
  qdecomp->translation_y = translation_y;
  qdecomp->translation_z = translation_z;
}

RTC_NAMESPACE_END


text:
package de.tu_berlin.cit.intercloud.occi.platform;

import de.tu_berlin.cit.intercloud.occi.core.annotations.Attribute;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Category;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Kind;
import de.tu_berlin.cit.intercloud.occi.core.annotations.Attribute.AttributeType;

/**
 * TODO
 *
 * @author Alexander Stanik <alexander.stanik@tu-berlin.de>
 * @author Daniel Thilo Schroeder <daniel.schroeder@mailbox.tu-berlin.de>
 */
@Kind(schema = PlatformSchemas.PlatformSchema, term = ComponentKind.ComponentTerm)
public class ComponentKind extends Category{

	public final static String ComponentTitle = "Component Resource";

	public final static String ComponentTerm = "component";

	public ComponentKind(){
		super(ComponentTitle);
	}

	public ComponentKind(String title){
		super(title);
	}

	public enum State {
		active,
		inactive,
		error
	}

	/**
	 * Current state of the component.
	 */
	@Attribute(name = "occi.component.state",
			type = AttributeType.ENUM,
			mutable = false,
			required = true,
			description = "current state of the component.")
	public State state = null;

	/**
	 * Human-readable explanation of the current instance state
	 */
	@Attribute(name = "occi.component.state.message",
			type = AttributeType.STRING,
			mutable = false,
			required = false,
			description = "Human-readable explanation of the current instance state")
	public String message = null;

}


text:
<?php

namespace MMiic\GeTui\Igetui\Reqs;

use MMiic\GeTui\Protobuf\Type\PBEnum;

class PushResult_EPushResult extends PBEnum
{
    const successed_online  = 0;
    const successed_offline  = 1;
    const successed_ignore  = 2;
    const failed  = 3;
    const busy  = 4;
    const success_startBatch  = 5;
    const success_endBatch  = 6;
}

?>


text:
package Views.Library.Menu.LibreryClass;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.linedeer.api.call;
import com.linedeer.player.Ui;
import com.player.playlistHandler;
import com.shape.Library.allsong.itemBack;
import com.shape.Library.allsong.itemRect;
import com.shape.home.menu.songDots;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import Views.ContentHome;
import Views.Popups.songsBtns;
import Views.api.FMText;
import Views.api.FMlyt;
import Views.api.ShapeView;
import Views.api.StringUtil;
import Views.radiusSqure;
import Views.textImg;

public class popupAdapter extends BaseAdapter {

    public ArrayList<String[]> data = new ArrayList<String[]>();
    public ArrayList<String[]> old = data;
    public HashMap<String, Integer> index = new HashMap<String, Integer>();
    public HashMap<String, Integer> oldIndex = index;
    public boolean[] selected;

    public popupAdapter(){
            String[] projection = {MediaStore.Audio.Playlists.Members.TITLE,MediaStore.Audio.Playlists.Members.AUDIO_ID,MediaStore.Audio.Playlists.Members.DURATION};
            Cursor cursor = Ui.ef.getContentResolver().query(
                MediaStore.Audio.Playlists.Members.getContentUri("external", Integer.parseInt(getId())), projection,
                MediaStore.Audio.Media.IS_MUSIC + " != 0 ", null,  MediaStore.Audio.Playlists.Members.PLAY_ORDER +" ASC");
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToNext();
                String str = cursor.getString(0);
                str = StringUtil.getFirstChar(str).toUpperCase();
                if(!str.equals("") && !index.containsKey(str)){
                    data.add(new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),str});
                    index.put(str,i);
                }else{
                    data.add(new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),""});
                }
            }
            cursor.close();
        selected = new boolean[data.size()];
    }

    public  String getId(){
        return " ";
    }

    public  String getName(){
        return "Error.";
    }

    public  String[] getAlbumData(){
        return null;
    }

    public int  getHeight(){
        return Ui.cd.DPH;
    }

    public int  getWidth(){
        return Ui.cd.DPW;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Item vm;
        if(convertView == null){
            vm = new Item(parent.getContext(),position);
        }else{
            vm = (Item) convertView;
            vm.setData(position);
        }
        return vm;
    }

    public void onMenu(){

    }

    public void onBack(){

    }

    public void  onSelect(){
        seclection = true;
    }

    boolean searching = false;
    public void searchData(String strStr){
        strStr = (""+strStr).toUpperCase();
        searching = true;
        data = new ArrayList<String[]>();
        index = new HashMap<String, Integer>();
        int length  = old.size();
        for (int i = 0; i < length; i++) {
            String str = old.get(i)[0];
            if(str.toUpperCase().contains(strStr)){
                str = StringUtil.getFirstChar(str).toUpperCase();
                if(!str.equals("") && !index.containsKey(str)){
                    data.add(old.get(i));
                    index.put(str,i);
                }else{
                    data.add(old.get(i));
                }
            }
        }
    }

    public void closeSearch(){
        searching = false;
        data = old;
        index = oldIndex;
    }

    boolean seclection = false;
    public int  getSelected(){
        int val = 0;
        for(int i = 0;i < selected.length;i++){
            if(selected[i]){
                val++;
            }
        }
        return val;
    }

    public void removeSelection(){
        seclection = false;
        int val = 0;
        for(int i = 0;i < selected.length;i++){
            selected[i] = false;
        }
    }

    public int[] getAIDs(){
        int[] AIDs = new int[data.size()];
        if(seclection){
            int count = 0;
            for(int a = 0;a < selected.length;a++){
                if(selected[0] == true){
                    count++;
                }
            }
            AIDs =  new int[count];
            count = 0;
            for(int a = 0;a < selected.length;a++){
                if(selected[0] == true){
                    AIDs[count] = Integer.parseInt(data.get(a)[1]);
                    count++;
                }
            }
        }else{
            for(int a = 0;a < selected.length;a++){
                AIDs[a] = Integer.parseInt(data.get(a)[1]);
            }
        }
        return AIDs;
    }
    public class Item extends FMlyt{

        public radiusSqure rSqure;
        public radiusSqure rtop;
        //FMText no;
        //FMText listName;
        textImg nameText;
        textImg noText;
        FMText artist;

        int position;

        public void setData(int position) {
            this.position = position;

            noText.setSize(0,0);
            noText.setText((position+1)+".");

           /* listName.setText(data.get(position)[0]);
            listName.setX(no.width + Ui.cd.getHt(5) + no.getX());
            if(width - Ui.cd.getHt(120) < listName.width){
                listName.setSize((int) (width - Ui.cd.getHt(100)),listName.height);
                listName.img.setEfects(new int[]{0x66FFFFFF,0x66FFFFFF,0x00FFFFFF});
            }else{
                listName.img.setColor(0x66FFFFFF);
            }*/
            nameText.setSize(0,0);
            nameText.setText(data.get(position)[0]);
            nameText.InCenter(0,height);
            nameText.setX((int) (noText.width + Ui.cd.getHt(5) + noText.getX()));

            noText.setY((int) nameText.y);
            if(width - Ui.cd.getHt(120) < nameText.width){
                nameText.setSize((int) (width - Ui.cd.getHt(100)), (int) nameText.height);
                nameText.setEfects(new int[]{0x66FFFFFF,0x66FFFFFF,0x00FFFFFF});
            }else{
                nameText.setColor(0x66FFFFFF);
            }

            if(selected[position]){
                rtop.setDrawing(true);
            }else{
                rtop.setDrawing(false);
            }

            invalidate();
        }

        Bitmap bm;
        Canvas cn;

        public Item(final Context context, final int Id) {
            super(context,popupAdapter.this.getWidth(), Ui.cd.getHt(44));
            setLayoutParams(new ListView.LayoutParams(width, Ui.cd.getHt(44)));
            setRipple(true,0.3f);
            setRippleDown(false);
            this.position = Id;

            //bm = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
            //cn = new Canvas(bm);

            setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                        if(selected[position]){
                            selected[position] = false;
                            rtop.setDrawing(false);
                        }else{
                            selected[position] = true;
                            rtop.setDrawing(true);
                        }

                        Item.this.invalidate();
                        onSelect();

                    return true;
                }
            });

            rSqure = new radiusSqure(width,height - Ui.cd.getHt(2),0,0,0);
            rSqure.setColor(itemRect.Color0);
            addShape(rSqure);

            rtop = new radiusSqure(width - Ui.cd.getHt(4),height - Ui.cd.getHt(2+4), Ui.cd.getHt(2), Ui.cd.getHt(2),0);
            rtop.setColor(0x99000000);
            rtop.setDrawing(false);
            addShape(rtop);

            final ShapeView menu = songDots.getFMview(context,true);
            menu.setRipple(true,0.3f);
            menu.setRippleDown(false);
            menu.setX(width - menu.width);

            menu.onClick(new call(){
                @Override
                public void onCall(boolean bl) {

                    onMenu();
                    final songsBtns mn = new songsBtns(context, Ui.cd.DPW, Ui.cd.DPH){
                        @Override
                        public void onSelect(String id) {
                            Ui.bk.back();
                            int Id = Integer.parseInt(id);
                            if(Id != -1){
                                playlistHandler.addTOPlaylistByID(Ui.ef.getContentResolver(),Id,new int[]{Integer.parseInt(data.get(position)[1])});
                            }
                            if(Id == Ui.ef.MusicPlayer.handler.playlist.id){
                                Ui.ef.MusicPlayer.handler.addSongs(new int[]{Integer.parseInt(data.get(position)[1])});
                            }
                        }

                        @Override
                        public void onBtn(String name) {
                            super.onBtn(name);
                            if(name.equals("PLAY ALL")){
                                Ui.ef.MusicPlayer.handler.playALlSong(0,getAIDs(),getName());
                                Ui.bk.back();
                            }else if(name.equals("ADD NEXT")) {

                                if (seclection) {
                                    Ui.ef.MusicPlayer.handler.addSongsNext(getAIDs());
                                } else{
                                    Ui.ef.MusicPlayer.handler.addSongsNext(new int[]{Integer.parseInt(data.get(position)[1])});
                                }
                                Ui.bk.back();

                            }else if(name.equals("SHOW FILE")){
                                Ui.bk.back();
                                Ui.bk.back();
                                Ui.bk.add(new call(){
                                    @Override
                                    public void onCall(boolean bl) {
                                        ContentHome.This.MenuHome.goingBack();
                                        ContentHome.This.MenuHome.openPage(0);
                                        ContentHome.This.MenuHome.drawCatch();
                                        final  songsPopup mn = new songsPopup(context, Ui.cd.DPW, Ui.cd.DPH,getAlbumData());
                                        ContentHome.This.addPopup(mn);
                                        mn.setClickable(true);
                                        Ui.bk.add(new call() {
                                            @Override
                                            public void onCall(boolean bl) {
                                                ContentHome.This.removePopup(mn);
                                                ContentHome.This.MenuHome.setVisibility(VISIBLE);
                                                ContentHome.This.MenuHome.removeCatch();
                                                ContentHome.This.MenuHome.setAlpha(1,true);
                                            }
                                        });
                                    }
                                });
                                String path = getAudiopath(Integer.parseInt(data.get(position)[1]));
                                ContentHome.This.MenuHome.openFolder(path);
                            }else if(name.equals("SHARE")){
                                Ui.bk.back();
                                String myFilePath = getAudiopath(Integer.parseInt(data.get(position)[1]));
                                Intent intentShareFile = new Intent(Intent.ACTION_SEND);
                                File fileWithinMyDir = new File(myFilePath);

                                if(fileWithinMyDir.exists()) {
                                    intentShareFile.setType("application/pdf");
                                    intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+myFilePath));
                                    intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing File...");
                                    intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");
                                    Ui.ef.startActivity(Intent.createChooser(intentShareFile, "Share File"));
                                }
                            }
                        }
                    };
                    //ContentHome.This.MenuHome.drawCatch();
                    ContentHome.This.addPopup(mn);
                    mn.setClickable(true);
                    Ui.bk.add(new call() {
                        @Override
                        public void onCall(boolean bl) {
                            ContentHome.This.removePopup(mn);
                           // ContentHome.This.MenuHome.removeCatch();
                            onBack();
                        }
                    });
                }
            });
            addView(menu);

            noText = textImg.getText((position+1)+".", Ui.cd.getHtF(14));
            noText.setX(Ui.cd.getHt(10));
            noText.setColor(0x33FFFFFF);
            addShape(noText);

            nameText = textImg.getText(data.get(position)[0], Ui.cd.getHtF(16));
            nameText.InCenter(0,height);
            nameText.setX((int) (noText.width + Ui.cd.getHt(5) + noText.getX()));
            noText.setY((int) nameText.y);
            if(width - Ui.cd.getHt(120) < nameText.width){
                nameText.setSize((int) (width - Ui.cd.getHt(100)), (int) nameText.height);
                nameText.setEfects(new int[]{0x66FFFFFF,0x66FFFFFF,0x00FFFFFF});
            }else{
                nameText.setColor(0x66FFFFFF);
            }
            addShape(nameText);

                setBackgroundColor(itemBack.Color0);

            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Ui.ef.clickPlay();
                   //Ui.ef.MusicPlayer.handler.playByPlaylistName("ok");
                    if(seclection){
                        if(selected[position]){
                            selected[position] = false;
                            rtop.setDrawing(false);
                        }else{
                            rtop.setDrawing(true);
                            selected[position] = true;
                        }
                        Item.this.invalidate();
                        onSelect();
                    }else{
                        Ui.ef.MusicPlayer.handler.playByPlaylistId(popupAdapter.this.getId(),position);
                    }

                }
            });

        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.drawShape(canvas);
            super.postDraw(canvas);
            super.afterDraw(canvas,rSqure.S0);

        }

    }

    public String getAudiopath(int Id) {
        String[] projection = { MediaStore.Audio.Media.DATA };
        Cursor DataCursor = Ui.ef.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection,
                MediaStore.Audio.Media._ID + " = " + Id, null, null);

        DataCursor.moveToNext();
        String audioPath = DataCursor.getString(0);
        DataCursor.close();
        return audioPath;
    }

}


text:
#ifndef PETABRICKSSYNTHETICRULE_H
#define PETABRICKSSYNTHETICRULE_H

#include "rule.h"

namespace petabricks {

/**
 * Provides reasonable no-op defaults for RuleInterface (base class for synthetic rules)
 */
class SyntheticRule : public RuleInterface {
public:
  void initialize(Transform&);
  void compileRuleBody(Transform& tx, RIRScope& s);
  void performExpansion(Transform&){}

  RuleFlags::PriorityT priority() const;
  bool isRecursive() const;
  bool hasCellAccess() const;
  bool hasCellAccess(const std::string& matrix) const;
  bool hasWhereClause() const;
  FormulaPtr getWhereClause() const;

  std::string getLabel() const;

  virtual void trimDependency(DependencyDirection& ,
                              const ChoiceDepGraphNode& ,
                              const ChoiceDepGraphNode& ){}

  bool canProvide(const MatrixDefPtr& m) const;

  void getApplicableRegionDescriptors(RuleDescriptorList& output,
                                      const MatrixDefPtr& matrix, int dimension, const RulePtr&);

//void generateCallCode(const std::string& nodename,
//                      Transform& trans,
//                      CodeGenerator& o,
//                      const SimpleRegionPtr& region,
//                      RuleFlavor flavor,
//                      std::vector<RegionNodeGroup>& regionNodesGroups,
//                      int nodeID,
//                      int gpuCopyOut,
//                      SpatialCallType spatialCallType);
//
  void virtual generateDeclCode(Transform& trans, CodeGenerator& o, RuleFlavor);
  void virtual generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor) = 0;
  void virtual generatePartialTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor);

  void markRecursive();
  void markHasCellAccess(const std::string& matrix);
  const FormulaPtr& recursiveHint() const;

  void print(std::ostream& os) const;

  int dimensions() const { UNIMPLEMENTED(); return 0; }
  FormulaPtr getSizeOfRuleIn(int) { UNIMPLEMENTED(); return 0; }
  void generateTrampCellCodeSimple(Transform&, CodeGenerator&, RuleFlavor) {
    UNIMPLEMENTED();
  }

};

/**
 * Base class for synthetic rules that wrap other rules
 * provides default implementations that forward to _rule
 */
class WrapperSyntheticRule : public SyntheticRule {
public:
  WrapperSyntheticRule(const RulePtr& rule)
    : _rule(rule)
  {
    _applicableRegion = _rule->applicableRegion();
  }

  //these just forward to _rule
  void generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor);

  void generateCallCode(const std::string& nodename,
                        Transform& trans,
                        CodeGenerator& o,
                        const SimpleRegionPtr& region,
                        RuleFlavor flavor,
			bool wrap,
                        std::vector<RegionNodeGroup>& regionNodesGroups,
                        int nodeID,
                        int gpuCopyOut,
                        SpatialCallType spatialCallType=SpatialCallTypes::INVALID);

  void generatePartialTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf);

  bool isSingleElement() const;
  int dimensions() const;
  FormulaPtr getSizeOfRuleIn(int d);
  void collectDependencies(StaticScheduler& scheduler);
  DependencyDirection getSelfDependency() const;
  petabricks::RuleFlags::PriorityT priority() const;
  bool isRecursive() const;
  bool hasWhereClause() const;
  petabricks::FormulaPtr getWhereClause() const;
  bool canProvide(const MatrixDefPtr& md) const;
  void getApplicableRegionDescriptors(RuleDescriptorList& rdl, const MatrixDefPtr& md, int i, const RulePtr&);
  const petabricks::FormulaPtr& recursiveHint() const;
protected:
  RulePtr _rule;
};

///
///combines multiple rules with where clauses
class WhereExpansionRule : public SyntheticRule {
public:
  WhereExpansionRule(const RuleSet& rules)
    : _rules(rules)
  {}

  void generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf);

  void generateCallCode(const std::string& nodename,
                        Transform& trans,
                        CodeGenerator& o,
                        const SimpleRegionPtr& region,
                        RuleFlavor flavor,
			bool wrap,
                        std::vector<RegionNodeGroup>& regionNodesGroups,
                        int nodeID,
                        int gpuCopyOut,
                        SpatialCallType spatialCallType=SpatialCallTypes::INVALID);

  bool isSingleElement() const;

  int dimensions() const;
  FormulaPtr getSizeOfRuleIn(int d);

  std::string codename() const;

  void collectDependencies(StaticScheduler& scheduler);

  void genWhereSwitch(Transform& trans, CodeGenerator& o, RuleFlavor rf);

  DependencyDirection getSelfDependency() const;
private:
  RuleSet _rules;
};

///
/// duplicate a rule that has a duplicate keyword
class DuplicateExpansionRule : public WrapperSyntheticRule {
public:
  DuplicateExpansionRule(const RulePtr& rule, size_t dup)
    : WrapperSyntheticRule(rule), _dup(dup)
  {
    JASSERT(_rule && dup<_rule->duplicateCount());
  }

  ///
  /// calls setDuplicateNumber() then forwards the call to _rule
  void generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor);

  void generateCallCode(const std::string& nodename,
                        Transform& trans,
                        CodeGenerator& o,
                        const SimpleRegionPtr& region,
                        RuleFlavor flavor,
			bool wrap,
                        std::vector<RegionNodeGroup>& regionNodesGroups,
                        int nodeID,
                        int gpuCopyOut,
                        SpatialCallType spatialCallType=SpatialCallTypes::INVALID);

  void generatePartialTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf);
private:
  size_t _dup;
};

///
///combines multiple rules that must be called together
class CallInSequenceRule : public SyntheticRule {
public:
  CallInSequenceRule(const RuleList& rules)
    : _rules(rules)
  {}

  void generateTrampCode(Transform& trans, CodeGenerator& o, RuleFlavor rf);

  void generateCallCode(const std::string& nodename,
                        Transform& trans,
                        CodeGenerator& o,
                        const SimpleRegionPtr& region,
                        RuleFlavor flavor,
			bool wrap,
                        std::vector<RegionNodeGroup>& regionNodesGroups,
                        int nodeID,
                        int gpuCopyOut,
                        SpatialCallType spatialCallType=SpatialCallTypes::INVALID);

  bool isSingleElement() const;

  int dimensions() const;
  FormulaPtr getSizeOfRuleIn(int d);

  std::string codename() const;

  void collectDependencies(StaticScheduler& scheduler);

  void genWhereSwitch(Transform& trans, CodeGenerator& o);

  DependencyDirection getSelfDependency() const;
private:
  RuleList _rules;
};

}

#endif


text:
/*
 * CheckMacros.h
 *
 *  Created on: Dec 15, 2009
 *      Author: gareth
 */

//
// DGW hacked version of UnitTest++ CheckMacros.h
//
// NB uses the same #ifndef so replaces the official header
//
#ifndef UNITTEST_CHECKMACROS_H
#define UNITTEST_CHECKMACROS_H

#include <UnitTest++/Checks.h>
#include <UnitTest++/AssertException.h>
#include <UnitTest++/MemoryOutStream.h>
#include <UnitTest++/TestDetails.h>
#include <UnitTest++/CurrentTest.h>

#include <iostream>

//#include "Checks.h"
//#include "AssertException.h"
//#include "MemoryOutStream.h"
//#include "TestDetails.h"
//#include "CurrentTest.h"

#ifdef CHECK
    #error UnitTest++ redefines CHECK
#endif

#ifdef CHECK_EQUAL
	#error UnitTest++ redefines CHECK_EQUAL
#endif

#ifdef CHECK_CLOSE
	#error UnitTest++ redefines CHECK_CLOSE
#endif

#ifdef CHECK_ARRAY_EQUAL
	#error UnitTest++ redefines CHECK_ARRAY_EQUAL
#endif

#ifdef CHECK_ARRAY_CLOSE
	#error UnitTest++ redefines CHECK_ARRAY_CLOSE
#endif

#ifdef CHECK_ARRAY2D_CLOSE
	#error UnitTest++ redefines CHECK_ARRAY2D_CLOSE
#endif

#define CHECK(value) \
    do \
    { \
        try { \
            if (!UnitTest::Check(value)) \
                UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), #value); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK(" #value ")"); \
        } \
    } while (0)

#define CHECK_EQUAL(expected, actual) \
    do \
    { \
        try { \
            UnitTest::CheckEqual(*UnitTest::CurrentTest::Results(), expected, actual, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_EQUAL(" #expected ", " #actual ")"); \
        } \
    } while (0)

#define CHECK_CLOSE(expected, actual, tolerance) \
    do \
    { \
        try { \
            UnitTest::CheckClose(*UnitTest::CurrentTest::Results(), expected, actual, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (UnitTest::AssertException) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "AssertException in CHECK_CLOSE(" #expected ", " #actual ")"); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_CLOSE(" #expected ", " #actual ")"); \
        } \
    } while (0)

#define CHECK_ARRAY_EQUAL(expected, actual, count) \
    do \
    { \
        try { \
            UnitTest::CheckArrayEqual(*UnitTest::CurrentTest::Results(), expected, actual, count, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_ARRAY_EQUAL(" #expected ", " #actual ")"); \
        } \
    } while (0)

#define CHECK_ARRAY_CLOSE(expected, actual, count, tolerance) \
    do \
    { \
        try { \
            UnitTest::CheckArrayClose(*UnitTest::CurrentTest::Results(), expected, actual, count, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_ARRAY_CLOSE(" #expected ", " #actual ")"); \
        } \
    } while (0)

#define CHECK_ARRAY2D_CLOSE(expected, actual, rows, columns, tolerance) \
    do \
    { \
        try { \
            UnitTest::CheckArray2DClose(*UnitTest::CurrentTest::Results(), expected, actual, rows, columns, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_ARRAY_CLOSE(" #expected ", " #actual ")"); \
        } \
    } while (0)

// DGW. Hacked to print a message when an exception is caught.
#define CHECK_THROW(expression, ExpectedExceptionType) \
    do \
    { \
        bool caught_ = false; \
        try { expression; } \
        catch (ExpectedExceptionType const&) { caught_ = true; } \
        catch (...) {} \
        if (caught_) { std::cout << "CHECK_THROW: Exception caught" << std::endl; } \
        if (!caught_) \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), "Expected exception: \"" #ExpectedExceptionType "\" not thrown"); \
    } while(0)

#define CHECK_ASSERT(expression) \
    CHECK_THROW(expression, UnitTest::AssertException);

// DGW
#if 0
template< typename Expected, typename Actual >
void CheckGreater(TestResults& results, Expected const& expected, Actual const& actual, TestDetails const& details)
{
    if (!(actual > expected))
    {
        UnitTest::MemoryOutStream stream;
        stream << "Expected >" << expected << " but was " << actual;

        results.OnTestFailure(details, stream.GetText());
    }
}

#define CHECK_GREATER(expected, actual) \
    do \
    { \
        try { \
            UnitTest::CheckGreater(*UnitTest::CurrentTest::Results(), expected, actual, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
        } \
        catch (...) { \
            UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
                    "Unhandled exception in CHECK_EQUAL(" #expected ", " #actual ")"); \
        } \
    } while (0)
#endif

#endif /* UNITTEST_CHECKMACROS_H */


text:
class TLD_device;
// a simple device that puts Button widgets on the simulated display
// the color can be read and changed, whereupon the display changes.

class TLD_device : public Device_base {
public:
	TLD_device(const std::string& id, Output_tee& ot);

	virtual void initialize();
	virtual void handle_Start_event();
	virtual void handle_Point_event(const Symbol& target_name);
	virtual void handle_Click_event(const Symbol& button_name);
	virtual void handle_Delay_event(const Symbol& type, const Symbol& datum,
		const Symbol& object_name, const Symbol& property_name, const Symbol& property_value);
private:
	Smart_Pointer<Screen_widget> screen_ptr;
	// a container of pointers to buttons
	typedef std::map<Symbol, Smart_Pointer<Button_widget> > buttons_t;
	buttons_t buttons;
	Smart_Pointer<Cursor_widget> cursor_ptr;

	Smart_Pointer<Object_widget> blip_ptr;	// at most one Blip can exist at a time
	int blip_counter;	// counts the number of time a blip was clicked on

	Symbol current_pointed_to_object_name;	// holds name of current button pointed to

	void create_initial_display();
	void create_button(TLD_device * dev_ptr, const Symbol& name, GU::Point location, const Symbol& label, bool state);

	void clear_display();
	void output_display() const;

};

#endif


text:
<?php

App::uses('DispatcherFilter', 'Routing');

/**
 * Filters a request and tests whether it is a file in the webroot folder or not and
 * serves the file to the client if appropriate.
 *
 * @package Cake.Routing.Filter
 */
class AssetDispatcher extends DispatcherFilter {

/**
 * Default priority for all methods in this filter
 * This filter should run before the request gets parsed by router
 *
 * @var integer
 */
	public $priority = 9;

/**
 * Checks if a requested asset exists and sends it to the browser
 *
 * @param CakeEvent $event containing the request and response object
 * @return CakeResponse if the client is requesting a recognized asset, null otherwise
 */
	public function beforeDispatch(CakeEvent $event) {
		$url = urldecode($event->data['request']->url);
		if (strpos($url, '..') !== false || strpos($url, '.') === false) {
			return;
		}

		if ($result = $this->_filterAsset($event)) {
			$event->stopPropagation();
			return $result;
		}

		$assetFile = $this->_getAssetFile($url);
		if ($assetFile === null || !file_exists($assetFile)) {
			return null;
		}

		$response = $event->data['response'];
		$event->stopPropagation();

		$response->modified(filemtime($assetFile));
		if ($response->checkNotModified($event->data['request'])) {
			return $response;
		}

		$pathSegments = explode('.', $url);
		$ext = array_pop($pathSegments);
		$this->_deliverAsset($response, $assetFile, $ext);
		return $response;
	}

/**
 * Checks if the client is requesting a filtered asset and runs the corresponding
 * filter if any is configured
 *
 * @param CakeEvent $event containing the request and response object
 * @return CakeResponse if the client is requesting a recognized asset, null otherwise
 */
	protected function _filterAsset(CakeEvent $event) {
		$url = $event->data['request']->url;
		$response = $event->data['response'];
		$filters = Configure::read('Asset.filter');
		$isCss = (
			strpos($url, 'ccss/') === 0 ||
			preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url)
		);
		$isJs = (
			strpos($url, 'cjs/') === 0 ||
			preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
		);

		if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
			$response->statusCode(404);
			return $response;
		}

		if ($isCss) {
			include WWW_ROOT . DS . $filters['css'];
			return $response;
		}

		if ($isJs) {
			include WWW_ROOT . DS . $filters['js'];
			return $response;
		}
	}

/**
 * Builds asset file path based off url
 *
 * @param string $url
 * @return string Absolute path for asset file
 */
	protected function _getAssetFile($url) {
		$parts = explode('/', $url);
		if ($parts[0] === 'theme') {
			$themeName = $parts[1];
			unset($parts[0], $parts[1]);
			$fileFragment = implode(DS, $parts);
			$path = App::themePath($themeName) . 'webroot' . DS;
			return $path . $fileFragment;
		}

		$plugin = Inflector::camelize($parts[0]);
		if ($plugin && CakePlugin::loaded($plugin)) {
			unset($parts[0]);
			$fileFragment = implode(DS, $parts);
			$pluginWebroot = CakePlugin::path($plugin) . 'webroot' . DS;
			return $pluginWebroot . $fileFragment;
		}
	}

/**
 * Sends an asset file to the client
 *
 * @param CakeResponse $response The response object to use.
 * @param string $assetFile Path to the asset file in the file system
 * @param string $ext The extension of the file to determine its mime type
 * @return void
 */
	protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) {
		ob_start();
		$compressionEnabled = Configure::read('Asset.compress') && $response->compress();
		if ($response->type($ext) == $ext) {
			$contentType = 'application/octet-stream';
			$agent = env('HTTP_USER_AGENT');
			if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
				$contentType = 'application/octetstream';
			}
			$response->type($contentType);
		}
		if (!$compressionEnabled) {
			$response->header('Content-Length', filesize($assetFile));
		}
		$response->cache(filemtime($assetFile));
		$response->send();
		ob_clean();
		if ($ext === 'css' || $ext === 'js') {
			include $assetFile;
		} else {
			readfile($assetFile);
		}

		if ($compressionEnabled) {
			ob_end_flush();
		}
	}

}


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

<title>R-Index</title>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M N O P R S T U V W Z

R

read() - Method in class nxt.util.CountingInputStream

read(byte[], int, int) - Method in class nxt.util.CountingInputStream

remove() - Method in interface nxt.peer.Peer

remove() - Method in class nxt.util.DbIterator

RemoveActivePeer - Class in nxt.user

RemoveBlacklistedPeer - Class in nxt.user

removeExceptionListener(Listener<Exception>, Logger.Event) - Static method in class nxt.util.Logger

RemoveKnownPeer - Class in nxt.user

removeListener(Listener<Account>, Account.Event) - Static method in class nxt.Account

removeListener(Listener<Generator>, Generator.Event) - Static method in class nxt.Generator

removeListener(Listener<Peer>, Peers.Event) - Static method in class nxt.peer.Peers

removeListener(Listener<T>, Enum<E>) - Method in class nxt.util.Listeners

removeListener(Listener<T>, E) - Method in interface nxt.util.Observable

removeMessageListener(Listener<String>, Logger.Event) - Static method in class nxt.util.Logger

runBeforeStart(Runnable) - Static method in class nxt.util.ThreadPool

A B C D E F G H I J L M N O P R S T U V W Z

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package org.bitbucket.ioplus.clblas;

/**
 * Created by przemek on 24/08/15.
 */
public class Level2 {

    /**
     * Matrix-vector product with a general rectangular matrix and float elements.
     * Matrix-vector products:

     * \( y \leftarrow \alpha A x + \beta y \)
     * \( y \leftarrow \alpha A^T x + \beta y \)
     *
     * @param order BlasOrder.ROW_MAJOR|COLUMN_MAJOR
     * @param transA How matrix A is to be transposed: BlasTrans.NO_TRANS|TRANS|CONJ_TRANS.
     * @param M Number of rows in matrix A.
     * @param N Number of columns in matrix A.
     * @param alpha The factor of matrix A.
     * @param A Buffer object storing matrix A.
     * @param lda Leading dimension of matrix A. It cannot be less than N if ROW_MAJOR.
     * @param x Buffer object storing vector x.
     * @param beta The factor of the vector y.
     * @param y Buffer object storing the vector y.
     **/
    public static int sgemv(BlasOrder order,
                            BlasTrans transA,
                             int M,
                             int N,
                             float alpha,
                             final float[] A,
                             int lda,
                             final float[] x,
                             float beta,
                             float[] y){
        return BLAS.sgemv(
                order.ordinal(),
                transA.ordinal(),
                M, N,
                alpha, A, 0, lda, x, 0, 1, beta, y, 0, 1);
    }

    /**
     * vector-vector product with double elements and performs the rank 1 operation A

     * Vector-vector products:

     *   \( A \leftarrow \alpha X Y^T + A \)
     *
     * @param order BlasOrder.ROW_MAJOR|COLUMN_MAJOR
     * @param M Number of rows in matrix A.
     * @param N Number of columns in matrix A.
     * @param alpha specifies the scalar alpha.
     * @param X Buffer object storing vector X.
     * @param Y Buffer object storing vector Y.
     * @param A Buffer object storing matrix A. On exit, A is overwritten by the updated matrix.
     * @param lda Leading dimension of matrix A. It cannot be less than N.
     **/
    public static int sger(BlasOrder order,
                           int M,
                            int N,
                            float alpha,
                            final float[] X,
                            final float[] Y,
                            float[] A,
                            int lda){
        return BLAS.sger(BlasOrder.ROW_MAJOR.ordinal(),
                M, N, alpha, X, 0, 1, Y, 0, 1, A, 0, lda);
    }

}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.util.html;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

public class HtmlLineSplitterTest {

	@Test
	public void testSplitWithMaxRetainLeadingSpacesWithSpacesAtFront() {
		String text = "              Heeey mom!  Look, no hands";
		List<String> lines = HtmlLineSplitter.split(text, 21, true);
		assertEquals(2, lines.size());
		assertEquals("              Heeey ", lines.get(0));
		assertEquals("mom!  Look, no hands", lines.get(1));
	}

	@Test
	public void testSplitWithMaxRetainLeadingSpacesWithSpacesInMiddle() {
		String text = "Heeey mom!                Look, no hands";
		List<String> lines = HtmlLineSplitter.split(text, 21, true);

		assertEquals(2, lines.size());
		assertEquals("Heeey mom!          ", lines.get(0));
		assertEquals("      Look, no hands", lines.get(1));
	}

	@Test
	public void testSplitNoMaxWithNewlines() {
		List<String> lines = HtmlLineSplitter.split("abc\ndef", 0);
		assertEquals(2, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("def", lines.get(1));
	}

	@Test
	public void testSplitNoMaxWithContiguousNewlinesInMiddle() {
		List<String> lines = HtmlLineSplitter.split("abc\n\ndef", 0);
		assertEquals(3, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("", lines.get(1));
		assertEquals("def", lines.get(2));

		lines = HtmlLineSplitter.split("abc\n\n\ndef", 0);
		assertEquals(4, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("", lines.get(1));
		assertEquals("", lines.get(2));
		assertEquals("def", lines.get(3));
	}

	@Test
	public void testSplitNoMaxWithContiguousNewlinesAtEnd() {

		List<String> lines = HtmlLineSplitter.split("abcdef\n\n", 0);
		assertEquals(3, lines.size());
		assertEquals("abcdef", lines.get(0));
		assertEquals("", lines.get(1));
		assertEquals("", lines.get(2));

		lines = HtmlLineSplitter.split("abcdef\n\n\n", 0);
		assertEquals(4, lines.size());
		assertEquals("abcdef", lines.get(0));
		assertEquals("", lines.get(1));
		assertEquals("", lines.get(2));
		assertEquals("", lines.get(3));
	}

	@Test
	public void testSplitNoMaxWithoutNewlines() {
		List<String> lines = HtmlLineSplitter.split("abcdef", 0);
		assertEquals(1, lines.size());
		assertEquals("abcdef", lines.get(0));
	}

	@Test
	public void testSplitWithMaxWithNewlines() {
		// length below max
		List<String> lines = HtmlLineSplitter.split("abc\ndef", 100);
		assertEquals(2, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("def", lines.get(1));

		// past max; newlines less than max
		lines = HtmlLineSplitter.split("abc\ndef", 5);
		assertEquals(2, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("def", lines.get(1));

		// past max; newlines larger than max (splits on newlines only; no other whitespace
		// upon which to split)
		lines = HtmlLineSplitter.split("abcdefg\nh", 5);
		assertEquals(2, lines.size());
		assertEquals("abcdefg", lines.get(0));
		assertEquals("h", lines.get(1));
	}

	@Test
	public void testSplitWithMaxWithoutNewlines() {
		// single string--no whitespace or newlines upon which to split
		List<String> lines = HtmlLineSplitter.split("abcdefghi", 3);
		assertEquals(1, lines.size());
		assertEquals("abcdefghi", lines.get(0));
	}

	@Test
	public void testSplitWithMaxWithSpaceAtEnd() {
		// The word is long enough to force a hard split on the first 'n' characters.  The
		// space at the end allows the remaining 'word' to be kept intact.
		List<String> lines = HtmlLineSplitter.split("abcdefghijklm ", 3);
		assertEquals(2, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("defghijklm", lines.get(1));
	}

	@Test
	public void testSplitWithMaxAtMaxWithSpacesAtEnd() {
		// The word is long enough to force a hard split on the first 'n' characters.  The
		// space at the end allows the remaining 'word' to be kept intact.
		List<String> lines = HtmlLineSplitter.split("abc        ", 3);
		assertEquals(1, lines.size());
		assertEquals("abc", lines.get(0));
	}

	@Test
	public void testSplitWithMaxWhitespaceAsPartOfMaxWithSpaceAtEnd() {
		// The word is long enough to force a hard split on the first 'n' characters.  The
		// space at the end allows the remaining 'word' to be kept intact.
		List<String> lines = HtmlLineSplitter.split("ab   c     ", 6);
		assertEquals(2, lines.size());
		assertEquals("ab", lines.get(0));
		assertEquals("c", lines.get(1));
	}

	@Test
	public void testSplitWithoutMaxNewlineAtBeginningAndEndOnly() {
		List<String> lines = HtmlLineSplitter.split("\nabcdefghi\n", 0);
		assertEquals(3, lines.size());
		assertEquals("", lines.get(0));
		assertEquals("abcdefghi", lines.get(1));
		assertEquals("", lines.get(2));
	}

	@Test
	public void testSplitWithMaxNewlineAtBeginningAndEndOnly() {
		// newlines at begin and end do not create lines; no whitespace--max is below
		// MAX_WORD_LENGTH, so single line only
		List<String> lines = HtmlLineSplitter.split("\nabcdefghi\n", 4);
		assertEquals(3, lines.size());
		assertEquals("", lines.get(0));
		assertEquals("abcdefghi", lines.get(1));
		assertEquals("", lines.get(2));
	}

	@Test
	public void testSplitWithMaxNewlineAtBeginningAndMiddleAndEndOnly() {
		// newlines at begin and end do not create lines; no whitespace--max is below
		// MAX_WORD_LENGTH, so single line only
		List<String> lines = HtmlLineSplitter.split("\nabcd\nefghi\n", 6);
		assertEquals(4, lines.size());
		assertEquals("", lines.get(0));
		assertEquals("abcd", lines.get(1));
		assertEquals("efghi", lines.get(2));
		assertEquals("", lines.get(3));
	}

	@Test
	public void testSplitWithMultipleTrailingNewlines() {
		// newlines at begin and end do not create lines; no whitespace--max is below
		// MAX_WORD_LENGTH, so single line only
		List<String> lines = HtmlLineSplitter.split("\naa\n\nbb\n\n\n", 100);
		assertEquals(7, lines.size());
		assertEquals("", lines.get(0));
		assertEquals("aa", lines.get(1));
		assertEquals("", lines.get(2));
		assertEquals("bb", lines.get(3));
		assertEquals("", lines.get(4));
		assertEquals("", lines.get(5));
		assertEquals("", lines.get(6));
	}

	@Test
	public void testSplitWithMultipleTrailingNewlines2() {
		// newlines at begin and end do not create lines; no whitespace--max is below
		// MAX_WORD_LENGTH, so single line only
		List<String> lines = HtmlLineSplitter.split("\naa\n\n", 100);
		assertEquals(4, lines.size());
		assertEquals("", lines.get(0));
		assertEquals("aa", lines.get(1));
		assertEquals("", lines.get(2));
		assertEquals("", lines.get(3));
	}

	@Test
	public void testSplitWithNoMaxWithMultipleNewlinesOnly() {
		// newlines at begin and end do not create lines; no whitespace--max is below
		// MAX_WORD_LENGTH, so single line only
		List<String> lines = HtmlLineSplitter.split("\n\n\n", 100);
		assertEquals(4, lines.size());
	}

	@Test
	public void testSplitWithMaxWithSpacesLessThanMax() {
		// the split routine will look backwards for a space.  So, we get one line shorter than
		// the requested max and one line longer
		List<String> lines = HtmlLineSplitter.split("abcd efghijklmnopq", 8);
		assertEquals(2, lines.size());
		assertEquals("abcd", lines.get(0));
		assertEquals("efghijklmnopq", lines.get(1));
	}

	@Test
	public void testSplitWithMaxWithSpacesGreaterThanMax() {
		// the split routine will look  forwards for a space.  It will split on this space
		List<String> lines = HtmlLineSplitter.split("abcdefg hijklmnopq", 3);
		assertEquals(2, lines.size());
		assertEquals("abcdefg", lines.get(0));
		assertEquals("hijklmnopq", lines.get(1));
	}

	@Test
	public void testSplitWithMaxWithSpacesFarAwayFromMax() {
		// the split routine will look  forwards for a space.  It will split on this space
		List<String> lines = HtmlLineSplitter.split("abcdefg hijklmnopq", 3);
		assertEquals(2, lines.size());
		assertEquals("abcdefg", lines.get(0));
		assertEquals("hijklmnopq", lines.get(1));
	}

	@Test
	public void testSplitWithMaxRetainBlankLines() {
		List<String> lines = HtmlLineSplitter.split("abcd\n\nefgh", 3);
		assertEquals("Wrong number of lines - " + lines, 3, lines.size());
		assertEquals("abcd", lines.get(0));
		assertEquals("", lines.get(1));
		assertEquals("efgh", lines.get(2));
	}

	@Test
	public void testSplitWithMaxWithoutSpacesGreaterThanMaxWordLength() {
		// assume MAX_WORD_LENGTH == 10 (I'm too lazy to dynamically generate the data)
		assertEquals("Update test for new MAX_WORD_LENGTH", 10, HtmlLineSplitter.MAX_WORD_LENGTH);

		List<String> lines = HtmlLineSplitter.split("abcdefghijklmnopqrstuvwxyz", 3);
		assertEquals(9, lines.size());
		assertEquals("abc", lines.get(0));
		assertEquals("def", lines.get(1));
		assertEquals("ghi", lines.get(2));
		assertEquals("jkl", lines.get(3));
		assertEquals("mno", lines.get(4));
		assertEquals("pqr", lines.get(5));
		assertEquals("stu", lines.get(6));
		assertEquals("vwx", lines.get(7));
		assertEquals("yz", lines.get(8));
	}

	@Test
	public void testSplitAtSpace() {
		List<String> lines = HtmlLineSplitter.split("split split", 5);
		assertEquals("Wrong number of lines - " + lines, 2, lines.size());
		assertEquals("split", lines.get(0));
		assertEquals("split", lines.get(1));
	}

	@Test
	public void testSplitAtSpace_PreserveWhitespace() {
		//
		// Interesting behavior: the second split attempts to split ' spli'.  The algorithm
		// then looks for a space to split on, to avoid breaking a word.  It finds the first
		// space and then splits there, creating a line that is just a ' '.  It looks unusual,
		// but it prevents splitting on a word.
		//
		List<String> lines = HtmlLineSplitter.split("split split", 5, true);
		assertEquals("Wrong number of lines - " + lines, 3, lines.size());
		assertEquals("split", lines.get(0));
		assertEquals(" ", lines.get(1));
		assertEquals("split", lines.get(2));
	}

}


text:
package org.jboss.arquillian.warp.extension.phaser.ftest.lifecycle;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class FailingPhaseListener implements PhaseListener {

    private static final long serialVersionUID = 1L;

    @Override
    public void afterPhase(PhaseEvent event) {
        throw new TestingException();
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        throw new TestingException();
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

    public static class TestingException extends RuntimeException {

        private static final long serialVersionUID = 1L;

    }

}


text:
package org.anodyneos.servlet.email;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.anodyneos.commons.net.ClassLoaderURIHandler;
import org.anodyneos.commons.xml.UnifiedResolver;
import org.anodyneos.commons.xml.xsl.TemplatesCache;
import org.anodyneos.commons.xml.xsl.TemplatesCacheImpl;
import org.anodyneos.servlet.multipart.MultipartHttpServletRequest;
import org.anodyneos.servlet.multipart.commons.CommonsMultipartResolver;
import org.anodyneos.servlet.net.ServletContextURIHandler;
import org.anodyneos.servlet.xsl.GenericErrorHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class EmailServlet extends javax.servlet.http.HttpServlet {

    protected static final Log logger = LogFactory.getLog(EmailServlet.class);

    private static final long serialVersionUID = 3544676161419817017L;

    private static final String IP_TEMPLATE_CACHE = "template.cache";
    private static final String IP_COMMAND_FACTORY = "aos.commandFactoryClass";

    /** if maxUploadSizeBytes is not set or invalid, default is 0 bytes */
    private static final String IP_MAX_UPLOAD = "maxUploadSizeBytes";

    private static final String IP_TMP_DIR = "tmpDir";

    private static final String TRUE = "true";
    private static final String FALSE = "false";

    private CommandFactory commandFactory;
    private UnifiedResolver resolver;
    private TemplatesCache templatesCache;

    private long ctxMaxUpload = 0L;

    private File tmpDir = null;

    /**
     * The attribute name in the <?xml-stylesheet> tag used in
     * stylesheet selection.
     */
    protected static final String STYLESHEET_ATTRIBUTE = "title";

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);

        boolean external;
        ServletContext ctx = servletConfig.getServletContext();
        ClassLoader classLoader = this.getClass().getClassLoader();
        resolver = new UnifiedResolver();

        // Setup commandFactory
        String clazz = servletConfig.getInitParameter(IP_COMMAND_FACTORY);
        if (clazz == null) {
            clazz = "org.anodyneos.servlet.email.CommandFactoryImpl";
        }
        commandFactory = (CommandFactory) Util.instantiateObject(EmailServlet.class, clazz);
        if (commandFactory == null) {
            throw new ServletException("Cannot instantiate command factory.");
        }

        // Setup resolver
        resolver.setDefaultLookupEnabled(false);
        resolver.addProtocolHandler("classloader",
                new ClassLoaderURIHandler(this.getClass().getClassLoader()));
        resolver.addProtocolHandler("webapp",
                new ServletContextURIHandler(servletConfig.getServletContext()));

        // Setup templatesCache
        templatesCache = new TemplatesCacheImpl();
        templatesCache.setUnifiedResolver(resolver);
        if (FALSE.equals(servletConfig.getInitParameter(IP_TEMPLATE_CACHE))) {
            templatesCache.setCacheEnabled(false);
        } else {
            templatesCache.setCacheEnabled(true);
        }

        // Setup ctxMaxUpload
        try {
            String maxUploadStr = servletConfig.getInitParameter(IP_MAX_UPLOAD);
            if (null != maxUploadStr) {
                ctxMaxUpload = Long.parseLong(maxUploadStr);
            }
        } catch(NumberFormatException e) {
            // do nothing, stick with 0L.
        }

        // Setup tmp directory
        String str =  servletConfig.getInitParameter(IP_TMP_DIR);
        if (null != str && str.length() > 0) {
            tmpDir = new File(str);
        }

    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws
            ServletException, IOException {
        doGet(req, res);
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws
            ServletException, IOException {

        Params params;
        URI configURI;
        Document configDoc;
        EmailContext ctx;

        CommonsMultipartResolver multipartResolver = null;

        // outer try block to make sure we cleanup uploaded files
        try {
            // Read configuration and setup context object
            try {
                //configURI = new URI("webapp:///WEB-INF/email/" + req.getPathInfo());
                configURI = new URI("webapp://" + req.getServletPath());
                configDoc = getDocumentBuilder().parse(resolver.resolveEntity("", configURI.toString()));

                // allow the config file to specify request encoding prior to parsing get/post
                String forceRequestEncoding = null;
                try {
                    forceRequestEncoding =
                        configDoc.getDocumentElement().getAttribute("forceRequestCharset");
                    if(null != forceRequestEncoding && ! ("".equals(forceRequestEncoding))) {
                        req.setCharacterEncoding(forceRequestEncoding);
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            } catch (SAXException e) {
                throw new ServletException("Cannot parse config xml.", e);
            } catch (ParserConfigurationException e) {
                throw new ServletException("Cannot create DocumentBuilder.", e);
            }

            // setup multipart parser if required
            long maxUpload = 0;
            if (ctxMaxUpload > 0) {
                String maxUploadStr = configDoc.getDocumentElement().getAttribute("maxUploadSize").trim();
                long xemlMaxUpload = 0;
                try {
                    xemlMaxUpload = Long.parseLong(maxUploadStr);
                } catch(NumberFormatException e) {
                    // do nothing, stick with 0L.
                }
                maxUpload = Math.min(ctxMaxUpload, xemlMaxUpload);
            }

            try {
                multipartResolver = new CommonsMultipartResolver(getServletContext());
                if (multipartResolver.isMultipart(req)) {
                    multipartResolver.setMaxInMemorySize(10240); // 10KB
                    multipartResolver.setMaxUploadSize(maxUpload);
                    if (null != tmpDir) {
                        multipartResolver.setUploadTempDir(tmpDir);
                    }
                    req = multipartResolver.resolveMultipart(req);
                }

                params = new Params(this, req);
                ctx = new EmailContext(templatesCache, resolver, params,  configURI, configDoc);

                String redir = processDoc(ctx);
                if (redir != null) {
                    res.sendRedirect(redir);
                } else {
                    /* This stuff should be put into a debugging operation */
                    /*
                     * params.addScopeElements(configDoc.getDocumentElement());
                     *
                     * String rawXMLMimeType = "text/xml"; if (
                     * "xml".equals(req.getParameter("rawXMLMime"))) {
                     * rawXMLMimeType = "text/xml"; } else if (
                     * "plain".equals(req.getParameter("rawXMLMime"))) {
                     * rawXMLMimeType = "text/plain"; }
                     * res.setContentType(rawXMLMimeType); PrintWriter out =
                     * res.getWriter(); Transformer transformer =
                     * templatesCache.getTransformer();
                     * transformer.setURIResolver(resolver);
                     * transformer.transform(new DOMSource(configDoc, "webapp://" +
                     * req.getServletPath()), new StreamResult(out)); out.close();
                     */

                    res.setContentType("text/html");
                    PrintWriter out = res.getWriter();
                    out.println("");
                    out.println("
The email has been sent.
");
                    out.println("");
                }
            //} catch (MaxUploadSizeExceededException e) {
                //throw e;
            //} catch (MultipartException e) {
                //throw e;
            } catch (Exception e) {
                logger.error("Error sending email", e);
                String failureRedirect = null;
                try {
                    failureRedirect =
                        configDoc.getDocumentElement().getAttribute("failureRedirect");
                } catch (Throwable t) {
                    // noop
                }
                if (!res.isCommitted()) {
                    res.reset();
                    if (null != failureRedirect && failureRedirect.length() > 0) {
                        res.sendRedirect(failureRedirect);
                    } else {
                        res.setContentType("text/html");
                        printErrorMessage(res.getWriter(), e);
                    }
                }
            }
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        } finally {
            if (null != multipartResolver && req instanceof MultipartHttpServletRequest) {
                multipartResolver.cleanupMultipart((MultipartHttpServletRequest) req);
            }
        }

    }

    public String processDoc(EmailContext ctx) throws Exception {
        Element config = ctx.getConfigDoc().getDocumentElement();
        NodeList nl = config.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element el = (Element) n;
                Command cmd = commandFactory.getHandlerFor(el);
                if (cmd != null) {
                    cmd.process(ctx, el);
                } else {
                    throw new ServletException("Cannot find command handler for element.");
                }
            }
        }

        // find redirect
        String successRedirect = config.getAttribute("successRedirect");
        if (! "".equals(successRedirect)) {
            return successRedirect;
        } else {
            return null;
        }
    }

    private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new GenericErrorHandler());
        docBuilder.setEntityResolver(resolver);
        return docBuilder;
    }

    protected void printErrorMessage(PrintWriter eout, Exception e) {
        eout.println("
Exception Thrown
");
        eout.println("
");
        eout.println(e.toString());
        eout.println("
");
        eout.println("
Stack Trace
");
        eout.println("\n
");
        e.printStackTrace(eout);
        eout.println("
");
    }

    private static String[] addStringToArray(String[] arr, String str) {
        String[] newArr = new String[arr.length + 1];
        System.arraycopy(arr, 0, newArr, 0, arr.length);
        newArr[arr.length] = str;
        return newArr;
    }

}


text:
all: cvesync

cvesync:
	go get github.com/mattn/go-sqlite3
	go get github.com/blackjack/syslog
	go build -o cvesync github.com/mikkolehtisalo/cvesync/main

install:
	mkdir -p /opt/cvesync/bin /opt/cvesync/etc /opt/cvesync/var
	cp cvesync /opt/cvesync/bin/
	chmod 755 /opt/cvesync/bin/cvesync
	cp ca.crt settings.json jira.json blacklist.txt rt.json jira.templ rt.templ cwec_v2.8.xml /opt/cvesync/etc/
	chmod -R 755 /opt/cvesync/etc
	cp cvesync.sqlite /opt/cvesync/var/
	chmod 755 /opt/cvesync/var/cvesync.sqlite

selinux:
	selinux/cvesync.sh

clean:
	rm cvesync

test:
	go test .

.PHONY: selinux


text:
package com.martinet.emplitude.Initialization;

import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.martinet.emplitude.Constants;
import com.martinet.emplitude.Models.City;
import com.martinet.emplitude.Models.School;
import com.martinet.emplitude.R;
import com.martinet.emplitude.Tool.Response;

import java.util.List;

/**
 * Created by martinet on 11/08/16.
 */

public class SelectionSchool extends FragmentSelection implements Response<String, String> {

    private City city;
    private Spinner spnSelection;
    private TextView tvNoFound;
    private TextView tvTitle;
    private ProgressBar prgLoading;
    private List<School> schools;
    private School school;

    public static SelectionSchool newInstance(City city)
    {
        SelectionSchool selectionSchool = new SelectionSchool();
        Bundle bdl = new Bundle();
        bdl.putSerializable("city", city);
        selectionSchool.setArguments(bdl);
        return selectionSchool;
    }

    public static SelectionSchool newInstance(City city, School school)
    {
        SelectionSchool selectionSchool = newInstance(city);
        selectionSchool.getArguments().putSerializable("school", school);
        return selectionSchool;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.school = (School) getArguments().get("school");
        this.city = (City) getArguments().get("city");

        View view = inflater.inflate(R.layout.initialisation_spinner, container, false);
        initialisation.getBtnNext().setOnClickListener(onValidate());
        initialisation.getBtnPrevious().setOnClickListener(onRevert());
        initialisation.getBtnPrevious().setVisibility(View.VISIBLE);

        tvTitle = (TextView) view.findViewById(R.id.titleSelection);
        spnSelection = (Spinner) view.findViewById(R.id.spnSelection);
        prgLoading = (ProgressBar) view.findViewById(R.id.loading);
        tvNoFound = (TextView) view.findViewById(R.id.nofound);

        tvTitle.setText(getResources().getText(R.string.selection_school_title));
        School.executeURL(this, city);

        return view;
    }

    public View.OnClickListener onValidate() {
        return new View.OnClickListener() {
            public void onClick(View v) {
                if(schools == null) {
                    Snackbar.make(v, "Vous devez d'abord choisir un établissement.", Snackbar.LENGTH_SHORT).show();
                } else {
                    School school = schools.get(schools.indexOf(spnSelection.getSelectedItem()));
                    school.setCity(city);

                    SelectionGroup selectionGroup = SelectionGroup.newInstance(school);
                    Constants.changeFragment( initialisation.getFragmentActivity(), R.id.selection, selectionGroup, R.anim.slide_in_left, R.anim.slide_out_right);
                }

            }
        };
    }

    public View.OnClickListener onRevert() {
        return new View.OnClickListener() {
            public void onClick(View v) {
                SelectionCity selection = SelectionCity.newInstance(city);
                Constants.changeFragment(initialisation.getFragmentActivity(), R.id.selection, selection, R.anim.slide_in_right, R.anim.slide_out_left);
            }
        };
    }

    @Override
    public void onSuccess(String value) {
        prgLoading.setVisibility(View.GONE);
        schools = School.parseJson(value);
        if(schools == null) {
            this.onError(getResources().getString(R.string.selectionSchoolNull));
        } else {
            spnSelection.setVisibility(View.VISIBLE);
            ArrayAdapter<School> adapter = new ArrayAdapter<>(initialisation.getFragmentActivity(), android.R.layout.simple_spinner_dropdown_item, schools);
            spnSelection.setAdapter(adapter);
            if(school != null) {
                spnSelection.setSelection(adapter.getPosition(school));
            }
        }

    }

    @Override
    public void onError(String message) {
        prgLoading.setVisibility(View.GONE);
        tvNoFound.setText(message);
        ((LinearLayout) tvNoFound.getParent()).setVisibility(View.VISIBLE);
    }
}


text:
currentMenu: getting-started-obtain-certificate
---

# Obtain a certificate

Now Acme PHP is available on your system (`php acmephp.phar --version` should display its version),
you can start requesting certificates for your domains using it.

**Note:** This is the long way to abtain a certificate. The
[recommended way describe here](/documentation/getting-started/2-obtain-certificate-easy.html)

Several steps are required to do so (note that only the 4th one will be necessary during renewal):

1. [Register on the Let's Encrypt/ACME server](#1-register-on-the-lets-encryptacme-server)
2. [Prove you own the domain](#2-prove-you-own-the-domain)
3. [Ask the server to check your proof](#3-ask-the-server-to-check-your-proof)
4. [Get your certificate](#4-get-your-certificate)
5. [Renew your certificate](#5-renew-your-certificate)
6. [List the certificates handled by Acme PHP](#6-list-the-certificates-handled-by-acme-php)

## 1. Register on the Let's Encrypt/ACME server

The first thing we need to do is to generate a global private key (your "account key") that will be
used for future exchanges with Let's Encrypt to prove your identity.

To do so, run the following command:

``` console
php acmephp.phar register youremail@example.com
```

This command will do three main things:
- create a default configuration file `~/.acmephp/acmephp.conf` that you may edit for advanced usages of Acme PHP
- generate a key pair for your account and store it in `~/.acmephp/master/account`
- register your account key in the Let's Encrypt/ACME server, associating it with your e-mail address

## 2. Prove you own the domain

You can only request certificates for domains you own so you need to prove to the Let's Encrypt server that you own
the domain.

The principle is quite simple:
- You ask the server for a token and expose it on a specific URL given by the server
- The server check that URL and verify the token is properly exposed there

**Note:** This technique is called HTTP checking as it uses a HTTP request to check your ownership.
You can also use [DNS checking](/documentation/guides/dns-challenge.html) which uses a DNS TXT field to expose the token
(it may be easier in your specific context).

Using this technique, you proved your server is responding behind the concerned domain.

**Note:** You'll need to periodically prove that you own a domain (certificates renewals may require a new token).

The first step is to get and expose the token. Run the following:

``` console
# Get a token to expose
php acmephp.phar authorize yourdomain.org

# The command will display explainations to help you expose the token properly.
# Usually, a simple text file is enough to expose the token.
```

## 3. Ask the server to check your proof

Once the token exposed (don't hesitate to check in your browser), run the following command to ask the server
to check your proof:

``` console
php acmephp.phar check yourdomain.org

# The server will check the URL for the token to expose. If it succeeds, you will be able to request certificate
# for this domain.
```

If there is an issue, you will usually have a message describing the problem. If you are stuck, don't hesitate to
ask on [Github issues](https://github.com/acmephp/acmephp/issues).

## 4. Get your certificate

Finally! You are the proved owner of your domain, you can now request and renew a certificate for this domain.
To do so, simply run the `request` command:

``` console
php acmephp.phar request yourdomain.org
```

This command will ask you required informations for the certificate, request it to the server and store it in
the `~/.acmephp` storage directory.

6 files will be created in the storage directory:

- **The full-chain certificate** at `~/.acmephp/master/certs/yourdomain.org/fullchain.pem`.
  This file is the certificate itself. You probably want to use this file in your webserver configuration as it
  includes all the issuers chain for a better compatibility with old devices.

- **The certificate private key** at `~/.acmephp/master/private/yourdomain.org/private.pem`.
  This file is usually required by the webserver.

- **The chain alone** at `~/.acmephp/master/certs/yourdomain.org/chain.pem`.
  Some webservers requires a separated chain and certificate. This is the chain part, if you need it.

- **The certificate alone** at `~/.acmephp/master/certs/yourdomain.org/cert.pem`.
  Some webservers requires a separated chain and certificate. This is the certificate part, if you need it.

- **The combined certificate** at `~/.acmephp/master/certs/yourdomain.org/combined.pem`.
  Some webservers requires a single file combining the full-chain and the certificate private key.
  This is it, if you need it.

- **The certificate public key** at `~/.acmephp/master/private/yourdomain.org/public.pem`.
  You probably won't need it, but it's still available here.

You can now [configure your webserver](/documentation/getting-started/3-configure-webserver.html)!

## 5. Renew your certificate

If a certificate will expire soon, you will probably want to renew it. To do so, simply rerun the `request` command:

``` console
php acmephp.phar request yourdomain.org
```

This time, the command won't ask you anything (all the required informations were stored at the first request).
The certificate will be renewed.

Please note that there may be a limit of renewals per day or week depending on the configuration of the ACME server.
Let's Encrypt has this kind of limitation: renew only when required (one week before expiration for instance).

By default, the `request` command won't renew until one week before the expiration of the certificate. Therefore you
can put it as a CRON every day and it will renew only when required.

## 6. List the certificates handled by Acme PHP

Using the command `./acmephp.phar status`, you can see what certificates are handled by the Acme PHP client
and when they will expire. It's a useful tool to avoid expired certificates:

``` console
php acmephp.phar status

+---------------+----------------------------+---------------------+---------------------+----------------+
| Domain        | Issuer                     | Valid from          | Valid to            | Needs renewal? |
+---------------+----------------------------+---------------------+---------------------+----------------+
| acmephp.com   | Let's Encrypt Authority X3 | 2016-06-17 13:08:00 | 2016-09-15 13:08:00 | No             |
+---------------+----------------------------+---------------------+---------------------+----------------+
```

---------------------------------------------------------------------

Next: [Configure your webserver](/documentation/getting-started/3-configure-webserver.html)


text:
import {Injectable} from '@angular/core';

@Injectable()
export class LoggerService {
  static log(msg: string): void {
    console.log(msg);
  }

  static error(msg: string, obj = {}): void {
    console.error(msg, obj);
  }
}


text:
class AddHomePageUrlForApplicationSettings < ActiveRecord::Migration[4.2]
  def change
    add_column :application_settings, :home_page_url, :string
  end
end


text:
import { DoCheck, ElementRef, KeyValueDiffers, Renderer } from '@angular/core';
/**
 * The `NgStyle` directive changes styles based on a result of expression evaluation.
 *
 * An expression assigned to the `ngStyle` property must evaluate to an object and the
 * corresponding element styles are updated based on changes to this object. Style names to update
 * are taken from the object's keys, and values - from the corresponding object's values.
 *
 * ### Syntax
 *
 * - `<div [ngStyle]="{'font-style': styleExp}"></div>`
 * - `<div [ngStyle]="{'max-width.px': widthExp}"></div>`
 * - `<div [ngStyle]="styleExp"></div>` - here the `styleExp` must evaluate to an object
 *
 * ### Example ([live demo](http://plnkr.co/edit/YamGS6GkUh9GqWNQhCyM?p=preview)):
 *
 * ```
 * import {Component} from '@angular/core';
 * import {NgStyle} from '@angular/common';
 *
 * @Component({
 *  selector: 'ngStyle-example',
 *  template: `
 *    <h1 [ngStyle]="{'font-style': style, 'font-size': size, 'font-weight': weight}">
 *      Change style of this text!
 *    </h1>
 *
 *    <hr>
 *
 *    <label>Italic: <input type="checkbox" (change)="changeStyle($event)"></label>
 *    <label>Bold: <input type="checkbox" (change)="changeWeight($event)"></label>
 *    <label>Size: <input type="text" [value]="size" (change)="size = $event.target.value"></label>
 *  `,
 *  directives: [NgStyle]
 * })
 * export class NgStyleExample {
 *    style = 'normal';
 *    weight = 'normal';
 *    size = '20px';
 *
 *    changeStyle($event: any) {
 *      this.style = $event.target.checked ? 'italic' : 'normal';
 *    }
 *
 *    changeWeight($event: any) {
 *      this.weight = $event.target.checked ? 'bold' : 'normal';
 *    }
 * }
 * ```
 *
 * In this example the `font-style`, `font-size` and `font-weight` styles will be updated
 * based on the `style` property's value changes.
 *
 * @stable
 */
export declare class NgStyle implements DoCheck {
    private _differs;
    private _ngEl;
    private _renderer;
    constructor(_differs: KeyValueDiffers, _ngEl: ElementRef, _renderer: Renderer);
    ngStyle: {
        [key: string]: string;
    };
    ngDoCheck(): void;
    private _applyChanges(changes);
    private _setStyle(name, val);
}