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

namespace Google\Cloud\Dialogflow\V2\HumanAgentHandoffConfig;

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

/**
 * Configuration specific to Salesforce Live Agent.
 *
 * Generated from protobuf message google.cloud.dialogflow.v2.HumanAgentHandoffConfig.SalesforceLiveAgentConfig
 */
class SalesforceLiveAgentConfig extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The organization ID of the Salesforce account.
     *
     * Generated from protobuf field string organization_id = 1 [(.google.api.field_behavior) = REQUIRED];
     */
    private $organization_id = '';
    /**
     * Required. Live Agent deployment ID.
     *
     * Generated from protobuf field string deployment_id = 2 [(.google.api.field_behavior) = REQUIRED];
     */
    private $deployment_id = '';
    /**
     * Required. Live Agent chat button ID.
     *
     * Generated from protobuf field string button_id = 3 [(.google.api.field_behavior) = REQUIRED];
     */
    private $button_id = '';
    /**
     * Required. Domain of the Live Agent endpoint for this agent. You can find
     * the endpoint URL in the `Live Agent settings` page. For example if URL
     * has the form https://d.la4-c2-phx.salesforceliveagent.com/...,
     * you should fill in d.la4-c2-phx.salesforceliveagent.com.
     *
     * Generated from protobuf field string endpoint_domain = 4 [(.google.api.field_behavior) = REQUIRED];
     */
    private $endpoint_domain = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $organization_id
     *           Required. The organization ID of the Salesforce account.
     *     @type string $deployment_id
     *           Required. Live Agent deployment ID.
     *     @type string $button_id
     *           Required. Live Agent chat button ID.
     *     @type string $endpoint_domain
     *           Required. Domain of the Live Agent endpoint for this agent. You can find
     *           the endpoint URL in the `Live Agent settings` page. For example if URL
     *           has the form https://d.la4-c2-phx.salesforceliveagent.com/...,
     *           you should fill in d.la4-c2-phx.salesforceliveagent.com.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Dialogflow\V2\ConversationProfile::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The organization ID of the Salesforce account.
     *
     * Generated from protobuf field string organization_id = 1 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getOrganizationId()
    {
        return $this->organization_id;
    }

    /**
     * Required. The organization ID of the Salesforce account.
     *
     * Generated from protobuf field string organization_id = 1 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setOrganizationId($var)
    {
        GPBUtil::checkString($var, True);
        $this->organization_id = $var;

        return $this;
    }

    /**
     * Required. Live Agent deployment ID.
     *
     * Generated from protobuf field string deployment_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getDeploymentId()
    {
        return $this->deployment_id;
    }

    /**
     * Required. Live Agent deployment ID.
     *
     * Generated from protobuf field string deployment_id = 2 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setDeploymentId($var)
    {
        GPBUtil::checkString($var, True);
        $this->deployment_id = $var;

        return $this;
    }

    /**
     * Required. Live Agent chat button ID.
     *
     * Generated from protobuf field string button_id = 3 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getButtonId()
    {
        return $this->button_id;
    }

    /**
     * Required. Live Agent chat button ID.
     *
     * Generated from protobuf field string button_id = 3 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setButtonId($var)
    {
        GPBUtil::checkString($var, True);
        $this->button_id = $var;

        return $this;
    }

    /**
     * Required. Domain of the Live Agent endpoint for this agent. You can find
     * the endpoint URL in the `Live Agent settings` page. For example if URL
     * has the form https://d.la4-c2-phx.salesforceliveagent.com/...,
     * you should fill in d.la4-c2-phx.salesforceliveagent.com.
     *
     * Generated from protobuf field string endpoint_domain = 4 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getEndpointDomain()
    {
        return $this->endpoint_domain;
    }

    /**
     * Required. Domain of the Live Agent endpoint for this agent. You can find
     * the endpoint URL in the `Live Agent settings` page. For example if URL
     * has the form https://d.la4-c2-phx.salesforceliveagent.com/...,
     * you should fill in d.la4-c2-phx.salesforceliveagent.com.
     *
     * Generated from protobuf field string endpoint_domain = 4 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setEndpointDomain($var)
    {
        GPBUtil::checkString($var, True);
        $this->endpoint_domain = $var;

        return $this;
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SalesforceLiveAgentConfig::class, \Google\Cloud\Dialogflow\V2\HumanAgentHandoffConfig_SalesforceLiveAgentConfig::class);


text:
from google.cloud import language_v1

def sample_analyze_syntax():
    # Create a client
    client = language_v1.LanguageServiceClient()

    # Initialize request argument(s)
    document = language_v1.Document()
    document.content = "content_value"

    request = language_v1.AnalyzeSyntaxRequest(
        document=document,
    )

    # Make the request
    response = client.analyze_syntax(request=request)

    # Handle the response
    print(response)

# [END language_v1_generated_LanguageService_AnalyzeSyntax_sync]

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.trigital.cm</groupId>
	<artifactId>Trigital-Api</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>TrigitalApi</name>
	<description>TrigitalApi</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.0.RELEASE</version>
	</parent>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.hsqldb</groupId>
				<artifactId>hsqldb</artifactId>
				<version>2.3.2</version>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jersey</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.4.5</version>
		</dependency>
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path</artifactId>
		</dependency>
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path-assert</artifactId>
			<version>0.9.1</version>
		</dependency>
		<dependency>
			<groupId>com.mangofactory</groupId>
			<artifactId>swagger-springmvc</artifactId>
			<version>0.8.5</version>
		</dependency>
	</dependencies>
</project>


text:
#popupMask {
	display:none;
	position:absolute;
	top:0;
	left:0;
	width:100%;
	height:100%;
	z-index:200;
	background-color:#000;
	-moz-opacity: 0.7;
	opacity:.70;
	filter: alpha(opacity=70);
}
#popupContainer {
	position: absolute;
	z-index: 201;
	top: 0px;
	left: 0px;
	display:none;
	padding: 0px;
	text-align:center;
	overflow:hidden;
	margin:0px;
}
#popupInner {
	border: 0px;
	background-color: #FFFFFF;
	overflow:hidden;
}
#popupFrame {
	margin: 0px;
	padding:0px;
	width: 100%;
	height: 100%;
	position: relative;
	z-index: 202;
	overflow:hidden;
}
* html #popupFrame {
	margin-top: -35px;
}
#popupTitleBar, #popupTitle, #popupControls, #popupControls a span {
	visibility:hidden;
	height:0px;
	top: -1000px;
	left: -1000px;
}
/*#popupTitle {
	visibility:hidden;
}
#popupControls {
	visibility:hidden;
}
#popupControls a span {
	visibility:hidden;
}*/


text:
package org.wso2.carbon.metrics.core.impl;

import org.wso2.carbon.metrics.core.Snapshot;

/**
 * Implementation class wrapping {@link com.codahale.metrics.Snapshot} for sampling metrics
 */
public class SnapshotImpl implements Snapshot {

    private final com.codahale.metrics.Snapshot snapshot;

    public SnapshotImpl(com.codahale.metrics.Snapshot snapshot) {
        this.snapshot = snapshot;
    }

    @Override
    public double getStdDev() {
        return snapshot.getStdDev();
    }

    @Override
    public double getValue(double quantile) {
        return snapshot.getValue(quantile);
    }

    @Override
    public long[] getValues() {
        return snapshot.getValues();
    }

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

    @Override
    public double getMedian() {
        return snapshot.getMedian();
    }

    @Override
    public double get75thPercentile() {
        return snapshot.get75thPercentile();
    }

    @Override
    public double get95thPercentile() {
        return snapshot.get95thPercentile();
    }

    @Override
    public double get98thPercentile() {
        return snapshot.get98thPercentile();
    }

    @Override
    public double get99thPercentile() {
        return snapshot.get99thPercentile();
    }

    @Override
    public double get999thPercentile() {
        return snapshot.get999thPercentile();
    }

    @Override
    public long getMax() {
        return snapshot.getMax();
    }

    @Override
    public double getMean() {
        return snapshot.getMean();
    }

    @Override
    public long getMin() {
        return snapshot.getMin();
    }
}


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

namespace CvrService.Service.ADMIN.CvrService {

    public partial class PropertiesPage {

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

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

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

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

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

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

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

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

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


text:
require 'spree_core'
require 'spree_brightpearl/engine'


text:
import sys

import petsc4py

petsc4py.init(sys.argv)

import numpy as np
# import pickle
# from time import time
# from scipy.io import loadmat
from src.stokes_flow import problem_dic, obj_dic
from src.geo import *
from petsc4py import PETSc
# from src import stokes_flow as sf
from src.myio import *
from src.objComposite import *
# from src.myvtk import *
# from src.support_class import *
from codeStore.helix_common import *

def get_problem_kwargs(**main_kwargs):
    problem_kwargs = get_solver_kwargs()

    kwargs_list = (get_vtk_tetra_kwargs(), get_ecoli_kwargs(), get_forcefree_kwargs(), main_kwargs,)
    for t_kwargs in kwargs_list:
        for key in t_kwargs:
            problem_kwargs[key] = t_kwargs[key]
    return problem_kwargs

def print_case_info(caseIntro='-->(some introduce here)', **problem_kwargs):
    fileHandle = problem_kwargs['fileHandle']
    PETSc.Sys.Print(caseIntro)
    print_solver_info(**problem_kwargs)
    print_forcefree_info(**problem_kwargs)
    print_ecoli_info(fileHandle, **problem_kwargs)
    return True

# @profile
def main_fun(**main_kwargs):
    OptDB = PETSc.Options()
    fileHandle = OptDB.getString('f', 'tail_U')
    OptDB.setValue('f', fileHandle)
    main_kwargs['fileHandle'] = fileHandle
    field_range = np.array([[-3, -3, -3], [3, 3, 3]])
    n_grid = np.array([1, 1, 1]) * OptDB.getInt('n_grid', 10)
    main_kwargs['field_range'] = field_range
    main_kwargs['n_grid'] = n_grid
    main_kwargs['region_type'] = 'rectangle'
    problem_kwargs = get_problem_kwargs(**main_kwargs)
    matrix_method = problem_kwargs['matrix_method']
    pickProblem = problem_kwargs['pickProblem']
    fileHandle = problem_kwargs['fileHandle']
    save_vtk = problem_kwargs['save_vtk']
    center = problem_kwargs['center']
    #

    rs1 = problem_kwargs['rs1']
    rs2 = problem_kwargs['rs2']
    assert rs1 == rs2
    ls = problem_kwargs['ls']
    es = problem_kwargs['es']
    zoom_factor = problem_kwargs['zoom_factor']
    ds = problem_kwargs['ds']

    if not problem_kwargs['restart']:
        print_case_info(**problem_kwargs)
        tail_obj_list = create_ecoli_tail(moveh=np.zeros(3), **problem_kwargs)
        # add a pipe inside the helical tail.
        vsobj = obj_dic[matrix_method]()
        vsgeo = tunnel_geo()
        dth = ds / rs1
        fsgeo = vsgeo.create_deltatheta(dth, rs1, ls, es, 1, 1, True)
        vsobj.set_data(fsgeo, vsgeo, name='sphere_0')
        vsobj.zoom(zoom_factor)

        # with pipe at center
        problem = problem_dic[matrix_method](**problem_kwargs)
        for tobj in tail_obj_list:
            problem.add_obj(tobj)
        problem.add_obj(vsobj)
        # problem.show_u_nodes(linestyle='')
        # assert 1 == 2
        if pickProblem:
            problem.pickmyself('%s_tran' % fileHandle, ifcheck=True)
        problem.print_info()
        problem.create_matrix()
        # AtBtCt_full(problem, save_vtk=False, pick_M=False, print_each=False,
        #             center=center)
        # translation
        for tobj in tail_obj_list:
            tobj.set_rigid_velocity(np.array((0, 0, 1, 0, 0, 0)))
        problem.create_F_U()
        problem.solve()
        tres = np.sum([tobj.get_total_force() for tobj in tail_obj_list], axis=0)
        PETSc.Sys.Print('-->>At')
        PETSc.Sys.Print(tres[:3])
        PETSc.Sys.Print('-->>Bt1')
        PETSc.Sys.Print(tres[3:])
        # rotation
        for tobj in tail_obj_list:
            tobj.set_rigid_velocity(np.array((0, 0, 0, 0, 0, 1)))
        problem.create_F_U()
        problem.solve()
        tres = np.sum([tobj.get_total_force() for tobj in tail_obj_list], axis=0)
        PETSc.Sys.Print('-->>Bt2')
        PETSc.Sys.Print(tres[:3])
        PETSc.Sys.Print('-->>Ct')
        PETSc.Sys.Print(tres[3:])

        # without pipe at center
        problem = problem_dic[matrix_method](**problem_kwargs)
        for tobj in tail_obj_list:
            problem.add_obj(tobj)
        if pickProblem:
            problem.pickmyself('%s_tran' % fileHandle, ifcheck=True)
        problem.print_info()
        problem.create_matrix()
        # AtBtCt_full(problem, save_vtk=False, pick_M=False, print_each=False,
        #             center=center)
        # translation
        for tobj in tail_obj_list:
            tobj.set_rigid_velocity(np.array((0, 0, 1, 0, 0, 0)))
        problem.create_F_U()
        problem.solve()
        tres = np.sum([tobj.get_total_force() for tobj in tail_obj_list], axis=0)
        PETSc.Sys.Print('-->>At')
        PETSc.Sys.Print(tres[:3])
        PETSc.Sys.Print('-->>Bt1')
        PETSc.Sys.Print(tres[3:])
        # rotation
        for tobj in tail_obj_list:
            tobj.set_rigid_velocity(np.array((0, 0, 0, 0, 0, 1)))
        problem.create_F_U()
        problem.solve()
        tres = np.sum([tobj.get_total_force() for tobj in tail_obj_list], axis=0)
        PETSc.Sys.Print('-->>Bt2')
        PETSc.Sys.Print(tres[:3])
        PETSc.Sys.Print('-->>Ct')
        PETSc.Sys.Print(tres[3:])
    return True

if __name__ == '__main__':
    OptDB = PETSc.Options()
    # if OptDB.getBool('self_repeat_tail', False):
    #     OptDB.setValue('main_fun', False)
    #     self_repeat_tail()
    #
    # if OptDB.getBool('main_fun', True):
    #     main_fun()

    # matrix_method = OptDB.getString('sm', 'rs_stokeslets')
    # assert matrix_method in ('pf', 'pf_selfRepeat', 'pf_selfRotate')
    # if matrix_method == 'pf_selfRepeat':
    #     self_repeat_tail()
    # if matrix_method == 'pf_selfRotate':
    #     self_rotate_tail()
    # elif matrix_method == 'pf':
    #     main_fun()
    main_fun()


text:
<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Warehouses Controller
 *
 * @property \App\Model\Table\WarehousesTable $Warehouses
 */
class WarehousesController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $warehouses = $this->paginate($this->Warehouses);

        $this->set(compact('warehouses'));
        $this->set('_serialize', ['warehouses']);
    }

    /**
     * View method
     *
     * @param string|null $id Warehouse id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $warehouse = $this->Warehouses->get($id, [
            'contain' => ['Inventories', 'Machines']
        ]);

        $this->set('warehouse', $warehouse);
        $this->set('_serialize', ['warehouse']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $warehouse = $this->Warehouses->newEntity();
        if ($this->request->is('post')) {
            $warehouse = $this->Warehouses->patchEntity($warehouse, $this->request->data);
            if ($this->Warehouses->save($warehouse)) {
                $this->Flash->success(__('The warehouse has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The warehouse could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('warehouse'));
        $this->set('_serialize', ['warehouse']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Warehouse id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $warehouse = $this->Warehouses->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $warehouse = $this->Warehouses->patchEntity($warehouse, $this->request->data);
            if ($this->Warehouses->save($warehouse)) {
                $this->Flash->success(__('The warehouse has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The warehouse could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('warehouse'));
        $this->set('_serialize', ['warehouse']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Warehouse id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $warehouse = $this->Warehouses->get($id);
        if ($this->Warehouses->delete($warehouse)) {
            $this->Flash->success(__('The warehouse has been deleted.'));
        } else {
            $this->Flash->error(__('The warehouse could not be deleted. Please, try again.'));
        }
        return $this->redirect(['action' => 'index']);
    }

    public function isAuthorized($user = null) {

    	if (in_array($this->request['action'], ['index', 'view']))
    		return true;
    	else
    		return parent::isAuthorized($user);
    }
}


text:
<?php

add_action('init', 'cfx_check_version', 5);
add_action('admin_init', 'cfx_check_dependency', 5);

function cfx_check_version(){
  if ( version_compare( phpversion(), '5.3', '<' ) ) {
    cfx_deactivate_plugin();
    add_action('admin_notices', 'cfx_notice_require_php');
    return false;
  }
  return true;
}

function cfx_check_dependency(){
  if(! file_exists( __DIR__ . '/../' . CFX_CALDERA_COREPATH) ){
    cfx_deactivate_plugin();
    add_action('admin_notices', 'cfx_notice_require_caldera_installed');
    return false;
  }
  if ( function_exists('is_plugin_active') and !is_plugin_active(CFX_CALDERA_COREPATH) ){
    cfx_deactivate_plugin();
    add_action('admin_notices', 'cfx_notice_require_caldera_activate');
    return false;
  }
  return true;
}

function cfx_deactivate_plugin(){
  $plugins = get_option( 'active_plugins' );
  if (($k = array_search( CFX_PLUGIN_COREPATH, $plugins)) !== false){
    unset( $plugins[$k] );
    update_option( 'active_plugins', $plugins );
  }
}

function cfx_caldera_loaded(){
  return class_exists('Caldera_Forms');
}

function cfx_notice_require_php(){
  echo '

' . CFX_PLUGIN_NAME . ' requires PHP 5.3 or higher!' . '

';
}

function cfx_notice_require_caldera_installed(){
  echo '

' . CFX_PLUGIN_NAME . ' requires Caldera Forms installed' . '

';
}

function cfx_notice_require_caldera_activate(){
  echo '

' . CFX_PLUGIN_NAME . ' requires Caldera Forms activated' . '

';
}


text:
import {
  DEFAULT_SCORE_CONFIG,
  SubscriptionsScoreFactor,
} from './score-factors.js';
import {Deferred} from '../../../src/utils/promise';
import {Entitlement} from './entitlement';
import {Observable} from '../../../src/observable';
import {devAssert, user} from '../../../src/log';
import {dict, hasOwn} from '../../../src/utils/object';

/** @typedef {{serviceId: string, entitlement: (!./entitlement.Entitlement|undefined)}} */
export let EntitlementChangeEventDef;

/** @const */
const TAG = 'amp-subscriptions';

/**
 * @typedef {{
 *   platform: !./subscription-platform.SubscriptionPlatform,
 *   weight: number,
 * }}
 */
let PlatformWeightDef;

export class PlatformStore {
  /**
   * @param {!Array<string>} expectedServiceIds
   * @param {!JsonObject|Object<string, number>} scoreConfig
   * @param {!./entitlement.Entitlement} fallbackEntitlement
   * @param {Object<string, !./subscription-platform.SubscriptionPlatform>=} opt_Platforms
   */
  constructor(
    expectedServiceIds,
    scoreConfig,
    fallbackEntitlement,
    opt_Platforms
  ) {
    /** @private @const {!Object<string, !./subscription-platform.SubscriptionPlatform>} */
    this.subscriptionPlatforms_ = opt_Platforms || dict();

    /** @private @const {!Array<string>} */
    this.serviceIds_ = expectedServiceIds;

    /** @private @const {!Object<string, !./entitlement.Entitlement>} */
    this.entitlements_ = {};

    /**
     * @private @const
     * {!Object<string, !Deferred<!./entitlement.Entitlement>>}
     */
    this.entitlementDeferredMap_ = {};
    expectedServiceIds.forEach(serviceId => {
      this.entitlementDeferredMap_[serviceId] = new Deferred();
    });

    /** @private @const {!Observable<!EntitlementChangeEventDef>} */
    this.onEntitlementResolvedCallbacks_ = new Observable();

    /** @private @const {!Observable<{serviceId: string}>} */
    this.onPlatformResolvedCallbacks_ = new Observable();

    /** @private {?Deferred} */
    this.grantStatusPromise_ = null;

    /** @private {?Entitlement} */
    this.grantStatusEntitlement_ = null;

    /** @private {?Deferred<?Entitlement>} */
    this.grantStatusEntitlementPromise_ = null;

    /** @private {?Deferred<!Array<!./entitlement.Entitlement>>} */
    this.allResolvedPromise_ = null;

    /** @private {!Array<string>} */
    this.failedPlatforms_ = [];

    /** @private @const {!./entitlement.Entitlement} */
    this.fallbackEntitlement_ = fallbackEntitlement;

    /** @private @const {!Object<string, number>} */
    this.scoreConfig_ = Object.assign(DEFAULT_SCORE_CONFIG, scoreConfig);
  }

  /**
   * Resolves a platform in the store
   * @param {string} serviceId
   * @param {!./subscription-platform.SubscriptionPlatform} platform
   */
  resolvePlatform(serviceId, platform) {
    this.subscriptionPlatforms_[serviceId] = platform;
    this.onPlatformResolvedCallbacks_.fire({
      serviceId,
    });
  }

  /**
   * Reset the platformStore via a factory that returns a
   * new PlatformStore with the same platforms as this one.
   * @return {PlatformStore}
   */
  resetPlatformStore() {
    // Reset individual platforms to ensure their UX clears.
    for (const platformKey in this.subscriptionPlatforms_) {
      this.subscriptionPlatforms_[platformKey].reset();
    }
    // Then create new platform store withe the newply reset platforms in it.
    return new PlatformStore(
      this.serviceIds_,
      this.scoreConfig_,
      this.fallbackEntitlement_,
      this.subscriptionPlatforms_
    );
  }

  /**
   *Calls a callback for when a platform is resolved.
   * @param {string} serviceId
   * @param {!Function} callback
   */
  onPlatformResolves(serviceId, callback) {
    const platform = this.subscriptionPlatforms_[serviceId];
    if (platform) {
      callback(platform);
    } else {
      this.onPlatformResolvedCallbacks_.add(e => {
        if (e.serviceId === serviceId) {
          callback(this.getPlatform(serviceId));
        }
      });
    }
  }

  /**
   * Returns the platform for the given id
   * @param {string} serviceId
   * @return {!./subscription-platform.SubscriptionPlatform}
   */
  getPlatform(serviceId) {
    const platform = this.subscriptionPlatforms_[serviceId];
    devAssert(platform, `Platform for id ${serviceId} is not resolved`);
    return platform;
  }

  /**
   * Returns the local platform
   * @return {!./subscription-platform.SubscriptionPlatform}
   */
  getLocalPlatform() {
    const localPlatform =
      /** @type {!./subscription-platform.SubscriptionPlatform} */
      (this.getPlatform('local'));
    return localPlatform;
  }

  /**
   * Returns all available platforms.
   *
   * @return {!Array<!./subscription-platform.SubscriptionPlatform>}
   */
  getAvailablePlatforms() {
    const platforms = [];
    for (const platformKey in this.subscriptionPlatforms_) {
      const subscriptionPlatform = this.subscriptionPlatforms_[platformKey];
      platforms.push(subscriptionPlatform);
    }
    return platforms;
  }

  /**
   * This registers a callback which is called whenever a service id is resolved
   * with an entitlement.
   * @param {function(!EntitlementChangeEventDef):void} callback
   */
  onChange(callback) {
    this.onEntitlementResolvedCallbacks_.add(callback);
  }

  /**
   * This resolves the entitlement to a serviceId
   * @param {string} serviceId
   * @param {!./entitlement.Entitlement} entitlement
   */
  resolveEntitlement(serviceId, entitlement) {
    if (entitlement) {
      entitlement.service = serviceId;
    }
    this.entitlements_[serviceId] = entitlement;
    const deferred = this.entitlementDeferredMap_[serviceId];
    if (deferred) {
      deferred.resolve(entitlement);
    }
    // Remove this serviceId as a failed platform now
    if (this.failedPlatforms_.indexOf(serviceId) != -1) {
      this.failedPlatforms_.splice(this.failedPlatforms_.indexOf(serviceId));
    }
    // Call all onChange callbacks.
    if (entitlement.granted) {
      this.saveGrantEntitlement_(entitlement);
    }
    this.onEntitlementResolvedCallbacks_.fire({serviceId, entitlement});
  }

  /**
   * Returns entitlement for a platform.
   * @param {string} serviceId
   * @return {!./entitlement.Entitlement} entitlement
   */
  getResolvedEntitlementFor(serviceId) {
    devAssert(
      this.entitlements_[serviceId],
      `Platform ${serviceId} has not yet resolved with entitlements`
    );
    return this.entitlements_[serviceId];
  }

  /**
   * Returns entitlement for a platform once it's resolved.
   * @param {string} serviceId
   * @return {!Promise<!./entitlement.Entitlement>} entitlement
   */
  getEntitlementPromiseFor(serviceId) {
    devAssert(
      this.entitlementDeferredMap_[serviceId],
      `Platform ${serviceId} is not declared`
    );
    return this.entitlementDeferredMap_[serviceId].promise;
  }

  /**
   * Get scoreFactor states for each platform
   * @return {!Promise<!JsonObject>}
   *
   * return value looks somethinglike this
   * {
   *   'subscribe.google.com': {
   *     isReadyToPay: 1,
   *     supportsViewer: 1,
   *   },
   *   local: {
   *     isReadyToPay: 0,
   *     supportsViewer: 0,
   *   },
   * }
   */
  getScoreFactorStates() {
    const states = dict({});
    return Promise.all(
      this.serviceIds_.map(platformId => {
        states[platformId] = dict();
        return Promise.all(
          Object.values(SubscriptionsScoreFactor).map(scoreFactor =>
            this.getScoreFactorPromiseFor_(platformId, scoreFactor).then(
              factorValue => {
                states[platformId][scoreFactor] = factorValue;
              }
            )
          )
        );
      })
    ).then(() => states);
  }

  /**
   * Return a score factor for a platform once it's resolved
   * @param {string} serviceId
   * @param {string} scoreFactor
   * @return {!Promise<number>}
   * @private
   */
  getScoreFactorPromiseFor_(serviceId, scoreFactor) {
    // Make sure the platform is ready
    return this.getEntitlementPromiseFor(serviceId).then(() => {
      return this.subscriptionPlatforms_[serviceId].getSupportedScoreFactor(
        scoreFactor
      );
    });
  }

  /**
   * @return {!Promise<boolean>}
   */
  getGrantStatus() {
    if (this.grantStatusPromise_ !== null) {
      return this.grantStatusPromise_.promise;
    }

    this.grantStatusPromise_ = new Deferred();

    // Check if current entitlements unblock the reader
    for (const key in this.entitlements_) {
      const entitlement = this.entitlements_[key];
      if (entitlement.granted) {
        this.saveGrantEntitlement_(entitlement);
        this.grantStatusPromise_.resolve(true);
      }
    }

    if (this.areAllPlatformsResolved_()) {
      // Resolve with null if none of the entitlements unblock the reader
      this.grantStatusPromise_.resolve(false);
    } else {
      // Listen if any upcoming entitlements unblock the reader
      this.onChange(e => {
        const {entitlement} = e;
        if (entitlement.granted) {
          this.grantStatusPromise_.resolve(true);
        } else if (this.areAllPlatformsResolved_()) {
          this.grantStatusPromise_.resolve(false);
        }
      });
    }

    return this.grantStatusPromise_.promise;
  }

  /**
   * Checks and saves the entitlement for grant status
   * @param {!Entitlement} entitlement
   * @private
   */
  saveGrantEntitlement_(entitlement) {
    // The entitlement will be stored if either it is the first one to grant
    // or the new one has full subscription but the last one didn't.
    if (
      (!this.grantStatusEntitlement_ && entitlement.granted) ||
      (this.grantStatusEntitlement_ &&
        !this.grantStatusEntitlement_.isSubscriber() &&
        entitlement.isSubscriber())
    ) {
      this.grantStatusEntitlement_ = entitlement;
    }
  }

  /**
   * Returns the entitlement which unlocked the document
   * @return {!Promise<?Entitlement>}
   */
  getGrantEntitlement() {
    if (this.grantStatusEntitlementPromise_) {
      return this.grantStatusEntitlementPromise_.promise;
    }
    this.grantStatusEntitlementPromise_ = new Deferred();
    if (
      (this.grantStatusEntitlement_ &&
        this.grantStatusEntitlement_.isSubscriber()) ||
      this.areAllPlatformsResolved_()
    ) {
      this.grantStatusEntitlementPromise_.resolve(this.grantStatusEntitlement_);
    } else {
      this.onEntitlementResolvedCallbacks_.add(() => {
        // Grant entitlement only if subscriber
        if (
          (this.grantStatusEntitlement_ &&
            this.grantStatusEntitlement_.isSubscriber()) ||
          this.areAllPlatformsResolved_()
        ) {
          this.grantStatusEntitlementPromise_.resolve(
            this.grantStatusEntitlement_
          );
        }
      });
    }
    return this.grantStatusEntitlementPromise_.promise;
  }

  /**
   * Clears the grant status
   */
  reset() {
    this.grantStatusPromise_ = null;
  }

  /**
   * Returns entitlements when all services are done fetching them.
   * @return {!Promise<!Array<!./entitlement.Entitlement>>}
   */
  getAllPlatformsEntitlements() {
    if (this.allResolvedPromise_) {
      return this.allResolvedPromise_.promise;
    }
    this.allResolvedPromise_ = new Deferred();
    if (this.areAllPlatformsResolved_()) {
      // Resolve with null if none of the entitlements unblock the reader
      this.allResolvedPromise_.resolve(
        this.getAvailablePlatformsEntitlements_()
      );
    } else {
      // Listen if any upcoming entitlements unblock the reader
      this.onChange(() => {
        if (this.areAllPlatformsResolved_()) {
          this.allResolvedPromise_.resolve(
            this.getAvailablePlatformsEntitlements_()
          );
        }
      });
    }
    return this.allResolvedPromise_.promise;
  }

  /**
   * Returns entitlements for resolved platforms.
   * @private
   * @return {!Array<!./entitlement.Entitlement>}
   */
  getAvailablePlatformsEntitlements_() {
    const entitlements = [];
    for (const platform in this.entitlements_) {
      if (hasOwn(this.entitlements_, platform)) {
        entitlements.push(this.entitlements_[platform]);
      }
    }
    return entitlements;
  }

  /**
   * Returns entitlements when all services are done fetching them.
   * @return {!Promise<!./subscription-platform.SubscriptionPlatform>}
   */
  selectPlatform() {
    return this.getAllPlatformsEntitlements().then(() => {
      // TODO(@prateekbh): explain why sometimes a quick resolve is possible vs
      // waiting for all entitlement.
      return this.selectApplicablePlatform_();
    });
  }

  /**
   * Returns the number of entitlements resolved
   * @return {boolean}
   * @private
   */
  areAllPlatformsResolved_() {
    const entitlementsResolved = Object.keys(this.entitlements_).length;
    return entitlementsResolved === this.serviceIds_.length;
  }

  /**
   * Calculates weight to add/remove based on getSupportedScoreFactor()
   * @param {string} factorName
   * @param {!./subscription-platform.SubscriptionPlatform} platform
   * @return {number}
   * @private
   */
  getSupportedFactorWeight_(factorName, platform) {
    const factorValue = platform.getSupportedScoreFactor(factorName);
    if (typeof factorValue !== 'number') {
      return 0;
    }
    return (
      this.scoreConfig_[factorName] * Math.min(1, Math.max(-1, factorValue))
    );
  }

  /**
   * Returns most qualified platform. Qualification of a platform is based on
   * weight. Every platform starts with weight 0 and evaluated against
   * the following parameters,
   * - base weight
   * - weight factors the platform supports multiplied by score in the config
   *
   * In the end candidate with max weight is selected. However if candidate's
   * weight is equal to local platform, then local platform is selected.
   * @return {!./subscription-platform.SubscriptionPlatform}
   * @private
   */
  selectApplicablePlatform_() {
    devAssert(
      this.areAllPlatformsResolved_(),
      'All platforms are not resolved yet'
    );

    // Subscriber wins immediately.
    const availablePlatforms = this.getAvailablePlatforms();
    while (availablePlatforms.length) {
      const platform = availablePlatforms.pop();
      const entitlement = this.getResolvedEntitlementFor(
        platform.getServiceId()
      );
      if (entitlement.isSubscriber()) {
        return platform;
      }
    }

    return this.rankPlatformsByWeight_(this.getAllPlatformWeights_());
  }

  /**
   * Calculate and return weights for all platforms
   * @return {!Array<!PlatformWeightDef>}
   * @private
   */
  getAllPlatformWeights_() {
    // Get weights for all of the platforms.
    return this.getAvailablePlatforms().map(platform => {
      return {
        platform,
        weight: this.calculatePlatformWeight_(platform),
      };
    });
  }

  /**
   * Calculate platform weight
   * @param {!./subscription-platform.SubscriptionPlatform} platform
   * @return {number}
   * @private
   */
  calculatePlatformWeight_(platform) {
    const factorWeights = [0]; // reduce always needs something to work with

    // Start with base score
    const weight = platform.getBaseScore();

    // Iterate score factors checking service support
    for (const factor in this.scoreConfig_) {
      if (hasOwn(this.scoreConfig_, factor)) {
        factorWeights.push(this.getSupportedFactorWeight_(factor, platform));
      }
    }

    return (
      weight +
      factorWeights.reduce((a, b) => {
        return a + b;
      })
    );
  }

  /**
   * @param {!Array<!PlatformWeightDef>} platformWeights
   * @return {!./subscription-platform.SubscriptionPlatform}
   * @private
   */
  rankPlatformsByWeight_(platformWeights) {
    const localPlatform = this.getLocalPlatform();
    platformWeights.sort((platform1, platform2) => {
      // Force local platform to win ties
      if (
        platform2.weight == platform1.weight &&
        platform1.platform == localPlatform
      ) {
        return -1;
      }
      return platform2.weight - platform1.weight;
    });
    return platformWeights[0].platform;
  }

  /**
   * Returns most qualified platform for the specified factor.
   *
   * In the end candidate with max weight is selected. However if candidate's
   * weight is equal to local platform, then local platform is selected.
   *
   * @param {string} factor
   * @return {!./subscription-platform.SubscriptionPlatform}
   * @private
   */
  selectApplicablePlatformForFactor_(factor) {
    const platformWeights = this.getAvailablePlatforms().map(platform => {
      const factorValue = platform.getSupportedScoreFactor(factor);
      const weight = typeof factorValue == 'number' ? factorValue : 0;
      return {platform, weight};
    });
    return this.rankPlatformsByWeight_(platformWeights);
  }

  /**
   * Records a platform failure
   * logs error if all platforms have failed
   * uses fallback if there is one.
   * @param {string} serviceId
   */
  reportPlatformFailureAndFallback(serviceId) {
    if (
      serviceId === this.getLocalPlatform().getServiceId() &&
      this.fallbackEntitlement_
    ) {
      this.resolveEntitlement(
        this.getLocalPlatform().getServiceId(),
        this.fallbackEntitlement_
      );
      user().warn(
        TAG,
        'Local platform has failed to resolve,  ' +
          'using fallback entitlement.'
      );
    } else if (this.failedPlatforms_.indexOf(serviceId) == -1) {
      const entitlement = Entitlement.empty(serviceId);
      this.resolveEntitlement(serviceId, entitlement);
      this.failedPlatforms_.push(serviceId);
    }
  }

  /**
   * Evaluates platforms and select the one to be selected for login.
   * @return {!./subscription-platform.SubscriptionPlatform}
   */
  selectPlatformForLogin() {
    return this.selectApplicablePlatformForFactor_(
      SubscriptionsScoreFactor.SUPPORTS_VIEWER
    );
  }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace IORAMHelper
{
		/// <summary>
		/// Definiert einen Puffer, der ganze Dateien einlesen und byteweise durchgehen kann.
		/// </summary>
		public class RAMBuffer : ICloneable
		{
			/// <summary>
			/// Die enthaltenen Bytedaten.
			/// </summary>
			private List<byte> _data;

			/// <summary>
			/// Die aktuelle Position im Puffer.
			/// </summary>
			private int _pos = 0;

			/// <summary>
			/// Erstellt ein neues RAMBuffer-Objekt.
			/// </summary>
			public RAMBuffer()
			{
				// Datenarray initialisieren
				_data = new List<byte>();
			}

			/// <summary>
			/// Erstellt ein neues RAMBuffer-Objekt aus den übergebenen Daten.
			/// </summary>
			/// <param name="data">Die einzufügenden Daten.</param>
			public RAMBuffer(byte[] data)
			{
				// Datenarray mit übergebenen Daten anlegen
				_data = new List<byte>(data);
			}

			/// <summary>
			/// Erstellt ein neues RAMBuffer-Objekt aus der angegebenen Datei.
			/// </summary>
			/// <param name="filename">Die zu ladende Datei.</param>
			public RAMBuffer(string filename)
			{
				// Puffer erstellen
				byte[] buffer;

				// Datei laden
				using(BinaryReader r = new BinaryReader(File.Open(filename, FileMode.Open)))
				{
					// Puffer initialisieren
					buffer = new byte[r.BaseStream.Length];

					// Puffer mit sämtlichen Dateidaten füllen
					r.Read(buffer, 0, (int)r.BaseStream.Length);

					// Stream schließen
					r.Close();
				}

				// Datenarray mit Pufferinhalt initialisieren
				_data = new List<byte>(buffer);
			}

			/// <summary>
			/// Liest ab der aktuellen Position die angegebene Menge von Bytes in ein angegebenes Byte-Array und gibt die tatsächliche Zahl der gelesenen Bytes zurück.
			/// </summary>
			/// <param name="buffer">Der Puffer, in den die Daten gelesen werden sollen (muss nicht initialisiert sein).</param>
			/// <param name="length">Die Länge der zu lesenden Daten.</param>
			/// <returns></returns>
			public int Read(out byte[] buffer, int length)
			{
				// Länge neu berechnen und ggf. verkleinern, falls diese über das Array hinausgeht
				int length2;
				if(length == 0 || _pos == _data.Count)
				{
					// Es können keine Daten gelesen werden, Array sicherheitshalber leer initialisieren (Null-Verweis-Fehler)
					buffer = new byte[0];

					// Nix zurückgeben
					return 0;
				}
				else if(_pos + length > _data.Count)
				{
					// Es dürfen nicht zu viele Daten gelesen werden
					length2 = _data.Count - _pos;
				}
				else
				{
					// Die Länge ist akzeptabel
					length2 = length;
				}

				// Puffer sicherheitshalber initialisieren
				buffer = new byte[length2];

				// Daten in Puffer kopieren
				_data.CopyTo(_pos, buffer, 0, length2);

				// Aktuelle Pufferposition erhöhen
				_pos += length2;

				// Datenlänge zurückgeben
				return length2;
			}

			/// <summary>
			/// Schreibt die angegebenen Daten an der aktuellen Position in den Puffer.
			/// </summary>
			/// <param name="data">Die zu schreibenden Daten.</param>
			/// <param name="overWrite">Legt fest, ob die Daten im Puffer mit den neuen Daten überschrieben werden sollen.</param>
			public void Write(byte[] data, bool overWrite = true)
			{
				// Datenlänge merken
				int len = data.Length;

				// Soll überschrieben werden?
				if(overWrite)
				{
					// Es muss ein bestimmter Bereich gelöscht werden; der Löschbereich darf die Puffergrenze nicht überschreiten
					if(_pos + len < _data.Count - 1)
					{
						// Alles OK, Bereich löschen
						_data.RemoveRange(_pos, len);
					}
					else
					{
						// Nur bis zum Listenende löschen
						_data.RemoveRange(_pos, _data.Count - _pos);
					}
				}

				// Daten einfügen
				_data.InsertRange(_pos, data);

				// Die Position um die Datenlänge erhöhen
				_pos += len;
			}

			/// <summary>
			/// Löscht alle enthaltenen Daten und setzt alle Statusvariablen zurück.
			/// </summary>
			public void Clear()
			{
				// Datenarray löschen
				_data.Clear();

				// Position zurücksetzen
				_pos = 0;
			}

			/// <summary>
			/// Schreibt alle Pufferinhalte in die angegebene Datei (bestehende Dateien werden überschrieben).
			/// </summary>
			/// <param name="filename">Die Zieldatei für die Pufferinhalte.</param>
			public void Save(string filename)
			{
				// Datei öffnen
				using(BinaryWriter w = new BinaryWriter(File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.None)))
				{
					// Daten schreiben
					w.Write((byte[])_data.ToArray());

					// Stream schließen
					w.Close();
				}
			}

			/// <summary>
			/// Erstellt eine Kopie des aktuellen Objekts und gibt diese zurück.
			/// </summary>
			/// <returns></returns>
			public object Clone()
			{
				return this.MemberwiseClone();
			}

			#region Konvertierende Hilfsfunktionen

			#region Lesen
			/// <summary>
			/// Liest ein Byte-Array der angegebenen Länge ab der aktuellen Position aus dem Puffer.
			/// </summary>
			/// <param name="len">Die Länge des zu lesenden Byte-Arrays.</param>
			/// <returns></returns>
			public byte[] ReadByteArray(int len)
			{
				// Puffer-Byte-Array
				byte[] buffer;

				// Lesen
				Read(out buffer, len);

				// Byte-Array zurückgeben
				return buffer;
			}

			/// <summary>
			/// Liest einen Byte-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public byte ReadByte()
			{
				// Wert zurückgeben
				return ReadByteArray(1)[0];
			}

			/// <summary>
			/// Liest einen Integer-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public int ReadInteger()
			{
				// Wert zurückgeben
				return BitConverter.ToInt32(ReadByteArray(4), 0);
			}

			/// <summary>
			/// Liest einen vorzeichenlosen Integer-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public uint ReadUInteger()
			{
				// Wert zurückgeben
				return BitConverter.ToUInt32(ReadByteArray(4), 0);
			}

			/// <summary>
			/// Liest einen Short-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public short ReadShort()
			{
				// Wert zurückgeben
				return BitConverter.ToInt16(ReadByteArray(2), 0);
			}

			/// <summary>
			/// Liest einen vorzeichenlosen Short-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public ushort ReadUShort()
			{
				// Wert zurückgeben
				return BitConverter.ToUInt16(ReadByteArray(2), 0);
			}

			/// <summary>
			/// Liest einen Long-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public long ReadLong()
			{
				// Wert zurückgeben
				return BitConverter.ToInt64(ReadByteArray(8), 0);
			}

			/// <summary>
			/// Liest einen vorzeichenlosen Long-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public ulong ReadULong()
			{
				// Wert zurückgeben
				return BitConverter.ToUInt64(ReadByteArray(8), 0);
			}

			/// <summary>
			/// Liest einen Float-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public float ReadFloat()
			{
				// Wert zurückgeben
				return BitConverter.ToSingle(ReadByteArray(4), 0);
			}

			/// <summary>
			/// Liest einen Double-Wert aus dem Puffer.
			/// </summary>
			/// <returns></returns>
			public double ReadDouble()
			{
				// Wert zurückgeben
				return BitConverter.ToDouble(ReadByteArray(8), 0);
			}

			/// <summary>
			/// Liest eine ANSI-Zeichenkette angegebener Länge aus dem Puffer.
			/// </summary>
			/// <param name="length">Die Länge der zu lesenden Zeichenkette.</param>
			/// <returns></returns>
			public string ReadString(int length)
			{
				// Wert zurückgeben
				return System.Text.Encoding.Default.GetString(ReadByteArray(length));
			}
			#endregion

			#region Schreiben
			/// <summary>
			/// Schreibt einen Byte-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteByte(byte value)
			{
				// Wert schreiben
				Write(new byte[] { value });
			}

			/// <summary>
			/// Schreibt einen Float-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteFloat(float value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen Integer-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteInteger(int value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen vorzeichenlosen Integer-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteUInteger(uint value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen Short-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteShort(short value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen vorzeichenlosen Short-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteUShort(ushort value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen Long-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteLong(long value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen vorzeichenlosen Long-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteULong(ulong value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen Float-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteLong(float value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt einen Double-Wert in den Puffer.
			/// </summary>
			/// <param name="value">Der zu schreibende Wert.</param>
			public void WriteLong(double value)
			{
				// Wert schreiben
				Write(BitConverter.GetBytes(value));
			}

			/// <summary>
			/// Schreibt eine ANSI-Zeichenkette in den Puffer.
			/// </summary>
			/// <param name="value">Die zu schreibende Zeichenkette.</param>
			public void WriteString(string value)
			{
				// Zeichenkette schreiben
				Write(System.Text.Encoding.Default.GetBytes(value));
			}
			#endregion

			#endregion

			#region Eigenschaften

			/// <summary>
			/// Ruft die aktuelle Pufferposition ab oder legt diese fest.
			/// </summary>
			public int Position
			{
				get
				{
					// Position zurückgeben
					return _pos;
				}
				set
				{
					// Position überprüfen und ggf. Fehler auslösen
					if(value <= _data.Count)
						_pos = value;
					else
						throw new ArgumentException("Die angegebene Position liegt nicht innerhalb der Daten!");
				}
			}

			/// <summary>
			/// Ruft die aktuelle Puffergröße ab.
			/// </summary>
			public int Length
			{
				get
				{
					// Pufferlänge zurückgeben
					return _data.Count;
				}
			}

			#endregion
		}
}


text:
Consider many words of which some may be camel case or not. Concatenate them all and transform _camelCase_ to _PascalCase_

## Test case 1

```bash
echo 'Word myWordBlub myBlah' | solution
```

Shall print the following output:

```
WordMyWordBlubMyBlah
```

## Solution 1

Split words up into several lines and transform first characters to upper case, then join lines.

```bash
echo 'Word myWordBlub myBlah' | for i in `</dev/stdin`; do echo `echo $i | cut -c1 | tr 'a-z' 'A-Z'``echo $i | cut -c2-`; done | tr -d '\n'; echo
```

## Solution 2

Using perl:

```bash
echo 'Word myWordBlub myBlah' | perl -pe 's# [a-z]#uc $&#ge' | tr -d \
```


text:
#include "mpf_dtmf_generator.h"
#include "apr.h"
#include "apr_thread_mutex.h"
#include "apt_log.h"
#include "mpf_named_event.h"
#include <math.h>

#ifndef M_PI
#	define M_PI 3.141592653589793238462643
#endif

/** Max DTMF digits waiting to be sent */
#define MPF_DTMFGEN_QUEUE_LEN  32

/** See RFC4733 */
#define DTMF_EVENT_ID_MAX      15  /* 0123456789*#ABCD */

/** See RFC4733 */
#define DTMF_EVENT_VOLUME      10

/** Amplitude of single sine wave from tone generator */
#define DTMF_SINE_AMPLITUDE 12288

/** State of the DTMF generator */
typedef enum mpf_dtmf_generator_state_e {
	/** Ready to generate next digit in queue */
	DTMF_GEN_STATE_IDLE,
	/** Generating tone */
	DTMF_GEN_STATE_TONE,
	/** Retransmitting final RTP packet */
	DTMF_GEN_STATE_ENDING,
	/** Generating silence between tones */
	DTMF_GEN_STATE_SILENCE
} mpf_dtmf_generator_state_e;

/**
 * Sine wave generator (second-order IIR filter) state:
 *
 * s(t) = Amp*sin(2*pi*f_tone/f_sampling*t)
 *
 * s(t) = coef * s(t-1) - s(t-2); s(0)=0; s(1)=Amp*sin(2*pi*f_tone/f_sampling)
 */
typedef struct sine_state_t {
	/** coef = cos(2*pi*f_tone/f_sampling) */
	double coef;
	/** s(t-2) @see sine_state_t */
	double s1;
	/** s(t-1) @see sine_state_t */
	double s2;
} sine_state_t;

/** Mapping event_id to frequency pair */
static const double dtmf_freq[DTMF_EVENT_ID_MAX+1][2] = {
	{941, 1336},  /* 0 */
	{697, 1209},  /* 1 */
	{697, 1336},  /* 2 */
	{697, 1477},  /* 3 */
	{770, 1209},  /* 4 */
	{770, 1336},  /* 5 */
	{770, 1477},  /* 6 */
	{852, 1209},  /* 7 */
	{852, 1336},  /* 8 */
	{852, 1477},  /* 9 */
	{941, 1209},  /* * */
	{941, 1477},  /* # */
	{697, 1633},  /* A */
	{770, 1633},  /* B */
	{852, 1633},  /* C */
	{941, 1633}   /* D */
};

/** Media Processing Framework's Dual Tone Multiple Frequncy generator */
struct mpf_dtmf_generator_t {
	/** Generator state */
	enum mpf_dtmf_generator_state_e  state;
	/** In-band or out-of-band */
	enum mpf_dtmf_generator_band_e   band;
	/** Mutex to guard the queue */
	struct apr_thread_mutex_t       *mutex;
	/** Queue of digits to generate */
	char                             queue[MPF_DTMFGEN_QUEUE_LEN+1];
	/** DTMF event_id according to RFC4733 */
	apr_byte_t                       event_id;
	/** Duration in RTP units: (sample_rate / 1000) * milliseconds */
	apr_uint32_t                     tone_duration;
	/** Duration of inter-digit silence @see tone_duration */
	apr_uint32_t                     silence_duration;
	/** Multipurpose counter; mostly in RTP time units */
	apr_uint32_t                     counter;
	/** Frame duration in RTP units */
	apr_uint32_t                     frame_duration;
	/** RTP named event duration (0..0xFFFF) */
	apr_uint32_t                     event_duration;
	/** Set MPF_MARKER_NEW_SEGMENT in the next event frame */
	apt_bool_t                       new_segment;
	/** Lower frequency generator */
	struct sine_state_t              sine1;
	/** Higher frequency generator */
	struct sine_state_t              sine2;
	/** Sampling rate of audio in Hz; used in tone generator */
	apr_uint32_t                     sample_rate_audio;
	/** Sampling rate of telephone-events in Hz; used for timing */
	apr_uint32_t                     sample_rate_events;
	/** How often to issue event packet */
	apr_uint32_t                     events_ptime;
	/** Milliseconds elapsed since last event packet */
	apr_uint32_t                     since_last_event;
};

MPF_DECLARE(struct mpf_dtmf_generator_t *) mpf_dtmf_generator_create_ex(
								const struct mpf_audio_stream_t *stream,
								enum mpf_dtmf_generator_band_e band,
								apr_uint32_t tone_ms,
								apr_uint32_t silence_ms,
								struct apr_pool_t *pool)
{
	struct mpf_dtmf_generator_t *gen;
	apr_status_t status;
	int flg_band = band;

	if (!stream->rx_descriptor) flg_band &= ~MPF_DTMF_GENERATOR_INBAND;
	if (!stream->rx_event_descriptor) flg_band &= ~MPF_DTMF_GENERATOR_OUTBAND;
	if (!flg_band) return NULL;

	gen = apr_palloc(pool, sizeof(struct mpf_dtmf_generator_t));
	if (!gen) return NULL;
	status = apr_thread_mutex_create(&gen->mutex, APR_THREAD_MUTEX_DEFAULT, pool);
	if (status != APR_SUCCESS) return NULL;
	gen->band = (enum mpf_dtmf_generator_band_e) flg_band;
	gen->queue[0] = 0;
	gen->state = DTMF_GEN_STATE_IDLE;
	if (stream->rx_descriptor)
		gen->sample_rate_audio = stream->rx_descriptor->sampling_rate;
	gen->sample_rate_events = stream->rx_event_descriptor ?
		stream->rx_event_descriptor->sampling_rate : gen->sample_rate_audio;
	gen->frame_duration = gen->sample_rate_events / 1000 * CODEC_FRAME_TIME_BASE;
	gen->tone_duration = gen->sample_rate_events / 1000 * tone_ms;
	gen->silence_duration = gen->sample_rate_events / 1000 * silence_ms;
	gen->events_ptime = CODEC_FRAME_TIME_BASE;  /* Should be got from event_descriptor */
	return gen;
}

MPF_DECLARE(apt_bool_t) mpf_dtmf_generator_enqueue(
								struct mpf_dtmf_generator_t *generator,
								const char *digits)
{
	apr_size_t qlen, dlen;
	apt_bool_t ret;

	dlen = strlen(digits);
	apr_thread_mutex_lock(generator->mutex);
	qlen = strlen(generator->queue);
	if (qlen + dlen > MPF_DTMFGEN_QUEUE_LEN) {
		ret = FALSE;
		apt_log(APT_LOG_MARK, APT_PRIO_WARNING, "DTMF queue too short (%d), "
			"cannot add %"APR_SIZE_T_FMT" digit%s, already has %"APR_SIZE_T_FMT,
			MPF_DTMFGEN_QUEUE_LEN, dlen, dlen > 1 ? "s" : "", qlen);
	} else {
		strcpy(generator->queue + qlen, digits);
		ret = TRUE;
	}
	apr_thread_mutex_unlock(generator->mutex);
	return ret;
}

MPF_DECLARE(void) mpf_dtmf_generator_reset(struct mpf_dtmf_generator_t *generator)
{
	apr_thread_mutex_lock(generator->mutex);
	generator->state = DTMF_GEN_STATE_IDLE;
	generator->queue[0] = 0;
	apr_thread_mutex_unlock(generator->mutex);
}

MPF_DECLARE(apt_bool_t) mpf_dtmf_generator_sending(const struct mpf_dtmf_generator_t *generator)
{
	return *generator->queue || ((generator->state != DTMF_GEN_STATE_IDLE) &&
		(generator->state != DTMF_GEN_STATE_SILENCE));
}

MPF_DECLARE(apt_bool_t) mpf_dtmf_generator_put_frame(
								struct mpf_dtmf_generator_t *generator,
								struct mpf_frame_t *frame)
{
	apr_thread_mutex_lock(generator->mutex);
	if ((generator->state == DTMF_GEN_STATE_IDLE) && *generator->queue) {
		/* Get next valid digit from queue */
		do {
			generator->event_id = (apr_byte_t) mpf_dtmf_char_to_event_id(*generator->queue);
			strcpy(generator->queue, generator->queue + 1);
		} while (*generator->queue && (generator->event_id > DTMF_EVENT_ID_MAX));
		/* Reset state */
		if (generator->event_id <= DTMF_EVENT_ID_MAX) {
			generator->state = DTMF_GEN_STATE_TONE;
			generator->counter = 0;
			generator->event_duration = 0;
			generator->since_last_event = generator->events_ptime;
			generator->new_segment = FALSE;
			/* Initialize tone generator */
			if (generator->band & MPF_DTMF_GENERATOR_INBAND) {
				double omega;

				omega = 2 * M_PI * dtmf_freq[generator->event_id][0] / generator->sample_rate_audio;
				generator->sine1.s1 = 0;
				generator->sine1.s2 = DTMF_SINE_AMPLITUDE * sin(omega);
				generator->sine1.coef = 2 * cos(omega);

				omega = 2 * M_PI * dtmf_freq[generator->event_id][1] / generator->sample_rate_audio;
				generator->sine2.s1 = 0;
				generator->sine2.s2 = DTMF_SINE_AMPLITUDE * sin(omega);
				generator->sine2.coef = 2 * cos(omega);
			}
		}
	}
	apr_thread_mutex_unlock(generator->mutex);
	if (generator->state == DTMF_GEN_STATE_IDLE) return FALSE;

	if (generator->state == DTMF_GEN_STATE_TONE) {
		generator->counter += generator->frame_duration;
		generator->event_duration += generator->frame_duration;
		if (generator->band & MPF_DTMF_GENERATOR_INBAND) {
			apr_size_t i;
			apr_int16_t *samples = (apr_int16_t *) frame->codec_frame.buffer;
			double s;

			frame->type |= MEDIA_FRAME_TYPE_AUDIO;
			/* Tone generator */
			for (i = 0; i < frame->codec_frame.size / 2; i++) {
				s = generator->sine1.s1;
				generator->sine1.s1 = generator->sine1.s2;
				generator->sine1.s2 = generator->sine1.coef * generator->sine1.s1 - s;
				samples[i] = (apr_int16_t) (s + generator->sine2.s1);
				s = generator->sine2.s1;
				generator->sine2.s1 = generator->sine2.s2;
				generator->sine2.s2 = generator->sine2.coef * generator->sine2.s1 - s;
			}
		}
		if (generator->band & MPF_DTMF_GENERATOR_OUTBAND) {
			generator->since_last_event += CODEC_FRAME_TIME_BASE;
			if (generator->since_last_event >= generator->events_ptime)
				generator->since_last_event = 0;
			else
				return TRUE;
			frame->type |= MEDIA_FRAME_TYPE_EVENT;
			frame->event_frame.reserved = 0;
			frame->event_frame.event_id = generator->event_id;
			frame->event_frame.volume = DTMF_EVENT_VOLUME;
			if (generator->counter >= generator->tone_duration) {
				generator->state = DTMF_GEN_STATE_ENDING;
				generator->counter = 0;
				frame->event_frame.edge = 1;
				frame->marker = MPF_MARKER_END_OF_EVENT;
				if (generator->event_duration > 0xFFFF) {
					/* Shorten the tone a bit instead of lenghtening */
					generator->new_segment = TRUE;
					frame->event_frame.duration = 0xFFFF;
					generator->event_duration = 0;
				} else
					frame->event_frame.duration = generator->event_duration;
			} else {
				frame->event_frame.edge = 0;
				if (generator->counter == generator->frame_duration)  /* First chunk of event */
					frame->marker = MPF_MARKER_START_OF_EVENT;
				else if (generator->new_segment) {
					frame->marker = MPF_MARKER_NEW_SEGMENT;
					generator->new_segment = FALSE;
				} else
					frame->marker = MPF_MARKER_NONE;
				if (generator->event_duration > 0xFFFF) {
					frame->event_frame.duration = 0xFFFF;
					generator->event_duration = 0;
					generator->new_segment = TRUE;
				} else
					frame->event_frame.duration = generator->event_duration;
			}
			return TRUE;
		}  /* MPF_DTMF_GENERATOR_OUTBAND */
		if (generator->counter >= generator->tone_duration) {
			generator->state = DTMF_GEN_STATE_SILENCE;
			generator->counter = 0;
		}
		return TRUE;
	}
	else if (generator->state == DTMF_GEN_STATE_ENDING) {
		generator->since_last_event += CODEC_FRAME_TIME_BASE;
		if (generator->since_last_event >= generator->events_ptime)
			generator->since_last_event = 0;
		else
			return TRUE;
		generator->counter++;
		frame->type |= MEDIA_FRAME_TYPE_EVENT;
		frame->marker = MPF_MARKER_END_OF_EVENT;
		frame->event_frame.event_id = generator->event_id;
		frame->event_frame.volume = DTMF_EVENT_VOLUME;
		frame->event_frame.reserved = 0;
		frame->event_frame.edge = 1;
		if (generator->new_segment)
			/* Tone was shortened a little bit */
			frame->event_frame.duration = 0xFFFF;
		else
			frame->event_frame.duration = generator->event_duration;
		if (generator->counter >= 2) {
			generator->state = DTMF_GEN_STATE_SILENCE;
			generator->counter *= generator->frame_duration;
		}
		if (generator->band & MPF_DTMF_GENERATOR_INBAND) {
			frame->type |= MEDIA_FRAME_TYPE_AUDIO;
			memset(frame->codec_frame.buffer, 0, frame->codec_frame.size);
		}
		return TRUE;
	}
	else if (generator->state == DTMF_GEN_STATE_SILENCE) {
		generator->counter += generator->frame_duration;
		if (generator->counter >= generator->silence_duration)
			generator->state = DTMF_GEN_STATE_IDLE;
	}

	return FALSE;
}

MPF_DECLARE(void) mpf_dtmf_generator_destroy(struct mpf_dtmf_generator_t *generator)
{
	mpf_dtmf_generator_reset(generator);
	apr_thread_mutex_destroy(generator->mutex);
	generator->mutex = NULL;
}


text:
#ifndef __SYSDEV_SIMPLE_GPIO_H
#define __SYSDEV_SIMPLE_GPIO_H

#include <linux/errno.h>

#ifdef CONFIG_SIMPLE_GPIO
extern void simple_gpiochip_init(const char *compatible);
#else
static inline void simple_gpiochip_init(const char *compatible) {}
#endif /* CONFIG_SIMPLE_GPIO */

#endif /* __SYSDEV_SIMPLE_GPIO_H */


text:
package com.centurylink.mdw.util;

import java.sql.Connection;

import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

import com.centurylink.mdw.app.ApplicationContext;
import com.centurylink.mdw.util.log.LoggerUtil;
import com.centurylink.mdw.util.log.StandardLogger;

public class TransactionUtil {

    private static TransactionUtil instance;
    private static ThreadLocal<Connection> currentConnection;

    public static TransactionUtil getInstance() {
        if (instance==null) {
            instance = new TransactionUtil();
            currentConnection = new ThreadLocal<Connection>();
        }
        return instance;
    }

    /**
     * Returns the current transaction
     */
    public Transaction getTransaction() {
        try {
            return getTransactionManager().getTransaction();
        }
        catch (Exception ex) {
            StandardLogger logger = LoggerUtil.getStandardLogger();
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }

    /**
     * Returns transaction manager
     */
    public TransactionManager getTransactionManager() {
        TransactionManager transMgr = null;
        try {
            String jndiName = ApplicationContext.getContextProvider().getTransactionManagerName();
            Object txMgr = ApplicationContext.getContextProvider().lookup(null, jndiName, TransactionManager.class);
            transMgr = (TransactionManager)txMgr;
        } catch (Exception ex) {
            StandardLogger logger = LoggerUtil.getStandardLogger();
            logger.error(ex.getMessage(), ex);
        }
        return transMgr;
    }

    public boolean isInTransaction() throws SystemException {
        TransactionManager transManager = getTransactionManager();
        return (transManager.getStatus()==Status.STATUS_ACTIVE);
    }

    public Connection getCurrentConnection() {
        return currentConnection.get();
    }

    public void setCurrentConnection(Connection connection) {
        currentConnection.set(connection);
    }
}


text:
package io.machinecode.chainlink.core.configuration;

import io.machinecode.chainlink.spi.configuration.ConfigurationLoader;
import io.machinecode.chainlink.spi.configuration.Dependencies;
import io.machinecode.chainlink.spi.property.PropertyLookup;
import io.machinecode.chainlink.spi.configuration.factory.ConfigurationLoaderFactory;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public class TestConfigurationLoaderFactory implements ConfigurationLoaderFactory {

    public static volatile boolean called = false;

    @Override
    public ConfigurationLoader produce(final Dependencies dependencies, final PropertyLookup properties) throws Exception {
        called = true;
        return new TestConfigurationLoader();
    }
}


text:
sleep 100
exit 0


text:
package org.elasticsearch.action.percolate;

import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.broadcast.BroadcastRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
 * A request to execute a percolate operation.
 */
public class PercolateRequest extends ActionRequest<PercolateRequest> implements IndicesRequest.Replaceable {

    protected String[] indices;
    private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed();
    private String documentType;
    private String routing;
    private String preference;
    private boolean onlyCount;

    private GetRequest getRequest;
    private BytesReference source;

    public String[] indices() {
        return indices;
    }

    public final PercolateRequest indices(String... indices) {
        this.indices = indices;
        return this;
    }

    public IndicesOptions indicesOptions() {
        return indicesOptions;
    }

    public PercolateRequest indicesOptions(IndicesOptions indicesOptions) {
        this.indicesOptions = indicesOptions;
        return this;
    }

    /**
     * Getter for {@link #documentType(String)}
     */
    public String documentType() {
        return documentType;
    }

    /**
     * Sets the type of the document to percolate. This is important as it selects the mapping to be used to parse
     * the document.
     */
    public PercolateRequest documentType(String type) {
        this.documentType = type;
        return this;
    }

    /**
     * Getter for {@link #routing(String)}
     */
    public String routing() {
        return routing;
    }

    /**
     * A comma separated list of routing values to control the shards the search will be executed on.
     */
    public PercolateRequest routing(String routing) {
        this.routing = routing;
        return this;
    }

    /**
     * Getter for {@link #preference(String)}
     */
    public String preference() {
        return preference;
    }

    /**
     * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
     * <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
     * a custom value, which guarantees that the same order will be used across different requests.
     */
    public PercolateRequest preference(String preference) {
        this.preference = preference;
        return this;
    }

    /**
     * Getter for {@link #getRequest(GetRequest)}
     */
    public GetRequest getRequest() {
        return getRequest;
    }

    /**
     * This defines where to fetch the document to be percolated from, which is an alternative of defining the document
     * to percolate in the request body.
     *
     * If this defined than this will override the document specified in the request body.
     */
    public PercolateRequest getRequest(GetRequest getRequest) {
        this.getRequest = getRequest;
        return this;
    }

    /**
     * @return The request body in its raw form.
     */
    public BytesReference source() {
        return source;
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(Map document) throws ElasticsearchGenerationException {
        return source(document, Requests.CONTENT_TYPE);
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    @SuppressWarnings("unchecked")
    public PercolateRequest source(Map document, XContentType contentType) throws ElasticsearchGenerationException {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.map(document);
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate [" + document + "]", e);
        }
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(String document) {
        this.source = new BytesArray(document);
        return this;
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(XContentBuilder documentBuilder) {
        source = documentBuilder.bytes();
        return this;
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(byte[] document) {
        return source(document, 0, document.length);
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(byte[] source, int offset, int length) {
        return source(new BytesArray(source, offset, length));
    }

    /**
     * Raw version of {@link #source(PercolateSourceBuilder)}
     */
    public PercolateRequest source(BytesReference source) {
        this.source = source;
        return this;
    }

    /**
     * Sets the request body definition for this percolate request as raw bytes.
     *
     * This is the preferred way to set the request body.
     */
    public PercolateRequest source(PercolateSourceBuilder sourceBuilder) {
        this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
        return this;
    }

    /**
     * Getter for {@link #onlyCount(boolean)}
     */
    public boolean onlyCount() {
        return onlyCount;
    }

    /**
     * Sets whether this percolate request should only count the number of percolator queries that matches with
     * the document being percolated and don't keep track of the actual queries that have matched.
     */
    public PercolateRequest onlyCount(boolean onlyCount) {
        this.onlyCount = onlyCount;
        return this;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = null;
        if (documentType == null) {
            validationException = addValidationError("type is missing", validationException);
        }
        if (source == null && getRequest == null) {
            validationException = addValidationError("source or get is missing", validationException);
        }
        if (getRequest != null && getRequest.fields() != null) {
            validationException = addValidationError("get fields option isn't supported via percolate request", validationException);
        }
        return validationException;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        indices = in.readStringArray();
        indicesOptions = IndicesOptions.readIndicesOptions(in);
        documentType = in.readString();
        routing = in.readOptionalString();
        preference = in.readOptionalString();
        source = in.readBytesReference();
        if (in.readBoolean()) {
            getRequest = new GetRequest();
            getRequest.readFrom(in);
        }
        onlyCount = in.readBoolean();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeStringArrayNullable(indices);
        indicesOptions.writeIndicesOptions(out);
        out.writeString(documentType);
        out.writeOptionalString(routing);
        out.writeOptionalString(preference);
        out.writeBytesReference(source);
        if (getRequest != null) {
            out.writeBoolean(true);
            getRequest.writeTo(out);
        } else {
            out.writeBoolean(false);
        }
        out.writeBoolean(onlyCount);
    }
}


text:
/* SPDX-License-Identifier: Apache-2.0 */

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

/** @file
 * Error codes and functions for detecting and assessing them.
 */

#ifndef __STUMPLESS_ERROR_H
#  define __STUMPLESS_ERROR_H

#include <stdbool.h>
#include <stdio.h>
#include <stumpless/config.h>
#include <stumpless/generator.h>

#  ifdef __cplusplus
extern "C" {
#  endif

/**
 * A macro to implement error id enum and error string array.
 */
#define STUMPLESS_FOREACH_ERROR(ERROR)	\
/**
  A provided network address was not valid.

  This might be formatting problem, or it might mean that a DNS lookup failed.
 */\
  ERROR(STUMPLESS_ADDRESS_FAILURE, 0)	\
/** A required function parameter was NULL or empty. */\
  ERROR(STUMPLESS_ARGUMENT_EMPTY, 1)	\
/** A provided argument was too big, for example to fit into a buffer target. */\
  ERROR(STUMPLESS_ARGUMENT_TOO_BIG, 2)	\
/**
  A duplicate of an already existing element was detected in an entry.

  @since release v1.6.0.
 */\
  ERROR(STUMPLESS_DUPLICATE_ELEMENT, 3)	\
/**
  No element with the specified characteristics was found.

  @since release v1.6.0.
 */\
  ERROR(STUMPLESS_ELEMENT_NOT_FOUND, 4)	\
/** Could not open a file. */\
  ERROR(STUMPLESS_FILE_OPEN_FAILURE, 5)	\
/** Could not write to a file. */\
  ERROR(STUMPLESS_FILE_WRITE_FAILURE, 6)	\
/** A provided index was not in a valid range. */\
  ERROR(STUMPLESS_INDEX_OUT_OF_BOUNDS, 7)	\
/** A provided facility code did not conform to RFC 5424. */\
  ERROR(STUMPLESS_INVALID_FACILITY, 8)	\
/** A target or entry ID was not valid. */\
  ERROR(STUMPLESS_INVALID_ID, 9)	\
/**
  A provided severity code did not conform to RFC 5424.

  @since release v1.6.0.
 */\
  ERROR(STUMPLESS_INVALID_SEVERITY, 10)	\
/** A memory allocation or reallocation failed. */\
  ERROR(STUMPLESS_MEMORY_ALLOCATION_FAILURE, 11)	\
/** The given layer 3 protocol is not supported by this implementation. */\
  ERROR(STUMPLESS_NETWORK_PROTOCOL_UNSUPPORTED, 12)	\
/**
  No param with the specified characteristics was found.

  @since release v1.6.0.
 */\
  ERROR(STUMPLESS_PARAM_NOT_FOUND, 13)	\
/** Could not bind to a socket. */\
  ERROR(STUMPLESS_SOCKET_BIND_FAILURE, 14)	\
/** Could not connect to a socket. */\
  ERROR(STUMPLESS_SOCKET_CONNECT_FAILURE, 15)	\
/** Could not create a socket. */\
  ERROR(STUMPLESS_SOCKET_FAILURE, 16)	\
/** Could not send to a socket. */\
  ERROR(STUMPLESS_SOCKET_SEND_FAILURE, 17)	\
/** Could not write to a stream. */\
  ERROR(STUMPLESS_STREAM_WRITE_FAILURE, 18)	\
/** The requested operation is not valid on the given target type. */\
  ERROR(STUMPLESS_TARGET_INCOMPATIBLE, 19)	\
/** The target type provided is unsupported by this implementation. */\
  ERROR(STUMPLESS_TARGET_UNSUPPORTED, 20)	\
/** The given layer 4 protocol is not supported by this implementation. */\
  ERROR(STUMPLESS_TRANSPORT_PROTOCOL_UNSUPPORTED, 21)	\
/** Could not close the Windows Event Log. */\
  ERROR(STUMPLESS_WINDOWS_EVENT_LOG_CLOSE_FAILURE, 22)	\
/** Could not open the Windows Event Log. */\
  ERROR(STUMPLESS_WINDOWS_EVENT_LOG_OPEN_FAILURE, 23)	\
/** A provided encoding does not conform to the standard. */\
  ERROR(STUMPLESS_INVALID_ENCODING, 24) \
/** The current hostname could not be retrieved. */\
  ERROR(STUMPLESS_GETHOSTNAME_FAILURE, 25 ) \
/**
 * A call to a function target's log function failed.
 *
 * @since release v2.1.0
 */\
  ERROR(STUMPLESS_FUNCTION_TARGET_FAILURE, 26 ) \
/**
 * A call to a systemd journald function failed.
 *
 * @since release v2.1.0
 */\
  ERROR( STUMPLESS_JOURNALD_FAILURE, 27 ) \
/**
 * A general failure of a Windows API call. Details on what call failed and
 * why are provided in the error details.
 *
 * @since release v2.1.0
 */\
  ERROR( STUMPLESS_WINDOWS_FAILURE, 28 )

/**
 * An (enum) identifier of the types of errors that might be encountered.
 *
 * Note that the same error may be encountered in different contexts with a
 * different ultimate cause. To completely diagnose a problem, you will need
 * to look at more than just the error id.
 *
 * @note The real implementation of enum values is now moved under `STUMPLESS_FOREACH_ERROR(ERROR)` macro.
 */
enum stumpless_error_id {
  STUMPLESS_FOREACH_ERROR(STUMPLESS_GENERATE_ENUM)
};

/**
 *Information describing an error encountered by the library.
 */
struct stumpless_error {
  enum stumpless_error_id id; /**< error family */
  const char *message; /**< specific details of the failure */
  int code; /**< an error code possibly providing more information */
  const char *code_type; /**< a description of the error code */
};

/**
 * Retrieves the error encountered by the last library call.
 *
 * The returned error struct is only valid until the next call to a stumpless
 * function. After this, it should not be referred to, and if the error of any
 * subsequent call is needed another call to stumpless_get_error must be made.
 *
 * Note that the id is the only field of the error that is guaranteed to be set.
 * Other members may or may not be set, depending on the context of the error.
 *
 * If the code_type is NULL, then the code is not valid and should be ignored.
 *
 * This function does _not_ clear or update the per-thread error code for
 * stumpless, as it is involved in the error handling process itself.
 *
 * **Thread Safety: MT-Safe**
 * This function is thread safe. No synchronization primitives are used as the
 * returned pointer is specific to the thread of execution. As a result, the
 * result should not be shared between threads.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers. If you do so, note that
 * if it is called before a stumpless library function in the handler itself
 * the result will not be meaningful.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be asynchronously
 * cancelled.
 *
 * @return A stumpless_error struct describing the error encountered by the last
 * function call. If no error was encountered, this will be NULL.
 */
STUMPLESS_PUBLIC_FUNCTION
const struct stumpless_error *
stumpless_get_error( void );

/**
 * Gets the error id of the given error.
 *
 * **Thread Safety: MT-Safe race:err**
 * This function is thread safe, as long as err is not modifed by other threads
 * during this call.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be asynchronously
 * cancelled.
 *
 * @since Release v1.5.0
 *
 * @param err The error to get the id from. This must not be NULL.
 *
 * @return The error id of the given error.
 */
STUMPLESS_PUBLIC_FUNCTION
enum stumpless_error_id
stumpless_get_error_id( const struct stumpless_error *err );

/**
 * Gets the error string of the given error id.
 *
 * This is a string literal that should not be modified or freed by the caller.
 *
 * **Thread Safety: MT-Safe**
 * This function is thread safe.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be asynchronously
 * cancelled.
 *
 * @since Release v1.6.0
 *
 * @param id The error id to get the error string from.
 *
 * @return The error string of the given error id.
 */
STUMPLESS_PUBLIC_FUNCTION
const char *
stumpless_get_error_id_string( enum stumpless_error_id id );

/**
 * Gets the current stream that errors are written to.
 *
 * **Thread Safety: MT-Safe**
 * This function is thread safe. Atomic variables are used to store and
 * retrieve the error stream.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be ansynchronously
 * cancelled.
 *
 * @return The current stream errors are written to.
 */
STUMPLESS_PUBLIC_FUNCTION
FILE *
stumpless_get_error_stream( void );

/**
 * True if the last call to a stumpless function encountered an error. To get
 * the error itself, use the stumpless_get_error function.
 *
 * **Thread Safety: MT-Safe**
 * This function is thread safe. No synchronization primitives are used as the
 * returned flag is specific to the thread of execution.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers. If you do so, note that
 * if it is called before a stumpless library function in the handler itself
 * the result will not be meaningful.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be asynchronously
 * cancelled.
 *
 * @since release v1.6.0.
 *
 * @return True if the last stumpless call had an error, false if not.
 */
STUMPLESS_PUBLIC_FUNCTION
bool
stumpless_has_error( void );

/**
 * Prints information about the current error to the error stream.
 *
 * A prefix can be added to the information if desired. If one is provided then
 * it will be followed by a colon character and a space, followed by the error
 * information. If it is not provided then the colon and space characters will
 * not be printed.
 *
 * The message will end with a newline.
 *
 * If there is not currently an active error message, then nothing will be
 * printed (not even the prefix).
 *
 * **Thread Safety: MT-Safe race:prefix**
 * This function is thread safe, of course assuming that prefix is not changed
 * by other threads during execution. A lock is used to coordinate accesses to
 * the error stream.
 *
 * **Async Signal Safety: AS-Unsafe lock**
 * This function is not safe to call from signal handlers, as it uses a
 * non-reentrant lock to synchronize access to the error stream.
 *
 * **Async Cancel Safety: AC-Unsafe lock**
 * This function is not safe to call from threads that may be asynchronously
 * cancelled, as the lock used to control access to the error stream may not
 * be released after a cancellation.
 *
 * @param prefix An optional prefix to print in front of the message. If this is
 * NULL then it will simply be ignored.
 */
STUMPLESS_PUBLIC_FUNCTION
void
stumpless_perror( const char *prefix );

/**
 * Sets the stream to write errors to.
 *
 * This will be stderr by default, but can be set to any stream. If it is set
 * to NULL then error messages will not be printed (essentially skipping all
 * \c stumpless_perror calls).
 *
 * **Thread Safety: MT-Safe**
 * This function is thread safe. Atomic variables are used to store and
 * retrieve the error stream.
 *
 * **Async Signal Safety: AS-Safe**
 * This function is safe to call from signal handlers.
 *
 * **Async Cancel Safety: AC-Safe**
 * This function is safe to call from threads that may be ansynchronously
 * cancelled.
 *
 * @param stream The stream to write errors to. If this is NULL then the messages
 *	intended for the error stream will be ignored.
 */
STUMPLESS_PUBLIC_FUNCTION
void
stumpless_set_error_stream( FILE *stream );

#  ifdef __cplusplus
}                               /* extern "C" */
#  endif

#endif                          /* __STUMPLESS_ERROR_H */


text:
<?php

namespace SensioLabs\Behat\PageObjectExtension\Context;

use Behat\Behat\Context\BehatContext;
use SensioLabs\Behat\PageObjectExtension\Context\PageFactory;
use SensioLabs\Behat\PageObjectExtension\PageObject\Page;

class PageObjectContext extends BehatContext implements PageObjectAwareInterface
{
    /**
     * @var PageFactory $pageFactory
     */
    private $pageFactory = null;

    /**
     * @param string $name
     *
     * @return Page
     */
    public function getPage($name)
    {
        if (null === $this->pageFactory) {
            throw new \RuntimeException('To create pages you need to pass a factory with setPageFactory()');
        }

        return $this->pageFactory->createPage($name);
    }

    /**
     * @param PageFactory $pageFactory
     */
    public function setPageFactory(PageFactory $pageFactory)
    {
        $this->pageFactory = $pageFactory;
    }
}


text:
cask "another-redis-desktop-manager" do
  version "1.3.7"
  sha256 "e5a8acdcf8f26c1240430a4702dc0d675d741b227711d33dbff63419673eeca1"

  url "https://github.com/qishibo/AnotherRedisDesktopManager/releases/download/v#{version}/Another-Redis-Desktop-Manager.#{version}.dmg"
  appcast "https://github.com/qishibo/AnotherRedisDesktopManager/releases.atom"
  name "Another Redis Desktop Manager"
  homepage "https://github.com/qishibo/AnotherRedisDesktopManager/"

  app "Another Redis Desktop Manager.app"
end


text:
career

July 2015 - Present

Applications Developer

Develop and support background API's responsible to support Sprint's business logic. Such API's are the main piece of the client's software architecture and are designed to handle hundreds of thousands of transactions per day. They are written in the Java programming language and use a variety of technologies to retrieve data and communicate with other applications such as MQ (Message Queueing with WebsphereMQ), SOAP and REST web services consumption and direct database access with native JDBC queries.

August 2015

Graduated in Information Systems

Graduated in Information Systems at University of São Paulo (USP).

July 2014 - june 2015

Jr. Systems Analyst

In this company, I was responsible for the web development segment of their products. I worked as a full stack web developer focused on developing dashboard like applications for data visualization integrating it with existing VOIP systems (Asterisk) for call management and reporting.

September 2013 - May 2014

Academical Exchange Program in Ireland, Waterfor Institute of Technology (WIT)

Studied a non-degree year abroad in Waterford Institute of Technology, over Science Without Borders program, sponsored by the Brazilian government. Classes related to software development, mobile development, business intelligence and software frameworks.

November 2012 - May 2013

Intern at São Carlos Institute of Physics

Responsible for the development of new features on existing web applications using primarily PHP and MySQL, also responsible for the general IT infrastructure support (Windows support, network support and management) and end user assistance.

January 2009

Entered University of São Paulo (USP-ICMC)

Started studing Computer Science / Information Systems at Institute of Mathematics and Computer Science (ICMC) at University of São Paulo (USP)

START


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Sistem.Web.Models.ViewModel.Managements.MenuSection
{
    public class MenuProcessModel
    {
        [Required]
        public string MenuName { get; set; }
        [Required]
        [Column(TypeName = "Money")]
        public decimal Price { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test 300x250</title>
    <meta name="ad.size" content="width=300,height=250">


text:
import tensorflow as tf
import tensorfx as tfx
from _config import Configuration
from _hooks import *
from _job import Job

class ModelTrainer(object):
  """Provides the functionality to train a model during a training job.
  """
  def __init__(self, config=None):
    """Initializes a ModelTrainer instance.

    Arguments:
      config: an optional configuration providing information about the training job and cluster.
    """
    if not config:
      # By default, use the configuration specified in the TF_CONFIG environment variable.
      config = Configuration.environment()

    self._config = config

  @property
  def config(self):
    """Retrieves the training configuration.
    """
    return self._config

  def train(self, model_builder, inputs, output):
    """Runs the training process to train a model.

    Arguments:
      model_builder: the ModelBuilder to use to build graphs during training.
      inputs: the input dataset for the job.
      output: the output path for the job.
    Returns:
      The trained Model. The resulting value is only relevant for master nodes.
    """
    job = Job(model_builder, inputs, output, self._config)
    job.configure_logging()

    server = self._config.create_server()
    if server and self._config.param_server:
      return self._run_ps(server)

    return self._run_training(server, job)

  def _run_ps(self, server):
    """Runs the parameter server task.

    A ps task runs forever (until killed) using implementation within TensorFlow runtime.
    """
    try:
      server.join()
    except AbortError:
      pass

  def _run_training(self, server, job):
    """Runs the worker and master tasks.

    Worker and master tasks create a TensorFlow session, and run the session loop. The session
    loop is customized via session hooks. A worker simply runs the training logic, while a master
    is also responsible for producing and evaluating checkpoints, as well producing summary event
    logs, and finally exporting the trained model.
    """
    job.start()

    with job.training.graph.as_default() as graph:
      master = server.target if server else ''
      config = self._create_session_config(job)
      hooks = self._create_session_hooks(job)

      if self._config.master:
        session_creator = tf.train.ChiefSessionCreator(job.training.scaffold,
                                                       master, config, job.checkpoints_path)
      else:
        session_creator = tf.train.WorkerSessionCreator(job.training.scaffold, master, config)

      with tf.train.MonitoredSession(session_creator, hooks) as session:
        while not session.should_stop():
          # TODO: Add session run timeouts
          session.run(job.training.train_op)

      if self._config.master:
        return tfx.prediction.Model.load(job.model_path)
      else:
        return None

  def _create_session_config(self, job):
    """Creates the TensorFlow session config object.
    """
    if self._config.local:
      # Don't have each process (esp. in case of distributed simulation) on the local machine to
      # attempt using all CPUs
      parallelism = 1
    else:
      # Use default
      parallelism = 0

    # Limit communication to specific devices. Specifically the goal is to disable communications
    # across workers, so as to increase performance and reliability.
    device_filters = ['/job:ps', self._config.device]

    return tf.ConfigProto(log_device_placement=job.args.log_device_placement,
                          device_filters=device_filters,
                          intra_op_parallelism_threads=parallelism,
                          inter_op_parallelism_threads=parallelism)

  def _create_session_hooks(self, job):
    """Creates the TensorFlow session hooks that customize the session loop.
    """
    hooks = []

    hooks.append(LogSessionHook(job))
    if self._config.master:
      hooks.append(LogTrainingHook(job))
      hooks.append(SaveCheckpointHook(job))
    hooks.append(StopTrainingHook(job))

    return hooks