text:
<?php
	/**
	*
	*/
	class Pay extends MY_controller
	{

		function __construct()
		{
			parent::__construct();
			$this->load->model('Bill_model');
			$this->load->model('BillInfo_model');
		}
		public function index()
		{
			$this->data['content']='front/pay/index';
			$this->load->view('front/layout/master',$this->data);
		}
		public function order()
		{
			$cart=$this->cart->contents();
			$this->Bill_model->create([
				'cus_name'=>$this->input->post('name'),
				'cus_phone'=>$this->input->post('phone'),
				'cus_email'=>$this->input->post('email'),
				'cus_adress'=>$this->input->post('address'),
				'total_price'=>$this->cart->total(),
				'created_at'=>date("Y-m-d"),
				'status'=>'0',
				'payment'=>$this->input->post('payment'),
				'note'=>$this->input->post('note')
				]);
			$bill_id=$this->db->insert_id();
			if($this->input->post('payment')=='offline')
			{
				foreach ($cart as $key => $value) {
					$this->BillInfo_model->create([
						'id_bill'=>$bill_id,
						'id_product'=>$value['id'],
						'quatyti'=>$value['qty'],
					]);
				}
				$this->cart->destroy();
				return redirect('pay/success');
			}
			if($this->input->post('payment')=='baokim')
			{
				$this->cart->destroy();
			}
		}
		public function success()
		{
			$this->data['content']='front/success/index';
			$this->load->view('front/layout/master',$this->data);
		}
	}
 ?>


text:
/**
 * assetWithBasePath
 * @param asset
 * @param basePath
 * @param isProd
 * @returns {*}
 */
function assetWithBasePath(asset, basePath, isProd) {
  if (asset.mediapath === undefined || asset.mediaurl === undefined) {
    return undefined;
  }

  if (process.env.NODE_ENV === "production" && isProd === true) {
    return basePath + asset.mediapath;
  }

  return asset.mediaurl;
}

export { assetWithBasePath };

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Insert X and Y coords"
        android:layout_marginTop="2dp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/x_percentage"
        android:hint="Insert x 0-100%"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:inputType="numberDecimal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/y_percentage"
        android:hint="Insert y 0-100%"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:inputType="numberDecimal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
var Domain = require("../../lib/Domain");

// Create new domain instance
var domain = new Domain();

// Get the getLeDataReportingDomain domain
domain.getLeDataReportingDomain("56072331", function(err, data) {
	if(err){
		console.log(err);
	}else{
		console.log(data);
		console.log(domain.leDataReportingDomain);
	}
});


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router} from '@angular/router';
//
import { environment } from '../../environments/environment';
//
import { AdminApiService } from '../admin-api.service';
//
import { RecruitContentComponent } from '../../app/recruit-content/recruit-content.component';
import { ApiService } from '../../app/api.service';
import { Recruit } from '../../app/recruit';
//

@Component({
  selector: 'app-recruit-edit',
  templateUrl: './recruit-edit.component.html',
  styleUrls: ['./recruit-edit.component.css']
})
export class RecruitEditComponent implements OnInit {

  editMode: boolean;
  id: any;
  type: string;
  recruit: Recruit;
  private sub: any;

  constructor(
    private router: Router,
    private apiService: ApiService,
    private adminApiService: AdminApiService,
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      if (params['id']) {
        this.id = params['id'];
        this.editMode = true;
        this.getRecruit(this.id);
      } else if (params['type']) {
        this.recruit = { type: params['type'], title: '', content: '' }
      } else {
        console.log('error');
      }
    });
  }

  getRecruit(id): void {
    this.apiService
      .getRecruit(id)
      .subscribe(data => {
        this.recruit = data;
      });
  }

  createRecruit(): void {
    this.adminApiService
      .createRecruit(this.recruit)
      .subscribe(data => {
        if (data.error_code != 0) {
          alert(data.error_code)
        }else{
          alert('新增成功');
          this.router.navigate(['/recruitments']);
        }
      });
  }

  updateRecruit(): void {
    this.adminApiService
      .updateRecruit(this.id, this.recruit)
      .subscribe(data => {
        if (data.error_code != 0) {
          alert(data.error_code)
        }
        else {
          alert('編輯成功');
          this.router.navigate(['/recruitments']);
        }
      });
  }

  deleteRecruit(): void {
    this.adminApiService
      .deleteRecruit(this.id)
      .subscribe(data => {
        if (data.error_code != 0) {
          alert(data.error_code)
        }
        else {
          alert('刪除成功');
          this.router.navigate(['/recruitments']);
        }
      });
  }

}


text:
namespace config {

ConfigContext::ConfigContext(const SourceSpec & spec)
    : ConfigContext(TimingValues(), spec)
{ }

ConfigContext::ConfigContext(const TimingValues & timingValues, const SourceSpec & spec)
    : _timingValues(timingValues),
      _generation(1),
      _manager(std::make_unique<ConfigManager>(spec.createSourceFactory(_timingValues), _generation))
{ }

IConfigManager &
ConfigContext::getManagerInstance()
{
    return *_manager;
}

void
ConfigContext::reload()
{
    _generation++;
    _manager->reload(_generation);
}

} // namespace config


text:
var obj2gltf = require('obj2gltf');
var options = {
    separateTextures : true // Don't embed image in the converted glTF
};

var args = process.argv.slice(2);

obj2gltf(args[0], args[0]+'.gltf', options)
    .then(function() {
        console.log('Conversion finished');
    },function(err){
        console.log('Whoops! Something went wrong!');
        console.error(err);
    });


text:
package com.blazemeter.jmeter.control;

import com.blazemeter.jmeter.threads.arrivals.ArrivalsThreadGroup;
import com.blazemeter.jmeter.threads.arrivals.ArrivalsThreadGroupTest;
import kg.apc.emulators.TestJMeterUtils;
import org.apache.jmeter.sampler.DebugSampler;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.*;

public class VirtualUserControllerTest {

    @BeforeClass
    public static void setUpClass() throws Exception {
        ArrivalsThreadGroupTest.setUpClass();
        TestJMeterUtils.createJmeterEnv();
    }

    @Test
    public void testThreadGroupInterrupted() {
        VirtualUserController vuc = new VirtualUserController();
        vuc.addTestElement(new DebugSampler());

        ArrivalsThreadGroup tg = new ArrivalsThreadGroup() {
            @Override
            public boolean isRunning() {
                return false;
            }
        };
        tg.addTestElement(vuc);
        vuc.setOwner(tg);
        assertNull(vuc.next());
    }
}


text:
import React from 'react';
import ReactSymbol from '../../../src/components/display/ReactSymbol.jsx';
import ShallowRenderer from 'react-test-renderer/shallow';
import unexpected from 'unexpected';
import unexpectedReactShallow from 'unexpected-react-shallow';

const expect = unexpected.clone().installPlugin(unexpectedReactShallow);
const renderer = new ShallowRenderer();

describe('ReactSymbol', () => {
    it('should render properly', function () {
        renderer.render(<ReactSymbol />);

        expect(renderer.getRenderOutput(), 'to have rendered',
            <div>⚛</div>
        )
    });
});


text:
include_recipe "bcpc::ceph-apt"

package "apache2" do
    action :upgrade
    version "2.2.22-1ubuntu1-inktank1"
end

package "libapache2-mod-fastcgi" do
    action :upgrade
    version "2.4.7~0910052141-1-inktank2"
end

%w{libapache2-mod-wsgi libapache2-mod-python libapache2-mod-php5}.each do |pkg|
    package pkg do
        action :upgrade
    end
end

%w{ssl wsgi python php5 proxy_http rewrite cache disk_cache}.each do |mod|
    bash "apache-enable-#{mod}" do
        user "root"
        code "a2enmod #{mod}"
        not_if "test -r /etc/apache2/mods-enabled/#{mod}.load"
        notifies :restart, "service[apache2]", :delayed
    end
end

template "/etc/apache2/sites-enabled/000-default" do
    source "apache-000-default.erb"
    owner "root"
    group "root"
    mode 00644
    notifies :restart, "service[apache2]", :delayed
end

bash "set-apache-bind-address" do
    code <<-EOH
        sed -i "s/\\\(^[\\\t ]*Listen[\\\t ]*\\\)80[\\\t ]*$/\\\\1#{node['bcpc']['management']['ip']}:80/g" /etc/apache2/ports.conf
        sed -i "s/\\\(^[\\\t ]*Listen[\\\t ]*\\\)443[\\\t ]*$/\\\\1#{node['bcpc']['management']['ip']}:443/g" /etc/apache2/ports.conf
    EOH
    not_if "grep #{node['bcpc']['management']['ip']} /etc/apache2/ports.conf"
    notifies :restart, "service[apache2]", :immediately
end

service "apache2" do
    action [:enable, :start]
end

template "/var/www/index.html" do
    source "index.html.erb"
    owner "root"
    group "root"
    mode 00644
    variables ({ :cookbook_version => run_context.cookbook_collection[cookbook_name].metadata.version })
end


text:
require 'spec_helper'

describe GeneratorType do
  it { should have_one :technical_component }
  it { should have_many :generators }
  it { should belong_to :fuel_market }

  it { should validate_presence_of :safety_mtbf }
  it { should validate_presence_of :safety_incident_severity }

  it { should validate_presence_of :ramping_speed }
  it { should allow_value(0).for(:ramping_speed) }
  it { should_not allow_value(-1).for(:ramping_speed) }

  it { should validate_presence_of :marginal_fuel_burn_rate }
  it { should allow_value(0).for(:marginal_fuel_burn_rate) }
  it { should_not allow_value(-1).for(:marginal_fuel_burn_rate) }

  it { should validate_presence_of :air_emissions }
  it { should_not allow_value(-1).for(:air_emissions) }

  it { should validate_presence_of :water_emissions }
  it { should_not allow_value(-1).for(:water_emissions) }

  it { should validate_presence_of :maintenance_cost_min }
  it { should_not allow_value(-1).for(:maintenance_cost_min) }

  it { should validate_presence_of :maintenance_cost_max }
  it { should_not allow_value(0).for(:maintenance_cost_max) }

  it { should validate_presence_of :tax_credit }
  it { should_not allow_value(-1).for(:tax_credit) }

  context "A GeneratorType instance" do
    before do
      @generator_type = Factory :generator_type
      @game = Factory :game
      @state = Factory :state, :game => @game
      @city = Factory :city, :state => @state
    end

    it "should return its marginal cost" do
      @generator_type.marginal_cost(@city).should be > 0
    end

    context "with a renewable fuel" do
      before do
        @generator_type.marginal_fuel_burn_rate = 0
      end

      it "should know its fuel is renewable" do
        @generator_type.renewable?.should eq true
      end

      it "should know it doesn't burn any fuel" do
        @generator_type.marginal_fuel_cost(@city).should eq(0)
      end
    end

    context "with a nonrenewable fuel" do
      it "should know its fuel is renewable" do
        @generator_type.renewable?.should be(false)
      end

      it "should return the amount of fuel it burns" do
        @generator_type.marginal_fuel_cost(@city).should eq(
            @city.current_price(@generator_type.fuel_market) *
              @generator_type.marginal_fuel_burn_rate)
      end

      it "should return a marginal cost dependent on fuel price" do
        original_mc = @generator_type.marginal_cost(@city)
        @generator_type.fuel_market.market_prices.create(:price => 42,
            :game => @game)
        assert_not_equal original_mc, @generator_type.marginal_cost(@city)
      end
    end
  end
end


text:
package net.sf.openmm.frontend2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.webkit.MimeTypeMap;

public class OpenMMUtil
{
	private static final String TAG = OpenMMUtil.class.getSimpleName();

	public static int BACKGROUND_COLOR = 0xFF3385FF;

	static final String PREF_NAME = "OpenMM2";

	public static SharedPreferences getPrefs( Context act )
	{
		return act.getSharedPreferences( OpenMMUtil.PREF_NAME, 0 );
	}

	/**
	 * Get the server url
	 * @param act
	 * @return
	 */
	public static String getServerConfigUrl( Activity act )
	{
		return getPrefs( act ).getString( "server.url", "http://localhost:3760" );
	}

	/**
	 * Get the server url
	 * @param act
	 * @return
	 */
	public static String getServerUrl( Activity act )
	{
		return getPrefs( act ).getString( "server.url", "http://localhost:3760" ) + "/openmm";
	}

	/**
	 * Get the server url with username/password
	 * @param act
	 * @return
	 */
	public static String getServerAccessUrl( Activity act )
	{
		return getServerUrl( act ).replace( "://", "://" + getServerUsername( act ) + ':' + getServerPassword( act ) + '@' );
	}

	/**
	 * Get the server password
	 * @param act
	 * @return
	 */
	public static String getServerPassword( Context act )
	{
		return getPrefs( act ).getString( "server.password", "password" );
	}

	/**
	 * Get the server username
	 * @param act
	 * @return
	 */
	public static String getServerUsername( Context act )
	{
		return getPrefs( act ).getString( "server.username", "admin" );
	}

	/**
	 * Get the number of rows to display
	 * @param act
	 * @return
	 */
	public static int getDisplayRows( Activity act )
	{
		return getPrefs( act ).getInt( "display.rows", 9 );
	}

	public static int getDisplayWidth( Activity act )
	{
		final Display display = act.getWindowManager().getDefaultDisplay();
		final Point size = new Point();
		display.getSize(size);
		return size.x;
	}

	public static int getTextViewHeight( Activity act )
	{
		final Display display = act.getWindowManager().getDefaultDisplay();
		final Point size = new Point();
		display.getSize( size );
		final int height = size.y;
		final int numRows = getPrefs( act ).getInt( "display.rows", 9 );

		final int TEXT_VIEW_HEIGHT = height / numRows;
		return TEXT_VIEW_HEIGHT;
	}

	public static int getTextMaxHeight( Activity act )
	{
		return getTextViewHeight( act ) * 9 / 10;
	}

	/**
	 * Play a url
	 * @param activity
	 * @param url
	 * @param ext
	 */
	public static void playUrl( Activity act, String url, String ext )
	{
		Log.d( TAG, "playUrl(" + url + ',' + ext + ')' );
		final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( ext );
		final Intent mediaIntent = new Intent( Intent.ACTION_VIEW );
		mediaIntent.setDataAndType( Uri.parse( url ), mimeType );
		act.startActivity( mediaIntent );
	}

	/**
	 * Start an activity
	 * @param act
	 * @param i
	 */
	public static void startActivityForResult( Activity act, Intent i )
	{
		if ( act.getIntent().hasExtra( "ACT_INDEX" ) )
		{
			int myIndex = act.getIntent().getIntExtra( "ACT_INDEX", 1 );
			i.putExtra( "ACT_INDEX", myIndex + 1 );
			Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + ( myIndex + 1 ) + ']' );
			act.startActivityForResult( i, myIndex + 1 );
		}
		else
		{
			i.putExtra( "ACT_INDEX", 1 );
			Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + 1 + ']' );
			act.startActivityForResult( i, 1 );
		}
	}

}


text:
<?php

namespace Jacoz\Symfony\ApiBundle\Entity\Traits;

use Doctrine\ORM\Mapping as ORM;

trait TimestampFieldsTrait
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", name="created_at")
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", name="updated_at")
     */
    protected $updatedAt;

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $createdAt
     */
    public function setCreatedAt(\DateTime $createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param \DateTime $updatedAt
     */
    public function setUpdatedAt(\DateTime $updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    /**
     * @ORM\PrePersist
     */
    public function updatedTimestamps()
    {
        $now = new \DateTime();

        if (!$this->getCreatedAt()) {
            $this->setCreatedAt($now);
        }

        $this->setUpdatedAt($now);
    }
}


text:
/**
 *
 */
package gov.va.med.siteservice;

import gov.va.med.imaging.DateUtil;

import java.io.File;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.log4j.Logger;

/**
 * @author vhaiswbeckec
 *
 */
public class SiteServiceConfiguration implements Serializable {
	private static final long serialVersionUID = 1L;
	public static String defaultSiteService = "http://localhost/VistaWebSvcs/ImagingExchangeSiteService.asmx";
	public static URI defaultSiteServiceUri = null;
	private static final String defaultVhaSitesXmlFileName = "VhaSites.xml";

	static {
		try {
			defaultSiteServiceUri = new URI(
					"http://localhost/VistaWebSvcs/ImagingExchangeSiteService.asmx");
		} catch (URISyntaxException e) {
			Logger.getLogger(SiteServiceConfiguration.class).error(
					e.getMessage());
		}
	}

	/**
	 * @return
	 */
	public static SiteServiceConfiguration createDefault(
			File configurationDirectory) {
		SiteServiceConfiguration config = new SiteServiceConfiguration();

		config.setRefreshHour(Messages.getInt(
				"SiteResolutionProvider.defaultRefreshHour", 23));
		config.setRefreshMinimumDelay(Messages.getInt(
				"SiteResolutionProvider.defaultRefreshMinimumDelay", 1));
		config.setRefreshPeriod(Messages.getLong(
				"SiteResolutionProvider.defaultRefreshPeriod",
				DateUtil.MILLISECONDS_IN_DAY));
		config
				.setSiteServiceCacheFileName(configurationDirectory
						+ "/"
						+ Messages
								.getString("SiteResolutionProvider.siteServiceCacheFileName"));
		config
				.setRegionListCacheFileName(configurationDirectory
						+ "/"
						+ Messages
								.getString("SiteResolutionProvider.siteServiceRegionCacheFileName"));
		config
				.setVhaSitesXmlFileName(configurationDirectory
				+ "/"
				+ Messages
						.getString("SiteResolutionProvider.vhaSitesXmlFileName"));
		config.setSiteServiceUri(defaultSiteServiceUri);
		config.setForceLoadFromLocalCache(false);
		config.setUseV2Service(true);
		return config;
	}

	private URI siteServiceUri = defaultSiteServiceUri;
	private int refreshHour;
	private int refreshMinimumDelay;
	private long refreshPeriod;
	private String siteServiceCacheFileName;
	private String regionListCacheFileName;
	private String vhaSitesXmlFileName;
	private boolean forceLoadFromLocalCache;
	private boolean useV2Service;

	public URI getSiteServiceUri() {
		return this.siteServiceUri;
	}

	public int getRefreshHour() {
		return this.refreshHour;
	}

	public int getRefreshMinimumDelay() {
		return this.refreshMinimumDelay;
	}

	public long getRefreshPeriod() {
		return this.refreshPeriod;
	}

	public String getSiteServiceCacheFileName() {
		return this.siteServiceCacheFileName;
	}

	public String getRegionListCacheFileName() {
		return this.regionListCacheFileName;
	}

	public String getVhaSitesXmlFileName() {
		if (vhaSitesXmlFileName != null)
			return this.vhaSitesXmlFileName;
		else
			return System.getenv("vixconfig") + "/" + defaultVhaSitesXmlFileName;
	}

	public void setSiteServiceUri(URI siteServiceUri) {
		this.siteServiceUri = siteServiceUri;
	}

	public void setRefreshHour(int refreshHour) {
		this.refreshHour = refreshHour;
	}

	public void setRefreshMinimumDelay(int refreshMinimumDelay) {
		this.refreshMinimumDelay = refreshMinimumDelay;
	}

	public void setRefreshPeriod(long refreshPeriod) {
		this.refreshPeriod = refreshPeriod;
	}

	public void setSiteServiceCacheFileName(String siteServiceCacheFileName) {
		this.siteServiceCacheFileName = siteServiceCacheFileName;
	}

	public void setRegionListCacheFileName(String regionListCacheFileName) {
		this.regionListCacheFileName = regionListCacheFileName;
	}

	public void setVhaSitesXmlFileName(String vhaSitesFileName) {
		this.vhaSitesXmlFileName = vhaSitesFileName;
	}

	public boolean getForceLoadFromLocalCache() {
		return forceLoadFromLocalCache;
	}

	public void setForceLoadFromLocalCache(boolean forceLoadFromLocalCache) {
		this.forceLoadFromLocalCache = forceLoadFromLocalCache;
	}

	/**
	 * @return the useV2Service
	 */
	public boolean isUseV2Service()
	{
		return useV2Service;
	}

	/**
	 * @param useV2Service the useV2Service to set
	 */
	public void setUseV2Service(boolean useV2Service)
	{
		this.useV2Service = useV2Service;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + this.refreshHour;
		result = prime * result + this.refreshMinimumDelay;
		result = prime * result
				+ (int) (this.refreshPeriod ^ (this.refreshPeriod >>> 32));
		result = prime
				* result
				+ ((this.regionListCacheFileName == null) ? 0
						: this.regionListCacheFileName.hashCode());
		result = prime
				* result
				+ ((this.siteServiceCacheFileName == null) ? 0
						: this.siteServiceCacheFileName.hashCode());
		result = prime
				* result
				+ ((this.vhaSitesXmlFileName == null) ? 0
						: this.vhaSitesXmlFileName.hashCode());
		result = prime
				* result
				+ ((this.siteServiceUri == null) ? 0 : this.siteServiceUri
						.hashCode());
		result = prime
				* result
				+ (forceLoadFromLocalCache ? 0 : 1);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final SiteServiceConfiguration other = (SiteServiceConfiguration) obj;
		if (this.refreshHour != other.refreshHour)
			return false;
		if (this.refreshMinimumDelay != other.refreshMinimumDelay)
			return false;
		if (this.refreshPeriod != other.refreshPeriod)
			return false;
		if (this.forceLoadFromLocalCache != other.forceLoadFromLocalCache)
			return false;
		if (this.regionListCacheFileName == null) {
			if (other.regionListCacheFileName != null)
				return false;
		} else if (!this.regionListCacheFileName
				.equals(other.regionListCacheFileName))
			return false;
		if (this.siteServiceCacheFileName == null) {
			if (other.siteServiceCacheFileName != null)
				return false;
		} else if (!this.siteServiceCacheFileName
				.equals(other.siteServiceCacheFileName))
			return false;
		if (this.vhaSitesXmlFileName == null) {
			if (other.vhaSitesXmlFileName != null)
				return false;
		} else if (!this.vhaSitesXmlFileName
				.equals(other.vhaSitesXmlFileName))
			return false;
		if (this.siteServiceUri == null) {
			if (other.siteServiceUri != null)
				return false;
		} else if (!this.siteServiceUri.equals(other.siteServiceUri))
			return false;
		return true;
	}
}


text:
<docs-search
  :list="[
    {id: 'component-a', name: 'component-a', path: '.', title: 'Component A'},
    {id: 'component-b', name: 'component-a', path: '.', title: 'Component B'},
    {id: 'other', name: 'component-a', path: '.', title: 'Other'}]"
  :current-view="'component-a'">
</docs-search>


text:
#pragma once
#ifndef _AIMLib_CalculationResult_Class_
#define _AIMLib_CalculationResult_Class_

#include <string>
#include <vector>

namespace aim_lib
{
	class AIMLIB_API CalculationResult
	{
	public:
		enum CalculationResultType
		{
			InvalidCalculationResultType = -1,
			Scalar = 0,
			Vector = 1,
			Histogram = 2,
			Matrix = 3,
			Array = 4,
			Binary = 5 // Very special case. You should probably not use it.
		};

	public:
		CalculationResult& operator=(const CalculationResult& calculationResult);
		virtual CalculationResult* Clone() const = 0;
		virtual ~CalculationResult();

		CalculationResultType GetType() const;
		const std::string& GetUnitOfMeasure() const;
		const iso_21090::CD& GetDataType() const;
		const DimensionVector& GetDimensionCollection() const;

		void SetType(CalculationResultType newVal);
		void SetUnitOfMeasure(const std::string& newVal);
		void SetDataType(const iso_21090::CD& newVal);
		void SetDimensionCollection(const DimensionVector& dimensionCollection);

		static const std::string CalculationResultTypeToString(const CalculationResultType& type);
		static const CalculationResultType StringToCalculationResultType(const std::string& stringType);

	protected:
		CalculationResult();
		CalculationResult(const CalculationResult& calculationResult);

		CalculationResultType _type;
		iso_21090::CD _dataType;
		std::string _unitOfMeasure;

		DimensionVector _dimensionCollection;
	};

	typedef std::vector<CalculationResult*> CalculationResultPtrVector;
}
#endif // _AIMLib_CalculationResult_Class_


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

#	rescue_from CanCan::AccessDenied do |exception|
#		redirect_to admin_dashboard_path, :alert => exception.message
#	end

  def current_ability
    @current_ability ||= Ability.new(current_user)
  end

end


text:
//Copyright (c) 2015-2021 Oliver Lehmann <lehmann@ans-netz.de>
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//1. Redistributions of source code must retain the above copyright
//notice, this list of conditions and the following disclaimer
//2. Redistributions in binary form must reproduce the above copyright
//notice, this list of conditions and the following disclaimer in the
//documentation and/or other materials provided with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
//ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
//OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
//OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.

package org.laladev.moneyjinn.server.controller.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.laladev.moneyjinn.core.error.ErrorCode;
import org.laladev.moneyjinn.core.rest.model.ValidationResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.CreateMoneyflowRequest;
import org.laladev.moneyjinn.core.rest.model.moneyflow.SearchMoneyflowsByAmountResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.SearchMoneyflowsRequest;
import org.laladev.moneyjinn.core.rest.model.moneyflow.SearchMoneyflowsResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.ShowAddMoneyflowsResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.ShowDeleteMoneyflowResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.ShowEditMoneyflowResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.ShowSearchMoneyflowFormResponse;
import org.laladev.moneyjinn.core.rest.model.moneyflow.UpdateMoneyflowRequest;
import org.laladev.moneyjinn.core.rest.model.transport.CapitalsourceTransport;
import org.laladev.moneyjinn.core.rest.model.transport.ContractpartnerTransport;
import org.laladev.moneyjinn.core.rest.model.transport.MoneyflowSplitEntryTransport;
import org.laladev.moneyjinn.core.rest.model.transport.MoneyflowTransport;
import org.laladev.moneyjinn.core.rest.model.transport.PostingAccountTransport;
import org.laladev.moneyjinn.core.rest.model.transport.PreDefMoneyflowTransport;
import org.laladev.moneyjinn.core.rest.model.transport.ValidationItemTransport;
import org.laladev.moneyjinn.model.Contractpartner;
import org.laladev.moneyjinn.model.PostingAccount;
import org.laladev.moneyjinn.model.PreDefMoneyflow;
import org.laladev.moneyjinn.model.PreDefMoneyflowID;
import org.laladev.moneyjinn.model.access.AccessRelation;
import org.laladev.moneyjinn.model.access.Group;
import org.laladev.moneyjinn.model.access.User;
import org.laladev.moneyjinn.model.access.UserID;
import org.laladev.moneyjinn.model.capitalsource.Capitalsource;
import org.laladev.moneyjinn.model.moneyflow.Moneyflow;
import org.laladev.moneyjinn.model.moneyflow.MoneyflowID;
import org.laladev.moneyjinn.model.moneyflow.MoneyflowSplitEntry;
import org.laladev.moneyjinn.model.moneyflow.MoneyflowSplitEntryID;
import org.laladev.moneyjinn.model.moneyflow.search.MoneyflowSearchParams;
import org.laladev.moneyjinn.model.validation.ValidationResult;
import org.laladev.moneyjinn.model.validation.ValidationResultItem;
import org.laladev.moneyjinn.server.annotation.RequiresAuthorization;
import org.laladev.moneyjinn.server.controller.mapper.CapitalsourceTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.ContractpartnerTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.MoneyflowSearchParamsTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.MoneyflowSplitEntryTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.MoneyflowTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.PostingAccountTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.PreDefMoneyflowTransportMapper;
import org.laladev.moneyjinn.server.controller.mapper.ValidationItemTransportMapper;
import org.laladev.moneyjinn.service.api.IAccessRelationService;
import org.laladev.moneyjinn.service.api.ICapitalsourceService;
import org.laladev.moneyjinn.service.api.IContractpartnerService;
import org.laladev.moneyjinn.service.api.IMoneyflowReceiptService;
import org.laladev.moneyjinn.service.api.IMoneyflowService;
import org.laladev.moneyjinn.service.api.IMoneyflowSplitEntryService;
import org.laladev.moneyjinn.service.api.IPostingAccountService;
import org.laladev.moneyjinn.service.api.IPreDefMoneyflowService;
import org.laladev.moneyjinn.service.api.IUserService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Transactional(propagation = Propagation.REQUIRES_NEW)
@RequestMapping("/moneyflow/server/moneyflow/")
public class MoneyflowController extends AbstractController {
	private static final Short SHORT_1 = new Short("1");
	@Inject
	private IUserService userService;
	@Inject
	private IAccessRelationService accessRelationService;
	@Inject
	private IPreDefMoneyflowService preDefMoneyflowService;
	@Inject
	private ICapitalsourceService capitalsourceService;
	@Inject
	private IContractpartnerService contractpartnerService;
	@Inject
	private IPostingAccountService postingAccountService;
	@Inject
	private IMoneyflowService moneyflowService;
	@Inject
	private IMoneyflowSplitEntryService moneyflowSplitEntryService;
	@Inject
	private IMoneyflowReceiptService moneyflowReceiptService;

	private static final DateTimeFormatter SEARCH_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

	@Override
	protected void addBeanMapper() {
		super.registerBeanMapper(new CapitalsourceTransportMapper());
		super.registerBeanMapper(new ContractpartnerTransportMapper());
		super.registerBeanMapper(new PostingAccountTransportMapper());
		super.registerBeanMapper(new PreDefMoneyflowTransportMapper());
		super.registerBeanMapper(new MoneyflowTransportMapper());
		super.registerBeanMapper(new ValidationItemTransportMapper());
		super.registerBeanMapper(new MoneyflowSearchParamsTransportMapper());
		super.registerBeanMapper(new MoneyflowSplitEntryTransportMapper());
	}

	private boolean isOnceAMonthAndAlreadyUsed(final LocalDate today, final PreDefMoneyflow preDefMoneyflow) {
		final LocalDate lastUsedDate = preDefMoneyflow.getLastUsedDate();

		return preDefMoneyflow.isOnceAMonth() //
				&& lastUsedDate != null && lastUsedDate.getMonth().equals(today.getMonth()) //
				&& lastUsedDate.getYear() == today.getYear();
	}

	@RequestMapping(value = "showAddMoneyflows", method = { RequestMethod.GET })
	@RequiresAuthorization
	public ShowAddMoneyflowsResponse showAddMoneyflows() {
		final UserID userId = super.getUserId();
		final ShowAddMoneyflowsResponse response = new ShowAddMoneyflowsResponse();

		final LocalDate today = LocalDate.now();

		final List<Capitalsource> capitalsources = this.capitalsourceService
				.getGroupBookableCapitalsourcesByDateRange(userId, today, today);
		if (capitalsources != null && !capitalsources.isEmpty()) {
			response.setCapitalsourceTransports(super.mapList(capitalsources, CapitalsourceTransport.class));
		}

		final List<Contractpartner> contractpartner = this.contractpartnerService
				.getAllContractpartnersByDateRange(userId, today, today);
		if (contractpartner != null && !contractpartner.isEmpty()) {
			response.setContractpartnerTransports(super.mapList(contractpartner, ContractpartnerTransport.class));
		}

		final List<PostingAccount> postingAccounts = this.postingAccountService.getAllPostingAccounts();
		if (postingAccounts != null && !postingAccounts.isEmpty()) {
			response.setPostingAccountTransports(super.mapList(postingAccounts, PostingAccountTransport.class));
		}

		List<PreDefMoneyflow> preDefMoneyflows = this.preDefMoneyflowService.getAllPreDefMoneyflows(userId);
		if (preDefMoneyflows != null && !preDefMoneyflows.isEmpty()) {
			preDefMoneyflows = preDefMoneyflows.stream().filter(pdm -> !this.isOnceAMonthAndAlreadyUsed(today, pdm))
					.collect(Collectors.toCollection(ArrayList::new));
			response.setPreDefMoneyflowTransports(super.mapList(preDefMoneyflows, PreDefMoneyflowTransport.class));
		}

		return response;
	}

	@RequestMapping(value = "showEditMoneyflow/{id}", method = { RequestMethod.GET })
	@RequiresAuthorization
	public ShowEditMoneyflowResponse showEditMoneyflow(@PathVariable(value = "id") final Long id) {

		final UserID userId = super.getUserId();
		final ShowEditMoneyflowResponse response = new ShowEditMoneyflowResponse();

		final Moneyflow moneyflow = this.moneyflowService.getMoneyflowById(userId, new MoneyflowID(id));

		if (moneyflow != null && moneyflow.getUser().getId().equals(userId)) {
			response.setMoneyflowTransport(super.map(moneyflow, MoneyflowTransport.class));

			final List<MoneyflowSplitEntry> moneyflowSplitEntries = this.moneyflowSplitEntryService
					.getMoneyflowSplitEntries(userId, moneyflow.getId());
			if (!moneyflowSplitEntries.isEmpty()) {
				response.setMoneyflowSplitEntryTransports(
						super.mapList(moneyflowSplitEntries, MoneyflowSplitEntryTransport.class));
			}

			final List<Capitalsource> capitalsources = this.capitalsourceService.getGroupBookableCapitalsources(userId);
			response.setCapitalsourceTransports(super.mapList(capitalsources, CapitalsourceTransport.class));

			final List<Contractpartner> contractpartner = this.contractpartnerService.getAllContractpartners(userId);
			response.setContractpartnerTransports(super.mapList(contractpartner, ContractpartnerTransport.class));

			final List<PostingAccount> postingAccounts = this.postingAccountService.getAllPostingAccounts();
			response.setPostingAccountTransports(super.mapList(postingAccounts, PostingAccountTransport.class));

			final List<MoneyflowID> moneyflowIdsWithReceipts = this.moneyflowReceiptService
					.getMoneyflowIdsWithReceipt(userId, Arrays.asList(moneyflow.getId()));

			response.setHasReceipt(moneyflowIdsWithReceipts.size() == 1);

		}

		return response;
	}

	@RequestMapping(value = "showDeleteMoneyflow/{id}", method = { RequestMethod.GET })
	@RequiresAuthorization
	public ShowDeleteMoneyflowResponse showDeleteMoneyflow(@PathVariable(value = "id") final Long id) {
		final UserID userId = super.getUserId();
		final MoneyflowID moneyflowId = new MoneyflowID(id);
		final ShowDeleteMoneyflowResponse response = new ShowDeleteMoneyflowResponse();

		final Moneyflow moneyflow = this.moneyflowService.getMoneyflowById(userId, moneyflowId);
		if (moneyflow != null && moneyflow.getUser().getId().equals(userId)) {
			response.setMoneyflowTransport(super.map(moneyflow, MoneyflowTransport.class));
		}

		return response;
	}

	@RequestMapping(value = "showSearchMoneyflowForm", method = { RequestMethod.GET })
	@RequiresAuthorization
	public ShowSearchMoneyflowFormResponse showSearchMoneyflowForm() {
		final UserID userId = super.getUserId();
		final ShowSearchMoneyflowFormResponse response = new ShowSearchMoneyflowFormResponse();

		final List<Contractpartner> contractpartner = this.contractpartnerService.getAllContractpartners(userId);
		if (contractpartner != null && !contractpartner.isEmpty()) {
			final List<ContractpartnerTransport> contractpartnerTransports = super.mapList(contractpartner,
					ContractpartnerTransport.class);
			response.setContractpartnerTransports(contractpartnerTransports);
		}

		final List<PostingAccount> postingAccounts = this.postingAccountService.getAllPostingAccounts();
		if (postingAccounts != null && !postingAccounts.isEmpty()) {
			final List<PostingAccountTransport> postingAccountTransports = super.mapList(postingAccounts,
					PostingAccountTransport.class);
			response.setPostingAccountTransports(postingAccountTransports);
		}

		return response;
	}

	@RequestMapping(value = "searchMoneyflows", method = { RequestMethod.PUT })
	@RequiresAuthorization
	public SearchMoneyflowsResponse searchMoneyflows(@RequestBody final SearchMoneyflowsRequest request) {
		final UserID userId = super.getUserId();

		final SearchMoneyflowsResponse response = new SearchMoneyflowsResponse();

		final MoneyflowSearchParams moneyflowSearchParams = super.map(request.getMoneyflowSearchParamsTransport(),
				MoneyflowSearchParams.class);

		final ValidationResult validationResult = new ValidationResult();

		if (moneyflowSearchParams == null || (moneyflowSearchParams.getContractpartnerId() == null
				&& moneyflowSearchParams.getPostingAccountId() == null
				&& moneyflowSearchParams.getSearchString() == null)) {
			validationResult
					.addValidationResultItem(new ValidationResultItem(null, ErrorCode.NO_SEARCH_CRITERIA_ENTERED));
		}

		if (!validationResult.isValid()) {
			response.setResult(false);
			response.setValidationItemTransports(
					super.mapList(validationResult.getValidationResultItems(), ValidationItemTransport.class));
		} else {
			final List<Moneyflow> moneyflows = this.moneyflowService.searchMoneyflows(userId, moneyflowSearchParams);
			if (moneyflows != null && !moneyflows.isEmpty()) {

				final List<MoneyflowTransport> moneyflowTransports = moneyflows.stream()
						.filter(mf -> !mf.isPrivat() || mf.getUser().getId().equals(userId))
						.map(mf -> super.map(mf, MoneyflowTransport.class))
						.collect(Collectors.toCollection(ArrayList::new));

				response.setMoneyflowTransports(moneyflowTransports);
			}
		}

		final List<Contractpartner> contractpartner = this.contractpartnerService.getAllContractpartners(userId);
		if (contractpartner != null && !contractpartner.isEmpty()) {
			final List<ContractpartnerTransport> contractpartnerTransports = super.mapList(contractpartner,
					ContractpartnerTransport.class);
			response.setContractpartnerTransports(contractpartnerTransports);
		}

		final List<PostingAccount> postingAccounts = this.postingAccountService.getAllPostingAccounts();
		if (postingAccounts != null && !postingAccounts.isEmpty()) {
			final List<PostingAccountTransport> postingAccountTransports = super.mapList(postingAccounts,
					PostingAccountTransport.class);
			response.setPostingAccountTransports(postingAccountTransports);
		}

		return response;
	}

	/**
	 * Creates a new moneyflow together with split entries if they where given.
	 *
	 * @param request
	 *            The request which contains the moneyflow
	 * @return ValidationResponse
	 */
	@RequestMapping(value = "createMoneyflow", method = { RequestMethod.POST })
	@RequiresAuthorization
	public ValidationResponse createMoneyflows(@RequestBody final CreateMoneyflowRequest request) {
		final UserID userId = super.getUserId();

		final Moneyflow moneyflow = super.map(request.getMoneyflowTransport(), Moneyflow.class);
		final List<MoneyflowSplitEntry> moneyflowSplitEntries = super.mapList(
				request.getInsertMoneyflowSplitEntryTransports(), MoneyflowSplitEntry.class);

		final Long preDefMoneyflowIdLong = request.getUsedPreDefMoneyflowId();

		boolean saveAsPreDefMoneyflow = false;
		final Short saveAsPreDefMoneyflowShort = request.getSaveAsPreDefMoneyflow();
		if (saveAsPreDefMoneyflowShort != null && saveAsPreDefMoneyflowShort.equals(SHORT_1)) {
			saveAsPreDefMoneyflow = true;
		}

		final User user = this.userService.getUserById(userId);
		final Group group = this.accessRelationService.getAccessor(userId);

		moneyflow.setUser(user);
		moneyflow.setGroup(group);

		this.prepareForValidityCheck(moneyflow, moneyflowSplitEntries);

		final ValidationResponse response = new ValidationResponse();
		final ValidationResult validationResult = this.moneyflowService.validateMoneyflow(moneyflow);

		if (validationResult.isValid()) {
			if (!moneyflowSplitEntries.isEmpty()) {
				moneyflowSplitEntries.stream().forEach(mse -> {
					validationResult
							.mergeValidationResult(this.moneyflowSplitEntryService.validateMoneyflowSplitEntry(mse));
				});

				if (validationResult.isValid()) {
					validationResult.mergeValidationResult(this.checkIfAmountIsEqual(moneyflow, moneyflowSplitEntries));
				}
			}

			if (validationResult.isValid()) {
				final MoneyflowID moneyflowId = this.moneyflowService.createMoneyflow(moneyflow);
				if (!moneyflowSplitEntries.isEmpty()) {
					moneyflowSplitEntries.stream().forEach(mse -> mse.setMoneyflowId(moneyflowId));
					this.moneyflowSplitEntryService.createMoneyflowSplitEntries(userId, moneyflowSplitEntries);
				}

				PreDefMoneyflowID preDefMoneyflowId = null;
				if (preDefMoneyflowIdLong != null) {
					preDefMoneyflowId = new PreDefMoneyflowID(preDefMoneyflowIdLong);
				}

				if (saveAsPreDefMoneyflow) {
					final PreDefMoneyflow preDefMoneyflow = new PreDefMoneyflow();
					preDefMoneyflow.setAmount(moneyflow.getAmount());
					preDefMoneyflow.setCapitalsource(moneyflow.getCapitalsource());
					preDefMoneyflow.setComment(moneyflow.getComment());
					preDefMoneyflow.setContractpartner(moneyflow.getContractpartner());
					preDefMoneyflow.setPostingAccount(moneyflow.getPostingAccount());
					preDefMoneyflow.setUser(user);

					if (preDefMoneyflowId != null) {
						final PreDefMoneyflow preDefMoneyflowOrig = this.preDefMoneyflowService
								.getPreDefMoneyflowById(userId, preDefMoneyflowId);
						if (preDefMoneyflowOrig != null) {
							preDefMoneyflow.setId(preDefMoneyflowId);
							preDefMoneyflow.setOnceAMonth(preDefMoneyflowOrig.isOnceAMonth());

							this.preDefMoneyflowService.updatePreDefMoneyflow(preDefMoneyflow);
						}
					} else {
						preDefMoneyflow.setOnceAMonth(false);
						preDefMoneyflowId = this.preDefMoneyflowService.createPreDefMoneyflow(preDefMoneyflow);
					}
				}

				if (preDefMoneyflowId != null) {
					this.preDefMoneyflowService.setLastUsedDate(userId, preDefMoneyflowId);
				}

				return null;
			}
		}

		if (!validationResult.isValid()) {
			response.setResult(false);
			response.setValidationItemTransports(
					super.mapList(validationResult.getValidationResultItems(), ValidationItemTransport.class));
		}

		return response;
	}

	/**
	 * Checks if capitalsource and contractparter are valid on bookingdate - otherwise the validity
	 * is modified. Also fills comment and postingaccount if it is empty and MoneyflowSplitEntries
	 * where provided with data from the first MoneyflowSplitEntry.
	 *
	 * @param moneyflow
	 *            Moneyflow
	 * @param moneyflowSplitEntries
	 *            MoneyflowSplitEntries
	 */
	private void prepareForValidityCheck(final Moneyflow moneyflow,
			final List<MoneyflowSplitEntry> moneyflowSplitEntries) {
		final LocalDate bookingDate = moneyflow.getBookingDate();

		final UserID userId = moneyflow.getUser().getId();
		final Group group = moneyflow.getGroup();

		if (bookingDate != null) {

			final AccessRelation accessRelation = this.accessRelationService
					.getAccessRelationById(moneyflow.getUser().getId(), LocalDate.now());
			// Only modify Capitalsources or Contractpartner if the Bookingdate is within the
			// current group assignment validity period
			if (!bookingDate.isBefore(accessRelation.getValidFrom())
					&& !bookingDate.isAfter(accessRelation.getValidTil())) {
				// Check if used Capitalsource is valid at bookingDate - if not, change its
				// validity so it fits.
				if (moneyflow.getCapitalsource() != null) {
					final Capitalsource capitalsource = this.capitalsourceService.getCapitalsourceById(userId,
							group.getId(), moneyflow.getCapitalsource().getId());

					if (capitalsource != null) {
						final boolean userMayUseCapitalsource = capitalsource.getUser().getId()
								.equals(moneyflow.getUser().getId()) || capitalsource.isGroupUse();

						if (userMayUseCapitalsource) {
							final boolean bookingDateIsBeforeValidity = bookingDate
									.isBefore(capitalsource.getValidFrom());
							final boolean bookingDateIsAfterValidity = bookingDate.isAfter(capitalsource.getValidTil());

							if (bookingDateIsBeforeValidity) {
								capitalsource.setValidFrom(bookingDate);
							}
							if (bookingDateIsAfterValidity) {
								capitalsource.setValidTil(bookingDate);
							}
							if (bookingDateIsAfterValidity || bookingDateIsBeforeValidity) {
								this.capitalsourceService.updateCapitalsource(capitalsource);

							}

						}
					}
				}

				// Check if used Contractpartner is valid at bookingDate - if not, change its
				// validity so it fits.
				if (moneyflow.getContractpartner() != null) {
					final Contractpartner contractpartner = this.contractpartnerService.getContractpartnerById(userId,
							moneyflow.getContractpartner().getId());

					if (contractpartner != null) {
						final boolean bookingDateIsBeforeValidity = bookingDate
								.isBefore(contractpartner.getValidFrom());
						final boolean bookingDateIsAfterValidity = bookingDate.isAfter(contractpartner.getValidTil());

						if (bookingDateIsBeforeValidity) {
							contractpartner.setValidFrom(bookingDate);
						}
						if (bookingDateIsAfterValidity) {
							contractpartner.setValidTil(bookingDate);
						}
						if (bookingDateIsAfterValidity || bookingDateIsBeforeValidity) {
							this.contractpartnerService.updateContractpartner(contractpartner);

						}
					}
				}
			}
		}

		// use the comment and postingaccount of the 1st split booking for the main booking if
		// nothing is specified
		if (!moneyflowSplitEntries.isEmpty()) {
			final MoneyflowSplitEntry moneyflowSplitEntry = moneyflowSplitEntries.iterator().next();

			if (moneyflow.getComment() == null || moneyflow.getComment().trim().isEmpty()) {
				moneyflow.setComment(moneyflowSplitEntry.getComment());
			}

			if (moneyflow.getPostingAccount() == null) {
				moneyflow.setPostingAccount(moneyflowSplitEntry.getPostingAccount());
			}
		}
	}

	/**
	 * Updates the given Moneyflow
	 *
	 * @param request
	 *            The Request object which contains the Moneyflow.
	 * @return Validation Response
	 */
	@RequestMapping(value = "updateMoneyflow", method = { RequestMethod.PUT })
	@RequiresAuthorization
	public ValidationResponse updateMoneyflow(@RequestBody final UpdateMoneyflowRequest request) {
		final UserID userId = super.getUserId();
		final User user = this.userService.getUserById(userId);
		final Group group = this.accessRelationService.getAccessor(userId);

		final List<MoneyflowSplitEntry> updateMoneyflowSplitEntries = super.mapList(
				request.getUpdateMoneyflowSplitEntryTransports(), MoneyflowSplitEntry.class);
		final List<MoneyflowSplitEntry> insertMoneyflowSplitEntries = super.mapList(
				request.getInsertMoneyflowSplitEntryTransports(), MoneyflowSplitEntry.class);
		List<MoneyflowSplitEntryID> deleteMoneyflowSplitEntryIds = null;
		if (request.getDeleteMoneyflowSplitEntryIds() != null) {
			deleteMoneyflowSplitEntryIds = request.getDeleteMoneyflowSplitEntryIds().stream()
					.map(MoneyflowSplitEntryID::new).collect(Collectors.toCollection(ArrayList::new));
		}
		final Moneyflow moneyflow = super.map(request.getMoneyflowTransport(), Moneyflow.class);
		moneyflow.setUser(user);
		moneyflow.setGroup(group);

		// build a List of all MoneyflowSplitEntries which will be there after his update
		final List<MoneyflowSplitEntry> moneyflowSplitEntries = this.moneyflowSplitEntryService
				.getMoneyflowSplitEntries(userId, moneyflow.getId());
		final ListIterator<MoneyflowSplitEntry> entryIterator = moneyflowSplitEntries.listIterator();
		while (entryIterator.hasNext()) {
			final MoneyflowSplitEntry entry = entryIterator.next();
			if (deleteMoneyflowSplitEntryIds != null && deleteMoneyflowSplitEntryIds.contains(entry.getId())) {
				entryIterator.remove();
			} else {
				final MoneyflowSplitEntry matchingUpdateEntry = updateMoneyflowSplitEntries.stream()
						.filter(mse -> mse.getId().equals(entry.getId())).findAny().orElse(null);
				if (matchingUpdateEntry != null) {
					entryIterator.set(matchingUpdateEntry);
				}
			}
		}

		moneyflowSplitEntries.addAll(insertMoneyflowSplitEntries);

		this.prepareForValidityCheck(moneyflow, moneyflowSplitEntries);

		final MoneyflowID moneyflowId = moneyflow.getId();
		final Moneyflow moneyflowById = this.moneyflowService.getMoneyflowById(userId, moneyflowId);

		// only the creator of a moneyflow may edit it!
		if (moneyflowById != null && moneyflowById.getUser().equals(user)) {

			final ValidationResult validationResult = this.moneyflowService.validateMoneyflow(moneyflow);

			if (validationResult.isValid()) {

				updateMoneyflowSplitEntries.forEach(mse -> {
					mse.setMoneyflowId(moneyflowId);
					validationResult
							.mergeValidationResult(this.moneyflowSplitEntryService.validateMoneyflowSplitEntry(mse));
				});

				insertMoneyflowSplitEntries.forEach(mse -> {
					mse.setMoneyflowId(moneyflowId);
					validationResult
							.mergeValidationResult(this.moneyflowSplitEntryService.validateMoneyflowSplitEntry(mse));
				});

				if (validationResult.isValid()) {

					validationResult.mergeValidationResult(this.checkIfAmountIsEqual(moneyflow, moneyflowSplitEntries));

					if (validationResult.isValid()) {
						if (deleteMoneyflowSplitEntryIds != null) {
							deleteMoneyflowSplitEntryIds.forEach(mseId -> this.moneyflowSplitEntryService
									.deleteMoneyflowSplitEntry(userId, moneyflowId, mseId));
						}

						updateMoneyflowSplitEntries
								.forEach(mse -> this.moneyflowSplitEntryService.updateMoneyflowSplitEntry(userId, mse));

						if (!insertMoneyflowSplitEntries.isEmpty()) {
							this.moneyflowSplitEntryService.createMoneyflowSplitEntries(userId,
									insertMoneyflowSplitEntries);
						}

						this.moneyflowService.updateMoneyflow(moneyflow);
					}
				}
			}

			if (!validationResult.isValid()) {
				return super.returnValidationResponse(validationResult);
			}
		}

		return null;
	}

	private ValidationResult checkIfAmountIsEqual(final Moneyflow moneyflow,
			final List<MoneyflowSplitEntry> moneyflowSplitEntries) {
		final ValidationResult validationResult = new ValidationResult();

		if (!moneyflowSplitEntries.isEmpty()) {
			final BigDecimal sumOfSplitEntriesAmount = moneyflowSplitEntries.stream()
					.map(MoneyflowSplitEntry::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

			if (sumOfSplitEntriesAmount.compareTo(moneyflow.getAmount()) != 0) {
				validationResult.addValidationResultItem(new ValidationResultItem(moneyflow.getId(),
						ErrorCode.SPLIT_ENTRIES_AMOUNT_IS_NOT_EQUALS_MONEYFLOW_AMOUNT));
			}
		}

		return validationResult;
	}

	/**
	 * Deletes the specified Moneyflow.
	 *
	 * @param id
	 *            The ID of the Moneyflow to delete
	 */
	@RequestMapping(value = "deleteMoneyflowById/{id}", method = { RequestMethod.DELETE })
	@RequiresAuthorization
	public void deleteMoneyflowById(@PathVariable(value = "id") final Long id) {
		final UserID userId = super.getUserId();
		final MoneyflowID moneyflowId = new MoneyflowID(id);
		this.moneyflowSplitEntryService.deleteMoneyflowSplitEntries(userId, moneyflowId);
		this.moneyflowReceiptService.deleteMoneyflowReceipt(userId, moneyflowId);
		this.moneyflowService.deleteMoneyflow(userId, moneyflowId);
	}

	/**
	 * Searches for Moneyflows given by an absolut amount and a date range.
	 *
	 * @param amount
	 *            ABS amount
	 * @param dateFromStr
	 *            date to start searching (format: YYYYMMDD)
	 * @param dateTilStr
	 *            date to end searching (format: YYYYMMDD)
	 * @return matching Moneyflows
	 */
	@RequestMapping(value = "searchMoneyflowsByAmount/{amount}/{dateFromStr}/{dateTilStr}", method = {
			RequestMethod.GET })
	@RequiresAuthorization
	public SearchMoneyflowsByAmountResponse searchMoneyflowsByAmount(
			@PathVariable(value = "amount") final BigDecimal amount,
			@PathVariable(value = "dateFromStr") final String dateFromStr,
			@PathVariable(value = "dateTilStr") final String dateTilStr) {
		final UserID userId = super.getUserId();
		final SearchMoneyflowsByAmountResponse response = new SearchMoneyflowsByAmountResponse();
		final LocalDate dateFrom = LocalDate.parse(dateFromStr, SEARCH_DATE_FORMATTER);
		final LocalDate dateTil = LocalDate.parse(dateTilStr, SEARCH_DATE_FORMATTER);

		final List<Moneyflow> moneyflows = this.moneyflowService.searchMoneyflowsByAbsoluteAmountDate(userId, amount,
				dateFrom, dateTil);
		if (moneyflows != null && !moneyflows.isEmpty()) {
			final List<Moneyflow> relevantMoneyflows = moneyflows.stream()
					.filter(mf -> !mf.isPrivat() || mf.getUser().getId().equals(userId))
					.collect(Collectors.toCollection(ArrayList::new));

			if (relevantMoneyflows != null && !relevantMoneyflows.isEmpty()) {
				final List<MoneyflowID> relevantMoneyflowIds = relevantMoneyflows.stream().map(Moneyflow::getId)
						.collect(Collectors.toCollection(ArrayList::new));

				final Map<MoneyflowID, List<MoneyflowSplitEntry>> moneyflowSplitEntries = this.moneyflowSplitEntryService
						.getMoneyflowSplitEntries(userId, relevantMoneyflowIds);

				final List<MoneyflowTransport> moneyflowTransports = relevantMoneyflows.stream()
						.map(mf -> super.map(mf, MoneyflowTransport.class))
						.collect(Collectors.toCollection(ArrayList::new));

				response.setMoneyflowTransports(moneyflowTransports);

				if (!moneyflowSplitEntries.isEmpty()) {
					final ArrayList<MoneyflowSplitEntry> moneyflowSplitEntryList = moneyflowSplitEntries.values()
							.stream().flatMap(List::stream).collect(Collectors.toCollection(ArrayList::new));

					response.setMoneyflowSplitEntryTransports(
							super.mapList(moneyflowSplitEntryList, MoneyflowSplitEntryTransport.class));
				}

				return response;
			}
		}

		return null;

	}
}


text:
package org.eclipse.emf.cdo.internal.common.model;

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

import org.eclipse.emf.cdo.common.branch.CDOBranchPoint;
import org.eclipse.emf.cdo.common.model.CDOModelUtil;
import org.eclipse.emf.cdo.common.model.CDOPackageInfo;
import org.eclipse.emf.cdo.common.model.CDOPackageUnit;
import org.eclipse.emf.cdo.common.model.CDOPackageUnit.State;
import org.eclipse.emf.cdo.internal.common.bundle.OM;
import org.eclipse.emf.cdo.internal.common.messages.Messages;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EPackageRegistryImpl;
import org.eclipse.net4j.util.CheckUtil;
import org.eclipse.net4j.util.ImplementationError;
import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
import org.eclipse.net4j.util.event.EventUtil;
import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.lifecycle.LifecycleException;
import org.eclipse.net4j.util.lifecycle.LifecycleState;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.trace.ContextTracer;

/**
 * @author Eike Stepper
 */
public class CDOPackageRegistryImpl extends EPackageRegistryImpl implements InternalCDOPackageRegistry
{
  private static final long serialVersionUID = 1L;

  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CDOPackageRegistryImpl.class);

  private static final boolean eagerInternalCaches = false;

  private boolean replacingDescriptors;

  private PackageProcessor packageProcessor;

  private PackageLoader packageLoader;

  private transient boolean active;

  @ExcludeFromDump
  private transient InternalCDOPackageInfo[] packageInfos;

  @ExcludeFromDump
  private transient InternalCDOPackageUnit[] packageUnits;

  @ExcludeFromDump
  private transient Map<EClass, List<EClass>> subTypes;

  private Map<Enumerator, EEnumLiteral> enumLiterals = new HashMap<Enumerator, EEnumLiteral>();

  private Set<CDOPackageInfo> visitedPackages = new HashSet<CDOPackageInfo>();

  private Map<EPackage, InternalCDOPackageInfo> packageInfoMap = new HashMap<EPackage, InternalCDOPackageInfo>();

  public CDOPackageRegistryImpl()
  {
  }

  public boolean isReplacingDescriptors()
  {
    return replacingDescriptors;
  }

  public void setReplacingDescriptors(boolean replacingDescriptors)
  {
    this.replacingDescriptors = replacingDescriptors;
  }

  public PackageProcessor getPackageProcessor()
  {
    return packageProcessor;
  }

  public void setPackageProcessor(PackageProcessor packageProcessor)
  {
    this.packageProcessor = packageProcessor;
  }

  public PackageLoader getPackageLoader()
  {
    return packageLoader;
  }

  public void setPackageLoader(PackageLoader packageLoader)
  {
    LifecycleUtil.checkInactive(this);
    this.packageLoader = packageLoader;
  }

  static int lockCount;

  @Override
  public Object get(Object key)
  {
    LifecycleUtil.checkActive(this);
    return super.get(key);
  }

  public synchronized Set<String> getAllKeys()
  {
    LifecycleUtil.checkActive(this);
    Set<String> result = new HashSet<String>();
    result.addAll(keySet());
    if (delegateRegistry != null)
    {
      if (delegateRegistry instanceof InternalCDOPackageRegistry)
      {
        result.addAll(((InternalCDOPackageRegistry)delegateRegistry).getAllKeys());
      }
      else
      {
        result.addAll(delegateRegistry.keySet());
      }
    }

    return result;
  }

  public synchronized Object getWithDelegation(String nsURI, boolean resolve)
  {
    LifecycleUtil.checkActive(this);
    Object result = getFrom(this, nsURI, resolve);
    if (result == null && delegateRegistry != null)
    {
      result = getFrom(delegateRegistry, nsURI, resolve);
    }

    return result;
  }

  private static Object getFrom(EPackage.Registry registry, String nsURI, boolean resolve)
  {
    if (resolve)
    {
      return registry.getEPackage(nsURI);
    }

    return registry.get(nsURI);
  }

  public synchronized Object basicPut(String nsURI, Object value)
  {
    LifecycleUtil.checkActive(this);
    if (TRACER.isEnabled())
    {
      TRACER.format("Registering {0} --> {1}", nsURI, value); //$NON-NLS-1$
    }

    if (packageProcessor != null)
    {
      value = packageProcessor.processPackage(value);
    }

    Object oldValue = get(nsURI);
    if (oldValue instanceof InternalCDOPackageInfo && value instanceof EPackage)
    {
      InternalCDOPackageInfo oldPackageInfo = (InternalCDOPackageInfo)oldValue;
      EPackage newValue = (EPackage)value;
      if (oldPackageInfo.getEPackage(false) == null)
      {
    	registerPackageInfo(newValue, oldPackageInfo);
        oldPackageInfo.getPackageUnit().setState(CDOPackageUnit.State.LOADED);
      }
    }
    else if (oldValue instanceof EPackage && value instanceof InternalCDOPackageInfo)
    {
      EPackage oldPackage = (EPackage)oldValue;
      InternalCDOPackageInfo oldPackageInfo = getPackageInfo(oldPackage);
      InternalCDOPackageInfo newPackageInfo = (InternalCDOPackageInfo)value;

      InternalCDOPackageUnit oldPackageUnit = oldPackageInfo.getPackageUnit();
      InternalCDOPackageUnit newPackageUnit = newPackageInfo.getPackageUnit();
      if (oldPackageUnit.getState() == CDOPackageUnit.State.NEW
          && newPackageUnit.getState() != CDOPackageUnit.State.NEW)
      {
        oldPackageUnit.setState(CDOPackageUnit.State.LOADED);
      }

      // Keep old value!
      return null;
    }

    return super.put(nsURI, value);
  }

  @Override
  public synchronized Object put(String nsURI, Object value)
  {
    LifecycleUtil.checkActive(this);
    if (replacingDescriptors && value instanceof EPackage.Descriptor)
    {
      EPackage.Descriptor descriptor = (EPackage.Descriptor)value;
      value = descriptor.getEPackage();
    }

    if (value instanceof EPackage)
    {
      EPackage ePackage = (EPackage)value;
      InternalCDOPackageInfo packageInfo = getPackageInfo(ePackage);
      if (packageInfo == null)
      {
        initPackageUnit(ePackage);
        return null;
      }
    }

    return basicPut(nsURI, value);
  }

  public synchronized Object putEPackage(EPackage ePackage)
  {
    LifecycleUtil.checkActive(this);
    return put(ePackage.getNsURI(), ePackage);
  }

  public synchronized void putPackageUnit(InternalCDOPackageUnit packageUnit)
  {
    LifecycleUtil.checkActive(this);
    packageUnit.setPackageRegistry(this);
    for (InternalCDOPackageInfo packageInfo : packageUnit.getPackageInfos())
    {
      EPackage ePackage = packageInfo.getEPackage(false);
      if (ePackage != null)
      {
    	registerPackageInfo(ePackage, packageInfo);
        basicPut(ePackage.getNsURI(), ePackage);
      }
      else
      {
        basicPut(packageInfo.getPackageURI(), packageInfo);
      }
    }

    resetInternalCaches();
  }

  public synchronized void putPackageUnits(InternalCDOPackageUnit[] packageUnits, State state)
  {
    LifecycleUtil.checkActive(this);
    for (InternalCDOPackageUnit packageUnit : packageUnits)
    {
      if (state != null)
      {
        packageUnit.setState(state);
      }

      putPackageUnit(packageUnit);
    }
  }

  public synchronized void registerPackageInfo(EPackage ePackage, InternalCDOPackageInfo packageInfo)
  {
	packageInfo.setEPackage(ePackage);
    packageInfoMap.put(ePackage, packageInfo);
  }

  public synchronized InternalCDOPackageInfo getPackageInfo(EPackage ePackage)
  {
    LifecycleUtil.checkActive(this);

    // Looks up a package descriptor in the registry
    Object object = get(ePackage.getNsURI());
    if (object instanceof InternalCDOPackageInfo)
    {
      InternalCDOPackageInfo packageInfo = (InternalCDOPackageInfo)object;
      if (packageInfo.getPackageUnit().getPackageRegistry() == this)
      {
        return packageInfo;
      }
    }

    // Looks up a package info in the packageInfoMap
    return packageInfoMap.get(ePackage);
  }

  public synchronized InternalCDOPackageInfo[] getPackageInfos()
  {
    LifecycleUtil.checkActive(this);
    if (packageInfos == null)
    {
      List<InternalCDOPackageInfo> result = new ArrayList<InternalCDOPackageInfo>();
      for (Object value : values())
      {
        if (value instanceof InternalCDOPackageInfo)
        {
          result.add((InternalCDOPackageInfo)value);
        }
        else if (value instanceof EPackage)
        {
          InternalCDOPackageInfo packageInfo = getPackageInfo((EPackage)value);
          if (packageInfo != null)
          {
            result.add(packageInfo);
          }
        }
      }

      packageInfos = result.toArray(new InternalCDOPackageInfo[result.size()]);
      Arrays.sort(packageInfos);
    }

    return packageInfos;
  }

  public synchronized InternalCDOPackageUnit getPackageUnit(EPackage ePackage)
  {
    LifecycleUtil.checkActive(this);
    CDOPackageInfo packageInfo = getPackageInfo(ePackage);
    if (packageInfo == null)
    {
      putEPackage(ePackage);
      packageInfo = getPackageInfo(ePackage);
      if (packageInfo == null)
      {
        throw new ImplementationError(MessageFormat.format(Messages.getString("CDOPackageRegistryImpl.0"), ePackage)); //$NON-NLS-1$
      }
    }

    return (InternalCDOPackageUnit)packageInfo.getPackageUnit();
  }

  public synchronized InternalCDOPackageUnit getPackageUnit(String id)
  {
    LifecycleUtil.checkActive(this);
    for (Object value : values())
    {
      InternalCDOPackageUnit packageUnit = null;
      if (value instanceof InternalCDOPackageInfo)
      {
        packageUnit = ((InternalCDOPackageInfo)value).getPackageUnit();
      }
      else if (value instanceof EPackage)
      {
        InternalCDOPackageInfo packageInfo = getPackageInfo((EPackage)value);
        if (packageInfo != null)
        {
          packageUnit = packageInfo.getPackageUnit();
        }
      }

      if (packageUnit != null && id.equals(packageUnit.getID()))
      {
        return packageUnit;
      }
    }

    return null;
  }

  public synchronized InternalCDOPackageUnit[] getPackageUnits(long startTime, long endTime)
  {
    LifecycleUtil.checkActive(this);
    if (endTime == CDOBranchPoint.UNSPECIFIED_DATE)
    {
      endTime = Long.MAX_VALUE;
    }

    Set<InternalCDOPackageUnit> result = new HashSet<InternalCDOPackageUnit>();
    for (Object value : values())
    {
      InternalCDOPackageUnit packageUnit = null;
      if (value instanceof InternalCDOPackageInfo)
      {
        packageUnit = ((InternalCDOPackageInfo)value).getPackageUnit();
      }
      else if (value instanceof EPackage)
      {
        InternalCDOPackageInfo packageInfo = getPackageInfo((EPackage)value);
        if (packageInfo != null)
        {
          packageUnit = packageInfo.getPackageUnit();
        }
      }

      if (packageUnit != null)
      {
        long timeStamp = packageUnit.getTimeStamp();
        if (startTime <= timeStamp && timeStamp <= endTime)
        {
          result.add(packageUnit);
        }
      }
    }

    return result.toArray(new InternalCDOPackageUnit[result.size()]);
  }

  public synchronized InternalCDOPackageUnit[] getPackageUnits(boolean withSystemPackages)
  {
    LifecycleUtil.checkActive(this);
    return collectPackageUnits(withSystemPackages);
  }

  public synchronized InternalCDOPackageUnit[] getPackageUnits()
  {
    LifecycleUtil.checkActive(this);
    if (packageUnits == null)
    {
      packageUnits = collectPackageUnits(true);
      Arrays.sort(packageUnits);
    }

    return packageUnits;
  }

  private InternalCDOPackageUnit[] collectPackageUnits(boolean withSystemPackages)
  {
    Set<InternalCDOPackageUnit> result = new HashSet<InternalCDOPackageUnit>();
    for (Object value : values())
    {
      InternalCDOPackageUnit packageUnit = collectPackageUnit(value);
      if (packageUnit != null && (withSystemPackages || !packageUnit.isSystem()))
      {
        result.add(packageUnit);
      }
    }

    return result.toArray(new InternalCDOPackageUnit[result.size()]);
  }

  private InternalCDOPackageUnit collectPackageUnit(Object value)
  {
    if (value instanceof InternalCDOPackageInfo)
    {
      return ((InternalCDOPackageInfo)value).getPackageUnit();
    }

    if (value instanceof EPackage)
    {
      InternalCDOPackageInfo packageInfo = getPackageInfo((EPackage)value);
      if (packageInfo != null)
      {
        InternalCDOPackageUnit packageUnit = packageInfo.getPackageUnit();
        return packageUnit;
      }
    }

    return null;
  }

  public synchronized EPackage[] getEPackages()
  {
    LifecycleUtil.checkActive(this);
    List<EPackage> result = new ArrayList<EPackage>();
    for (String packageURI : keySet())
    {
      EPackage ePackage = getEPackage(packageURI);
      if (ePackage != null)
      {
        result.add(ePackage);
      }
    }

    return result.toArray(new EPackage[result.size()]);
  }

  public synchronized EEnumLiteral getEnumLiteralFor(Enumerator value)
  {
    LifecycleUtil.checkActive(this);
    EEnumLiteral result = enumLiterals.get(value);
    if (result != null)
    {
      return result;
    }

    for (CDOPackageUnit packageUnit : getPackageUnits())
    {
      for (CDOPackageInfo packageInfo : packageUnit.getPackageInfos())
      {
        if (visitedPackages.add(packageInfo))
        {
          result = visitPackage(packageInfo, value);
          if (result != null)
          {
            return result;
          }
        }
      }
    }

    return null;
  }

  private EEnumLiteral visitPackage(CDOPackageInfo packageInfo, Enumerator value)
  {
    EEnumLiteral result = null;
    for (EClassifier classifier : packageInfo.getEPackage().getEClassifiers())
    {
      if (classifier instanceof EEnum)
      {
        EEnum eenum = (EEnum)classifier;
        for (EEnumLiteral eEnumLiteral : eenum.getELiterals())
        {
          Enumerator instance = eEnumLiteral.getInstance();
          enumLiterals.put(instance, eEnumLiteral);
          if (instance == value)
          {
            result = eEnumLiteral;
          }
        }
      }
    }

    return result;
  }

  public synchronized Map<EClass, List<EClass>> getSubTypes()
  {
    LifecycleUtil.checkActive(this);
    if (subTypes == null)
    {
      subTypes = CDOModelUtil.getSubTypes(this);
    }

    return subTypes;
  }

  @Override
  public String toString()
  {
    return MessageFormat.format("{0}[packageLoader={1}]", getClass().getSimpleName(), getPackageLoader()); //$NON-NLS-1$
  }

  public void addListener(IListener listener)
  {
    // Do nothing
  }

  public void removeListener(IListener listener)
  {
    // Do nothing
  }

  public IListener[] getListeners()
  {
    return EventUtil.NO_LISTENERS;
  }

  public boolean hasListeners()
  {
    return false;
  }

  public synchronized boolean isActive()
  {
    return active;
  }

  public synchronized LifecycleState getLifecycleState()
  {
    return active ? LifecycleState.ACTIVE : LifecycleState.INACTIVE;
  }

  public synchronized void activate() throws LifecycleException
  {
    if (!active)
    {
      CheckUtil.checkState(packageLoader, "packageLoader"); //$NON-NLS-1$
      active = true;
    }
  }

  public synchronized Exception deactivate()
  {
    if (active)
    {
      try
      {
    	packageInfoMap.clear();
        disposePackageUnits();
        clear();
        active = false;
      }
      catch (RuntimeException ex)
      {
        return ex;
      }
    }

    return null;
  }

  protected void disposePackageUnits()
  {
    for (InternalCDOPackageUnit packageUnit : getPackageUnits())
    {
      packageUnit.dispose();
    }

    packageInfos = null;
    packageUnits = null;
    subTypes = null;
  }

  protected void initPackageUnit(EPackage ePackage)
  {
    InternalCDOPackageUnit packageUnit = createPackageUnit();
    packageUnit.init(ePackage);
    resetInternalCaches();
  }

  protected void resetInternalCaches()
  {
    packageInfos = null;
    packageUnits = null;
    subTypes = null;
    if (eagerInternalCaches)
    {
      getPackageInfos();
      getPackageUnits();
      getSubTypes();
    }
  }

  public InternalCDOPackageUnit createPackageUnit()
  {
    InternalCDOPackageUnit packageUnit = (InternalCDOPackageUnit)CDOModelUtil.createPackageUnit();
    packageUnit.setPackageRegistry(this);
    return packageUnit;
  }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Crime_Management_System.io {

    public partial class WebForm1 {

        /// <summary>
        /// name control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label name;

        /// <summary>
        /// gvOfficerAssignedCases control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView gvOfficerAssignedCases;

        /// <summary>
        /// tbCaseID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox tbCaseID;

        /// <summary>
        /// tbDate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox tbDate;

        /// <summary>
        /// tbExpenditure control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox tbExpenditure;

        /// <summary>
        /// tbProgress control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox tbProgress;

        /// <summary>
        /// cbCaseCompleted control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox cbCaseCompleted;

        /// <summary>
        /// btnSubmit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnSubmit;
    }
}


text:
var express       = require('express');
var path          = require('path');
var favicon       = require('static-favicon');
var logger        = require('morgan');
var cookieParser  = require('cookie-parser');
var bodyParser    = require('body-parser');
var expressHbs    = require('express3-handlebars');
var fs            = require('fs');
var tokenAuth     = require('./middleware/tokenAuth');
var ssd           = require('./app/staleSessionDestroyer');

var app           = express();

app.engine('.html', expressHbs({
    extname      : '.html',
    defaultLayout: 'main',
    layoutsDir   : 'views/layouts'
}));

app.set('view engine', '.html');

// view engine setup
app.set('views', path.join(__dirname, 'views'));

var config = JSON.parse(fs.readFileSync("./config/api.json", 'utf8'));

app.set('config', config);

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/',                    require('./routes/index'));

// API
app.all('/api/*',                   [bodyParser.json(), tokenAuth]);

app.use('/api/v1/plugins',          require('./routes/api/plugins'));
app.use('/api/v1/logs',             require('./routes/api/logger'));
app.use('/api/v1/autocomplete',     require('./routes/api/autocomplete'));
app.use('/api/v1/notes',            require('./routes/api/note'));
app.use('/api/v1/accounts',         require('./routes/api/account'));
app.use('/api/v1/accounts/avatar',  require('./routes/api/avatar'));
app.use('/api/v1/session',          require('./routes/api/session'));

// Not API
app.use('/plugins',             require('./routes/plugins'));
app.use('/accounts',            require('./routes/accounts'));
app.use('/session',             require('./routes/session'));
app.use('/logs',                require('./routes/logs'));

process.on('error', function (e) {
    console.log(e.stack);
});

// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found!');
    err.status = 404;
    next(err);
});

// error handlers

/*
process.stderr.on('data', function(data) {
    console.log(data);
});*/

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        console.log('err: ', err);

        if (err.status === 400) {
            res.status(400).json({
                status : "ERROR",
                message: err.message
            });
        } else {
            next();
        }
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    if (err.status !== 400) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    }
});

module.exports = app;


text:
<?php

class Mage_Sales_Model_Entity_Order_Invoice_Attribute_Backend_Item
    extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
    public function afterSave($object)
    {
        if ($object->getOrderItem()) {
            $object->getOrderItem()->save();
        }
        return parent::beforeSave($object);
    }
}


text: ton-social is a site!


text:
<?php

namespace Steelbot\TelegramBotApi\Method;

use Steelbot\TelegramBotApi\Type\File;

class GetFile extends AbstractMethod
{
    /**
     * @var string
     */
    protected $fileId;

    public function __construct(string $fileId)
    {
        $this->fileId = $fileId;
    }

    /**
     * @return string
     */
    public function getFileId(): string
    {
        return $this->fileId;
    }

    /**
     * @param string $fileId
     */
    public function setFileId(string $fileId)
    {
        $this->fileId = $fileId;
    }

    /**
     * Get method name.
     *
     * @return string
     */
    public function getMethodName(): string
    {
        return 'getFile';
    }

    /**
     * HTTP method
     *
     * @return string
     */
    public function getHttpMethod(): string
    {
        return self::HTTP_GET;
    }

    /**
     * Get parameters for HTTP query.
     *
     * @return mixed
     */
    public function getParams(): array
    {
        return [
            'file_id' => $this->fileId
        ];
    }

    /**
     * Build result type from array of data.
     *
     * @param array $result
     *
     * @return object
     */
    public function buildResult($result): File
    {
        $file = new File($result);

        return $file;
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/dlp.proto

namespace Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Result of the numerical stats computation.
 *
 * Generated from protobuf message google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.NumericalStatsResult
 */
class NumericalStatsResult extends \Google\Protobuf\Internal\Message
{
    /**
     * Minimum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value min_value = 1;
     */
    private $min_value = null;
    /**
     * Maximum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value max_value = 2;
     */
    private $max_value = null;
    /**
     * List of 99 values that partition the set of field values into 100 equal
     * sized buckets.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.Value quantile_values = 4;
     */
    private $quantile_values;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Dlp\V2\Value $min_value
     *           Minimum value appearing in the column.
     *     @type \Google\Cloud\Dlp\V2\Value $max_value
     *           Maximum value appearing in the column.
     *     @type \Google\Cloud\Dlp\V2\Value[]|\Google\Protobuf\Internal\RepeatedField $quantile_values
     *           List of 99 values that partition the set of field values into 100 equal
     *           sized buckets.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Privacy\Dlp\V2\Dlp::initOnce();
        parent::__construct($data);
    }

    /**
     * Minimum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value min_value = 1;
     * @return \Google\Cloud\Dlp\V2\Value|null
     */
    public function getMinValue()
    {
        return $this->min_value;
    }

    public function hasMinValue()
    {
        return isset($this->min_value);
    }

    public function clearMinValue()
    {
        unset($this->min_value);
    }

    /**
     * Minimum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value min_value = 1;
     * @param \Google\Cloud\Dlp\V2\Value $var
     * @return $this
     */
    public function setMinValue($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\Value::class);
        $this->min_value = $var;

        return $this;
    }

    /**
     * Maximum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value max_value = 2;
     * @return \Google\Cloud\Dlp\V2\Value|null
     */
    public function getMaxValue()
    {
        return $this->max_value;
    }

    public function hasMaxValue()
    {
        return isset($this->max_value);
    }

    public function clearMaxValue()
    {
        unset($this->max_value);
    }

    /**
     * Maximum value appearing in the column.
     *
     * Generated from protobuf field .google.privacy.dlp.v2.Value max_value = 2;
     * @param \Google\Cloud\Dlp\V2\Value $var
     * @return $this
     */
    public function setMaxValue($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\Value::class);
        $this->max_value = $var;

        return $this;
    }

    /**
     * List of 99 values that partition the set of field values into 100 equal
     * sized buckets.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.Value quantile_values = 4;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getQuantileValues()
    {
        return $this->quantile_values;
    }

    /**
     * List of 99 values that partition the set of field values into 100 equal
     * sized buckets.
     *
     * Generated from protobuf field repeated .google.privacy.dlp.v2.Value quantile_values = 4;
     * @param \Google\Cloud\Dlp\V2\Value[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setQuantileValues($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Dlp\V2\Value::class);
        $this->quantile_values = $arr;

        return $this;
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(NumericalStatsResult::class, \Google\Cloud\Dlp\V2\AnalyzeDataSourceRiskDetails_NumericalStatsResult::class);


text:
namespace Shuttle.Esb
{
    public interface IWorkQueueConfiguration : IThreadCount
    {
        IQueue WorkQueue { get; set; }
        string WorkQueueUri { get; }
    }
}


text:
angular.module('ionicApp', ['ionic'])

.directive('fakeStatusbar', function () {
  return {
    restrict: 'E',
    replace: true,
    template: '

Carrier

3:30 PM

50%

'
  };
})

.directive('headerShrink', function ($document) {
  var fadeAmt;

  var shrink = function (header, content, amt, max) {
    amt = Math.min(44, amt);
    fadeAmt = 1 - amt / 44;
    ionic.requestAnimationFrame(function () {
      header.style[ionic.CSS.TRANSFORM] = 'translate3d(0, -' + amt + 'px, 0)';
      for (var i = 0, j = header.children.length; i < j; i++) {
        header.children[i].style.opacity = fadeAmt;
      }
    });
  };

  return {
    restrict: 'A',
    link: function ($scope, $element, $attr) {
      var starty = $scope.$eval($attr.headerShrink) || 0;
      var shrinkAmt;

      var header = $document[0].body.querySelector('.bar-header');
      var headerHeight = header.offsetHeight;

      $element.bind('scroll', function (e) {
        if (e.detail.scrollTop > starty) {
          // Start shrinking
          shrinkAmt = headerHeight - Math.max(0, (starty + headerHeight) - e.detail.scrollTop);
          shrink(header, $element[0], shrinkAmt, headerHeight);
        } else {
          shrink(header, $element[0], 0, headerHeight);
        }
      });
    }
  };
});


text:
module QiniuDirectUploader
  class Engine < ::Rails::Engine
  end
end


text:
<!DOCTYPE html>

  <title>DES exposure checker | Hodge-podge</title>
  <link rel="stylesheet" media="screen" href="assets/bootstrap/css/bootstrap.min.css" type="text/css" charset="utf-8">
  <link rel="stylesheet" media="screen" href="assets/eyeball.css" type="text/css" charset="utf-8">
  <meta charset="utf-8">
  <meta name="author" content="Peter Melchior, Erin Sheldon">
  <link rel="icon" href="assets/DES_logo_trans.png" type="image/png">

	DES exposure checker

Viewer

Tutorial

FAQ

Statistics

API

Gallery

Hodge-podge

Hodge-podgeor: the things called "Other..."

We make every attempt at providing categories for all problem cases we know of.
      However, if we learned one thing from this website, it's that many things can go wrong in many ways.
      It is therefore not unexpected that unknown problems surface or that previously corrected problems
      reappear after a change in the DESDM pipelines. These are the kinds of problems we collect under
      the catch-all category Other..., where you can and should provide a short descriptive explanation
      of what you found weird in any given image.

But your reports only becomes useful if we can find patterns or re-occurrances
      of such problems in the data. Think of an unexpected failure mode. To make it easier to find such cases,
      we ask you to see what problems have been marked by yourself and other users. Below you'll find the
      list of problems labelled as Other..., ordered by how many images show this problem.
      You can click on the link and get to an example image. If you find the same problem
      again, you can help us identify that failure mode by using the same description text that is already in use.

At the moment, we ask you to copy the description from this page to the viewer, but a more elegant approach
      is in the works.

What's in the bag

Do you need help?

Always. Consolidating the descriptions is not difficult, but it requires some familiarity with the
    set of known problems (as we list them in our Turorial) and judgement to decide
    if two or more descriptions actually refer to one problem.

If that sounds like a job for you, please contact us.

Created by Peter Melchior, Erin Sheldon, Alex Drlica-Wagner


text:
import ReactIcon from './ReactIcon';

export default ReactIcon;