text:
<?php

namespace Magento\Braintree\Controller\Adminhtml\Order;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Message\MessageInterface;
use Magento\Payment\Model\Method\Adapter;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\TestFramework\TestCase\AbstractBackendController;

/**
 * Class PaymentReviewTest
 */
class PaymentReviewTest extends AbstractBackendController
{
    /**
     * @var Order
     */
    private $order;

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    protected function setUp()
    {
        parent::setUp();

        /** @var FilterBuilder $filterBuilder */
        $filterBuilder = $this->_objectManager->get(FilterBuilder::class);
        $filters = [
            $filterBuilder->setField(OrderInterface::INCREMENT_ID)
                ->setValue('100000002')
                ->create()
        ];

        /** @var SearchCriteriaBuilder $searchCriteriaBuilder */
        $searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class);
        $searchCriteria = $searchCriteriaBuilder->addFilters($filters)
            ->create();

        $this->orderRepository = $this->_objectManager->get(OrderRepositoryInterface::class);
        $orders = $this->orderRepository->getList($searchCriteria)
            ->getItems();
        /** @var OrderInterface $order */
        $this->order = array_pop($orders);
    }

    /**
     * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute
     * @magentoDataFixture Magento/Braintree/_files/fraud_order.php
     * @magentoAppArea adminhtml
     */
    public function testExecuteAccept()
    {
        $orderId = $this->order->getEntityId();
        $this->dispatch('backend/sales/order/reviewPayment/action/accept/order_id/' . $orderId);

        static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId));
        static::assertSessionMessages(
            static::equalTo(['The payment has been accepted.']),
            MessageInterface::TYPE_SUCCESS
        );

        $order = $this->orderRepository->get($orderId);
        static::assertEquals(Order::STATE_PROCESSING, $order->getState());
        static::assertEquals(Order::STATE_PROCESSING, $order->getStatus());
    }

    /**
     * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute
     * @magentoDataFixture Magento/Braintree/_files/fraud_order.php
     * @magentoAppArea adminhtml
     */
    public function testExecuteDeny()
    {
        $orderId = $this->order->getEntityId();
        $payment = $this->order->getPayment();

        $adapter = $this->getMockBuilder(Adapter::class)
            ->disableOriginalConstructor()
            ->setMethods(['denyPayment'])
            ->getMock();
        // uses the mock instead a real adapter to avoid api calls to Braintree gateway
        $payment->setMethodInstance($adapter);
        $this->orderRepository->save($this->order);

        $adapter->expects(static::once())
            ->method('denyPayment')
            ->with($payment)
            ->willReturn(true);

        $this->dispatch('backend/sales/order/reviewPayment/action/deny/order_id/' . $orderId);

        static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId));
        static::assertSessionMessages(
            static::equalTo(['The payment has been denied.']),
            MessageInterface::TYPE_SUCCESS
        );

        $order = $this->orderRepository->get($orderId);
        static::assertEquals(Order::STATE_CANCELED, $order->getState());
        static::assertEquals(Order::STATE_CANCELED, $order->getStatus());
    }
}


text: sudo python3 -m pip install --upgrade timezonefinder pytz 'apache-beam[gcp]'

redpajama_set_name: RedPajamaGithub


text: {{n < 10 ? '0' + n : n }}


text:
package com.developer.bsince.sample;

import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bsince.optimus.callback.BaseProcessor;
import com.bsince.optimus.callback.Processor;
import com.bsince.optimus.client.OptimusClient;
import com.bsince.optimus.client.req.Method;
import com.bsince.optimus.data.MulitDataSet;
import com.bsince.optimus.data.SimpleDataSet;
import com.bsince.optimus.event.ImageEvent;
import com.bsince.optimus.event.SimpleEvent;
import com.bsince.optimus.event.TextEvent;

import java.io.File;
import java.io.FileNotFoundException;

public class MainActivity extends ActionBarActivity {

    private EditText mEditText;
    private ImageView view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.text);
        view = (ImageView) findViewById(R.id.imageshow);
        mEditText.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void onAction(View v){
        switch (v.getId()){
            case R.id.get:

               TextEvent event= new TextEvent("http://www.baidu.com", new BaseProcessor<String>() {
                    @Override
                    public void onSuccess(int statusCode, String s) {
                        mEditText.setText(s);
                    }

                    @Override
                    public void onFail(int statusCode, Exception e) {
                        mEditText.setText(statusCode+":"+e.toString());
                    }
                }) ;
                OptimusClient.get(this).postEvent(event);
                break;
            case R.id.post:
                SimpleDataSet ds = new SimpleDataSet(Method.POST,"/habit");
                ds.put("user","张三");
                ds.put("habit","吃饭,睡觉");
                SimpleEvent<JavaBean> event2= new SimpleEvent<JavaBean>(ds, new BaseProcessor<JavaBean>() {
                    @Override
                    public void onSuccess(int statusCode, JavaBean s) {
                        mEditText.setText(s.value);
                    }

                    @Override
                    public void onFail(int statusCode, Exception e) {
                        mEditText.setText(statusCode+":"+e.toString());
                    }
                }) {
                    @Override
                    public JavaBean parseToJavaBean(String data) throws Exception {
                        //parse to your own jave bean
                        JavaBean bean = new JavaBean();
                        bean.value  = data;
                        return bean;
                    }
                };
                OptimusClient.get(this).postEvent(event2);
                break;
            case R.id.put:
                    MulitDataSet dataSet = new MulitDataSet(Method.POST,"/upload");
                            dataSet.put("file","xxx");
                try {
                    dataSet.put("f",new File(Environment.getExternalStorageDirectory(),"xiong.jpg"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    mEditText.setText("文件不存在");
                    return;
                }
                TextEvent te= new TextEvent(dataSet, new BaseProcessor<String>() {
                    @Override
                    public void onSuccess(int statusCode, String s) {
                        mEditText.setText("上传成功:"+s);
                    }

                    @Override
                    public void onFail(int statusCode, Exception e) {
                        mEditText.setText("上传失败:"+statusCode+":"+e.toString());
                    }
                });
                OptimusClient.get(this).postEvent(te);
                break;
            case R.id.image:
                ImageEvent event1 = new ImageEvent("http://pica.nipic.com/2007-11-09/2007119124513598_2.jpg", new BaseProcessor<Bitmap>() {
                    @Override
                    public void onSuccess(int statusCode, Bitmap bitmap) {
                        view.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onFail(int statusCode, Exception e) {
                        Toast.makeText(MainActivity.this,"图片下载失败",Toast.LENGTH_SHORT).show();
                    }
                },0,0, Bitmap.Config.RGB_565);
                event1.setCache(false);
                event1.setTarget("image");//标记用于取消请求
                OptimusClient.get(this).postEvent(event1);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        OptimusClient.get(this).cancelAllRequests();;
        OptimusClient.get(this).cancelRequests("image");
    }

    class  JavaBean{
        String value;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Provides a Google corp implementation of IndividualAttestation.
 */
'use strict';

/**
 * Google corp implementation of IndividualAttestation that requests
 * individual certificates for corp accounts.
 * @constructor
 * @implements IndividualAttestation
 */
function GoogleCorpIndividualAttestation() {}

/**
 * @param {string} appIdHash The app id hash.
 * @return {boolean} Whether to request the individual attestation certificate
 *     for this app id.
 */
GoogleCorpIndividualAttestation.prototype.requestIndividualAttestation =
    function(appIdHash) {
  return appIdHash === GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID_HASH;
};

/**
 * App ID used by Google employee accounts.
 * @const
 */
GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID =
    'https://www.gstatic.com/securitykey/a/google.com/origins.json';

/**
 * Hash of the app ID used by Google employee accounts.
 * @const
 */
GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID_HASH = B64_encode(
    sha256HashOfString(GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID));


text:
- Custom servicenames can now be mapped to Ext.Direct API (Ocramius)

## 0.1.1

- Added AssetManager (Ocramius)
- Added Composer (Ocramius)

## 0.1.0

- Direct API generator + controller (Rovak)


text:
var emitter = new (require('events').EventEmitter)
emitter.id = 'Api Test'

exports.emitter = emitter
exports.initApi = initApi
exports.setApi = setApi

var api

function initApi() {
	return api.apply(this, Array.prototype.slice.call(arguments))
}

function setApi(f) {
	api = f
}


text:
package ilargia.entitas.api.events;

import ilargia.entitas.api.IComponent;
import ilargia.entitas.api.entitas.IEntity;
import ilargia.entitas.api.IGroup;

@FunctionalInterface
public interface GroupChanged<TEntity extends IEntity> {

    void changed(final IGroup<TEntity> group, final TEntity entity, final int index, final IComponent component);

}


text:
<?php
//	error_reporting(E_ALL);
//	ini_set("display_errors", 1);

	$root = $_SERVER['DOCUMENT_ROOT'];
	require_once 'backends/public.php';
	require_once ($root . '/views/front/Layout_View.php');
	$data 		= $backend->loadBackend('map');

	$view 		= new Layout_View($data);

	echo $view->printHTMLPage('map');


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

		[page:Object3D] → [page:Light] → [page:LightProbe]

[name]

			Light probes are an alternative way of adding light to a 3D scene. HemisphereLightProbe is the light estimation data
			of a single hemisphere light in the scene. For more information about light probes, go to [page:LightProbe].

Constructor

[name]( [param:Color skyColor], [param:Color groundColor], [param:Float intensity] )

			[page:Color skyColor] - (optional) An instance of Color, string representing a color or a number representing a color.

			[page:Color groundColor] - (optional) An instance of Color, string representing a color or a number representing a color.

			[page:Float intensity] - (optional) Numeric value of the light probe's intensity. Default is 1.

			Creates a new [name].

Properties

				See the base [page:LightProbe LightProbe] class for common properties.

Methods

				See the base [page:LightProbe LightProbe] class for common methods.

Source

			[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
angular.module('todo', [])

.controller('ToDoCtrl', ['$scope', function($scope, $http) {
    $scope.tasklist = [
    ];
    $scope.priority = 'normal';

    $scope.addTask = function() {
        if(event.keyCode == 13 && $scope.taskName) {
            $scope.tasklist.push({"name": $scope.taskName, "completed": false, "priority": $scope.priority});
            $scope.taskName = "";
            $scope.priority = 'normal';
        }
    }

    $scope.deleteTask = function(index) {
        $scope.tasklist.splice(index, 1);
    }
}])


text:
var glob = require('glob');
var path  = require('path');
// var options = {
//     sync:true,
//     cwf: path.resolve(__dirname, './src')
// }

// var globInstance = new glob('*.html', options);

// module.exports =   globInstance.found;

var pageArr = Object.keys(getEntry('./src/*.html'));

//按文件名来获取入口文件(即需要生成的模板文件数量)
function getEntry(globPath) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        entries[pathname] = './' + entry;
    }
    return entries;
}

module.exports = pageArr;


text:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GitHub profile searcher</title>
    <link rel="icon" type="image/x-icon" href="/img/favicon.ico">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/konpa/devicon@4f6a4b08efdad6bb29f9cc801f5c07e263b39907/devicon.min.css">
    <base href="/">
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>


text:
<?php

return [
    'employee_grades'             => 'Employee Grades',
    'employee_departments'        => 'Employee Departments',
    'edit_employee_department'    => 'Edit Employee Department',
    'new_employee_department'     => 'New Employee Department',
    'employee_department_details' => 'Employee Department Details',

    'name' => 'Name',
    'code' => 'Code',

    'employee_department_created' => 'Employee Department created.',
    'employee_department_updated' => 'Employee Department updated.',

    'empty_list' => 'There are no Employee Departments in the system.',
];


text:
import logging

from tornado import gen
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler

from moth import AsyncMoth

class ExampleHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        email = 'ch@rlesthom.as'
        want_retval = 'test retval'
        moth = server.settings['moth']

        ### create_token ###
        self.write('test create_token...
')
        token = yield moth.create_token(email, retval=want_retval)
        self.write(token + '
')

        ### auth_token ###
        self.write('test auth_token...
')
        have_retval = yield moth.auth_token(email, token)
        self.write('"%s" should match "%s"
' % (want_retval, have_retval))

        ### auth_token for invalid email ###
        self.write('test bad auth...
')
        should_be_False = yield moth.auth_token('fake@f.com', token)
        self.write('"%s" should be False
' % should_be_False)

        ### remove_token ###
        self.write('test remove_token...
')
        yield moth.remove_token(email, token)

        ### remove_user ###
        self.write('test remove_user...
')
        yield moth.remove_user(email)

        self.finish()

server = Application([('/', ExampleHandler)], debug=True)
server.settings['moth'] = AsyncMoth('moth_test')
server.listen(9000)
IOLoop.instance().start()


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>概览列表</title>
<meta name="date" content="2017-01-20">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

所有类

程序包

com.teemo.core

com.teemo.core.aop

com.teemo.core.entity

com.teemo.core.exception

com.teemo.core.security

com.teemo.core.util

com.teemo.dao

com.teemo.dto

com.teemo.entity

com.teemo.service

com.teemo.web.controller

core.cache

core.dao

core.exception

core.service

core.support

core.support.page

core.support.repository

core.support.search

core.util

core.web.controller


text:
@interface HSensorService : NSObject

+ (HSensorService *)instance;

- (void)start;
- (void)stop;

@end

extern NSString * const HSensorServiceRecordDidStartNotification;
extern NSString * const HSensorServiceRecordDidStopNotification;
extern NSString * const HSensorServiceMeasurementDidApearNotification;


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 1: 540 (1882)

#### Original name
Sphaeria lloydii P. Crouan & H. Crouan, 1867

### Remarks
null


text:
@interface CPERootViewController : UIViewController <UIPageViewControllerDelegate>

@property (strong, nonatomic) UIPageViewController *pageViewController;

@end


text:
// Patterns: 0

using System;
using Autofac;
using TestApplication.Types;

namespace TestApplication.Autofac
{
    public class RegisterWithActivatorCreateInstance : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(context => Activator.CreateInstance(typeof(Foo)));
        }
    }
}


text:
package org.achartengine.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

// Referenced classes of package org.achartengine.model:
//            XYSeries

public class XYMultipleSeriesDataset
    implements Serializable
{

    private List a;

    public XYMultipleSeriesDataset()
    {
        a = new ArrayList();
    }

    public void addAllSeries(List list)
    {
        this;
        JVM INSTR monitorenter ;
        a.addAll(list);
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }

    public void addSeries(int i, XYSeries xyseries)
    {
        this;
        JVM INSTR monitorenter ;
        a.add(i, xyseries);
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }

    public void addSeries(XYSeries xyseries)
    {
        this;
        JVM INSTR monitorenter ;
        a.add(xyseries);
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }

    public void clear()
    {
        this;
        JVM INSTR monitorenter ;
        a.clear();
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }

    public XYSeries[] getSeries()
    {
        this;
        JVM INSTR monitorenter ;
        XYSeries axyseries[] = (XYSeries[])a.toArray(new XYSeries[0]);
        this;
        JVM INSTR monitorexit ;
        return axyseries;
        Exception exception;
        exception;
        throw exception;
    }

    public XYSeries getSeriesAt(int i)
    {
        this;
        JVM INSTR monitorenter ;
        XYSeries xyseries = (XYSeries)a.get(i);
        this;
        JVM INSTR monitorexit ;
        return xyseries;
        Exception exception;
        exception;
        throw exception;
    }

    public int getSeriesCount()
    {
        this;
        JVM INSTR monitorenter ;
        int i = a.size();
        this;
        JVM INSTR monitorexit ;
        return i;
        Exception exception;
        exception;
        throw exception;
    }

    public void removeSeries(int i)
    {
        this;
        JVM INSTR monitorenter ;
        a.remove(i);
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }

    public void removeSeries(XYSeries xyseries)
    {
        this;
        JVM INSTR monitorenter ;
        a.remove(xyseries);
        this;
        JVM INSTR monitorexit ;
        return;
        Exception exception;
        exception;
        throw exception;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>CMAKE_VERBOSE_MAKEFILE — CMake 3.8.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="CMAKE_VERSION" href="CMAKE_VERSION.html" />
    <link rel="prev" title="CMAKE_TWEAK_VERSION" href="CMAKE_TWEAK_VERSION.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-variables(7) »

CMAKE_VERBOSE_MAKEFILE¶

Enable verbose output from Makefile builds.

This variable is a cache entry initialized (to FALSE) by
the project() command.  Users may enable the option
in their local build tree to get more verbose output from
Makefile builds and show each command line as it is launched.

Previous topic

CMAKE_TWEAK_VERSION

Next topic

CMAKE_VERSION

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-variables(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
package esgi.project.ratpdroid;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import esgi.project.ratpdroid.model.Stop;

public class SearchFragment extends Fragment {

	private static final String TAG = "SearchFragment";

	private ImageView buttonSearch;
	private EditText editTextSearch;
	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_search, container, false);

		buttonSearch = (ImageView) view.findViewById(R.id.searchButton);
		editTextSearch = (EditText) view.findViewById(R.id.editTextSearch);

		Log.v(TAG, "onCreateView");

		buttonSearch.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Log.v(TAG, "Click sur le bouton search");

				for (Stop stop : Datas.GetInstance().GetStops()) {
					if (stop.getName().contains(
							editTextSearch.getText().toString().toUpperCase())) {
						Datas.GetInstance().SetCurrentStop(stop);

						intent = new Intent(v.getContext(), DetailStation.class);
						startActivity(intent);

						break;
					}
				}
			}
		});

		return view;
	}

	public void update()
	{
		editTextSearch.setText(R.string.search);
	}
}


text:
package net.phyokyaw.jaquapi.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import net.phyokyaw.jaquapi.core.model.Device;
import net.phyokyaw.jaquapi.core.model.OnOffMode;
import net.phyokyaw.jaquapi.programme.model.Programme.ProgrammeDevice;
import net.phyokyaw.jaquapi.programme.services.PowerControlDeviceService;
import net.phyokyaw.jaquapi.programme.services.PowerControlDeviceService.DeviceStatus;

@Controller
public class PowerWebControl {

	private static Logger logger = LoggerFactory.getLogger(PowerWebControl.class);

	@Autowired
	@Qualifier("programme")
	private PowerControlDeviceService powerControlDeviceService;

	@RequestMapping("/device_status")
	public @ResponseBody DeviceStatus[] getDeviceStatus() {
		Device devices[] = powerControlDeviceService.getDevices();
		DeviceStatus[] deviceStatus = new DeviceStatus[devices.length];
		for (int i = 0; i < devices.length; i++) {
			deviceStatus[i] = new DeviceStatus(devices[i]);
		}
		return deviceStatus;
	}

	@RequestMapping("/device_status/{id}")
	public @ResponseBody DeviceStatus getDeviceStatus(@PathVariable("id") long id) {
		Device devices[] = powerControlDeviceService.getDevices();
		for (int i = 0; i < devices.length; i++) {
			if (devices[i].getId() == id) {
				return new DeviceStatus(devices[i]);
			}
		}
		return null;
	}

	@RequestMapping("/device/{id}")
	public @ResponseBody ModelAndView getDeviceDetail(@PathVariable("id") long id) {
		ModelAndView mav = new ModelAndView("device_detail");
		mav.addObject("device", powerControlDeviceService.getDevice(id));
		return mav;
	}

	@RequestMapping("/secure/device_override/{id}/{on}/{duration}")
	public @ResponseBody boolean deviceOverride(@PathVariable("id") long id, @PathVariable("on") boolean on,
			@PathVariable("duration") long duration) {
		powerControlDeviceService.getDevice(id).setOverridingMode(new OnOffMode(on), duration * 1000 * 60);
		return true;
	}

	@RequestMapping("/secure/cancel_device_override/{id}")
	public @ResponseBody boolean cancelOverride(@PathVariable("id") long id) {
		powerControlDeviceService.getDevice(id).cancelOverridingMode();
		return true;
	}

	@RequestMapping("/programmes")
	public @ResponseBody ModelAndView getProgrammes() {
		ModelAndView mav = new ModelAndView("maintenance");
		mav.addObject("programmesStatus", powerControlDeviceService.getProgrammesStatus());
		return mav;
	}

	@RequestMapping("/programme_detail/{id}")
	public @ResponseBody ModelAndView getProgrammes(@PathVariable("id") long id) {
		ModelAndView mav = new ModelAndView("programme_detail");
		mav.addObject("programmeStatus", powerControlDeviceService.getProgrammeStatus(id));
		return mav;
	}

	@RequestMapping("/secure/activate_programme/{id}")
	public String activateProgramme(@PathVariable("id") long id) {
		powerControlDeviceService.activateProgramme(id);
		return "redirect:/programmes";
	}

	@RequestMapping("/programme_devices_status/{id}")
	public @ResponseBody DeviceStatus[] getProgrammeDeviceStatus(@PathVariable("id") long id) {
		ProgrammeDevice[] devices = powerControlDeviceService.getProgrammeStatus(id).getProgrammeDevices();
		DeviceStatus[] deviceStatus = new DeviceStatus[devices.length];
		for (int i = 0; i < devices.length; i++) {
			deviceStatus[i] = new DeviceStatus(devices[i].getDevice());
		}
		return deviceStatus;
	}

	// @RequestMapping("/secure/deactivate_programme/{id}")
	// public void deactivateProgramme(@PathVariable("id") long id) {
	// powerControlDeviceService.deactivateProgramme(id);
	// }
	//
	// @RequestMapping("/programme_status/{id}")
	// public @ResponseBody ProgrammeStatus programmeStatus(@PathVariable("id")
	// long id) {
	// Programme programme = powerControlDeviceService.getProgramme(id);
	// return new ProgrammeStatus(programme);
	// }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

/**
 * dispatch custom events
 */

var eventDispatcher = function eventDispatcher() {
  var events = {};

  /**
   * Register a handler for event, to be fired
   * for every event.
   */
  var on = function on(eventName, handler) {
    events[eventName] = events[eventName] || [];
    events[eventName].push(handler);
    return undefined;
  };

  /**
   * dispatch an event for a handler.
   */
  var dispatch = function dispatch(eventName, data) {
    if (events[eventName]) {
      events[eventName].forEach(function (fn) {
        fn(data);
      });
    }
  };

  return {
    on: on,
    dispatch: dispatch
  };
};

exports.default = eventDispatcher;


text:
var should = require('should');
var helper = require('../helper');
var validate = require('bateeq-models').validator.master;
var manager;

function getData() {
    var Store = require('bateeq-models').master.Store;
    var store = new Store();

    var now = new Date();
    var stamp = now / 1000 | 0;
    var code = stamp.toString(36);

    store.code = code;
    store.name = `name[${code}]`;
    store.description = `description for ${code}`;

    return store;
}

before('#00. connect db', function(done) {
    helper.getDb()
        .then(db => {
            var StoreManager = require('../../src/managers/master/store-manager');
            manager = new StoreManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdId;
it('#01. should success when create new data', function(done) {
    var data = getData();
    manager.create(data)
        .then(id => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdData;
it(`#02. should success when get created data with id`, function(done) {
    manager.getSingleByQuery({
            _id: createdId
        })
        .then(data => {
            validate.store(data);
            createdData = data;
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#03. should success when update created data`, function(done) {

    createdData.code += '[updated]';
    createdData.name += '[updated]';
    createdData.description += '[updated]';

    manager.update(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#04. should success when get updated data with id`, function(done) {
    manager.getSingleByQuery({
            _id: createdId
        })
        .then(data => {
            validate.store(data);
            data.code.should.equal(createdData.code);
            data.name.should.equal(createdData.name);
            data.description.should.equal(createdData.description);
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#05. should success when delete data`, function(done) {
    manager.delete(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#06. should _deleted=true`, function(done) {
    manager.getSingleByQuery({
            _id: createdId
        })
        .then(data => {
            validate.store(data);
            data._deleted.should.be.Boolean();
            data._deleted.should.equal(true);
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#07. should error when create new data with same code', function(done) {
    var data = Object.assign({}, createdData);
    delete data._id;
    manager.create(data)
        .then(id => {
            id.should.be.Object();
            createdId = id;
            done("Should not be able to create data with same code");
        })
        .catch(e => {
            try {
                e.errors.should.have.property('code');
                done();
            }
            catch (e) {
                done(e);
            }
        })
});

it('#08. should error with property code and name ', function(done) {
    manager.create({})
        .then(id => {
            done("Should not be error with property code and name");
        })
        .catch(e => {
            try {
                e.errors.should.have.property('code');
                e.errors.should.have.property('name');
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});


text:
#include "createFVMaster.h"

#include "readline.h"
#include "security.h"

#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#include <Security/SecKeychain.h>
#include <Security/SecCertificate.h>
#include <Security/SecKeychain.h>
#include <Security/oidsalg.h>
#include <Security/oidsattr.h>
#include <limits.h>

#include "srCdsaUtils.h"

#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>

const char * const _masterKeychainName = "FileVaultMaster.keychain";
const char * const _masterKeychainPath = "./FileVaultMaster";

/*
 * Parameters used to create key pairs and certificates in
 * SR_CertificateAndKeyCreate().
 */
#define SR_KEY_ALGORITHM			CSSM_ALGID_RSA
#define SR_KEY_SIZE_IN_BITS			1024

#define SR2_KEY_SIZE_IN_BITS		2048        // Recommended size for FileVault2 (FDE)

/*
 * The CSSM_ALGORITHMS and OID values defining the signature
 * algorithm in the generated certificate.
 */
#define SR_CERT_SIGNATURE_ALGORITHM	CSSM_ALGID_SHA1WithRSA
#define SR_CERT_SIGNATURE_ALG_OID	CSSMOID_SHA1WithRSA

OSStatus makeMasterPassword(const char *fvmkcName, const char *masterPasswordPassword, uint32 keySizeInBits, SecKeychainRef *keychainRef);

OSStatus createPair(CFStringRef hostName,CFStringRef userName,SecKeychainRef keychainRef, uint32 keySizeInBits, CFDataRef *cert);
OSStatus generateKeyPair(CSSM_CSP_HANDLE cspHand, CSSM_DL_DB_HANDLE dlDbHand, CSSM_ALGORITHMS keyAlg,
    uint32 keySizeInBits, const char *keyLabel, CSSM_KEY_PTR *pubKeyPtr, CSSM_KEY_PTR *privKeyPtr);
OSStatus createRootCert(CSSM_TP_HANDLE tpHand, CSSM_CL_HANDLE clHand, CSSM_CSP_HANDLE cspHand,
    CSSM_KEY_PTR subjPubKey, CSSM_KEY_PTR signerPrivKey, const char *hostName, const char *userName,
    CSSM_ALGORITHMS sigAlg, const CSSM_OID *sigOid, CSSM_DATA_PTR certData);
void randUint32(uint32 *u);

static char *secCopyCString(CFStringRef theString);

OSStatus makeMasterPassword(const char *fvmkcName, const char *masterPasswordPassword, uint32 keySizeInBits, SecKeychainRef *keychainRef)
{
    /*
        OSStatus SecFileVaultMakeMasterPassword(CFStringRef masterPasswordPassword);

        *** In the real code, this will be done directly rather than exec'ing a tool, since there are too many parameters to specify
        *** this needs to be done as root, since the keychain will be a system keychain
        /usr/bin/certtool y c k=/Library/Keychains/FileVaultMaster.keychain p=<masterPasswordPassword>
        /usr/bin/certtool c   k=/Library/Keychains/FileVaultMaster.keychain o=/Library/Keychains/FileVaultMaster.cer
        Two steps: create the keychain, then create the keypair
    */

    SecAccessRef initialAccess = NULL;

    if (!masterPasswordPassword)
    {
        sec_error("You must supply a non-empty password");
        return -2;
    }

    //  We return an error if the keychain already exists
    OSStatus status = SecKeychainCreate(fvmkcName, strlen(masterPasswordPassword), masterPasswordPassword, false, initialAccess, keychainRef);
    if (status!=noErr)
    {
		if (status==errSecDuplicateKeychain || status==CSSMERR_DL_DATASTORE_ALREADY_EXISTS)
            sec_error("The keychain file %s already exists", fvmkcName);
        return status;
    }

    // Create the key pair
    char host[PATH_MAX];
	int rx = gethostname(host, sizeof(host));
    if (rx)
        strcpy(host, "localhost");

    CFStringRef hostName = CFSTR("FileVault Recovery Key");		// This is what shows up in Keychain Access display
    CFStringRef userName = CFStringCreateWithCString(kCFAllocatorDefault, host, kCFStringEncodingUTF8);
    CFDataRef certData = NULL;
    printf("Generating a %d bit key pair; this may take several minutes\n", keySizeInBits);
    status = createPair(hostName,userName,*keychainRef,keySizeInBits, &certData);
    if (status)
        sec_error("Error in createPair: %s", sec_errstr(status));
    if (certData)
        CFRelease(certData);

    return status;
}

OSStatus createPair(CFStringRef hostName,CFStringRef userName,SecKeychainRef keychainRef, uint32 keySizeInBits, CFDataRef *cert)
{
	SecCertificateRef	certRef = NULL;
	CSSM_DL_DB_HANDLE 	dlDbHand = {0, 0};
	CSSM_CSP_HANDLE		cspHand = 0;
	CSSM_TP_HANDLE		tpHand = 0;
	CSSM_CL_HANDLE		clHand = 0;
	CSSM_KEY_PTR		pubKey = NULL;
	CSSM_KEY_PTR		privKey = NULL;
	CSSM_DATA			certData = {0, NULL};
	char 				*hostStr = NULL;
	char				*userStr = NULL;
	OSStatus			ortn;
	CSSM_OID 			algOid = SR_CERT_SIGNATURE_ALG_OID;

	hostStr = secCopyCString(hostName);
	userStr = secCopyCString(userName);
	if (!hostStr || !userStr)	// could not convert to UTF-8
	{
    	ortn = paramErr;
        goto xit;
    }

	// open keychain, connect to all the CDSA modules we'll need

	ortn = SecKeychainGetCSPHandle(keychainRef, &cspHand);
	if (ortn)
        goto xit;

	ortn = SecKeychainGetDLDBHandle(keychainRef, &dlDbHand);
	if (ortn)
        goto xit;

	tpHand = srTpStartup();
	if (tpHand == 0)
	{
    	ortn = ioErr;
        goto xit;
    }

	clHand = srClStartup();
	if (clHand == 0)
	{
    	ortn = ioErr;
        goto xit;
    }

	// generate key pair, private key stored in keychain
	ortn = generateKeyPair(cspHand, dlDbHand, SR_KEY_ALGORITHM, keySizeInBits,
		"FileVault Master Password Key", &pubKey, &privKey);
	if (ortn)
        goto xit;

	// generate the cert
	ortn = createRootCert(tpHand,clHand,cspHand,pubKey,privKey,hostStr,userStr,
		SR_CERT_SIGNATURE_ALGORITHM,&algOid,&certData);
	if (ortn)
        goto xit;

	// store the cert in the same DL/DB as the key pair [see SecCertificateCreateFromData]
	ortn = SecCertificateCreateFromData(&certData, CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER, &certRef);
	if (ortn)
        goto xit;

	ortn = SecCertificateAddToKeychain(certRef, keychainRef);
	if (ortn)
        goto xit;

	// return the cert to caller
    *cert = CFDataCreate(NULL, certData.Data, certData.Length);

    // cleanup
xit:
    if (certRef)
        CFRelease(certRef);
    if (certData.Data)
        free(certData.Data);
	if (hostStr)
		free(hostStr);
	if (userStr)
		free(userStr);
	if (tpHand)
		CSSM_ModuleDetach(tpHand);
	if (clHand)
		CSSM_ModuleDetach(clHand);
	if (pubKey)
    {
		CSSM_FreeKey(cspHand,
			NULL,			// access cred
			pubKey,
			CSSM_FALSE);	// delete
		APP_FREE(pubKey);
	}
	if (privKey)
    {
		CSSM_FreeKey(cspHand,
			NULL,			// access cred
			privKey,
			CSSM_FALSE);	// delete
		APP_FREE(privKey);
	}

	return ortn;
}

/*
* Given a CFStringRef, this function allocates and returns a pointer
* to a null-terminated 'C' string copy. If conversion of the string
* to UTF8 fails for some reason, the function will return NULL.
*
* The caller must free this pointer
*/

char *secCopyCString(CFStringRef theString)
{
	CFIndex maxLength = CFStringGetMaximumSizeForEncoding(CFStringGetLength(theString), kCFStringEncodingUTF8) + 1;
	char* buffer = (char*) malloc(maxLength);
	Boolean converted = CFStringGetCString(theString, buffer, maxLength, kCFStringEncodingUTF8);
	if (!converted) {
       free(buffer);
       buffer = NULL;
	}
	return buffer;
}

#pragma mark -------------------- SecFileVaultCert private implementation --------------------

OSStatus createRootCert(
	CSSM_TP_HANDLE		tpHand,
	CSSM_CL_HANDLE		clHand,
	CSSM_CSP_HANDLE		cspHand,
	CSSM_KEY_PTR		subjPubKey,
	CSSM_KEY_PTR		signerPrivKey,
	const char			*hostName,			// CSSMOID_CommonName
	const char 			*userName,			// CSSMOID_Description
	CSSM_ALGORITHMS 	sigAlg,
	const CSSM_OID		*sigOid,
	CSSM_DATA_PTR		certData)			// mallocd and RETURNED
{
	CE_DataAndType 				exts[2];
	CE_DataAndType 				*extp = exts;
	unsigned					numExts;
	CSSM_DATA					refId;		// mallocd by
											//    CSSM_TP_SubmitCredRequest
	CSSM_APPLE_TP_CERT_REQUEST	certReq;
	CSSM_TP_REQUEST_SET			reqSet;
	sint32						estTime;
	CSSM_BOOL					confirmRequired;
	CSSM_TP_RESULT_SET_PTR		resultSet=NULL;
	CSSM_ENCODED_CERT			*encCert=NULL;
	CSSM_APPLE_TP_NAME_OID		subjectNames[2];
	CSSM_TP_CALLERAUTH_CONTEXT 	CallerAuthContext;
	CSSM_FIELD					policyId;

	numExts = 0;

	certReq.challengeString = NULL;

	/* KeyUsage extension */
	extp->type = DT_KeyUsage;
	extp->critical = CSSM_FALSE;
	extp->extension.keyUsage = CE_KU_DigitalSignature |
							   CE_KU_KeyCertSign |
							   CE_KU_KeyEncipherment |
							   CE_KU_DataEncipherment;
	extp++;
	numExts++;

	/* BasicConstraints */
	extp->type = DT_BasicConstraints;
	extp->critical = CSSM_TRUE;
	extp->extension.basicConstraints.cA = CSSM_FALSE;
	extp->extension.basicConstraints.pathLenConstraintPresent = CSSM_FALSE;
	extp++;
	numExts++;

	/* name array */
	subjectNames[0].string 	= hostName;
	subjectNames[0].oid 	= &CSSMOID_CommonName;
	subjectNames[1].string	= userName;
	subjectNames[1].oid 	= &CSSMOID_Description;

	/* certReq */
	certReq.cspHand = cspHand;
	certReq.clHand = clHand;
	randUint32(&certReq.serialNumber);		// random serial number
	certReq.numSubjectNames = 2;
	certReq.subjectNames = subjectNames;

	certReq.numIssuerNames = 0;				// root for now
	certReq.issuerNames = NULL;
	certReq.issuerNameX509 = NULL;
	certReq.certPublicKey = subjPubKey;
	certReq.issuerPrivateKey = signerPrivKey;
	certReq.signatureAlg = sigAlg;
	certReq.signatureOid = *sigOid;
	certReq.notBefore = 0;
	certReq.notAfter = 60 * 60 * 24 * 365;	// seconds from now, one year
	certReq.numExtensions = numExts;
	certReq.extensions = exts;

	reqSet.NumberOfRequests = 1;
	reqSet.Requests = &certReq;

	/* a CSSM_TP_CALLERAUTH_CONTEXT to specify an OID */
	memset(&CallerAuthContext, 0, sizeof(CSSM_TP_CALLERAUTH_CONTEXT));
	memset(&policyId, 0, sizeof(CSSM_FIELD));
	policyId.FieldOid = CSSMOID_APPLE_TP_LOCAL_CERT_GEN;

	CallerAuthContext.Policy.NumberOfPolicyIds = 1;
	CallerAuthContext.Policy.PolicyIds = &policyId;

	CSSM_RETURN crtn = CSSM_TP_SubmitCredRequest(tpHand,
		NULL,				// PreferredAuthority
		CSSM_TP_AUTHORITY_REQUEST_CERTISSUE,
		&reqSet,
		&CallerAuthContext,
		&estTime,
		&refId);

	if(crtn) {
		sec_error("CSSM_TP_SubmitCredRequest: %s", sec_errstr(crtn));
		goto xit;
	}
	crtn = CSSM_TP_RetrieveCredResult(tpHand,
		&refId,
		NULL,				// CallerAuthCredentials
		&estTime,
		&confirmRequired,
		&resultSet);
	if(crtn) {
		sec_error("CSSM_TP_RetrieveCredResult: %s", sec_errstr(crtn));
		goto xit;
	}
	if(resultSet == NULL) {
		sec_error("CSSM_TP_RetrieveCredResult: returned NULL result set");
		crtn = ioErr;
		goto xit;
	}
	encCert = (CSSM_ENCODED_CERT *)resultSet->Results;
    certData->Length = encCert->CertBlob.Length;
    certData->Data = malloc(encCert->CertBlob.Length);
    if (certData->Data)
        memcpy(certData->Data, encCert->CertBlob.Data, encCert->CertBlob.Length);
	crtn = noErr;

xit:
	/* free resources allocated by TP */
	APP_FREE(refId.Data);
    if (encCert)
    {
        if (encCert->CertBlob.Data)
        {
            APP_FREE(encCert->CertBlob.Data);
        }
        APP_FREE(encCert);
    }
	APP_FREE(resultSet);
	return crtn;
}

/* Convert a reference key to a raw key. */
static CSSM_RETURN refKeyToRaw(
	CSSM_CSP_HANDLE	cspHand,
	const CSSM_KEY	*refKey,
	CSSM_KEY_PTR	rawKey)			// RETURNED
{
	CSSM_CC_HANDLE		ccHand;
	CSSM_RETURN			crtn;
	CSSM_ACCESS_CREDENTIALS	creds;

	memset(rawKey, 0, sizeof(CSSM_KEY));
	memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
	crtn = CSSM_CSP_CreateSymmetricContext(cspHand,
			CSSM_ALGID_NONE,
			CSSM_ALGMODE_NONE,
			&creds,				// passPhrase
			NULL,				// wrapping key
			NULL,				// init vector
			CSSM_PADDING_NONE,	// Padding
			0,					// Params
			&ccHand);
	if(crtn) {
		sec_error("CSSM_CSP_CreateSymmetricContext: refKeyToRaw context err: %s", sec_errstr(crtn));
		return crtn;
	}

	crtn = CSSM_WrapKey(ccHand,
		&creds,
		refKey,
		NULL,			// DescriptiveData
		rawKey);
	if(crtn != CSSM_OK) {
		sec_error("CSSM_WrapKey: refKeyToRaw wrap err: %s", sec_errstr(crtn));
		return crtn;
	}
	CSSM_DeleteContext(ccHand);
	return CSSM_OK;
}

/*
 * Find private key by label, modify its Label attr to be the
 * hash of the associated public key.
 */
CSSM_RETURN setPubKeyHash(
	CSSM_CSP_HANDLE 	cspHand,
	CSSM_DL_DB_HANDLE 	dlDbHand,
	const CSSM_KEY		*pubOrPrivKey,	// to get hash; raw or ref/CSPDL
	const char			*keyLabel)		// look up by this
{
	CSSM_QUERY						query;
	CSSM_SELECTION_PREDICATE		predicate;
	CSSM_DB_UNIQUE_RECORD_PTR		record = NULL;
	CSSM_RETURN						crtn;
	CSSM_DATA						labelData;
	CSSM_HANDLE						resultHand;

	labelData.Data = (uint8 *)keyLabel;
	labelData.Length = strlen(keyLabel) + 1;	// incl. NULL
	query.RecordType = CSSM_DL_DB_RECORD_PRIVATE_KEY;
	query.Conjunctive = CSSM_DB_NONE;
	query.NumSelectionPredicates = 1;
	predicate.DbOperator = CSSM_DB_EQUAL;

	predicate.Attribute.Info.AttributeNameFormat =
		CSSM_DB_ATTRIBUTE_NAME_AS_STRING;
	predicate.Attribute.Info.Label.AttributeName = "Label";
	predicate.Attribute.Info.AttributeFormat =
		CSSM_DB_ATTRIBUTE_FORMAT_BLOB;
	predicate.Attribute.Value = &labelData;
	query.SelectionPredicate = &predicate;

	query.QueryLimits.TimeLimit = 0;
	query.QueryLimits.SizeLimit = 1;
	query.QueryFlags = 0;

	/* build Record attribute with one attr */
	CSSM_DB_RECORD_ATTRIBUTE_DATA recordAttrs;
	CSSM_DB_ATTRIBUTE_DATA attr;
	attr.Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING;
	attr.Info.Label.AttributeName = "Label";
	attr.Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB;

	recordAttrs.DataRecordType = CSSM_DL_DB_RECORD_PRIVATE_KEY;
	recordAttrs.NumberOfAttributes = 1;
	recordAttrs.AttributeData = &attr;

	crtn = CSSM_DL_DataGetFirst(dlDbHand,
		&query,
		&resultHand,
		&recordAttrs,
		NULL,			// hopefully optional ...theData,
		&record);
	/* abort only on success */
	if(crtn != CSSM_OK) {
		sec_error("CSSM_DL_DataGetFirst: setPubKeyHash: can't find private key: %s", sec_errstr(crtn));
		return crtn;
	}

	/*
	 * If specified key is a ref key, do NULL unwrap for use with raw CSP.
	 * If the CSPDL and SecurityServer support the key digest passthrough
	 * this is unnecessary.
	 */
	CSSM_KEY rawKeyToDigest;
	if(pubOrPrivKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) {
		crtn = refKeyToRaw(cspHand, pubOrPrivKey, &rawKeyToDigest);
		if(crtn) {
            sec_error("setPubKeyHash: Error converting public key to raw format: %s", sec_errstr(crtn));
			return crtn;
		}
	}
	else {
		/* use as is */
		rawKeyToDigest = *pubOrPrivKey;
	}

	/* connect to raw CSP */
	CSSM_CSP_HANDLE rawCspHand = srCspStartup(CSSM_TRUE);
	if(rawCspHand == 0) {
		printf("***Error connecting to raw CSP; aborting.\n");
		return -1;
	}

	/* calculate hash of pub key from private or public part */
	CSSM_DATA_PTR keyDigest = NULL;
	CSSM_CC_HANDLE ccHand;
	crtn = CSSM_CSP_CreatePassThroughContext(rawCspHand,
	 	&rawKeyToDigest,
		&ccHand);
	if(ccHand == 0) {
        sec_error("CSSM_CSP_CreatePassThroughContext: Error calculating public key hash. Aborting: %s", sec_errstr(crtn));
		return -1;
	}
	crtn = CSSM_CSP_PassThrough(ccHand,
		CSSM_APPLECSP_KEYDIGEST,
		NULL,
		(void **)&keyDigest);
	if(crtn) {
        sec_error("CSSM_CSP_PassThrough(PUBKEYHASH): Error calculating public key hash. Aborting: %s", sec_errstr(crtn));
		return crtn;
	}
	if(pubOrPrivKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) {
		/* created in refKeyToRaw().... */
		CSSM_FreeKey(cspHand, NULL, &rawKeyToDigest, CSSM_FALSE);
	}
	CSSM_DeleteContext(ccHand);
	CSSM_ModuleDetach(rawCspHand);

	/*
	 * Replace Label attr data with hash.
	 * NOTE: the module which allocated this attribute data - a DL -
	 * was loaded and attached by the Sec layer, not by us. Thus
	 * we can't use the memory allocator functions *we* used when
	 * attaching to the CSPDL - we have to use the ones
	 * which the Sec layer registered with the DL.
	 */
	CSSM_API_MEMORY_FUNCS memFuncs;
	crtn = CSSM_GetAPIMemoryFunctions(dlDbHand.DLHandle, &memFuncs);
	if(crtn) {
        sec_error("CSSM_GetAPIMemoryFunctions(DLHandle): Error: %s", sec_errstr(crtn));
		/* oh well, leak and continue */
	}
	else {
		memFuncs.free_func(attr.Value->Data, memFuncs.AllocRef);
		memFuncs.free_func(attr.Value, memFuncs.AllocRef);
	}
	attr.Value = keyDigest;

	/* modify key attributes */
	crtn = CSSM_DL_DataModify(dlDbHand,
			CSSM_DL_DB_RECORD_PRIVATE_KEY,
			record,
			&recordAttrs,
            NULL,				// DataToBeModified
			CSSM_DB_MODIFY_ATTRIBUTE_REPLACE);
	if(crtn) {
        sec_error("CSSM_DL_DataModify(PUBKEYHASH): Error setting public key hash. Aborting: %s", sec_errstr(crtn));
		return crtn;
	}
	crtn = CSSM_DL_DataAbortQuery(dlDbHand, resultHand);
	if(crtn) {
        sec_error("CSSM_DL_DataAbortQuery: Error while stopping query: %s", sec_errstr(crtn));
		/* let's keep going in this case */
	}
	crtn = CSSM_DL_FreeUniqueRecord(dlDbHand, record);
	if(crtn) {
        sec_error("CSSM_DL_FreeUniqueRecord: Error while freeing record: %s", sec_errstr(crtn));
		/* let's keep going in this case */
		crtn = CSSM_OK;
	}

	/* free resources */
    if (keyDigest)
    {
        srAppFree(keyDigest->Data, NULL);
        srAppFree(keyDigest, NULL);
    }
	return CSSM_OK;
}

/*
 * Generate a key pair using the CSPDL.
 */
OSStatus generateKeyPair(
	CSSM_CSP_HANDLE 	cspHand,
	CSSM_DL_DB_HANDLE 	dlDbHand,
	CSSM_ALGORITHMS 	keyAlg,				// e.g., CSSM_ALGID_RSA
	uint32				keySizeInBits,
	const char 			*keyLabel,			// C string
	CSSM_KEY_PTR 		*pubKeyPtr,			// mallocd, created, RETURNED
	CSSM_KEY_PTR 		*privKeyPtr)		// mallocd, created, RETURNED
{
	CSSM_KEY_PTR pubKey = (CSSM_KEY_PTR)(APP_MALLOC(sizeof(CSSM_KEY)));
	CSSM_KEY_PTR privKey = (CSSM_KEY_PTR)(APP_MALLOC(sizeof(CSSM_KEY)));
	if((pubKey == NULL) || (privKey == NULL)) {
		return memFullErr;
	}

	CSSM_RETURN crtn;
	CSSM_KEYUSE pubKeyUse;
	CSSM_KEYUSE privKeyUse;

	pubKeyUse = CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_ENCRYPT |
			CSSM_KEYUSE_WRAP;
	privKeyUse = CSSM_KEYUSE_SIGN | CSSM_KEYUSE_DECRYPT |
			CSSM_KEYUSE_UNWRAP;

	crtn = srCspGenKeyPair(cspHand,
		&dlDbHand,
		keyAlg,
		keyLabel,
		strlen(keyLabel) + 1,
		keySizeInBits,
		pubKey,
		pubKeyUse,
		CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_RETURN_REF,
		privKey,
		privKeyUse,
		CSSM_KEYATTR_SENSITIVE | CSSM_KEYATTR_RETURN_REF |
			CSSM_KEYATTR_PERMANENT | CSSM_KEYATTR_EXTRACTABLE);

	if(crtn) {
		APP_FREE(pubKey);
		APP_FREE(privKey);
		return paramErr;
	}

	/* bind private key to cert by public key hash */
	crtn = setPubKeyHash(cspHand,
		dlDbHand,
		pubKey,
		keyLabel);
	if(crtn) {
        sec_error("setPubKeyHash: Error setting public key hash. Continuing at peril: %s", sec_errstr(crtn));
	}

	*pubKeyPtr = pubKey;
	*privKeyPtr = privKey;
	return noErr;
}

//	Fill a uint32 with random data
void randUint32(uint32 *u)
{
	int dev = open("/dev/random", O_RDONLY);
	if(dev < 0) {
		return;
	}
	read(dev, u, sizeof(*u));
	close(dev);
}

//==========================================================================

int
keychain_createMFV(int argc, char * const *argv)
{
	int zero_password = 0;
	char *password = NULL;
    const char *keychainName = NULL;
	int result = 0, ch = 0;
	Boolean do_prompt = FALSE;
    SecKeychainRef keychainRef = NULL;
    uint32 keySizeInBits = SR2_KEY_SIZE_IN_BITS;    // default

/* AG: getopts optstring name [args]
    AG: while loop calling getopt is used to extract password from cl from user
    password is the only option to keychain_create
    optstring  is  a  string  containing the legitimate option
    characters.  If such a character is followed by  a  colon,
    the  option  requires  an  argument,  so  getopt  places a
    pointer to the following text in the same argv-element, or
    the  text  of  the following argv-element, in optarg.
*/
	while ((ch = getopt(argc, argv, "hp:s:P")) != -1)
	{
		switch  (ch)
		{
		case 'p':
			password = optarg;
			break;
		case 'P':
			do_prompt = TRUE;
			break;
        case 's':
        //  Specify the keysize in bits (default 1024)
            keySizeInBits = atoi(optarg);
            if (!(keySizeInBits == SR_KEY_SIZE_IN_BITS || keySizeInBits == SR2_KEY_SIZE_IN_BITS || keySizeInBits == 4096))
                return 2;
            break;
		case '?':
		default:
			return 2; /* @@@ Return 2 triggers usage message. */
		}
	}
/*
    AG:   The external variable optind is  the  index  of  the  next
       array  element  of argv[] to be processed; it communicates
       from one call of getopt() to the  next  which  element  to
       process.
       The variable optind is the index of the next element of the argv[] vector to 	be processed. It shall be initialized to 1 by the system, and getopt() shall 	update it when it finishes with each element of argv[]. When an element of argv[] 	contains multiple option characters, it is unspecified how getopt() determines 	which options have already been processed.

*/
	argc -= optind;
	argv += optind;

	if (argc > 1)
        return 2; /* @@@ Return 2 triggers usage message. */

    keychainName = (argc == 1)?*argv:_masterKeychainName;
    if (!keychainName || *keychainName == '\0')
        return -1;

	if (!password && !do_prompt)
	{
		int compare = 1;
		int tries;

		for (tries = 3; tries-- > 0;)
		{
			char *firstpass;

			password = getpass("password for new keychain: ");
			if (!password)
			{
				result = -1;
				goto loser;
			}

			firstpass = malloc(strlen(password) + 1);
			strcpy(firstpass, password);
			password = getpass("retype password for new keychain: ");
			compare = password ? strcmp(password, firstpass) : 1;
			memset(firstpass, 0, strlen(firstpass));
			free(firstpass);
			if (!password)
			{
				result = -1;
				goto loser;
			}

			if (compare)
			{
				fprintf(stderr, "passwords don't match\n");
				memset(password, 0, strlen(password));
			}
			else
			{
				zero_password = 1;
				break;
			}
		}

		if (compare)
		{
			result = 1;
			goto loser;
		}
	}

	do
	{
	//	result = do_create(keychain, password, do_prompt);
		result = makeMasterPassword(keychainName, password, keySizeInBits, &keychainRef);
        if (keychainRef)
            CFRelease(keychainRef);
		if (zero_password)
			memset(password, 0, strlen(password));
		if (result)
			goto loser;

		argc--;
		argv++;
        keychainName = *argv;
	} while (argc > 0);

loser:

	return result;
}


text:
package com.evolveum.midpoint.gui.impl.factory;

import javax.annotation.PostConstruct;
import javax.xml.namespace.QName;

import com.evolveum.midpoint.gui.api.prism.ItemWrapper;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.impl.prism.*;
import com.evolveum.midpoint.model.api.authentication.CompiledUserProfile;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.gui.api.prism.ItemStatus;
import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper;
import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper;
import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry;
import com.evolveum.midpoint.gui.impl.registry.GuiComponentRegistryImpl;
import com.evolveum.midpoint.model.api.ModelInteractionService;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.schema.ResourceShadowDiscriminator;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.prism.ValueStatus;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author katka
 *
 */
@Component
public class PrismObjectWrapperFactoryImpl<O extends ObjectType> extends PrismContainerWrapperFactoryImpl<O> implements PrismObjectWrapperFactory<O> {

    private static final transient Trace LOGGER = TraceManager.getTrace(PrismObjectWrapperFactoryImpl.class);

    private static final String DOT_CLASS = PrismObjectWrapperFactoryImpl.class.getName() + ".";
    private static final String OPERATION_DETERMINE_VIRTUAL_CONTAINERS = DOT_CLASS + "determineVirtualContainers";

    private static final QName VIRTUAL_CONTAINER_COMPLEX_TYPE = new QName("VirtualContainerType");
    private static final QName VIRTUAL_CONTAINER = new QName("virtualContainer");

    @Autowired private GuiComponentRegistry registry;
    @Autowired protected ModelInteractionService modelInteractionService;

    public PrismObjectWrapper<O> createObjectWrapper(PrismObject<O> object, ItemStatus status, WrapperContext context) throws SchemaException {

        try {
            applySecurityConstraints(object, context);
        } catch (CommunicationException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException e) {
            context.getResult().recordFatalError("Cannot create object wrapper for " + object + ". An eeror occured: " + e.getMessage(), e);
            throw new SchemaException(e.getMessage(), e);
        }
        if (context.getObjectStatus() == null) {
            context.setObjectStatus(status);
        }

        List<VirtualContainersSpecificationType> virtualContainers = determineVirtualContainers(object.getDefinition().getTypeName(), context);
        context.setVirtualContainers(virtualContainers);

        PrismObjectWrapper<O> objectWrapper = createObjectWrapper(object, status);
        if (context.getReadOnly() != null) {
            objectWrapper.setReadOnly(context.getReadOnly().booleanValue());
        }
        context.setShowEmpty(ItemStatus.ADDED == status ? true : false);
        PrismContainerValueWrapper<O> valueWrapper = createValueWrapper(objectWrapper, object.getValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context);
        objectWrapper.getValues().add(valueWrapper);

        registry.registerWrapperPanel(object.getDefinition().getTypeName(), PrismContainerPanel.class);
        return objectWrapper;

    }

    @Override
    public PrismObjectValueWrapper<O> createContainerValueWrapper(PrismContainerWrapper<O> objectWrapper, PrismContainerValue<O> objectValue, ValueStatus status, WrapperContext context) {
        return new PrismObjectValueWrapperImpl<O>((PrismObjectWrapper<O>) objectWrapper, (PrismObjectValue<O>) objectValue, status);
    }

    public PrismObjectWrapper<O> createObjectWrapper(PrismObject<O> object, ItemStatus status) {
        return new PrismObjectWrapperImpl<O>(object, status);
    }

    @Override
    public PrismContainerValueWrapper<O> createValueWrapper(PrismContainerWrapper<O> parent, PrismContainerValue<O> value, ValueStatus status, WrapperContext context) throws SchemaException {
        PrismContainerValueWrapper<O> objectValueWrapper = super.createValueWrapper(parent, value, status, context);

        if (CollectionUtils.isEmpty(context.getVirtualContainers())) {
            return objectValueWrapper;
        }

        for (VirtualContainersSpecificationType virtualContainer : context.getVirtualContainers()){

            MutableComplexTypeDefinition mCtd = getPrismContext().definitionFactory().createComplexTypeDefinition(VIRTUAL_CONTAINER_COMPLEX_TYPE);
            DisplayType display = virtualContainer.getDisplay();

            //TODO: support full polystring -> translations could be defined directly there.
            mCtd.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel()));
            mCtd.setHelp(WebComponentUtil.getOrigStringFromPoly(display.getHelp()));
            mCtd.setRuntimeSchema(true);

            MutablePrismContainerDefinition def = getPrismContext().definitionFactory().createContainerDefinition(VIRTUAL_CONTAINER, mCtd);
            def.setMaxOccurs(1);
            def.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel()));
            def.setDynamic(true);

            ItemWrapperFactory factory = getRegistry().findWrapperFactory(def);
            if (factory == null) {
                LOGGER.warn("Cannot find factory for {}. Skipping wrapper creation.", def);
                continue;
            }

            WrapperContext ctx = context.clone();
            ctx.setVirtualItemSpecification(virtualContainer.getItem());
            ItemWrapper iw = factory.createWrapper(objectValueWrapper, def, ctx);

            if (iw == null) {
                continue;
            }
            ((List)objectValueWrapper.getItems()).add(iw);

        }

        return objectValueWrapper;
    }

    private List<VirtualContainersSpecificationType> determineVirtualContainers(QName objectType, WrapperContext context) {
        OperationResult result = context.getResult().createMinorSubresult(OPERATION_DETERMINE_VIRTUAL_CONTAINERS);
        try {
            CompiledUserProfile userProfile = modelInteractionService.getCompiledUserProfile(context.getTask(), context.getResult());
            GuiObjectDetailsSetType objectDetailsSetType = userProfile.getObjectDetails();
            if (objectDetailsSetType == null) {
                result.recordSuccess();
                return null;
            }
            List<GuiObjectDetailsPageType> detailsPages = objectDetailsSetType.getObjectDetailsPage();
            for (GuiObjectDetailsPageType detailsPage : detailsPages) {
                if (objectType == null) {
                    LOGGER.trace("Object type is not known, skipping considering custom details page settings.");
                    continue;
                }
                if (detailsPage.getType() == null) {
                    LOGGER.trace("Object type for details page {} not know, skipping considering custom details page settings.", detailsPage);
                    continue;
                }

                if (QNameUtil.match(objectType, detailsPage.getType())) {
                    result.recordSuccess();
                    return detailsPage.getContainer();
                }
            }
            result.recordSuccess();
            return null;
        } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) {
            LOGGER.error("Cannot determine virtual containers for {}, reason: {}", objectType, e.getMessage(), e);
            result.recordPartialError("Cannot determine virtual containers for " + objectType + ", reason: " + e.getMessage(), e);
            return null;
        }

    }

    /**
     *
     * @param object
     *
     * apply security constraint to the object, update wrapper context with additional information, e.g. shadow related attributes, ...
     */
    protected void applySecurityConstraints(PrismObject<O> object, WrapperContext context) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException {
        AuthorizationPhaseType phase = context.getAuthzPhase();
        Task task = context.getTask();
        OperationResult result = context.getResult();

        ObjectReferenceType archetypesToBeAdded = null;
        if (AssignmentHolderType.class.isAssignableFrom(object.getCompileTimeClass())) {
            archetypesToBeAdded = listArchetypes((PrismObject) object);
            if (archetypesToBeAdded != null) {
                applyArchetypes((PrismObject) object, archetypesToBeAdded);
            }
        }

        try {
            PrismObjectDefinition<O> objectDef = modelInteractionService.getEditObjectDefinition(object, phase, task, result);
            object.applyDefinition(objectDef, true);
        } catch (SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException
            | CommunicationException | SecurityViolationException e) {
            throw e;
        } finally {
            if (archetypesToBeAdded != null) {
                cleanupArchetypesToBeAdded((PrismObject) object, archetypesToBeAdded);
            }
        }

    }

    private <AH extends AssignmentHolderType> void applyArchetypes(PrismObject<AH> object, ObjectReferenceType ref) throws SchemaException {
        PrismReference archetypeRef = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF);

        if (archetypeRef == null) {
            archetypeRef = object.findOrCreateReference(AssignmentHolderType.F_ARCHETYPE_REF);
        }

        if (CollectionUtils.isNotEmpty(archetypeRef.getValues())) {
            throw new SchemaException("Cannot apply new archetype to the object with already assigned archetype.");
        }

        archetypeRef.getValues().add(ref.asReferenceValue());
    }

    private <AH extends  AssignmentHolderType> void cleanupArchetypesToBeAdded(PrismObject<AH> object, ObjectReferenceType ref) throws SchemaException {
        //Now we expect thet object can have just one archetyperef, so if something was added, we just remove it.

        PrismReference archetype = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF);
        if (archetype == null) {
            return;
        }

        if (archetype.getValues() != null && archetype.getValues().size() > 1) {
            throw new SchemaException("More then one archetype ref found, but this is not supported.");
        }

        object.removeReference(AssignmentHolderType.F_ARCHETYPE_REF);
    }

    private <AH extends AssignmentHolderType> ObjectReferenceType listArchetypes(PrismObject<AH> object) throws SchemaException {
        PrismContainer<AssignmentType> assignmentContainer = object.findContainer(AssignmentHolderType.F_ASSIGNMENT);
        Collection<AssignmentType> assignments = null;
        if (assignmentContainer != null) {
            assignments = assignmentContainer.getRealValues();
        }

        if (CollectionUtils.isEmpty(assignments)) {
            return null;
        }

        List<AssignmentType> archetypeAssignments = assignments.stream().filter(a -> a.getTargetRef() != null && QNameUtil.match(ArchetypeType.COMPLEX_TYPE, a.getTargetRef().getType())).collect(Collectors.toList());

        if (archetypeAssignments.size() > 1) {
            throw new SchemaException("More then one archetype assignment not supported.");
        }

        if (CollectionUtils.isEmpty(archetypeAssignments)) {
            return null;
        }

        AssignmentType archetypeAssignment = archetypeAssignments.iterator().next();

        PrismReference existingArchetypeRefs = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF);
        if (existingArchetypeRefs == null || CollectionUtils.isEmpty(existingArchetypeRefs.getRealValues())) {
            return archetypeAssignment.getTargetRef();
        }

        return null;

    }

    @Override
    public boolean match(ItemDefinition<?> def) {
        return def instanceof PrismObjectDefinition;
    }

    @Override
    @PostConstruct
    public void register() {
        registry.addToRegistry(this);
    }

    @Override
    public int getOrder() {
        return 100;
    }

}


text:
using namespace gpos;
using namespace gpdxl;

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::CDXLPhysicalSplit
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CDXLPhysicalSplit::CDXLPhysicalSplit(CMemoryPool *mp,
									 ULongPtrArray *delete_colid_array,
									 ULongPtrArray *insert_colid_array,
									 ULONG action_colid, ULONG ctid_colid,
									 ULONG segid_colid, BOOL preserve_oids,
									 ULONG tuple_oid)
	: CDXLPhysical(mp),
	  m_deletion_colid_array(delete_colid_array),
	  m_insert_colid_array(insert_colid_array),
	  m_action_colid(action_colid),
	  m_ctid_colid(ctid_colid),
	  m_segid_colid(segid_colid),
	  m_preserve_oids(preserve_oids),
	  m_tuple_oid(tuple_oid)
{
	GPOS_ASSERT(nullptr != delete_colid_array);
	GPOS_ASSERT(nullptr != insert_colid_array);
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::~CDXLPhysicalSplit
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CDXLPhysicalSplit::~CDXLPhysicalSplit()
{
	m_deletion_colid_array->Release();
	m_insert_colid_array->Release();
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::GetDXLOperator
//
//	@doc:
//		Operator type
//
//---------------------------------------------------------------------------
Edxlopid
CDXLPhysicalSplit::GetDXLOperator() const
{
	return EdxlopPhysicalSplit;
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::GetOpNameStr
//
//	@doc:
//		Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLPhysicalSplit::GetOpNameStr() const
{
	return CDXLTokens::GetDXLTokenStr(EdxltokenPhysicalSplit);
}

//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::SerializeToDXL
//
//	@doc:
//		Serialize function descriptor in DXL format
//
//---------------------------------------------------------------------------
void
CDXLPhysicalSplit::SerializeToDXL(CXMLSerializer *xml_serializer,
								  const CDXLNode *dxlnode) const
{
	const CWStringConst *element_name = GetOpNameStr();
	xml_serializer->OpenElement(
		CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name);

	CWStringDynamic *delete_cols =
		CDXLUtils::Serialize(m_mp, m_deletion_colid_array);
	xml_serializer->AddAttribute(
		CDXLTokens::GetDXLTokenStr(EdxltokenDeleteCols), delete_cols);
	GPOS_DELETE(delete_cols);

	CWStringDynamic *insert_cols =
		CDXLUtils::Serialize(m_mp, m_insert_colid_array);
	xml_serializer->AddAttribute(
		CDXLTokens::GetDXLTokenStr(EdxltokenInsertCols), insert_cols);
	GPOS_DELETE(insert_cols);

	xml_serializer->AddAttribute(
		CDXLTokens::GetDXLTokenStr(EdxltokenActionColId), m_action_colid);
	xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenCtidColId),
								 m_ctid_colid);
	xml_serializer->AddAttribute(
		CDXLTokens::GetDXLTokenStr(EdxltokenGpSegmentIdColId), m_segid_colid);

	xml_serializer->AddAttribute(
		CDXLTokens::GetDXLTokenStr(EdxltokenUpdatePreservesOids),
		m_preserve_oids);

	if (m_preserve_oids)
	{
		xml_serializer->AddAttribute(
			CDXLTokens::GetDXLTokenStr(EdxltokenTupleOidColId), m_tuple_oid);
	}

	dxlnode->SerializePropertiesToDXL(xml_serializer);

	// serialize project list
	(*dxlnode)[0]->SerializeToDXL(xml_serializer);

	// serialize physical child
	(*dxlnode)[1]->SerializeToDXL(xml_serializer);

	xml_serializer->CloseElement(
		CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name);
}

#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
//	@function:
//		CDXLPhysicalSplit::AssertValid
//
//	@doc:
//		Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLPhysicalSplit::AssertValid(const CDXLNode *dxlnode,
							   BOOL validate_children) const
{
	GPOS_ASSERT(2 == dxlnode->Arity());
	CDXLNode *child_dxlnode = (*dxlnode)[1];
	GPOS_ASSERT(EdxloptypePhysical ==
				child_dxlnode->GetOperator()->GetDXLOperatorType());

	if (validate_children)
	{
		child_dxlnode->GetOperator()->AssertValid(child_dxlnode,
												  validate_children);
	}
}

#endif	// GPOS_DEBUG

// EOF


text:
'use strict';

const debug = require('debug')('main:find');

const CouchError = require('../util/CouchError');
const { getUserGroups } = require('../util/groups');

const validateMethods = require('./validate');

const methods = {
  async findEntriesByRight(user, right, options) {
    debug('findEntriesByRight (%s, %s)', user, right);
    await this.open();
    options = options || {};
    const query = options.query || {};

    // Check options
    if (query.sort && !query.use_index) {
      throw new CouchError('query with sort must use index', 'bad argument');
    }

    right = right || 'read';

    user = validateMethods.userFromTokenAndRights(user, options.token, [right]);

    // First check if user has global right
    const hasGlobalRight = await validateMethods.checkGlobalRight(
      this,
      user,
      right,
    );

    query.selector = query.selector || {};
    query.selector['\\$type'] = 'entry';
    if (hasGlobalRight) {
      query.selector['\\$owners'] = undefined;
    } else {
      const userGroups = await getUserGroups(
        this,
        user,
        right,
        options.groups,
        options.mine,
      );
      query.selector['\\$owners'] = {
        $in: userGroups,
      };
    }

    if (options.stream) {
      return this._db.queryMangoStream(query);
    } else {
      return this._db.queryMango(query);
    }
  },
};

module.exports = { methods };


text:
#import "IoTDeviceEnumSelection.h"
#import "IoTDeviceEnumCell.h"

@interface IoTDeviceEnumSelection ()
{
    BOOL selected;
}

@property (nonatomic, strong) IoTDeviceEnumCell *cell;

@end

@implementation IoTDeviceEnumSelection

- (id)initWithEnumCell:(IoTDeviceEnumCell *)cell
{
    self = [super initWithStyle:UITableViewStylePlain];
    if(self)
    {
        self.cell = cell;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationItem.title = self.cell.title;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    selected = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if(selected && [self.cell.delegate respondsToSelector:@selector(IoTDeviceEnumDidSelectedValue:index:)])
        [self.cell.delegate IoTDeviceEnumDidSelectedValue:self.cell index:self.cell.index];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cell.values.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *enumIdentifier = @"enumCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:enumIdentifier];
    if(nil == cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:enumIdentifier];

    cell.textLabel.text = self.cell.values[indexPath.row];
    if(indexPath.row == self.cell.index)
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    else
        cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView selectRowAtIndexPath:nil animated:NO scrollPosition:UITableViewScrollPositionNone];

    NSInteger oldValue = self.cell.index;
    if(oldValue != indexPath.row)
    {
        self.cell.index = indexPath.row;
        NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:oldValue inSection:0];
        [tableView reloadRowsAtIndexPaths:@[oldIndexPath, indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }

    selected = YES;
    [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@YES afterDelay:0.2];
}

@end


text:
package net.prasenjit.identity.events;

import net.prasenjit.identity.entity.AuditEvent;
import net.prasenjit.identity.entity.ResourceType;
import org.springframework.context.ApplicationEvent;

import java.time.LocalDateTime;

public abstract class AbstractModificationEvent extends ApplicationEvent {
    private static final long serialVersionUID = -3909826132531495974L;
    protected final String id;
    protected final ResourceType type;

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     * @param type   type of the resource
     * @param id     identifier of the resource
     */
    AbstractModificationEvent(Object source, ResourceType type, String id) {
        super(source);
        this.type = type;
        this.id = id;
    }

    /**
     * Create a audit object to insert into audit table
     *
     * @return AuditEvent object
     */
    public AuditEvent createAudit() {
        AuditEvent audit = new AuditEvent();
        audit.setEventName(this.getClass().getSimpleName());
        audit.setEventTime(LocalDateTime.now());
        audit.setMessage(prepareMessage());
        audit.setDisplayLevel(1);
        audit.setResourceId(id);
        audit.setResourceType(type);
        return audit;
    }

    protected abstract String prepareMessage();

    String getUserType() {
        return type.name().toLowerCase();
    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>iScrum</title>
  <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/jquery-ui/jquery-ui.css">

      iScrum

Backlog

Sprint: {{sprint.title}}

 {{ sprint.begin | formatDate }} - {{ sprint.end | formatDate }}

Archive

Add sprint

          <input class="form-control" placeholder="example: sprint 123" v-model="newsprint.title">
          <input class="datepicker form-control" placeholder="begin(Y-m-d), example 2017-10-10" v-model="newsprint.begin">
          <input class="datepicker form-control" placeholder="end(Y-m-d), example 2017-10-20" v-model="newsprint.end">
          <button class="btn btn-primary" v-on:click="sprint_create">Save</button>

User Stories ({{stories.length }})

            {{{story.epic | epicFilter}}}

            <input type="checkbox" v-model="bind_stories" :value="story" />
            ISC-{{ story.id }}}

            {{ story.title }}
            {{story.points}}

            (x)

Danger zone

         <button class="btn btn-xs btn-danger" v-on:click="sprint_delete(currentSprint)">Delete this sprint</button>

Add story

              <input class="form-control" placeholder="define a story" v-model="newstory.title">
              <input class="form-control" placeholder="epic" v-model="newstory.epic">
              <input class="form-control" placeholder="points" v-model="newstory.points">
              <button class="btn btn-primary" v-on:click="story_create">Save</button>

            Select sprint:
            <select v-on:change="select_sprint($event)" class="form-control">
                          <option :value="sprint.id" v-for="sprint in sprints">{{sprint.title}}</option>
                        </select>

          <input type="submit" class="btn btn-primary1" value="Add stories to sprint" v-on:click="btn_click_sprintstory_create" />
          <input type="submit" class="btn btn-primary1" value="Remove stories" v-on:click="btn_click_story_delete" />


text:
package org.apache.reef.runtime.common.driver.evaluator;

import org.apache.reef.annotations.audience.DriverSide;
import org.apache.reef.annotations.audience.Private;
import org.apache.reef.driver.catalog.NodeDescriptor;
import org.apache.reef.driver.evaluator.EvaluatorDescriptor;
import org.apache.reef.driver.evaluator.EvaluatorProcess;

import javax.inject.Inject;

/**
 * A simple all-data implementation of EvaluatorDescriptor.
 */
@Private
@DriverSide
public final class EvaluatorDescriptorImpl implements EvaluatorDescriptor {

  private final NodeDescriptor nodeDescriptor;
  private final int megaBytes;
  private final int numberOfCores;
  private EvaluatorProcess process;
  private final String runtimeName;

  private EvaluatorDescriptorImpl(
      final NodeDescriptor nodeDescriptor,
      final int megaBytes,
      final int numberOfCores,
      final EvaluatorProcess process,
      final String runtimeName) {
    this.nodeDescriptor = nodeDescriptor;
    this.megaBytes = megaBytes;
    this.numberOfCores = numberOfCores;
    this.process = process;
    this.runtimeName = runtimeName;
  }

  @Override
  public NodeDescriptor getNodeDescriptor() {
    return this.nodeDescriptor;
  }

  @Override
  public synchronized EvaluatorProcess getProcess() {
    if (null == this.process) {
      throw new IllegalArgumentException("EvaluatorProcess must be set");
    }
    return this.process;
  }

  public synchronized void setProcess(final EvaluatorProcess process) {
    this.process = process;
  }

  @Override
  public int getMemory() {
    return this.megaBytes;
  }

  @Override
  public int getNumberOfCores() {
    return this.numberOfCores;
  }

  @Override
  public String getRuntimeName() {
    return this.runtimeName;
  }

  /**
   * Evaluator descriptor builder factory that creates a  new evaluator descriptor builder impl.
   */
  static final class BuilderFactory implements EvaluatorDescriptorBuilderFactory {
    @Inject
    private BuilderFactory() {
    }

    @Override
    public EvaluatorDescriptorBuilder newBuilder() {
      return new Builder();
    }

    @Override
    public EvaluatorDescriptorBuilder newBuilder(final EvaluatorDescriptor copy) {
      return newBuilder()
          .setNodeDescriptor(copy.getNodeDescriptor())
          .setMemory(copy.getMemory())
          .setNumberOfCores(copy.getNumberOfCores())
          .setEvaluatorProcess(copy.getProcess())
          .setRuntimeName(copy.getRuntimeName());
    }
  }

  /**
   * An builder for this evaluator descriptor implementation.
   */
  private static final class Builder implements EvaluatorDescriptorBuilder {
    private NodeDescriptor nodeDescriptor = null;
    private int memory = 0;
    private int numberOfCores = 0;
    private EvaluatorProcess evaluatorProcess = null;
    private String runtimeName = null;

    @Override
    public Builder setNodeDescriptor(final NodeDescriptor nodeDescriptor) {
      this.nodeDescriptor = nodeDescriptor;
      return this;
    }

    @Override
    public Builder setMemory(final int megaBytes) {
      this.memory = megaBytes;
      return this;
    }

    @Override
    public Builder setNumberOfCores(final int numberOfCores) {
      this.numberOfCores = numberOfCores;
      return this;
    }

    @Override
    public Builder setEvaluatorProcess(final EvaluatorProcess evaluatorProcess) {
      this.evaluatorProcess = evaluatorProcess;
      return this;
    }

    @Override
    public Builder setRuntimeName(final String runtimeName) {
      this.runtimeName = runtimeName;
      return this;
    }

    @Override
    public EvaluatorDescriptor build() {
      if (this.memory == 0) {
        throw new IllegalArgumentException("memory not set");
      } else if (this.numberOfCores == 0) {
        throw new IllegalArgumentException("number of cores not set");
      }
      return new EvaluatorDescriptorImpl(
          this.nodeDescriptor,
          this.memory,
          this.numberOfCores,
          this.evaluatorProcess,
          this.runtimeName);
    }
  }
}


text:
import Ember from 'ember';

function flatten(array) {
  var flattened = [];
  for (let i = 0, len = array.length; i < len; i++) {
    let value = array[i];
    if (Ember.isArray(value)) {
      flattened.push(...flatten(value));
    } else {
      flattened.push(value);
    }
  }
  return flattened;
}

export default flatten;


text:
package android.support.v7.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.text.AllCapsTransformationMethod;
import android.util.AttributeSet;
import android.widget.TextView;

import com.yc.androidsupportlibrary.R;

class AppCompatTextHelper {

    static AppCompatTextHelper create(TextView textView) {
        if (Build.VERSION.SDK_INT >= 17) {
            return new AppCompatTextHelperV17(textView);
        }
        return new AppCompatTextHelper(textView);
    }

    private static final int[] VIEW_ATTRS = {android.R.attr.textAppearance,
            android.R.attr.drawableLeft, android.R.attr.drawableTop,
            android.R.attr.drawableRight, android.R.attr.drawableBottom };
    private static final int[] TEXT_APPEARANCE_ATTRS = {R.attr.textAllCaps};

    final TextView mView;

    private TintInfo mDrawableLeftTint;
    private TintInfo mDrawableTopTint;
    private TintInfo mDrawableRightTint;
    private TintInfo mDrawableBottomTint;

    AppCompatTextHelper(TextView view) {
        mView = view;
    }

    void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {
        final Context context = mView.getContext();
        final TintManager tintManager = TintManager.get(context);

        // First read the TextAppearance style id
        TypedArray a = context.obtainStyledAttributes(attrs, VIEW_ATTRS, defStyleAttr, 0);
        final int ap = a.getResourceId(0, -1);

        // Now read the compound drawable and grab any tints
        if (a.hasValue(1)) {
            mDrawableLeftTint = createTintInfo(context, tintManager, a.getResourceId(1, 0));
        }
        if (a.hasValue(2)) {
            mDrawableTopTint = createTintInfo(context, tintManager, a.getResourceId(2, 0));
        }
        if (a.hasValue(3)) {
            mDrawableRightTint = createTintInfo(context, tintManager, a.getResourceId(3, 0));
        }
        if (a.hasValue(4)) {
            mDrawableBottomTint = createTintInfo(context, tintManager, a.getResourceId(4, 0));
        }
        a.recycle();

        // Now check TextAppearance's textAllCaps value
        if (ap != -1) {
            TypedArray appearance = context.obtainStyledAttributes(ap, R.styleable.TextAppearance);
            if (appearance.hasValue(R.styleable.TextAppearance_textAllCaps)) {
                setAllCaps(appearance.getBoolean(R.styleable.TextAppearance_textAllCaps, false));
            }
            appearance.recycle();
        }

        // Now read the style's value
        a = context.obtainStyledAttributes(attrs, TEXT_APPEARANCE_ATTRS, defStyleAttr, 0);
        if (a.getBoolean(0, false)) {
            setAllCaps(true);
        }
        a.recycle();
    }

    void onSetTextAppearance(Context context, int resId) {
        TypedArray appearance = context.obtainStyledAttributes(resId, TEXT_APPEARANCE_ATTRS);
        if (appearance.hasValue(0)) {
            setAllCaps(appearance.getBoolean(0, false));
        }
        appearance.recycle();
    }

    void setAllCaps(boolean allCaps) {
        mView.setTransformationMethod(allCaps
                ? new AllCapsTransformationMethod(mView.getContext())
                : null);
    }

    void applyCompoundDrawablesTints() {
        if (mDrawableLeftTint != null || mDrawableTopTint != null ||
                mDrawableRightTint != null || mDrawableBottomTint != null) {
            final Drawable[] compoundDrawables = mView.getCompoundDrawables();
            applyCompoundDrawableTint(compoundDrawables[0], mDrawableLeftTint);
            applyCompoundDrawableTint(compoundDrawables[1], mDrawableTopTint);
            applyCompoundDrawableTint(compoundDrawables[2], mDrawableRightTint);
            applyCompoundDrawableTint(compoundDrawables[3], mDrawableBottomTint);
        }
    }

    final void applyCompoundDrawableTint(Drawable drawable, TintInfo info) {
        if (drawable != null && info != null) {
            TintManager.tintDrawable(drawable, info, mView.getDrawableState());
        }
    }

    protected static TintInfo createTintInfo(Context context,
            TintManager tintManager, int drawableId) {
        final ColorStateList tintList = tintManager.getTintList(drawableId);
        if (tintList != null) {
            final TintInfo tintInfo = new TintInfo();
            tintInfo.mHasTintList = true;
            tintInfo.mTintList = tintList;
        }
        return null;
    }
}


text:
/**
 *
 */
package co.sabi11.interfaces.implementation;

import co.sabi11.classes.GarageDoor;
import co.sabi11.interfaces.Command;

/**
 * @author Sabi
 *
 */
public class GarageDoorDownCommand implements Command {

	// Init
	GarageDoor garageDoor;

	/**
	 *
	 */
	public GarageDoorDownCommand(GarageDoor garageDoor) {
		this.garageDoor = garageDoor;
	}

	@Override
	public void execute() {

		garageDoor.down();
	}

}


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Component\Server\Event\InitialAccessToken;

use OAuth2Framework\Component\Server\Model\Event\Event;
use OAuth2Framework\Component\Server\Model\Event\EventId;
use OAuth2Framework\Component\Server\Model\Id\Id;
use OAuth2Framework\Component\Server\Model\InitialAccessToken\InitialAccessTokenId;
use OAuth2Framework\Component\Server\Model\UserAccount\UserAccountId;
use OAuth2Framework\Component\Server\Schema\DomainObjectInterface;

final class InitialAccessTokenCreatedEvent extends Event
{
    /**
     * @var InitialAccessTokenId
     */
    private $initialAccessTokenId;

    /**
     * @var \DateTimeImmutable
     */
    private $expiresAt;

    /**
     * @var UserAccountId|null
     */
    private $userAccountId;

    /**
     * InitialAccessTokenCreatedEvent constructor.
     *
     * @param InitialAccessTokenId    $initialAccessTokenId
     * @param null|\DateTimeImmutable $expiresAt
     * @param UserAccountId|null      $userAccountId
     * @param \DateTimeImmutable|null $recordedOn
     * @param EventId|null            $eventId
     */
    protected function __construct(InitialAccessTokenId $initialAccessTokenId, ? UserAccountId $userAccountId, ? \DateTimeImmutable $expiresAt, ? \DateTimeImmutable $recordedOn, ? EventId $eventId)
    {
        parent::__construct($recordedOn, $eventId);
        $this->initialAccessTokenId = $initialAccessTokenId;
        $this->expiresAt = $expiresAt;
        $this->userAccountId = $userAccountId;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSchema(): string
    {
        return 'https://oauth2-framework.spomky-labs.com/schemas/events/initial-access-token/created/1.0/schema';
    }

    /**
     * @param InitialAccessTokenId    $initialAccessTokenId
     * @param null|\DateTimeImmutable $expiresAt
     * @param UserAccountId|null      $userAccountId
     *
     * @return InitialAccessTokenCreatedEvent
     */
    public static function create(InitialAccessTokenId $initialAccessTokenId, ? UserAccountId $userAccountId, ? \DateTimeImmutable $expiresAt): InitialAccessTokenCreatedEvent
    {
        return new self($initialAccessTokenId, $userAccountId, $expiresAt, null, null);
    }

    /**
     * @return InitialAccessTokenId
     */
    public function getInitialAccessTokenId(): InitialAccessTokenId
    {
        return $this->initialAccessTokenId;
    }

    /**
     * @return \DateTimeImmutable
     */
    public function getExpiresAt(): \DateTimeImmutable
    {
        return $this->expiresAt;
    }

    /**
     * @return null|UserAccountId
     */
    public function getUserAccountId()
    {
        return $this->userAccountId;
    }

    /**
     * {@inheritdoc}
     */
    public function getDomainId(): Id
    {
        return $this->getInitialAccessTokenId();
    }

    /**
     * {@inheritdoc}
     */
    public function getPayload()
    {
        return (object) [
            'user_account_id' => $this->userAccountId ? $this->userAccountId->getValue() : null,
            'expires_at' => $this->expiresAt ? $this->expiresAt->getTimestamp() : null,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function createFromJson(\stdClass $json): DomainObjectInterface
    {
        $initialAccessTokenId = InitialAccessTokenId::create($json->domain_id);
        $eventId = EventId::create($json->event_id);
        $recordedOn = \DateTimeImmutable::createFromFormat('U', (string) $json->recorded_on);

        $userAccountId = null === $json->payload->user_account_id ? null : UserAccountId::create($json->payload->user_account_id);
        $expiresAt = null === $json->payload->expires_at ? null : \DateTimeImmutable::createFromFormat('U', (string) $json->payload->expires_at);

        return new self(
            $initialAccessTokenId,
            $userAccountId,
            $expiresAt,
            $recordedOn,
            $eventId
        );
    }
}


text:
package com.ritesh.zstreamingquote.db;

import com.ritesh.zstreamingquote.config.ZStreamingConfig;

public class StreamingQuoteStorageFactory {

	/**
	 * getStreamingQuoteStorage - StreamingQuoteStorage Instance provider factory
	 * @return StreamingQuoteStorage Instance
	 */
	public static IStreamingQuoteStorage getStreamingQuoteStorage(){
		IStreamingQuoteStorage streamingQuoteStorage = null;

		if(ZStreamingConfig.getStreamingQuoteMode().equals(ZStreamingConfig.QUOTE_STREAMING_MODE_LTP)){
			streamingQuoteStorage = new StreamingQuoteDAOModeLtp();
		} else if(ZStreamingConfig.getStreamingQuoteMode().equals(ZStreamingConfig.QUOTE_STREAMING_MODE_QUOTE)){
			streamingQuoteStorage = new StreamingQuoteDAOModeQuote();
		} else if(ZStreamingConfig.getStreamingQuoteMode().equals(ZStreamingConfig.QUOTE_STREAMING_MODE_FULL)){
			streamingQuoteStorage = new StreamingQuoteDAOModeFull();
		} else{
			System.out.println("StreamingQuoteStorageFactory.getStreamingQuoteStorage(): ERROR: " +
					"Current DB storage type not supported for Quote type [" + ZStreamingConfig.getStreamingQuoteMode() + "]");
		}

		return streamingQuoteStorage;
	}
}