text:
from utils import utility

class Animation(object):
    def __init__(self):
        self.sequence_dict = {}
        self.current_sequence = 0
        self.frame_dict = {}
        self.current_frame = 0
        self.is_playing = True
        self.image = None
        self.parent = None

    def __repr__(self):
        return '<Animation({0} Sequences): {1}>'.format(self.length, self.keys)

    def __len__(self):
        return len(self.sequence_dict)

    @property
    def length(self):
        return len(self.sequence_dict)

    @property
    def keys(self):
        return self.sequence_dict.keys()

    def set_parent(self, parent):
        self.parent = parent
        self.parent.image = self.sequence_dict[self.current_sequence][self.current_frame]

    def update(self):
        if self.is_playing:
            self.current_frame += 1

        if self.current_frame > len(self.sequence_dict[self.current_sequence]) - 1:
            self.current_frame = 0

        self.image = self.sequence_dict[self.current_sequence][self.current_frame]

    def play(self, sequence_id, frame_id=0):
        self.is_playing = True

        if self.current_sequence != sequence_id:
            self.current_sequence = sequence_id
            self.current_frame = frame_id

    def stop(self, sequence_id=None, frame_id=0):
        self.is_playing = False

        if sequence_id:
            self.current_sequence = sequence_id

        if frame_id:
            self.current_frame = frame_id

    def build_animation(self, sequence_id, frames):
        self.sequence_dict[sequence_id] = []
        if not self.current_sequence:
            self.current_sequence = sequence_id

        try:
            for frame in frames:
                try:
                    self.sequence_dict[sequence_id].append(self.frame_dict[frame])

                except:
                    self.frame_dict[frame] = (utility.load_image(frame))
                    self.sequence_dict[sequence_id].append(self.frame_dict[frame])

        except:
            try:
                self.sequence_dict[sequence_id].append(self.frame_dict[frames])

            except:
                self.frame_dict[frames] = (utility.load_image(frames))
                self.sequence_dict[sequence_id].append(self.frame_dict[frames])

        self.image = self.sequence_dict[self.current_sequence][self.current_frame]


text:
/* This file was generated by syncqt. */
#ifndef QT_QTNETWORK_VERSION_H
#define QT_QTNETWORK_VERSION_H

#define QTNETWORK_VERSION_STR "5.3.0"

#define QTNETWORK_VERSION 0x050300

#endif // QT_QTNETWORK_VERSION_H

redpajama_set_name: RedPajamaGithub


text:
Adjust form input padding easily.

```javascript
  type Props = {
    children: ReactElement,
    paddingTop: string,
    paddingBottom: string,
  };
  <FormGroup paddingTop="15px" paddingBottom="15px">Form Elements</FormGroup>
```


text:
//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//
package javax.persistence;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target( { TYPE })
@Retention(RUNTIME)
public @interface Cacheable {

    boolean value() default true;
}


text:
"use strict";

var Binary  = require('mongomise').Binary;
var Promise = require('bluebird');
var _       = require('lodash');

var mmm = require('mmmagic'),
    Magic = mmm.Magic,
    magic = new Magic(mmm.MAGIC_MIME_TYPE);

var Chunk = function(file, n, collection) {
    if(!(this instanceof Chunk)) {
        return new Chunk(file, n, collection);
    }

    this.file = file;
    this.n = n;
    this.collection = collection;

    // this.data = new Binary();
    this.position = 0;
    this.length = 0;
    this.modified = false;
}

Chunk.CHUNK_SIZE = 256 * 1024;

module.exports = Chunk;

Chunk.prototype.load = function() {
    var self = this;

    return self.collection.findOne({
        'files_id': self.file._id,
        n: self.n
    }).then(function(chunk) {
        if(!chunk){
            throw new Error('No chunk for fileId=' + self.file._id.toString() + ', and n=' + self.n)
        }
        self._id = chunk._id;
        self.data = chunk.data.value(true);
        self.position = self.data.length
        self.length = self.data.length;
        self.modified = false;
    })
}

var mimetype = function (buffer) {
    var deferred = Promise.defer();
    magic.detect(buffer, function(err, result) {
        if (err) {
            return deferred.reject(err)
        }
        deferred.resolve(result)
    })
    return deferred.promise;
}

Chunk.prototype.save = function() {
    var self = this, p;

    if(!self.modified){
        return Promise.resolve()
    }

    var data = self.data.slice(0, self.length)

    if(self._id){
        p = self.collection.updateById(self._id, {
            $set: {
                data: new Binary(data)
            }
        }, {w: 1})
    } else {
        p = self.collection.insert({
            'files_id': self.file._id,
            n: self.n,
            data: new Binary(data)
        }, {w: 1})
    }

    return p.then(function() {
        self.mofified = false;
        if(self.n === 0){
            return mimetype(data)
                .then(function(_mt) {
                    self.file.contentType = _mt;
                })
                .catch(function() {})
        }
    })
}

Chunk.prototype.write = function(buffer, position) {
    var self = this;

    self.modified = true;

    // allocate new buffer
    if(!self.data){
        self.data = new Buffer(Chunk.CHUNK_SIZE);
    }

    // chunk data is appended, grow the buffer
    if(self.data.length < Chunk.CHUNK_SIZE){
        var newBuf = new Buffer(Chunk.CHUNK_SIZE)
        self.data.copy(newBuf)
        self.data = newBuf
    }

    if(position > self.length){
        return 0
    }

    self.position = position;

    var bytesToWrite = Chunk.CHUNK_SIZE - self.position
    if(bytesToWrite > buffer.length){
        bytesToWrite = buffer.length
    }

    if(bytesToWrite === 0){
        return 0
    }

    buffer.copy(self.data, self.position, 0, bytesToWrite)
    self.position += bytesToWrite

    if(self.position > self.length){
        self.length = self.position
    }

    return bytesToWrite;
}

Chunk.prototype.read = function(buffer, position, length) {
    var self = this;

    if(position >= self.data.length){
        return 0
    }

    var bytesToRead = self.data.length - position
    if(bytesToRead > length){
        bytesToRead = length
    }

    self.data.slice(position, position + bytesToRead).copy(buffer)
    self.position += bytesToRead

    return bytesToRead
}


text:
package com.google.code.twig.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Activate
{
	int value() default 1;
}


text:
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;

namespace openVisN.Containers
{
    [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
    public partial class MultiControlDisplay : UserControl
    {
        public MultiControlDisplay()
        {
            base.SetStyle(ControlStyles.ContainerControl, true);
            base.SetStyle(ControlStyles.Selectable, false);
            InitializeComponent();
        }
    }
}


text:
<?php

namespace OpenOrchestra\Backoffice\Tests\Form\Type\Component;

use OpenOrchestra\BaseBundle\Tests\AbstractTest\AbstractBaseTestCase;
use Phake;
use OpenOrchestra\Backoffice\Form\Type\Component\ContentChoiceType;
use Doctrine\Common\Collections\ArrayCollection;
use OpenOrchestra\ModelInterface\Repository\ReadContentRepositoryInterface;

/**
 * Class ContentChoiceTypeTest
 */
class ContentChoiceTypeTest extends AbstractBaseTestCase
{
    protected $form;
    protected $formTypeName = 'fakeFormTypeName';
    protected $contentType = 'fakeContentType';
    protected $keyword = 'fakeKeyword';
    protected $language = 'fakeLanguage';
    protected $siteId = 'fakeSiteId';
    protected $contentId0 = 'fakeContentId0';
    protected $contentName0 = 'fakeContentName0';
    protected $contentId1 = 'fakeContentId1';
    protected $contentName1 = 'fakeContentName1';
    protected $choiceType = 'fakeChoiceType';

    /**
     * Set up the test
     */
    public function setUp()
    {
        $content0 = Phake::mock('OpenOrchestra\ModelInterface\Model\ContentInterface');
        Phake::when($content0)->getId()->thenReturn($this->contentId0);
        Phake::when($content0)->getName()->thenReturn($this->contentName0);

        $content1 = Phake::mock('OpenOrchestra\ModelInterface\Model\ContentInterface');
        Phake::when($content1)->getId()->thenReturn($this->contentId1);
        Phake::when($content1)->getName()->thenReturn($this->contentName1);

        $contents = new ArrayCollection();
        $contents->add($content0);
        $contents->add($content1);

        $contentRepository = Phake::mock('OpenOrchestra\ModelInterface\Repository\ContentRepositoryInterface');
        Phake::when($contentRepository)->findByContentTypeAndCondition($this->language, $this->contentType, $this->choiceType, $this->keyword, $this->siteId)->thenReturn($contents);

        $contextManager = Phake::mock('OpenOrchestra\Backoffice\Context\ContextBackOfficeInterface');
        Phake::when($contextManager)->getSiteDefaultLanguage()->thenReturn($this->language);
        Phake::when($contextManager)->getSiteId()->thenReturn($this->siteId);

        $referenceToEmbedTransformer = Phake::mock('OpenOrchestra\Backoffice\Form\DataTransformer\ReferenceToEmbedTransformer');

        $this->form = new ContentChoiceType($contentRepository, $contextManager, $referenceToEmbedTransformer, $this->formTypeName);
    }

    /**
     * Test instance
     */
    public function testInstance()
    {
        $this->assertInstanceOf('Symfony\Component\Form\AbstractType', $this->form);
    }

    /**
     * Test Name
     */
    public function testGetName()
    {
        $this->assertEquals('oo_content_choice', $this->form->getName());
    }

    /**
     * Test resolver
     */
    public function testConfigureOptions()
    {
        $resolver = Phake::mock('Symfony\Component\OptionsResolver\OptionsResolver');

        $this->form->configureOptions($resolver);

        Phake::verify($resolver)->setDefaults(
            array(
                'content_search' => array(
                    'contentType' => '',
                    'choiceType' => ReadContentRepositoryInterface::CHOICE_AND,
                    'keywords' => null,
                )
            )
        );
    }

    /**
     * Test buildForm
     */
    public function testBuildForm()
    {
        $builder = Phake::mock('Symfony\Component\Form\FormBuilderInterface');

        $this->form->buildForm($builder,
            array(
                'content_search' => array(
                    'contentType' => $this->contentType,
                    'choiceType' => $this->choiceType,
                    'keywords' => $this->keyword,
                )
            )
        );

        Phake::verify($builder)->add($this->formTypeName, 'choice', array(
                'label' => false,
                'choices' => array(
                    $this->contentId0 => $this->contentName0,
                    $this->contentId1 => $this->contentName1,
                ),
            )
        );
    }

}


text:
/**
 * @author Fabricio Pontes Harsich fabriph@gmail.com
 */
package com.fabricioph.piteacher;

import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.fabricioph.piteacher.adapters.DBAdapter;
import com.fabricioph.piteacher.adapters.ExamTemplateCursorAdapter;

public class ExamTemplateListActivity extends ListActivity {
	Bundle bundleAnimation = null;
	private DBAdapter mDbHelper;
	private long courseId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exam_template_list);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		bundleAnimation = ActivityOptions.makeCustomAnimation(
				getApplicationContext(), R.anim.enter_1, R.anim.enter_2)
				.toBundle();

		mDbHelper = new DBAdapter(this);
		mDbHelper.open();
		fillData();
	}

	private void fillData() {
		SharedPreferences sharedPref = getSharedPreferences(
				getString(R.string.preference_file_key), Context.MODE_PRIVATE);
		courseId = sharedPref.getLong(DBAdapter.C_KEY_ROWID,
				DBAdapter.ERROR_VALUE);
		if (courseId == DBAdapter.ERROR_VALUE) {
			Log.e(getString(R.string.app_tag), "Couldn't get course id.");
			finish();
			return;
		}
		Cursor c = mDbHelper.allExamTemplates(courseId);
		setListAdapter(new ExamTemplateCursorAdapter(this, c));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			fillData();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.exam_template_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			overridePendingTransition(R.anim.leave_1, R.anim.leave_2);
			return true;
		case R.id.exam_template_list_action_new:
			startActivityForResult(new Intent(this,
					com.fabricioph.piteacher.ExamTemplateCreateActivity.class), 0, bundleAnimation);
			return true;
		case R.id.exam_template_list_action_delete:
			new AlertDialog.Builder(this)
					.setTitle(getString(R.string.delete_students_and_exams))
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									mDbHelper.deleteAllExams(courseId);
									mDbHelper.deleteAllStudents(courseId);
								}
							})
					.setNegativeButton(android.R.string.no,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.leave_1, R.anim.leave_2);
	}
}


text:
package org.jbpm.services.task.assignment.impl;

import org.kie.internal.task.api.assignment.Assignment;

public class AssignmentImpl extends Assignment {

    private static final long serialVersionUID = 1681037121432440328L;

    private Long currentlyAssigned = 0l;

    public AssignmentImpl(String user) {
        super(user);
    }

    public AssignmentImpl(String user, Long currentlyAssigned) {
        super(user);
        this.currentlyAssigned = currentlyAssigned;
    }

    public Long getCurrentlyAssigned() {
        return currentlyAssigned;
    }

    @Override
    public String toString() {
        return "AssignmentImpl [user=" + getUser() + ", currentlyAssigned=" + currentlyAssigned + "]";
    }
}


text:
package android.test;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.test.mock.MockApplication;
import android.view.Window;
import android.util.Log;

/**
 * This class provides isolated testing of a single activity.  The activity under test will
 * be created with minimal connection to the system infrastructure, and you can inject mocked or
 * wrappered versions of many of Activity's dependencies.  Most of the work is handled
 * automatically here by {@link #setUp} and {@link #tearDown}.
 *
 *
If you prefer a functional test, see {@link android.test.ActivityInstrumentationTestCase}.
 *
 *
It must be noted that, as a true unit test, your Activity will not be running in the
 * normal system and will not participate in the normal interactions with other Activities.
 * The following methods should not be called in this configuration - most of them will throw
 * exceptions:
 *

 *
{@link android.app.Activity#createPendingResult(int, Intent, int)}

 *
{@link android.app.Activity#startActivityIfNeeded(Intent, int)}

 *
{@link android.app.Activity#startActivityFromChild(Activity, Intent, int)}

 *
{@link android.app.Activity#startNextMatchingActivity(Intent)}

 *
{@link android.app.Activity#getCallingActivity()}

 *
{@link android.app.Activity#getCallingPackage()}

 *
{@link android.app.Activity#createPendingResult(int, Intent, int)}

 *
{@link android.app.Activity#getTaskId()}

 *
{@link android.app.Activity#isTaskRoot()}

 *
{@link android.app.Activity#moveTaskToBack(boolean)}

 *

 *
 *
The following methods may be called but will not do anything.  For test purposes, you can use
 * the methods {@link #getStartedActivityIntent()} and {@link #getStartedActivityRequest()} to
 * inspect the parameters that they were called with.
 *

 *
{@link android.app.Activity#startActivity(Intent)}

 *
{@link android.app.Activity#startActivityForResult(Intent, int)}

 *

 *
 *
The following methods may be called but will not do anything.  For test purposes, you can use
 * the methods {@link #isFinishCalled()} and {@link #getFinishedActivityRequest()} to inspect the
 * parameters that they were called with.
 *

 *
{@link android.app.Activity#finish()}

 *
{@link android.app.Activity#finishFromChild(Activity child)}

 *
{@link android.app.Activity#finishActivity(int requestCode)}

 *

 *
 * @deprecated Write
 * Local Unit Tests
 * instead.
 */
@Deprecated
public abstract class ActivityUnitTestCase<T extends Activity>
        extends ActivityTestCase {

    private static final String TAG = "ActivityUnitTestCase";
    private Class<T> mActivityClass;

    private Context mActivityContext;
    private Application mApplication;
    private MockParent mMockParent;

    private boolean mAttached = false;
    private boolean mCreated = false;

    public ActivityUnitTestCase(Class<T> activityClass) {
        mActivityClass = activityClass;
    }

    @Override
    public T getActivity() {
        return (T) super.getActivity();
    }

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

        // default value for target context, as a default
      mActivityContext = getInstrumentation().getTargetContext();
    }

    /**
     * Start the activity under test, in the same way as if it was started by
     * {@link android.content.Context#startActivity Context.startActivity()}, providing the
     * arguments it supplied.  When you use this method to start the activity, it will automatically
     * be stopped by {@link #tearDown}.
     *
     *
This method will call onCreate(), but if you wish to further exercise Activity life
     * cycle methods, you must call them yourself from your test case.
     *
     *
Do not call from your setUp() method.  You must call this method from each of your
     * test methods.
     *
     * @param intent The Intent as if supplied to {@link android.content.Context#startActivity}.
     * @param savedInstanceState The instance state, if you are simulating this part of the life
     * cycle.  Typically null.
     * @param lastNonConfigurationInstance This Object will be available to the
     * Activity if it calls {@link android.app.Activity#getLastNonConfigurationInstance()}.
     * Typically null.
     * @return Returns the Activity that was created
     */
    protected T startActivity(Intent intent, Bundle savedInstanceState,
            Object lastNonConfigurationInstance) {
        assertFalse("Activity already created", mCreated);

        if (!mAttached) {
            assertNotNull(mActivityClass);
            setActivity(null);
            T newActivity = null;
            try {
                IBinder token = null;
                if (mApplication == null) {
                    setApplication(new MockApplication());
                }
                ComponentName cn = new ComponentName(mActivityClass.getPackage().getName(),
                        mActivityClass.getName());
                intent.setComponent(cn);
                ActivityInfo info = new ActivityInfo();
                CharSequence title = mActivityClass.getName();
                mMockParent = new MockParent();
                String id = null;

                newActivity = (T) getInstrumentation().newActivity(mActivityClass, mActivityContext,
                        token, mApplication, intent, info, title, mMockParent, id,
                        lastNonConfigurationInstance);
            } catch (Exception e) {
                Log.w(TAG, "Catching exception", e);
                assertNotNull(newActivity);
            }

            assertNotNull(newActivity);
            setActivity(newActivity);

            mAttached = true;
        }

        T result = getActivity();
        if (result != null) {
            getInstrumentation().callActivityOnCreate(getActivity(), savedInstanceState);
            mCreated = true;
        }
        return result;
    }

    @Override
    protected void tearDown() throws Exception {

        setActivity(null);

        // Scrub out members - protects against memory leaks in the case where someone
        // creates a non-static inner class (thus referencing the test case) and gives it to
        // someone else to hold onto
        scrubClass(ActivityInstrumentationTestCase.class);

        super.tearDown();
    }

    /**
     * Set the application for use during the test.  You must call this function before calling
     * {@link #startActivity}.  If your test does not call this method,
     * @param application The Application object that will be injected into the Activity under test.
     */
    public void setApplication(Application application) {
        mApplication = application;
    }

    /**
     * If you wish to inject a Mock, Isolated, or otherwise altered context, you can do so
     * here.  You must call this function before calling {@link #startActivity}.  If you wish to
     * obtain a real Context, as a building block, use getInstrumentation().getTargetContext().
     */
    public void setActivityContext(Context activityContext) {
        mActivityContext = activityContext;
    }

    /**
     * This method will return the value if your Activity under test calls
     * {@link android.app.Activity#setRequestedOrientation}.
     */
    public int getRequestedOrientation() {
        if (mMockParent != null) {
            return mMockParent.mRequestedOrientation;
        }
        return 0;
    }

    /**
     * This method will return the launch intent if your Activity under test calls
     * {@link android.app.Activity#startActivity(Intent)} or
     * {@link android.app.Activity#startActivityForResult(Intent, int)}.
     * @return The Intent provided in the start call, or null if no start call was made.
     */
    public Intent getStartedActivityIntent() {
        if (mMockParent != null) {
            return mMockParent.mStartedActivityIntent;
        }
        return null;
    }

    /**
     * This method will return the launch request code if your Activity under test calls
     * {@link android.app.Activity#startActivityForResult(Intent, int)}.
     * @return The request code provided in the start call, or -1 if no start call was made.
     */
    public int getStartedActivityRequest() {
        if (mMockParent != null) {
            return mMockParent.mStartedActivityRequest;
        }
        return 0;
    }

    /**
     * This method will notify you if the Activity under test called
     * {@link android.app.Activity#finish()},
     * {@link android.app.Activity#finishFromChild(Activity)}, or
     * {@link android.app.Activity#finishActivity(int)}.
     * @return Returns true if one of the listed finish methods was called.
     */
    public boolean isFinishCalled() {
        if (mMockParent != null) {
            return mMockParent.mFinished;
        }
        return false;
    }

    /**
     * This method will return the request code if the Activity under test called
     * {@link android.app.Activity#finishActivity(int)}.
     * @return The request code provided in the start call, or -1 if no finish call was made.
     */
    public int getFinishedActivityRequest() {
        if (mMockParent != null) {
            return mMockParent.mFinishedActivityRequest;
        }
        return 0;
    }

    /**
     * This mock Activity represents the "parent" activity.  By injecting this, we allow the user
     * to call a few more Activity methods, including:
     *

     *
{@link android.app.Activity#getRequestedOrientation()}

     *
{@link android.app.Activity#setRequestedOrientation(int)}

     *
{@link android.app.Activity#finish()}

     *
{@link android.app.Activity#finishActivity(int requestCode)}

     *
{@link android.app.Activity#finishFromChild(Activity child)}

     *

     *
     * TODO: Make this overrideable, and the unit test can look for calls to other methods
     */
    private static class MockParent extends Activity {

        public int mRequestedOrientation = 0;
        public Intent mStartedActivityIntent = null;
        public int mStartedActivityRequest = -1;
        public boolean mFinished = false;
        public int mFinishedActivityRequest = -1;

        /**
         * Implementing in the parent allows the user to call this function on the tested activity.
         */
        @Override
        public void setRequestedOrientation(int requestedOrientation) {
            mRequestedOrientation = requestedOrientation;
        }

        /**
         * Implementing in the parent allows the user to call this function on the tested activity.
         */
        @Override
        public int getRequestedOrientation() {
            return mRequestedOrientation;
        }

        /**
         * By returning null here, we inhibit the creation of any "container" for the window.
         */
        @Override
        public Window getWindow() {
            return null;
        }

        /**
         * By defining this in the parent, we allow the tested activity to call
         *

         *
{@link android.app.Activity#startActivity(Intent)}

         *
{@link android.app.Activity#startActivityForResult(Intent, int)}

         *

         */
        @Override
        public void startActivityFromChild(Activity child, Intent intent, int requestCode) {
            mStartedActivityIntent = intent;
            mStartedActivityRequest = requestCode;
        }

        /**
         * By defining this in the parent, we allow the tested activity to call
         *

         *
{@link android.app.Activity#finish()}

         *
{@link android.app.Activity#finishFromChild(Activity child)}

         *

         */
        @Override
        public void finishFromChild(Activity child) {
            mFinished = true;
        }

        /**
         * By defining this in the parent, we allow the tested activity to call
         *

         *
{@link android.app.Activity#finishActivity(int requestCode)}

         *

         */
        @Override
        public void finishActivityFromChild(Activity child, int requestCode) {
            mFinished = true;
            mFinishedActivityRequest = requestCode;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <name>Cilogi Base</name>
    <description>Base library for</description>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cilogi</groupId>
    <artifactId>cilogi-base</artifactId>
    <version>1.6.1</version>
    <packaging>jar</packaging>
    <url>https://github.com/cilogi/cilogi-base</url>
    <developers>
        <developer>
            <name>Tim Niblett</name>
            <organization>Cilogi</organization>
            <organizationUrl>http://www.cilogi.com</organizationUrl>
            <roles>
                <role>developer</role>
            </roles>
            <timezone>0</timezone>
        </developer>
    </developers>
    <licenses>
      <license>
        <name>MIT license</name>
        <url>http://www.opensource.org/licenses/mit-license.php</url>
      </license>
    </licenses>
    <scm>
        <connection>scm:git:git@github.com:cilogi/cilogi-base.git</connection>
        <developerConnection>scm:git:git@github.com:cilogi/cilogi-base.git</developerConnection>
        <url>git@github.com:cilogi/cilogi-base.git</url>
    </scm>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <net.spy.log.LoggerImpl>net.spy.memcached.compat.log.SunLogger</net.spy.log.LoggerImpl>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>java3d</groupId>
            <artifactId>vecmath</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>colt</groupId>
            <artifactId>colt</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!-- test dependencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <excludes>
                        <exclude>secret.properties</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!--
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <id>sign-artifacts</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            -->
        </plugins>
    </build>

</project>


text:
class Numeric
  def as_avro
    self
  end
end


text:
from sqlalchemy import *
from migrate import *

from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
friends = Table('friends', pre_meta,
    Column('follower_id', INTEGER),
    Column('followed_id', INTEGER),
)

friends = Table('friends', post_meta,
    Column('friend_id', Integer),
    Column('friended_id', Integer),
)

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    pre_meta.tables['friends'].columns['followed_id'].drop()
    pre_meta.tables['friends'].columns['follower_id'].drop()
    post_meta.tables['friends'].columns['friend_id'].create()
    post_meta.tables['friends'].columns['friended_id'].create()

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    pre_meta.tables['friends'].columns['followed_id'].create()
    pre_meta.tables['friends'].columns['follower_id'].create()
    post_meta.tables['friends'].columns['friend_id'].drop()
    post_meta.tables['friends'].columns['friended_id'].drop()


text:
PgUtils provides a small set of behaviors useful for working with Postgres datasources.

## Requirements

The master branch has the following requirements:

* CakePHP 2.2.0 or greater.
* PHP 5.3.0 or greater.

## Features

* Search behavior - Performing text searches on models. Allows sophisticated full text searches to be
performed. Also includes a simplified query parser.
* JSON behavior - Retrieving and storing json datatypes. Values are exploded into associative arrays upon
retrieval and collapsed back down on save.
* Array behavior - Retrieving and storing array datatypes. Values are exploded into arrays upon retrieval
and collapsed back down on save
* Interval behavior - Retrieving and storing interval datatypes. PHP intervals are converted to ISO8601 format
and stored into this special PostgreSQL datatype column.

## Installation

* Clone/Copy the files in this directory into `app/Plugin/PgUtils`
* Ensure the plugin is loaded in `app/Config/bootstrap.php` by calling `CakePlugin::load('PgUtils');`
* To use the IntervalBehavior, you must ensure values are stored/retrieved using iso8601 via your database connection.

```php
	public $default = array(
		'datasource' => 'Database/Postgres',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'user',
		'password' => 'password',
		'database' => 'database_name',
		'prefix' => '',
		'encoding' => 'utf8',
		'settings' => array(
			'intervalstyle' => 'iso_8601'
		)
	);
```

* Full text search requires a ts_vector column to be created and maintained. The simplest way
is with a trigger.

### Using Composer

Ensure `require` is present in `composer.json`. This will install the plugin into `Plugin/AwsUtils`:

```
{
    "require": {
        "cuppett/cakephp-pg_utils": "1.0.*"
    },
    "extra":
	{
	    "installer-paths":
	    {
	        "app/Plugin/PgUtils": ["cuppett/cakephp-pg_utils"]
	    }
	}
}
```

## Examples

### Using Interval/JSON/Array types in a model

If your database table contains interval, json or array types in their definition, you can configure behaviors to help translate them into more PHP-friendly types and values via the afterFind and beforeSave callbacks.

They are configured on the model by identifying the fields to convert. One potential enhancement would be to automatically detect these fields; however, it may be useful to not have all converted automatically as well.

```php
class Task extends AppModel {
    public $actsAs = array(
        'PgUtils.Interval' => array(
            'fields' => array(
                'estimate',
                'actual',
                'remain'
            )
        ),
        'PgUtils.Json' => array('fields' => array('custom_attributes'))
    );
```

### Integrating the search column into your database.

The search behavior requires a ts_vector column to be defined. The column must be maintained separately
of the behavior. Here is an example set of SQL to add & update the column when the database
is updated:

```sql
CREATE TABLE primary_objects (
  id UUID NOT NULL default uuid_generate_v4(),
  "name" varchar(255) not null,
  description text,
  created timestamp with time zone not null default CURRENT_TIMESTAMP,
  modified timestamp with time zone not null default CURRENT_TIMESTAMP,
  searchable_text tsvector
);

CREATE OR REPLACE FUNCTION updateVector() RETURNS trigger AS $$
BEGIN
	NEW.searchable_text =
		setweight(to_tsvector('pg_catalog.english', coalesce(NEW."name", '')), 'A') ||
		setweight(to_tsvector('pg_catalog.english', coalesce(NEW.description, '')), 'D');

	RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER indexObjects
	BEFORE INSERT OR UPDATE OF "name", description ON primary_objects
	FOR EACH ROW
	EXECUTE PROCEDURE updateVector();
```

You can add other columns & weights to the search; you can add a gist or gin index to the table/column to
speed up the results; etc.

### Using search from your application

In your Model class:

```php
$this->Behaviors->load(
    'PgUtils.Search', array(
        'column' => 'searchable_text',
        'weights' => array(
            'name' => 'A',
            'description' => 'D'
        )
    )
);
```

From your Controller:

```php
$results = $this->PrimaryObject->search($this->request->data['Search']['query'],
    array(
        'limit' => 25,
        'headline' => array('name', 'description'),
        'fields' => array('id', 'name', 'description', 'modified')
     )
);
```

Then you can display the results in your view like normal.

Potential searches include freeform text such as "cat and dog", "cat or dog", etc. The current set of
operators are "and", "or", and "-" to exclude certain terms.

You can also prefix the term with a field name such as "name:cat". From the above setup examples, this
will change the query such that only the "A" category will be searched for the term "cat".

Please see the topic [Controlling Text Search][text_search] in the PostgreSQL documentation for more
information on these topics. I've tried to expose the most commonly desired knobs for my use cases, but
I'm open to other suggestions.

## Reporting issues

If you have a problem with PgUtils please open an issue on [GitHub][issues].

[text_search]: http://www.postgresql.org/docs/9.4/static/textsearch-controls.html
[issues]: https://github.com/cuppett/cakephp-pg_utils/issues


text:
/*
 *  Abstraction over the unsafe usage of the VGA text buffer memory.
 *
 *  This will allow us to print arbitrary text to the console,
 *  as well as support the standard println! and format! macros.
 */

#![allow(dead_code)]

use spin::Mutex;

const COLOR_CODE: ColorCode = ColorCode::new(Color::LightGreen, Color::Black);
const RAW_WRITER: Writer = Writer::new(0, COLOR_CODE, 0xB8000);
pub static WRITER: Mutex<Writer> = Mutex::new(RAW_WRITER);

macro_rules! print {
    ($($arg:tt)*) => ({
        $crate::vga_buffer::print(format_args!($($arg)*));
    });
}

macro_rules! println {
    ($fmt:expr) => (print!(concat!($fmt, "\n")));
    ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}

pub fn print(args: fmt::Arguments) {
    use core::fmt::Write;
    WRITER.lock().write_fmt(args).unwrap();
}

pub fn clear_screen() {
    for _ in 0..BUFFER_HEIGHT {
        println!("");
    }
}

#[repr(u8)]
#[derive(Debug, Clone, Copy)]
pub enum Color {
    Black      = 0x0,
    Blue       = 0x1,
    Green      = 0x2,
    Cyan       = 0x3,
    Red        = 0x4,
    Magenta    = 0x5,
    Brown      = 0x6,
    LightGray  = 0x7,
    DarkGray   = 0x8,
    LightBlue  = 0x9,
    LightGreen = 0xA,
    LightCyan  = 0xB,
    LightRed   = 0xC,
    PINK       = 0xD,
    YELLOW     = 0xE,
    WHITE      = 0xF
}

#[derive(Debug, Clone, Copy)]
struct ColorCode(u8);

impl ColorCode {
    const fn new(foreground: Color, background: Color) -> ColorCode {
        ColorCode((background as u8) << 4 | (foreground as u8))
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct ScreenChar {
    ascii_char: u8,
    color_code: ColorCode
}

use volatile::Volatile;

const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH:  usize = 80;

struct Buffer {
    chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT]
}

use core::ptr::Unique;

pub struct Writer {
    column_position: usize,
    color_code: ColorCode,
    buffer: Unique<Buffer>
}

impl Writer {
    const fn new(column_position: usize, color_code: ColorCode, buffer: usize) -> Writer {
        Writer {
            column_position: column_position,
            color_code: color_code,
            buffer: unsafe { Unique::new_unchecked(buffer as *mut _) }
        }
    }

    pub fn write_str(&mut self, s: &str) {
        for byte in s.bytes() {
            self.write_byte(byte)
        }
    }

    pub fn write_byte(&mut self, byte: u8) {
        match byte {
            b'\n' => self.write_new_line(),
            _     => self.write_character(byte)
        }
    }

    fn write_character(&mut self, chr: u8) {
        if self.column_position >= BUFFER_WIDTH {
            self.write_new_line();
        }

        let row = BUFFER_HEIGHT - 1;
        let col = self.column_position;

        let color_code = self.color_code;
        self.buffer().chars[row][col].write(ScreenChar {
            ascii_char: chr,
            color_code: color_code
        });
        self.column_position += 1;
    }

    fn write_new_line(&mut self) {
        for row in 1..BUFFER_HEIGHT {
            let buf = self.buffer();
            for col in 0..BUFFER_WIDTH {
                let chr = buf.chars[row][col].read();
                buf.chars[row - 1][col].write(chr);
            }
        }

        self.clear_row(BUFFER_HEIGHT - 1);
        self.column_position = 0;
    }

    fn buffer(&mut self) -> &mut Buffer {
        unsafe {
            self.buffer.as_mut()
        }
    }

    fn clear_row(&mut self, row: usize) {
        let blank = ScreenChar {
            ascii_char: b' ',
            color_code: self.color_code
        };

        let buf = self.buffer();
        for col in 0..BUFFER_WIDTH {
            buf.chars[row][col].write(blank)
        }
    }
}

use core::fmt;

impl fmt::Write for Writer {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.write_str(s);
        Ok(())
    }
}


text:
DELETE FROM config_cfg WHERE cfg_value = cfg_default;

ALTER TABLE config_cfg DROP COLUMN cfg_type;
ALTER TABLE config_cfg DROP COLUMN cfg_default;
ALTER TABLE config_cfg DROP COLUMN cfg_tooltip;
ALTER TABLE config_cfg DROP COLUMN cfg_section;
ALTER TABLE config_cfg DROP COLUMN cfg_category;
ALTER TABLE config_cfg DROP COLUMN cfg_order;
ALTER TABLE config_cfg DROP COLUMN cfg_data;


text:
package at.alladin.rmbt.client;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.json.JSONObject;

import at.alladin.rmbt.client.RMBTTest.CurrentSpeed;
import at.alladin.rmbt.client.helper.Config;
import at.alladin.rmbt.client.helper.ControlServerConnection;
import at.alladin.rmbt.client.helper.IntermediateResult;
import at.alladin.rmbt.client.helper.RMBTOutputCallback;
import at.alladin.rmbt.client.helper.TestStatus;
import at.alladin.rmbt.client.v2.task.TaskDesc;
import at.alladin.rmbt.client.v2.task.result.QoSResultCollector;
import at.alladin.rmbt.client.v2.task.service.TestMeasurement;
import at.alladin.rmbt.client.v2.task.service.TrafficService;
import at.alladin.rmbt.util.tools.InformationCollectorTool;

public class RMBTClient
{
    private static final ExecutorService COMMON_THREAD_POOL = Executors.newCachedThreadPool();

    private final RMBTTestParameter params;

    private final long durationInitNano = 2500000000L; // TODO
    private final long durationUpNano;
    private final long durationDownNano;

    private final AtomicLong initNano = new AtomicLong(-1);
    private final AtomicLong pingNano = new AtomicLong(-1);
    private final AtomicLong downBitPerSec = new AtomicLong(-1);
    private final AtomicLong upBitPerSec = new AtomicLong(-1);

    /* ping status */
    private final AtomicLong pingTsStart = new AtomicLong(-1);
    private final AtomicInteger pingNumDome = new AtomicInteger(-1);
    private final AtomicLong pingTsLastPing = new AtomicLong(-1);

    private final static long MIN_DIFF_TIME = 100000000; // 100 ms

    private final static int KEEP_LAST_ENTRIES = 20;
    private int lastCounter;
    private final long[][] lastTransfer;
    private final long[][] lastTime;

    private final ExecutorService testThreadPool;

    private final RMBTTest[] testTasks;

    private TotalTestResult result;

    private SSLSocketFactory sslSocketFactory;

    private RMBTOutputCallback outputCallback;
    private final boolean outputToStdout = true;

    private final ControlServerConnection controlConnection;

    private final AtomicBoolean aborted = new AtomicBoolean();

    private String errorMsg = "";

    /*------------------------------------
    	V2 tests
    --------------------------------------*/

    public final static String TASK_UDP = "udp";
    public final static String TASK_TCP = "tcp";
    public final static String TASK_DNS = "dns";
    public final static String TASK_VOIP = "voip";
    public final static String TASK_NON_TRANSPARENT_PROXY = "non_transparent_proxy";
    public final static String TASK_HTTP = "http_proxy";
    public final static String TASK_WEBSITE = "website";
    public final static String TASK_TRACEROUTE = "traceroute";

    private List<TaskDesc> taskDescList;

    /*------------------------------------*/

    private final AtomicReference<TestStatus> testStatus = new AtomicReference<TestStatus>(TestStatus.WAIT);
    private final AtomicReference<TestStatus> statusBeforeError = new AtomicReference<TestStatus>(null);
    private final AtomicLong statusChangeTime = new AtomicLong();

    private TrafficService trafficService;

    private InformationCollectorTool informationCollectorTool;

    public static ExecutorService getCommonThreadPool()
    {
        return COMMON_THREAD_POOL;
    }

    private ConcurrentHashMap<TestStatus, TestMeasurement> measurementMap = new ConcurrentHashMap<TestStatus, TestMeasurement>();

    public static RMBTClient getInstance(final String host, final String pathPrefix, final int port,
            final boolean encryption, final ArrayList<String> geoInfo, final String uuid, final String clientType,
            final String clientName, final String clientVersion, final RMBTTestParameter overrideParams,
            final JSONObject additionalValues)
    {
        final ControlServerConnection controlConnection = new ControlServerConnection();

        final String error = controlConnection.requestNewTestConnection(host, pathPrefix, port, encryption, geoInfo,
                uuid, clientType, clientName, clientVersion, additionalValues);

        if (error != null)
        {
            System.out.println(error);
            return null;
        }

        //TODO: simple and fast solution; make it better
        final String errorNewTest = controlConnection.requestQoSTestParameters(host, pathPrefix, port, encryption, geoInfo,
                uuid, clientType, clientName, clientVersion, additionalValues);

        if (errorNewTest != null)
        {
            System.out.println(errorNewTest);
            return null;
        }

        final RMBTTestParameter params = controlConnection.getTestParameter(overrideParams);

        return new RMBTClient(params, controlConnection);
    }

    public static RMBTClient getInstance(final RMBTTestParameter params)
    {
        return new RMBTClient(params, null);
    }

    private RMBTClient(final RMBTTestParameter params, final ControlServerConnection controlConnection)
    {
        this.params = params;
        this.controlConnection = controlConnection;

        params.check();

        if (params.getNumThreads() > 0)
        {
            testThreadPool = Executors.newFixedThreadPool(params.getNumThreads());
            testTasks = new RMBTTest[params.getNumThreads()];
        }
        else
        {
            testThreadPool = null;
            testTasks = null;
        }

        durationDownNano = params.getDuration() * 1000000000L;
        durationUpNano = params.getDuration() * 1000000000L;

        lastTransfer = new long[params.getNumThreads()][KEEP_LAST_ENTRIES];
        lastTime = new long[params.getNumThreads()][KEEP_LAST_ENTRIES];

        this.taskDescList = controlConnection.v2TaskDesc;
        //if (params.isEncryption())
        //    sslSocketFactory = createSSLSocketFactory();

    }

    public void setTrafficService(TrafficService trafficService) {
    	this.trafficService = trafficService;
    }

    public TrafficService getTrafficService() {
    	return this.trafficService;
    }

    public void setInformationCollectorTool(InformationCollectorTool tool) {
    	this.informationCollectorTool = tool;
    }

    public InformationCollectorTool getInformationCollectorTool() {
    	return this.informationCollectorTool;
    }

    public void startInformationCollectorTool() {
    	if (this.informationCollectorTool != null && !this.informationCollectorTool.isRunning()) {
    		this.informationCollectorTool.start(COMMON_THREAD_POOL);
    	}
    }

    public JSONObject getInformationCollectorToolIntermediateResult(boolean clean) {
    	if (this.informationCollectorTool != null && !this.informationCollectorTool.isRunning()) {
    		return this.informationCollectorTool.getJsonObject(clean);
    	}

    	return null;
    }

    public void stopInformationCollectorTool() {
    	if (this.informationCollectorTool != null && this.informationCollectorTool.isRunning()) {
    		this.informationCollectorTool.stop();
    	}
    }

    private SSLSocketFactory createSSLSocketFactory()
    {
        log("initSSL...");
        try
        {
            final SSLContext sc = getSSLContext(null, null);

            final SSLSocketFactory factory = sc.getSocketFactory();

            return factory;
        }
        catch (final Exception e)
        {
            setErrorStatus();
            log(e);
        }
        return null;
    }

    public static TrustManager getTrustingManager()
    {
        return new javax.net.ssl.X509TrustManager()
        {
            public X509Certificate[] getAcceptedIssuers()
            {
                return new X509Certificate[] {};
            }

            public void checkClientTrusted(final X509Certificate[] certs, final String authType)
                    throws CertificateException
            {
                // System.out.println("[TRUSTING] checkClientTrusted: " +
                // Arrays.toString(certs) + " - " + authType);
            }

            public void checkServerTrusted(final X509Certificate[] certs, final String authType)
                    throws CertificateException
            {
                // System.out.println("[TRUSTING] checkServerTrusted: " +
                // Arrays.toString(certs) + " - " + authType);
            }
        };
    }

    public static SSLContext getSSLContext(final String caResource, final String certResource)
            throws NoSuchAlgorithmException, KeyManagementException
    {
        X509Certificate _ca = null;
        try
        {
            if (caResource != null)
            {
                final CertificateFactory cf = CertificateFactory.getInstance("X.509");
                _ca = (X509Certificate) cf.generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(
                        caResource));
            }
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }

        final X509Certificate ca = _ca;

        X509Certificate _cert = null;
        try
        {
            if (certResource != null)
            {
                final CertificateFactory cf = CertificateFactory.getInstance("X.509");
                _cert = (X509Certificate) cf.generateCertificate(RMBTClient.class.getClassLoader().getResourceAsStream(
                        certResource));
            }
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
        final X509Certificate cert = _cert;

        // TrustManagerFactory tmf = null;
        // try
        // {
        // if (cert != null)
        // {
        // final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // ks.load(null, null);
        // ks.setCertificateEntry("crt", cert);
        //
        // tmf =
        // TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // tmf.init(ks);
        // }
        // }
        // catch (Exception e)
        // {
        // e.printStackTrace();
        // }

        final TrustManager tm;
        if (cert == null)
            tm = getTrustingManager();
        else
            tm = new javax.net.ssl.X509TrustManager()
            {
                public X509Certificate[] getAcceptedIssuers()
                {
                    // System.out.println("getAcceptedIssuers");
                    if (ca == null)
                        return new X509Certificate[] { cert };
                    else
                        return new X509Certificate[] { ca };
                }

                public void checkClientTrusted(final X509Certificate[] certs, final String authType)
                        throws CertificateException
                {
                    // System.out.println("checkClientTrusted: " +
                    // Arrays.toString(certs) + " - " + authType);
                }

                public void checkServerTrusted(final X509Certificate[] certs, final String authType)
                        throws CertificateException
                {
                    // System.out.println("checkServerTrusted: " +
                    // Arrays.toString(certs) + " - " + authType);
                    if (certs == null)
                        throw new CertificateException();
                    for (final X509Certificate c : certs)
                        if (cert.equals(c))
                            return;
                    throw new CertificateException();
                }
            };

        final TrustManager[] trustManagers = new TrustManager[] { tm };

        javax.net.ssl.SSLContext sc;
        sc = javax.net.ssl.SSLContext.getInstance(Config.RMBT_ENCRYPTION_STRING);

        sc.init(null, trustManagers, new java.security.SecureRandom());
        return sc;
    }

    public TestResult runTest() throws InterruptedException
    {
    	System.out.println("starting test...");

    	long txBytes = 0;
    	long rxBytes = 0;
    	final long timeStampStart = System.nanoTime();

        if (testStatus.get() != TestStatus.ERROR && testThreadPool != null)
        {

        	if (trafficService != null) {
        		txBytes = trafficService.getTotalTxBytes();
        		rxBytes = trafficService.getTotalRxBytes();
        	}

            resetSpeed();
            downBitPerSec.set(-1);
            upBitPerSec.set(-1);
            pingNano.set(-1);
            initNano.set(-1);

            final long waitTime = params.getStartTime() - System.currentTimeMillis();
            if (waitTime > 0)
            {
                setStatus(TestStatus.WAIT);
                log(String.format(Locale.US, "we have to wait %d ms...", waitTime));
                Thread.sleep(waitTime);
                log(String.format(Locale.US, "...done.", waitTime));
            }
            else
                log(String.format(Locale.US, "luckily we do not have to wait.", waitTime));

            setStatus(TestStatus.INIT);
            statusBeforeError.set(null);

            if (testThreadPool.isShutdown())
                throw new IllegalStateException("RMBTClient already shut down");
            log("starting test...");

            final int numThreads = params.getNumThreads();

            aborted.set(false);

            result = new TotalTestResult();

            if (params.isEncryption())
                sslSocketFactory = createSSLSocketFactory();

            log(String.format(Locale.US, "Host: %s; Port: %s; Enc: %s", params.getHost(), params.getPort(), params.isEncryption()));
            log(String.format(Locale.US, "starting %d threads...", numThreads));

            final CyclicBarrier barrier = new CyclicBarrier(numThreads);

            @SuppressWarnings("unchecked")
            final Future<ThreadTestResult>[] results = new Future[numThreads];

            final int storeResults = (int) (params.getDuration() * 1000000000L / MIN_DIFF_TIME);

            final AtomicBoolean fallbackToOneThread = new AtomicBoolean();

            for (int i = 0; i < numThreads; i++)
            {
                testTasks[i] = new RMBTTest(this, params, i, barrier, storeResults, MIN_DIFF_TIME, fallbackToOneThread);
                results[i] = testThreadPool.submit(testTasks[i]);
            }

            try
            {

                long shortestPing = Long.MAX_VALUE;

                // wait for all threads first
                for (int i = 0; i < numThreads; i++)
                    results[i].get();

                if (aborted.get())
                    return null;

                final long[][] allDownBytes = new long[numThreads][];
                final long[][] allDownNsecs = new long[numThreads][];
                final long[][] allUpBytes = new long[numThreads][];
                final long[][] allUpNsecs = new long[numThreads][];

                int realNumThreads = 0;
                log("");
                for (int i = 0; i < numThreads; i++)
                {
                    final ThreadTestResult testResult = results[i].get();

                    if (testResult != null)
                    {
                        realNumThreads++;

                        log(String.format(Locale.US, "Thread %d: Download: bytes: %d time: %.3f s", i,
                                ThreadTestResult.getLastEntry(testResult.down.bytes),
                                ThreadTestResult.getLastEntry(testResult.down.nsec) / 1e9));
                        log(String.format(Locale.US, "Thread %d: Upload:   bytes: %d time: %.3f s", i,
                                ThreadTestResult.getLastEntry(testResult.up.bytes),
                                ThreadTestResult.getLastEntry(testResult.up.nsec) / 1e9));

                        final long ping = testResult.ping_shortest;
                        if (ping < shortestPing)
                            shortestPing = ping;

                        if (!testResult.pings.isEmpty())
                            result.pings.addAll(testResult.pings);

                        allDownBytes[i] = testResult.down.bytes;
                        allDownNsecs[i] = testResult.down.nsec;
                        allUpBytes[i] = testResult.up.bytes;
                        allUpNsecs[i] = testResult.up.nsec;

                        result.totalDownBytes += testResult.totalDownBytes;
                        result.totalUpBytes += testResult.totalUpBytes;

                        // aggregate speedItems
                        result.speedItems.addAll(testResult.speedItems);
                    }
                }

                result.calculateDownload(allDownBytes, allDownNsecs);
                result.calculateUpload(allUpBytes, allUpNsecs);

                log("");
                log(String.format(Locale.US, "Total calculated bytes down: %d", result.bytes_download));
                log(String.format(Locale.US, "Total calculated time down:  %.3f s", result.nsec_download / 1e9));
                log(String.format(Locale.US, "Total calculated bytes up:   %d", result.bytes_upload));
                log(String.format(Locale.US, "Total calculated time up:    %.3f s", result.nsec_upload / 1e9));

                // get Connection Info from thread 1 (one thread must run)
                result.ip_local = results[0].get().ip_local;
                result.ip_server = results[0].get().ip_server;
                result.port_remote = results[0].get().port_remote;
                result.encryption = results[0].get().encryption;

                result.num_threads = realNumThreads;

                result.ping_shortest = shortestPing;

                result.speed_download = result.getDownloadSpeedBitPerSec() / 1e3;
                result.speed_upload = result.getUploadSpeedBitPerSec() / 1e3;

                log("");
                log(String.format(Locale.US, "Total Down: %.0f kBit/s", result.getDownloadSpeedBitPerSec() / 1e3));
                log(String.format(Locale.US, "Total UP:   %.0f kBit/s", result.getUploadSpeedBitPerSec() / 1e3));
                log(String.format(Locale.US, "Ping:       %.2f ms", shortestPing / 1e6));

                if (controlConnection != null)
                {
                    log("");
                    final String testId = controlConnection.getTestId();
                    final String testUUID = params.getUUID();
                    final long testTime = controlConnection.getTestTime();
                    log(String.format(Locale.US, "uid=%s, time=%s, uuid=%s\n", testId, new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm:ss.SSS", Locale.US).format(new Date(testTime)), testUUID));
                }

                downBitPerSec.set(Math.round(result.getDownloadSpeedBitPerSec()));
                upBitPerSec.set(Math.round(result.getUploadSpeedBitPerSec()));

                log("end.");
                setStatus(TestStatus.SPEEDTEST_END);

            	if (trafficService != null) {
            		txBytes = trafficService.getTotalTxBytes() - txBytes;
            		rxBytes = trafficService.getTotalRxBytes() - rxBytes;
            		result.setTotalTrafficMeasurement(new TestMeasurement(rxBytes, txBytes, timeStampStart, System.nanoTime()));
            		result.setMeasurementMap(measurementMap);
            	}

                return result;
            }
            catch (final ExecutionException e)
            {
                log(e);
                abortTest(true);
                return null;
            }
            catch (final InterruptedException e)
            {
                log("RMBTClient interrupted!");
                abortTest(false);
                throw e;
            }
        }
        else {
            setStatus(TestStatus.SPEEDTEST_END);

        	return null;
        }
    }

    public boolean abortTest(final boolean error)
    {
        System.out.println("RMBTClient stopTest");

        if (error)
            setErrorStatus();
        else
            setStatus(TestStatus.ABORTED);
        aborted.set(true);

        if (testThreadPool != null)
            testThreadPool.shutdownNow();

        return true;
    }

    public void shutdown()
    {
        System.out.println("Shutting down RMBT thread pool...");
        if (testThreadPool != null)
            testThreadPool.shutdownNow();

        System.out.println("Shutdown finished.");
    }

    @Override
    protected void finalize() throws Throwable
    {
        super.finalize();
        if (testThreadPool != null)
            testThreadPool.shutdownNow();
    }

    public SSLSocketFactory getSslSocketFactory()
    {
        return sslSocketFactory;
    }

    public void setOutputCallback(final RMBTOutputCallback outputCallback)
    {
        this.outputCallback = outputCallback;
    }

    private void resetSpeed()
    {
        lastCounter = 0;
    }

    private float getTotalSpeed()
    {
        long sumTrans = 0;
        long maxTime = 0;

        final CurrentSpeed currentSpeed = new CurrentSpeed();

        for (int i = 0; i < params.getNumThreads(); i++)
            if (testTasks[i] != null)
            {
                testTasks[i].getCurrentSpeed(currentSpeed);

                if (currentSpeed.time > maxTime)
                    maxTime = currentSpeed.time;
                sumTrans += currentSpeed.trans;
            }

        return maxTime == 0f ? 0f : (float) sumTrans / (float) maxTime * 1e9f * 8.0f;
    }

    final Map<Integer, List<SpeedItem>> speedMap = new HashMap<Integer, List<SpeedItem>>();

    private float getAvgSpeed()
    {
        long sumDiffTrans = 0;
        long maxDiffTime = 0;

        final CurrentSpeed currentSpeed = new CurrentSpeed();

        final int currentIndex = lastCounter % KEEP_LAST_ENTRIES;
        int diffReferenceIndex = (lastCounter - KEEP_LAST_ENTRIES + 1) % KEEP_LAST_ENTRIES;
        if (diffReferenceIndex < 0)
            diffReferenceIndex = 0;

        lastCounter++;

        for (int i = 0; i < params.getNumThreads(); i++)
            if (testTasks[i] != null)
            {
                testTasks[i].getCurrentSpeed(currentSpeed);

                lastTime[i][currentIndex] = currentSpeed.time;
                lastTransfer[i][currentIndex] = currentSpeed.trans;

//                System.out.println("T" + i + ": " + currentSpeed);

                List<SpeedItem> speedList = speedMap.get(i);
                if (speedList == null) {
                	speedList = new ArrayList<SpeedItem>();
                	speedMap.put(i, speedList);
                }

                speedList.add(new SpeedItem(false, i, currentSpeed.time, currentSpeed.trans));

                final long diffTime = currentSpeed.time - lastTime[i][diffReferenceIndex];
                final long diffTrans = currentSpeed.trans - lastTransfer[i][diffReferenceIndex];

                if (diffTime > maxDiffTime)
                    maxDiffTime = diffTime;
                sumDiffTrans += diffTrans;
            }

        //TotalTestResult totalResult = TotalTestResult.calculateAndGet(lastTransfer, lastTime, false);
        //TotalTestResult totalResult = TotalTestResult.calculateAndGet(speedMap);

        final float speedAvg = maxDiffTime == 0f ? 0f : (float) sumDiffTrans / (float) maxDiffTime * 1e9f * 8.0f;
        //final float speedAvg = (float)totalResult.speed_download * 1e3f;

//        System.out.println("calculate: bytes=" + totalResult.bytes_download + " speed=" + (totalResult.speed_download * 1e3)
//        		+ " nsec=" + totalResult.nsec_download + ", simple: diff=" + sumDiffTrans + " avg=" + speedAvg);

        return speedAvg;
    }

    public IntermediateResult getIntermediateResult(IntermediateResult iResult)
    {
        if (iResult == null)
            iResult = new IntermediateResult();
        iResult.status = testStatus.get();
        iResult.remainingWait = 0;
        final long diffTime = System.nanoTime() - statusChangeTime.get();
        switch (iResult.status)
        {
        case WAIT:
            iResult.progress = 0;
            iResult.remainingWait = params.getStartTime() - System.currentTimeMillis();
            break;

        case INIT:
            iResult.progress = (float) diffTime / durationInitNano;
            break;

        case PING:
            iResult.progress = getPingProgress();
            break;

        case DOWN:
            iResult.progress = (float) diffTime / durationDownNano;
            downBitPerSec.set(Math.round(getAvgSpeed()));
            break;

        case INIT_UP:
            iResult.progress = 0;
            break;

        case UP:
            iResult.progress = (float) diffTime / durationUpNano;
            upBitPerSec.set(Math.round(getAvgSpeed()));
            break;

        case SPEEDTEST_END:
            iResult.progress = 1;
            break;

        case ERROR:
        case ABORTED:
            iResult.progress = 0;
            break;
        default:
        	break;
        }

        if (iResult.progress > 1)
            iResult.progress = 1;

        iResult.initNano = initNano.get();
        iResult.pingNano = pingNano.get();
        iResult.downBitPerSec = downBitPerSec.get();
        iResult.upBitPerSec = upBitPerSec.get();

        iResult.setLogValues();

        return iResult;
    }

    public TestStatus getStatus()
    {
        return testStatus.get();
    }

    public TestStatus getStatusBeforeError()
    {
        return statusBeforeError.get();
    }

    public void setStatus(final TestStatus status)
    {
        testStatus.set(status);
        statusChangeTime.set(System.nanoTime());
        if (status == TestStatus.INIT_UP)
        {
            // DOWN is finished
            downBitPerSec.set(Math.round(getTotalSpeed()));
            resetSpeed();
        }
    }

    public void startTrafficService(final int threadId, final TestStatus status) {
    	if (trafficService != null) {
    		//a concurrent map is needed in case multiple threads want to start the traffic service
    		//only the first thread should be able to start the service
    		TestMeasurement tm = new TestMeasurement(status.toString(), trafficService);
        	TestMeasurement previousTm = measurementMap.putIfAbsent(status, tm);
        	if (previousTm == null) {
        		tm.start(threadId);
        	}
    	}
    }

    public void stopTrafficMeasurement(final int threadId, final TestStatus status) {
    	final TestMeasurement testMeasurement = measurementMap.get(status);
    	if (testMeasurement != null)
    	    testMeasurement.stop(threadId);
    }

    public String getErrorMsg()
    {
        return errorMsg;
    }

    public void sendResult(final JSONObject additionalValues)
    {
    	if (controlConnection != null) {
    		final String errorMsg = controlConnection.sendTestResult(result, additionalValues);
            if (errorMsg != null)
            {
                setErrorStatus();
                log("Error sending Result...");
                log(errorMsg);
            }
    	}
    }

    public void sendQoSResult(final QoSResultCollector qosResult) {
    	if (controlConnection != null) {
    		final String errorMsg = controlConnection.sendQoSResult(result, qosResult.toJson());
            if (errorMsg != null)
            {
                setErrorStatus();
                log("Error sending QoS Result...");
                log(errorMsg);
            }
    	}
    }

    private void setErrorStatus()
    {
        final TestStatus lastStatus = testStatus.getAndSet(TestStatus.ERROR);
        if (lastStatus != TestStatus.ERROR)
            statusBeforeError.set(lastStatus);
    }

    void log(final CharSequence text)
    {
        if (outputToStdout)
            System.out.println(text);
        if (outputCallback != null)
            outputCallback.log(text);
    }

    void log(final Exception e)
    {
        if (outputToStdout)
            e.printStackTrace(System.out);
        if (outputCallback != null)
            outputCallback.log(String.format(Locale.US, "Error: %s", e.getMessage()));
    }

    void setInitTime(final long initDuration) {
    	initNano.set(initDuration);
    }

    long getInitTime() {
    	return initNano.get();
    }

    void setPing(final long shortestPing)
    {
        pingNano.set(shortestPing);
    }

    void updatePingStatus(final long tsStart, int pingsDone, long tsLastPing)
    {
        pingTsStart.set(tsStart);
        pingNumDome.set(pingsDone);
        pingTsLastPing.set(tsLastPing);
    }

    private float getPingProgress()
    {
        final long start = pingTsStart.get();

        if (start == -1) // not yet started
            return 0;

        final int numDone = pingNumDome.get();
        final long lastPing = pingTsLastPing.get();
        final long now = System.nanoTime();

        final int numPings = params.getNumPings();

        if (numPings <= 0) // nothing to do
            return 1;

        final float factorPerPing = (float)1 / (float)numPings;
        final float base = factorPerPing * numDone;

        final long approxTimePerPing;
        if (numDone == 0 || lastPing == -1) // during first ping, assume 100ms
            approxTimePerPing = 100000000;
        else
            approxTimePerPing = (lastPing - start) / numDone;

        float factorLastPing = (float)(now - lastPing) / (float)approxTimePerPing;
        if (factorLastPing < 0)
            factorLastPing = 0;
        if (factorLastPing > 1)
            factorLastPing = 1;

        final float result = base + factorLastPing * factorPerPing;
        if (result < 0)
            return 0;
        if (result > 1)
            return 1;

//        System.out.println("atpp: " + approxTimePerPing + "; flp:" + factorLastPing+ "; res:" +result);
        return result;
    }

    public String getPublicIP()
    {
        if (controlConnection == null)
            return null;
        return controlConnection.getRemoteIp();
    }

    public String getServerName()
    {
        if (controlConnection == null)
            return null;
        return controlConnection.getServerName();
    }

    public String getProvider()
    {
        if (controlConnection == null)
            return null;
        return controlConnection.getProvider();
    }

    public String getTestUuid()
    {
        if (controlConnection == null)
            return null;
        return controlConnection.getTestUuid();
    }

    public ControlServerConnection getControlConnection()
    {
        return controlConnection;
    }

    /**
     *
     * @return
     */
	public List<TaskDesc> getTaskDescList() {
		return taskDescList;
	}

}


text:
        <title>Content Contributor programme | Champion-FX.com</title>

Partnerships

Content Contributor programme

Are you a successful financial trader or investment coach with extensive speaking and writing experiences?

Join us as a content contributor and position yourself as a leading expert on binary options trading and the financial markets.

What does a ChampionFX content contributor do?

Contribute webinars, ebooks, and market reports that help our prospects and clients:

Master strategies and popular techniques for trading.

Keep up with the latest news in the financial markets.

Use the latest industry trends to their advantage.

Why should I join the ChampionFX Content Contributor programme?

Enhanced reputation

Join the ranks of the world's most successful traders.

Wider reach

Extend your reach through free marketing campaigns.

Earn commission

Convert viewers and readers into ChampionFX clients.

                            Apply now

Note: Your commission is generated through clients who trade using both Champion Trader and MT5 platforms.


text:
/* @flow */

import React, { Component } from 'react';
import { connect } from 'react-redux';

import { FeedbackButton } from '../../feedback';
import UIEvents from '../../../../service/UI/UIEvents';

import {
    toggleSideToolbarContainer
} from '../actions';
import { getToolbarClassNames } from '../functions';
import Toolbar from './Toolbar';

declare var APP: Object;

/**
 * Implementation of secondary toolbar React component.
 *
 * @class SecondaryToolbar
 * @extends Component
 */
class SecondaryToolbar extends Component {
    state: Object;

    /**
     * Secondary toolbar property types.
     *
     * @static
     */
    static propTypes = {
        /**
         * The indicator which determines whether the local participant is a
         * guest in the conference.
         */
        _isGuest: React.PropTypes.bool,

        /**
         * Handler dispatching toggle toolbar container.
         */
        _onSideToolbarContainerToggled: React.PropTypes.func,

        /**
         * Contains map of secondary toolbar buttons.
         */
        _secondaryToolbarButtons: React.PropTypes.instanceOf(Map),

        /**
         * Shows whether toolbox is visible.
         */
        _visible: React.PropTypes.bool
    };

    /**
     * Register legacy UI listener.
     *
     * @returns {void}
     */
    componentDidMount(): void {
        APP.UI.addListener(
            UIEvents.SIDE_TOOLBAR_CONTAINER_TOGGLED,
            this.props._onSideToolbarContainerToggled);
    }

    /**
     * Unregisters legacy UI listener.
     *
     * @returns {void}
     */
    componentWillUnmount(): void {
        APP.UI.removeListener(
            UIEvents.SIDE_TOOLBAR_CONTAINER_TOGGLED,
            this.props._onSideToolbarContainerToggled);
    }

    /**
     * Renders secondary toolbar component.
     *
     * @returns {ReactElement}
     */
    render(): ReactElement<*> | null {
        const { _secondaryToolbarButtons } = this.props;

        // The number of buttons to show in the toolbar isn't fixed, it depends
        // on the availability of features and configuration parameters. So
        // there may be nothing to render.
        if (_secondaryToolbarButtons.size === 0) {
            return null;
        }

        const { secondaryToolbarClassName } = getToolbarClassNames(this.props);

        return (
            <Toolbar
                className = { secondaryToolbarClassName }
                toolbarButtons = { _secondaryToolbarButtons }
                tooltipPosition = { 'right' }>
                <FeedbackButton />
            </Toolbar>
        );
    }
}

/**
 * Maps some of Redux actions to component's props.
 *
 * @param {Function} dispatch - Redux action dispatcher.
 * @returns {{
 *     _onSideToolbarContainerToggled
 * }}
 * @private
 */
function _mapDispatchToProps(dispatch: Function): Object {
    return {

        /**
         * Dispatches an action signalling that side toolbar container is
         * toggled.
         *
         * @param {string} containerId - Id of side toolbar container.
         * @returns {Object} Dispatched action.
         */
        _onSideToolbarContainerToggled(containerId: string) {
            dispatch(toggleSideToolbarContainer(containerId));
        }
    };
}

/**
 * Maps part of Redux state to component's props.
 *
 * @param {Object} state - Snapshot of Redux store.
 * @returns {{
 *     _isGuest: boolean,
 *     _secondaryToolbarButtons: Map,
 *     _visible: boolean
 * }}
 * @private
 */
function _mapStateToProps(state: Object): Object {
    const { isGuest } = state['features/jwt'];
    const { secondaryToolbarButtons, visible } = state['features/toolbox'];

    return {
        /**
         * The indicator which determines whether the local participant is a
         * guest in the conference.
         *
         * @private
         * @type {boolean}
         */
        _isGuest: isGuest,

        /**
         * Default toolbar buttons for secondary toolbar.
         *
         * @private
         * @type {Map}
         */
        _secondaryToolbarButtons: secondaryToolbarButtons,

        /**
         * The indicator which determines whether the {@code SecondaryToolbar}
         * is visible.
         *
         * @private
         * @type {boolean}
         */
        _visible: visible
    };
}

export default connect(_mapStateToProps, _mapDispatchToProps)(SecondaryToolbar);


text:
package org.hisp.dhis.tracker.preheat.mappers;

import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.mapstruct.BeanMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

@Mapper( uses = {
    AttributeValueMapper.class
} )
public interface OrganisationUnitMapper
    extends PreheatMapper<OrganisationUnit>
{
    OrganisationUnitMapper INSTANCE = Mappers.getMapper( OrganisationUnitMapper.class );

    @Override
    @BeanMapping( ignoreByDefault = true )
    @Mapping( target = "id" )
    @Mapping( target = "uid" )
    @Mapping( target = "code" )
    @Mapping( target = "name" )
    @Mapping( target = "attributeValues" )
    @Mapping( target = "user" )
    @Mapping( target = "publicAccess" )
    @Mapping( target = "externalAccess" )
    @Mapping( target = "userGroupAccesses" )
    @Mapping( target = "userAccesses" )
    @Mapping( target = "parent", qualifiedByName = "parentMapper" )
    OrganisationUnit map( OrganisationUnit organisationUnit );

    /**
     * Makes sure that the parent OU is only mapped by fetching the UID
     *
     */
    @Named( "parentMapper" )
    @BeanMapping( ignoreByDefault = true )
    @Mapping( target = "uid" )
    @Mapping( target = "parent", qualifiedByName = "parentMapper" )
    OrganisationUnit fetchParent( OrganisationUnit organisationUnit );
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package no.sintef.bvr.planner.operators;

import no.sintef.bvr.planner.State;
import no.sintef.bvr.planner.Status;
import no.sintef.bvr.planner.operators.interfaces.IIsExpression;

/**
 *
 * @author franckc
 */
public class IsNegative implements IIsExpression {

    private final String featureName;

    public IsNegative(String feature) {
        this.featureName = feature;
    }

    @Override
    public boolean evaluateOn(State state) {
        return state.isNegative(featureName);
    }

    @Override
    public State applyTo(State state) {
        return state.copyAndSet(featureName, Status.NEGATIVE);
    }

    @Override
    public String toString() {
        return "IsNegative("+ featureName + ')';
    }

	@Override
	public String getFeatureName() {
		return featureName;
	}
}


text:
package com.mingsoft.basic.security;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;

import org.springframework.web.context.WebApplicationContext;

import com.mingsoft.base.constant.Const;

/**
 *
 * 权限过滤器
 * @author killfen QQ:78750478
 * @version
 * 版本号:100-000-000

 * 创建日期:2015年9月8日

 * 历史修订:

 */
@WebFilter(filterName = "baseAuthFilter", urlPatterns = "/*")
public class BaseAuthFilter extends org.springframework.web.filter.DelegatingFilterProxy {

	@Override
	protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
		// TODO Auto-generated method stub
		Const.BASE = wac.getServletContext().getContextPath();
		Const.PROJECT_PATH = wac.getServletContext().getRealPath("/");
		return super.initDelegate(wac);
	}

}


text:
from smart.interfaces.qt.progress import QtProgress
from smart.interfaces.qt.changes import QtChanges
from smart.interfaces.qt.log import QtLog
from smart.interface import Interface, getScreenWidth
from smart.fetcher import Fetcher
from smart.const import DEBUG
from smart import *
import qt
import sys

app = qt.QApplication(sys.argv)

class QtInterface(Interface):

    def _currentThread(self):
        if hasattr(qt, 'QThread'):
            return qt.QThread.currentThread()
        else:
            return None

    def __init__(self, ctrl, argv):
        Interface.__init__(self, ctrl)
        self._log = QtLog()
        self._progress = QtProgress(False)
        self._progress.setMainThread(self._currentThread())
        self._hassubprogress = QtProgress(True)
        self._hassubprogress.setMainThread(self._currentThread())
        self._changes = QtChanges()
        self._window = None
        self._sys_excepthook = sys.excepthook

    def run(self, command=None, argv=None):
        self.setCatchExceptions(True)
        result = Interface.run(self, command, argv)
        self.setCatchExceptions(False)
        return result

    def eventsPending(self):
        return qt.QApplication.eventLoop().hasPendingEvents()

    def processEvents(self):
        qt.QApplication.eventLoop().processEvents(qt.QEventLoop.AllEvents)

    def getProgress(self, obj, hassub=False):
        if hassub:
            self._progress.hide()
            fetcher = isinstance(obj, Fetcher) and obj or None
            self._hassubprogress.setFetcher(fetcher)
            return self._hassubprogress
        else:
            self._hassubprogress.hide()
            return self._progress

    def getSubProgress(self, obj):
        return self._hassubprogress

    def askYesNo(self, question, default=False):
        response = qt.QMessageBox.question(self._window,
                                        _("Question..."),
                                        question,
                                        qt.QMessageBox.Yes,
                                        qt.QMessageBox.No)

        if response == qt.QMessageBox.Yes:
            return True
        elif response == qt.QMessageBox.No:
            return False
        else:
            return default

    def askContCancel(self, question, default=False):
        response = qt.QMessageBox.question(self._window,
                                   _("Question..."),
                                   question,
                                   _("Continue"),
                                   _("Cancel"),
                                   )

        #response.setButtonText(QMessageBox.Ok, )

        if response == 0:
            return True
        elif response == 1:
            return False
        else:
            return default

    def askOkCancel(self, question, default=False):
        response = qt.QMessageBox.question(self._window,
                                   _("Question..."),
                                   question,
                                   qt.QMessageBox.Ok,
                                   qt.QMessageBox.Cancel)

        if response == qt.QMessageBox.Ok:
            return True
        elif response == qt.QMessageBox.Cancel:
            return False
        else:
            return default

    def askInput(self, prompt, message=None, widthchars=40, echo=True):
        if (message != None):
            stringToShow = message + "\n" + prompt
        else:
            stringToShow = prompt
        if echo:
            echoMode = qt.QLineEdit.Normal
        else:
            echoMode = qt.QLineEdit.Password

        text, ok = qt.QInputDialog.getText( _("Input"), stringToShow, echoMode)

        if (ok and text != None):
            return text[0:widthchars]
        else:
            return ""

    def insertRemovableChannels(self, channels):
        question = _("Insert one or more of the following removable "
                     "channels:\n")
        question += "\n"
        for channel in channels:
            question += "    "
            question += channel.getName()
            question += "\n"
        return self.askOkCancel(question, default=True)

    def message(self, level, msg):
        self._log.message(level, msg)

    def confirmChange(self, oldchangeset, newchangeset, expected=1):
        changeset = newchangeset.difference(oldchangeset)
        keep = []
        for pkg in oldchangeset:
            if pkg not in newchangeset:
                keep.append(pkg)
        if len(keep)+len(changeset) <= expected:
            return True
        return self._changes.showChangeSet(changeset, keep=keep, confirm=True)

    def confirmChangeSet(self, changeset):
        return self._changes.showChangeSet(changeset, confirm=True)

    # Non-standard interface methods

    def _excepthook(self, type, value, tb):
        if issubclass(type, Error) and not sysconf.get("log-level") is DEBUG:
            self._hassubprogress.hide()
            self._progress.hide()
            iface.error(unicode(value[0]))
        else:
            import traceback
            lines = traceback.format_exception(type, value, tb)
            iface.error("\n".join(lines))

    def setCatchExceptions(self, flag):
        if flag:
            sys.excepthook = self._excepthook
        else:
            sys.excepthook = self._sys_excepthook

    def hideProgress(self):
        self._progress.hide()
        self._hassubprogress.hide()

# vim:ts=4:sw=4:et


text:
//---------------------------------------------------------------------
// <copyright file="CodeDelegateInvokeExpression.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace System.CodeDom {

    using System.Diagnostics;
    using System;
    using System.Collections;
    using System.Runtime.InteropServices;

    /// <devdoc>
    ///    <para>
    ///       Represents an
    ///       expression that invokes a delegate.
    ///    </para>
    /// </devdoc>
    [
        ClassInterface(ClassInterfaceType.None),
        ComVisible(true),
        //Serializable,
    ]
    public class CodeDelegateInvokeExpression : CodeExpression {
        private CodeExpression targetObject;
        private CodeExpressionCollection parameters = new CodeExpressionCollection();

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='System.CodeDom.CodeDelegateInvokeExpression'/>.
        ///    </para>
        /// </devdoc>
        public CodeDelegateInvokeExpression() {
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='System.CodeDom.CodeDelegateInvokeExpression'/>.
        ///    </para>
        /// </devdoc>
        public CodeDelegateInvokeExpression(CodeExpression targetObject) {
            TargetObject = targetObject;
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of <see cref='System.CodeDom.CodeDelegateInvokeExpression'/>
        ///       .
        ///    </para>
        /// </devdoc>
        public CodeDelegateInvokeExpression(CodeExpression targetObject, params CodeExpression[] parameters) {
            TargetObject = targetObject;
            Parameters.AddRange(parameters);
        }

        /// <devdoc>
        ///    <para>
        ///       The
        ///       delegate's target object.
        ///    </para>
        /// </devdoc>
        public CodeExpression TargetObject {
            get {
                return targetObject;
            }
            set {
                this.targetObject = value;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       The
        ///       delegate parameters.
        ///    </para>
        /// </devdoc>
        public CodeExpressionCollection Parameters {
            get {
                return parameters;
            }
        }
    }
}