text:
'use strict';

import * as assert from 'assert';

import { Duplex } from 'stream';
import {
	InitializeParams, InitializeRequest, InitializeResult, createProtocolConnection, StreamMessageReader, StreamMessageWriter, Logger, ProtocolConnection,
	WorkDoneProgressBegin, WorkDoneProgressReport, WorkDoneProgressEnd
} from '../main';
import { DocumentSymbolRequest, DocumentSymbolParams } from '../../common/protocol';
import { ProgressType } from 'vscode-jsonrpc';
import { SymbolInformation, SymbolKind } from 'vscode-languageserver-types';

class NullLogger implements Logger {
	error(_message: string): void {
	}
	warn(_message: string): void {
	}
	info(_message: string): void {
	}
	log(_message: string): void {
	}
}

class TestStream extends Duplex {
	_write(chunk: string, _encoding: string, done: () => void) {
		this.emit('data', chunk);
		done();
	}

	_read(_size: number) {
	}
}

suite('Connection Tests', () => {
	test('Ensure proper param passing', async() => {
		const up = new TestStream();
		const down = new TestStream();
		const logger = new NullLogger();
		const serverConnection = createProtocolConnection(new StreamMessageReader(up), new StreamMessageWriter(down), logger);
		const clientConnection = createProtocolConnection(new StreamMessageReader(down), new StreamMessageWriter(up), logger);
		serverConnection.listen();
		clientConnection.listen();

		let paramsCorrect: boolean = false;
		serverConnection.onRequest(InitializeRequest.type, (params) => {
			paramsCorrect = !Array.isArray(params);
			let result: InitializeResult = {
				capabilities: {
				}
			};
			return result;
		});

		const init: InitializeParams = {
			rootUri: 'file:///home/dirkb',
			processId: 1,
			capabilities: {},
			workspaceFolders: null,
		};
		await clientConnection.sendRequest(InitializeRequest.type, init);
		assert.ok(paramsCorrect, 'Parameters are transferred correctly');
	});
});

suite('Partial result tests', () => {

	let serverConnection: ProtocolConnection;
	let clientConnection: ProtocolConnection;
	let progressType: ProgressType<any> = new ProgressType();

	setup(() => {
		const up = new TestStream();
		const down = new TestStream();
		const logger = new NullLogger();
		serverConnection = createProtocolConnection(new StreamMessageReader(up), new StreamMessageWriter(down), logger);
		clientConnection = createProtocolConnection(new StreamMessageReader(down), new StreamMessageWriter(up), logger);
		serverConnection.listen();
		clientConnection.listen();
	});

	test('Token provided', async () => {
		serverConnection.onRequest(DocumentSymbolRequest.type, (params) => {
			assert.ok(params.partialResultToken === '3b1db4c9-e011-489e-a9d1-0653e64707c2');
			return [];
		});

		const params: DocumentSymbolParams = {
			textDocument: { uri: 'file:///abc.txt' },
			partialResultToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2'
		};
		await clientConnection.sendRequest(DocumentSymbolRequest.type, params);
	});

	test('Result reported', async () => {
		let result: SymbolInformation = {
			name: 'abc',
			kind: SymbolKind.Class,
			location: {
				uri: 'file:///abc.txt',
				range: { start: { line: 0, character: 1 }, end: { line: 2, character: 3} }
			}
		};
		serverConnection.onRequest(DocumentSymbolRequest.type, async (params) => {
			assert.ok(params.partialResultToken === '3b1db4c9-e011-489e-a9d1-0653e64707c2');
			await serverConnection.sendProgress(progressType, params.partialResultToken!, [ result ]);
			return [];
		});

		const params: DocumentSymbolParams = {
			textDocument: { uri: 'file:///abc.txt' },
			partialResultToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2'
		};
		let progressOK: boolean = false;
		clientConnection.onProgress(progressType, '3b1db4c9-e011-489e-a9d1-0653e64707c2', (values) => {
			progressOK = (values !== undefined && values.length === 1);
		});
		await clientConnection.sendRequest(DocumentSymbolRequest.type, params);
		assert.ok(progressOK);
	});
});

suite('Work done tests', () => {

	let serverConnection: ProtocolConnection;
	let clientConnection: ProtocolConnection;
	const progressType: ProgressType<WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd> = new ProgressType();

	setup(() => {
		const up = new TestStream();
		const down = new TestStream();
		const logger = new NullLogger();
		serverConnection = createProtocolConnection(new StreamMessageReader(up), new StreamMessageWriter(down), logger);
		clientConnection = createProtocolConnection(new StreamMessageReader(down), new StreamMessageWriter(up), logger);
		serverConnection.listen();
		clientConnection.listen();
	});

	test('Token provided', async () => {
		serverConnection.onRequest(DocumentSymbolRequest.type, (params) => {
			assert.ok(params.workDoneToken === '3b1db4c9-e011-489e-a9d1-0653e64707c2');
			return [];
		});

		const params: DocumentSymbolParams = {
			textDocument: { uri: 'file:///abc.txt' },
			workDoneToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2'
		};
		await clientConnection.sendRequest(DocumentSymbolRequest.type, params);
	});

	test('Result reported', async () => {
		serverConnection.onRequest(DocumentSymbolRequest.type, async (params) => {
			assert.ok(params.workDoneToken === '3b1db4c9-e011-489e-a9d1-0653e64707c2');
			await serverConnection.sendProgress(progressType, params.workDoneToken!, {
				kind: 'begin',
				title: 'progress'
			});
			await serverConnection.sendProgress(progressType, params.workDoneToken!, {
				kind: 'report',
				message: 'message'
			});
			await serverConnection.sendProgress(progressType, params.workDoneToken!, {
				kind: 'end',
				message: 'message'
			});
			return [];
		});

		const params: DocumentSymbolParams = {
			textDocument: { uri: 'file:///abc.txt' },
			workDoneToken: '3b1db4c9-e011-489e-a9d1-0653e64707c2'
		};
		let result: string = '';
		clientConnection.onProgress(progressType, '3b1db4c9-e011-489e-a9d1-0653e64707c2', (value) => {
			result += value.kind;
		});
		await clientConnection.sendRequest(DocumentSymbolRequest.type, params);
		assert.ok(result === 'beginreportend');
	});
});


text:
package org.apache.cassandra.utils;

import java.io.DataInputStream;
import java.io.IOException;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.AbstractSerializationsTester;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus;
import org.apache.cassandra.io.util.DataOutputStreamPlus;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Murmur3Partitioner;

import java.io.File;
import java.io.FileInputStream;

public class SerializationsTest extends AbstractSerializationsTester
{
    @BeforeClass
    public static void initDD()
    {
        DatabaseDescriptor.daemonInitialization();
    }

    private static void testBloomFilterWrite(boolean offheap) throws IOException
    {
        IPartitioner partitioner = Util.testPartitioner();
        try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap))
        {
            for (int i = 0; i < 100; i++)
                bf.add(partitioner.decorateKey(partitioner.getTokenFactory().toByteArray(partitioner.getRandomToken())));
            try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter.bin"))
            {
                FilterFactory.serialize(bf, out);
            }
        }
    }

    private static void testBloomFilterWrite1000(boolean offheap) throws IOException
    {
        try (IFilter bf = FilterFactory.getFilter(1000000, 0.0001, offheap))
        {
            for (int i = 0; i < 1000; i++)
                bf.add(Util.dk(Int32Type.instance.decompose(i)));
            try (DataOutputStreamPlus out = getOutput("3.0", "utils.BloomFilter1000.bin"))
            {
                FilterFactory.serialize(bf, out);
            }
        }
    }

    @Test
    public void testBloomFilterRead1000() throws IOException
    {
        if (EXECUTE_WRITES)
            testBloomFilterWrite1000(true);

        try (DataInputStream in = getInput("3.0", "utils.BloomFilter1000.bin");
             IFilter filter = FilterFactory.deserialize(in, true))
        {
            boolean present;
            for (int i = 0 ; i < 1000 ; i++)
            {
                present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i)));
                Assert.assertTrue(present);
            }
            for (int i = 1000 ; i < 2000 ; i++)
            {
                present = filter.isPresent(Util.dk(Int32Type.instance.decompose(i)));
                Assert.assertFalse(present);
            }
        }
    }

    @Test
    public void testBloomFilterTable() throws Exception
    {
        testBloomFilterTable("test/data/bloom-filter/la/foo/la-1-big-Filter.db");
    }

    private static void testBloomFilterTable(String file) throws Exception
    {
        Murmur3Partitioner partitioner = new Murmur3Partitioner();

        try (DataInputStream in = new DataInputStream(new FileInputStream(new File(file)));
             IFilter filter = FilterFactory.deserialize(in, true))
        {
            for (int i = 1; i <= 10; i++)
            {
                DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i));
                boolean present = filter.isPresent(decoratedKey);
                Assert.assertTrue(present);
            }

            int positives = 0;
            for (int i = 11; i <= 1000010; i++)
            {
                DecoratedKey decoratedKey = partitioner.decorateKey(Int32Type.instance.decompose(i));
                boolean present = filter.isPresent(decoratedKey);
                if (present)
                    positives++;
            }
            double fpr = positives;
            fpr /= 1000000;
            Assert.assertTrue(fpr <= 0.011d);
        }
    }

    private static void testEstimatedHistogramWrite() throws IOException
    {
        EstimatedHistogram hist0 = new EstimatedHistogram();
        EstimatedHistogram hist1 = new EstimatedHistogram(5000);
        long[] offsets = new long[1000];
        long[] data = new long[offsets.length + 1];
        for (int i = 0; i < offsets.length; i++)
        {
            offsets[i] = i;
            data[i] = 10 * i;
        }
        data[offsets.length] = 100000;
        EstimatedHistogram hist2 = new EstimatedHistogram(offsets, data);

        try (DataOutputStreamPlus out = getOutput("utils.EstimatedHistogram.bin"))
        {
            EstimatedHistogram.serializer.serialize(hist0, out);
            EstimatedHistogram.serializer.serialize(hist1, out);
            EstimatedHistogram.serializer.serialize(hist2, out);
        }
    }

    @Test
    public void testEstimatedHistogramRead() throws IOException
    {
        if (EXECUTE_WRITES)
            testEstimatedHistogramWrite();

        try (DataInputStreamPlus in = getInput("utils.EstimatedHistogram.bin"))
        {
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
            Assert.assertNotNull(EstimatedHistogram.serializer.deserialize(in));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals
from .responses import DynamoHandler

url_bases = [
    "https?://dynamodb.(.+).amazonaws.com"
]

url_paths = {
    "{0}/": DynamoHandler.dispatch,
}


text:
#include <inttypes.h>

typedef struct {
    int int_value;
    uint8_t int_zero_counter;
} cmac_stub_def;

extern cmac_stub_def cmac_stub;


text:
<BioSample
	xsi:schemaLocation="http://www.ebi.ac.uk/biosamples/SampleGroupExport/1.0 http://www.ebi.ac.uk/biosamples/assets/xsd/v1.0/BioSDSchema.xsd"
	id="SAMD00046940" submissionUpdateDate="2017-04-07T21:57:22+00:00"
	submissionReleaseDate="2017-04-06T23:00:00+00:00"
	xmlns="http://www.ebi.ac.uk/biosamples/SampleGroupExport/1.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<Property class="Sample Name" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>MiSeq, Diospyros lotus L8 male flower 23 Apr MeGI promoter
			</Value>
		</QualifiedValue>
	</Property>
	<Property class="Organism" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>Diospyros lotus</Value>
			<TermSourceREF>
				<Name />
				<TermSourceID>55363</TermSourceID>
			</TermSourceREF>
		</QualifiedValue>
	</Property>
	<Property class="Sex" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>male</Value>
			<TermSourceREF>
				<Name />
				<TermSourceID>http://purl.obolibrary.org/obo/PATO_0000384
				</TermSourceID>
			</TermSourceREF>
		</QualifiedValue>
	</Property>
	<Property class="colection date" characteristic="false"
		comment="false" type="STRING">
		<QualifiedValue>
			<Value>2014-04-23</Value>
		</QualifiedValue>
	</Property>
	<Property class="cultivar" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>KK-L8</Value>
		</QualifiedValue>
	</Property>
	<Property class="model" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>Generic</Value>
		</QualifiedValue>
	</Property>
	<Property class="organism part" characteristic="false"
		comment="false" type="STRING">
		<QualifiedValue>
			<Value>whole flower</Value>
		</QualifiedValue>
	</Property>
	<Property class="package" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>Generic.1.0</Value>
		</QualifiedValue>
	</Property>
	<Property class="synonym" characteristic="false" comment="false"
		type="STRING">
		<QualifiedValue>
			<Value>TA_Meth-2</Value>
		</QualifiedValue>
	</Property>
	<Database>
		<Name>ENA</Name>
		<URI>http://www.ebi.ac.uk/ena/data/view/SAMD00046940</URI>
		<ID>SAMD00046940</ID>
	</Database>
</BioSample>


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Books on Leif Madsen.</title>
    <link>http://blog.leifmadsen.com/tags/books/</link>
    <description>Recent content in Books on Leif Madsen.</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>Leif Madsen</copyright>
    <lastBuildDate>Fri, 25 Mar 2011 13:40:31 +0000</lastBuildDate>
    <atom:link href="/tags/books/" rel="self" type="application/rss+xml" />

    <item>
      <title>Asterisk Cookbook Is Done!</title>
      <link>http://blog.leifmadsen.com/blog/2011/03/25/asterisk-cookbook-is-done/</link>
      <pubDate>Fri, 25 Mar 2011 13:40:31 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/03/25/asterisk-cookbook-is-done/</guid>
      <description>Just a quick update that the Asterisk Cookbook is complete! We&rsquo;ll be releasing it under a Creative Commons license (just like Asterisk: The Definitive Guide) again. It&rsquo;ll be a 24 recipe e-book right now, with it growing over time and eventually becoming a full print edition once the size warrants it. Of course if you purchase now you help spur on additional incentive to continue making it larger. I&rsquo;ve been told that you also continue to receive updates automatically as the book grows and corrections are made (which sounds pretty cool!</description>
    </item>

    <item>
      <title>Asterisk Cookbook Is On! (We Think :))</title>
      <link>http://blog.leifmadsen.com/blog/2011/01/27/asterisk-cookbook-is-on-we-think-/</link>
      <pubDate>Thu, 27 Jan 2011 14:33:00 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2011/01/27/asterisk-cookbook-is-on-we-think-/</guid>
      <description>After finishing the first draft of Asterisk: The Definitive Guide (3rd Edition), I&rsquo;ve been a bit antsy with wanting to do some more writing. After about a week of a break (i.e. sleeping in past 7am for the first time in nearly a year), Russell Bryant and I have decided to team up on delivering the long awaited Asterisk Cookbook.
To start off with, we&rsquo;ll be writing a short, 80-100 page eBook that will be distributed by O&rsquo;Reilly in all the formats they support (http://oreilly.</description>
    </item>

  </channel>
</rss>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::flow::interface10::opencl_info::default_opencl_factory Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

flow

interface10

opencl_info

default_opencl_factory

Public Types |
Friends |
List of all members

tbb::flow::interface10::opencl_info::default_opencl_factory Class Reference

Inheritance diagram for tbb::flow::interface10::opencl_info::default_opencl_factory:

  <map id="tbb::flow::interface10::opencl_info::default_opencl_factory_map" name="tbb::flow::interface10::opencl_info::default_opencl_factory_map">
<area href="a00098.html" alt="tbb::flow::interface10::opencl_factory< default_device_filter >" shape="rect" coords="0,0,358,24"/>
</map>

Public Types

template<typename T >

using 	async_msg_type = opencl_async_msg< T, default_opencl_factory >

 Public Types inherited from tbb::flow::interface10::opencl_factory< default_device_filter >

using 	async_msg_type = opencl_async_msg< T, opencl_factory< default_device_filter >>

typedef opencl_device 	device_type

typedef kernel 	kernel_type

typedef opencl_range 	range_type

Friends

default_opencl_factory & 	default_factory ()

Additional Inherited Members

 Public Member Functions inherited from tbb::flow::interface10::opencl_factory< default_device_filter >

bool 	init (const opencl_device_list &device_list)

void 	send_kernel (opencl_device device, const kernel_type &kernel, const range_type &work_size, Args &...args)

void 	send_data (opencl_device device, T &t, Rest &...args)

void 	send_data (opencl_device)

void 	finalize (opencl_device device, FinalizeFn fn, Args &...args)

const opencl_device_list & 	devices ()

The documentation for this class was generated from the following file:

flow_graph_opencl_node.h

Copyright © 2005-2018 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
package com.github.automain.common.generator;

import com.github.automain.common.bean.ColumnBean;

import java.util.List;

public class BeanGenerator {

    public String generate(List<ColumnBean> columns, String tableName, String upperTableName) {
        return getImportHead(columns) + getClassHead(upperTableName) + getProperties(columns)
                + getGetterSetter(columns, upperTableName) + getTableName(tableName)
                + getColumnMap(columns) + getBeanFromResultSet(columns, upperTableName)
                + getToString(columns, upperTableName) + "\n}";
    }

    private String getImportHead(List<ColumnBean> columns) {
        String bigDecimalType = "";
        for (ColumnBean column : columns) {
            String dataType = column.getDataType();
            if ("BigDecimal".equals(dataType)) {
                bigDecimalType = "import java.math.BigDecimal;\n";
                break;
            }
        }
        return "package com.github.automain.bean;\n\n" +
                "import com.github.fastjdbc.BaseBean;\n\n" + bigDecimalType +
                "import java.sql.ResultSet;\n" +
                "import java.sql.SQLException;\n" +
                "import java.util.HashMap;\n" +
                "import java.util.Map;\n\n";
    }

    private String getClassHead(String upperTableName) {
        return "public class " + upperTableName + " implements BaseBean<" + upperTableName + "> {\n";
    }

    private String getProperties(List<ColumnBean> columns) {
        StringBuilder resultStr = new StringBuilder();
        for (ColumnBean column : columns) {
            String lowerColumnName = CommonGenerator.convertToJavaName(column.getColumnName(), false);
            resultStr.append("\n    // ").append(column.getColumnComment())
                    .append("\n    private ").append(column.getDataType()).append(" ").append(lowerColumnName).append(";");
        }
        return resultStr.toString();
    }

    private String getGetterSetter(List<ColumnBean> columns, String upperTableName) {
        StringBuilder resultStr = new StringBuilder();
        for (ColumnBean column : columns) {
            String upperColumnName = CommonGenerator.convertToJavaName(column.getColumnName(), true);
            String lowerColumnName = CommonGenerator.convertToJavaName(column.getColumnName(), false);
            resultStr.append("\n\n    public ").append(column.getDataType())
                    .append(" get").append(upperColumnName).append("() {\n        return ")
                    .append(lowerColumnName).append(";\n    }\n\n    public ")
                    .append(upperTableName).append(" set").append(upperColumnName)
                    .append("(").append(column.getDataType())
                    .append(" ").append(lowerColumnName)
                    .append(") {\n        this.").append(lowerColumnName)
                    .append(" = ").append(lowerColumnName)
                    .append(";\n        return this;\n    }");
        }
        return resultStr.toString();
    }

    private String getTableName(String tableName) {
        String outTable = tableName == null ? null : "\"" + tableName + "\"";
        return "\n\n    @Override\n" +
                "    public String tableName() {\n" +
                "        return " + outTable + ";\n" +
                "    }";
    }

    private String getColumnMap(List<ColumnBean> columns) {
        StringBuilder notNullBody = new StringBuilder();
        int size = 0;
        for (ColumnBean column : columns) {
            String upperColumnName = CommonGenerator.convertToJavaName(column.getColumnName(), true);
            notNullBody.append("\n        if (all || this.get").append(upperColumnName).append("() != null) {\n")
                    .append("            map.put(\"").append(column.getColumnName()).append("\", this.get")
                    .append(upperColumnName).append("());\n        }");
            size++;
        }
        return "\n\n    @Override\n" +
                "    public Map<String, Object> columnMap(boolean all) {\n" +
                "        Map<String, Object> map = new HashMap<String, Object>(" + Math.max(1, size) + ");" +
                notNullBody.toString() + "\n" +
                "        return map;\n" +
                "    }";
    }

    private String getBeanFromResultSet(List<ColumnBean> columns, String upperTableName) {
        StringBuilder setValueBody = new StringBuilder();
        for (ColumnBean column : columns) {
            String dataType = column.getDataType();
            if ("Integer".equals(dataType)) {
                dataType = "Int";
            }
            if ("byte[]".equals(dataType)) {
                dataType = "Object";
            }
            setValueBody.append("\n                .set")
                    .append(CommonGenerator.convertToJavaName(column.getColumnName(), true))
                    .append("(rs.get").append(dataType)
                    .append("(\"").append(column.getColumnName()).append("\"))");
        }
        return "\n\n    @Override\n" +
                "    public " + upperTableName + " beanFromResultSet(ResultSet rs) throws SQLException {\n" +
                "        return new " + upperTableName + "()" +
                setValueBody + ";\n    }";
    }

    private String getToString(List<ColumnBean> columns, String upperTableName) {
        StringBuilder setValueBody = new StringBuilder();
        List<String> numberTypeList = List.of("BigDecimal", "Double", "Float", "Integer");
        boolean isFirst = true;
        for (ColumnBean column : columns) {
            String dataType = column.getDataType();
            String columnName = CommonGenerator.convertToJavaName(column.getColumnName(), false);
            if (numberTypeList.contains(dataType)) {
                if (isFirst) {
                    setValueBody.append("                \"").append(columnName).append("=\" + ").append(columnName).append(" +\n");
                } else {
                    setValueBody.append("                \", ").append(columnName).append("=\" + ").append(columnName).append(" +\n");
                }
            } else {
                if (isFirst) {
                    setValueBody.append("                \"").append(columnName).append("='\" + ").append(columnName).append(" + '\\''").append(" +\n");
                } else {
                    setValueBody.append("                \", ").append(columnName).append("='\" + ").append(columnName).append(" + '\\''").append(" +\n");
                }
            }
            isFirst = false;
        }
        return "\n\n    @Override\n" +
                "    public String toString() {\n" +
                "        return \""+upperTableName+"{\" +\n" +
                setValueBody.toString() + "                '}';\n    }";
    }

}


text: {% include "single_narrative.html" %}


text:
type TwEntity
  data::Int
end


text:
"""
PushBank - Bank account balance change detector
Copyright 2014, ssut
Licensed under the MIT License.
"""
import logging
import os
import sys
from textwrap import dedent as trim

def create_default_config(fn):
    f = open(fn, 'w')
    print >> f, trim("""\
    #-*- coding: utf-8 -*-
    EMAIL = {
        'SMTP_SERVER': 'smtp.gmail.com',
        'SMTP_PORT': 587,
        'SMTP_USER': '',
        'SMTP_PASSWORD': '',
        'SMTP_TLS': True,
        'TARGET': '',
        'TITLE': u'{bank_name} 예금액 변동 알림',
    }

    BANK = {
        'kbstar': {
            'account': '',
            'password': '',
            'resident': '',
            'username': '',
        },
        'hana': {
            'account': '',
            'password': '',
            'resident': '',
        }
    }

    INCLUDE_BANKS = (
        'kbstar',
        'hana',
    )

    # seconds
    REFRESH_INTERVAL = 15
    """)
    f.close()

def main():
    config_file = os.path.join('.', 'config.py')
    tmp_dir = os.path.join('.', 'tmp')
    if not os.path.isfile(config_file):
        create_default_config(config_file)
        print >> sys.stdout, \
            'Created config file. Edit config.py and run pb again'
        sys.exit(0)
    if not os.path.isdir(tmp_dir):
        os.mkdir(tmp_dir, 0777)

    try:
        import config
    except:
        pritn >> sys.stderr, 'Error: Could not import a config file!'
        sys.exit(1)

    import optparse
    optp = optparse.OptionParser()
    optp.add_option('-v', '--verbose', dest='verbose', action='count',
                    help="Increase verbosity"
                    "(specify multiple times for more)")
    opts, args = optp.parse_args()

    log_level = logging.WARNING
    if opts.verbose == 1:
        log_level = logging.INFO
    elif opts.verbose >= 2:
        log_level = logging.DEBUG

    config.log_level = log_level

    from pushbank import PushBank
    return PushBank.execute(config)

if __name__ == "__main__":
    sys.exit(main())


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

<TITLE>
Uses of Interface org.apache.hadoop.mapred.OutputFormat (Hadoop 0.20.2 API)
</TITLE>

<META NAME="date" CONTENT="2010-02-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.hadoop.mapred.OutputFormat

Packages that use OutputFormat

org.apache.hadoop.contrib.index.mapred

org.apache.hadoop.examples.terasort
This package consists of 3 map/reduce applications for Hadoop to
compete in the annual terabyte sort
competition.

org.apache.hadoop.mapred
A software framework for easily writing applications which process vast
amounts of data (multi-terabyte data-sets) parallelly on large clusters
(thousands of nodes) built of commodity hardware in a reliable, fault-tolerant
manner.

org.apache.hadoop.mapred.lib
Library of generally useful mappers, reducers, and partitioners.

org.apache.hadoop.mapred.lib.db
org.apache.hadoop.mapred.lib.db Package

Uses of OutputFormat in org.apache.hadoop.contrib.index.mapred

Classes in org.apache.hadoop.contrib.index.mapred that implement OutputFormat

 class
IndexUpdateOutputFormat

          The record writer of this output format simply puts a message in an output
 path when a shard update is done.

Uses of OutputFormat in org.apache.hadoop.examples.terasort

Classes in org.apache.hadoop.examples.terasort that implement OutputFormat

 class
TeraOutputFormat

          A streamlined text output format that writes key, value, and "\r\n".

Uses of OutputFormat in org.apache.hadoop.mapred

Classes in org.apache.hadoop.mapred that implement OutputFormat

 class
FileOutputFormat<K,V>

          A base class for OutputFormat.

 class
MapFileOutputFormat

          An OutputFormat that writes MapFiles.

 class
SequenceFileAsBinaryOutputFormat

          An OutputFormat that writes keys, values to
 SequenceFiles in binary(raw) format

 class
SequenceFileOutputFormat<K,V>

          Deprecated. Use
   SequenceFileOutputFormat
   instead.

 class
TextOutputFormat<K,V>

          Deprecated. Use
   TextOutputFormat instead.

Methods in org.apache.hadoop.mapred that return OutputFormat

 OutputFormat
JobConf.getOutputFormat()

          Deprecated. Get the OutputFormat implementation for the map-reduce job,
 defaults to TextOutputFormat if not specified explicity.

Method parameters in org.apache.hadoop.mapred with type arguments of type OutputFormat

 void
JobConf.setOutputFormat(Class<? extends OutputFormat> theClass)

          Deprecated. Set the OutputFormat implementation for the map-reduce job.

Uses of OutputFormat in org.apache.hadoop.mapred.lib

Classes in org.apache.hadoop.mapred.lib that implement OutputFormat

 class
MultipleOutputFormat<K,V>

          This abstract class extends the FileOutputFormat, allowing to write the
 output data to different output files.

 class
MultipleSequenceFileOutputFormat<K,V>

          This class extends the MultipleOutputFormat, allowing to write the output data
 to different output files in sequence file output format.

 class
MultipleTextOutputFormat<K,V>

          This class extends the MultipleOutputFormat, allowing to write the output
 data to different output files in Text output format.

 class
NullOutputFormat<K,V>

          Deprecated. Use
   NullOutputFormat instead.

Methods in org.apache.hadoop.mapred.lib that return types with arguments of type OutputFormat

static Class<? extends OutputFormat>
MultipleOutputs.getNamedOutputFormatClass(JobConf conf,
                          String namedOutput)

          Returns the named output OutputFormat.

Method parameters in org.apache.hadoop.mapred.lib with type arguments of type OutputFormat

static void
MultipleOutputs.addMultiNamedOutput(JobConf conf,
                    String namedOutput,
                    Class<? extends OutputFormat> outputFormatClass,
                    Class<?> keyClass,
                    Class<?> valueClass)

          Adds a multi named output for the job.

static void
MultipleOutputs.addNamedOutput(JobConf conf,
               String namedOutput,
               Class<? extends OutputFormat> outputFormatClass,
               Class<?> keyClass,
               Class<?> valueClass)

          Adds a named output for the job.

Uses of OutputFormat in org.apache.hadoop.mapred.lib.db

Classes in org.apache.hadoop.mapred.lib.db that implement OutputFormat

 class
DBOutputFormat<K extends DBWritable,V>

          A OutputFormat that sends the reduce output to a SQL table.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 The Apache Software Foundation


text:
@interface FullTweetView : TweetView

@end


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="styles/main.css">

    Interrupt


text:
import React from 'react';
import { withStyles, createClassNameFromProps } from './common/StyleManager';

class BBadge extends React.PureComponent {
  render() {
    return (
      {this.props.children}
    );
  }
}

export const Badge =  withStyles('badge')(BBadge);


text:
'use strict';

const models = require('./index');

/**
 * The path of the SAP ECC OData entity.
 *
 * @extends models['Dataset']
 */
class SapEccResourceDataset extends models['Dataset'] {
  /**
   * Create a SapEccResourceDataset.
   * @member {string} path The path of the SAP ECC OData entity. Type: string
   * (or Expression with resultType string).
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of SapEccResourceDataset
   *
   * @returns {object} metadata of SapEccResourceDataset
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'SapEccResource',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: 'type',
          clientName: 'type'
        },
        uberParent: 'Dataset',
        className: 'SapEccResourceDataset',
        modelProperties: {
          description: {
            required: false,
            serializedName: 'description',
            type: {
              name: 'String'
            }
          },
          structure: {
            required: false,
            serializedName: 'structure',
            type: {
              name: 'Object'
            }
          },
          linkedServiceName: {
            required: true,
            serializedName: 'linkedServiceName',
            defaultValue: {},
            type: {
              name: 'Composite',
              className: 'LinkedServiceReference'
            }
          },
          parameters: {
            required: false,
            serializedName: 'parameters',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'ParameterSpecificationElementType',
                  type: {
                    name: 'Composite',
                    className: 'ParameterSpecification'
                  }
              }
            }
          },
          annotations: {
            required: false,
            serializedName: 'annotations',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ObjectElementType',
                  type: {
                    name: 'Object'
                  }
              }
            }
          },
          folder: {
            required: false,
            serializedName: 'folder',
            type: {
              name: 'Composite',
              className: 'DatasetFolder'
            }
          },
          type: {
            required: true,
            serializedName: 'type',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          },
          path: {
            required: true,
            serializedName: 'typeProperties.path',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = SapEccResourceDataset;


text:
<?php

/**
 * Unit test class for the NonceVerification Sniff.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    J.D. Grimes <jdg@codesymphony.co>
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

class WordPress_Tests_CSRF_NonceVerificationUnitTest extends AbstractSniffUnitTest {

	/**
	 * Returns the lines where errors should occur.
	 *
	 * The key of the array should represent the line number and the value
	 * should represent the number of errors that should occur on that line.
	 *
	 * @return array(int => int)
	 */
	public function getErrorList() {

		return array(
			5 => 1,
			9 => 1,
			31 => 1,
			44 => 1,
			48 => 1,
			69 => 1,
			89 => 1,
			113 => 1,
			114 => 1,
		);
	}

	/**
	 * Returns the lines where warnings should occur.
	 *
	 * The key of the array should represent the line number and the value
	 * should represent the number of warnings that should occur on that line.
	 *
	 * @return array(int => int)
	 */
	public function getWarningList() {
		return array();
	}

} // end class


text:
package org.rioproject.tools.ui.prefs;

import org.rioproject.tools.ui.*;
import org.rioproject.tools.ui.cybernodeutilization.CybernodeUtilizationPanel;
import org.rioproject.ui.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

/**
 * A dialog for allowing the user to provide preferences like color for
 * displayed elements
 *
 * @author Dennis Reedy
 */
public class PreferencesDialog extends JDialog {
    private final JFrame frame;

    public PreferencesDialog(final Main frame,
                             final GraphView graphView,
                             final CybernodeUtilizationPanel cybernodeUtil) {
        super(frame);
        this.frame = frame;
        String frameTitle = frame.getTitle();
        frameTitle = (frameTitle.equals("")?"Rio UI":frameTitle);
        setTitle(frameTitle+" Preferences");

        JPanel pane = new JPanel();
        pane.setLayout(new BorderLayout(8, 8));
        final ColorManager colorManager = graphView.getColorManager();
        final ColorPanel colorPanel = new ColorPanel(colorManager.getFailureColor(),
                                                     colorManager.getOkayColor(),
                                                     colorManager.getWarningColor(),
                                                     colorManager.getUnManagedColor());

        final CybernodePanel cybernodePanel =
            new CybernodePanel(frame.getCybernodeRefreshRate(),
                               frame.getUtilizationColumnManager().getSelectedColumns());

        final JTabbedPane tabs = new JTabbedPane();

        tabs.add("Utilization Table", cybernodePanel);
        tabs.add("Color Settings", colorPanel);

        //pane.add(colorPanel, BorderLayout.CENTER);
        pane.add(tabs, BorderLayout.CENTER);
        JButton okay = new JButton("Okay");
        okay.setToolTipText("Accept settings and close dialog");
        okay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                boolean runVis = false;

                int refreshRate = cybernodePanel.getRefreshRate();
                if(refreshRate==0) {
                    JOptionPane.showMessageDialog(frame,
                                                  "The Cybernode Table RefreshRate must be > 0",
                                                  "Invalid Value",
                                                  JOptionPane.ERROR_MESSAGE);
                    tabs.setSelectedIndex(2);
                    return;
                }

                if(!colorManager.getFailureColor().equals(colorPanel.getFailureColor())) {
                    colorManager.setFailureColor(colorPanel.getFailureColor());
                    runVis = true;
                }

                if(!colorManager.getOkayColor().equals(colorPanel.getOkayColor())) {
                    colorManager.setOkayColor(colorPanel.getOkayColor());
                    runVis = true;
                }

                if(!colorManager.getWarningColor().equals(colorPanel.getWarningColor())) {
                    colorManager.setWarningColor(colorPanel.getWarningColor());
                    runVis = true;
                }

                if(!colorManager.getUnManagedColor().equals(colorPanel.getUnManagedColor())) {
                    colorManager.setUnManagedColor(colorPanel.getUnManagedColor());
                    runVis = true;
                }

                frame.setCybernodeRefreshRate(cybernodePanel.getRefreshRate());
                if(runVis)
                    graphView.getVisualization().run("repaint");

                String[] cols = cybernodePanel.getSelectedColumns();
                frame.getUtilizationColumnManager().setSelectedColumns(cols);

                //System.out.println(getSize());
                dispose();
            }
        });
        JButton cancel = new JButton("Cancel");
        cancel.setToolTipText("Close the dialog without changing any settings");
        cancel.addActionListener(new Util.DisposeActionListener(this));
        JButton reset = new JButton("Reset");
        reset.setToolTipText("Restore system settings");
        reset.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event) {
                Map<String, Color> colorMap = colorManager.getDefaultColorMap();
                colorPanel.setFailureColor(colorMap.get(Constants.FAILURE_COLOR));
                colorPanel.setOkayColor(colorMap.get(Constants.OKAY_COLOR));
                colorPanel.setWarningColor(colorMap.get(Constants.WARNING_COLOR));
                colorPanel.setUnManagedColor(colorMap.get(Constants.UNMANAGED_COLOR));
            }
        });
        JPanel buttonPane = new JPanel();
        buttonPane.add(okay);
        buttonPane.add(cancel);
        buttonPane.add(reset);
        pane.add(buttonPane, BorderLayout.SOUTH);
        getContentPane().add(pane);
    }

    public void setVisible(boolean visible) {
        if(visible) {
            int width = 600;
            int height = 435;
            pack();
            setSize(width, height);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int widthLoc = screenSize.width / 2 - width / 2;
            int heightLoc = screenSize.height / 2 - height / 2;
            setLocation(widthLoc, heightLoc);
            setLocationRelativeTo(frame);
        }
        super.setVisible(visible);
    }

}


text:
package config

import (
	"github.com/spf13/cobra"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
	genericprinters "k8s.io/kubernetes/pkg/kubectl/genericclioptions/printers"
	"k8s.io/kubernetes/pkg/printers"
)

// kubectlConfigPrintFlags composes common printer flag structs
// used across all config commands, and provides a method
// of retrieving a known printer based on flag values provided.
type kubectlConfigPrintFlags struct {
	JSONYamlPrintFlags *genericclioptions.JSONYamlPrintFlags
	NamePrintFlags     *genericclioptions.NamePrintFlags
	TemplateFlags      *printers.KubeTemplatePrintFlags

	TypeSetter *genericprinters.TypeSetterPrinter

	OutputFormat *string
}

func (f *kubectlConfigPrintFlags) Complete(successTemplate string) error {
	return f.NamePrintFlags.Complete(successTemplate)
}

func (f *kubectlConfigPrintFlags) ToPrinter() (printers.ResourcePrinter, error) {
	outputFormat := ""
	if f.OutputFormat != nil {
		outputFormat = *f.OutputFormat
	}

	if p, err := f.JSONYamlPrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return f.TypeSetter.WrapToPrinter(p, err)
	}

	if p, err := f.NamePrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return f.TypeSetter.WrapToPrinter(p, err)
	}

	if p, err := f.TemplateFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return f.TypeSetter.WrapToPrinter(p, err)
	}

	return nil, genericclioptions.NoCompatiblePrinterError{Options: f}
}

func (f *kubectlConfigPrintFlags) AddFlags(cmd *cobra.Command) {
	f.JSONYamlPrintFlags.AddFlags(cmd)
	f.NamePrintFlags.AddFlags(cmd)
	f.TemplateFlags.AddFlags(cmd)

	if f.OutputFormat != nil {
		cmd.Flags().StringVarP(f.OutputFormat, "output", "o", *f.OutputFormat, "Output format. One of: json|yaml|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath].")
	}
}

// WithDefaultOutput sets a default output format if one is not provided through a flag value
func (f *kubectlConfigPrintFlags) WithDefaultOutput(output string) *kubectlConfigPrintFlags {
	f.OutputFormat = &output
	return f
}

func newKubeConfigPrintFlags(scheme runtime.ObjectTyper) *kubectlConfigPrintFlags {
	outputFormat := ""

	return &kubectlConfigPrintFlags{
		OutputFormat: &outputFormat,

		JSONYamlPrintFlags: genericclioptions.NewJSONYamlPrintFlags(),
		NamePrintFlags:     genericclioptions.NewNamePrintFlags(""),
		TemplateFlags:      printers.NewKubeTemplatePrintFlags(),

		TypeSetter: genericprinters.NewTypeSetter(scheme),
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Qt 4.8: norwegianwoodstyle.cpp Example File (widgets/styles/norwegianwoodstyle.cpp)</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

A

A

A

                Print

norwegianwoodstyle.cpp Example File

widgets/styles/norwegianwoodstyle.cpp

 #include <QtGui>

 #include "norwegianwoodstyle.h"

 void NorwegianWoodStyle::polish(QPalette &palette)
 {
     QColor brown(212, 140, 95);
     QColor beige(236, 182, 120);
     QColor slightlyOpaqueBlack(0, 0, 0, 63);

     QPixmap backgroundImage(":/images/woodbackground.png");
     QPixmap buttonImage(":/images/woodbutton.png");
     QPixmap midImage = buttonImage;

     QPainter painter;
     painter.begin(&midImage);
     painter.setPen(Qt::NoPen);
     painter.fillRect(midImage.rect(), slightlyOpaqueBlack);
     painter.end();

     palette = QPalette(brown);

     palette.setBrush(QPalette::BrightText, Qt::white);
     palette.setBrush(QPalette::Base, beige);
     palette.setBrush(QPalette::Highlight, Qt::darkGreen);
     setTexture(palette, QPalette::Button, buttonImage);
     setTexture(palette, QPalette::Mid, midImage);
     setTexture(palette, QPalette::Window, backgroundImage);

     QBrush brush = palette.background();
     brush.setColor(brush.color().dark());

     palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush);
     palette.setBrush(QPalette::Disabled, QPalette::Text, brush);
     palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush);
     palette.setBrush(QPalette::Disabled, QPalette::Base, brush);
     palette.setBrush(QPalette::Disabled, QPalette::Button, brush);
     palette.setBrush(QPalette::Disabled, QPalette::Mid, brush);
 }

 void NorwegianWoodStyle::polish(QWidget *widget)
 {
     if (qobject_cast<QPushButton *>(widget)
             || qobject_cast<QComboBox *>(widget))
         widget->setAttribute(Qt::WA_Hover, true);
 }

 void NorwegianWoodStyle::unpolish(QWidget *widget)
 {
     if (qobject_cast<QPushButton *>(widget)
             || qobject_cast<QComboBox *>(widget))
         widget->setAttribute(Qt::WA_Hover, false);
 }

 int NorwegianWoodStyle::pixelMetric(PixelMetric metric,
                                     const QStyleOption *option,
                                     const QWidget *widget) const
 {
     switch (metric) {
     case PM_ComboBoxFrameWidth:
         return 8;
     case PM_ScrollBarExtent:
         return QMotifStyle::pixelMetric(metric, option, widget) + 4;
     default:
         return QMotifStyle::pixelMetric(metric, option, widget);
     }
 }

 int NorwegianWoodStyle::styleHint(StyleHint hint, const QStyleOption *option,
                                   const QWidget *widget,
                                   QStyleHintReturn *returnData) const
 {
     switch (hint) {
     case SH_DitherDisabledText:
         return int(false);
     case SH_EtchDisabledText:
         return int(true);
     default:
         return QMotifStyle::styleHint(hint, option, widget, returnData);
     }
 }

 void NorwegianWoodStyle::drawPrimitive(PrimitiveElement element,
                                        const QStyleOption *option,
                                        QPainter *painter,
                                        const QWidget *widget) const
 {
     switch (element) {
     case PE_PanelButtonCommand:
         {
             int delta = (option->state & State_MouseOver) ? 64 : 0;
             QColor slightlyOpaqueBlack(0, 0, 0, 63);
             QColor semiTransparentWhite(255, 255, 255, 127 + delta);
             QColor semiTransparentBlack(0, 0, 0, 127 - delta);

             int x, y, width, height;
             option->rect.getRect(&x, &y, &width, &height);

             QPainterPath roundRect = roundRectPath(option->rect);
             int radius = qMin(width, height) / 2;

             QBrush brush;
             bool darker;

             const QStyleOptionButton *buttonOption =
                     qstyleoption_cast<const QStyleOptionButton *>(option);
             if (buttonOption
                     && (buttonOption->features & QStyleOptionButton::Flat)) {
                 brush = option->palette.background();
                 darker = (option->state & (State_Sunken | State_On));
             } else {
                 if (option->state & (State_Sunken | State_On)) {
                     brush = option->palette.mid();
                     darker = !(option->state & State_Sunken);
                 } else {
                     brush = option->palette.button();
                     darker = false;
                 }
             }

             painter->save();
             painter->setRenderHint(QPainter::Antialiasing, true);
             painter->fillPath(roundRect, brush);
             if (darker)
                 painter->fillPath(roundRect, slightlyOpaqueBlack);

             int penWidth;
             if (radius < 10)
                 penWidth = 3;
             else if (radius < 20)
                 penWidth = 5;
             else
                 penWidth = 7;

             QPen topPen(semiTransparentWhite, penWidth);
             QPen bottomPen(semiTransparentBlack, penWidth);

             if (option->state & (State_Sunken | State_On))
                 qSwap(topPen, bottomPen);

             int x1 = x;
             int x2 = x + radius;
             int x3 = x + width - radius;
             int x4 = x + width;

             if (option->direction == Qt::RightToLeft) {
                 qSwap(x1, x4);
                 qSwap(x2, x3);
             }

             QPolygon topHalf;
             topHalf << QPoint(x1, y)
                     << QPoint(x4, y)
                     << QPoint(x3, y + radius)
                     << QPoint(x2, y + height - radius)
                     << QPoint(x1, y + height);

             painter->setClipPath(roundRect);
             painter->setClipRegion(topHalf, Qt::IntersectClip);
             painter->setPen(topPen);
             painter->drawPath(roundRect);

             QPolygon bottomHalf = topHalf;
             bottomHalf[0] = QPoint(x4, y + height);

             painter->setClipPath(roundRect);
             painter->setClipRegion(bottomHalf, Qt::IntersectClip);
             painter->setPen(bottomPen);
             painter->drawPath(roundRect);

             painter->setPen(option->palette.foreground().color());
             painter->setClipping(false);
             painter->drawPath(roundRect);

             painter->restore();
         }
         break;
     default:
         QMotifStyle::drawPrimitive(element, option, painter, widget);
     }
 }

 void NorwegianWoodStyle::drawControl(ControlElement element,
                                      const QStyleOption *option,
                                      QPainter *painter,
                                      const QWidget *widget) const
 {
     switch (element) {
     case CE_PushButtonLabel:
         {
             QStyleOptionButton myButtonOption;
             const QStyleOptionButton *buttonOption =
                     qstyleoption_cast<const QStyleOptionButton *>(option);
             if (buttonOption) {
                 myButtonOption = *buttonOption;
                 if (myButtonOption.palette.currentColorGroup()
                         != QPalette::Disabled) {
                     if (myButtonOption.state & (State_Sunken | State_On)) {
                         myButtonOption.palette.setBrush(QPalette::ButtonText,
                                 myButtonOption.palette.brightText());
                     }
                 }
             }
             QMotifStyle::drawControl(element, &myButtonOption, painter, widget);
         }
         break;
     default:
         QMotifStyle::drawControl(element, option, painter, widget);
     }
 }

 void NorwegianWoodStyle::setTexture(QPalette &palette, QPalette::ColorRole role,
                                     const QPixmap &pixmap)
 {
     for (int i = 0; i < QPalette::NColorGroups; ++i) {
         QColor color = palette.brush(QPalette::ColorGroup(i), role).color();
         palette.setBrush(QPalette::ColorGroup(i), role, QBrush(color, pixmap));
     }
 }

 QPainterPath NorwegianWoodStyle::roundRectPath(const QRect &rect)
 {
     int radius = qMin(rect.width(), rect.height()) / 2;
     int diam = 2 * radius;

     int x1, y1, x2, y2;
     rect.getCoords(&x1, &y1, &x2, &y2);

     QPainterPath path;
     path.moveTo(x2, y1 + radius);
     path.arcTo(QRect(x2 - diam, y1, diam, diam), 0.0, +90.0);
     path.lineTo(x1 + radius, y1);
     path.arcTo(QRect(x1, y1, diam, diam), 90.0, +90.0);
     path.lineTo(x1, y2 - radius);
     path.arcTo(QRect(x1, y2 - diam, diam, diam), 180.0, +90.0);
     path.lineTo(x1 + radius, y2);
     path.arcTo(QRect(x2 - diam, y2 - diam, diam, diam), 270.0, +90.0);
     path.closeSubpath();
     return path;
 }

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
package org.xander.spring.springIdol.transactions;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class BookShopCashier implements Cashier {
    private BookShop bookShop;
    public void setBookShop(BookShop bookShop) {
        this.bookShop = bookShop;
    }
    @Transactional
    public void checkout(List<String> isbns, String username) {
        for (String isbn : isbns) {
            bookShop.purchase(isbn, username);
        }
    }
}


text:
"use strict";

(function () {

    var io = require('socket.io').listen(8889),
        DBModel = require('./../database/mongodb/mongodb-schema'),
        DBCrud = require('./../database/mongodb/mongodb-crud');

    io.on('connection', function (socket) {

        socket.on('new:message', function (msg) {

            socket.broadcast.emit('send:message', msg);
            DBCrud.readOne(DBModel.Conversions, msg.conversionId, function (err, resp){
                if(err){
                    socket.emit('message:send:error');
                }else {
                    socket.broadcast.emit('send:message', resp);

                }

            })

        });

        socket.on('create:room', function (room){
            socket.broadcast.emit('new:room', room);
        })

    });

})();


text:
<!DOCTYPE html>

    <title>jQuery-Machine Demo</title>

jQuery-Machine Demo

Click on the button and watch it transition to different states:

    <button id="mybutton">Click me!</button>

State Log:

    Other examples:
    On-Off Button


text:
package groovy.ui.text;

import java.awt.Font;
import java.awt.Toolkit;

import java.awt.datatransfer.Clipboard;

/**
 * Contains all the basic resources and values used by the utility frame work
 * framework.
 *
 * @author Evan "Hippy" Slatis
 */
public final class StructuredSyntaxResources {

    // ==================================================
    // ClipBoard
    // ==================================================

    public static final Clipboard SYSTEM_CLIPBOARD;
    static {
        Clipboard systemClipboard = null;
        try {
            // if we don't have access to the system clipboard, will throw
            // a security exception
            SecurityManager mgr = System.getSecurityManager();
            if (mgr != null) {
                mgr.checkSystemClipboardAccess();
            }
            systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        }
        catch (SecurityException e) {
            // means we can't get to system clipboard, so create app level one
            systemClipboard = new Clipboard("UIResourceMgr");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        SYSTEM_CLIPBOARD = systemClipboard;
    }

    // =====================================================
    // STANDARD FONTS
    // =====================================================

    public static final Font LARGE_FONT = Font.decode("Arial-24");
    public static final Font MEDIUM_FONT = Font.decode("Arial-18");
    public static final Font SMALL_FONT = Font.decode("Arial-12");

    public static final Font EDITOR_FONT = Font.decode("Monospaced-12");

    // =====================================================
    // UNDO/REDO NAMES
    // =====================================================

    public static final String UNDO = "Undo";
    public static final String REDO = "Redo";
    public static final String PRINT = "Print";
    public static final String FIND = "Find";
    public static final String FIND_NEXT = "Find Next";
    public static final String REPLACE = "Replace";

    // singleton
    private StructuredSyntaxResources() {
    }
}


text:
<?php

namespace HanischIt\KrakenApi\Call\TradeVolume;

use HanischIt\KrakenApi\Call\TradeVolume\Model\FeeModel;
use HanischIt\KrakenApi\Model\ResponseInterface;

/**
 * Class TradeVolumeResponse
 * @package HanischIt\KrakenApi\Call\TradeVolume
 */
class TradeVolumeResponse implements ResponseInterface
{
    /**
     * @var string
     */
    private $currency;
    /**
     * @var float
     */
    private $volume;
    /**
     * @var FeeModel[]
     */
    private $fees = [];
    /**
     * @var FeeModel[]
     */
    private $feesMaker = [];

    /**
     * @param array $result
     */
    public function manualMapping($result)
    {
        $this->currency = $result["currency"];
        $this->volume = $result["volume"];

        if (isset($result["fees"])) {
            foreach ($result["fees"] as $fee) {
                $this->fees[] = new FeeModel(
                    $fee["fee"],
                    $fee["minfee"],
                    $fee["maxfee"],
                    $fee["nextfee"],
                    $fee["nextvolume"],
                    $fee["tiervolume"]
                );
            }
        }

        if (isset($result["fees_maker"])) {
            foreach ($result["fees_maker"] as $fee) {
                $this->feesMaker[] = new FeeModel(
                    $fee["fee"],
                    $fee["minfee"],
                    $fee["maxfee"],
                    $fee["nextfee"],
                    $fee["nextvolume"],
                    $fee["tiervolume"]
                );
            }
        }
    }

    /**
     * @return string
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @return float
     */
    public function getVolume()
    {
        return $this->volume;
    }

    /**
     * @return FeeModel[]
     */
    public function getFees()
    {
        return $this->fees;
    }

    /**
     * @return FeeModel[]
     */
    public function getFeesMaker()
    {
        return $this->feesMaker;
    }

}


text:
docker stop selenium-hub
docker rm selenium-hub
docker stop selenium-node-chrome
docker rm selenium-node-chrome

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.48.2
docker run -d --link selenium-hub:hub --name selenium-node-chrome -v /dev/shm:/dev/shm selenium/node-chrome:2.48.2


text:
.scalr-mainwindow-docked-warning {
	white-space: nowrap;
	font-family: Arial;
	font-size: 14px;
	text-align: center;
	background: #FFF4CC;
	color: #974706;
	border: 1px solid #CEA16D !important;
}

.scalr-mainwindow-docked-toolbar{
	border: 1px solid #99BBE8 !important;
}

.scalr-treepanel {
	border-bottom: 0px;
	border-top: 0px;
	border-left: 0px;
	border-right: 1px;
}

.scalr-mainwindow-docked-map {
	border: 1px solid #99BBE8 !important;
}

/* View switch button */
.scalr-ui-btn-icon-viewswitch {
	width: 56px;
	height: 21px;
}

.scalr-ui-btn-icon-viewswitch .view {
	width: 28px;
	height: 21px;
	float: left;
	cursor: pointer;
}

.scalr-ui-btn-icon-viewswitch .grid {
	width: 28px;
	height: 21px;
	float: left;
	cursor: pointer;
}

.scalr-ui-btn-icon-viewswitch-grid {
	background-image: url('/ui2/images/icons/grid/view_switch.png') !important;
	background-position: 0px 21px;
}

.scalr-ui-btn-icon-viewswitch-view {
	background-image: url('/ui2/images/icons/grid/view_switch.png') !important;
	background-position: 0px 0px;
}

/* Scalr UI messages */
.scalr-ui-message {
	width: 60%;
	max-width: 600px;
	left: 30%;
	z-index: 16000;
	position: absolute;
	background-color: #EBF1FC;
	border: 1px solid #94A5BC;
	box-shadow: 0 1px #FFF inset, 0 -1px #FFF inset, 1px 0 #FFF inset, -1px 0 #FFF inset, 0 0 6px #999;
	font-size: 13px;
	line-height: 18px;
}

.scalr-ui-message-success {
	background: url('/ui2/images/icons/message/success_16x16.png') no-repeat scroll 10px 8px;
	color: #438800;
	padding: 8px 25px 8px 34px;
}

.scalr-ui-message-error {
	background: url('/ui2/images/icons/message/error_16x16.png') no-repeat scroll 10px 8px;
	color: #CA4100;
	padding: 8px 25px 8px 34px;
}

.scalr-ui-message-info {
	background: url('/ui2/images/icons/message/info_16x16.png') no-repeat scroll 10px 8px;
	color: #307AB0;
	padding: 8px 25px 8px 34px;
}

.scalr-ui-message-warning {
	background: url('/ui2/images/icons/message/warning_16x16.png') no-repeat scroll 10px 8px;
	color: #474747;
	padding: 8px 25px 8px 34px;
}

/* Edit combobox status icon */
.scalr-ui-grid-row-combobox {
	padding-right: 5px;
}

.scalr-ui-grid-row-combobox .x-grid-cell-inner {
	background-image: url('/ui2/images/icons/grid/arrow_icon.png') !important;
	background-position: right center;
	background-repeat: no-repeat;
	padding-right: 13px;
}

/*
 * Operation status style
 */
.scalr-operation-status-complete {
	background: url('/ui2/images/icons/operation_status_icons_sprite.png') no-repeat;
	height:14px;
	width:14px;
	background-position: 0px 0px;
	float:left;
	margin-right:5px;
}

.scalr-operation-status-running {
	/*background: url('/ui2/images/icons/operation_status_icons_sprite.png') no-repeat;*/
	height:14px;
	width:14px;
	/*background-position: 0px -14px;*/
	float:left;
	margin-right:5px;
}

.scalr-operation-status-warning {
	background: url('/ui2/images/icons/operation_status_icons_sprite.png') no-repeat;
	height:14px;
	width:14px;
	background-position: 0px -28px;
	float:left;
	margin-right:5px;
}

.scalr-operation-status-error {
	background: url('/ui2/images/icons/operation_status_icons_sprite.png') no-repeat;
	height:14px;
	width:14px;
	color: red;
	background-position: 0px -42px;
	float:left;
	margin-right:5px;
}

.scalr-operation-status-pending {
	float:left;
	height:14px;
	width:14px;
	margin-right:5px;
}

/*
 * Form
 */

/* ultra-large buttons (64px) (on top) */
.scalr-btn-icon-ultra-large .x-btn-inner {
	padding-top: 68px;
	background-position: center top;
	min-width: 68px;
	width: 89px;
}

.scalr-btn-icon-ultra-large .x-btn-icon {
	height: 64px;
}

.scalr-btn-icon-billing .x-btn-inner {
	margin-left: 20px;
	padding-left: 10px;
}

.scalr-btn-icon-billing .x-btn-icon {
	height: 113px;
	width: 70px;
}


text:
var QE = require('../models/queueEntry');
var bluebird = require('bluebird');
var _ = require('lodash');

var exports = {};

// Todo: dispatch events for all of these actions
exports.getQueue = function(queueOwner) {
  return QE.find({queueOwner})
    .sort({createdAt: 'asc'})
    .sort({isConfirmationPending: 'asc'})
    .then((queueEntries) => {
      return {
        owner: queueOwner,
        entries: queueEntries
      }
    });
};

exports.enqueue = function(queueOwner, username) {
  return QE.create({queueOwner, username});
};

exports.remove = function(queueOwner, username) {
  return QE.remove({queueOwner, username});
};

exports.dequeue = function(queueOwner, count) {
  return QE.find({queueOwner, isConfirmationPending: true})
    .sort({createdAt: 'asc'})
    .limit(count)
    .then((queueEntries) => {
      return bluebird.map(queueEntries, (queueEntry) => {
        queueEntry.isConfirmationPending = false;

        return queueEntry.save();
      });
    });
};

module.exports = exports;


text:
import { Component } from '@angular/core';
import { StepInformation } from '../contracts/step-information';
import { StepsInformationService } from '../services/steps-information.service';
import { StepsExecutionService } from '../services/steps-execution.service';
import { StepExecutionResult } from '../contracts/step-execution-result';
import { ExecutionOptionsFactory } from '../contracts/execution-options';
import { OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'step',
    templateUrl: 'app/steps/step.component.html',
    styleUrls: [ 'app/steps/step.component.css' ]
})
export class StepComponent implements OnInit, OnDestroy {
    step: StepInformation;
    result: StepExecutionResult;
    error: any;
    navigated = false;
    subscription: Subscription;

    constructor(
        private route: ActivatedRoute,
        private stepsInformationService: StepsInformationService,
        private stepsExecutionService: StepsExecutionService,
        private executionOptionsFactory: ExecutionOptionsFactory) {
    }

    ngOnInit() {
        this.navigated = true;
        this.subscription = this.route.params.subscribe(params => {
            let name = String(params['name']);
            this.stepsInformationService.getStep(name).
                then(step => this.step = step);
        });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    goBack() {
        if (this.navigated) {
            window.history.back();
        }
    }

    save() {
    }

    execute() {
        let executionOptions = this.executionOptionsFactory.create(
            this.step.name,
            this.step.stepParameterType,
            this.step.stepParameterProperties);

        this.stepsExecutionService.execute(executionOptions).
            then(results =>
            {
                let executionResults = results as StepExecutionResult[];
                if (executionResults.length > 0)
                    this.result = executionResults[0];
            });
    }
}


text:
#include "power_states.h"
#include "vreg.h"

#if (QM_SENSOR)
#include "qm_sensor_regs.h"
#endif
#include "soc_watch.h"

void power_soc_sleep()
{
	/* Go to sleep */
	QM_SCSS_PMU->slp_cfg &= ~QM_SCSS_SLP_CFG_LPMODE_EN;

	SOC_WATCH_LOG_EVENT(SOCW_EVENT_REGISTER, SOCW_REG_SLP_CFG);
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_SLEEP, 0);
	QM_SCSS_PMU->pm1c |= QM_SCSS_PM1C_SLPEN;
}

void power_soc_deep_sleep()
{
	/* Switch to linear regulators.
	 * For low power deep sleep mode, it is a requirement that the platform
	 * voltage regulators are not in switching mode.
	 */
	vreg_plat1p8_set_mode(VREG_MODE_LINEAR);
	vreg_plat3p3_set_mode(VREG_MODE_LINEAR);

	/* Enable low power sleep mode */
	QM_SCSS_PMU->slp_cfg |= QM_SCSS_SLP_CFG_LPMODE_EN;
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_REGISTER, SOCW_REG_SLP_CFG);
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_SLEEP, 0);
	QM_SCSS_PMU->pm1c |= QM_SCSS_PM1C_SLPEN;
}

#if (ENABLE_RESTORE_CONTEXT) && (!QM_SENSOR)
/*
 * The restore trap address is stored in the variable __x86_restore_info.
 * The variable __x86_restore_info is defined in the linker script as a new
 * and independent memory segment.
 */
extern uint32_t __x86_restore_info[];
/*
 * The stack pointer is saved in the global variable sp_restore_storage
 * by qm_x86_save_context() before sleep and it is restored by
 * qm_x86_restore_context() after wake up.
 */
uint32_t sp_restore_storage;
void power_soc_sleep_restore()
{
	/*
	 * Save x86 restore trap address.
	 * The first parameter in this macro represents the label defined in
	 * the qm_x86_restore_context() macro, which is actually the restore
	 * trap address.
	 */
	qm_x86_set_resume_vector(sleep_restore_trap, __x86_restore_info);

	/* Save x86 execution context. */
	qm_x86_save_context(sp_restore_storage);

	/* Set restore flags. */
	power_soc_set_x86_restore_flag();

	/* Enter sleep. */
	power_soc_sleep();

	/*
	 * Restore x86 execution context.
	 * The bootloader code will jump to this location after waking up from
	 * sleep. The restore trap address is the label defined in the macro.
	 * That label is exposed here through the first parameter.
	 */
	qm_x86_restore_context(sleep_restore_trap, sp_restore_storage);
}

void power_soc_deep_sleep_restore()
{
	/*
	 * Save x86 restore trap address.
	 * The first parameter in this macro represents the label defined in
	 * the qm_x86_restore_context() macro, which is actually the restore
	 * trap address.
	 */
	qm_x86_set_resume_vector(deep_sleep_restore_trap, __x86_restore_info);

	/* Save x86 execution context. */
	qm_x86_save_context(sp_restore_storage);

	/* Set restore flags. */
	power_soc_set_x86_restore_flag();

	/* Enter sleep. */
	power_soc_deep_sleep();

	/*
	 * Restore x86 execution context.
	 * The bootloader code will jump to this location after waking up from
	 * sleep. The restore trap address is the label defined in the macro.
	 * That label is exposed here through the first parameter.
	 */
	qm_x86_restore_context(deep_sleep_restore_trap, sp_restore_storage);
}

void power_sleep_wait()
{
	/*
	 * Save x86 restore trap address.
	 * The first parameter in this macro represents the label defined in
	 * the qm_x86_restore_context() macro, which is actually the restore
	 * trap address.
	 */
	qm_x86_set_resume_vector(sleep_restore_trap, __x86_restore_info);

	/* Save x86 execution context. */
	qm_x86_save_context(sp_restore_storage);

	/* Set restore flags. */
	power_soc_set_x86_restore_flag();

	/* Enter C2 and stay in it until sleep and wake-up. */
	while (1) {
		power_cpu_c2();
	}

	/*
	 * Restore x86 execution context.
	 * The bootloader code will jump to this location after waking up from
	 * sleep. The restore trap address is the label defined in the macro.
	 * That label is exposed here through the first parameter.
	 */
	qm_x86_restore_context(sleep_restore_trap, sp_restore_storage);
}

void power_soc_set_x86_restore_flag(void)
{
	QM_SCSS_GP->gps0 |= BIT(QM_GPS0_BIT_X86_WAKEUP);
}
#endif /* ENABLE_RESTORE_CONTEXT */

#if (!QM_SENSOR)
void power_cpu_c1()
{
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_HALT, 0);
	/*
	 * STI sets the IF flag. After the IF flag is set,
	 * the core begins responding to external,
	 * maskable interrupts after the next instruction is executed.
	 * When this function is called with interrupts disabled,
	 * this guarantees that an interrupt is caught only
	 * after the processor has transitioned into HLT.
	 */
	__asm__ __volatile__("sti\n\t"
			     "hlt\n\t");
}

void power_cpu_c2()
{
	QM_SCSS_CCU->ccu_lp_clk_ctl &= ~QM_SCSS_CCU_C2_LP_EN;
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_REGISTER, SOCW_REG_CCU_LP_CLK_CTL);

	/* Read P_LVL2 to trigger a C2 request */
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_SLEEP, 0);
	QM_SCSS_PMU->p_lvl2;
}

void power_cpu_c2lp()
{
	QM_SCSS_CCU->ccu_lp_clk_ctl |= QM_SCSS_CCU_C2_LP_EN;
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_REGISTER, SOCW_REG_CCU_LP_CLK_CTL);

	/* Read P_LVL2 to trigger a C2 request */
	SOC_WATCH_LOG_EVENT(SOCW_EVENT_SLEEP, 0);
	QM_SCSS_PMU->p_lvl2;
}
#endif


text:
module Boards
  class CreateService < BaseService
    def execute
      if project.boards.empty?
        create_board!
      else
        project.boards.first
      end
    end

    private

    def create_board!
      board = project.boards.create
      board.lists.create(list_type: :backlog)
      board.lists.create(list_type: :done)

      board
    end
  end
end


text:
<?php

require_once("../../global/library.php");
ft_init_module_page();
$request = array_merge($_POST, $_GET);
$sortable_id = "export_group_list";

if (isset($request["add_export_group"]))
  list ($g_success, $g_message) = exp_add_export_group($request);
if (isset($request["delete"]))
  list ($g_success, $g_message) = exp_delete_export_group($request["delete"]);
if (isset($request["update"]))
{
  $request["sortable_id"] = $sortable_id;
  list ($g_success, $g_message) = exp_reorder_export_groups($request);
}

$export_groups = exp_get_export_groups();

// ------------------------------------------------------------------------------------------------

$page_vars = array();
$page_vars["export_groups"] = $export_groups;
$page_vars["sortable_id"] = $sortable_id;
$page_vars["head_string"] =<<< END
<link type="text/css" rel="stylesheet" href="{$g_root_url}/modules/export_manager/global/css/styles.css">

END;

$page_vars["head_js"] =<<< EOF
var page_ns = {};
page_ns.dialog = $("

");

page_ns.delete_export_group = function(el) {
  ft.create_dialog({
    dialog:     page_ns.dialog,
    title:      "{$LANG["phrase_please_confirm"]}",
    content:    "{$L["confirm_delete_export_group"]}",
    popup_type: "warning",
    buttons: [{
      text: "{$LANG["word_yes"]}",
      click: function() {
        var export_group_id = $(el).closest(".row_group").find(".sr_order").val();
        window.location = "index.php?delete=" + export_group_id;
      }
    },
    {
      text: "{$LANG["word_no"]}",
      click: function() {
        $(this).dialog("close");
      }
    }]
  });
  return false;
}
EOF;

ft_display_module_page("templates/index.tpl", $page_vars);


text:
package softlayer_network_loadbalancer_virtualipaddress

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED

import (
	slapi "github.com/sudorandom/softlayer-go/slapi"

	gentypes "github.com/sudorandom/softlayer-go-gen/types"
)

// Disable - Disable a Virtual IP Address, removing it from load balancer rotation and denying all
// connections to that IP address.
func Disable(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:  "disable",
		ID:      ID,
	}
}

// EditObject - Like any other API object, the load balancers can have their exposed properties edited
// by passing in a modified version of the object. The load balancer object also can modify its
// services in this way. Simply request the load balancer object you wish to edit, then modify the
// objects in the services array and pass the modified object to this function. WARNING: Services
// cannot be deleted in this manner, you must call deleteObject() on the service to physically remove
// them from the load balancer.
func EditObject(ID interface{}, templateObject gentypes.SoftLayer_Network_LoadBalancer_VirtualIpAddress) slapi.Request {
	return slapi.Request{
		Service:    "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:     "editObject",
		ID:         ID,
		Parameters: []interface{}{templateObject},
	}
}

// Enable - Enable a disabled Virtual IP Address, allowing connections back to the IP address.
func Enable(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:  "enable",
		ID:      ID,
	}
}

// GetObject - getObject retrieves the SoftLayer_Network_LoadBalancer_VirtualIpAddress object whose ID
// number corresponds to the ID number of the init parameter passed to the
// SoftLayer_Network_LoadBalancer_VirtualIpAddress service. You can only retrieve Load Balancers
// assigned to your account.
func GetObject(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:  "getObject",
		ID:      ID,
	}
}

// KickAllConnections - Quickly remove all active external connections to a Virtual IP Address.
func KickAllConnections(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:  "kickAllConnections",
		ID:      ID,
	}
}

// UpgradeConnectionLimit - Upgrades the connection limit on the VirtualIp and changes the billing item
// on your account to reflect the change. This function will only upgrade you to the next "level" of
// service. The next level follows this pattern Current Level => Next Level 50 100 100 200 200 500 500
// 1000 1000 1200 1200 1500 1500 2000 2000 2500 2500 3000
func UpgradeConnectionLimit(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Network_LoadBalancer_VirtualIpAddress",
		Method:  "upgradeConnectionLimit",
		ID:      ID,
	}
}


text:
/**
 * @unrestricted
 */
Sources.FilteredUISourceCodeListDelegate = class extends UI.FilteredListWidget.Delegate {
  /**
   * @param {!Map.<!Workspace.UISourceCode, number>=} defaultScores
   * @param {!Array<string>=} history
   */
  constructor(defaultScores, history) {
    super(history || []);

    this._defaultScores = defaultScores;
    this._scorer = new Sources.FilePathScoreFunction('');
    Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.workspace.addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
  }

  /**
   * @param {!Common.Event} event
   */
  _projectRemoved(event) {
    var project = /** @type {!Workspace.Project} */ (event.data);
    this.populate(project);
    this.refresh();
  }

  /**
   * @protected
   * @param {!Workspace.Project=} skipProject
   */
  populate(skipProject) {
    /** @type {!Array.<!Workspace.UISourceCode>} */
    this._uiSourceCodes = [];
    var projects = Workspace.workspace.projects().filter(this.filterProject.bind(this));
    for (var i = 0; i < projects.length; ++i) {
      if (skipProject && projects[i] === skipProject)
        continue;
      var uiSourceCodes = projects[i].uiSourceCodes().filter(this._filterUISourceCode.bind(this));
      this._uiSourceCodes = this._uiSourceCodes.concat(uiSourceCodes);
    }
  }

  /**
   * @param {!Workspace.UISourceCode} uiSourceCode
   * @return {boolean}
   */
  _filterUISourceCode(uiSourceCode) {
    var binding = Persistence.persistence.binding(uiSourceCode);
    return !binding || binding.network === uiSourceCode;
  }

  /**
   * @param {?Workspace.UISourceCode} uiSourceCode
   * @param {number=} lineNumber
   * @param {number=} columnNumber
   */
  uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber) {
    // Overridden by subclasses
  }

  /**
   * @param {!Workspace.Project} project
   * @return {boolean}
   */
  filterProject(project) {
    return true;
    // Overridden by subclasses
  }

  /**
   * @override
   * @return {number}
   */
  itemCount() {
    return this._uiSourceCodes.length;
  }

  /**
   * @override
   * @param {number} itemIndex
   * @return {string}
   */
  itemKeyAt(itemIndex) {
    return this._uiSourceCodes[itemIndex].url();
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @return {number}
   */
  itemScoreAt(itemIndex, query) {
    var uiSourceCode = this._uiSourceCodes[itemIndex];
    var score = this._defaultScores ? (this._defaultScores.get(uiSourceCode) || 0) : 0;
    if (!query || query.length < 2)
      return score;

    if (this._query !== query) {
      this._query = query;
      this._scorer = new Sources.FilePathScoreFunction(query);
    }

    var url = uiSourceCode.url();
    return score + 10 * this._scorer.score(url, null);
  }

  /**
   * @override
   * @param {number} itemIndex
   * @param {string} query
   * @param {!Element} titleElement
   * @param {!Element} subtitleElement
   */
  renderItem(itemIndex, query, titleElement, subtitleElement) {
    query = this.rewriteQuery(query);
    var uiSourceCode = this._uiSourceCodes[itemIndex];
    var fullDisplayName = uiSourceCode.fullDisplayName();
    var indexes = [];
    var score = new Sources.FilePathScoreFunction(query).score(fullDisplayName, indexes);
    var fileNameIndex = fullDisplayName.lastIndexOf('/');

    titleElement.textContent = uiSourceCode.displayName() + (this._queryLineNumberAndColumnNumber || '');
    this._renderSubtitleElement(subtitleElement, fullDisplayName);
    subtitleElement.title = fullDisplayName;
    var ranges = [];
    for (var i = 0; i < indexes.length; ++i)
      ranges.push({offset: indexes[i], length: 1});

    if (indexes[0] > fileNameIndex) {
      for (var i = 0; i < ranges.length; ++i)
        ranges[i].offset -= fileNameIndex + 1;
      UI.highlightRangesWithStyleClass(titleElement, ranges, 'highlight');
    } else {
      UI.highlightRangesWithStyleClass(subtitleElement, ranges, 'highlight');
    }
  }

  /**
   * @param {!Element} element
   * @param {string} text
   */
  _renderSubtitleElement(element, text) {
    element.removeChildren();
    var splitPosition = text.lastIndexOf('/');
    if (text.length > 55)
      splitPosition = text.length - 55;
    var first = element.createChild('div', 'first-part');
    first.textContent = text.substring(0, splitPosition);
    var second = element.createChild('div', 'second-part');
    second.textContent = text.substring(splitPosition);
    element.title = text;
  }

  /**
   * @override
   * @param {?number} itemIndex
   * @param {string} promptValue
   */
  selectItem(itemIndex, promptValue) {
    var parsedExpression = promptValue.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/);
    if (!parsedExpression)
      return;

    var lineNumber;
    var columnNumber;
    if (parsedExpression[2])
      lineNumber = parseInt(parsedExpression[2].substr(1), 10) - 1;
    if (parsedExpression[3])
      columnNumber = parseInt(parsedExpression[3].substr(1), 10) - 1;
    var uiSourceCode = itemIndex !== null ? this._uiSourceCodes[itemIndex] : null;
    this.uiSourceCodeSelected(uiSourceCode, lineNumber, columnNumber);
  }

  /**
   * @override
   * @param {string} query
   * @return {string}
   */
  rewriteQuery(query) {
    if (!query)
      return query;
    query = query.trim();
    var lineNumberMatch = query.match(/^([^:]+)((?::[^:]*){0,2})$/);
    this._queryLineNumberAndColumnNumber = lineNumberMatch ? lineNumberMatch[2] : '';
    return lineNumberMatch ? lineNumberMatch[1] : query;
  }

  /**
   * @param {!Common.Event} event
   */
  _uiSourceCodeAdded(event) {
    var uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data);
    if (!this._filterUISourceCode(uiSourceCode) || !this.filterProject(uiSourceCode.project()))
      return;
    this._uiSourceCodes.push(uiSourceCode);
    this.refresh();
  }

  /**
   * @override
   */
  dispose() {
    Workspace.workspace.removeEventListener(
        Workspace.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    Workspace.workspace.removeEventListener(Workspace.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
  }
};


text:
package org.ovirt.engine.ui.webadmin.section.main.presenter.popup.storage;

import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.uicommonweb.models.storage.RemoveStorageModel;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;

public class StorageRemovePopupPresenterWidget extends AbstractModelBoundPopupPresenterWidget<RemoveStorageModel, StorageRemovePopupPresenterWidget.ViewDef> {

    public interface ViewDef extends AbstractModelBoundPopupPresenterWidget.ViewDef<RemoveStorageModel> {
    }

    @Inject
    public StorageRemovePopupPresenterWidget(EventBus eventBus, ViewDef view) {
        super(eventBus, view);
    }

}


text:
<?php

defined('_JEXEC') or die;
ksort($this->files, SORT_STRING);
?>

	<?php foreach($this->files as $key => $value): ?>
		<?php if(is_array($value)): ?>

				<a class='folder-url nowrap' data-id='<?php echo base64_encode($key); ?>' href=''>
					 <?php $explodeArray = explode('/', $key); echo end($explodeArray); ?>

				<?php echo $this->folderTree($value); ?>

		<?php endif; ?>
	<?php endforeach; ?>


text:
/*
 * StepTest.cpp
 *
 *  Created on: Oct 27, 2015
 *      Author: Péter Fankhauser
 *	 Institute: ETH Zurich, Autonomous Systems Lab
 */

#include "free_gait_core/TypeDefs.hpp"
#include "free_gait_core/step/Step.hpp"

// gtest
#include <gtest/gtest.h>

using namespace free_gait;

TEST(step, initialization)
{
  Step step;
  ASSERT_FALSE(step.hasBaseMotion());
  ASSERT_FALSE(step.hasLegMotion());
  ASSERT_FALSE(step.hasLegMotion(LimbEnum::RF_LEG));
  Step stepCopy(step);
  ASSERT_FALSE(step.hasBaseMotion());
  ASSERT_FALSE(step.hasLegMotion());
  ASSERT_FALSE(step.hasLegMotion(LimbEnum::RF_LEG));
}


text:
package kafka.javaapi

import kafka.common.TopicAndPartition
import kafka.api.{Request, PartitionOffsetRequestInfo}
import scala.collection.mutable
import java.nio.ByteBuffer

class OffsetRequest(requestInfo: java.util.Map[TopicAndPartition, PartitionOffsetRequestInfo],
                    versionId: Short,
                    clientId: String) {

  val underlying = {
    import collection.JavaConversions._
    val scalaMap = (requestInfo: mutable.Map[TopicAndPartition, PartitionOffsetRequestInfo]).toMap
    kafka.api.OffsetRequest(
      requestInfo = scalaMap,
      versionId = versionId,
      clientId = clientId,
      replicaId = Request.OrdinaryConsumerId
    )
  }

  def writeTo(buffer: ByteBuffer) { underlying.writeTo(buffer) }

  def sizeInBytes = underlying.sizeInBytes

  override def toString = underlying.toString

  override def equals(other: Any) = canEqual(other) && {
    val otherOffsetRequest = other.asInstanceOf[kafka.javaapi.OffsetRequest]
    this.underlying.equals(otherOffsetRequest.underlying)
  }

  def canEqual(other: Any) = other.isInstanceOf[kafka.javaapi.OffsetRequest]

  override def hashCode = underlying.hashCode

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.adexchangebuyer2.v2beta1.model;

/**
 * A request for watching changes to creative Status.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Ad Exchange Buyer API II. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class WatchCreativeRequest extends com.google.api.client.json.GenericJson {

  /**
   * The Pub/Sub topic to publish notifications to. This topic must already exist and must give
   * permission to ad-exchange-buyside-reports@google.com to write to the topic. This should be the
   * full resource name in "projects/{project_id}/topics/{topic_id}" format.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String topic;

  /**
   * The Pub/Sub topic to publish notifications to. This topic must already exist and must give
   * permission to ad-exchange-buyside-reports@google.com to write to the topic. This should be the
   * full resource name in "projects/{project_id}/topics/{topic_id}" format.
   * @return value or {@code null} for none
   */
  public java.lang.String getTopic() {
    return topic;
  }

  /**
   * The Pub/Sub topic to publish notifications to. This topic must already exist and must give
   * permission to ad-exchange-buyside-reports@google.com to write to the topic. This should be the
   * full resource name in "projects/{project_id}/topics/{topic_id}" format.
   * @param topic topic or {@code null} for none
   */
  public WatchCreativeRequest setTopic(java.lang.String topic) {
    this.topic = topic;
    return this;
  }

  @Override
  public WatchCreativeRequest set(String fieldName, Object value) {
    return (WatchCreativeRequest) super.set(fieldName, value);
  }

  @Override
  public WatchCreativeRequest clone() {
    return (WatchCreativeRequest) super.clone();
  }

}


text:
package ch.randelshofer.gui.datatransfer;

import java.awt.datatransfer.*;
import java.io.IOException;
/**
 * StringTransferable.
 *

 * Note: This transferable should always be used in conjunction with
 * PlainTextTransferable.
 *

 * Usage:
 *

 * String text = "bla";
 * CompositeTransfer t = new CompositeTransferable();
 * t.add(new StringTransferable(text));
 * t.add(new PlainTextTransferable(text));
 *

 *
 * @author Werner Randelshofer
 * @version 1.0 22. August 2007 Created.
 */
public class StringTransferable extends AbstractTransferable {
    private String string;

    public StringTransferable(String string) {
        this(getDefaultFlavors(), string);
    }
    public StringTransferable(DataFlavor flavor, String string) {
        this(new DataFlavor[] { flavor }, string);
    }
    public StringTransferable(DataFlavor[] flavors, String string) {
        super(flavors);
        this.string = string;
    }

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (! isDataFlavorSupported(flavor)) {
            throw new UnsupportedFlavorException(flavor);
        }
        return string;
    }

    protected static DataFlavor[] getDefaultFlavors() {
        try {
            return new DataFlavor[] {
                new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType+";class=java.lang.String"),
                DataFlavor.stringFlavor
            };
        } catch (ClassNotFoundException cle) {
            InternalError ie = new InternalError(
                    "error initializing StringTransferable");
            ie.initCause(cle);
            throw ie;
        }
    }
}


text:
This is the source code for the National Data Catalog. The current version (v2) intended to be more social and more collaborative than v1.

## History

Version 1 of the National Data Catalog consisted of multiple applications (a Sinatra API, a Rails 2 web app, and many importers) that worked together.

This version (v2) is instead one combined Rails 3 application. This will make it easier to modify and maintain the application, plus it will be easier to customize and install if you want to run your own data catalog.

## Changes since Version 1

### Users

* Each User has a dedicated page.
* Each User page has an activity stream.
* Users can watch DataSets.
* Users can follow other Users.

### Sites

* Sites, external web sites that we import from, are top-level resources
* Sites have useful metadata describing their 'goodness' as data catalogs.

### Catalogs

* A Catalog is a grouping of DataSets.
* The application can contain multiple Catalogs.
* Each Catalog can be administered by its owners and curators.

### Organizations

* An Organization can group other Organizations when needed. Two examples are the "U.S. District Courts" and the "U.S. Executive Departments".

### DataSets

* DataSets can aggregate other DataSets. (This is a useful way to bundle up very similar DataSets, such as the Toxic Release Inventory data sets on Data.gov.)
* DataSets can be rated along three dimensions: Interestingness, Documentation Quality, and Data Quality.
* Users can suggest DataSets and provide as much metadata as they like.
* Users can suggest 'missing' DataSets.
* Added DataSet activity stream.
* DataSets can belong to more than one Catalog.

### Locations

* Locations, geographical locations, are top-level resources.
* Locations are hierarchical.
* Locations are a better way to convey the ideas of:
    * jurisdiction of an Organization
    * geographic coverage of a DataSet

## Installation / Setup

Just install the National Data Catalog like a typical Rails 3 application. Here are a few notes about parts that are less common:

1. We highly recommend that you use the [latest stable version of Ruby](http://www.ruby-lang.org/en/downloads/). As of this writing we are using 1.9.2p136. While the app may run on Ruby 1.8.7, we will not be developing or testing it for that environment.
    * We recommend installing a current version of the Ruby interpreter using [RVM, the Ruby Version Manager](http://rvm.beginrescueend.com/).
2. Download and run [MongoDB](http://mongodb.org).
3. Configure [Mongoid](http://mongoid.org).
    * Adjust `config/mongoid.yml` as necessary.
4. Install and run [Redis](http://code.google.com/p/redis/).
    * On Mac OS X, we recommend [homebrew](http://mxcl.github.com/homebrew/):
        * `brew install redis`
    * On Ubuntu 10.10, we recommend:
        * `sudo apt-get install redis-server`
5. Load data into the database:
    * For quicker testing:
        * `rake db:reset db:seed db:seed_examples`
    * For a full setup:
        * `rake db:reset db:seed db:seed_examples import:*`
6. Start the background processing system:
    * `QUEUE=* rake resque:work`
    * `rake resque:scheduler`
    * Optionally: `resque-web`
7. Start the Rails server:
    * `rails s`
8. Optional: if you are customizing or modifying the source code, fire up autotest:
    * `autotest`
9. Optional: if you want to use [spork](http://spork.rubyforge.org/) drb to speed up your tests:
    * Start spork:
        * `spork`
     * Run a spec:
        * `rspec --drb spec/models/organization_spec.rb`

## Notable Directories

Our directory structure follows the Rails conventions; however, we have a few differences that are worth highlighting:

1. [Sass](http://sass-lang.com) templates live in `app/sass` (which is different from the default location of `public/stylesheets/sass`). (Sass is extension of CSS3 that adds nested rules, variables, mixins, and selector inheritance.)
2. Importers (which import DataSets from external Sites) are kept in `lib/importers`.
3. Cached [gravatars](http://gravatar.com) live in `public/images/gravatars`.
4. Delayed processing logic (for [Resque](http://github.com/defunkt/resque)) lives in `lib/resque`.
5. Some [Mongoid](http://mongoid.org) models take advantage of [MongoDB's](http://mongodb.org) [map/reduce](http://www.mongodb.org/display/DOCS/MapReduce). The map and reduce functions live in javascript files located in `app/models/{model}/{method}`. Separating the javascript functions out of the ruby models is helpful to your text editor -- it allows for accurate syntax highlighting and [JSLint](http://www.jslint.com/) checking.


text:
package org.wso2.carbon.esb.mediator.test.call;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;

import static org.testng.Assert.assertTrue;

public class CallMediatorBlockingFailoverTestCase extends ESBIntegrationTest {

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init();
        loadESBConfigurationFromClasspath(
                "/artifacts/ESB/mediatorconfig/call/CallMediatorBlockingFailoverEndpointTest.xml");
    }

    @Test(groups = { "wso2.esb" })
    public void CallMediatorBlockingFailoverTestCase() throws AxisFault {

        OMElement response = axis2Client
                .sendSimpleStockQuoteRequest(getProxyServiceURLHttp("TestCallBlockingFailOverProxy"), null, "WSO2");
        boolean responseContainsWSO2 = response.getFirstElement().toString().contains("WSO2");
        assertTrue(responseContainsWSO2);
    }

    @AfterClass(alwaysRun = true)
    public void destroy() throws Exception {
        super.cleanup();
    }
}