text:
import mock
from oslo_messaging.rpc import dispatcher as rpc
from oslo_utils import uuidutils
import six

from senlin.common import exception as exc
from senlin.db import api as db_api
from senlin.engine.actions import base as action_base
from senlin.engine import service
from senlin.tests.unit.common import base
from senlin.tests.unit.common import utils

class ActionTest(base.SenlinTestCase):

    def setUp(self):
        super(ActionTest, self).setUp()
        self.ctx = utils.dummy_context(project='action_test_project')
        self.eng = service.EngineService('host-a', 'topic-a')
        self.eng.init_tgm()

    @mock.patch.object(db_api, 'action_get')
    def test_action_find_by_uuid(self, mock_get):
        x_action = mock.Mock()
        mock_get.return_value = x_action

        aid = uuidutils.generate_uuid()
        result = self.eng.action_find(self.ctx, aid)

        self.assertEqual(x_action, result)
        mock_get.assert_called_once_with(self.ctx, aid, project_safe=True)

    @mock.patch.object(db_api, 'action_get_by_name')
    @mock.patch.object(db_api, 'action_get')
    def test_action_find_by_uuid_as_name(self, mock_get, mock_get_name):
        x_action = mock.Mock()
        mock_get_name.return_value = x_action
        mock_get.return_value = None

        aid = uuidutils.generate_uuid()
        result = self.eng.action_find(self.ctx, aid, False)

        self.assertEqual(x_action, result)
        mock_get.assert_called_once_with(self.ctx, aid, project_safe=False)
        mock_get_name.assert_called_once_with(self.ctx, aid,
                                              project_safe=False)

    @mock.patch.object(db_api, 'action_get_by_name')
    def test_action_find_by_name(self, mock_get_name):
        x_action = mock.Mock()
        mock_get_name.return_value = x_action

        aid = 'this-is-not-uuid'
        result = self.eng.action_find(self.ctx, aid)

        self.assertEqual(x_action, result)
        mock_get_name.assert_called_once_with(self.ctx, aid, project_safe=True)

    @mock.patch.object(db_api, 'action_get_by_short_id')
    @mock.patch.object(db_api, 'action_get_by_name')
    def test_action_find_by_shortid(self, mock_get_name, mock_get_shortid):
        x_action = mock.Mock()
        mock_get_shortid.return_value = x_action
        mock_get_name.return_value = None

        aid = 'abcd-1234-abcd'
        result = self.eng.action_find(self.ctx, aid, False)

        self.assertEqual(x_action, result)
        mock_get_name.assert_called_once_with(self.ctx, aid,
                                              project_safe=False)
        mock_get_shortid.assert_called_once_with(self.ctx, aid,
                                                 project_safe=False)

    @mock.patch.object(db_api, 'action_get_by_name')
    def test_action_find_not_found(self, mock_get_name):
        mock_get_name.return_value = None

        ex = self.assertRaises(exc.ActionNotFound,
                               self.eng.action_find,
                               self.ctx, 'bogus')
        self.assertEqual('The action (bogus) could not be found.',
                         six.text_type(ex))
        mock_get_name.assert_called_once_with(self.ctx, 'bogus',
                                              project_safe=True)

    @mock.patch.object(action_base.Action, 'load_all')
    def test_action_list(self, mock_load):
        x_1 = mock.Mock()
        x_1.to_dict.return_value = {'k': 'v1'}
        x_2 = mock.Mock()
        x_2.to_dict.return_value = {'k': 'v2'}

        mock_load.return_value = [x_1, x_2]

        result = self.eng.action_list(self.ctx)
        expected = [{'k': 'v1'}, {'k': 'v2'}]
        self.assertEqual(expected, result)

        mock_load.assert_called_once_with(self.ctx, filters=None, limit=None,
                                          marker=None, sort=None,
                                          project_safe=True)

    @mock.patch.object(action_base.Action, 'load_all')
    def test_action_list_with_params(self, mock_load):
        mock_load.return_value = []

        result = self.eng.action_list(self.ctx, filters='F', limit=1,
                                      marker='M', sort='status',
                                      project_safe=True)

        self.assertEqual([], result)

        mock_load.assert_called_once_with(self.ctx, filters='F', limit=1,
                                          marker='M', sort='status',
                                          project_safe=True)

    def test_action_list_with_bad_params(self):
        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_list,
                               self.ctx, limit='large')
        self.assertEqual(exc.InvalidParameter, ex.exc_info[0])

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_list,
                               self.ctx, sort='crazykey')
        self.assertEqual(exc.InvalidParameter, ex.exc_info[0])

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_list,
                               self.ctx, project_safe='yes')
        self.assertEqual(exc.InvalidParameter, ex.exc_info[0])

    @mock.patch.object(action_base.Action, 'load_all')
    def test_action_list_with_project_safe(self, mock_load):
        mock_load.return_value = []

        result = self.eng.action_list(self.ctx)
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, filters=None, limit=None,
                                          sort=None, marker=None,
                                          project_safe=True)
        mock_load.reset_mock()

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_list,
                               self.ctx, project_safe=False)
        self.assertEqual(exc.Forbidden, ex.exc_info[0])

        self.ctx.is_admin = True

        result = self.eng.action_list(self.ctx)
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, filters=None, limit=None,
                                          sort=None, marker=None,
                                          project_safe=True)
        mock_load.reset_mock()

        result = self.eng.action_list(self.ctx, project_safe=True)
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, filters=None, limit=None,
                                          sort=None, marker=None,
                                          project_safe=True)
        mock_load.reset_mock()

        result = self.eng.action_list(self.ctx, project_safe=False)
        self.assertEqual([], result)
        mock_load.assert_called_once_with(self.ctx, filters=None, limit=None,
                                          sort=None, marker=None,
                                          project_safe=False)

    @mock.patch.object(action_base.Action, 'create')
    @mock.patch.object(service.EngineService, 'cluster_find')
    def test_action_create(self, mock_find, mock_action):
        mock_find.return_value = mock.Mock(id='FAKE_CLUSTER')
        mock_action.return_value = 'ACTION_ID'

        result = self.eng.action_create(self.ctx, 'a1', 'C1', 'OBJECT_ACTION')

        self.assertEqual({'action': 'ACTION_ID'}, result)
        mock_find.assert_called_once_with(self.ctx, 'C1')
        mock_action.assert_called_once_with(
            self.ctx, 'FAKE_CLUSTER', 'OBJECT_ACTION',
            name='a1',
            cause=action_base.CAUSE_RPC,
            status=action_base.Action.READY,
            inputs={})

    @mock.patch.object(service.EngineService, 'cluster_find')
    def test_action_create_cluster_not_found(self, mock_find):
        mock_find.side_effect = exc.ClusterNotFound(cluster='C1')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_create,
                               self.ctx, 'a1', 'C1', 'OBJECT_ACTION')

        self.assertEqual(exc.ClusterNotFound, ex.exc_info[0])
        mock_find.assert_called_once_with(self.ctx, 'C1')

    @mock.patch.object(action_base.Action, 'load')
    @mock.patch.object(service.EngineService, 'action_find')
    def test_action_get(self, mock_find, mock_load):
        x_obj = mock.Mock()
        mock_find.return_value = x_obj
        x_action = mock.Mock()
        x_action.to_dict.return_value = {'k': 'v'}
        mock_load.return_value = x_action

        result = self.eng.action_get(self.ctx, 'ACTION_ID')

        self.assertEqual({'k': 'v'}, result)
        mock_find.assert_called_once_with(self.ctx, 'ACTION_ID')
        mock_load.assert_called_once_with(self.ctx, db_action=x_obj)

    @mock.patch.object(service.EngineService, 'action_find')
    def test_action_get_not_found(self, mock_find):
        mock_find.side_effect = exc.ActionNotFound(action='Bogus')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_get,
                               self.ctx, 'Bogus')
        self.assertEqual(exc.ActionNotFound, ex.exc_info[0])
        mock_find.assert_called_once_with(self.ctx, 'Bogus')

    @mock.patch.object(action_base.Action, 'delete')
    @mock.patch.object(service.EngineService, 'action_find')
    def test_action_delete(self, mock_find, mock_delete):
        x_obj = mock.Mock()
        x_obj.id = 'FAKE_ID'
        mock_find.return_value = x_obj
        mock_delete.return_value = None

        result = self.eng.action_delete(self.ctx, 'ACTION')
        self.assertIsNone(result)
        mock_find.assert_called_once_with(self.ctx, 'ACTION')
        mock_delete.assert_called_once_with(self.ctx, 'FAKE_ID')

    @mock.patch.object(action_base.Action, 'delete')
    @mock.patch.object(service.EngineService, 'action_find')
    def test_action_delete_resource_busy(self, mock_find, mock_delete):
        x_obj = mock.Mock()
        x_obj.id = 'FAKE_ID'
        mock_find.return_value = x_obj
        ex = exc.ResourceBusyError(resource_type='action',
                                   resource_id='FAKE_ID')
        mock_delete.side_effect = ex

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_delete,
                               self.ctx, 'ACTION')

        self.assertEqual(exc.ResourceInUse, ex.exc_info[0])
        mock_find.assert_called_once_with(self.ctx, 'ACTION')
        mock_delete.assert_called_once_with(self.ctx, 'FAKE_ID')

    @mock.patch.object(service.EngineService, 'action_find')
    def test_action_delete_not_found(self, mock_find):
        mock_find.side_effect = exc.ActionNotFound(action='Bogus')

        ex = self.assertRaises(rpc.ExpectedException,
                               self.eng.action_delete,
                               self.ctx, 'Bogus')

        self.assertEqual(exc.ActionNotFound, ex.exc_info[0])


text:
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "config.h"
#include "V8SVGFEFuncGElement.h"

#if ENABLE(SVG) && ENABLE(FILTERS)

#include "RuntimeEnabledFeatures.h"
#include "V8Binding.h"
#include "V8BindingState.h"
#include "V8DOMWrapper.h"
#include "V8IsolatedContext.h"
#include "V8Proxy.h"
#include "V8SVGComponentTransferFunctionElement.h"
#include <wtf/UnusedParam.h>

namespace WebCore {

WrapperTypeInfo V8SVGFEFuncGElement::info = { V8SVGFEFuncGElement::GetTemplate, V8SVGFEFuncGElement::derefObject, 0, &V8SVGComponentTransferFunctionElement::info };

namespace SVGFEFuncGElementInternal {

template <typename T> void V8_USE(T) { }

} // namespace SVGFEFuncGElementInternal

static v8::Persistent<v8::FunctionTemplate> ConfigureV8SVGFEFuncGElementTemplate(v8::Persistent<v8::FunctionTemplate> desc)
{
    desc->ReadOnlyPrototype();

    v8::Local<v8::Signature> defaultSignature = configureTemplate(desc, "SVGFEFuncGElement", V8SVGComponentTransferFunctionElement::GetTemplate(), V8SVGFEFuncGElement::internalFieldCount,
        0, 0,
        0, 0);
    UNUSED_PARAM(defaultSignature); // In some cases, it will not be used.

    // Custom toString template
    desc->Set(getToStringName(), getToStringTemplate());
    return desc;
}

v8::Persistent<v8::FunctionTemplate> V8SVGFEFuncGElement::GetRawTemplate()
{
    V8BindingPerIsolateData* data = V8BindingPerIsolateData::current();
    V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info);
    if (result != data->rawTemplateMap().end())
        return result->second;

    v8::HandleScope handleScope;
    v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate();
    data->rawTemplateMap().add(&info, templ);
    return templ;
}

v8::Persistent<v8::FunctionTemplate> V8SVGFEFuncGElement::GetTemplate()
{
    V8BindingPerIsolateData* data = V8BindingPerIsolateData::current();
    V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info);
    if (result != data->templateMap().end())
        return result->second;

    v8::HandleScope handleScope;
    v8::Persistent<v8::FunctionTemplate> templ =
        ConfigureV8SVGFEFuncGElementTemplate(GetRawTemplate());
    data->templateMap().add(&info, templ);
    return templ;
}

bool V8SVGFEFuncGElement::HasInstance(v8::Handle<v8::Value> value)
{
    return GetRawTemplate()->HasInstance(value);
}

v8::Handle<v8::Object> V8SVGFEFuncGElement::wrapSlow(SVGFEFuncGElement* impl)
{
    v8::Handle<v8::Object> wrapper;
    V8Proxy* proxy = 0;
    if (impl->document()) {
        proxy = V8Proxy::retrieve(impl->document()->frame());
        if (proxy && static_cast<Node*>(impl->document()) == static_cast<Node*>(impl)) {
            if (proxy->windowShell()->initContextIfNeeded()) {
                // initContextIfNeeded may have created a wrapper for the object, retry from the start.
                return V8SVGFEFuncGElement::wrap(impl);
            }
        }
    }

    v8::Handle<v8::Context> context;
    if (proxy)
        context = proxy->context();

    // Enter the node's context and create the wrapper in that context.
    if (!context.IsEmpty())
        context->Enter();
    wrapper = V8DOMWrapper::instantiateV8Object(proxy, &info, impl);
    // Exit the node's context if it was entered.
    if (!context.IsEmpty())
        context->Exit();
    if (wrapper.IsEmpty())
        return wrapper;

    impl->ref();
    v8::Persistent<v8::Object> wrapperHandle = v8::Persistent<v8::Object>::New(wrapper);

    if (!hasDependentLifetime)
        wrapperHandle.MarkIndependent();
    wrapperHandle.SetWrapperClassId(v8DOMSubtreeClassId);
    getDOMNodeMap().set(impl, wrapperHandle);
    return wrapper;
}

void V8SVGFEFuncGElement::derefObject(void* object)
{
    static_cast<SVGFEFuncGElement*>(object)->deref();
}

} // namespace WebCore

#endif // ENABLE(SVG) && ENABLE(FILTERS)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.gobblin.writer;

import org.testng.Assert;
import org.testng.annotations.Test;

import org.apache.gobblin.source.extractor.DefaultCheckpointableWatermark;
import org.apache.gobblin.source.extractor.extract.LongWatermark;

@Test
public class WatermarkTrackerTest {

  private void commits(WatermarkTracker watermarkTracker, String source, int... commit)
  {
    for (int oneCommit: commit) {
      watermarkTracker.committedWatermark(new DefaultCheckpointableWatermark(source, new LongWatermark(oneCommit)));
    }
  }

  @Test
  public void testSingleSource() {

    MultiWriterWatermarkTracker watermarkTracker = new MultiWriterWatermarkTracker();
    commits(watermarkTracker, "default", 0, 4, 5, 6);

    Assert.assertEquals(watermarkTracker.getCommittableWatermark("default").get().getSource(), "default");
    Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("default")
        .get().getWatermark()).getValue(), 6L);
  }

  @Test
  public void testMultiSource() {
    MultiWriterWatermarkTracker watermarkTracker = new MultiWriterWatermarkTracker();
    commits(watermarkTracker, "default", 0, 4, 5, 6);
    commits(watermarkTracker, "other", 1, 3, 5, 7);

    Assert.assertEquals(watermarkTracker.getCommittableWatermark("default").get().getSource(), "default");
    Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("default")
        .get().getWatermark()).getValue(), 6L);
    Assert.assertEquals(watermarkTracker.getCommittableWatermark("other").get().getSource(), "other");
    Assert.assertEquals(((LongWatermark) watermarkTracker.getCommittableWatermark("other")
        .get().getWatermark()).getValue(), 7L);

  }

}


text:
MANAJEMEN PASSWORD

	<?php echo validation_errors(); ?>

<?php echo $this->session->flashdata("result_login"); ?>

	<?php echo form_open("admin_panitia/password/simpan"); ?>
	USERNAME :
	<input type="text" name="username" id="username" placeholder="Username...." value="<?php echo $username; ?>" readonly="true" />
	PASSWORD LAMA :
	<input type="password" name="password_lama" id="password_lama" placeholder="Masukkan password lama...." />
	PASSWORD BARU :
	<input type="password" name="password_baru" id="password_baru" placeholder="Masukkan password baru...." />
	ULANGI PASSWORD BARU :
	<input type="password" name="ulangi_password" id="ulangi_password" placeholder="Masukkan ulang password baru...." />
	<input type="hidden" name="id_param" value="<?php echo $id_param; ?>" />

		<input type="submit" value="UPDATE DATA" />
		<input type="reset" value="HAPUS" />

	<?php echo form_close(); ?>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.joshsCode;

import com.sun.squawk.util.MathUtils;
import edu.wpi.first.wpilibj.RobotDrive;

/**
 *
 * @author Warbots
 */
public class DriveMethods {

    public static void quadraticTankDrive(RobotDrive drive, double argDeadzone, double argLeftY, double argRightY) {
        //Deadzone is essentially a gate. Any input less than that will simply not be reported
        //Sensitivity coefficient makes Joystick.getY() equal to Joystick.getY() * (sensitiveCoefficients)
        double deadzone = argDeadzone;
        double leftY  =  argLeftY;
        double rightY = argRightY;
        //Lefty and righty! Ha! I'm so witty... (Not really)
        //Anyway, these are simply the y axis values from each stick
        if (Math.abs(leftY) < deadzone) {
            leftY = 0.0;
        } else {
            leftY *= Math.abs(leftY);
        }
        if (Math.abs(rightY) < deadzone) {
            rightY = 0.0;
        } else {
            rightY *= Math.abs(rightY);
        }
        drive.tankDrive(leftY, rightY);
    }

    public static void linearTankDrive(RobotDrive drive, double argDeadzone, double argSensitiveCoefficient, double argLeftY, double argRightY) {
        //Deadzone is essentially a gate. Any input less than that will simply not be reported
        //Sensitivity coefficient makes Joystick.getY() equal to Joystick.getY() * (sensitiveCoefficients)
        double deadzone = argDeadzone;
        double sensitiveCoefficient = argSensitiveCoefficient;
        double leftY  = argLeftY;
        double rightY = argRightY;
        //Lefty and righty! Ha! I'm so witty... (Not really)
        //Anyway, these are simply the y axis values from each stick
        if (Math.abs(leftY) < deadzone) {
            leftY = 0.0;
        } else {
            leftY *= sensitiveCoefficient;
        }
        if (Math.abs(rightY) < deadzone) {
            rightY = 0.0;
        } else {
            rightY *= sensitiveCoefficient;
        }
        drive.tankDrive(leftY, rightY);
    }

    public static void exponentialTankDrive(RobotDrive drive, double argDeadzone, double argLeftY, double argRightY) {
        double deadzone = argDeadzone;
        double leftY = argLeftY;
        double rightY = argRightY;
        if (Math.abs(leftY) < deadzone) {
            leftY = 0.0;
        } else {
            leftY = MathUtils.pow(2, Math.abs(leftY)) - 1;
            if (argLeftY < 0) {
                leftY *= -1;
            }
        }
        if (Math.abs(rightY) < deadzone) {
            rightY = 0.0;
        } else {
            rightY = MathUtils.pow(2, Math.abs(rightY)) - 1;
            if (argRightY < 0) {
                rightY *= -1;
            }
        }
        //System.out.println(leftY + " " + rightY);
    drive.tankDrive(leftY,rightY);
    }
}


text:
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import axios from 'axios';
import reducer from '../reducers';
import * as constants from '../utils/constants';

function configureStore(initialState) {
// Add a response interceptor

  const enhancers = compose(
    // Middleware store enhancer.

    applyMiddleware(
      // Initialising redux-thunk with extra arguments will pass the below
      // arguments to all the redux-thunk actions. Below we are passing a
      // preconfigured axios instance which can be used to fetch data with.
      // @see https://github.com/gaearon/redux-thunk

      thunk.withExtraArgument({ axios }),
    ),
    // Redux Dev Tools store enhancer.
    // @see https://github.com/zalmoxisus/redux-devtools-extension
    // We only want this enhancer enabled for development and when in a browser
    // with the extension installed.
    process.env.NODE_ENV === 'development'
      && typeof window !== 'undefined'
      && typeof window.devToolsExtension !== 'undefined'
      // Call the brower extension function to create the enhancer.
      ? window.devToolsExtension()
      // Else we return a no-op function.
      : f => f,
  );

  const store = initialState
    ? createStore(reducer, initialState, enhancers)
    : createStore(reducer, enhancers);

  if (process.env.NODE_ENV === 'development' && module.hot) {
    // Enable Webpack hot module replacement for reducers. This is so that we
    // don't lose all of our current application state during hot reloading.
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers').default; // eslint-disable-line global-require

      store.replaceReducer(nextRootReducer);
    });
  }

  axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    if(error.response.status == 401 && error.response.request.responseURL !== constants.baseAPIUrl+"auth/login"){
      localStorage.removeItem("token");
      window.location.href="/login"
    }
    return Promise.reject(error);
  });

  return store;
}

// NOTE: If we create an '/api' endpoint in our application then we will neeed to
// configure the axios instances so that they will resolve to the proper URL
// endpoints on the server. We have to provide absolute URLs for any of our
// server bundles. To do so we can set the default 'baseURL' for axios. Any
// relative path requests will then be appended to the 'baseURL' in order to
// form an absolute URL.
// We don't need to worry about this for client side executions, relative paths
// will work fine there.
// Example:
//
// const axiosConfig = process.env.IS_NODE === true
//   ? { baseURL: process.env.NOW_URL || notEmpty(process.env.SERVER_URL) }
//   : {};
//
// Then we will then have to initialise our redux-thunk middlware like so:
//
// thunk.withExtraArgument({
//   axios: axios.create(axiosConfig),
// })

export default configureStore;


text:
package net.kwas.impatient.ch5

import org.scalatest._

class TimeSpec extends FlatSpec with Matchers {

  behavior of "A Time with ten hours and 5 minutes"
  val base = new Time(10, 5)

  it should "be before a Time with eleven hours" in {
    val other = new Time(11, 0)
    base.before(other) should be (true)
  }

  it should "be before a Time with ten hours and ten minutes" in {
    val other = new Time(10, 10)
    base.before(other) should be (true)
  }

  it should "not be before a Time with nine hours" in {
    val other = new Time(9, 0)
    base.before(other) should be (false)
  }

  it should "not be before a Time with ten hours and one minute" in {
    val other = new Time(10, 1)
    base.before(other) should be (false)
  }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- Enable auto-wiring -->
    <context:annotation-config/>

    <!-- Scan for auto-wiring classes in spring saml packages -->
    <context:component-scan base-package="org.springframework.security.saml"/>

    <!-- Security for the administration UI -->
    <!--<security:http pattern="/saml/**" use-expressions="false">-->
        <!--<security:access-denied-handler error-page="/saml/metadata/login"/>-->
        <!--<security:form-login login-processing-url="/saml/metadata/login" login-page="/saml/metadata/login" default-target-url="/saml/metadata"/>-->
        <!--<security:intercept-url pattern="/saml/metadata/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>-->
        <!--<security:intercept-url pattern="/saml/**" access="ROLE_ADMIN"/>-->
        <!--<security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>-->
    <!--</security:http>-->

    <!--<!– Secured pages with SAML as entry point –>-->
    <!--<security:http entry-point-ref="samlEntryPoint" use-expressions="false">-->
        <!--<security:intercept-url pattern="/saml/*" access="IS_AUTHENTICATED_FULLY"/>-->
        <!--<security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>-->
        <!--<security:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>-->
    <!--</security:http>-->

    <!-- Filters for processing of SAML messages -->
    <!--<bean id="samlFilter" class="org.springframework.security.web.FilterChainProxy">-->
        <!--<security:filter-chain-map request-matcher="ant">-->
            <!--<security:filter-chain pattern="/saml/login/**" filters="samlEntryPoint"/>-->
            <!--<security:filter-chain pattern="/saml/logout/**" filters="samlLogoutFilter"/>-->
            <!--<security:filter-chain pattern="/saml/metadata/**" filters="metadataDisplayFilter"/>-->
            <!--<security:filter-chain pattern="/saml/SSO/**" filters="samlWebSSOProcessingFilter"/>-->
            <!--<security:filter-chain pattern="/saml/SSOHoK/**" filters="samlWebSSOHoKProcessingFilter"/>-->
            <!--<security:filter-chain pattern="/saml/SingleLogout/**" filters="samlLogoutProcessingFilter"/>-->
            <!--<security:filter-chain pattern="/saml/discovery/**" filters="samlIDPDiscovery"/>-->
        <!--</security:filter-chain-map>-->
    <!--</bean>-->

    <!-- Handler deciding where to redirect user after successful login -->
    <!--<bean id="successRedirectHandler"-->
          <!--class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">-->
        <!--<property name="defaultTargetUrl" value="/"/>-->
    <!--</bean>-->
    <!--
    Use the following for interpreting RelayState coming from unsolicited response as redirect URL:
    <bean id="successRedirectHandler" class="org.springframework.security.saml.SAMLRelayStateSuccessHandler">
       <property name="defaultTargetUrl" value="/" />
    </bean>
    -->

    <!-- Handler deciding where to redirect user after failed login -->
    <!--<bean id="failureRedirectHandler"-->
          <!--class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">-->
        <!--<property name="useForward" value="true"/>-->
        <!--<property name="defaultFailureUrl" value="/error"/>-->
    <!--</bean>-->

    <!-- Handler for successful logout -->
    <!--<bean id="successLogoutHandler" class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">-->
        <!--<property name="defaultTargetUrl" value="/sso/web/logout"/>-->
    <!--</bean>-->

    <!--<security:authentication-manager alias="authenticationManager">-->
        <!--<!– Register authentication manager for SAML provider –>-->
        <!--<security:authentication-provider ref="samlAuthenticationProvider"/>-->
        <!--<!– Register authentication manager for administration UI –>-->
        <!--<security:authentication-provider>-->
            <!--<security:user-service id="adminInterfaceService">-->
                <!--<security:user name="admin" password="admin" authorities="ROLE_ADMIN"/>-->
            <!--</security:user-service>-->
        <!--</security:authentication-provider>-->
    <!--</security:authentication-manager>-->

    <!-- Logger for SAML messages and events -->
    <bean id="samlLogger" class="org.springframework.security.saml.log.SAMLDefaultLogger"/>

    <!-- Central storage of cryptographic keys -->
    <bean id="keyManager" class="org.springframework.security.saml.key.JKSKeyManager">
        <constructor-arg value="classpath:security/samlKeystore.jks"/>
        <constructor-arg type="java.lang.String" value="nalle123"/>
        <constructor-arg>
            <map>
                <entry key="apollo" value="nalle123"/>
            </map>
        </constructor-arg>
        <constructor-arg type="java.lang.String" value="apollo"/>
    </bean>

    <!-- Entry point to initialize authentication, default values taken from properties file -->
    <bean id="samlEntryPoint" class="org.springframework.security.saml.SAMLEntryPoint">
        <property name="defaultProfileOptions">
            <ref bean="webSSOProfileOptions" />
        </property>
    </bean>

    <bean id="webSSOProfileOptions" class="org.springframework.security.saml.websso.WebSSOProfileOptions">
        <property name="includeScoping" value="false"/>
        <property name="providerName" value="platform_idp" />
        <property name="allowedIDPs">
            <set value-type="java.lang.String">
                <bean class="java.lang.String">
                    <constructor-arg value="${idphost}"/>
                </bean>
            </set>
        </property>
    </bean>

    <!-- IDP Discovery Service -->
    <bean id="samlIDPDiscovery" class="org.springframework.security.saml.SAMLDiscovery">
        <property name="idpSelectionPath" value="/idp/idpSelection"/>
    </bean>

    <!-- Filter automatically generates default SP metadata -->
    <bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
        <constructor-arg>
            <bean class="org.springframework.security.saml.metadata.MetadataGenerator">
                <property name="extendedMetadata">
                    <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        <property name="idpDiscoveryEnabled" value="true"/>
                    </bean>
                </property>
            </bean>
        </constructor-arg>
    </bean>

    <!-- The filter is waiting for connections on URL suffixed with filterSuffix and presents SP metadata there -->
    <bean id="metadataDisplayFilter" class="org.springframework.security.saml.metadata.MetadataDisplayFilter"/>

    <!-- Configure HTTP Client to accept certificates from the keystore for HTTPS verification -->
    <!--
    <bean class="org.springframework.security.saml.trust.httpclient.TLSProtocolConfigurer">
        <property name="sslHostnameVerification" value="default"/>
    </bean>
    -->

    <!-- sP Metadata configuration - paths to metadata of sPs in circle of trust is here -->
    <bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
        <constructor-arg>
            <list>
                <!-- Example of classpath metadata with Extended Metadata -->
                <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                    <constructor-arg>
                        <bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider">
                            <constructor-arg>
                                <bean class="java.util.Timer"/>
                            </constructor-arg>
                            <constructor-arg>
                                <bean class="org.opensaml.util.resource.ClasspathResource">
                                    <constructor-arg value="/metadata/sp.xml"/>
                                </bean>
                            </constructor-arg>
                            <property name="parserPool" ref="parserPool"/>
                        </bean>
                    </constructor-arg>
                    <constructor-arg>
                        <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        </bean>
                    </constructor-arg>
                </bean>
                <!-- Example of HTTP metadata without Extended Metadata -->
                <!--<bean class="org.opensaml.saml2.metadata.provider.HTTPMetadataProvider">-->
                    <!--<!– URL containing the metadata –>-->
                    <!--<constructor-arg>-->
                        <!--<value type="java.lang.String">http://idp.ssocircle.com/idp-meta.xml</value>-->
                    <!--</constructor-arg>-->
                    <!--<!– Timeout for metadata loading in ms –>-->
                    <!--<constructor-arg>-->
                        <!--<value type="int">15000</value>-->
                    <!--</constructor-arg>-->
                    <!--<property name="parserPool" ref="parserPool"/>-->
                <!--</bean>-->
                <!-- Example of file System metadata without Extended Metadata -->
                <!--
                <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
                    <constructor-arg>
                        <value type="java.io.File">/usr/local/metadata/sp.xml</value>
                    </constructor-arg>
                    <property name="parserPool" ref="parserPool"/>
                </bean>
                -->
            </list>
        </constructor-arg>
        <!-- OPTIONAL used when one of the metadata files contains information about this service provider -->
        <!-- <property name="hostedSPName" value=""/> -->
        <!-- OPTIONAL property: can tell the System which IDP should be used for authenticating user by default. -->
        <!-- <property name="defaultIDP" value="http://localhost:8080/opensso"/> -->
    </bean>

    <!-- SAML Authentication Provider responsible for validating of received SAML messages -->
    <bean id="samlAuthenticationProvider" class="org.springframework.security.saml.SAMLAuthenticationProvider">
        <!-- OPTIONAL property: can be used to store/load user data after login -->
        <!--
        <property name="userDetails" ref="bean" />
        -->
    </bean>

    <!-- Provider of default SAML Context -->
    <bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderImpl"/>

    <!-- Processing filter for WebSSO profile messages -->
    <!--<bean id="samlWebSSOProcessingFilter" class="org.springframework.security.saml.SAMLProcessingFilter">-->
        <!--<property name="authenticationManager" ref="authenticationManager"/>-->
        <!--<property name="authenticationSuccessHandler" ref="successRedirectHandler"/>-->
        <!--<property name="authenticationFailureHandler" ref="failureRedirectHandler"/>-->
    <!--</bean>-->

    <!-- Processing filter for WebSSO Holder-of-Key profile -->
    <!--<bean id="samlWebSSOHoKProcessingFilter" class="org.springframework.security.saml.SAMLWebSSOHoKProcessingFilter">-->
        <!--<property name="authenticationManager" ref="authenticationManager"/>-->
        <!--<property name="authenticationSuccessHandler" ref="successRedirectHandler"/>-->
        <!--<property name="authenticationFailureHandler" ref="failureRedirectHandler"/>-->
    <!--</bean>-->

    <!-- Logout handler terminating local session -->
    <!--<bean id="logoutHandler"-->
          <!--class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">-->
        <!--<property name="invalidateHttpSession" value="false"/>-->
    <!--</bean>-->

    <!-- Override default logout processing filter with the one processing SAML messages -->
    <!--<bean id="samlLogoutFilter" class="org.springframework.security.saml.SAMLLogoutFilter">-->
        <!--<constructor-arg index="0" ref="successLogoutHandler"/>-->
        <!--<constructor-arg index="1" ref="logoutHandler"/>-->
        <!--<constructor-arg index="2" ref="logoutHandler"/>-->
    <!--</bean>-->

    <!-- Filter processing incoming logout messages -->
    <!-- First argument determines URL user will be redirected to after successful global logout -->
    <!--<bean id="samlLogoutProcessingFilter" class="org.springframework.security.saml.SAMLLogoutProcessingFilter">-->
        <!--<constructor-arg index="0" ref="successLogoutHandler"/>-->
        <!--<constructor-arg index="1" ref="logoutHandler"/>-->
    <!--</bean>-->

    <!-- Class loading incoming SAML messages from httpRequest stream -->
    <bean id="processor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
        <constructor-arg>
            <list>
                <ref bean="redirectBinding"/>
                <ref bean="postBinding"/>
                <ref bean="artifactBinding"/>
                <ref bean="soapBinding"/>
                <ref bean="paosBinding"/>
            </list>
        </constructor-arg>
    </bean>

    <!-- SAML 2.0 WebSSO Assertion Consumer -->
    <bean id="webSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerImpl"/>

    <!-- SAML 2.0 Holder-of-Key WebSSO Assertion Consumer -->
    <bean id="hokWebSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>

    <!-- SAML 2.0 Web SSO profile -->
    <bean id="webSSOprofile" class="org.springframework.security.saml.websso.WebSSOProfileImpl"/>

    <!-- SAML 2.0 Holder-of-Key Web SSO profile -->
    <bean id="hokWebSSOProfile" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>

    <!-- SAML 2.0 ECP profile -->
    <bean id="ecpprofile" class="org.springframework.security.saml.websso.WebSSOProfileECPImpl"/>

    <!-- SAML 2.0 Logout Profile -->
    <bean id="logoutprofile" class="org.springframework.security.saml.websso.SingleLogoutProfileImpl"/>

    <!-- Bindings, encoders and decoders used for creating and parsing messages -->
    <bean id="postBinding" class="org.springframework.security.saml.processor.HTTPPostBinding">
        <constructor-arg ref="parserPool"/>
        <constructor-arg ref="velocityEngine"/>
    </bean>

    <bean id="redirectBinding" class="org.springframework.security.saml.processor.HTTPRedirectDeflateBinding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <bean id="artifactBinding" class="org.springframework.security.saml.processor.HTTPArtifactBinding">
        <constructor-arg ref="parserPool"/>
        <constructor-arg ref="velocityEngine"/>
        <constructor-arg>
            <bean class="org.springframework.security.saml.websso.ArtifactResolutionProfileImpl">
                <constructor-arg>
                    <bean class="org.apache.commons.httpclient.HttpClient">
                        <constructor-arg>
                            <bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
                        </constructor-arg>
                    </bean>
                </constructor-arg>
                <property name="processor">
                    <bean class="org.springframework.security.saml.processor.SAMLProcessorImpl">
                        <constructor-arg ref="soapBinding"/>
                    </bean>
                </property>
            </bean>
        </constructor-arg>
    </bean>

    <bean id="soapBinding" class="org.springframework.security.saml.processor.HTTPSOAP11Binding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <bean id="paosBinding" class="org.springframework.security.saml.processor.HTTPPAOS11Binding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <!-- Initialization of OpenSAML library-->
    <bean class="org.springframework.security.saml.SAMLBootstrap"/>

    <!-- Initialization of the velocity engine -->
    <bean id="velocityEngine" class="org.springframework.security.saml.util.VelocityFactory" factory-method="getEngine"/>

    <!-- XML parser pool needed for OpenSAML parsing -->
    <bean id="parserPool" class="org.opensaml.xml.parse.StaticBasicParserPool" init-method="initialize">
        <property name="builderFeatures">
            <map>
                <entry key="http://apache.org/xml/features/dom/defer-node-expansion" value="false"/>
            </map>
        </property>
    </bean>

    <bean id="parserPoolHolder" class="org.springframework.security.saml.parser.ParserPoolHolder"/>

</beans>


text:
using System;
using FluentNHibernate.Conventions.Inspections;

namespace FluentNHibernate.Conventions.Instances
{
    [Obsolete("Use ICollectionInstance")]
    public interface IBagInstance : IBagInspector, ICollectionInstance
    {}
}


text:
class Mailers::TaskApproved
  include Hanami::Mailer

  from    'noreply@ossboard.org'
  to      :recipient
  subject 'OSSBoard: your task was approved!'

  def link_to_task
    "http://www.ossboard.org/tasks/#{task.id}"
  end

private

  def recipient
    user.email
  end
end


text:
class FakeSafeBrowsingService : public SafeBrowsingService {
 public:
  // URLs with this host are treated as unsafe.
  static const std::string kUnsafeHost;

  FakeSafeBrowsingService();

  FakeSafeBrowsingService(const FakeSafeBrowsingService&) = delete;
  FakeSafeBrowsingService& operator=(const FakeSafeBrowsingService&) = delete;

  // SafeBrowsingService:
  void Initialize(PrefService* prefs,
                  const base::FilePath& user_data_path,
                  safe_browsing::SafeBrowsingMetricsCollector*
                      safe_browsing_metrics_collector) override;
  void ShutDown() override;
  std::unique_ptr<safe_browsing::SafeBrowsingUrlCheckerImpl> CreateUrlChecker(
      network::mojom::RequestDestination request_destination,
      web::WebState* web_state) override;
  bool CanCheckUrl(const GURL& url) const override;
  scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
  scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager> GetDatabaseManager()
      override;
  void ClearCookies(const net::CookieDeletionInfo::TimeRange& creation_range,
                    base::OnceClosure callback) override;

 protected:
  ~FakeSafeBrowsingService() override;

 private:
  network::TestURLLoaderFactory url_loader_factory_;
};

#endif  // IOS_CHROME_BROWSER_SAFE_BROWSING_FAKE_SAFE_BROWSING_SERVICE_H_


text:
export type Props = {
  className?: string;
  onClick: () => void;
  children: React.ReactNode;
};

export type _Props = Props;


text:
@extends('layouts.masterLayout')

@section('html_title', 'All Corporations')

@section('page_content')

            All Corporations(s) @if (count($corporations) > 0) ({{ count($corporations) }}) @endif

              Corp Name
              CEO
              Alliance
              Tax Rate
              Members
              Shares

              @foreach ($corporations as $corporation)

                    {{ Seat\Services\Helpers\Img::corporation($corporation->corporationID, 16, array('class' => 'img-circle eveIcon small')) }}
                    {{ $corporation->corporationName }} [{{ $corporation->ticker }}]

                     $corporation->ceoID)) }}">
                      {{ Seat\Services\Helpers\Img::character($corporation->ceoID, 16, array('class' => 'img-circle eveIcon small')) }}
                      {{ $corporation->ceoName }}

                      {{ Seat\Services\Helpers\Img::alliance($corporation->allianceID, 16, array('class' => 'img-circle eveIcon small')) }}
                      {{ $corporation->allianceName }}

                      {{ number_format($corporation->taxRate, 1, $settings['decimal_seperator'], $settings['thousand_seperator']) }} %

                      {{ number_format($corporation->memberCount, 0, $settings['decimal_seperator'], $settings['thousand_seperator']) }} /
                      {{ number_format($corporation->memberLimit, 0, $settings['decimal_seperator'], $settings['thousand_seperator']) }}

                      {{ number_format($corporation->shares, 0, $settings['decimal_seperator'], $settings['thousand_seperator']) }}

                  {{-- key information --}}

                    @if ($corporation->isOk == 1)
                       Key Ok
                    @else
                       Key not Ok
                    @endif

              @endforeach

@stop


text:
A package of open-sourceable angularjs utils

## Installation

0. `bower install townsquared/utils`
0. load the `utils.js`
0. `angular.module('myApp', ['ts.utils'])`

## Utils

### autoGrow

Increases height of textarea while typing

**Note:** use with `min-height`, `max-height` and `box-sizing: border-box`

```html
<textarea auto-grow></textarea>
```

### focusOn

Focuses an input on scope broadcasted event.

Specify the name of the broadcast event you would like to use to trigger the focusing.

```html
<input focus-on="someEventName">
or
<input focus-on="focus-row-{{$index}}">
```

```js
$scope.$broadcast('someEventName');
or
$scope.$broadcast('focus-row-'+$index);
```

### scrollOn

Scroll to a certain point inside an overflowing DOM element on scope broadcasted event.

Specify the name of the broadcast event you would like to use to trigger scrolling.
Pass the location to scroll to as the data of the event.
**Location:** 'top' | 'bottom' | 200

 ```html
 <ul scroll-on="someEventName" style="overflow: auto">...</ul>
 ```

```js
 var location = 'bottom';
 $scope.$broadcast('someEventName', location);
 ```

### truncate

Truncates a string by a specified number of words

```html
<p>
  {{::post.body | tsTruncate : 35}}
  <a ng-if="::post.body.split(' ').length>35">Read More</a>
</p>
```

### uiEvent

**TODO:** Remove in liue of ui-utils

General-purpose Event binding. Bind any event not natively supported by Angular
Pass an object with keynames for events and their callback expressions
Allows $event object and $params object to be passed to expressions

```html
<input ui-event="{ focus : 'counter++', blur : 'someCallback()' }">
<input ui-event="{ myCustomEvent : 'myEventHandler($event, $params)'}">
```


text:
#include "OptimizationTests_AutoFastJNIDetection_Sleep_Main.h"
#include <unistd.h>

// Sleep should be rejected by AutoFastJNIDetection
extern "C" JNIEXPORT jint JNICALL Java_OptimizationTests_AutoFastJNIDetection_Sleep_Main_nativeSleep (JNIEnv *env, jobject myobject, jint a) {
    if (a < 5) {
        sleep(1);
    }
        return a + 1;
    }


text:
package v1

import (
	"errors"
	"fmt"
	"strings"
	"time"

	buildv1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// ProwJobType specifies how the job is triggered.
type ProwJobType string

// Various job types.
const (
	// PresubmitJob means it runs on unmerged PRs.
	PresubmitJob ProwJobType = "presubmit"
	// PostsubmitJob means it runs on each new commit.
	PostsubmitJob ProwJobType = "postsubmit"
	// Periodic job means it runs on a time-basis, unrelated to git changes.
	PeriodicJob ProwJobType = "periodic"
	// BatchJob tests multiple unmerged PRs at the same time.
	BatchJob ProwJobType = "batch"
)

// ProwJobState specifies whether the job is running
type ProwJobState string

// Various job states.
const (
	// TriggeredState means the job has been created but not yet scheduled.
	TriggeredState ProwJobState = "triggered"
	// PendingState means the job is scheduled but not yet running.
	PendingState ProwJobState = "pending"
	// SuccessState means the job completed without error (exit 0)
	SuccessState ProwJobState = "success"
	// FailureState means the job completed with errors (exit non-zero)
	FailureState ProwJobState = "failure"
	// AbortedState means prow killed the job early (new commit pushed, perhaps).
	AbortedState ProwJobState = "aborted"
	// ErrorState means the job could not schedule (bad config, perhaps).
	ErrorState ProwJobState = "error"
)

// ProwJobAgent specifies the controller (such as plank or jenkins-agent) that runs the job.
type ProwJobAgent string

const (
	// KubernetesAgent means prow will create a pod to run this job.
	KubernetesAgent ProwJobAgent = "kubernetes"
	// JenkinsAgent means prow will schedule the job on jenkins.
	JenkinsAgent ProwJobAgent = "jenkins"
	// KnativeBuildAgent means prow will schedule the job via a build-crd resource.
	KnativeBuildAgent ProwJobAgent = "knative-build"
)

const (
	// DefaultClusterAlias specifies the default cluster key to schedule jobs.
	DefaultClusterAlias = "default"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ProwJob contains the spec as well as runtime metadata.
type ProwJob struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   ProwJobSpec   `json:"spec,omitempty"`
	Status ProwJobStatus `json:"status,omitempty"`
}

// ProwJobSpec configures the details of the prow job.
//
// Details include the podspec, code to clone, the cluster it runs
// any child jobs, concurrency limitations, etc.
type ProwJobSpec struct {
	// Type is the type of job and informs how
	// the jobs is triggered
	Type ProwJobType `json:"type,omitempty"`
	// Agent determines which controller fulfills
	// this specific ProwJobSpec and runs the job
	Agent ProwJobAgent `json:"agent,omitempty"`
	// Cluster is which Kubernetes cluster is used
	// to run the job, only applicable for that
	// specific agent
	Cluster string `json:"cluster,omitempty"`
	// Namespace defines where to create pods/resources.
	Namespace string `json:"namespace,omitempty"`
	// Job is the name of the job
	Job string `json:"job,omitempty"`
	// Refs is the code under test, determined at
	// runtime by Prow itself
	Refs *Refs `json:"refs,omitempty"`
	// ExtraRefs are auxiliary repositories that
	// need to be cloned, determined from config
	ExtraRefs []Refs `json:"extra_refs,omitempty"`

	// Report determines if the result of this job should
	// be posted as a status on GitHub
	Report bool `json:"report,omitempty"`
	// Context is the name of the status context used to
	// report back to GitHub
	Context string `json:"context,omitempty"`
	// RerunCommand is the command a user would write to
	// trigger this job on their pull request
	RerunCommand string `json:"rerun_command,omitempty"`
	// MaxConcurrency restricts the total number of instances
	// of this job that can run in parallel at once
	MaxConcurrency int `json:"max_concurrency,omitempty"`
	// ErrorOnEviction indicates that the ProwJob should be completed and given
	// the ErrorState status if the pod that is executing the job is evicted.
	// If this field is unspecified or false, a new pod will be created to replace
	// the evicted one.
	ErrorOnEviction bool `json:"error_on_eviction,omitempty"`

	// PodSpec provides the basis for running the test under
	// a Kubernetes agent
	PodSpec *corev1.PodSpec `json:"pod_spec,omitempty"`

	// BuildSpec provides the basis for running the test as
	// a build-crd resource
	// https://github.com/knative/build
	BuildSpec *buildv1alpha1.BuildSpec `json:"build_spec,omitempty"`

	// DecorationConfig holds configuration options for
	// decorating PodSpecs that users provide
	DecorationConfig *DecorationConfig `json:"decoration_config,omitempty"`
}

// DecorationConfig specifies how to augment pods.
//
// This is primarily used to provide automatic integration with gubernator
// and testgrid.
type DecorationConfig struct {
	// Timeout is how long the pod utilities will wait
	// before aborting a job with SIGINT.
	Timeout time.Duration `json:"timeout,omitempty"`
	// GracePeriod is how long the pod utilities will wait
	// after sending SIGINT to send SIGKILL when aborting
	// a job. Only applicable if decorating the PodSpec.
	GracePeriod time.Duration `json:"grace_period,omitempty"`
	// UtilityImages holds pull specs for utility container
	// images used to decorate a PodSpec.
	UtilityImages *UtilityImages `json:"utility_images,omitempty"`
	// GCSConfiguration holds options for pushing logs and
	// artifacts to GCS from a job.
	GCSConfiguration *GCSConfiguration `json:"gcs_configuration,omitempty"`
	// GCSCredentialsSecret is the name of the Kubernetes secret
	// that holds GCS push credentials.
	GCSCredentialsSecret string `json:"gcs_credentials_secret,omitempty"`
	// SSHKeySecrets are the names of Kubernetes secrets that contain
	// SSK keys which should be used during the cloning process.
	SSHKeySecrets []string `json:"ssh_key_secrets,omitempty"`
	// SSHHostFingerprints are the fingerprints of known SSH hosts
	// that the cloning process can trust.
	// Create with ssh-keyscan [-t rsa] host
	SSHHostFingerprints []string `json:"ssh_host_fingerprints,omitempty"`
	// SkipCloning determines if we should clone source code in the
	// initcontainers for jobs that specify refs
	SkipCloning *bool `json:"skip_cloning,omitempty"`
	// CookieFileSecret is the name of a kubernetes secret that contains
	// a git http.cookiefile, which should be used during the cloning process.
	CookiefileSecret string `json:"cookiefile_secret,omitempty"`
}

// ApplyDefault applies the defaults for the ProwJob decoration. If a field has a zero value, it
// replaces that with the value set in def.
func (d *DecorationConfig) ApplyDefault(def *DecorationConfig) *DecorationConfig {
	if d == nil && def == nil {
		return nil
	}
	var merged DecorationConfig
	if d != nil {
		merged = *d
	} else {
		merged = *def
	}
	if d == nil || def == nil {
		return &merged
	}
	merged.UtilityImages = merged.UtilityImages.ApplyDefault(def.UtilityImages)
	merged.GCSConfiguration = merged.GCSConfiguration.ApplyDefault(def.GCSConfiguration)

	if merged.Timeout == 0 {
		merged.Timeout = def.Timeout
	}
	if merged.GracePeriod == 0 {
		merged.GracePeriod = def.GracePeriod
	}
	if merged.GCSCredentialsSecret == "" {
		merged.GCSCredentialsSecret = def.GCSCredentialsSecret
	}
	if len(merged.SSHKeySecrets) == 0 {
		merged.SSHKeySecrets = def.SSHKeySecrets
	}
	if len(merged.SSHHostFingerprints) == 0 {
		merged.SSHHostFingerprints = def.SSHHostFingerprints
	}
	if merged.SkipCloning == nil {
		merged.SkipCloning = def.SkipCloning
	}
	if merged.CookiefileSecret == "" {
		merged.CookiefileSecret = def.CookiefileSecret
	}

	return &merged
}

// Validate ensures all the values set in the DecorationConfig are valid.
func (d *DecorationConfig) Validate() error {
	if d.UtilityImages == nil {
		return errors.New("utility image config is not specified")
	}
	var missing []string
	if d.UtilityImages.CloneRefs == "" {
		missing = append(missing, "clonerefs")
	}
	if d.UtilityImages.InitUpload == "" {
		missing = append(missing, "initupload")
	}
	if d.UtilityImages.Entrypoint == "" {
		missing = append(missing, "entrypoint")
	}
	if d.UtilityImages.Sidecar == "" {
		missing = append(missing, "sidecar")
	}
	if len(missing) > 0 {
		return fmt.Errorf("the following utility images are not specified: %q", missing)
	}

	if d.GCSConfiguration == nil {
		return errors.New("GCS upload configuration is not specified")
	}
	if d.GCSCredentialsSecret == "" {
		return errors.New("GCS upload credential secret is not specified")
	}
	if err := d.GCSConfiguration.Validate(); err != nil {
		return fmt.Errorf("GCS configuration is invalid: %v", err)
	}
	return nil
}

// UtilityImages holds pull specs for the utility images
// to be used for a job
type UtilityImages struct {
	// CloneRefs is the pull spec used for the clonerefs utility
	CloneRefs string `json:"clonerefs,omitempty"`
	// InitUpload is the pull spec used for the initupload utility
	InitUpload string `json:"initupload,omitempty"`
	// Entrypoint is the pull spec used for the entrypoint utility
	Entrypoint string `json:"entrypoint,omitempty"`
	// sidecar is the pull spec used for the sidecar utility
	Sidecar string `json:"sidecar,omitempty"`
}

// ApplyDefault applies the defaults for the UtilityImages decorations. If a field has a zero value,
// it replaces that with the value set in def.
func (u *UtilityImages) ApplyDefault(def *UtilityImages) *UtilityImages {
	if u == nil {
		return def
	} else if def == nil {
		return u
	}

	merged := *u
	if merged.CloneRefs == "" {
		merged.CloneRefs = def.CloneRefs
	}
	if merged.InitUpload == "" {
		merged.InitUpload = def.InitUpload
	}
	if merged.Entrypoint == "" {
		merged.Entrypoint = def.Entrypoint
	}
	if merged.Sidecar == "" {
		merged.Sidecar = def.Sidecar
	}
	return &merged
}

// PathStrategy specifies minutia about how to construct the url.
// Usually consumed by gubernator/testgrid.
const (
	PathStrategyLegacy   = "legacy"
	PathStrategySingle   = "single"
	PathStrategyExplicit = "explicit"
)

// GCSConfiguration holds options for pushing logs and
// artifacts to GCS from a job.
type GCSConfiguration struct {
	// Bucket is the GCS bucket to upload to
	Bucket string `json:"bucket,omitempty"`
	// PathPrefix is an optional path that follows the
	// bucket name and comes before any structure
	PathPrefix string `json:"path_prefix,omitempty"`
	// PathStrategy dictates how the org and repo are used
	// when calculating the full path to an artifact in GCS
	PathStrategy string `json:"path_strategy,omitempty"`
	// DefaultOrg is omitted from GCS paths when using the
	// legacy or simple strategy
	DefaultOrg string `json:"default_org,omitempty"`
	// DefaultRepo is omitted from GCS paths when using the
	// legacy or simple strategy
	DefaultRepo string `json:"default_repo,omitempty"`
}

// ApplyDefault applies the defaults for GCSConfiguration decorations. If a field has a zero value,
// it replaces that with the value set in def.
func (g *GCSConfiguration) ApplyDefault(def *GCSConfiguration) *GCSConfiguration {
	if g == nil && def == nil {
		return nil
	}
	var merged GCSConfiguration
	if g != nil {
		merged = *g
	} else {
		merged = *def
	}
	if g == nil || def == nil {
		return &merged
	}

	if merged.Bucket == "" {
		merged.Bucket = def.Bucket
	}
	if merged.PathPrefix == "" {
		merged.PathPrefix = def.PathPrefix
	}
	if merged.PathStrategy == "" {
		merged.PathStrategy = def.PathStrategy
	}
	if merged.DefaultOrg == "" {
		merged.DefaultOrg = def.DefaultOrg
	}
	if merged.DefaultRepo == "" {
		merged.DefaultRepo = def.DefaultRepo
	}
	return &merged
}

// Validate ensures all the values set in the GCSConfiguration are valid.
func (g *GCSConfiguration) Validate() error {
	if g.PathStrategy != PathStrategyLegacy && g.PathStrategy != PathStrategyExplicit && g.PathStrategy != PathStrategySingle {
		return fmt.Errorf("gcs_path_strategy must be one of %q, %q, or %q", PathStrategyLegacy, PathStrategyExplicit, PathStrategySingle)
	}
	if g.PathStrategy != PathStrategyExplicit && (g.DefaultOrg == "" || g.DefaultRepo == "") {
		return fmt.Errorf("default org and repo must be provided for GCS strategy %q", g.PathStrategy)
	}
	return nil
}

// ProwJobStatus provides runtime metadata, such as when it finished, whether it is running, etc.
type ProwJobStatus struct {
	StartTime      metav1.Time  `json:"startTime,omitempty"`
	CompletionTime *metav1.Time `json:"completionTime,omitempty"`
	State          ProwJobState `json:"state,omitempty"`
	Description    string       `json:"description,omitempty"`
	URL            string       `json:"url,omitempty"`

	// PodName applies only to ProwJobs fulfilled by
	// plank. This field should always be the same as
	// the ProwJob.ObjectMeta.Name field.
	PodName string `json:"pod_name,omitempty"`

	// BuildID is the build identifier vended either by tot
	// or the snowflake library for this job and used as an
	// identifier for grouping artifacts in GCS for views in
	// TestGrid and Gubernator. Idenitifiers vended by tot
	// are monotonically increasing whereas identifiers vended
	// by the snowflake library are not.
	BuildID string `json:"build_id,omitempty"`

	// JenkinsBuildID applies only to ProwJobs fulfilled
	// by the jenkins-operator. This field is the build
	// identifier that Jenkins gave to the build for this
	// ProwJob.
	JenkinsBuildID string `json:"jenkins_build_id,omitempty"`

	// PrevReportStates stores the previous reported prowjob state per reporter
	// So crier won't make duplicated report attempt
	PrevReportStates map[string]ProwJobState `json:"prev_report_states,omitempty"`
}

// Complete returns true if the prow job has finished
func (j *ProwJob) Complete() bool {
	// TODO(fejta): support a timeout?
	return j.Status.CompletionTime != nil
}

// SetComplete marks the job as completed (at time now).
func (j *ProwJob) SetComplete() {
	j.Status.CompletionTime = new(metav1.Time)
	*j.Status.CompletionTime = metav1.Now()
}

// ClusterAlias specifies the key in the clusters map to use.
//
// This allows scheduling a prow job somewhere aside from the default build cluster.
func (j *ProwJob) ClusterAlias() string {
	if j.Spec.Cluster == "" {
		return DefaultClusterAlias
	}
	return j.Spec.Cluster
}

// Pull describes a pull request at a particular point in time.
type Pull struct {
	Number int    `json:"number"`
	Author string `json:"author"`
	SHA    string `json:"sha"`
	Title  string `json:"title,omitempty"`

	// Ref is git ref can be checked out for a change
	// for example,
	// github: pull/123/head
	// gerrit: refs/changes/00/123/1
	Ref string `json:"ref,omitempty"`
	// Link links to the pull request itself.
	Link string `json:"link,omitempty"`
	// CommitLink links to the commit identified by the SHA.
	CommitLink string `json:"commit_link,omitempty"`
	// AuthorLink links to the author of the pull request.
	AuthorLink string `json:"author_link,omitempty"`
}

// Refs describes how the repo was constructed.
type Refs struct {
	// Org is something like kubernetes or k8s.io
	Org string `json:"org"`
	// Repo is something like test-infra
	Repo string `json:"repo"`
	// RepoLink links to the source for Repo.
	RepoLink string `json:"repo_link,omitempty"`

	BaseRef string `json:"base_ref,omitempty"`
	BaseSHA string `json:"base_sha,omitempty"`
	// BaseLink is a link to the commit identified by BaseSHA.
	BaseLink string `json:"base_link,omitempty"`

	Pulls []Pull `json:"pulls,omitempty"`

	// PathAlias is the location under <root-dir>/src
	// where this repository is cloned. If this is not
	// set, <root-dir>/src/github.com/org/repo will be
	// used as the default.
	PathAlias string `json:"path_alias,omitempty"`
	// CloneURI is the URI that is used to clone the
	// repository. If unset, will default to
	// `https://github.com/org/repo.git`.
	CloneURI string `json:"clone_uri,omitempty"`
	// SkipSubmodules determines if submodules should be
	// cloned when the job is run. Defaults to true.
	SkipSubmodules bool `json:"skip_submodules,omitempty"`
}

func (r Refs) String() string {
	rs := []string{fmt.Sprintf("%s:%s", r.BaseRef, r.BaseSHA)}
	for _, pull := range r.Pulls {
		ref := fmt.Sprintf("%d:%s", pull.Number, pull.SHA)

		if pull.Ref != "" {
			ref = fmt.Sprintf("%s:%s", ref, pull.Ref)
		}

		rs = append(rs, ref)
	}
	return strings.Join(rs, ",")
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// ProwJobList is a list of ProwJob resources
type ProwJobList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata"`

	Items []ProwJob `json:"items"`
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Frameshop.Data;

namespace Frameshop
{
    internal class Option : PList
    {
        public static readonly string PLUGIN_FOLDER = Path.GetDirectoryName(Application.ExecutablePath) + "\\plugin";
        public static readonly string COMMAND_EXT = ".fsc";

        public static readonly string CMD_ESC_FULL = "$FULL$";
        public static readonly string CMD_ESC_PARENT = "$PARENT$";
        public static readonly string CMD_ESC_FILE = "$FILE$";
        public static readonly string CMD_ESC_EXT = "$EXT$";

        public static string GetCommandFilePath(string name)
        {
            return PLUGIN_FOLDER + "\\" + name + COMMAND_EXT;
        }

        private string SettingsFilePath
        {
            get
            {
                return Path.GetDirectoryName(Application.ExecutablePath) + "\\options.plist";
            }
        }

        private Option()
        {
        }

        private static Option self = null;
        public static Option GetInstance()
        {
            if (self == null)
                self = new Option();

            return self;
        }

        public void Init()
        {
            PList winProp = new PList();
            this["win_prop"] = winProp;
            winProp["max"] = true;
            winProp["x"] = 20;
            winProp["y"] = 10;
            winProp["w"] = 800;
            winProp["h"] = 600;

            PList winAnim = new PList();
            this["win_anim"] = winAnim;
            winAnim["max"] = false;
            winAnim["x"] = 50;
            winAnim["y"] = 30;
            winAnim["w"] = 640;
            winAnim["h"] = 480;

            PList fsc = new PList();
            this["commands"] = fsc;
            fsc["folder"] = string.Empty;
            fsc["tex"] = string.Empty;
            fsc["data"] = string.Empty;
            fsc["anim"] = string.Empty;
            fsc["call_anim_at_pub"] = true;

            PList misc = new PList();
            this["misc"] = misc;
            misc["first_run"] = true;
            misc["last_dir"] = Environment.CurrentDirectory;
            misc["ask_before_rem_frame"] = true;
            misc["add_folder_recursively"] = true;
        }

        public void Load()
        {
            if (File.Exists(SettingsFilePath))
                Load(SettingsFilePath);
            else
                Init();
        }

        public void Save()
        {
            Save(SettingsFilePath);
        }
    }
}


text:
module matchone {

  import Pool = entitas.Pool;
  import Group = entitas.Group;
  import Entity = entitas.Entity;
  import Matcher = entitas.Matcher;
  import Exception = entitas.Exception;
  import TriggerOnEvent = entitas.TriggerOnEvent;
  import IReactiveSystem = entitas.IReactiveSystem;
  import ISetPool = entitas.ISetPool;
  import IComponent = entitas.IComponent;
  import GameBoardComponent = matchone.GameBoardComponent;
  import GameBoardCacheComponent = matchone.GameBoardCacheComponent;

  function getNextEmptyRow(grid, column:number, row:number) {
    var rowBelow = row - 1;
    while (rowBelow >= 0 && grid[column][rowBelow] === undefined) {
      rowBelow -= 1;
    }
    return rowBelow + 1;
  }

  export class FallSystem implements IReactiveSystem, ISetPool {

    protected pool:Pool;
    public get trigger():TriggerOnEvent {
      return Matcher.GameBoardElement.onEntityRemoved();
    }

    public setPool(pool:Pool) {
      this.pool = pool;
    }

    public execute(entities:Array<Entity>) {
      var gameBoard = this.pool.gameBoard;
      var grid = (<GameBoardCacheComponent>this.pool.gameBoardCache).grid;

      for (var column=0; column < (<GameBoardComponent>gameBoard).columns; column++) {
        for (var row=1; row < (<GameBoardComponent>gameBoard).rows; row++) {
          var e = grid[column][row];
          if (e !== undefined && e.isMovable) {
            this.moveDown(e, column, row, grid);
          }

        }
      }
    }

    protected moveDown(e:Entity, column:number, row:number, grid:any) {
      var nextRowPos = getNextEmptyRow(grid, column, row);
      if (nextRowPos !== row) {
        e.replacePosition(column, nextRowPos);
      }
    }
  }
}


text:
export { default as ControllerMissingError } from './controller-missing';
export { default as SerializerMissingError } from './serializer-missing';


text:
package com.dremio.exec.planner.sql.parser;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.SqlSpecialOperator;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.parser.SqlParserPos;

import com.dremio.exec.ops.QueryContext;
import com.dremio.exec.planner.sql.handlers.direct.SimpleDirectHandler;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;

/**
 * Implements SQL Role create to create a role from the system. Represents statements like:
 * CREATE ROLE role_name
 */
public class SqlCreateRole extends SqlCall implements SimpleDirectHandler.Creator {
  private final SqlIdentifier roleToCreate;

  public static final SqlSpecialOperator OPERATOR = new SqlSpecialOperator("CREATE", SqlKind.OTHER) {
    @Override
    public SqlCall createCall(SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) {
      Preconditions.checkArgument(operands.length == 1, "SqlCreateRole.createCall() has to get 1 operands!");
      return new SqlCreateRole(
        pos,
        (SqlIdentifier) operands[0]
      );
    }
  };

  public SqlCreateRole(SqlParserPos pos,
                     SqlIdentifier roleToCreate) {
    super(pos);
    this.roleToCreate = roleToCreate;
  }

  @Override
  public SqlOperator getOperator() {
    return OPERATOR;
  }

  @Override
  public List<SqlNode> getOperandList() {
    List<SqlNode> ops = Lists.newArrayList();
    ops.add(roleToCreate);

    return ops;
  }

  @Override
  public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
    writer.keyword("CREATE");
    writer.keyword("ROLE");
    roleToCreate.unparse(writer, leftPrec, rightPrec);
  }

  @Override
  public SimpleDirectHandler toDirectHandler(QueryContext context) {
    try {
      Class<?> cl = null;
      if (context.isCloud()) {
        cl = Class.forName("com.dremio.exec.planner.sql.handlers.DCSCreateRoleHandler");
      } else {
        cl = Class.forName("com.dremio.exec.planner.sql.handlers.RoleCreateHandler");
      }
      Constructor<?> ctor = cl.getConstructor(QueryContext.class);
      return (SimpleDirectHandler) ctor.newInstance(context);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException
      | NoSuchMethodException | InvocationTargetException e) {
      throw Throwables.propagate(e);
    }
  }

  public SqlIdentifier getRoleToCreate() {
    return roleToCreate;
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: mopkob
 * Date: 06.01.16
 * Time: 21:26
 */

namespace ownCommands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class toReadEntities extends Command {
    protected function configure()
    {
        parent::configure();
        $this
            ->setName('2read-ent')
            ->setDescription('Command for read test entities')
            ->setDefinition(array())
            ->setHelp(<<<EOT
Cпециальное место для вывода HELP
EOT
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getHelper('em')->getEntityManager();

        $e= $em->find('Entities\Employee',3);
        print_r($e->getname());
        print_r($e->gettitle());
    }

}


text:
@interface NSCoder (SIAIvarCoder)

- (void)sia_encodeInstanceVariables:(id)object ofClass:(Class)objectClass;
- (void)sia_encodeInstanceVariables:(id)object ofClass:(Class)objectClass ignore:(const void *)firstIgnoreVariable, ...;
- (void)sia_decodeInstanceVariables:(id)object ofClass:(Class)objectClass;
- (void)sia_decodeInstanceVariables:(id)object ofClass:(Class)objectClass ignore:(const void *)firstIgnoreVariable, ...;

@end


text:
#include "../../include/data/HH_Redis.h"
#include "../../include/HH_Log.h"

hhou::HHRedis::HHRedis()
        : m_pRedisConn(nullptr),
          m_pRedisReply(nullptr)
{

}

hhou::HHRedis::~HHRedis()
{
    redisFree(m_pRedisConn);
}

bool hhou::HHRedis::ConnectToRedis(const string &strHost, int nPort, struct timeval &timeout)
{
    m_pRedisConn = redisConnectWithTimeout(strHost.c_str(), nPort, timeout);
    if (m_pRedisConn == nullptr && strlen(m_pRedisConn->errstr) > 0)
    {
        LOG(ERROR) << "Redis connect " << strHost << " port: " << nPort << " error: " << m_pRedisConn->errstr;
        return false;
    }
    return true;
}

void hhou::HHRedis::Excute(const string &command, string &strRet)
{
    m_pRedisReply = (redisReply *)redisCommand(m_pRedisConn, command.c_str());
    strRet = m_pRedisReply->str;
    freeReplyObject(m_pRedisReply);
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

# Validations
describe Survey, "when saving a new one" do
  before(:each) do
    @survey = Factory(:survey, :title => "Foo")
  end

  it "should be invalid without a title" do
    @survey.title = nil
    @survey.should have(1).error_on(:title)
  end

  it "should adjust the title to save unique titles" do
    original = Survey.new(:title => "Foo")
    original.save.should be_true
    imposter = Survey.new(:title => "Foo")
    imposter.save.should be_true
    imposter.title.should == "Foo 1"
    bandwagoneer = Survey.new(:title => "Foo")
    bandwagoneer.save.should be_true
    bandwagoneer.title.should == "Foo 2"
  end

  it "should not adjust the title when updating itself" do
    original = Factory(:survey, :title => "Foo")
    original.save.should be_true
    original.update_attributes(:title => "Foo")
    original.title.should == "Foo"
  end

  it "should have an api_id" do
    @survey.api_id.length.should == 36
  end
end

# Associations
describe Survey, "that has sections" do
  before(:each) do
    @survey = Factory(:survey, :title => "Foo")
    @s1 = Factory(:survey_section, :survey => @survey, :title => "wise", :display_order => 2)
    @s2 = Factory(:survey_section, :survey => @survey, :title => "er", :display_order => 3)
    @s3 = Factory(:survey_section, :survey => @survey, :title => "bud", :display_order => 1)
    @q1 = Factory(:question, :survey_section => @s1, :text => "what is wise?", :display_order => 2)
    @q2 = Factory(:question, :survey_section => @s2, :text => "what is er?", :display_order => 4)
    @q3 = Factory(:question, :survey_section => @s2, :text => "what is mill?", :display_order => 3)
    @q4 = Factory(:question, :survey_section => @s3, :text => "what is bud?", :display_order => 1)
  end

  it "should return survey_sections in display order" do
    @survey.sections.should have(3).sections
    @survey.sections.should == [@s3, @s1, @s2]
  end

  it "should return survey_sections_with_questions in display order" do
    @survey.sections_with_questions.map(&:questions).flatten.should have(4).questions
    @survey.sections_with_questions.map(&:questions).flatten.should == [@q4,@q1,@q3,@q2]
  end
  it "should delete survey sections when it is deleted" do
    section_ids = @survey.sections.map(&:id)
    @survey.destroy
    section_ids.each{|id| SurveySection.find_by_id(id).should be_nil}
  end
end

# Methods
describe Survey do
  before(:each) do
    @survey = Survey.new
  end

  it "should be inactive by default" do
    @survey.active?.should == false
  end

  it "should be active or active as of a certain date/time" do
    @survey.inactive_at = 3.days.ago
    @survey.active_at = 2.days.ago
    @survey.active?.should be_true
    @survey.inactive_at.should be_nil
  end

  it "should be able to deactivate as of a certain date/time" do
    @survey.active_at = 2.days.ago
    @survey.inactive_at = 3.days.ago
    @survey.active?.should be_false
    @survey.active_at.should be_nil
  end

  it "should activate and deactivate" do
    @survey.activate!
    @survey.active?.should be_true
    @survey.deactivate!
    @survey.active?.should be_false
  end

end


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Shenfun - automating the spectral Galerkin method">
<meta name="keywords" content="Computational Methods,Spectral,Galerkin,Chebyshev,Legendre">

<title>Shenfun - automating the spectral Galerkin method</title>

<link href="https://netdna.bootstrapcdn.com/bootswatch/3.1.1/cyborg/bootstrap.min.css" rel="stylesheet">

$$
\newcommand{\bs}[1]{\boldsymbol{#1}}
\newcommand{\ts}[1]{\bs{\textsf{#1}}}
$$

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

    </button>
    Shenfun - automating the spectral Galerkin method

        Contents

Table of contents

Introduction

Spectral Galerkin Method

Shenfun

   Classes for basis functions

   Classes for matrices

   Variational forms in 1D

   Poisson equation implemented in 1D

      Periodic boundary conditions

      Dirichlet boundary conditions

Tensor product spaces

Other functionality of shenfun

Ginzburg-Landau equation

Conclusions

Acknowledgements

Bibliography

Tensor product spaces

Now that we know how to solve problems in one dimension, it is time to move on to more challenging tasks. Consider again the Poisson equation, but now in possibly more than one dimension
$$
\begin{equation}
 -\nabla^2 u(\bs{x}) = f(\bs{x}) \quad \text{for }\bs{x} \in \Omega.
\tag{42}
\end{equation}
$$

Lets first consider 2 dimensions, with Dirichlet boundary conditions in the
first direction and with periodicity in the second. Let \( \Omega \) be the domain
\( [-1, 1] \times [0, 2 \pi] \), and \( T(x,y) = V^C(x) \otimes V^p(y) \) be the tensor product function space. We can solve this problem for some suitable function \( f(\bs{x}) \) in shenfun by constructing a few more classes than were required in 1D

from shenfun.chebyshev.bases import ShenDirichletBasis
from shenfun.fourier.bases import FourierBasis
import numpy as np
from shenfun import Function, TensorProductSpace
from mpi4py import MPI

Now the TensorProductSpace class is used to construct \( T \), whereas Function is a subclass of numpy.ndarray used to hold solution arrays. The MPI communicator, on the other hand, is used for distributing the tensor product grids on a given number of processes

comm = MPI.COMM_WORLD
N = (32, 33)

K0 = ShenDirichletBasis(N[0])
K1 = FourierBasis(N[1], dtype=np.float)
T = TensorProductSpace(comm, (K0, K1))

# Alternatively, switch order for periodic in first direction instead
# T = TensorProductSpace(comm, (K1, K0), axes=(1, 0))

Under the hood, within the TensorProductSpace class, the mesh is distributed,
both in real, physical space, and in spectral space. In the real space the mesh
is distributed along the first index, whereas in spectral space the
wavenumbermesh is distributed along the second dimension. This is the default
behaviour of TensorProductSpace. However, the distribution may also be
configured specifically by the user, e.g., as shown in the commented out text,
where the Dirichlet basis is found along the second axis. In this case the order
of the axes to transform over has been flipped, such that in spectral space the
data is distributed along the first dimension and aligned in the second. This is
required for solving the linear algebra system that arises for the Dirichlet
basis. The arrays created using Function are distributed, and no further
attention to MPI is required. However, note that arrays may have different type
and shape in real space and in spectral space. For this reason Function has a
keyword argument forward_output, that is used as w_hat = Function(T,
forward_output=True) to create an array consistent with the output of
T.forward (solution in spectral space), and w = Function(T,
forward_output=False) to create an array consistent with the input (solution in
real space). Furthermore, uh = np.zeros_like(w_hat) and w_hat = Function(T, buffer=uh) can be used to wrap a Function instance around a regular Numpy array uh. Note that uh and w_hat now will share the same data, and modifying one will naturally modify also the other.

The solution of a complete Poisson problem in 2D is shown below. Very similar code is required to solve the Poisson problem with the Legendre basis. The main difference is that for Legendre it is natural to integrate the weak form by parts and use matrices = inner(grad(v), grad(u))

from shenfun.chebyshev.la import Helmholtz as Solver

# Create a solution that satisfies boundary conditions
x, y = symbols("x,y")
ue = (cos(4*y) + sin(2*x))*(1-x**2)
fe = ue.diff(x, 2) + ue.diff(y, 2)

# Lambdify for faster evaluation
ul = lambdify((x, y), ue, 'numpy')
fl = lambdify((x, y), fe, 'numpy')

X = T.local_mesh(True)
u = TrialFunction(T)
v = TestFunction(T)

# Get f on quad points
fj = fl(X[0], X[1])

# Compute right hand side of Poisson equation
f_hat = inner(v, fj)

# Get left hand side of Poisson equation
matrices = inner(v, div(grad(u)))

# Create Helmholtz linear algebra solver
H = Solver(**matrices)

# Solve and transform to real space
u_hat = Function(T)           # Solution spectral space
u_hat = H(u_hat, f_hat)       # Solve
u = T.backward(u_hat)

The test functions and function spaces require a bit more attention. Test
functions for space \( T(x, y)=V^C(x) \otimes V^p(y) \) are given as
$$
\begin{equation}
\phi_{\ts{k}}(x, y) = v_l(x) e^{imy},
\tag{43}
\end{equation}
$$

which introduces the sans serif Cartesian product wavenumber mesh \( \ts{k} = \bs{l}^D \times \bs{l} \)
$$
\begin{equation}
 \ts{k} = \{ (l, m) | l \in \bs{l}^D \text{ and } m \in \bs{l}\}.
\tag{44}
\end{equation}
$$

Similarly there is a Cartesian product grid \( \ts{x} = \bs{x} \times \bs{y} \), where \( \bs{y} = \{y_k\}_{k=0}^{M-1} = 2 \pi k /M \)
$$
\begin{equation}
 \ts{x} = \{ (x_j, y_k) | j=0,1,\ldots, N-1 \text{ and } k=0,1,\ldots, M-1\}.
\tag{45}
\end{equation}
$$

Note that for computing on the Cartesian grids using Numpy arrays with vectorization, the mesh and wavenumber components need to be represented as 2D arrays. As such we create
$$
\begin{equation}
\bs{\textsf{x}} = (\bs{x}, \bs{y}) = \Big(\{x_i\}_{i=0}^{N-1} \times I^M,  I^N \times \{y_j\}_{j=0}^{M-1} \Big),
\tag{46}
\end{equation}
$$

where \( I^N \) is an N-length vector of ones. Similarly
$$
\begin{equation}
\bs{\textsf{k}} = (\bs{l}, \bs{m}) = \Big(\{ l \}_{l=0}^{N-1} \times I^M,  I^N \times \{ m \}_{m=0}^{M/2} \Big).
\tag{47}
\end{equation}
$$

Such Cartesian grids can be very efficiently stored with Numpy arrays, using no more space than the two vectors used to create them. The key to this efficiency is broadcasting. We store \( \ts{k} \) as a list of two numpy arrays, \( \bs{l} \) and \( \bs{m} \), corresponding to the two 1D wavenumber meshes \( \{ l \}_{l=0}^{N-1} \) and \( \{ m \}_{m=0}^{M/2} \).
However, \( \bs{l} \) and \( \bs{m} \) are now stored as 2D arrays of shape \( (N, 1) \) and \( (1, M/2+1) \), respectively. And broadcasting takes care of the additional dimension, such that the two arrays work just like if they were stored as \( (N, M/2+1) \) arrays. We can look up \( \bs{l}(l, m) \), just like a regular \( (N, M/2+1) \) array, but the storage required is still only one single vector.
The same goes for \( \ts{x} \), which is stored as a list of two arrays \( \bs{x} \), \( \bs{y} \) of shape \( (N, 1) \) and \( (1, M) \) respectively. This extends straightforward to even higher dimensions.

Assembling a weak form like \( (v, \nabla^2 u)_w^N \) leads to two non-diagonal matrices, both the stiffness and mass matrix, since it expands like
$$
\begin{equation}
(v, \nabla^2 u)_w^N = \left(v, \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} \right)_w^N.
\tag{48}
\end{equation}
$$

Inserting for test function \( v = \phi_{\ts{k}} (= \phi_{l, m} =v_l(x) e^{imy}) \) and trial function \( u = \sum_{(q,r)\in \ts{k}} \hat{u}_{q, r} \phi_{q,r} \), we obtain
$$
\begin{align}
 (v, \nabla^2 u)_w^N &= \left(\phi_{l, m}, \frac{\partial^2}{\partial x^2} \sum_{(q, r) \in \ts{k}} \hat{u}_{q, r} \phi_{q, r} + \frac{\partial^2}{\partial y^2} \sum_{(q,r) \in \ts{k}} \hat{u}_{q, r} \phi_{q, r} \right)_w^N,
\tag{49}\\
 &= 2\pi \left(\sum_{(q, r) \in \ts{k}} A_{lq} \delta_{rm} \hat{u}_{q,r} -  \sum_{(q, r) \in \ts{k}} {r}^2  B_{lq} \delta_{rm} \hat{u}_{q,r}\right),
\tag{50}\\
 &= 2\pi \left(\sum_{q\in \bs{l}^D} A_{lq} \hat{u}_{q,m} - {m}^2 \sum_{q\in \bs{l}^D}  B_{lq} \hat{u}_{q,m}\right) \quad \forall (l, m) \in \bs{l}^D \times \bs{l}. \tag{51}
\end{align}
$$

As can be seen from Eq.(51), the linear system of equations is set up to act along the Dirichlet direction, whereas for the periodic direction the matrices are diagonal and no additional work is required. The system of equations correspond to a series of 1D Helmholtz problems, that need to be solved once for each \( m \in \bs{l} \). This is what goes on under the hood with the Helmholtz solver imported through from shenfun.chebyshev.la import Helmholtz as Solver.

The right hand side of the Poisson problem is computed as
$$
\begin{align}
(v, f)_w^N &= 2\pi \underbrace{\sum_{j}\underbrace{\frac{1}{N} \sum_{k} f(x_j, y_k) e^{imy_k} }_{\mathcal{F}_m} v_l(x_j)   w_j}_{\mathcal{S}_l} \quad \forall (l, m) \in \bs{l}^D \times \bs{l}, \notag
\tag{52}\\
  &= 2\pi \mathcal{S}(f) = 2 \pi \mathcal{S}_l(\mathcal{F}_m(f)).
\tag{53}
\end{align}
$$

The TensorProductSpace class can take any number of Fourier bases. A 3 dimensional tensor product space can be created as

N = (32, 33, 34)
K0 = ShenDirichletBasis(N[0])
K1 = C2CBasis(N[1])
K2 = R2CBasis(N[2])
W = TensorProductSpace(comm, (K0, K1, K2))

Here the default behaviour of TensorProductSpace is to distribute the first 2 indices in real space using two subcommunicators, with a decomposition often referred to as pencil decomposition. In spectral space the last two indices will be distributed. For example, using 4 CPUs, a subprocessor mesh of size \( 2 \times 2 \) will be created, and 2 subprocessors share the first index and the other two share the second index.  If the program is run with 3 processors, then only the first index will be distributed and the subprocessormesh will be \( 3 \times 1 \). It is also possible to configure TensorProductSpace to run with 4 CPUs and a \( 4 \times 1 \) subprocessormesh, or 40,000 CPUs with a \( 200 \times 200 \) processormesh. The latter requires that the mesh is big enough, though, but otherwise it is just a matter of acquiring computing power. The biggest simulations tested thus far used 64,000 CPUs.

Solving a biharmonic problem is just as easy as the Poisson problem. Consider the fourth order biharmonic PDE in 3-dimensional space
$$
\begin{align}
\nabla^4 u(\bs{x}) &= f(\bs{x}), \quad \bs{x} \in \Omega
\tag{54}\\
 u(x=\pm1, y, z) &= \frac{\partial u}{\partial x} (x=\pm 1, y, z) = 0
\tag{55}\\
 u(x, y+2\pi, z) &= u(x, y, z),
\tag{56}\\
 u(x, y, z+2\pi) &= u(x, y, z).
\tag{57}
\end{align}
$$

that is periodic in \( y- \) and \( z- \) directions and with clamped boundary conditions at \( x=\pm 1 \). The problem may be solved using either one of these two bases:
$$
\begin{align}
V^C &= \text{span}\{T_l - \frac{2(l+2)}{l+3}T_{l+2} + \frac{l+1}{l+3}T_{l+4} , l \in \bs{l}^B\}, \tag{58} \\
V^L &= \text{span}\{L_l - \frac{2(2l+5)}{2l+7}L_{l+2} + \frac{2l+3}{2l+7}, l \in \bs{l}^B\}, \tag{59}
\end{align}
$$

where \( \bs{l}^B = 0, 1, \ldots, N-5 \). A tensor product space may be constructed as \( W(x,y,z) = V^C(x) \otimes V^p(y) \otimes V^p(z) \), and the variational problem
$$
\begin{equation}
(v, \nabla^4 u)^N_w = (v, f)^N_w,
\tag{60}
\end{equation}
$$

where \( u \) and \( v \) are trial and test functions in \( W \), may be implemented in shenfun as shown below

from shenfun.chebyshev.bases import ShenBiharmonicBasis, Basis
from shenfun.fourier.bases import R2CBasis, C2CBasis
from shenfun.chebyshev.la import Biharmonic as Solver
from shenfun import inner , div , grad , TestFunction, TrialFunction, project, Dx
from shenfun import Function, TensorProductSpace
from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD

N = (32, 33, 34)
K0 = ShenBiharmonicBasis(N[0])
K1 = C2CBasis(N[1])
K2 = R2CBasis(N[2])
W = TensorProductSpace(comm, (K0, K1, K2))
u = TrialFunction(W)
v = TestFunction(W)
matrices = inner(v, div(grad(div(grad(u)))))
fj = Function(W, False)
fj[:] = np.random.random(fj.shape)

f_hat = inner(v, fj) # Some right hand side
B = Solver(**matrices)

# Solve and transform to real space
u_hat = Function(W) # Solution spectral space
u_hat = B(u_hat , f_hat) # Solve
u = Function(W, False)
u = W.backward(u_hat, u)

Note that C2CBasis is used for the Fourier basis along axis 1, whereas
R2CBasis is used for the last axis. This is because the right hand side of the
Poisson equation, and
thus the input data, is real and not complex. Yet, taking the Fourier
transform along the last axis, results in a complex array. Hence we need
real-to-complex transforms for axis 2 and complex-to-complex (C2CBasis)
transforms for axis 1.

    ← Prev

    Next →


text:
import {Anno} from './resources/setup';

class StaticMethod {
  @Anno
  static method(@Anno x) {}
}

assertArrayEquals([new Anno], StaticMethod.method.annotations);
assertArrayEquals([[new Anno]], StaticMethod.method.parameters);