text:
package org.hibernate.test.dom4j;

/**
 * @author Paco Hernández
 */
public class CarPart implements java.io.Serializable {

	private long id;
	private String partName;

	/**
	 * @return Returns the id.
	 */
	public long getId() {
		return id;
	}
	/**
	 * @param id The id to set.
	 */
	public void setId(long id) {
		this.id = id;
	}
	/**
	 * @return Returns the typeName.
	 */
	public String getPartName() {
		return partName;
	}
	/**
	 * @param typeName The typeName to set.
	 */
	public void setPartName(String typeName) {
		this.partName = typeName;
	}
}


text:
const webpack = require('webpack'); //to access builtin plugins
const path = require('path'); //needed to resolve output path

const HtmlWebpackPlugin  = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');

const srcDir = 'src';
const outputDir = '../dist';

module.exports = {
    devtool: "eval",
    entry: {
        //'vendor': path.resolve(srcDir, 'libs.ts'),
        //'app': path.resolve(srcDir, 'app.module.ts')
        'app':  './src/app.module.ts'    //main app.module
    },
    output: {
        path: path.resolve(__dirname,outputDir),
        filename: '[name].[hash].bundle.js',
        sourceMapFilename: '[name].[hash].map',
        chunkFilename: '[id].[hash].chunk.js'
    },
    resolve: {
        extensions: ['.ts', '.js', '.less', '.css']
    },
    module: {
        rules: [
            { test: /\.ts$/, enforce: 'pre', loader: 'tslint-loader' },
            { test: /(\.component|\.service|)\.ts$/, use: ['ts-loader'] },
            { test: /\.component\.html$/, use: ['raw-loader'] },
            { test: /(\.component|)\.less$/, use: ['to-string-loader', 'css-loader', 'less-loader'] },
            { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })},
            { test: /\.(png|gif|jpg)$/, use:'file-loader'},
            { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use:[{ loader: 'file-loader', options: { name: '[path][name].[ext]'} } ]},
            { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use:[{ loader: 'file-loader', options: { name: '[path][name].[ext]'} } ]},
            { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use:[{ loader: 'file-loader', options: { name: '[path][name].[ext]'} } ]},
            { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use:[{ loader: 'file-loader', options: { name: '[path][name].[ext]'} } ]},
            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use:[{ loader: 'file-loader', options: { name: '[path][name].[ext]'} } ]}
        ]
       // noParse: /node_modules|angular2|bundles/
        //noParse: [ path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, 'angular2'), path.resolve(__dirname, 'bundles') ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            geojsonvt: 'geojson-vt',
        }),
        new ExtractTextPlugin("[name].[contenthash].css"),
        new HtmlWebpackPlugin({
            template: path.resolve(srcDir, 'index.html'),
            inject: true
        }),
        /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      /*  new webpack.ContextReplacementPlugin(
         // The (\\|\/) piece accounts for path separators in *nix and Windows
         /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
         root('./src'), // location of your src
         { }
        ),*/
        new webpack.ContextReplacementPlugin(
             /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            root('./src')
        ),
        new ScriptExtHtmlWebpackPlugin({
          defaultAttribute: 'defer'
        }),
        new WebpackCleanupPlugin({
          exclude: ['index.html', 'data/airports.geojson']
        }),
        new webpack.LoaderOptionsPlugin({debug:true}),
        new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'node_modules/font-awesome/css/font-awesome.min.css', to: 'assets/font-awesome/css/font-awesome.min.css'},
        { from: 'node_modules/font-awesome/fonts', to: 'assets/font-awesome/fonts'},
        { from: 'node_modules/wim-styles/core/css/wim.css', to: 'assets/wim-styles/css/wim.css'}//,
     //   { from: 'node_modules/bootstrap/dist/css/bootstrap.css', to: 'assets/bootstrap/css/bootstrap.css'}
      ])
    ]
};
function root(__path) {
  return path.join(__dirname, __path);
}

redpajama_set_name: RedPajamaGithub


text:
package com.evolveum.midpoint.web.component.assignment;

import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.web.component.util.BaseDeprecatedPanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import java.util.List;

/**
 * @author lazyman
 */
public class ACAttributePanel extends BaseDeprecatedPanel<ACAttributeDto> {

    private static final String ID_ATTRIBUTE_LABEL = "attributeLabel";
    private static final String ID_VALUES = "values";
    private static final String ID_VALUE = "value";
    private static final String ID_REQUIRED = "required";
    private static final String ID_HAS_OUTBOUND = "hasOutbound";

    public ACAttributePanel(String id, IModel<ACAttributeDto> model) {
        super(id, model);
    }

    @Override
    protected void initLayout() {
        Label attributeLabel = new Label(ID_ATTRIBUTE_LABEL, new PropertyModel(getModel(), ACAttributeDto.F_NAME));
        add(attributeLabel);

        WebMarkupContainer required = new WebMarkupContainer(ID_REQUIRED);
        required.add(new VisibleEnableBehaviour() {

            @Override
            public boolean isVisible() {
                ACAttributeDto dto = getModel().getObject();
                PrismPropertyDefinition def = dto.getDefinition();

                return def.isMandatory();
            }
        });
        add(required);

        WebMarkupContainer hasOutbound = new WebMarkupContainer(ID_HAS_OUTBOUND);
        hasOutbound.add(new VisibleEnableBehaviour() {

            @Override
            public boolean isVisible() {
                return hasOutbound();
            }
        });
        add(hasOutbound);

        ListView<ACValueConstructionDto> values = new ListView<ACValueConstructionDto>(ID_VALUES,
                new PropertyModel<List<ACValueConstructionDto>>(getModel(), ACAttributeDto.F_VALUES)) {

            @Override
            protected void populateItem(ListItem<ACValueConstructionDto> listItem) {
                Form form = findParent(Form.class);
                listItem.add(new ACAttributeValuePanel(ID_VALUE, listItem.getModel(), form));
            }
        };
        add(values);
    }

    private boolean hasOutbound() {
        ACAttributeDto dto = getModel().getObject();
        PrismPropertyDefinition def = dto.getDefinition();
        if (!(def instanceof RefinedAttributeDefinition)) {
            return false;
        }

        RefinedAttributeDefinition refinedDef = (RefinedAttributeDefinition) def;
        return refinedDef.hasOutboundMapping();
    }
}


text: extern inline linux_error_t linux_sysinfo(struct linux_sysinfo* info);


text:
//
//  Title:  JPEG Exception Definitions
//
//  Author:  John M. Miano  miano@colosseumbuilders.com
//

#include "grexcept.h"

// Base class for trappable JPEG errors.
class EJpegError : public EGraphicsException
{
public:
  EJpegError (char *msg) : EGraphicsException (msg) {}
} ;

// Exception that makes reading the image impossible.
class EJpegFatal : public EGraphicsException
{
public:
  EJpegFatal (char *msg) : EGraphicsException (msg) {}
} ;

// Exception thrown when the callback function returns a values
// indicating the caller wants to abort the decode.
class EJpegAbort : public EGraphicsException
{
public:
  EJpegAbort  () : EGraphicsException ("JPEG Aborted") {}
} ;

class EJpegValueOutOfRange : public EJpegError
{
public:
  EJpegValueOutOfRange () : EJpegError ("Value out of range") {}
} ;

class EJpegIndexOutOfRange : public EJpegError
{
public:
  EJpegIndexOutOfRange () : EJpegError ("Index out of range") {}
} ;

class EJpegBadOutputParameter : public EJpegError
{
public:
  EJpegBadOutputParameter (char *msg) : EJpegError (msg) {}
} ;

class EJpegBadData : public EJpegError
{
public:
  EJpegBadData (char *msg) : EJpegError (msg) {}
} ;

#endif


text:
package task.application.com.colette.ui.utility.widgets;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import task.application.com.colette.R;

import static android.view.MotionEvent.ACTION_UP;

/**
 * TODO: document your custom view class.
 */
public class ClearableEditText extends AppCompatEditText implements View.OnTouchListener,
        View.OnFocusChangeListener, TextWatcher {
    private String mExampleString; // TODO: use a default from R.string...
    private int mExampleColor = Color.RED; // TODO: use a default from R.color...
    private float mExampleDimension = 0; // TODO: use a default from R.dimen...
    private Drawable mExampleDrawable;

    private TextPaint mTextPaint;
    private float mTextWidth;
    private float mTextHeight;
    private OnFocusChangeListener onFocusChangeListener;
    private OnTouchListener onTouchListener;

    private Drawable clearTextIcon;

    public ClearableEditText(Context context) {
        this(context, null);
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(final Context context) {
        final Drawable drawable = ContextCompat.getDrawable(context, R.drawable.ic_close_black_18dp);
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, getCurrentHintTextColor());
        clearTextIcon = wrappedDrawable;
        clearTextIcon.setBounds(0, 0, clearTextIcon.getIntrinsicHeight(), clearTextIcon.getIntrinsicWidth());
        setClearIconVisible(false);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
        addTextChangedListener(this);
    }

    private void setClearIconVisible(final boolean visible) {
        clearTextIcon.setVisible(visible, false);
        final Drawable[] compoundDrawables = getCompoundDrawables();
        setCompoundDrawables(compoundDrawables[0], compoundDrawables[1],
                visible ? clearTextIcon : null, compoundDrawables[3]);
    }

    @Override
    public void setOnFocusChangeListener(OnFocusChangeListener l) {
        onFocusChangeListener = l;
    }

    @Override
    public void setOnTouchListener(OnTouchListener l) {
        onTouchListener = l;
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
        if (onFocusChangeListener != null) {
            onFocusChangeListener.onFocusChange(view, hasFocus);
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        final int x = (int) motionEvent.getX();
        if (clearTextIcon.isVisible() && x > getWidth() - getPaddingRight() - clearTextIcon.getIntrinsicWidth()) {
            if (motionEvent.getAction() == ACTION_UP)
                setText("");
            return true;
        }
        return onTouchListener != null && onTouchListener.onTouch(view, motionEvent);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (isFocused())
            setClearIconVisible(charSequence.length() > 0);
    }
}


text:
@extends('app')

@section('content')

Edit Attachmenttype {{ $attachmenttype->id }}

    @if ($errors->any())

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

    @endif

    <form action="{{ url('/attachmenttypes/' . $attachmenttype->id) }}" method="post" enctype="multipart/form-data">
        {{ method_field('patch') }}
        {{ csrf_field() }}
        @include ('attachmenttypes.form', ['submitButtonText' => 'Update'])
    </form>

@endsection


text:
#ifndef BaseLib_Containers_HashMap_h
#define BaseLib_Containers_HashMap_h

#include "BaseLib/Containers/Array.h"
#include <utility>

namespace BaseLib {
namespace Containers {

template<typename Key, typename Value>
class HashMap {
public:

	typedef uint HashType;
	typedef typename Key KeyType;
	typedef typename Value ValueType;
	typedef typename std::pair<const KeyType, ValueType> PairType;

	HashMap()
		: count(0)
		, hashTable(31)
	{
	}

	inline void insert(const PairType& keyValuePair)
	{
		int hashTableSize = hashTable.getCount();
		if (count >= hashTableSize * 10)
		{
			increaseTableSize();
		}

		HashType hashValue = hash(key);
		hashValue %= hashTableSize;
		if (hashTable[hashValue].firstIndexOf(value) == -1)
		{
			hashTable[hashValue] += keyValuePair;
			++count;
		}
	}

	inline void insert(const KeyType& key, const ValueType& value)
	{
		insert(PairType(key, value));
	}

	inline bool remove(const KeyType& key)
	{
		HashType hashValue = hash(key);
		hashValue %= hashTable.getCount();
		Array<PairType>& list = hashTable[hashValue];
		const int count = list.getCount();
		for (int i = 0; i < count; ++i)
		{
			if (list[i].first == key)
			{
				list.remove(i);
				--count;
				return true;
			}
		}
		return false;
	}

	inline bool has(const KeyType& key) const
	{
		HashType hashValue = hash(key);
		hashValue %= hashTable.getCount();
		Array<PairType>& list = hashTable[hashValue];
		const int count = list.getCount();
		for (int i = 0; i < count; ++i)
		{
			if (list[i].first == key)
			{
				return true;
			}
		}
		return false;
	}

	inline ValueType get(const KeyType& key) const
	{
		HashType hashValue = hash(key);
		hashValue %= hashTable.getCount();
		Array<PairType>& list = hashTable[hashValue];
		const int count = list.getCount();
		for (int i = 0; i < count; ++i)
		{
			if (list[i].first == key)
			{
				return list[i].second;
			}
		}
		BaseLib::ErrorHandling::argumentError("Can't find value for key!");
		return ValueType();
	}

	inline int getCount() const
	{
		return count;
	}

private:

	int count;
	typedef Array<Array<PairType> > HashTable;
	HashTable hashTable;

	inline void increaseTableSize()
	{
		Array<PairType> buffer(count);
		int index = 0;
		for (int i = 0; i < hashTableSize; ++i)
		{
			Array<PairType>& list = hashTable[i];
			const int listSize = list.getCount();
			buffer.assign(&list.firstElement(), listSize, index);
			index += listSize;
			list.setCount(0);
		}

		hashTableSize = (hashTableSize + 1) * 2 - 1;
		hashTable.setCount(hashTableSize);

		for (int i = 0; i < count; ++i)
		{
			insert(buffer[i]);
		}
	}
};

} // namespace Containers
} // namespace BaseLib

#endif // #ifndef BaseLib_Containers_HashMap_h


text:
"use strict";

const Data = require("../types/data");
const { Controller } = require("servicecom");

class Datas extends Controller {
    constructor() {
        super(Data, [ "read", "create" ]);
    }
}

module.exports = Datas;


text:
// @flow
jest.enableAutomock();
jest.unmock('../libDefs.js');
jest.unmock('../semver.js');
jest.unmock('semver');

import Git from 'nodegit';

import {fs} from '../node.js';
import {
  _CACHE_REPO_DIR as CACHE_REPO_DIR,
  _CACHE_REPO_EXPIRY as CACHE_REPO_EXPIRY,
  _CACHE_REPO_GIT_DIR as CACHE_REPO_GIT_DIR,
  _ensureCacheRepo as ensureCacheRepo,
  updateCacheRepo,
  _LAST_UPDATED_FILE as LAST_UPDATED_FILE,
  filterLibDefs,
} from '../libDefs.js';
import {stringToVersion} from '../semver.js';

/**
 * Jest's process of mocking in place fools Flow, so we use this as an explicit
 * escape hatch when we need to side-step Flow.
 */
function _mock(mockFn) {
  return (mockFn: any);
}

describe('libDefs', () => {
  describe('ensureCacheRepo', () => {
    beforeEach(() => {
      _mock(Git.Clone).mockClear();
      const repo = _mock(Git.Repository)._mockRepo;
      repo.checkoutBranch.mockClear();
      repo.rebaseBranches.mockClear();
      _mock(Git.Repository.open).mockClear();
    });

    pit('clones the repo if not present on disk', async () => {
      _mock(fs.exists).mockImplementation(dirPath => {
        return dirPath !== CACHE_REPO_DIR;
      });

      await ensureCacheRepo();
      expect(_mock(Git.Clone).mock.calls.length).toBe(1);
      expect(_mock(fs.writeFile).mock.calls.length).toBe(1);
      expect(_mock(fs.writeFile).mock.calls[0][0]).toBe(LAST_UPDATED_FILE);
    });

    pit('does NOT clone the repo if already present on disk', async () => {
      _mock(fs.exists).mockImplementation(dirPath => {
        return dirPath === CACHE_REPO_DIR;
      });

      await ensureCacheRepo();
      expect(_mock(Git.Clone).mock.calls.length).toBe(0);
    });

    pit('rebases if present on disk + lastUpdated is old', async () => {
      _mock(fs.exists).mockImplementation(dirPath => {
        return dirPath === CACHE_REPO_DIR || dirPath === CACHE_REPO_GIT_DIR;
      });
      _mock(fs.readFile).mockImplementation((filePath) => {
        if (filePath === LAST_UPDATED_FILE) {
          return String(Date.now() - CACHE_REPO_EXPIRY - 1);
        }
      });

      await ensureCacheRepo();
      expect(_mock(Git.Repository.open).mock.calls).toEqual([
        [CACHE_REPO_DIR],
      ]);
      const _mockRepo = _mock(Git.Repository)._mockRepo;
      expect(_mockRepo.rebaseBranches.mock.calls).toEqual([
        ['master', 'origin/master'],
      ]);
    });

    pit('does NOT rebase if on disk, but lastUpdated is recent', async () => {
      _mock(fs.exists).mockImplementation(dirPath => {
        return dirPath === CACHE_REPO_DIR || dirPath === CACHE_REPO_GIT_DIR;
      });
      _mock(fs.readFile).mockImplementation((filePath) => {
        if (filePath === LAST_UPDATED_FILE) {
          return String(Date.now());
        }
      });

      await ensureCacheRepo();
      expect(_mock(Git.Repository.open).mock.calls.length).toBe(0);
    });
  });

  describe('updateCacheRepo', () => {
    beforeEach(() => {
      _mock(Git.Clone).mockClear();
      const repo = _mock(Git.Repository)._mockRepo;
      repo.checkoutBranch.mockClear();
      repo.rebaseBranches.mockClear();
      _mock(Git.Repository.open).mockClear();
    });

    pit('rebases if present on disk + lastUpdated is old', async () => {
      _mock(fs.exists).mockImplementation(dirPath => {
        return dirPath === CACHE_REPO_DIR || dirPath === CACHE_REPO_GIT_DIR;
      });

      _mock(fs.readFile).mockImplementation((filePath) => {
        if (filePath === LAST_UPDATED_FILE) {
          return String(Date.now() - CACHE_REPO_EXPIRY - 1);
        }
      });

      await updateCacheRepo();
      expect(_mock(Git.Repository.open).mock.calls).toEqual([
        [CACHE_REPO_DIR],
      ]);
      const _mockRepo = _mock(Git.Repository)._mockRepo;
      expect(_mockRepo.rebaseBranches.mock.calls).toEqual([
        ['master', 'origin/master'],
      ]);
    });
  });

  describe('filterLibDefs', () => {
    function _generateFixturePkg(name, verStr, flowVerStr) {
      return {
        pkgName: name,
        pkgVersion: stringToVersion(verStr),
        pkgVersionStr: verStr,
        pkgNameVersionStr: `${name}_${verStr}`,
        flowVersion: stringToVersion(verStr),
        flowVersionStr: flowVerStr,
        path: '',
        testFilePaths: [],
      };
    }

    describe('fuzzy filter', () => {
      it('filters on exact name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'fuzzy', term: 'mori'});
        expect(filtered).toEqual([fixture[1], fixture[0]]);
      });

      it('filters on differently-cased name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'fuzzy', term: 'Mori'});
        expect(filtered).toEqual([fixture[1], fixture[0]]);
      });

      it('filters on partial name', () => {
        const fixture = [
          _generateFixturePkg('**mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori**', 'v0.3.x', '>=v0.18.x'),
          _generateFixturePkg('mo**ri', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'fuzzy', term: 'mori'});
        expect(filtered).toEqual([fixture[1], fixture[0]]);
      });

      it('filters on flow version', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {
          type: 'fuzzy',
          term: 'mori',
          flowVersion: stringToVersion('v0.19.0')
        });
        expect(filtered).toEqual([fixture[1]]);
      });
    });

    describe('exact-name filter', () => {
      it('filters on exact name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'exact-name', term: 'mori'});
        expect(filtered).toEqual([fixture[1], fixture[0]]);
      });

      it('filters on differently-cased name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'exact-name', term: 'Mori'});
        expect(filtered).toEqual([fixture[1], fixture[0]]);
      });

      it('DOES NOT filter on partial name', () => {
        const fixture = [
          _generateFixturePkg('**mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
          _generateFixturePkg('mo**ri', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {type: 'exact-name', term: 'mori'});
        expect(filtered).toEqual([fixture[1]]);
      });

      it('filters on flow version', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture, {
          type: 'exact-name',
          term: 'mori',
          flowVersion: stringToVersion('v0.19.0')
        });
        expect(filtered).toEqual([fixture[1]]);
      });
    });

    describe('exact filter', () => {
      function _generateLibDef(pkgName, pkgVersionStr, flowVersionStr) {
        return {
          pkgName,
          pkgVersion: stringToVersion(pkgVersionStr),
          pkgVersionStr,
          pkgNameVersionStr: `${pkgName}_${pkgVersionStr}`,
          flowVersion: stringToVersion(flowVersionStr),
          flowVersionStr,
          path: '',
          testFilePaths: [],
        };
      }

      it('filters on exact name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('notmori', 'v0.3.x', '>=v0.22.x'),
        ];
        const filtered = filterLibDefs(
          fixture,
          {type: 'exact', libDef: _generateLibDef('mori', 'v0.3.1', 'v0.x.x')},
        );
        expect(filtered).toEqual([fixture[0]]);
      });

      it('filters on differently-cased name', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('notmori', 'v0.3.x', '>=v0.22.x'),
        ];
        const filtered = filterLibDefs(
          fixture,
          {type: 'exact', libDef: _generateLibDef('Mori', 'v0.3.1', 'v0.x.x')},
        );
        expect(filtered).toEqual([fixture[0]]);
      });

      it('DOES NOT filter on partial name', () => {
        const fixture = [
          _generateFixturePkg('**mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori**', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mo**ri', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori',   'v0.3.x', '>=v0.22.x'),
        ];
        const filtered = filterLibDefs(
          fixture,
          {type: 'exact', libDef: _generateLibDef('mori', 'v0.3.1', 'v0.x.x')},
        );
        expect(filtered).toEqual([fixture[3]]);
      });

      it('filters on flow version', () => {
        const fixture = [
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.22.x'),
          _generateFixturePkg('mori', 'v0.3.x', '>=v0.18.x'),
        ];
        const filtered = filterLibDefs(fixture,{
          type: 'exact',
          libDef: _generateLibDef('mori', 'v0.3.1', 'v0.x.x'),
          flowVersion: stringToVersion('v0.19.0')
        });
        expect(filtered).toEqual([fixture[1]]);
      });
    });
  });
});


text:
({

    TEST_ARRAY : ['red',
                  'green',
                  'blue',
                  'green',
                  'yellow'],

    EMPTY_ARRAY : [],

    testArrayIndex : {
        test : function(cmp) {
            $A.test.assertTrue(this.TEST_ARRAY.indexOf('red') === 0, "Wrong index for first array element returned");
            $A.test.assertTrue(this.TEST_ARRAY.indexOf('yellow') === 4, "Wrong index for last array element returned");
            $A.test.assertTrue(this.TEST_ARRAY.indexOf('nonexistent') === -1, "Element not found in array should return -1");
            $A.test.assertTrue(this.TEST_ARRAY.indexOf('') === -1, "Index returned on search for empty string");
            $A.test.assertTrue(this.TEST_ARRAY.indexOf(null) === -1, "Index returned on search for null");
            $A.test.assertTrue(this.TEST_ARRAY.indexOf(undefined) === -1, "Index returned on search for undefined");
        }
    },

    testArrayIndexOnEmptyArray : {
        test : function(cmp) {
            $A.test.assertTrue(this.EMPTY_ARRAY.indexOf('red') === -1, "Element found in empty array");
            $A.test.assertTrue(this.EMPTY_ARRAY.indexOf('') === -1, "Element found in empty array");
        }
    },

    testArrayIndexOnArrayFromComponent : {
        test : function(cmp) {
            var array = cmp.get("v.array");
            $A.test.assertTrue(array.indexOf('red') === 0, "Wrong index for first array element returned");
            $A.test.assertTrue(array.indexOf('yellow') === 4, "Wrong index for last array element returned");
            $A.test.assertTrue(array.indexOf('nonexistent') === -1, "Element not found in array should return -1");
            $A.test.assertTrue(array.indexOf('') === -1, "Index returned for empty search");
            $A.test.assertTrue(array.indexOf(null) === -1, "Index returned for null search");
            $A.test.assertTrue(array.indexOf(undefined) === -1, "Index returned for undefined search");

        }
    }
})


text:
layout: patterns
title: Box
---

{% include patterns/box/index.html %}


text:
package horizon

import (
	"encoding/json"
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	"github.com/stellar/go-horizon/test"
)

func TestAccountActions(t *testing.T) {

	Convey("Account Actions:", t, func() {
		test.LoadScenario("base")
		app := NewTestApp()
		defer app.Close()
		rh := NewRequestHelper(app)

		Convey("GET /accounts/GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ", func() {
			w := rh.Get("/accounts/GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ", test.RequestHelperNoop)

			So(w.Code, ShouldEqual, 200)

			var result AccountResource
			err := json.Unmarshal(w.Body.Bytes(), &result)
			So(err, ShouldBeNil)
			So(result.Sequence, ShouldEqual, 3)
		})

		Convey("GET /accounts/100", func() {
			w := rh.Get("/accounts/100", test.RequestHelperNoop)
			So(w.Code, ShouldEqual, 404)
		})

		Convey("GET /accounts", func() {
			w := rh.Get("/accounts", test.RequestHelperNoop)
			So(w.Code, ShouldEqual, 200)
			So(w.Body, ShouldBePageOf, 3)

			w = rh.Get("/accounts?limit=1", test.RequestHelperNoop)
			So(w.Code, ShouldEqual, 200)
			So(w.Body, ShouldBePageOf, 1)
		})
	})
}


text:
namespace Microsoft.Azure.Management.Monitor.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The response to a metrics query.
    /// </summary>
    public partial class Response
    {
        /// <summary>
        /// Initializes a new instance of the Response class.
        /// </summary>
        public Response()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Response class.
        /// </summary>
        /// <param name="timespan">The timespan for which the data was
        /// retrieved. Its value consists of two datatimes concatenated,
        /// separated by '/'.  This may be adjusted in the future and returned
        /// back from what was originally requested.</param>
        /// <param name="value">the value of the collection.</param>
        /// <param name="cost">The integer value representing the cost of the
        /// query, for data case.</param>
        /// <param name="interval">The interval (window size) for which the
        /// metric data was returned in.  This may be adjusted in the future
        /// and returned back from what was originally requested.  This is not
        /// present if a metadata request was made.</param>
        /// <param name="namespaceProperty">The namespace of the metrics been
        /// queried</param>
        /// <param name="resourceregion">The region of the resource been
        /// queried for metrics.</param>
        public Response(string timespan, IList<Metric> value, double? cost = default(double?), System.TimeSpan? interval = default(System.TimeSpan?), string namespaceProperty = default(string), string resourceregion = default(string))
        {
            Cost = cost;
            Timespan = timespan;
            Interval = interval;
            NamespaceProperty = namespaceProperty;
            Resourceregion = resourceregion;
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the integer value representing the cost of the query,
        /// for data case.
        /// </summary>
        [JsonProperty(PropertyName = "cost")]
        public double? Cost { get; set; }

        /// <summary>
        /// Gets or sets the timespan for which the data was retrieved. Its
        /// value consists of two datatimes concatenated, separated by '/'.
        /// This may be adjusted in the future and returned back from what was
        /// originally requested.
        /// </summary>
        [JsonProperty(PropertyName = "timespan")]
        public string Timespan { get; set; }

        /// <summary>
        /// Gets or sets the interval (window size) for which the metric data
        /// was returned in.  This may be adjusted in the future and returned
        /// back from what was originally requested.  This is not present if a
        /// metadata request was made.
        /// </summary>
        [JsonProperty(PropertyName = "interval")]
        public System.TimeSpan? Interval { get; set; }

        /// <summary>
        /// Gets or sets the namespace of the metrics been queried
        /// </summary>
        [JsonProperty(PropertyName = "namespace")]
        public string NamespaceProperty { get; set; }

        /// <summary>
        /// Gets or sets the region of the resource been queried for metrics.
        /// </summary>
        [JsonProperty(PropertyName = "resourceregion")]
        public string Resourceregion { get; set; }

        /// <summary>
        /// Gets or sets the value of the collection.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<Metric> Value { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Timespan == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Timespan");
            }
            if (Value == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Value");
            }
            if (Cost < 0)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "Cost", 0);
            }
            if (Value != null)
            {
                foreach (var element in Value)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
package edu.gatech.gtri.typesafeconfigextensions.factory;

import java.nio.file.Path;

/**
 * This type is used for {@link ConfigFactory}'s DSL API when specifying
 * {@link ConfigSource}s that reference filesystem paths.
 *
 * <p>{@link FileConfigSourceStep} should generally be implemented by
 * extending {@link BaseFileConfigSourceStep}.</p>
 */
public interface FileConfigSourceStep {

    NamedConfigSource by(PathSpecification pathSpecification);

    /**
     * Equivalent to {@code by ( PathSpecifications.byPath(path) )}.
     *
     * @see #by(PathSpecification)
     * @see PathSpecifications#byPath(Path)
     */
    NamedConfigSource byPath(Path path);

    /**
     * Equivalent to {@code by ( PathSpecifications.byKey(key) )}.
     *
     * @see #by(PathSpecification)
     * @see PathSpecifications#byKey(String)
     */
    NamedConfigSource byKey(String key);
}


text:
NSString *const kTWConsumerKey = @"";
NSString *const kTWConsumerSecret = @"";

@interface ViewController ()

@property (nonatomic, strong) YATTwitterHelper *twitterHelper;
@property (weak, nonatomic) IBOutlet UITextView *tokenTextView;

- (IBAction)testAuthTapped:(UIButton *)sender;
- (IBAction)reverseAuthTapped:(UIButton *)sender;

@end

@implementation ViewController

#pragma mark - UIViewController Overrides

- (void)viewDidLoad {
    [super viewDidLoad];
    _twitterHelper = [[YATTwitterHelper alloc] initWithKey:kTWConsumerKey andSecret:kTWConsumerSecret];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - IBActions

- (IBAction)testAuthTapped:(UIButton *)sender {
    self.tokenTextView.text = @"";
    [self.twitterHelper authWithSuccess:^(ACAccount *account) {
        self.tokenTextView.text = [NSString stringWithFormat:@"User: %@ authorized", account.accountDescription];
    } failure:^(NSError *error) {
        self.tokenTextView.text = error.description;
    }];
}

- (IBAction)reverseAuthTapped:(UIButton *)sender {
    self.tokenTextView.text = @"";
    [self.twitterHelper reverseAuthWithSuccess:^(NSDictionary *data) {
        self.tokenTextView.text = [data descriptionInStringsFileFormat];
    } failure:^(NSError *error) {
        self.tokenTextView.text = error.description;
    }];
}
@end


text:
using System;
using System.Collections.Generic;
using KLibrary.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTest.Linq
{
    [TestClass]
    public class ComparisonTest
    {
        [TestMethod]
        public void CreateComparer()
        {
            Assert.AreEqual(-1, Comparer<int>.Default.Compare(1, 2));
            Assert.AreEqual(-1, Comparer<int>.Create((x, y) => x.CompareTo(y)).Compare(1, 2));
            Assert.AreEqual(1, Comparer<int>.Create((x, y) => -x.CompareTo(y)).Compare(1, 2));

            Assert.AreEqual(-1, Comparison.CreateComparer<int>((x, y) => x.CompareTo(y)).Compare(1, 2));
            Assert.AreEqual(1, Comparison.CreateComparer<int>((x, y) => -x.CompareTo(y)).Compare(1, 2));
        }

        [TestMethod]
        public void CreateEqualityComparer()
        {
            Assert.AreEqual(true, EqualityComparer<int>.Default.Equals(2, 2));
            Assert.AreEqual(false, EqualityComparer<int>.Default.Equals(1, 2));

            var comparer = Comparison.CreateEqualityComparer<string>((x, y) => string.Equals(x, y, StringComparison.InvariantCultureIgnoreCase));
            Assert.AreEqual(true, comparer.Equals("abc", "ABC"));
            Assert.AreEqual(false, comparer.Equals("abcd", "ABC"));
        }
    }
}


text:
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;

[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: CLSCompliant(true)]

[assembly: XmlnsPrefix("urn:TomsToolbox.Wpf.Styles", "styles")]
[assembly: XmlnsDefinition("urn:TomsToolbox.Wpf.Styles", "TomsToolbox.Wpf.Styles")]
[assembly: XmlnsDefinition("urn:TomsToolbox.Wpf.Styles", "TomsToolbox.Wpf.Styles.Effects")]


text:
package io.micrometer.dynatrace.v1;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.common.util.internal.logging.LogEvent;
import io.micrometer.common.util.internal.logging.MockLogger;
import io.micrometer.common.util.internal.logging.MockLoggerFactory;
import io.micrometer.core.instrument.*;
import io.micrometer.core.instrument.config.validate.ValidationException;
import io.micrometer.core.ipc.http.HttpSender;
import io.micrometer.dynatrace.DynatraceApiVersion;
import io.micrometer.dynatrace.DynatraceConfig;
import io.micrometer.dynatrace.DynatraceMeterRegistry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static io.micrometer.common.util.internal.logging.InternalLogLevel.DEBUG;
import static io.micrometer.common.util.internal.logging.InternalLogLevel.ERROR;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;

/**
 * Tests for {@link DynatraceExporterV1}.
 *
 * @author Johnny Lim
 */
class DynatraceExporterV1Test {

    private static final MockLoggerFactory FACTORY = new MockLoggerFactory();

    private static final MockLogger LOGGER = FACTORY.getLogger(DynatraceExporterV1.class);

    private static final Double GAUGE_VALUE = 1.0;

    private final DynatraceConfig config = createDynatraceConfig();

    private final MockClock clock = new MockClock();

    private final HttpSender httpClient = request -> new HttpSender.Response(200, null);

    private final DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient));

    private final DynatraceMeterRegistry meterRegistry = DynatraceMeterRegistry.builder(config).clock(clock)
            .httpClient(httpClient).build();

    private final ObjectMapper mapper = new ObjectMapper();

    @AfterEach
    void tearDown() {
        LOGGER.clear();
    }

    @Test
    void constructorWhenUriIsMissingShouldThrowValidationException() {
        assertThatThrownBy(() -> new DynatraceMeterRegistry(new DynatraceConfig() {
            @Override
            public String get(String key) {
                return null;
            }

            @Override
            public String deviceId() {
                return "deviceId";
            }

            @Override
            public String apiToken() {
                return "apiToken";
            }

            @Override
            public DynatraceApiVersion apiVersion() {
                return DynatraceApiVersion.V1;
            }
        }, Clock.SYSTEM)).isExactlyInstanceOf(ValidationException.class);
    }

    @Test
    void constructorWhenDeviceIdIsMissingShouldThrowValidationException() {
        assertThatThrownBy(() -> new DynatraceMeterRegistry(new DynatraceConfig() {
            @Override
            public String get(String key) {
                return null;
            }

            @Override
            public String uri() {
                return "uri";
            }

            @Override
            public String apiToken() {
                return "apiToken";
            }

            @Override
            public DynatraceApiVersion apiVersion() {
                return DynatraceApiVersion.V1;
            }

        }, Clock.SYSTEM)).isExactlyInstanceOf(ValidationException.class);
    }

    @Test
    void constructorWhenApiTokenIsMissingShouldThrowValidationException() {
        assertThatThrownBy(() -> new DynatraceMeterRegistry(new DynatraceConfig() {
            @Override
            public String get(String key) {
                return null;
            }

            @Override
            public String uri() {
                return "uri";
            }

            @Override
            public String deviceId() {
                return "deviceId";
            }

            @Override
            public DynatraceApiVersion apiVersion() {
                return DynatraceApiVersion.V1;
            }
        }, Clock.SYSTEM)).isExactlyInstanceOf(ValidationException.class);
    }

    @Test
    void putCustomMetricOnSuccessShouldAddMetricIdToCreatedCustomMetrics()
            throws NoSuchFieldException, IllegalAccessException {
        Field createdCustomMetricsField = DynatraceExporterV1.class.getDeclaredField("createdCustomMetrics");
        createdCustomMetricsField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Set<String> createdCustomMetrics = (Set<String>) createdCustomMetricsField.get(exporter);
        assertThat(createdCustomMetrics).isEmpty();

        DynatraceMetricDefinition customMetric = new DynatraceMetricDefinition("metricId", null, null, null,
                new String[] { "type" }, null);
        exporter.putCustomMetric(customMetric);
        assertThat(createdCustomMetrics).containsExactly("metricId");
    }

    @Test
    void writeMeterWithGauge() {
        meterRegistry.gauge("my.gauge", GAUGE_VALUE);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        assertThat(exporter.writeMeter(gauge)).hasSize(1);
    }

    @Test
    void writeMeterWithGaugeShouldDropNanValue() {
        meterRegistry.gauge("my.gauge", Double.NaN);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        assertThat(exporter.writeMeter(gauge)).isEmpty();
    }

    @SuppressWarnings("unchecked")
    @Test
    void writeMeterWithGaugeWhenChangingFiniteToNaNShouldWork() {
        AtomicBoolean first = new AtomicBoolean(true);
        meterRegistry.gauge("my.gauge", first, (b) -> b.getAndSet(false) ? GAUGE_VALUE : Double.NaN);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        Stream<DynatraceCustomMetric> stream = exporter.writeMeter(gauge);
        List<DynatraceCustomMetric> metrics = stream.collect(Collectors.toList());
        assertThat(metrics).hasSize(1);
        DynatraceCustomMetric metric = metrics.get(0);
        DynatraceTimeSeries timeSeries = metric.getTimeSeries();
        try {
            Map<String, Object> map = mapper.readValue(timeSeries.asJson(), Map.class);
            List<List<Number>> dataPoints = (List<List<Number>>) map.get("dataPoints");
            assertThat(dataPoints.get(0).get(1).doubleValue()).isEqualTo(GAUGE_VALUE);
        }
        catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Test
    void writeMeterWithGaugeShouldDropInfiniteValues() {
        meterRegistry.gauge("my.gauge", Double.POSITIVE_INFINITY);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        assertThat(exporter.writeMeter(gauge)).isEmpty();

        meterRegistry.gauge("my.gauge", Double.NEGATIVE_INFINITY);
        gauge = meterRegistry.find("my.gauge").gauge();
        assertThat(exporter.writeMeter(gauge)).isEmpty();
    }

    @Test
    void writeMeterWithTimeGauge() {
        AtomicReference<Double> obj = new AtomicReference<>(GAUGE_VALUE);
        meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get);
        TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge();
        assertThat(exporter.writeMeter(timeGauge)).hasSize(1);
    }

    @Test
    void writeMeterWithTimeGaugeShouldDropNanValue() {
        AtomicReference<Double> obj = new AtomicReference<>(Double.NaN);
        meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get);
        TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge();
        assertThat(exporter.writeMeter(timeGauge)).isEmpty();
    }

    @Test
    void writeMeterWithTimeGaugeShouldDropInfiniteValues() {
        AtomicReference<Double> obj = new AtomicReference<>(Double.POSITIVE_INFINITY);
        meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get);
        TimeGauge timeGauge = meterRegistry.find("my.timeGauge").timeGauge();
        assertThat(exporter.writeMeter(timeGauge)).isEmpty();

        obj = new AtomicReference<>(Double.NEGATIVE_INFINITY);
        meterRegistry.more().timeGauge("my.timeGauge", Tags.empty(), obj, TimeUnit.SECONDS, AtomicReference::get);
        timeGauge = meterRegistry.find("my.timeGauge").timeGauge();
        assertThat(exporter.writeMeter(timeGauge)).isEmpty();
    }

    @Test
    void writeCustomMetrics() {
        Double number = 1d;
        meterRegistry.gauge("my.gauge", number);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        Stream<DynatraceCustomMetric> series = exporter.writeMeter(gauge);
        List<DynatraceTimeSeries> timeSeries = series.map(DynatraceCustomMetric::getTimeSeries)
                .collect(Collectors.toList());
        List<DynatraceBatchedPayload> entries = exporter.createPostMessages("my.type", null, timeSeries);
        assertThat(entries).hasSize(1);
        assertThat(entries.get(0).metricCount).isEqualTo(1);
        assertThat(isValidJson(entries.get(0).payload)).isEqualTo(true);
    }

    @Test
    void whenAllTsTooLargeEmptyMessageListReturned() {
        List<DynatraceBatchedPayload> messages = exporter.createPostMessages("my.type", null,
                Collections.singletonList(createTimeSeriesWithDimensions(10_000)));
        assertThat(messages).isEmpty();
    }

    @Test
    void splitsWhenExactlyExceedingMaxByComma() {
        // @formatter:off
        // comma needs to be considered when there is more than one time series
        List<DynatraceBatchedPayload> messages = exporter.createPostMessages(
                "my.type",
                "my.group",
                // Max bytes: 15330 (excluding header/footer, 15360 with header/footer)
                Arrays.asList(
                        createTimeSeriesWithDimensions(750), // 14861 bytes
                        // 469 bytes (overflows due to comma)
                        createTimeSeriesWithDimensions(23, "asdfg"),
                        createTimeSeriesWithDimensions(750), // 14861 bytes
                        createTimeSeriesWithDimensions(22, "asd") // 468 bytes + comma
                )
        );
        // @formatter:on
        assertThat(messages).hasSize(3);
        assertThat(messages.get(0).metricCount).isEqualTo(1);
        assertThat(messages.get(1).metricCount).isEqualTo(1);
        assertThat(messages.get(2).metricCount).isEqualTo(2);
        assertThat(messages.get(2).payload.getBytes(UTF_8).length).isEqualTo(15360);
        assertThat(messages.stream().map(message -> message.payload).allMatch(this::isValidJson)).isTrue();
    }

    @Test
    void countsPreviousAndNextComma() {
        // @formatter:off
        List<DynatraceBatchedPayload> messages = exporter.createPostMessages(
                "my.type",
                null,
                // Max bytes: 15330 (excluding header/footer, 15360 with header/footer)
                Arrays.asList(
                        createTimeSeriesWithDimensions(750), // 14861 bytes
                        createTimeSeriesWithDimensions(10, "asdf"), // 234 bytes + comma
                        // 234 bytes + comma = 15331 bytes (overflow)
                        createTimeSeriesWithDimensions(10, "asdf")
                )
        );
        // @formatter:on
        assertThat(messages).hasSize(2);
        assertThat(messages.get(0).metricCount).isEqualTo(2);
        assertThat(messages.get(1).metricCount).isEqualTo(1);
        assertThat(messages.stream().map(message -> message.payload).allMatch(this::isValidJson)).isTrue();
    }

    @Test
    void writeMeterWhenCustomMeterHasOnlyNonFiniteValuesShouldNotBeWritten() {
        Measurement measurement1 = new Measurement(() -> Double.POSITIVE_INFINITY, Statistic.VALUE);
        Measurement measurement2 = new Measurement(() -> Double.NEGATIVE_INFINITY, Statistic.VALUE);
        Measurement measurement3 = new Measurement(() -> Double.NaN, Statistic.VALUE);
        List<Measurement> measurements = Arrays.asList(measurement1, measurement2, measurement3);
        Meter meter = Meter.builder("my.meter", Meter.Type.GAUGE, measurements).register(this.meterRegistry);
        assertThat(exporter.writeMeter(meter)).isEmpty();
    }

    @Test
    void writeMeterWhenCustomMeterHasMixedFiniteAndNonFiniteValuesShouldSkipOnlyNonFiniteValues() {
        Measurement measurement1 = new Measurement(() -> Double.POSITIVE_INFINITY, Statistic.VALUE);
        Measurement measurement2 = new Measurement(() -> Double.NEGATIVE_INFINITY, Statistic.VALUE);
        Measurement measurement3 = new Measurement(() -> Double.NaN, Statistic.VALUE);
        Measurement measurement4 = new Measurement(() -> 1d, Statistic.VALUE);
        Measurement measurement5 = new Measurement(() -> 2d, Statistic.VALUE);
        List<Measurement> measurements = Arrays.asList(measurement1, measurement2, measurement3, measurement4,
                measurement5);
        Meter meter = Meter.builder("my.meter", Meter.Type.GAUGE, measurements).register(this.meterRegistry);
        assertThat(exporter.writeMeter(meter)).hasSize(2);
    }

    @Test
    void writeSummary() {
        DistributionSummary summary = DistributionSummary.builder("my.distribution.summary").register(meterRegistry);

        summary.record(1d);
        summary.record(2d);
        summary.record(3d);

        clock.add(config.step());

        List<String> metrics = exporter.writeSummary(summary).map((metric) -> metric.getTimeSeries().asJson())
                .collect(Collectors.toList());

        assertThat(metrics).containsExactlyInAnyOrder(
                "{\"timeseriesId\":\"custom:my.distribution.summary.sum\",\"dataPoints\":[[60001,6]]}",
                "{\"timeseriesId\":\"custom:my.distribution.summary.count\",\"dataPoints\":[[60001,3]]}",
                "{\"timeseriesId\":\"custom:my.distribution.summary.avg\",\"dataPoints\":[[60001,2]]}",
                "{\"timeseriesId\":\"custom:my.distribution.summary.max\",\"dataPoints\":[[60001,3]]}");
    }

    @Test
    void failOnPutShouldHaveProperLogging() {
        HttpSender httpClient = request -> new HttpSender.Response(500, "simulated");
        DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient));

        meterRegistry.gauge("my.gauge", GAUGE_VALUE);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        exporter.export(Collections.singletonList(gauge));

        assertThat(LOGGER.getLogEvents()).hasSize(1);
        assertThat(LOGGER.getLogEvents().get(0).getLevel()).isSameAs(ERROR);
        assertThat(LOGGER.getLogEvents().get(0).getMessage()).isEqualTo(
                "failed to create custom metric custom:my.gauge in Dynatrace: Error Code=500, Response Body=simulated");
        assertThat(LOGGER.getLogEvents().get(0).getCause()).isNull();
    }

    @Test
    void failOnPostShouldHaveProperLogging() throws Throwable {
        HttpSender httpClient = mock(HttpSender.class);
        HttpSender.Request.Builder builder = HttpSender.Request.build("https://test", httpClient);
        when(httpClient.put(isA(String.class))).thenReturn(builder);
        when(httpClient.post(isA(String.class))).thenReturn(builder);
        when(httpClient.send(isA(HttpSender.Request.class))).thenReturn(new HttpSender.Response(200, null),
                new HttpSender.Response(500, "simulated"));

        DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient));

        meterRegistry.gauge("my.gauge", GAUGE_VALUE);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();
        exporter.export(Collections.singletonList(gauge));

        assertThat(LOGGER.getLogEvents()).hasSize(3);
        assertThat(LOGGER.getLogEvents().get(0).getLevel()).isSameAs(DEBUG);
        assertThat(LOGGER.getLogEvents().get(0).getMessage())
                .isEqualTo("created custom:my.gauge as custom metric in Dynatrace");
        assertThat(LOGGER.getLogEvents().get(0).getCause()).isNull();

        assertThat(LOGGER.getLogEvents().get(1).getLevel()).isSameAs(ERROR);
        assertThat(LOGGER.getLogEvents().get(1).getMessage())
                .isEqualTo("failed to send metrics to Dynatrace: Error Code=500, Response Body=simulated");
        assertThat(LOGGER.getLogEvents().get(1).getCause()).isNull();
    }

    @Test
    void testTokenShouldBeRedactedInPutFailure() {
        HttpSender httpClient = spy(HttpSender.class);

        String invalidUrl = "http://localhost###";
        String apiToken = "this.is.a.fake.apiToken";

        DynatraceExporterV1 exporter = getDynatraceExporterV1(httpClient, invalidUrl, apiToken);

        meterRegistry.gauge("my.gauge", GAUGE_VALUE);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();

        exporter.export(Collections.singletonList(gauge));

        assertThat(LOGGER.getLogEvents())
                // map to only keep the message strings
                .extracting(LogEvent::getMessage)
                .containsExactly(String.format(
                        "failed to build request: Illegal character in fragment at index 17: %s/api/v1/timeseries/custom:my.gauge?api-token=<redacted>",
                        invalidUrl));
    }

    @Test
    void testTokenShouldBeRedactedInPostFailure() throws Throwable {
        HttpSender httpClient = spy(HttpSender.class);

        String invalidUrl = "http://localhost###";
        String apiToken = "this.is.a.fake.apiToken";

        HttpSender.Request.Builder builder = HttpSender.Request.build("http://localhost", httpClient);
        // mock the PUT call, so we can even run the post call
        doReturn(builder).when(httpClient).put(anyString());
        doReturn(new HttpSender.Response(200, "")).when(httpClient).send(any(HttpSender.Request.class));

        DynatraceExporterV1 exporter = getDynatraceExporterV1(httpClient, invalidUrl, apiToken);

        meterRegistry.gauge("my.gauge", GAUGE_VALUE);
        Gauge gauge = meterRegistry.find("my.gauge").gauge();

        exporter.export(Collections.singletonList(gauge));

        assertThat(LOGGER.getLogEvents())
                // map to only keep the message strings
                .extracting(LogEvent::getMessage).containsExactly(
                        // the custom metric was created, meaning the PUT call succeeded
                        "created custom:my.gauge as custom metric in Dynatrace",
                        // the POST call throws an exception and the token is redacted
                        String.format(
                                "failed to build request: Illegal character in fragment at index 17: %s/api/v1/entity/infrastructure/custom/?api-token=<redacted>",
                                invalidUrl));
    }

    @Test
    void trySendHttpRequestSuccess() throws Throwable {
        HttpSender httpClient = mock(HttpSender.class);
        DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient));
        HttpSender.Request.Builder reqBuilder = mock(HttpSender.Request.Builder.class);

        // simulate a success response
        when(reqBuilder.send()).thenReturn(new HttpSender.Response(200, ""));

        // test that everything works and no error is logged
        exporter.trySendHttpRequest(reqBuilder);
        verify(reqBuilder).send();
        assertThat(LOGGER.getLogEvents()).isEmpty();
    }

    @Test
    void trySendHttpRequestErrorCode() throws Throwable {
        HttpSender httpClient = mock(HttpSender.class);
        DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> createExporter(httpClient));
        HttpSender.Request.Builder reqBuilder = mock(HttpSender.Request.Builder.class);

        // simulate a failure response, errors are handled elsewhere
        when(reqBuilder.send()).thenReturn(new HttpSender.Response(400, ""));

        // test that everything works and no error is logged
        exporter.trySendHttpRequest(reqBuilder);
        verify(reqBuilder).send();
        assertThat(LOGGER.getLogEvents()).isEmpty();
    }

    @Test
    void trySendHttpRequestThrowsAndRedacts() throws Throwable {
        HttpSender httpClient = mock(HttpSender.class);
        String apiToken = "this.is.a.fake.apiToken";
        DynatraceExporterV1 exporter = getDynatraceExporterV1(httpClient, "http://localhost", apiToken);

        HttpSender.Request.Builder reqBuilder = mock(HttpSender.Request.Builder.class);

        // Simulate that the request builder throws an exception.
        // Should not happen if the endpoint is invalid, the URI is validated elsewhere.
        String exceptionMessageTemplate = "Exception with the token: %s";
        when(reqBuilder.send()).thenThrow(new Throwable(String.format(exceptionMessageTemplate, apiToken)));

        exporter.trySendHttpRequest(reqBuilder);
        verify(reqBuilder).send();
        // assert that an error is logged
        assertThat(LOGGER.getLogEvents()).hasSize(1).extracting(x -> x.getMessage()).containsExactlyInAnyOrder(
                "failed to send metrics to Dynatrace: " + String.format(exceptionMessageTemplate, "<redacted>"));
    }

    private DynatraceExporterV1 getDynatraceExporterV1(HttpSender httpClient, String url, String apiToken) {
        DynatraceExporterV1 exporter = FACTORY.injectLogger(() -> new DynatraceExporterV1(new DynatraceConfig() {
            @Override
            public String get(String key) {
                return null;
            }

            @Override
            public String apiToken() {
                return apiToken;
            }

            @Override
            public String uri() {
                return url;
            }
        }, clock, httpClient));
        return exporter;
    }

    private DynatraceExporterV1 createExporter(HttpSender httpClient) {
        return new DynatraceExporterV1(config, clock, httpClient);
    }

    private DynatraceTimeSeries createTimeSeriesWithDimensions(int numberOfDimensions) {
        return createTimeSeriesWithDimensions(numberOfDimensions, "some.metric");
    }

    private DynatraceTimeSeries createTimeSeriesWithDimensions(int numberOfDimensions, String metricId) {
        return new DynatraceTimeSeries(metricId, System.currentTimeMillis(), 1.23,
                createDimensionsMap(numberOfDimensions));
    }

    private Map<String, String> createDimensionsMap(int numberOfDimensions) {
        Map<String, String> map = new HashMap<>();
        IntStream.range(0, numberOfDimensions).forEach(i -> map.put("key" + i, "value" + i));
        return map;
    }

    private DynatraceConfig createDynatraceConfig() {
        return new DynatraceConfig() {
            @Override
            public String get(String key) {
                return null;
            }

            @Override
            public String uri() {
                return "http://localhost";
            }

            @Override
            public String deviceId() {
                return "deviceId";
            }

            @Override
            public String apiToken() {
                return "apiToken";
            }

            @Override
            public DynatraceApiVersion apiVersion() {
                return DynatraceApiVersion.V1;
            }
        };
    }

    private boolean isValidJson(String json) {
        try {
            mapper.readTree(json);
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }

}


text:
require 'jinx/helpers/validation'

module CaTissue
  class ContainerPosition
    add_mandatory_attributes(:parent_container)

    add_attribute_aliases(:parent => :parent_container, :from => :parent_container, :holder => :parent_container,
      :occupant => :occupied_container, :to => :occupied_container)

    # Each ContainerPosition has a container and there is only one position per container.
    set_secondary_key_attributes(:occupied_container)

    set_attribute_inverse(:parent_container, :occupied_positions)

    set_attribute_inverse(:occupied_container, :located_at_position)

    qualify_attribute(:parent_container, :fetched)

    private

    # @raise [Jinx::ValidationError] if the parent is the same as the occupant
    def validate_local
      super
      if parent == occupant or (parent.identifier and parent.identifier == occupant.identifier) then
         raise Jinx::ValidationError.new("#{self} has a circular containment reference to subcontainer #{occupant}")
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project>
  <add-on id="spring.persistence"/>
  <add-on id="spring.web"/>
  <add-on id="spring.test"/>
</project>


text:
package org.jcrom.converter;

import org.jcrom.annotations.JcrProperty;

/**
 *

 * Interface to implement to customize the conversion from an entity attribute value to JCR property representation and conversely.

 * The class that implements this interface can then be added at the declaration of the annotation {@link JcrProperty}.

 * The parameter Y representing the JCR property type must be supported by Jcrom (see org.jcrom.Validator).
 *

 *
 *
Example:

 *

 * public class ColorConverter implements Converter<Color, String> {
 *
 *   @Override
 *   public String convertToJcrProperty(Color color) { ... }
 *
 *   @Override
 *   public Color convertToEntityAttribute(String colorString) { ... }
 *
 * }
 *

 *

 * public class EntityWithConverter extends AbstractJcrEntity {
 *
 *   @JcrProperty(converter = ColorConverter.class)
 *   private Color color;
 *
 *   ...
 *
 * }
 *

 *
 * @param X the type of the entity attribute
 * @param Y the type of the JCR property
 *
 * @author Nicolas Dos Santos
 */
public interface Converter<X, Y> {

    /**
     * Converts the value stored in the entity attribute into the data representation to be stored in the JCR property.
     *
     * @param attribute the entity attribute value to be converted
     * @return the converted data to be stored in the JCR property
     */
    Y convertToJcrProperty(X attribute);

    /**
     * Converts the data stored in the JCR property into the value to be stored in the entity attribute.
     *
     * @param jcrData the data from the JCR property to be converted
     * @return the converted value to be stored in the entity attribute
     */
    X convertToEntityAttribute(Y jcrData);

}


text:
// [START setup]
// [START imports]
const { GoogleAuth } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
// [END imports]

/**
 * Demo class for creating and managing Event tickets in Google Wallet.
 */
class DemoEventTicket {
  constructor() {
    /**
     * Path to service account key file from Google Cloud Console. Environment
     * variable: GOOGLE_APPLICATION_CREDENTIALS.
     */
    this.keyFilePath = process.env.GOOGLE_APPLICATION_CREDENTIALS || '/path/to/key.json';

    /**
     * Base URL for Google Wallet API requests.
     */
    this.baseUrl = 'https://walletobjects.googleapis.com/walletobjects/v1'
  }
  // [END setup]

  // [START auth]
  /**
   * Create authenticated HTTP client using a service account file.
   */
  auth() {
    this.credentials = require(this.keyFilePath);

    this.httpClient = new GoogleAuth({
      credentials: this.credentials,
      scopes: 'https://www.googleapis.com/auth/wallet_object.issuer',
    });
  }
  // [END auth]

  // [START class]
  /**
   * Create a class via the API. This can also be done in the Google Pay and
   * Wallet console.
   *
   * @param {string} issuerId The issuer ID being used for this request.
   * @param {string} classSuffix Developer-defined unique ID for this pass class.
   *
   * @returns {string} The pass class ID: `${issuerId}.${classSuffix}`
   */
  async createEventTicketClass(issuerId, classSuffix) {
    const eventTicketClassUrl = `${this.baseUrl}/eventTicketClass`;

    // See below for more information on required properties
    // https://developers.google.com/wallet/tickets/events/rest/v1/eventticketclass
    let eventTicketClass = {
      'id': `${issuerId}.${classSuffix}`,
      'issuerName': 'Issuer name',
      'reviewStatus': 'UNDER_REVIEW',
      'eventName': {
        'defaultValue': {
          'language': 'en-US',
          'value': 'Event name',
        },
      },
    };

    let response = await this.httpClient.request({
      url: eventTicketClassUrl,
      method: 'POST',
      data: eventTicketClass,
    });

    console.log('Class insert response');
    console.log(response);

    return response.data.id;
  }
  // [END class]

  // [START object]
  /**
   * Create an object via the API.
   *
   * @param {string} issuerId The issuer ID being used for this request.
   * @param {string} classSuffix Developer-defined unique ID for this pass class.
   * @param {string} userId Developer-defined user ID for this object.
   *
   * @returns {string} The pass object ID: `${issuerId}.${userId}`
   */
  async createEventTicketObject(issuerId, classSuffix, userId) {
    const eventTicketObjectUrl = `${this.baseUrl}/eventTicketObject`;

    // Generate the object ID
    // Should only include alphanumeric characters, '.', '_', or '-'
    let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}`;

    // See below for more information on required properties
    // https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
    let eventTicketObject = {
      'id': `${objectId}`,
      'classId': `${issuerId}.${classSuffix}`,
      'state': 'ACTIVE',
      'heroImage': {
        'sourceUri': {
          'uri': 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg',
        },
        'contentDescription': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'Hero image description',
          },
        },
      },
      'textModulesData': [
        {
          'header': 'Text module header',
          'body': 'Text module body',
          'id': 'TEXT_MODULE_ID',
        },
      ],
      'linksModuleData': {
        'uris': [
          {
            'uri': 'http://maps.google.com/',
            'description': 'Link module URI description',
            'id': 'LINK_MODULE_URI_ID',
          },
          {
            'uri': 'tel:6505555555',
            'description': 'Link module tel description',
            'id': 'LINK_MODULE_TEL_ID',
          },
        ],
      },
      'imageModulesData': [
        {
          'mainImage': {
            'sourceUri': {
              'uri': 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg',
            },
            'contentDescription': {
              'defaultValue': {
                'language': 'en-US',
                'value': 'Image module description',
              },
            },
          },
          'id': 'IMAGE_MODULE_ID',
        },
      ],
      'barcode': {
        'type': 'QR_CODE',
        'value': 'QR code',
      },
      'locations': [
        {
          'latitude': 37.424015499999996,
          'longitude': -122.09259560000001,
        },
      ],
      'seatInfo': {
        'seat': {
          'defaultValue': {
            'language': 'en-US',
            'value': '42',
          },
        },
        'row': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'G3',
          },
        },
        'section': {
          'defaultValue': {
            'language': 'en-US',
            'value': '5',
          },
        },
        'gate': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'A',
          },
        },
      },
      'ticketHolderName': 'Ticket holder name',
      'ticketNumber': 'Ticket number',
    };

    let response;
    try {
      response = await this.httpClient.request({
        url: `${eventTicketObjectUrl}/${objectId}`,
        method: 'GET',
      });

      console.log('Object get response');
      console.log(response);

      return response.data.id;
    } catch (err) {
      if (err.response && err.response.status === 404) {
        // Object does not yet exist
        // Send POST request to create it
        response = await this.httpClient.request({
          url: eventTicketObjectUrl,
          method: 'POST',
          data: eventTicketObject,
        });

        console.log('Object insert response');
        console.log(response);

        return response.data.id;
      } else {
        // Something else went wrong
        console.log(err);
      }
    }
  }
  // [END object]

  // [START jwt]
  /**
   * Generate a signed JWT that creates a new pass class and object.
   *
   * When the user opens the "Add to Google Wallet" URL and saves the pass to
   * their wallet, the pass class and object defined in the JWT are
   * created. This allows you to create multiple pass classes and objects in
   * one API call when the user saves the pass to their wallet.
   *
   * @param {string} issuerId The issuer ID being used for this request.
   * @param {string} classSuffix Developer-defined unique ID for this pass class.
   * @param {string} userId Developer-defined user ID for this object.
   *
   * @returns {string} An "Add to Google Wallet" link.
   */
  createJwtSaveUrl(issuerId, classSuffix, userId) {
    // Generate the object ID
    // Should only include alphanumeric characters, '.', '_', or '-'
    let objectId = `${issuerId}.${userId.replace(/[^\w.-]/g, '_')}`;

    // See below for more information on required properties
    // https://developers.google.com/wallet/tickets/events/rest/v1/eventticketclass
    let eventTicketClass = {
      'id': `${issuerId}.${classSuffix}`,
      'issuerName': 'Issuer name',
      'reviewStatus': 'UNDER_REVIEW',
      'eventName': {
        'defaultValue': {
          'language': 'en-US',
          'value': 'Event name',
        },
      },
    };

    // See below for more information on required properties
    // https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
    let eventTicketObject = {
      'id': `${objectId}`,
      'classId': `${issuerId}.${classSuffix}`,
      'state': 'ACTIVE',
      'heroImage': {
        'sourceUri': {
          'uri': 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg',
        },
        'contentDescription': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'Hero image description',
          },
        },
      },
      'textModulesData': [
        {
          'header': 'Text module header',
          'body': 'Text module body',
          'id': 'TEXT_MODULE_ID',
        },
      ],
      'linksModuleData': {
        'uris': [
          {
            'uri': 'http://maps.google.com/',
            'description': 'Link module URI description',
            'id': 'LINK_MODULE_URI_ID',
          },
          {
            'uri': 'tel:6505555555',
            'description': 'Link module tel description',
            'id': 'LINK_MODULE_TEL_ID',
          },
        ],
      },
      'imageModulesData': [
        {
          'mainImage': {
            'sourceUri': {
              'uri': 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg',
            },
            'contentDescription': {
              'defaultValue': {
                'language': 'en-US',
                'value': 'Image module description',
              },
            },
          },
          'id': 'IMAGE_MODULE_ID',
        },
      ],
      'barcode': {
        'type': 'QR_CODE',
        'value': 'QR code',
      },
      'locations': [
        {
          'latitude': 37.424015499999996,
          'longitude': -122.09259560000001,
        },
      ],
      'seatInfo': {
        'seat': {
          'defaultValue': {
            'language': 'en-US',
            'value': '42',
          },
        },
        'row': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'G3',
          },
        },
        'section': {
          'defaultValue': {
            'language': 'en-US',
            'value': '5',
          },
        },
        'gate': {
          'defaultValue': {
            'language': 'en-US',
            'value': 'A',
          },
        },
      },
      'ticketHolderName': 'Ticket holder name',
      'ticketNumber': 'Ticket number',
    };

    // Create the JWT claims
    let claims = {
      iss: this.credentials.client_email,
      aud: 'google',
      origins: ['www.example.com'],
      typ: 'savetowallet',
      payload: {
        // The listed classes and objects will be created
        eventTicketClasses: [eventTicketClass,],
        eventTicketObjects: [eventTicketObject,],
      },
    };

    // The service account credentials are used to sign the JWT
    let token = jwt.sign(claims, this.credentials.private_key, { algorithm: 'RS256' });

    console.log('Add to Google Wallet link');
    console.log(`https://pay.google.com/gp/v/save/${token}`);

    return `https://pay.google.com/gp/v/save/${token}`;
  }
  // [END jwt]

  // [START createIssuer]
  /**
   * Create a new Google Wallet issuer account.
   *
   * @param {string} issuerName The issuer's name.
   * @param {string} issuerEmail The issuer's email address.
   */
  async createIssuerAccount(issuerName, issuerEmail) {
    // Issuer API endpoint
    const issuerUrl = `${this.baseUrl}/issuer`;

    // New issuer information
    let issuer = {
      name: issuerName,
      contactInfo: {
        email: issuerEmail,
      },
    };

    let response = await this.httpClient.request({
      url: issuerUrl,
      method: 'POST',
      data: issuer
    });

    console.log('Issuer insert response');
    console.log(response);
  }
  // [END createIssuer]

  // [START updatePermissions]
  /**
   * Update permissions for an existing Google Wallet issuer account.
   * **Warning:** This operation overwrites all existing permissions!
   *
   * Example permissions list argument below. Copy the dict entry as
   * needed for each email address that will need access. Supported
   * values for role are: 'READER', 'WRITER', and 'OWNER'
   *
   * let permissions = [
   *  {
   *    'emailAddress': 'email-address',
   *    'role': 'OWNER',
   *  },
   * ];
   *
   * @param {string} issuerId The issuer ID being used for this request.
   * @param {Array} permissions The list of email addresses and roles to assign.
   */
  async updateIssuerPermissions(issuerId, permissions) {
    // Permissions API endpoint
    const permissionsUrl = `${this.baseUrl}/permissions/${issuerId}`;

    let response = await this.httpClient.request({
      url: permissionsUrl,
      method: 'PUT',
      data: {
        issuerId: issuerId,
        permissions: permissions,
      }
    });

    console.log('Permissions update response');
    console.log(response);
  }
  // [END updatePermissions]

  // [START batch]
  /**
   * Batch create Google Wallet objects from an existing class.
   *
   * @param {string} issuerId The issuer ID being used for this request.
   * @param {string} classSuffix Developer-defined unique ID for this pass class.
   */
  async batchCreateEventTicketObjects(issuerId, classSuffix) {
    // See below for more information
    // https://cloud.google.com/compute/docs/api/how-tos/batch#example
    let data = '';
    let eventTicketObject;
    let userId;
    let objectId;

    // Example: Generate three new pass objects
    for (let i = 0; i < 3; i++) {
      // Generate a random user ID
      userId = uuidv4().replace('[^\w.-]', '_');

      // Generate an object ID with the user ID
      // Should only include alphanumeric characters, '.', '_', or '-'
      objectId = `${issuerId}.${userId}`;

      // See below for more information on required properties
      // https://developers.google.com/wallet/tickets/events/rest/v1/eventticketobject
      eventTicketObject = {
        'id': `${objectId}`,
        'classId': `${issuerId}.${classSuffix}`,
        'state': 'ACTIVE',
        'heroImage': {
          'sourceUri': {
            'uri': 'https://farm4.staticflickr.com/3723/11177041115_6e6a3b6f49_o.jpg',
          },
          'contentDescription': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'Hero image description',
            },
          },
        },
        'textModulesData': [
          {
            'header': 'Text module header',
            'body': 'Text module body',
            'id': 'TEXT_MODULE_ID',
          },
        ],
        'linksModuleData': {
          'uris': [
            {
              'uri': 'http://maps.google.com/',
              'description': 'Link module URI description',
              'id': 'LINK_MODULE_URI_ID',
            },
            {
              'uri': 'tel:6505555555',
              'description': 'Link module tel description',
              'id': 'LINK_MODULE_TEL_ID',
            },
          ],
        },
        'imageModulesData': [
          {
            'mainImage': {
              'sourceUri': {
                'uri': 'http://farm4.staticflickr.com/3738/12440799783_3dc3c20606_b.jpg',
              },
              'contentDescription': {
                'defaultValue': {
                  'language': 'en-US',
                  'value': 'Image module description',
                },
              },
            },
            'id': 'IMAGE_MODULE_ID',
          },
        ],
        'barcode': {
          'type': 'QR_CODE',
          'value': 'QR code',
        },
        'locations': [
          {
            'latitude': 37.424015499999996,
            'longitude': -122.09259560000001,
          },
        ],
        'seatInfo': {
          'seat': {
            'defaultValue': {
              'language': 'en-US',
              'value': '42',
            },
          },
          'row': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'G3',
            },
          },
          'section': {
            'defaultValue': {
              'language': 'en-US',
              'value': '5',
            },
          },
          'gate': {
            'defaultValue': {
              'language': 'en-US',
              'value': 'A',
            },
          },
        },
        'ticketHolderName': 'Ticket holder name',
        'ticketNumber': 'Ticket number',
      };

      data += '--batch_createobjectbatch\n';
      data += 'Content-Type: application/json\n\n';
      data += 'POST /walletobjects/v1/eventTicketObject\n\n';

      data += JSON.stringify(eventTicketObject) + '\n\n';
    }
    data += '--batch_createobjectbatch--';

    // Invoke the batch API calls
    let response = await this.httpClient.request({
      url: `${this.baseUrl}/batch`,
      method: 'POST',
      data: data,
      headers: {
        // `boundary` is the delimiter between API calls in the batch request
        'Content-Type': 'multipart/mixed; boundary=batch_createobjectbatch'
      }
    });

    console.log('Batch insert response');
    console.log(response);
  }
  // [END batch]
}

module.exports = { DemoEventTicket };


text:
<?php

/* input.html.twig */
class __TwigTemplate_f0a30d419b7456c97f777505664e9ebfba5d048a5c81fa2a7187c49171e82708 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'input' => array($this, 'block_input'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $tags = array("spaceless" => 22, "if" => 23, "block" => 31);
        $filters = array();
        $functions = array();

        try {
            $this->env->getExtension('sandbox')->checkSecurity(
                array('spaceless', 'if', 'block'),
                array(),
                array()
            );
        } catch (Twig_Sandbox_SecurityError $e) {
            $e->setTemplateFile($this->getTemplateName());

            if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
                $e->setTemplateLine($tags[$e->getTagName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
                $e->setTemplateLine($filters[$e->getFilterName()]);
            } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
                $e->setTemplateLine($functions[$e->getFunctionName()]);
            }

            throw $e;
        }

        // line 22
        ob_start();
        // line 23
        echo "  ";
        if ((isset($context["input_group"]) ? $context["input_group"] : null)) {
            // line 24
            echo "

  ";
        }
        // line 26
        echo "
  ";
        // line 27
        if ((isset($context["prefix"]) ? $context["prefix"] : null)) {
            // line 28
            echo "    ";
            echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["prefix"]) ? $context["prefix"] : null), "html", null, true));
            echo "
  ";
        }
        // line 30
        echo "
  ";
        // line 31
        $this->displayBlock('input', $context, $blocks);
        // line 34
        echo "
  ";
        // line 35
        if ((isset($context["suffix"]) ? $context["suffix"] : null)) {
            // line 36
            echo "    ";
            echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["suffix"]) ? $context["suffix"] : null), "html", null, true));
            echo "
  ";
        }
        // line 38
        echo "
  ";
        // line 39
        if ((isset($context["input_group"]) ? $context["input_group"] : null)) {
            // line 40
            echo "

  ";
        }
        // line 42
        echo "
  ";
        // line 43
        echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true));
        echo "
";
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }

    // line 31
    public function block_input($context, array $blocks = array())
    {
        // line 32
        echo "    <input";
        echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true));
        echo " />
  ";
    }

    public function getTemplateName()
    {
        return "input.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  102 => 32,  99 => 31,  92 => 43,  89 => 42,  85 => 40,  83 => 39,  80 => 38,  74 => 36,  72 => 35,  69 => 34,  67 => 31,  64 => 30,  58 => 28,  56 => 27,  53 => 26,  49 => 24,  46 => 23,  44 => 22,);
    }
}
/* {#*/
/* /***/
/*  * @file*/
/*  * Default theme implementation for an 'input' #type form element.*/
/*  **/
/*  * Available variables:*/
/*  * - attributes: A list of HTML attributes for the input element.*/
/*  * - children: Optional additional rendered elements.*/
/*  * - icon: An icon.*/
/*  * - input_group: Flag to display as an input group.*/
/*  * - icon_position: Where an icon should be displayed.*/
/*  * - prefix: Markup to display before the input element.*/
/*  * - suffix: Markup to display after the input element.*/
/*  * - type: The type of input.*/
/*  **/
/*  * @see \Drupal\bootstrap\Plugin\Preprocess\Input*/
/*  * @see template_preprocess_input()*/
/*  **/
/*  * @ingroup templates*/
/*  *//* */
/* #}*/
/* {% spaceless %}*/
/*   {% if input_group %}*/
/*
*/
/*   {% endif %}*/
/* */
/*   {% if prefix %}*/
/*     {{ prefix }}*/
/*   {% endif %}*/
/* */
/*   {% block input %}*/
/*     <input{{ attributes }} />*/
/*   {% endblock %}*/
/* */
/*   {% if suffix %}*/
/*     {{ suffix }}*/
/*   {% endif %}*/
/* */
/*   {% if input_group %}*/
/*
*/
/*   {% endif %}*/
/* */
/*   {{ children }}*/
/* {% endspaceless %}*/
/* */


text:
package com.anooc.android.md.model.entity;

import com.google.gson.annotations.SerializedName;

import com.anooc.android.md.model.api.ApiDefine;
import com.anooc.android.md.util.FormatUtils;
import org.joda.time.DateTime;

import java.util.List;

public class Reply {

    public enum UpAction {
        up,
        down
    }

    private String id;

    private Author author;

    private String content;

    @SerializedName("ups")
    private List<String> upList;

    @SerializedName("reply_id")
    private String replyId;

    @SerializedName("create_at")
    private DateTime createAt;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
        contentHtml = null; // 清除已经处理的Html渲染缓存
    }

    public List<String> getUpList() {
        return upList;
    }

    public void setUpList(List<String> upList) {
        this.upList = upList;
    }

    public String getReplyId() {
        return replyId;
    }

    public void setReplyId(String replyId) {
        this.replyId = replyId;
    }

    public DateTime getCreateAt() {
        return createAt;
    }

    public void setCreateAt(DateTime createAt) {
        this.createAt = createAt;
    }

    /**
     * Html渲染缓存
     */

    @SerializedName("content_html")
    private String contentHtml;

    public String getContentHtml() {
        if (contentHtml == null) {
            if (ApiDefine.MD_RENDER) {
                contentHtml = FormatUtils.handleHtml(content);
            } else {
                contentHtml = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content));
            }
        }
        return contentHtml;
    }

    public void setContentFromLocal(String content) {
        if (ApiDefine.MD_RENDER) {
            this.content = FormatUtils.renderMarkdown(content);
        } else {
            this.content = content;
        }
        contentHtml = null; // 清除已经处理的Html渲染缓存
    }

}


text:
<?php

namespace Acme\EdelaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ActionType
 *
 * @ORM\Table(name="ed_action_types")
 * @ORM\Entity
 */
class ActionType
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="tkey", type="string", length=255)
     */
    private $tkey;

    /**
     * @ORM\OneToMany(targetEntity="Action", mappedBy="actionType")
     */
    private $actions;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return ActionType
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set tkey
     *
     * @param string $tkey
     * @return ActionType
     */
    public function setTkey($tkey)
    {
        $this->tkey = $tkey;

        return $this;
    }

    /**
     * Get tkey
     *
     * @return string
     */
    public function getTkey()
    {
        return $this->tkey;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->actions = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add actions
     *
     * @param \Acme\EdelaBundle\Entity\Action $actions
     * @return ActionType
     */
    public function addAction(\Acme\EdelaBundle\Entity\Action $actions)
    {
        $this->actions[] = $actions;

        return $this;
    }

    /**
     * Remove actions
     *
     * @param \Acme\EdelaBundle\Entity\Action $actions
     */
    public function removeAction(\Acme\EdelaBundle\Entity\Action $actions)
    {
        $this->actions->removeElement($actions);
    }

    /**
     * Get actions
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getActions()
    {
        return $this->actions;
    }

    public function __toString()
    {
        return $this->title;
    }
}


text:
using namespace llvm;

namespace llvm {

class Mips16HardFloat : public ModulePass {

public:
  static char ID;

  Mips16HardFloat(MipsTargetMachine &TM_) : ModulePass(ID),
    TM(TM_), Subtarget(TM.getSubtarget<MipsSubtarget>()) {
  }

  const char *getPassName() const override {
    return "MIPS16 Hard Float Pass";
  }

  bool runOnModule(Module &M) override;

protected:
  /// Keep a pointer to the MipsSubtarget around so that we can make the right
  /// decision when generating code for different targets.
  const TargetMachine &TM;
  const MipsSubtarget &Subtarget;

};

ModulePass *createMips16HardFloat(MipsTargetMachine &TM);

}
#endif


text:
package com.texttalk.core;

import com.texttalk.common.JedisFactory;
import com.texttalk.common.model.Message;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.io.ByteArrayOutputStream;
import java.util.Map;

/**
 * Created by andrew on 08/03/15.
 * Use redis cache for storing and publishing  data
 */
public class Cache {

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

    private Jedis jedis;

    public Cache(Map config) {

        JedisFactory.setConnectionSettings(
                config.get("redis.host").toString(),
                Integer.parseInt(config.get("redis.port").toString()),
                config.get("redis.password").toString()
        );

        jedis = JedisFactory.getRes();

    }

    public void storeSpeech(String key, String base64VoiceTrack, String txt) {

        jedis.set(
                key,
                base64VoiceTrack
        );

        jedis.set(
                key + ":txt",
                txt
        );

        logger.info("------> storing speech: " + key);
    }

    public void linkSpeech(String key, String value) {
        jedis.sadd(key, value);

        logger.info("------> linking speech: " + key);
    }

    public void notify(String channel, Message msg) {

        JSONObject json = new JSONObject();

        json.put("action", "synthNotify");
        json.put("id", msg.getId());
        json.put("parentHashCode", msg.getParentHashCode());
        json.put("hashCode", msg.getHashCode());
        json.put("orderId", msg.getOrderId());
        json.put("totalChunks", msg.getTotalChunks());
        json.put("voiceTrack", msg.getVoiceTrack());

        jedis.publish(channel, json.toJSONString());

        logger.info("------> publishing speech: " + channel + " <- " + json.toJSONString());
    }
}


text:
ACCEPTED

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

#### Published in
Ann. Bot. (König & Sims) 1:234. 1804

#### Original name
Antholyza ringens L.

### Remarks
null