text:
namespace csapex
{
class Canny : public CornerLineDetection
{
public:
    Canny();
    void process() override;
    void setup(csapex::NodeModifier& node_modifier) override;
    void setupParameters(Parameterizable& parameters) override;

protected:
    void update();

    double threshold_1_;
    double threshold_2_;
    int aperture_size_;
    bool L2_gradient_;
};
}  // namespace csapex

#endif  // CANNY_H


text:
package org.jhove2.module.format.wave;

import java.io.EOFException;
import java.io.IOException;
import org.jhove2.annotation.ReportableProperty;
import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.core.io.Input;
import org.jhove2.core.source.Source;
import org.jhove2.module.format.riff.GenericChunk;

import com.sleepycat.persist.model.Persistent;

/** WAVE fact chunk.
 *
 * @author slabrams
 */
@Persistent
public class FactChunk
    extends GenericChunk
{
    /** Sample length, in bytes. */
    protected long sampleLength;

    /** Instantiate a new FactChunk. */
    public FactChunk() {
        super();
    }

    /**
     * Parse a WAVE chunk.
     *
     * @param jhove2
     *            JHOVE2 framework
     * @param source
     *            WAVE source unit
     * @param input  WAVE source input
     * @return Number of bytes consumed
     * @throws EOFException
     *             If End-of-File is reached reading the source unit
     * @throws IOException
     *             If an I/O exception is raised reading the source unit
     * @throws JHOVE2Exception
     * @see org.jhove2.module.format.Parser#parse(org.jhove2.core.JHOVE2,
     *      org.jhove2.core.source.Source, org.jhove2.core.io.Input)
     */
    @Override
    public long parse(JHOVE2 jhove2, Source source, Input input)
        throws EOFException, IOException, JHOVE2Exception
    {
        long consumed = super.parse(jhove2, source, input);

        /* Sample length. */
        this.sampleLength = input.readUnsignedInt();
        consumed += 4;

        return consumed;
    }

    /** Get fact chunk sample length.
     * @return Fact chunk sample length
     */
    @ReportableProperty(order=1, value="Sample length, in byes.")
    public long getSampleLength() {
        return this.sampleLength;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*************************************************************************

    Atari Gauntlet hardware

*************************************************************************/

#include "machine/atarigen.h"

class gauntlet_state : public atarigen_state
{
public:
	gauntlet_state(const machine_config &mconfig, device_type type, const char *tag)
		: atarigen_state(mconfig, type, tag) { }

	UINT16			m_sound_reset_val;
	UINT8			m_vindctr2_screen_refresh;
	UINT8			m_playfield_tile_bank;
	UINT8			m_playfield_color_bank;
};

/*----------- defined in video/gauntlet.c -----------*/

WRITE16_HANDLER( gauntlet_xscroll_w );
WRITE16_HANDLER( gauntlet_yscroll_w );

VIDEO_START( gauntlet );
SCREEN_UPDATE( gauntlet );


text:
"""
    Salt Edge Account Information API

    API Reference for services  # noqa: E501

    OpenAPI spec version: 5.0.0
    Contact: support@saltedge.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import re  # noqa: F401

# python 2 and python 3 compatibility library
import six

from swagger_client.api_client import ApiClient

class RatesApi(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    Ref: https://github.com/swagger-api/swagger-codegen
    """

    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

    def rates_get(self, **kwargs):  # noqa: E501
        """List of rates  # noqa: E501

        You can get the list of all the currency rates that we support. You will receive the currency rates starting March 21, 2014. If any older date is requested, you will still receive the rates starting March 21, 2014.   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.rates_get(async_req=True)
        >>> result = thread.get()

        :param async_req bool
        :param date _date:
        :return: RatesResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('async_req'):
            return self.rates_get_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.rates_get_with_http_info(**kwargs)  # noqa: E501
            return data

    def rates_get_with_http_info(self, **kwargs):  # noqa: E501
        """List of rates  # noqa: E501

        You can get the list of all the currency rates that we support. You will receive the currency rates starting March 21, 2014. If any older date is requested, you will still receive the rates starting March 21, 2014.   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.rates_get_with_http_info(async_req=True)
        >>> result = thread.get()

        :param async_req bool
        :param date _date:
        :return: RatesResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['_date']  # noqa: E501
        all_params.append('async_req')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in six.iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method rates_get" % key
                )
            params[key] = val
        del params['kwargs']

        collection_formats = {}

        path_params = {}

        query_params = []
        if '_date' in params:
            query_params.append(('date', params['_date']))  # noqa: E501

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = ['app_id', 'secret']  # noqa: E501

        return self.api_client.call_api(
            '/rates', 'GET',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type='RatesResponse',  # noqa: E501
            auth_settings=auth_settings,
            async_req=params.get('async_req'),
            _return_http_data_only=params.get('_return_http_data_only'),
            _preload_content=params.get('_preload_content', True),
            _request_timeout=params.get('_request_timeout'),
            collection_formats=collection_formats)


text:
<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		if(!isset($users[$this->username]))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		elseif($users[$this->username]!==$this->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;
		return !$this->errorCode;
	}

	//以后要放入缓存中
	public static function getuserid($openid){
		if (! empty ( $openid )) {
			$user = User::model ()->get_id ()->findByAttributes ( array (
					'udid' => $openid
			) );
			if(!$user){
				$user=new User();
				$user->udid = $openid;
				$user->create_at=$this->getTime();
				$user->save();
			}
			return $user->id;
		}
		return "";
	}
	public static function getUserOpenid($userid){
		if (! empty ( $userid )) {
			$user = User::model ()->get_id ()->findByPk ($userid);
			return $user->udid;
		}
		return "";
	}
}


text:
namespace NEventStoreExample.Infrastructure
{
  using System;
  using CommonDomain;
  using CommonDomain.Core;
  using LiteGuard;
  using NEventStore;

  public class SnapshotCreator<T> where T : AggregateBase, IMementoCreator
  {
    private readonly IEventStoreRepository repo;
    private readonly int delta;

    public SnapshotCreator(IEventStoreRepository repo, int delta)
    {
      Guard.AgainstNullArgument("repo", repo);
      this.repo = repo;
      this.delta = delta;
    }

    /// <summary>
    /// Save new Aggregate Snapshot depending on specific Snapshoting policies.
    /// NOTE: In real context, it should be an external thread save snapshots, without interfere with online process
    /// </summary>
    public Snapshot SaveSnapShot(Guid id)
    {
      Snapshot result = null;
      T aggregate = this.repo.GetById<T>(id);
      if (aggregate.Version % delta == 0)
      {
        IMemento memento = ((IMementoCreator)aggregate).CreateMemento();
        result = new Snapshot(aggregate.Id.ToString(), aggregate.Version, memento);
        this.repo.EventStore.Advanced.AddSnapshot(result);
      }
      return result;
    }
  }
}


text:
package ml

import (
	"errors"
	"fmt"
	"strings"
)

// Common erros.
var (
	ErrBadDim           = errors.New("dimension of the two matrix differs")
	ErrInconsistentData = errors.New("matrix has different y dimension per x")
	ErrUninitialized    = errors.New("matrix not initialized")
	ErrNotAVector       = errors.New("the current vector has multi dimension")
)

// Matrix .
type Matrix [][]float64

// NewMatrix instantiates a new matrix of (n,m) dimension.
func NewMatrix(n, m int) Matrix {
	ret := make(Matrix, n)
	for i := 0; i < n; i++ {
		ret[i] = make([]float64, m)
	}
	return ret
}

// Dim returns the dimension of the matrix.
func (m Matrix) Dim() (int, int) {
	if len(m) == 0 {
		return 0, 0
	}
	return len(m), len(m[0])
}

// Add adds Kthe given matrix to the current one and return the result.
// Does not change current matrix state.
func (m Matrix) Add(m2 Matrix) Matrix {
	if !m.DimMatch(m2) {
		panic(ErrBadDim)
	}
	ret := NewMatrix(m.Dim())
	for i, line := range m {
		for j := range line {
			ret[i][j] = m[i][j] + m2[i][j]
		}
	}
	return ret
}

// Sub substracts the given matrix to the current one and return the result.
// Does not change current matrix state.
func (m Matrix) Sub(m2 Matrix) Matrix {
	if !m.DimMatch(m2) {
		panic(ErrBadDim)
	}
	ret := NewMatrix(m.Dim())
	for i, line := range m {
		for j := range line {
			ret[i][j] = m[i][j] - m2[i][j]
		}
	}
	return ret
}

// Equal compares the given matrix to the current one.
func (m Matrix) Equal(m2 Matrix) bool {
	// If dim mismatch, mot equal.
	if !m.DimMatch(m2) {
		return false
	}
	// Check each element of both matrix.
	x, y := m.Dim()
	for i := 0; i < x; i++ {
		for j := 0; j < y; j++ {
			if m[i][j] != m2[i][j] {
				return false
			}
		}
	}
	return true
}

// Validate checks if the current matrix is valid.
// NOTE: When instantiating a matrix outside ml.NewMatrix, Validate should be called.
func (m Matrix) Validate() error {
	// Empty matrix is valid, but nil one is not.
	if m == nil {
		return ErrUninitialized
	}
	if len(m) == 0 {
		return nil
	}
	y := len(m[0])
	for _, line := range m {
		if len(line) != y {
			return ErrInconsistentData
		}
	}
	return nil
}

// DimMatch checks if the given matrice has the same dimension as the current one.
func (m Matrix) DimMatch(m2 Matrix) bool {
	x, y := m.Dim()
	x1, y1 := m2.Dim()
	return x == x1 && y == y1
}

// String pretty prints the matrix.
func (m Matrix) String() string {
	if m == nil {
		return "<nil>"
	}
	if len(m) == 0 {
		return "||"
	}
	ret := ""
	for _, line := range m {
		ret += fmt.Sprintf("%4v\n", line)
	}
	return strings.TrimSpace(ret)
}

// Vector is a matrix with 1 column.
type Vector Matrix

// NewVector instantiate a new vector of dimensin n.
func NewVector(n int) Vector {
	return Vector(NewMatrix(n, 1))
}

// Validate checks if the current matrix is valid.
// NOTE: When instantiating a matrix outside ml.NewVector, Validate should be called.
func (v Vector) Validate() error {
	if err := Matrix(v).Validate(); err != nil {
		return err
	}
	if len(v) > 0 && len(v[0]) != 1 {
		return ErrNotAVector
	}
	return nil
}


text:
class LitesqlDocument: public wxDocument
{
  DECLARE_DYNAMIC_CLASS(LitesqlDocument)

private:
public:

  LitesqlDocument(void){};
  ~LitesqlDocument(void);
};

#endif // #ifndef LITESQL_DOCUMENT_H


text:
$(function () {

	/*--------------------------------------------------
	Plugin: Msg Growl
	--------------------------------------------------*/
	$('.growl-type').live ('click', function (e) {
		$.msgGrowl ({
			type: $(this).attr ('data-type')
			, title: 'Header'
			, text: 'Lorem ipsum dolor sit amet, consectetur ipsum dolor sit amet, consectetur.'
		});
	});

	/*--------------------------------------------------
	Plugin: Msg Box
	--------------------------------------------------*/

	$('.msgbox-alert').live ('click', function (e) {
		$.msgbox("The selection includes process white objects. Overprinting such objects is only useful in combination with transparency effects.");
	});

	$('.msgbox-info').live ('click', function (e) {
		$.msgbox("jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.", {type: "info"});
	});

	$('.msgbox-error').live ('click', function (e) {
		$.msgbox("An error 1053 ocurred while perfoming this service operation on the MySql Server service.", {type: "error"});
	});

	$('.msgbox-confirm').live ('click', function (e) {
		$.msgbox("Are you sure that you want to permanently delete the selected element?", {
		  type: "confirm",
		  buttons : [
		    {type: "submit", value: "Yes"},
		    {type: "submit", value: "No"},
		    {type: "cancel", value: "Cancel"}
		  ]
		}, function(result) {
		  	$("#result2").text(result);
			});
	});

	$('.msgbox-prompt').live ('click', function (e) {
		$.msgbox("Insert your name below:", {
		  type: "prompt"
		}, function(result) {
		  if (result) {
		    alert("Hello " + result);
		  }
		});
	});

});


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using Alkaid;

public class TestWindow : BaseWindow {

    public InputField ipLabel;
    public InputField portLabel;
    public Text connectLabel;
    public Text pingLabel;

	public override bool Init ()
	{
		RegisterEvent (EventId.Network);
		RegisterEvent (EventId.Ping);
		return base.Init ();
	}

	public override void OnShow ()
	{
		connectLabel.text = "unknow";
	}

	public override void OnHide ()
	{

	}

	public override void OnUIEventHandler (int eventId, params object[] args)
	{
		if (eventId == (int)EventId.Network) {
			OnNetworkEvent ((bool)args [0]);
		} else if (eventId == (int)EventId.Ping) {
			OnPingEvent ((double)args [0]);
		}
	}

    private void OnNetworkEvent(bool status)
    {
        if (status)
        {
            connectLabel.text = "Connected";
        }
        else
        {
            connectLabel.text = "DisConnected";
        }
    }

    private void OnPingEvent(double ms)
    {
        pingLabel.text = string.Format("{0}ms", (int)ms);
    }

    public void OnConnectClick()
    {
        string ip = ipLabel.text;
        int port = int.Parse(portLabel.text);
        this.StartCoroutine(Rosetta.Instance.ConnectLobby(ip, port));

        Ping();
    }

    public void OnDisconnectClick()
    {
        Rosetta.Instance.DisconnectLobby();

    }

    private void Ping()
    {
        Rosetta.Instance.Ping();

        Invoke("Ping", 1);
    }

}


text:
package hitwh.xyz.coolweatherbyxyz;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (prefs.getString("weather",null)!=null) {
            Intent intent = new Intent(this, WeatherActivity.class);
            startActivity(intent);
            finish();
        }
    }
}


text:
/**
 * Teacher
 *
 * @module      :: Model
 * @description :: A short summary of how this model works and what it represents.
 * @docs		:: http://sailsjs.org/#!documentation/models
 */

module.exports = {

  attributes: {
  	name: 'string',

		students: {
			collection: 'student'
		},

		classroom: {
			model: 'classroom',
			required: true
		}
  }

};


text:
.. _ASSERT_COLUMN_EXISTS:

==============================
ASSERT_COLUMN_EXISTS procedure
==============================

Raises an assertion error if the specified column doesn't exist.

Prototypes
==========

.. code-block:: sql

    ASSERT_COLUMN_EXISTS(ASCHEMA VARCHAR(128), ATABLE VARCHAR(128), ACOLNAME VARCHAR(128))
    ASSERT_COLUMN_EXISTS(ATABLE VARCHAR(128), ACOLNAME VARCHAR(128))

Description
===========

Raises the :ref:`ASSERT_FAILED_STATE` state if **ACOLNAME** does not exist in
the table specified by **ASCHEMA** and **ATABLE**. If not specified,
**ASCHEMA** defaults to the value of the *CURRENT SCHEMA* special register.

Parameters
==========

ASCHEMA
    Specifies the schema containing the table to check. If omitted, defaults to
    the value of the *CURRENT SCHEMA* special register.

ATABLE
    Specifies the name of the table to check.

ACOLNAME
    Specifies the name of the column to test for existence.

Examples
========

Test the TABNAME column exists in the SYSCAT.TABLES view:

.. code-block:: sql

    CALL ASSERT_COLUMN_EXISTS('SYSCAT', 'TABLES', 'TABNAME');

Test the existence of a made-up column in the SYSCAT.TABLES view:

.. code-block:: sql

    CALL ASSERT_COLUMN_EXISTS('SYSCAT', 'TABLES', 'FOO');

::

    SQL0438N  Application raised error or warning with diagnostic text: "FOO
    does not exist in SYSCAT.TABLES                 ".  SQLSTATE=90001

See Also
========

* `Source code`_
* :ref:`ASSERT_TABLE_EXISTS`
* :ref:`ASSERT_TRIGGER_EXISTS`
* :ref:`ASSERT_ROUTINE_EXISTS`
* :ref:`ASSERT_FAILED_STATE`

.. _Source code: https://github.com/waveform-computing/db2utils/blob/master/assert.sql#L164


text:
(function (collections, model, Teeble) {

    collections.PaginatedCollection = Teeble.ClientCollection.extend({
        model: model,
        sortbarColumns: [
            "grade",
            "os",
            "version"
        ],
        sortbarSortOptions: {
            "name": "Name"
        },
        sortbarColumnOptions: {
            "platform": "Platform",
            "os": "Operating System",
            "version": "Version",
            "grade": "Grade"
        },

        paginator_core: {
            // the type of the request (GET by default)
            type: 'GET',

            // the URL (or base URL) for the service
            url: 'data.json'
        },

        paginator_ui: {
            // the lowest page index your API allows to be accessed
            firstPage: 1,

            // which page should the paginator start from
            // (also, the actual page the paginator is on)
            currentPage: 1,

            // how many items per page should be shown
            perPage: 10,

            // a default number of total pages to query in case the API or
            // service you are using does not support providing the total
            // number of pages for us.
            // 10 as a default in case your service doesn't return the total
            totalPages: 10,

            pagesInRange: 3
        },

        server_api: {
        },

        parse: function (response) {
            var data = response.data;
            return data;
        }

    });

})( app.collections, app.models.Item, Teeble);


text:
package api

import (
	"bytes"
	"fmt"
	"reflect"
	"sort"
	"strings"
)

type examplesBuilder interface {
	BuildShape(*ShapeRef, map[string]interface{}, bool) string
	BuildList(string, string, *ShapeRef, []interface{}) string
	BuildComplex(string, string, *ShapeRef, map[string]interface{}) string
	Imports(*API) string
}

type defaultExamplesBuilder struct{}

// BuildShape will recursively build the referenced shape based on the json object
// provided.
// isMap will dictate how the field name is specified. If isMap is true, we will expect
// the member name to be quotes like "Foo".
func (builder defaultExamplesBuilder) BuildShape(ref *ShapeRef, shapes map[string]interface{}, isMap bool) string {
	order := make([]string, len(shapes))
	for k := range shapes {
		order = append(order, k)
	}
	sort.Strings(order)

	ret := ""
	for _, name := range order {
		if name == "" {
			continue
		}
		shape := shapes[name]

		// If the shape isn't a map, we want to export the value, since every field
		// defined in our shapes are exported.
		if len(name) > 0 && !isMap && strings.ToLower(name[0:1]) == name[0:1] {
			name = strings.Title(name)
		}

		memName := name
		if isMap {
			memName = fmt.Sprintf("%q", memName)
		}

		switch v := shape.(type) {
		case map[string]interface{}:
			ret += builder.BuildComplex(name, memName, ref, v)
		case []interface{}:
			ret += builder.BuildList(name, memName, ref, v)
		default:
			ret += builder.BuildScalar(name, memName, ref, v)
		}
	}
	return ret
}

// BuildList will construct a list shape based off the service's definition
// of that list.
func (builder defaultExamplesBuilder) BuildList(name, memName string, ref *ShapeRef, v []interface{}) string {
	ret := ""

	if len(v) == 0 || ref == nil {
		return ""
	}

	t := ""
	dataType := ""
	format := ""
	isComplex := false
	passRef := ref
	isMap := false

	if ref.Shape.MemberRefs[name] != nil {
		t = builder.GoType(&ref.Shape.MemberRefs[name].Shape.MemberRef, false)
		dataType = ref.Shape.MemberRefs[name].Shape.MemberRef.Shape.Type
		passRef = ref.Shape.MemberRefs[name]
		if dataType == "map" {
			t = fmt.Sprintf("map[string]%s", builder.GoType(&ref.Shape.MemberRefs[name].Shape.MemberRef.Shape.ValueRef, false))
			passRef = &ref.Shape.MemberRefs[name].Shape.MemberRef.Shape.ValueRef
			isMap = true
		}
	} else if ref.Shape.MemberRef.Shape != nil && ref.Shape.MemberRef.Shape.MemberRefs[name] != nil {
		t = builder.GoType(&ref.Shape.MemberRef.Shape.MemberRefs[name].Shape.MemberRef, false)
		dataType = ref.Shape.MemberRef.Shape.MemberRefs[name].Shape.MemberRef.Shape.Type
		passRef = &ref.Shape.MemberRef.Shape.MemberRefs[name].Shape.MemberRef
	} else {
		t = builder.GoType(&ref.Shape.MemberRef, false)
		dataType = ref.Shape.MemberRef.Shape.Type
		passRef = &ref.Shape.MemberRef
	}

	switch v[0].(type) {
	case string:
		format = "%s"
	case bool:
		format = "%t"
	case float64:
		if dataType == "integer" || dataType == "int64" {
			format = "%d"
		} else {
			format = "%f"
		}
	default:
		if ref.Shape.MemberRefs[name] != nil {
		} else {
			passRef = ref.Shape.MemberRef.Shape.MemberRefs[name]

			// if passRef is nil that means we are either in a map or within a nested array
			if passRef == nil {
				passRef = &ref.Shape.MemberRef
			}
		}
		isComplex = true
	}
	ret += fmt.Sprintf("%s: []%s {\n", memName, t)
	for _, elem := range v {
		if isComplex {
			ret += fmt.Sprintf("{\n%s\n},\n", builder.BuildShape(passRef, elem.(map[string]interface{}), isMap))
		} else {
			if dataType == "integer" || dataType == "int64" || dataType == "long" {
				elem = int(elem.(float64))
			}
			ret += fmt.Sprintf("%s,\n", getValue(t, fmt.Sprintf(format, elem)))
		}
	}
	ret += "},\n"
	return ret
}

// BuildScalar will build atomic Go types.
func (builder defaultExamplesBuilder) BuildScalar(name, memName string, ref *ShapeRef, shape interface{}) string {
	if ref == nil || ref.Shape == nil {
		return ""
	} else if ref.Shape.MemberRefs[name] == nil {
		if ref.Shape.MemberRef.Shape != nil && ref.Shape.MemberRef.Shape.MemberRefs[name] != nil {
			return correctType(memName, ref.Shape.MemberRef.Shape.MemberRefs[name].Shape.Type, shape)
		}
		if ref.Shape.Type != "structure" && ref.Shape.Type != "map" {
			return correctType(memName, ref.Shape.Type, shape)
		}
		return ""
	}

	switch v := shape.(type) {
	case bool:
		return convertToCorrectType(memName, ref.Shape.MemberRefs[name].Shape.Type, fmt.Sprintf("%t", v))
	case int:
		if ref.Shape.MemberRefs[name].Shape.Type == "timestamp" {
			return parseTimeString(ref, memName, fmt.Sprintf("%d", v))
		}
		return convertToCorrectType(memName, ref.Shape.MemberRefs[name].Shape.Type, fmt.Sprintf("%d", v))
	case float64:
		dataType := ref.Shape.MemberRefs[name].Shape.Type
		if dataType == "integer" || dataType == "int64" || dataType == "long" {
			return convertToCorrectType(memName, ref.Shape.MemberRefs[name].Shape.Type, fmt.Sprintf("%d", int(shape.(float64))))
		}
		return convertToCorrectType(memName, ref.Shape.MemberRefs[name].Shape.Type, fmt.Sprintf("%f", v))
	case string:
		t := ref.Shape.MemberRefs[name].Shape.Type
		switch t {
		case "timestamp":
			return parseTimeString(ref, memName, fmt.Sprintf("%s", v))
		case "blob":
			if (ref.Shape.MemberRefs[name].Streaming || ref.Shape.MemberRefs[name].Shape.Streaming) && ref.Shape.Payload == name {
				return fmt.Sprintf("%s: aws.ReadSeekCloser(strings.NewReader(%q)),\n", memName, v)
			}

			return fmt.Sprintf("%s: []byte(%q),\n", memName, v)
		default:
			return convertToCorrectType(memName, t, v)
		}
	default:
		panic(fmt.Errorf("Unsupported scalar type: %v", reflect.TypeOf(v)))
	}
	return ""
}

func (builder defaultExamplesBuilder) BuildComplex(name, memName string, ref *ShapeRef, v map[string]interface{}) string {
	t := ""
	if ref == nil {
		return builder.BuildShape(nil, v, true)
	}

	member := ref.Shape.MemberRefs[name]

	if member != nil && member.Shape != nil {
		t = ref.Shape.MemberRefs[name].Shape.Type
	} else {
		t = ref.Shape.Type
	}

	switch t {
	case "structure":
		passRef := ref.Shape.MemberRefs[name]
		// passRef will be nil if the entry is a map. In that case
		// we want to pass the reference, because the previous call
		// passed the value reference.
		if passRef == nil {
			passRef = ref
		}
		return fmt.Sprintf(`%s: &%s{
				%s
			},
			`, memName, builder.GoType(passRef, true), builder.BuildShape(passRef, v, false))
	case "map":
		return fmt.Sprintf(`%s: %s{
				%s
			},
			`, name, builder.GoType(ref.Shape.MemberRefs[name], false), builder.BuildShape(&ref.Shape.MemberRefs[name].Shape.ValueRef, v, true))
	}

	return ""
}

func (builder defaultExamplesBuilder) GoType(ref *ShapeRef, elem bool) string {
	prefix := ""
	if ref.Shape.Type == "list" {
		ref = &ref.Shape.MemberRef
		prefix = "[]*"
	}

	name := ref.GoTypeWithPkgName()
	if elem {
		name = ref.GoTypeElem()
		if !strings.Contains(name, ".") {
			name = strings.Join([]string{ref.API.PackageName(), name}, ".")
		}
	}

	if ref.Shape.Type != "structure" && ref.Shape.Type != "list" {
		return name
	}

	return prefix + name
}

func (builder defaultExamplesBuilder) Imports(a *API) string {
	buf := bytes.NewBuffer(nil)
	buf.WriteString(`"fmt"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/session"
	`)

	buf.WriteString(fmt.Sprintf("\"%s/%s\"", "github.com/aws/aws-sdk-go/service", a.PackageName()))
	return buf.String()
}
//Added a line for testing
//Adding another line for Git event testing part 2
//Adding another line for Git event testing part 2.1
//Adding another line for Git event testing part 2.2


text:
import _ from 'lodash';

const merge = _.assign;

function arrayDiffer(a, b) {
    if (_.isNil(a) || _.isNil(b) ) {
        return true;
    }
    if (a.length !== b.length) {
        return true;
    }
    for (var i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            return true;
        }
    }
    return false;
}

function fontAndLinesDiffer(a, b) {
    if (a === b) {
        return false;
    }
    if (a.font !== b.font) {
        if (a.font === null) {
            return true;
        }
        if (b.font === null) {
            return true;
        }

        if (
            a.font.fontFamily !== b.font.fontFamily ||
            a.font.fontSize !== b.font.fontSize ||
            a.font.fontWeight !== b.font.fontWeight ||
            a.font.fontStyle !== b.font.fontStyle
        ) {
            return true;
        }
    }
    return arrayDiffer(a.lines, b.lines);
}

const ViewBoxAttributes = {
    minX: true,
    minY: true,
    vbWidth: true,
    vbHeight: true,
    align: true,
    meetOrSlice: true,
    name: true
};

const NodeAttributes = {
    name: true,
    matrix: {
        diff: arrayDiffer
    },
    opacity: true,
    clipRule: true,
    clipPath: true,
    propList: {
        diff: arrayDiffer
    },
    responsible: true
};

const RenderableOnlyAttributes = {
    fill: {
        diff: arrayDiffer
    },
    fillOpacity: true,
    fillRule: true,
    stroke: {
        diff: arrayDiffer
    },
    strokeOpacity: true,
    strokeWidth: true,
    strokeLinecap: true,
    strokeLinejoin: true,
    strokeDasharray: {
        diff: arrayDiffer
    },
    strokeDashoffset: true,
    strokeMiterlimit: true
};

const RenderableAttributes = merge({}, NodeAttributes, RenderableOnlyAttributes);

const GroupAttributes = RenderableAttributes;

const UseAttributes = merge({
    href: true,
    width: true,
    height: true
}, RenderableAttributes);

const PathAttributes = merge({
    d: true
}, RenderableAttributes);

const TextAttributes = merge({
    alignment: true,
    frame: {
        diff: fontAndLinesDiffer
    },
    path: {
        diff: arrayDiffer
    }
}, RenderableAttributes);

const ClipPathAttributes = {
    name: true
};

const LinearGradientAttributes = merge({
    x1: true,
    y1: true,
    x2: true,
    y2: true,
    gradient: {
        diff: arrayDiffer
    }
}, ClipPathAttributes);

const RadialGradientAttributes = merge({
    fx: true,
    fy: true,
    rx: true,
    ry: true,
    cx: true,
    cy: true,
    r: true,
    gradient: {
        diff: arrayDiffer
    }
}, ClipPathAttributes);

const CircleAttributes = merge({
    cx: true,
    cy: true,
    r: true
}, RenderableAttributes);

const EllipseAttributes = merge({
    cx: true,
    cy: true,
    rx: true,
    ry: true
}, RenderableAttributes);

const ImageAttributes = merge({
    x: true,
    y: true,
    width: true,
    height: true,
    src: true,
    align: true,
    meetOrSlice: true
}, RenderableAttributes);

const LineAttributes = merge({
    x1: true,
    y1: true,
    x2: true,
    y2: true
}, RenderableAttributes);

const RectAttributes = merge({
    x: true,
    y: true,
    width: true,
    height: true,
    rx: true,
    ry: true
}, RenderableAttributes);

export {
    PathAttributes,
    TextAttributes,
    GroupAttributes,
    ClipPathAttributes,
    CircleAttributes,
    EllipseAttributes,
    ImageAttributes,
    LineAttributes,
    RectAttributes,
    UseAttributes,
    RenderableOnlyAttributes,
    LinearGradientAttributes,
    RadialGradientAttributes,
    ViewBoxAttributes
};


text:
package org.apache.lens.cube.metadata;

import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;

import com.google.common.base.Preconditions;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * Abstract table with expressions
 */
@Getter
@Slf4j
public abstract class AbstractBaseTable extends AbstractCubeTable {
  private final Set<ExprColumn> expressions;
  private static final List<FieldSchema> COLUMNS = new ArrayList<FieldSchema>();
  private final Map<String, ExprColumn> exprMap;
  @Getter
  private final Set<JoinChain> joinChains;
  private final Map<String, JoinChain> chainMap;

  static {
    COLUMNS.add(new FieldSchema("dummy", "string", "dummy column"));
  }

  public AbstractBaseTable(String name, Set<ExprColumn> exprs, Set<JoinChain> joinChains, Map<String, String>
    properties, double weight) {
    super(name, COLUMNS, properties, weight);

    exprMap = new HashMap<String, ExprColumn>();
    if (exprs == null) {
      this.expressions = new HashSet<ExprColumn>();
    } else {
      this.expressions = exprs;
    }

    for (ExprColumn expr : expressions) {
      exprMap.put(expr.getName().toLowerCase(), expr);
    }

    if (joinChains != null) {
      this.joinChains = joinChains;
    } else {
      this.joinChains = new HashSet<JoinChain>();
    }

    chainMap = new HashMap<String, JoinChain>();
    for (JoinChain chain : this.joinChains) {
      chainMap.put(chain.getName().toLowerCase(), chain);
    }
  }

  public AbstractBaseTable(Table tbl) {
    super(tbl);
    this.expressions = getExpressions(getName(), getProperties());
    exprMap = new HashMap<String, ExprColumn>();
    for (ExprColumn expr : expressions) {
      exprMap.put(expr.getName().toLowerCase(), expr);
    }
    this.joinChains = getJoinChains(this, getJoinChainListPropKey(getName()), getProperties());
    chainMap = new HashMap<String, JoinChain>();
    for (JoinChain chain : joinChains) {
      chainMap.put(chain.getName().toLowerCase(), chain);
    }
  }

  @Override
  public Set<String> getStorages() {
    return null;
  }

  @Override
  public void addProperties() {
    super.addProperties();
    MetastoreUtil.addNameStrings(getProperties(), MetastoreUtil.getExpressionListKey(getName()), expressions);
    setExpressionProperties(getProperties(), expressions);
    MetastoreUtil.addNameStrings(getProperties(), getJoinChainListPropKey(getName()), joinChains);
    setJoinChainProperties(joinChains);
  }

  private static void setExpressionProperties(Map<String, String> props, Set<ExprColumn> expressions) {
    for (ExprColumn expr : expressions) {
      expr.addProperties(props);
    }
  }

  private static Set<ExprColumn> getExpressions(String name, Map<String, String> props) {
    Set<ExprColumn> exprs = new HashSet<ExprColumn>();
    String exprStr = MetastoreUtil.getNamedStringValue(props, MetastoreUtil.getExpressionListKey(name));
    if (!StringUtils.isBlank(exprStr)) {
      String[] names = exprStr.split(",");
      for (String exprName : names) {
        ExprColumn expr = new ExprColumn(exprName, props);
        exprs.add(expr);
      }
    }
    return exprs;
  }

  @Override
  public int hashCode() {
    return super.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    if (!super.equals(obj)) {
      return false;
    }
    AbstractBaseTable other = (AbstractBaseTable) obj;
    if (this.getExpressions() == null) {
      if (other.getExpressions() != null) {
        return false;
      }
    } else if (!this.getExpressions().equals(other.getExpressions())) {
      return false;
    }

    if (this.getJoinChains() == null) {
      if (other.getJoinChains() != null) {
        return false;
      }
    } else if (!this.getJoinChains().equals(other.getJoinChains())) {
      return false;
    }
    return true;
  }

  public ExprColumn getExpressionByName(String exprName) {
    return exprMap.get(exprName == null ? exprName : exprName.toLowerCase());
  }

  public CubeColumn getColumnByName(String column) {
    return getExpressionByName(column);
  }

  /**
   * Alters the expression if already existing or just adds if it is new expression.
   *
   * @param expr
   * @throws HiveException
   */
  public void alterExpression(ExprColumn expr) throws HiveException {
    if (expr == null) {
      throw new NullPointerException("Cannot add null expression");
    }

    // Replace measure if already existing
    if (exprMap.containsKey(expr.getName().toLowerCase())) {
      expressions.remove(getExpressionByName(expr.getName()));
      log.info("Replacing expression {} with {}", getExpressionByName(expr.getName()), expr);
    }

    expressions.add(expr);
    exprMap.put(expr.getName().toLowerCase(), expr);
    MetastoreUtil.addNameStrings(getProperties(), MetastoreUtil.getExpressionListKey(getName()), expressions);
    expr.addProperties(getProperties());
  }

  /**
   * Remove the measure with name specified
   *
   * @param exprName
   */
  public void removeExpression(String exprName) {
    if (exprMap.containsKey(exprName.toLowerCase())) {
      log.info("Removing expression {}", getExpressionByName(exprName));
      expressions.remove(getExpressionByName(exprName));
      exprMap.remove(exprName.toLowerCase());
      MetastoreUtil.addNameStrings(getProperties(), MetastoreUtil.getExpressionListKey(getName()), expressions);
    }
  }

  public Set<String> getExpressionNames() {
    Set<String> exprNames = new HashSet<String>();
    for (ExprColumn f : getExpressions()) {
      exprNames.add(f.getName().toLowerCase());
    }
    return exprNames;
  }

  /**
   * @return the expressions
   */
  public Set<ExprColumn> getExpressions() {
    return expressions;
  }

  public Set<String> getAllFieldNames() {
    return getExpressionNames();
  }

  public void setJoinChainProperties(Set<JoinChain> chains) {
    for (JoinChain chain : chains) {
      chain.addProperties(this);
    }
  }

  /**
   * Alters the joinchain if already existing or just adds if it is new chain
   *
   * @param joinchain
   * @throws HiveException
   */
  public void alterJoinChain(JoinChain joinchain) throws HiveException {
    if (joinchain == null) {
      throw new NullPointerException("Cannot add null joinchain");
    }

    // Replace dimension if already existing
    if (chainMap.containsKey(joinchain.getName().toLowerCase())) {
      joinChains.remove(getChainByName(joinchain.getName()));
      log.info("Replacing joinchain {} with {}", getChainByName(joinchain.getName()), joinchain);
    }

    joinChains.add(joinchain);
    chainMap.put(joinchain.getName().toLowerCase(), joinchain);
    MetastoreUtil.addNameStrings(getProperties(), getJoinChainListPropKey(getName()), joinChains);
    joinchain.addProperties(this);
  }

  public JoinChain getChainByName(String name) {
    Preconditions.checkNotNull(name);
    return chainMap.get(name.toLowerCase());
  }

  /**
   * Returns the property key for Cube/Dimension specific join chain list
   *
   * @param tblname
   * @return
   */
  protected abstract String getJoinChainListPropKey(String tblname);

  /**
   * Get join chains from properties
   *
   * @return
   */
  private static Set<JoinChain> getJoinChains(AbstractBaseTable tbl, String propName, Map<String, String> props) {
    Set<JoinChain> joinChains = new HashSet<JoinChain>();
    String joinChainsStr = MetastoreUtil.getNamedStringValue(props, propName);
    if (!StringUtils.isBlank(joinChainsStr)) {
      String[] cnames = joinChainsStr.split(",");
      for (String chainName : cnames) {
        JoinChain chain = new JoinChain(tbl, chainName);
        joinChains.add(chain);
      }
    }
    return joinChains;
  }

  public Set<String> getJoinChainNames() {
    Set<String> chainNames = new HashSet<String>();
    for (JoinChain f : getJoinChains()) {
      chainNames.add(f.getName().toLowerCase());
    }
    return chainNames;
  }

  /**
   * Remove the joinchain with name specified
   *
   * @param chainName
   */
  public boolean removeJoinChain(String chainName) {
    if (chainMap.containsKey(chainName.toLowerCase())) {
      joinChains.remove(getChainByName(chainName));
      chainMap.remove(chainName.toLowerCase());
      MetastoreUtil.addNameStrings(getProperties(), getJoinChainListPropKey(getName()), joinChains);
      return true;
    }
    return false;
  }

}


text:
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;

[InitializeOnLoad]
#endif
public class FBSettings : ScriptableObject
{

    const string facebookSettingsAssetName = "FacebookSettings";
    const string facebookSettingsPath = "Facebook/Resources";
    const string facebookSettingsAssetExtension = ".asset";

    private static FBSettings instance;

    static FBSettings Instance
    {
        get
        {
            if (instance == null)
            {
                instance = Resources.Load(facebookSettingsAssetName) as FBSettings;
                if (instance == null)
                {
                    // If not found, autocreate the asset object.
                    instance = CreateInstance<FBSettings>();
#if UNITY_EDITOR
                    string properPath = Path.Combine(Application.dataPath, facebookSettingsPath);
                    if (!Directory.Exists(properPath))
                    {
                        AssetDatabase.CreateFolder("Assets/Facebook", "Resources");
                    }

                    string fullPath = Path.Combine(Path.Combine("Assets", facebookSettingsPath),
                                                   facebookSettingsAssetName + facebookSettingsAssetExtension
                                                  );
                    AssetDatabase.CreateAsset(instance, fullPath);
#endif
                }
            }
            return instance;
        }
    }

#if UNITY_EDITOR
    [MenuItem("Facebook/Edit Settings")]
    public static void Edit()
    {
        Selection.activeObject = Instance;
    }

    [MenuItem("Facebook/Developers Page")]
    public static void OpenAppPage()
    {
        string url = "https://developers.facebook.com/apps/";
        if (Instance.AppIds[Instance.SelectedAppIndex] != "0")
            url += Instance.AppIds[Instance.SelectedAppIndex];
        Application.OpenURL(url);
    }

    [MenuItem("Facebook/SDK Documentation")]
    public static void OpenDocumentation()
    {
        string url = "https://developers.facebook.com/games/unity/";
        Application.OpenURL(url);
    }

    [MenuItem("Facebook/SDK Facebook Group")]
    public static void OpenFacebookGroup()
    {
        string url = "https://www.facebook.com/groups/491736600899443/";
        Application.OpenURL(url);
    }

    [MenuItem("Facebook/Report a SDK Bug")]
    public static void ReportABug()
    {
        string url = "https://developers.facebook.com/bugs/create";
        Application.OpenURL(url);
    }
#endif

    #region App Settings

    [SerializeField]
    private int selectedAppIndex = 0;
    [SerializeField]
    private string[] appIds = new[] { "0" };
    [SerializeField]
    private string[] appLabels = new[] { "App Name" };
    [SerializeField]
    private bool cookie = true;
    [SerializeField]
    private bool logging = true;
    [SerializeField]
    private bool status = true;
    [SerializeField]
    private bool xfbml = false;
    [SerializeField]
    private bool frictionlessRequests = true;
    [SerializeField]
    private string iosURLSuffix = "";

    public void SetAppIndex(int index)
    {
        if (selectedAppIndex != index)
        {
            selectedAppIndex = index;
            DirtyEditor();
        }
    }

    public int SelectedAppIndex
    {
        get { return selectedAppIndex; }
    }

    public void SetAppId(int index, string value)
    {
        if (appIds[index] != value)
        {
            appIds[index] = value;
            DirtyEditor();
        }
    }

    public string[] AppIds
    {
        get { return appIds; }
        set
        {
            if (appIds != value)
            {
                appIds = value;
                DirtyEditor();
            }
        }
    }

    public void SetAppLabel(int index, string value)
    {
        if (appLabels[index] != value)
        {
            AppLabels[index] = value;
            DirtyEditor();
        }
    }

    public string[] AppLabels
    {
        get { return appLabels; }
        set
        {
            if (appLabels != value)
            {
                appLabels = value;
                DirtyEditor();
            }
        }
    }

    public static string[] AllAppIds
    {
        get
        {
            return Instance.AppIds;
        }
    }

    public static string AppId
    {
        get
        {
            return Instance.AppIds[Instance.SelectedAppIndex];
        }
    }

    public static bool IsValidAppId
    {
        get
        {
            return FBSettings.AppId != null
                && FBSettings.AppId.Length > 0
                && !FBSettings.AppId.Equals("0");
        }
    }

    public static bool Cookie
    {
        get { return Instance.cookie; }
        set
        {
            if (Instance.cookie != value)
            {
                Instance.cookie = value;
                DirtyEditor();
            }
        }
    }

    public static bool Logging
    {
        get { return Instance.logging; }
        set
        {
            if (Instance.logging != value)
            {
                Instance.logging = value;
                DirtyEditor();
            }
        }
    }

    public static bool Status
    {
        get { return Instance.status; }
        set
        {
            if (Instance.status != value)
            {
                Instance.status = value;
                DirtyEditor();
            }
        }
    }

    public static bool Xfbml
    {
        get { return Instance.xfbml; }
        set
        {
            if (Instance.xfbml != value)
            {
                Instance.xfbml = value;
                DirtyEditor();
            }
        }
    }

    public static string IosURLSuffix
    {
        get { return Instance.iosURLSuffix; }
        set
        {
            if (Instance.iosURLSuffix != value)
            {
                Instance.iosURLSuffix = value;
                DirtyEditor ();
            }
        }
    }

    public static string ChannelUrl
    {
        get { return "/channel.html"; }
    }

    public static bool FrictionlessRequests
    {
        get { return Instance.frictionlessRequests; }
        set
        {
            if (Instance.frictionlessRequests != value)
            {
                Instance.frictionlessRequests = value;
                DirtyEditor();
            }
        }
    }

#if UNITY_EDITOR

    private string testFacebookId = "";
    private string testAccessToken = "";

    public static string TestFacebookId
    {
        get { return Instance.testFacebookId; }
        set
        {
            if (Instance.testFacebookId != value)
            {
                Instance.testFacebookId = value;
                DirtyEditor();
            }
        }
    }

    public static string TestAccessToken
    {
        get { return Instance.testAccessToken; }
        set
        {
            if (Instance.testAccessToken != value)
            {
                Instance.testAccessToken = value;
                DirtyEditor();
            }
        }
    }
#endif

    private static void DirtyEditor()
    {
#if UNITY_EDITOR
        EditorUtility.SetDirty(Instance);
#endif
    }

    #endregion
}


text:
<?php

/**
 * Newsletter template preview block
 */
namespace Magento\Newsletter\Block\Adminhtml\Template;

class Preview extends \Magento\Backend\Block\Widget
{
    /**
     * Name for profiler
     *
     * @var string
     */
    protected $profilerName = "newsletter_template_proccessing";

    /**
     * @var \Magento\Newsletter\Model\TemplateFactory
     */
    protected $_templateFactory;

    /**
     * @var \Magento\Newsletter\Model\SubscriberFactory
     */
    protected $_subscriberFactory;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Newsletter\Model\TemplateFactory $templateFactory
     * @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Newsletter\Model\TemplateFactory $templateFactory,
        \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
        array $data = []
    ) {
        $this->_templateFactory = $templateFactory;
        $this->_subscriberFactory = $subscriberFactory;
        parent::__construct($context, $data);
    }

    /**
     * Get html code
     *
     * @return string
     */
    protected function _toHtml()
    {
        /* @var $template \Magento\Newsletter\Model\Template */
        $template = $this->_templateFactory->create();

        if ($id = (int)$this->getRequest()->getParam('id')) {
            $this->loadTemplate($template, $id);
        } else {
            $template->setTemplateType($this->getRequest()->getParam('type'));
            $template->setTemplateText($this->getRequest()->getParam('text'));
            $template->setTemplateStyles($this->getRequest()->getParam('styles'));
        }

        \Magento\Framework\Profiler::start($this->profilerName);
        $vars = [];

        $vars['subscriber'] = $this->_subscriberFactory->create();
        if ($this->getRequest()->getParam('subscriber')) {
            $vars['subscriber']->load($this->getRequest()->getParam('subscriber'));
        }

        $template->emulateDesign($this->getStoreId());
        $templateProcessed = $this->_appState->emulateAreaCode(
            \Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA,
            [$template, 'getProcessedTemplate'],
            [$vars]
        );
        $template->revertDesign();

        if ($template->isPlain()) {
            $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>";
        }

        \Magento\Framework\Profiler::stop($this->profilerName);

        return $templateProcessed;
    }

    /**
     * Get Store Id from request or default
     *
     * @return int|null
     */
    protected function getStoreId()
    {
        $storeId = (int)$this->getRequest()->getParam('store');
        if ($storeId) {
            return $storeId;
        }

        $defaultStore = $this->_storeManager->getDefaultStoreView();
        if (!$defaultStore) {
            $allStores = $this->_storeManager->getStores();
            if (isset($allStores[0])) {
                $defaultStore = $allStores[0];
            }
        }

        return $defaultStore ? $defaultStore->getId() : null;
    }

    /**
     * @param \Magento\Newsletter\Model\Template $template
     * @param string $id
     * @return $this
     */
    protected function loadTemplate(\Magento\Newsletter\Model\Template $template, $id)
    {
        $template->load($id);
        return $this;
    }
}


text:
============
Nablarch API
============

* :javadoc_url:`Nablarch API Documentation(for architects) <nablarch-all/publishedApiDoc/architect/>`
* :javadoc_url:`Nablarch API Documentation(for application programmers) <nablarch-all/publishedApiDoc/programmer/>`
* :javadoc_url:`Nablarch Testing API Documentation(for architects) <nablarch-testing/publishedApiDoc/architect/>`
* :javadoc_url:`Nablarch Testing API Documentation(for application programmers) <nablarch-testing/publishedApiDoc/programmer/>`


text:
FROM nginx:1.11-alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY dist/ /usr/share/nginx/html

CMD set -o xtrace errexit;\
    nginx -t -c /etc/nginx/nginx.conf;\
    exec nginx -g 'daemon off;'


text:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


text:
package io.fintrospect.formats

import java.math.BigInteger

import com.twitter.finagle.http.Status
import io.circe.{Decoder, Encoder, Json}
import io.fintrospect.ResponseSpec
import io.fintrospect.formats.Circe.JsonFormat.encode
import io.fintrospect.formats.JsonFormat.{InvalidJson, InvalidJsonForDecoding}
import io.fintrospect.parameters._

/**
  * Circe JSON support (application/json content type)
  */
object Circe extends JsonLibrary[Json, Json] {

  /**
    * Auto-marshalling Service wrappers that can be used to create Services which take and return domain objects
    * instead of HTTP responses
    */
  object Auto extends Auto[Json](ResponseBuilder) {

    implicit def tToBody[T](implicit e: Encoder[T], d: Decoder[T]): Body[T] = Body.of(bodySpec[T]())

    implicit def tToJson[T](implicit e: Encoder[T]): (T => Json) = (t: T) => e(t)
  }

  object JsonFormat extends JsonFormat[Json, Json] {

    override def parse(in: String): Json = io.circe.jawn.parse(in) match {
      case Right(r) => r
      case Left(e) => throw new InvalidJson
    }

    override def pretty(node: Json): String = node.spaces2

    override def compact(node: Json): String = node.noSpaces

    override def obj(fields: Iterable[Field]): Json = Json.obj(fields.map(f => (f._1, f._2)).toSeq: _*)

    override def array(elements: Iterable[Json]) = Json.arr(elements.toSeq: _*)

    override def string(value: String) = Json.fromString(value)

    override def number(value: Int) = Json.fromInt(value)

    override def number(value: Double) = Json.fromDoubleOrString(value)

    override def number(value: BigDecimal) = Json.fromBigDecimal(value.doubleValue)

    override def number(value: Long) = Json.fromLong(value)

    override def number(value: BigInteger) = Json.fromBigInt(value)

    override def boolean(value: Boolean) = Json.fromBoolean(value)

    override def nullNode() = Json.Null

    def encode[T](in: T)(implicit e: Encoder[T]) = e(in)

    def decode[T](in: Json)(implicit d: Decoder[T]) = d.decodeJson(in) match {
      case Right(r) => r
      case Left(_) => throw new InvalidJsonForDecoding
    }
  }

  /**
    * Function that will modify a given case class with the fields from a incoming JSON object.
    * Useful for PATCH/PUT requests, where only modified fields are sent to the server.
    */
  def patcher[T](in: Json)(implicit d: Decoder[T => T]) = JsonFormat.decode[T => T](in)

  /**
    * A Body that provides a function that will modify a given case class with the fields from a incoming JSON object.
    * Useful for PATCH/PUT requests, where only fields to be modified are sent to the server. Note that this Body only
    * supports inbound messages.
    */
  def patchBody[R](description: String = null, example: R = null)
                  (implicit e: Encoder[R], d: Decoder[R => R]): Body[R => R] = Body.of[R => R](
    BodySpec.json(this).map(j => JsonFormat.decode[R => R](j),
      (u: R => R) => encode(u(example))), description, Option(example).map(_ => (r: R) => example).orNull)

  /**
    * Convenience method for creating BodySpecs that just use straight JSON encoding/decoding logic
    */
  def bodySpec[R]()(implicit e: Encoder[R], d: Decoder[R]) =
    BodySpec.json(this).map(j => JsonFormat.decode[R](j), (u: R) => encode(u))

  /**
    * Convenience method for creating ResponseSpecs that just use straight JSON encoding/decoding logic for examples
    */
  def responseSpec[R](statusAndDescription: (Status, String), example: R)
                     (implicit e: Encoder[R], d: Decoder[R]) =
    ResponseSpec.json(statusAndDescription, encode(example), this)

  /**
    * Convenience method for creating ParameterSpecs that just use straight JSON encoding/decoding logic
    */
  def parameterSpec[R]()(implicit e: Encoder[R], d: Decoder[R]) =
    ParameterSpec.json(this).map(j => JsonFormat.decode[R](j), (u: R) => encode(u))

}


text:
import * as React from 'react';
import { render as ReactDomRender } from 'react-dom';
import * as injectTapEventPlugin from 'react-tap-event-plugin';
import Demo from './demo';

injectTapEventPlugin();
let bootstrapNode = document.createElement('div');
ReactDomRender(<Demo />, bootstrapNode);
document.body.appendChild(bootstrapNode);


text:
from dqn_cartpole import *

import gym

def main():
    env = gym.make("CartPole-v0")
    agent = DQNCartpole(env.action_space.n, mode=PLAY, load=True)

    total_reward = 0
    observation = env.reset()
    for step in range(300):
        env.render()
        action = agent.make_action(observation)
        observation, reward, done, _ = env.step(action)
        total_reward += reward

        if done:
            break

    env.close()
    print("Total reward:", total_reward)

if __name__ == "__main__":
    main()


text:
/* This file contains the master driver module for use by SGI IOC4 subdrivers.
 *
 * It allocates any resources shared between multiple subdevices, and
 * provides accessor functions (where needed) and the like for those
 * resources.  It also provides a mechanism for the subdevice modules
 * to support loading and unloading.
 *
 * Non-shared resources (e.g. external interrupt A_INT_OUT register page
 * alias, serial port and UART registers) are handled by the subdevice
 * modules themselves.
 *
 * This is all necessary because IOC4 is not implemented as a multi-function
 * PCI device, but an amalgamation of disparate registers for several
 * types of device (ATA, serial, external interrupts).  The normal
 * resource management in the kernel doesn't have quite the right interfaces
 * to handle this situation (e.g. multiple modules can't claim the same
 * PCI ID), thus this IOC4 master module.
 */

#include <linux/errno.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/ioc4.h>
#include <linux/ktime.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/time.h>
#include <asm/io.h>

/***************
 * Definitions *
 ***************/

/* Tweakable values */

/* PCI bus speed detection/calibration */
#define IOC4_CALIBRATE_COUNT 63		/* Calibration cycle period */
#define IOC4_CALIBRATE_CYCLES 256	/* Average over this many cycles */
#define IOC4_CALIBRATE_DISCARD 2	/* Discard first few cycles */
#define IOC4_CALIBRATE_LOW_MHZ 25	/* Lower bound on bus speed sanity */
#define IOC4_CALIBRATE_HIGH_MHZ 75	/* Upper bound on bus speed sanity */
#define IOC4_CALIBRATE_DEFAULT_MHZ 66	/* Assumed if sanity check fails */

/************************
 * Submodule management *
 ************************/

static DEFINE_MUTEX(ioc4_mutex);

static LIST_HEAD(ioc4_devices);
static LIST_HEAD(ioc4_submodules);

/* Register an IOC4 submodule */
int
ioc4_register_submodule(struct ioc4_submodule *is)
{
	struct ioc4_driver_data *idd;

	mutex_lock(&ioc4_mutex);
	list_add(&is->is_list, &ioc4_submodules);

	/* Initialize submodule for each IOC4 */
	if (!is->is_probe)
		goto out;

	list_for_each_entry(idd, &ioc4_devices, idd_list) {
		if (is->is_probe(idd)) {
			printk(KERN_WARNING
			       "%s: IOC4 submodule %s probe failed "
			       "for pci_dev %s",
			       __func__, module_name(is->is_owner),
			       pci_name(idd->idd_pdev));
		}
	}
 out:
	mutex_unlock(&ioc4_mutex);
	return 0;
}

/* Unregister an IOC4 submodule */
void
ioc4_unregister_submodule(struct ioc4_submodule *is)
{
	struct ioc4_driver_data *idd;

	mutex_lock(&ioc4_mutex);
	list_del(&is->is_list);

	/* Remove submodule for each IOC4 */
	if (!is->is_remove)
		goto out;

	list_for_each_entry(idd, &ioc4_devices, idd_list) {
		if (is->is_remove(idd)) {
			printk(KERN_WARNING
			       "%s: IOC4 submodule %s remove failed "
			       "for pci_dev %s.\n",
			       __func__, module_name(is->is_owner),
			       pci_name(idd->idd_pdev));
		}
	}
 out:
	mutex_unlock(&ioc4_mutex);
}

/*********************
 * Device management *
 *********************/

#define IOC4_CALIBRATE_LOW_LIMIT \
	(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_LOW_MHZ)
#define IOC4_CALIBRATE_HIGH_LIMIT \
	(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_HIGH_MHZ)
#define IOC4_CALIBRATE_DEFAULT \
	(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_DEFAULT_MHZ)

#define IOC4_CALIBRATE_END \
	(IOC4_CALIBRATE_CYCLES + IOC4_CALIBRATE_DISCARD)

#define IOC4_INT_OUT_MODE_TOGGLE 0x7	/* Toggle INT_OUT every COUNT+1 ticks */

/* Determines external interrupt output clock period of the PCI bus an
 * IOC4 is attached to.  This value can be used to determine the PCI
 * bus speed.
 *
 * IOC4 has a design feature that various internal timers are derived from
 * the PCI bus clock.  This causes IOC4 device drivers to need to take the
 * bus speed into account when setting various register values (e.g. INT_OUT
 * register COUNT field, UART divisors, etc).  Since this information is
 * needed by several subdrivers, it is determined by the main IOC4 driver,
 * even though the following code utilizes external interrupt registers
 * to perform the speed calculation.
 */
static void __devinit
ioc4_clock_calibrate(struct ioc4_driver_data *idd)
{
	union ioc4_int_out int_out;
	union ioc4_gpcr gpcr;
	unsigned int state, last_state = 1;
	struct timespec start_ts, end_ts;
	uint64_t start, end, period;
	unsigned int count = 0;

	/* Enable output */
	gpcr.raw = 0;
	gpcr.fields.dir = IOC4_GPCR_DIR_0;
	gpcr.fields.int_out_en = 1;
	writel(gpcr.raw, &idd->idd_misc_regs->gpcr_s.raw);

	/* Reset to power-on state */
	writel(0, &idd->idd_misc_regs->int_out.raw);
	mmiowb();

	/* Set up square wave */
	int_out.raw = 0;
	int_out.fields.count = IOC4_CALIBRATE_COUNT;
	int_out.fields.mode = IOC4_INT_OUT_MODE_TOGGLE;
	int_out.fields.diag = 0;
	writel(int_out.raw, &idd->idd_misc_regs->int_out.raw);
	mmiowb();

	/* Check square wave period averaged over some number of cycles */
	do {
		int_out.raw = readl(&idd->idd_misc_regs->int_out.raw);
		state = int_out.fields.int_out;
		if (!last_state && state) {
			count++;
			if (count == IOC4_CALIBRATE_END) {
				ktime_get_ts(&end_ts);
				break;
			} else if (count == IOC4_CALIBRATE_DISCARD)
				ktime_get_ts(&start_ts);
		}
		last_state = state;
	} while (1);

	/* Calculation rearranged to preserve intermediate precision.
	 * Logically:
	 * 1. "end - start" gives us the measurement period over all
	 *    the square wave cycles.
	 * 2. Divide by number of square wave cycles to get the period
	 *    of a square wave cycle.
	 * 3. Divide by 2*(int_out.fields.count+1), which is the formula
	 *    by which the IOC4 generates the square wave, to get the
	 *    period of an IOC4 INT_OUT count.
	 */
	end = end_ts.tv_sec * NSEC_PER_SEC + end_ts.tv_nsec;
	start = start_ts.tv_sec * NSEC_PER_SEC + start_ts.tv_nsec;
	period = (end - start) /
		(IOC4_CALIBRATE_CYCLES * 2 * (IOC4_CALIBRATE_COUNT + 1));

	/* Bounds check the result. */
	if (period > IOC4_CALIBRATE_LOW_LIMIT ||
	    period < IOC4_CALIBRATE_HIGH_LIMIT) {
		printk(KERN_INFO
		       "IOC4 %s: Clock calibration failed.  Assuming"
		       "PCI clock is %d ns.\n",
		       pci_name(idd->idd_pdev),
		       IOC4_CALIBRATE_DEFAULT / IOC4_EXTINT_COUNT_DIVISOR);
		period = IOC4_CALIBRATE_DEFAULT;
	} else {
		u64 ns = period;

		do_div(ns, IOC4_EXTINT_COUNT_DIVISOR);
		printk(KERN_DEBUG
		       "IOC4 %s: PCI clock is %llu ns.\n",
		       pci_name(idd->idd_pdev), (unsigned long long)ns);
	}

	/* Remember results.  We store the extint clock period rather
	 * than the PCI clock period so that greater precision is
	 * retained.  Divide by IOC4_EXTINT_COUNT_DIVISOR to get
	 * PCI clock period.
	 */
	idd->count_period = period;
}

/* There are three variants of IOC4 cards: IO9, IO10, and PCI-RT.
 * Each brings out different combinations of IOC4 signals, thus.
 * the IOC4 subdrivers need to know to which we're attached.
 *
 * We look for the presence of a SCSI (IO9) or SATA (IO10) controller
 * on the same PCI bus at slot number 3 to differentiate IO9 from IO10.
 * If neither is present, it's a PCI-RT.
 */
static unsigned int __devinit
ioc4_variant(struct ioc4_driver_data *idd)
{
	struct pci_dev *pdev = NULL;
	int found = 0;

	/* IO9: Look for a QLogic ISP 12160 at the same bus and slot 3. */
	do {
		pdev = pci_get_device(PCI_VENDOR_ID_QLOGIC,
				      PCI_DEVICE_ID_QLOGIC_ISP12160, pdev);
		if (pdev &&
		    idd->idd_pdev->bus->number == pdev->bus->number &&
		    3 == PCI_SLOT(pdev->devfn))
			found = 1;
	} while (pdev && !found);
	if (NULL != pdev) {
		pci_dev_put(pdev);
		return IOC4_VARIANT_IO9;
	}

	/* IO10: Look for a Vitesse VSC 7174 at the same bus and slot 3. */
	pdev = NULL;
	do {
		pdev = pci_get_device(PCI_VENDOR_ID_VITESSE,
				      PCI_DEVICE_ID_VITESSE_VSC7174, pdev);
		if (pdev &&
		    idd->idd_pdev->bus->number == pdev->bus->number &&
		    3 == PCI_SLOT(pdev->devfn))
			found = 1;
	} while (pdev && !found);
	if (NULL != pdev) {
		pci_dev_put(pdev);
		return IOC4_VARIANT_IO10;
	}

	/* PCI-RT: No SCSI/SATA controller will be present */
	return IOC4_VARIANT_PCI_RT;
}

static void
ioc4_load_modules(struct work_struct *work)
{
	request_module("sgiioc4");
}

static DECLARE_WORK(ioc4_load_modules_work, ioc4_load_modules);

/* Adds a new instance of an IOC4 card */
static int __devinit
ioc4_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
{
	struct ioc4_driver_data *idd;
	struct ioc4_submodule *is;
	uint32_t pcmd;
	int ret;

	/* Enable IOC4 and take ownership of it */
	if ((ret = pci_enable_device(pdev))) {
		printk(KERN_WARNING
		       "%s: Failed to enable IOC4 device for pci_dev %s.\n",
		       __func__, pci_name(pdev));
		goto out;
	}
	pci_set_master(pdev);

	/* Set up per-IOC4 data */
	idd = kmalloc(sizeof(struct ioc4_driver_data), GFP_KERNEL);
	if (!idd) {
		printk(KERN_WARNING
		       "%s: Failed to allocate IOC4 data for pci_dev %s.\n",
		       __func__, pci_name(pdev));
		ret = -ENODEV;
		goto out_idd;
	}
	idd->idd_pdev = pdev;
	idd->idd_pci_id = pci_id;

	/* Map IOC4 misc registers.  These are shared between subdevices
	 * so the main IOC4 module manages them.
	 */
	idd->idd_bar0 = pci_resource_start(idd->idd_pdev, 0);
	if (!idd->idd_bar0) {
		printk(KERN_WARNING
		       "%s: Unable to find IOC4 misc resource "
		       "for pci_dev %s.\n",
		       __func__, pci_name(idd->idd_pdev));
		ret = -ENODEV;
		goto out_pci;
	}
	if (!request_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs),
			    "ioc4_misc")) {
		printk(KERN_WARNING
		       "%s: Unable to request IOC4 misc region "
		       "for pci_dev %s.\n",
		       __func__, pci_name(idd->idd_pdev));
		ret = -ENODEV;
		goto out_pci;
	}
	idd->idd_misc_regs = ioremap(idd->idd_bar0,
				     sizeof(struct ioc4_misc_regs));
	if (!idd->idd_misc_regs) {
		printk(KERN_WARNING
		       "%s: Unable to remap IOC4 misc region "
		       "for pci_dev %s.\n",
		       __func__, pci_name(idd->idd_pdev));
		ret = -ENODEV;
		goto out_misc_region;
	}

	/* Failsafe portion of per-IOC4 initialization */

	/* Detect card variant */
	idd->idd_variant = ioc4_variant(idd);
	printk(KERN_INFO "IOC4 %s: %s card detected.\n", pci_name(pdev),
	       idd->idd_variant == IOC4_VARIANT_IO9 ? "IO9" :
	       idd->idd_variant == IOC4_VARIANT_PCI_RT ? "PCI-RT" :
	       idd->idd_variant == IOC4_VARIANT_IO10 ? "IO10" : "unknown");

	/* Initialize IOC4 */
	pci_read_config_dword(idd->idd_pdev, PCI_COMMAND, &pcmd);
	pci_write_config_dword(idd->idd_pdev, PCI_COMMAND,
			       pcmd | PCI_COMMAND_PARITY | PCI_COMMAND_SERR);

	/* Determine PCI clock */
	ioc4_clock_calibrate(idd);

	/* Disable/clear all interrupts.  Need to do this here lest
	 * one submodule request the shared IOC4 IRQ, but interrupt
	 * is generated by a different subdevice.
	 */
	/* Disable */
	writel(~0, &idd->idd_misc_regs->other_iec.raw);
	writel(~0, &idd->idd_misc_regs->sio_iec);
	/* Clear (i.e. acknowledge) */
	writel(~0, &idd->idd_misc_regs->other_ir.raw);
	writel(~0, &idd->idd_misc_regs->sio_ir);

	/* Track PCI-device specific data */
	idd->idd_serial_data = NULL;
	pci_set_drvdata(idd->idd_pdev, idd);

	mutex_lock(&ioc4_mutex);
	list_add_tail(&idd->idd_list, &ioc4_devices);

	/* Add this IOC4 to all submodules */
	list_for_each_entry(is, &ioc4_submodules, is_list) {
		if (is->is_probe && is->is_probe(idd)) {
			printk(KERN_WARNING
			       "%s: IOC4 submodule 0x%s probe failed "
			       "for pci_dev %s.\n",
			       __func__, module_name(is->is_owner),
			       pci_name(idd->idd_pdev));
		}
	}
	mutex_unlock(&ioc4_mutex);

	/* Request sgiioc4 IDE driver on boards that bring that functionality
	 * off of IOC4.  The root filesystem may be hosted on a drive connected
	 * to IOC4, so we need to make sure the sgiioc4 driver is loaded as it
	 * won't be picked up by modprobes due to the ioc4 module owning the
	 * PCI device.
	 */
	if (idd->idd_variant != IOC4_VARIANT_PCI_RT) {
		/* Request the module from a work procedure as the modprobe
		 * goes out to a userland helper and that will hang if done
		 * directly from ioc4_probe().
		 */
		printk(KERN_INFO "IOC4 loading sgiioc4 submodule\n");
		schedule_work(&ioc4_load_modules_work);
	}

	return 0;

out_misc_region:
	release_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs));
out_pci:
	kfree(idd);
out_idd:
	pci_disable_device(pdev);
out:
	return ret;
}

/* Removes a particular instance of an IOC4 card. */
static void __devexit
ioc4_remove(struct pci_dev *pdev)
{
	struct ioc4_submodule *is;
	struct ioc4_driver_data *idd;

	idd = pci_get_drvdata(pdev);

	/* Remove this IOC4 from all submodules */
	mutex_lock(&ioc4_mutex);
	list_for_each_entry(is, &ioc4_submodules, is_list) {
		if (is->is_remove && is->is_remove(idd)) {
			printk(KERN_WARNING
			       "%s: IOC4 submodule 0x%s remove failed "
			       "for pci_dev %s.\n",
			       __func__, module_name(is->is_owner),
			       pci_name(idd->idd_pdev));
		}
	}
	mutex_unlock(&ioc4_mutex);

	/* Release resources */
	iounmap(idd->idd_misc_regs);
	if (!idd->idd_bar0) {
		printk(KERN_WARNING
		       "%s: Unable to get IOC4 misc mapping for pci_dev %s. "
		       "Device removal may be incomplete.\n",
		       __func__, pci_name(idd->idd_pdev));
	}
	release_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs));

	/* Disable IOC4 and relinquish */
	pci_disable_device(pdev);

	/* Remove and free driver data */
	mutex_lock(&ioc4_mutex);
	list_del(&idd->idd_list);
	mutex_unlock(&ioc4_mutex);
	kfree(idd);
}

static struct pci_device_id ioc4_id_table[] = {
	{PCI_VENDOR_ID_SGI, PCI_DEVICE_ID_SGI_IOC4, PCI_ANY_ID,
	 PCI_ANY_ID, 0x0b4000, 0xFFFFFF},
	{0}
};

static struct pci_driver ioc4_driver = {
	.name = "IOC4",
	.id_table = ioc4_id_table,
	.probe = ioc4_probe,
	.remove = __devexit_p(ioc4_remove),
};

MODULE_DEVICE_TABLE(pci, ioc4_id_table);

/*********************
 * Module management *
 *********************/

/* Module load */
static int __init
ioc4_init(void)
{
	return pci_register_driver(&ioc4_driver);
}

/* Module unload */
static void __exit
ioc4_exit(void)
{
	/* Ensure ioc4_load_modules() has completed before exiting */
	flush_work_sync(&ioc4_load_modules_work);
	pci_unregister_driver(&ioc4_driver);
}

module_init(ioc4_init);
module_exit(ioc4_exit);

MODULE_AUTHOR("Brent Casavant - Silicon Graphics, Inc. <bcasavan@sgi.com>");
MODULE_DESCRIPTION("PCI driver master module for SGI IOC4 Base-IO Card");
MODULE_LICENSE("GPL");

EXPORT_SYMBOL(ioc4_register_submodule);
EXPORT_SYMBOL(ioc4_unregister_submodule);


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Ripped Pants

						Expand All | Collapse All

Ripped Pants

  He entered the drugstore. He took the down escalator. He couldn't find what he wanted. He got on the up escalator. Seconds later, something grabbed his pants cuff. He pulled his cuff free. What was that, he wondered. He turned around to look. He saw a little screw. A loose screw was sticking out of the escalator wall. He got to the top of the escalator. He looked at his pants. The cuff was ripped. It was just a little rip. But that screw might hurt someone. I'd better tell someone about it, he thought. He found an employee. He told her what had happened. He pointed out the loose screw. She apologized. She said, "Don't worry. We'll pay for repairing your pants. Just bring us the bill. And we'll take care of that screw immediately." He thanked her. A week later, he returned. The loose screw was still there.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package com.glaf.dts.query;

import java.util.*;
import com.glaf.core.query.DataQuery;

public class TransformStepQuery extends DataQuery {
	private static final long serialVersionUID = 1L;
	protected String activityId;
	protected List<String> activityIds;
	protected String queryId;
	protected String titleLike;
	protected String descriptionLike;
	protected Integer priority;
	protected Integer priorityGreaterThanOrEqual;
	protected Integer priorityLessThanOrEqual;
	protected Date createTimeGreaterThanOrEqual;
	protected Date createTimeLessThanOrEqual;
	protected Integer lockedGreaterThanOrEqual;
	protected Integer lockedLessThanOrEqual;
	protected Integer revision;
	protected Integer revisionGreaterThanOrEqual;
	protected Integer revisionLessThanOrEqual;

	public TransformStepQuery() {

	}

	public TransformStepQuery activityId(String activityId) {
		if (activityId == null) {
			throw new RuntimeException("activityId is null");
		}
		this.activityId = activityId;
		return this;
	}

	public TransformStepQuery activityIds(List<String> activityIds) {
		if (activityIds == null) {
			throw new RuntimeException("activityIds is empty ");
		}
		this.activityIds = activityIds;
		return this;
	}

	public TransformStepQuery createBy(String createBy) {
		if (createBy == null) {
			throw new RuntimeException("createBy is null");
		}
		this.createBy = createBy;
		return this;
	}

	public TransformStepQuery createTimeGreaterThanOrEqual(
			Date createTimeGreaterThanOrEqual) {
		if (createTimeGreaterThanOrEqual == null) {
			throw new RuntimeException("createTime is null");
		}
		this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual;
		return this;
	}

	public TransformStepQuery createTimeLessThanOrEqual(
			Date createTimeLessThanOrEqual) {
		if (createTimeLessThanOrEqual == null) {
			throw new RuntimeException("createTime is null");
		}
		this.createTimeLessThanOrEqual = createTimeLessThanOrEqual;
		return this;
	}

	public TransformStepQuery descriptionLike(String descriptionLike) {
		if (descriptionLike == null) {
			throw new RuntimeException("description is null");
		}
		this.descriptionLike = descriptionLike;
		return this;
	}

	public String getActivityId() {
		return activityId;
	}

	public List<String> getActivityIds() {
		return activityIds;
	}

	public Date getCreateTimeGreaterThanOrEqual() {
		return createTimeGreaterThanOrEqual;
	}

	public Date getCreateTimeLessThanOrEqual() {
		return createTimeLessThanOrEqual;
	}

	public String getDescriptionLike() {
		if (descriptionLike != null && descriptionLike.trim().length() > 0) {
			if (!descriptionLike.startsWith("%")) {
				descriptionLike = "%" + descriptionLike;
			}
			if (!descriptionLike.endsWith("%")) {
				descriptionLike = descriptionLike + "%";
			}
		}
		return descriptionLike;
	}

	public Integer getLockedGreaterThanOrEqual() {
		return lockedGreaterThanOrEqual;
	}

	public Integer getLockedLessThanOrEqual() {
		return lockedLessThanOrEqual;
	}

	public String getOrderBy() {
		if (sortField != null) {
			String a_x = " asc ";
			if (getSortOrder() != null) {
				a_x = " desc ";
			}

			if ("activityId".equals(sortField)) {
				orderBy = "E.ACTIVITYID_" + a_x;
			}

			if ("queryId".equals(sortField)) {
				orderBy = "E.QUERYID_" + a_x;
			}

			if ("title".equals(sortField)) {
				orderBy = "E.TITLE_" + a_x;
			}

			if ("description".equals(sortField)) {
				orderBy = "E.DESCRIPTION_" + a_x;
			}

			if ("priority".equals(sortField)) {
				orderBy = "E.PRIORITY_" + a_x;
			}

			if ("createTime".equals(sortField)) {
				orderBy = "E.CREATETIME_" + a_x;
			}

			if ("createBy".equals(sortField)) {
				orderBy = "E.CREATEBY_" + a_x;
			}

			if ("locked".equals(sortField)) {
				orderBy = "E.LOCKED_" + a_x;
			}

			if ("revision".equals(sortField)) {
				orderBy = "E.REVISION_" + a_x;
			}

		}
		return orderBy;
	}

	public Integer getPriority() {
		return priority;
	}

	public Integer getPriorityGreaterThanOrEqual() {
		return priorityGreaterThanOrEqual;
	}

	public Integer getPriorityLessThanOrEqual() {
		return priorityLessThanOrEqual;
	}

	public String getQueryId() {
		return queryId;
	}

	public Integer getRevision() {
		return revision;
	}

	public Integer getRevisionGreaterThanOrEqual() {
		return revisionGreaterThanOrEqual;
	}

	public Integer getRevisionLessThanOrEqual() {
		return revisionLessThanOrEqual;
	}

	public String getTitleLike() {
		if (titleLike != null && titleLike.trim().length() > 0) {
			if (!titleLike.startsWith("%")) {
				titleLike = "%" + titleLike;
			}
			if (!titleLike.endsWith("%")) {
				titleLike = titleLike + "%";
			}
		}
		return titleLike;
	}

	@Override
	public void initQueryColumns() {
		super.initQueryColumns();
		addColumn("id", "ID_");
		addColumn("activityId", "ACTIVITYID_");
		addColumn("queryId", "QUERYID_");
		addColumn("title", "TITLE_");
		addColumn("description", "DESCRIPTION_");
		addColumn("priority", "PRIORITY_");
		addColumn("createTime", "CREATETIME_");
		addColumn("createBy", "CREATEBY_");
		addColumn("locked", "LOCKED_");
		addColumn("revision", "REVISION_");
	}

	public TransformStepQuery lockedGreaterThanOrEqual(
			Integer lockedGreaterThanOrEqual) {
		if (lockedGreaterThanOrEqual == null) {
			throw new RuntimeException("locked is null");
		}
		this.lockedGreaterThanOrEqual = lockedGreaterThanOrEqual;
		return this;
	}

	public TransformStepQuery lockedLessThanOrEqual(
			Integer lockedLessThanOrEqual) {
		if (lockedLessThanOrEqual == null) {
			throw new RuntimeException("locked is null");
		}
		this.lockedLessThanOrEqual = lockedLessThanOrEqual;
		return this;
	}

	public TransformStepQuery priority(Integer priority) {
		if (priority == null) {
			throw new RuntimeException("priority is null");
		}
		this.priority = priority;
		return this;
	}

	public TransformStepQuery priorityGreaterThanOrEqual(
			Integer priorityGreaterThanOrEqual) {
		if (priorityGreaterThanOrEqual == null) {
			throw new RuntimeException("priority is null");
		}
		this.priorityGreaterThanOrEqual = priorityGreaterThanOrEqual;
		return this;
	}

	public TransformStepQuery priorityLessThanOrEqual(
			Integer priorityLessThanOrEqual) {
		if (priorityLessThanOrEqual == null) {
			throw new RuntimeException("priority is null");
		}
		this.priorityLessThanOrEqual = priorityLessThanOrEqual;
		return this;
	}

	public TransformStepQuery queryId(String queryId) {
		if (queryId == null) {
			throw new RuntimeException("queryId is null");
		}
		this.queryId = queryId;
		return this;
	}

	public TransformStepQuery revision(Integer revision) {
		if (revision == null) {
			throw new RuntimeException("revision is null");
		}
		this.revision = revision;
		return this;
	}

	public TransformStepQuery revisionGreaterThanOrEqual(
			Integer revisionGreaterThanOrEqual) {
		if (revisionGreaterThanOrEqual == null) {
			throw new RuntimeException("revision is null");
		}
		this.revisionGreaterThanOrEqual = revisionGreaterThanOrEqual;
		return this;
	}

	public TransformStepQuery revisionLessThanOrEqual(
			Integer revisionLessThanOrEqual) {
		if (revisionLessThanOrEqual == null) {
			throw new RuntimeException("revision is null");
		}
		this.revisionLessThanOrEqual = revisionLessThanOrEqual;
		return this;
	}

	public void setActivityId(String activityId) {
		this.activityId = activityId;
	}

	public void setActivityIds(List<String> activityIds) {
		this.activityIds = activityIds;
	}

	public void setCreateTimeGreaterThanOrEqual(
			Date createTimeGreaterThanOrEqual) {
		this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual;
	}

	public void setCreateTimeLessThanOrEqual(Date createTimeLessThanOrEqual) {
		this.createTimeLessThanOrEqual = createTimeLessThanOrEqual;
	}

	public void setDescriptionLike(String descriptionLike) {
		this.descriptionLike = descriptionLike;
	}

	public void setLockedGreaterThanOrEqual(Integer lockedGreaterThanOrEqual) {
		this.lockedGreaterThanOrEqual = lockedGreaterThanOrEqual;
	}

	public void setLockedLessThanOrEqual(Integer lockedLessThanOrEqual) {
		this.lockedLessThanOrEqual = lockedLessThanOrEqual;
	}

	public void setPriority(Integer priority) {
		this.priority = priority;
	}

	public void setPriorityGreaterThanOrEqual(Integer priorityGreaterThanOrEqual) {
		this.priorityGreaterThanOrEqual = priorityGreaterThanOrEqual;
	}

	public void setPriorityLessThanOrEqual(Integer priorityLessThanOrEqual) {
		this.priorityLessThanOrEqual = priorityLessThanOrEqual;
	}

	public void setQueryId(String queryId) {
		this.queryId = queryId;
	}

	public void setRevision(Integer revision) {
		this.revision = revision;
	}

	public void setRevisionGreaterThanOrEqual(Integer revisionGreaterThanOrEqual) {
		this.revisionGreaterThanOrEqual = revisionGreaterThanOrEqual;
	}

	public void setRevisionLessThanOrEqual(Integer revisionLessThanOrEqual) {
		this.revisionLessThanOrEqual = revisionLessThanOrEqual;
	}

	public void setTitleLike(String titleLike) {
		this.titleLike = titleLike;
	}

	public TransformStepQuery titleLike(String titleLike) {
		if (titleLike == null) {
			throw new RuntimeException("title is null");
		}
		this.titleLike = titleLike;
		return this;
	}

}


text:
package quasar;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/**
 * @author doug
 *
 */
class DocumentTests
{

    /**
     * Test method for {@link quasar.Document#Document()}.
     */
    @Test
    @DisplayName("Empty document object")
    void testDocument()
    {
        Document d = new Document();
        assertNotNull(d);
        assertEquals(Quasar.DOCUMENT, d.getType());
        assertTrue(d.getDescription().isEmpty());
        assertTrue(d.getPath().isEmpty());
    }

    /**
     * Test method for {@link quasar.Document#Document(java.lang.String)}.
     */
    @Test
    @DisplayName("Document with path")
    void testDocumentString()
    {
        String unixPath = "/home/user/Documents";
        String windowsPath = "C:\\Users\\user\\Documents";

        Document d = new Document(unixPath);
        assertNotNull(d);
        assertEquals(Quasar.DOCUMENT, d.getType());
        assertFalse(d.getPath().isEmpty());

        d.setPath(windowsPath);
        assertEquals(windowsPath, d.getPath());
    }

    /**
     * Test method for {@link quasar.Document#Document(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
     */
    @Test
    @DisplayName("Document with all fields")
    void testDocumentStringStringStringString()
    {
        Document d = new Document("somepath", "666", "Famous Author", "The Publishing House");
        assertNotNull(d);
        assertEquals(Quasar.DOCUMENT, d.getType());
        assertEquals("somepath", d.getPath());
        assertEquals("666", d.getPageNumber());
        assertEquals("Famous Author", d.getAuthor());
        assertEquals("The Publishing House", d.getPublishDate());
    }

}


text:
/*
* TLS Handshake State Transitions
* (C) 2004-2006,2011,2012 Jack Lloyd
*     2017 Harry Reimann, Rohde & Schwarz Cybersecurity
*     2022 René Meusel, Hannes Rantzsch - neXenio GmbH
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_TLS_HANDSHAKE_TRANSITIONS_H_
#define BOTAN_TLS_HANDSHAKE_TRANSITIONS_H_

#include <vector>

#include <botan/tls_magic.h>

namespace Botan::TLS {

/**
 * Manages the expectations for incoming handshake messages in both TLS 1.2 and 1.3.
 * This does not bear any knowledge about the actual state machine but is a mere
 * helper to implement state transition validation.
 */
class BOTAN_TEST_API Handshake_Transitions
   {
   public:
      /**
       * Return true iff we have received a particular message already
       * @param msg_type the message type
       */
      bool received_handshake_msg(Handshake_Type msg_type) const;

      /**
       * Confirm that we were expecting this message type
       * @param msg_type the message type
       */
      void confirm_transition_to(Handshake_Type msg_type);

      /**
       * Record that we are expecting a particular message type next
       * @param msg_type the message type
       */
      void set_expected_next(Handshake_Type msg_type);

      /**
       * Record that we are expecting one of the enumerated message types next.
       * Note that receiving any of the expected messages in `confirm_transition_to`
       * resets _all_ the expectations.
       *
       * @param msg_types the message types
       */
      void set_expected_next(const std::vector<Handshake_Type>& msg_types);

      /**
       * Check whether a Change Cipher Spec must be expected
       */
      bool change_cipher_spec_expected() const;

   private:
      uint32_t m_hand_expecting_mask = 0;
      uint32_t m_hand_received_mask = 0;
   };

}

#endif


text:
package com.jetbrains.edu.coursecreator;

import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.edu.learning.core.EduNames;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public class PyCCLanguageManager implements CCLanguageManager {

  @Nullable
  @Override
  public String getDefaultTaskFileExtension() {
    return "py";
  }

  @Nullable
  @Override
  public FileTemplate getTaskFileTemplateForExtension(@NotNull final Project project, String extension) {
    if (!extension.equals("py")) {
      return null;
    }
    return getInternalTemplateByName(project, "task.py");
  }

  @Nullable
  @Override
  public FileTemplate getTestsTemplate(@NotNull final Project project) {
    return getInternalTemplateByName(project, EduNames.TESTS_FILE);
  }

  @Override
  public boolean doNotPackFile(File pathname) {
    String name = pathname.getName();
    return name.contains("__pycache__") || name.contains(".pyc");
  }

  private static FileTemplate getInternalTemplateByName(@NotNull final Project project, String name) {
    return FileTemplateManager.getInstance(project).getInternalTemplate(name);
  }

  @Override
  public boolean isTestFile(VirtualFile file) {
    return EduNames.TESTS_FILE.equals(file.getName());
  }
}


text:
.. _security:

=================
Security Overview
=================

While the Bare Metal service is intended to be a secure application, it is
important to understand what it does and does not cover today.

Deployers must properly evaluate their use case and take the appropriate
actions to secure their environment(s). This document is intended to provide an
overview of what risks an operator of the Bare Metal service should be aware
of. It is not intended as a How-To guide for securing a data center or an
OpenStack deployment.

.. TODO: add "Security Considerations for Network Boot" section

.. TODO: add "Credential Storage and Management" section

.. TODO: add "Multi-tenancy Considerations" section

REST API: user roles and policy settings
========================================

Beginning with the Newton (6.1.0) release, the Bare Metal service allows
operators significant control over API access:

* Access may be restricted to each method (GET, PUT, etc) for each
  REST resource. Defaults are provided with the release and defined in code.
* Access may be divided between an "administrative" role with full access and
  "observer" role with read-only access. By default, these roles are assigned
  the names ``baremetal_admin`` and ``baremetal_observer``, respectively.
* As before, passwords may be hidden in ``driver_info``.

Prior to the Newton (6.1.0) release, the Bare Metal service only supported two
policy options:

* API access may be secured by a simple policy rule: users with administrative
  privileges may access all API resources, whereas users without administrative
  privileges may only access public API resources.
* Passwords contained in the ``driver_info`` field may be hidden from all API
  responses with the ``show_password`` policy setting. This defaults to always
  hide passwords, regardless of the user's role.

Multi-tenancy
=============

There are two aspects of multitenancy to consider when evaluating a deployment
of the Bare Metal Service: interactions between tenants on the network, and
actions one tenant can take on a machine that will affect the next tenant.

Network Interactions
--------------------
Interactions between tenants' workloads running simultaneously on separate
servers include, but are not limited to: IP spoofing, packet sniffing, and
network man-in-the-middle attacks.

By default, the Bare Metal service provisions all nodes on a "flat" network, and
does not take any precautions to avoid or prevent interaction between tenants.
This can be addressed by integration with the OpenStack Identity, Compute, and
Networking services, so as to provide tenant-network isolation. Additional
documentation on `network multi-tenancy <multitenancy>`_ is available.

Lingering Effects
-----------------
Interactions between tenants placed sequentially on the same server include, but
are not limited to: changes in BIOS settings, modifications to firmware, or
files left on disk or peripheral storage devices (if these devices are not
erased between uses).

By default, the Bare Metal service will erase (clean) the local disk drives
during the "cleaning" phase, after deleting an instance. It *does not* reset
BIOS or reflash firmware or peripheral devices. This can be addressed through
customizing the utility ramdisk used during the "cleaning" phase. See details in
the `Firmware security`_ section.

Firmware security
=================

When the Bare Metal service deploys an operating system image to a server, that
image is run natively on the server without virtualization. Any user with
administrative access to the deployed instance has administrative access to
the underlying hardware.

Most servers' default settings do not prevent a privileged local user from
gaining direct access to hardware devices.  Such a user could modify device or
firmware settings, and potentially flash new firmware to the device, before
deleting their instance and allowing the server to be allocated to another
user.

If the ``[conductor]/automated_clean`` configuration option is enabled (and
the ``[deploy]/erase_devices_priority`` configuration option is not zero),
the Bare Metal service will securely erase all local disk devices within a
machine during instance deletion. However, the service does not ship with
any code that will validate the integrity of, or make any modifications to,
system or device firmware or firmware settings.

Operators are encouraged to write their own hardware manager plugins for the
``ironic-python-agent`` ramdisk.  This should include custom ``clean steps``
that would be run during the :ref:`cleaning` process, as part of Node
de-provisioning. The ``clean steps``
would perform the specific actions necessary within that environment to ensure
the integrity of each server's firmware.

Ideally, an operator would work with their hardware vendor to ensure that
proper firmware security measures are put in place ahead of time. This could
include:

  - installing signed firmware for BIOS and peripheral devices
  - using a TPM (Trusted Platform Module) to validate signatures at boot time
  - booting machines in :ref:`iLO UEFI Secure Boot Support`, rather than BIOS mode, to
    validate kernel signatures
  - disabling local (in-band) access from the host OS to the management controller (BMC)
  - disabling modifications to boot settings from the host OS

Additional references:
  - :ref:`cleaning`
  - `trusted boot with partition image`_
  - :ref:`iLO UEFI Secure Boot Support`

.. _trusted boot with partition image: http://docs.openstack.org/project-install-guide/baremetal/ocata/advanced.html#trusted-boot-with-partition-image


text:
To adjust the disk utilization of your StashCache cache, modify the values of `pfc.diskusage` in `/etc/xrootd/xrootd-stashcache-cache-server.cfg`:
```
pfc.diskusage 0.98 .99
```
The first value and second values correspond to the low and high usage watermarks, respectively, in percentages. When the high watermark is reached, the XRootD service will automatically purge cache objects down to the low watermark.

## Enable remote debugging
This feature enables remote debugging via the `digFS` read-only file system, it's optional line in the [config file](../configs/xrootd-stashcache-cache-server.cfg):
```
xrootd.diglib * /etc/xrootd/digauth.cf
```
where `/etc/xrootd/digauth.cf` may have following content:
```
all allow host h=abc.org
all allow host h=*.xyz.edu
```

When ready with configuration, please [register](../ops/register.md) and [start](../ops/start.md) your StashCache Cache server.