text:
export declare type StreamDataSource = 'server' | 'client';
export declare class StreamDataError {
    static readonly DEFAULT_TYPE: string;
    static readonly DEFAULT_MESSAGE: string;
    static readonly DEFAULT_STATUS: number;
    static readonly DEFAULT_SOURCE: StreamDataSource;
    static createDefault(original: any): StreamDataError;
    type: string;
    message: string;
    status: number | string;
    source: string;
    original: any;
    constructor(type: string, message: string, status: number | string, source?: StreamDataSource, original?: any);
    /**
     * @memberOf StreamdataError#
     * @return {boolean} true if error is from server side.
     */
    readonly isServer: boolean;
    /**
     * @memberOf StreamdataError#
     * @return {boolean} true if error is from client side.
     */
    readonly isClient: boolean;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
	<cbid>CROMU_00001</cbid>
	<replay>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>hkjohjg\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>ginlsdd\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>zrpskrb\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>zmbtmfl\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>xtnbcxp\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>plztfyc\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>sobwqdh\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>gumsxee\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>hrcawtr\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>jgphtgk\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>gumsxee\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>5\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Logging out...\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Create User\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Login\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>2\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>username: </data></match></read>
		<write echo="ascii"><data>xtnbcxp\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Login Success\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>zmbtmfl\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>biexjahvvwtigvxhtejm\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>sobwqdh\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>givxipxdfi\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>1\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>To: </data></match></read>
		<write echo="ascii"><data>hkjohjg\n</data></write>
		<read echo="ascii"><delim> </delim><match><data>Message: </data></match></read>
		<write echo="ascii"><data>xfdrrrfdnzlsoogo\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>1) Send Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>2) Read Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>3) List Messages\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>4) Delete Message\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>5) Logout\n</data></match></read>
		<read echo="ascii"><delim>\n</delim><match><data>6) Exit\n</data></match></read>
		<read echo="ascii"><delim> </delim><match><data>: </data></match></read>
		<write echo="ascii"><data>6\n</data></write>
		<read echo="ascii"><delim>\n</delim><match><data>Exiting...\n</data></match></read>
	</replay>
</pov>


text:
import os
from pypi_server.cache import Cache, DAY
from tornado.gen import coroutine, Return
from tornado_xmlrpc.handler import XMLRPCHandler
from pypi_server.handlers import route, add_slash
from pypi_server.handlers.base import BaseHandler, threaded
from pypi_server.handlers.pypi.proxy.client import PYPIClient
from pypi_server.db.packages import Package, PackageVersion, PackageFile

@route(r'/simple/?')
@add_slash
class PackagesHandler(BaseHandler, XMLRPCHandler):
    @coroutine
    def get(self):
        self.render(
            os.path.join('simple', 'packages.html'),
            packages=(yield self.pkg_list())
        )

    @classmethod
    @threaded
    @Cache(5, files_cache=True, ignore_self=True)
    def pkg_list(cls):
        return list(Package.select().order_by(Package.lower_name))

    @classmethod
    @threaded
    @Cache(5)
    def rpc_package_releases(cls, package_name, show_hidden=False):
        package = Package.select().where(Package.name == package_name)
        return list(map(lambda x: str(x.name), package.versions()))

    @classmethod
    @threaded
    @Cache(5)
    def rpc_release_urls(cls, package_name, version):
        raise Return(
            list(
                map(
                    lambda x: "/".join((version, x.name)),
                    PackageFile.select().join(
                        Package
                    ).join(
                        PackageVersion
                    ).where(
                        Package.name == package_name,
                        PackageVersion.version == version
                    )
                )
            )
        )

    @classmethod
    @threaded
    @Cache(5)
    def rpc_list_packages(cls):
        return list(map(lambda x: x.name, Package.select()))

    @coroutine
    def rpc_search(self, query, operator='or'):
        results = []

        assert operator in ("and", "or"), "Operator must be 'and' or 'or'"

        names = tuple(query.get('name', []))
        descriptions = tuple(query.get('summary', []))

        async_queries = yield [
            self._search(names, descriptions, operator),
            PYPIClient.search(names, descriptions, operator)
        ]

        for res in async_queries:
            for result in res:
                results.append(result)

        raise Return(results)

    @classmethod
    @threaded
    @Cache(DAY, files_cache=True)
    def _search(cls, names, descriptions, operator):
        op_and = lambda x, y: x & y
        op_or = lambda x, y: x | y

        operator_func = ({'or': op_or, 'and': op_and}).get(operator.lower(), op_and)
        result = []

        packages = PackageVersion.select(
            Package.name,
            PackageVersion,
        ).join(Package).where(
            operator_func(
                Package.name in tuple(names),
                PackageVersion.description.contains(descriptions)
            )
        )

        for version in packages:
            pkg_dict = dict(
                name=version.package.name,
                version=str(version.version),
                summary=version.description,
                _pypi_ordering=1,
            )

            result.append(pkg_dict)

        return result


text:
<?php
namespace cii\web;

use Yii;
class User extends \yii\web\User {
	public function can($permissionName, $params = [], $allowCaching = true) {
        //grant all rights to super user
        if($this->getIdentity() && $this->getIdentity()->superadmin) {
			return true;
		}

        if(($manager = $this->getAuthManager()) === null) {
            return false;
        }

        if(!is_array($permissionName)) {
        	throw new \Exception('You have to pass an array to User->can');
        }

        list($packageId, $permission) = $permissionName;
        return $manager->checkAccess($this->getId(), $packageId, $permission, $params);
    }
}


text:
This sample renders a rotating cube on the screen with swapchain that uses an
extended colorspace if one is available. The use of extended swapchain
colorspaces is enabled by requesting the instance extensions
`VK_EXT_swapchain_colorspace` and `VK_KHR_get_surface_capabilities2`. The option
of using an extended colorspace is controlled by setting the extended swapchain
colorspace flag in `SampleOptions` with the function
`EnableExtendedSwapchainColorSpace`.


text:
"""Common classes and methods for managing persistent entities."""

__author__ = 'Pavel Simakov (psimakov@google.com)'

from counters import PerfCounter
from google.appengine.ext import db

# datastore performance counters
DB_QUERY = PerfCounter(
    'gcb-models-db-query',
    'A number of times a query()/all() was executed on a datastore.')
DB_GET = PerfCounter(
    'gcb-models-db-get',
    'A number of times an object was fetched from datastore.')
DB_PUT = PerfCounter(
    'gcb-models-db-put',
    'A number of times an object was put into datastore.')
DB_DELETE = PerfCounter(
    'gcb-models-db-delete',
    'A number of times an object was deleted from datastore.')

# String. Name of the safe key property used for data export.
SAFE_KEY_NAME = 'safe_key'

def delete(keys):
    """Wrapper around db.delete that counts entities we attempted to get."""
    DB_DELETE.inc(increment=_count(keys))
    return db.delete(keys)

def get(keys):
    """Wrapper around db.get that counts entities we attempted to get."""
    DB_GET.inc(increment=_count(keys))
    return db.get(keys)

def put(keys):
    """Wrapper around db.put that counts entities we attempted to put."""
    DB_PUT.inc(increment=_count(keys))
    return db.put(keys)

def _count(keys):
    # App engine accepts key or list of key; count entities found.
    return len(keys) if isinstance(keys, (list, tuple)) else 1

class ExportEntity(db.Expando):
    """An entity instantiated, but never saved; for data export only.

    Will not work with the webapp.
    """

    def __init__(self, *args, **kwargs):
        assert kwargs.get(SAFE_KEY_NAME)
        super(ExportEntity, self).__init__(*args, **kwargs)

    def get(self):
        raise NotImplementedError

    def put(self):
        raise NotImplementedError

class BaseEntity(db.Model):
    """A common class to all datastore entities."""

    # List of db.Property. The properties on this model that should be purged
    # before export via tools/etl.py because they contain private information
    # about a user. For fields that must be transformed rather than purged, see
    # BaseEntity.for_export().
    _PROPERTY_EXPORT_BLACKLIST = []

    @classmethod
    def all(cls, **kwds):
        DB_QUERY.inc()
        return super(BaseEntity, cls).all(**kwds)

    @classmethod
    def get(cls, keys):
        DB_GET.inc()
        return super(BaseEntity, cls).get(keys)

    @classmethod
    def get_by_key_name(cls, key_names):
        DB_GET.inc()
        return super(BaseEntity, cls).get_by_key_name(key_names)

    @classmethod
    def safe_key(cls, db_key, unused_transform_fn):
        """Creates a copy of db_key that is safe for export.

        Keys may contain sensitive user data, like the user_id of a users.User.
        This method takes a db_key for an entity that is the same kind as cls.
        It returns a new instance of a key for that same kind with any sensitive
        data irreversibly transformed.

        The suggested irreversible transformation is cls.hash. The
        transformation must take a value and a client-defined secret. It must be
        deterministic and nonreversible.

        Args:
            db_key: db.Key of the same kind as cls. Key containing original
                values.
            unused_transform_fn: function that takes a single argument castable
                to string and returns a transformed string of that user data
                that is safe for export. If no user data is sensitive, the
                identity transform should be used. Used in subclass
                implementations.

        Returns:
            db.Key of the same kind as cls with sensitive data irreversibly
            transformed.
        """
        assert cls.kind() == db_key.kind()
        return db_key

    def _get_export_blacklist(self):
        """Collapses all _PROPERTY_EXPORT_BLACKLISTs in the class hierarchy."""
        blacklist = []
        for klass in self.__class__.__mro__:
            if hasattr(klass, '_PROPERTY_EXPORT_BLACKLIST'):
                # Treat as module-protected.
                # pylint: disable-msg=protected-access
                blacklist.extend(klass._PROPERTY_EXPORT_BLACKLIST)
        return sorted(set(blacklist))

    def put(self):
        DB_PUT.inc()
        return super(BaseEntity, self).put()

    def delete(self):
        DB_DELETE.inc()
        super(BaseEntity, self).delete()

    def for_export(self, transform_fn):
        """Creates an ExportEntity populated from this entity instance.

        This method is called during export via tools/etl.py to make an entity
        instance safe for export via tools/etl.py when --privacy is passed. For
        this to obtain,

        1) Properties that need to be purged must be deleted from the instance.
           Subclasses can set these fields in _PROPERTY_EXPORT_BLACKLIST.
        2) Properties that need to be transformed should be modified in subclass
           implementations. In particular, properties with customizable JSON
           contents often need to be handled this way.

        Args:
            transform_fn: function that takes a single argument castable to
                string and returns a transformed string of that user data that
                is safe for export. If no user data is sensitive, the identity
                transform should be used.

        Returns:
            EventEntity populated with the fields from self, plus a new field
            called 'safe_key', containing a string representation of the value
            returned by cls.safe_key().
        """
        properties = {}

        # key is a reserved property and cannot be mutated; write to safe_key
        # instead, but refuse to handle entities that set safe_key themselves.
        # TODO(johncox): reserve safe_key so it cannot be used in the first
        # place?
        assert SAFE_KEY_NAME not in self.properties().iterkeys()
        properties[SAFE_KEY_NAME] = self.safe_key(self.key(), transform_fn)

        for name in self.properties():
            if name not in [prop.name for prop in self._get_export_blacklist()]:
                properties[name] = getattr(self, name)

        return ExportEntity(**properties)


text:
class ConfigFile
{
public:
   /// ctor
   ConfigFile();

   /// Loads configuration from given filename
   void Load(const std::string& filename);

   /// maps file extension to a color to use in file output
   unsigned int GetColorByExtension(const std::string& extensionWithoutDot) const;

private:
   /// parses single line of configuration file
   void ParseLine(std::string line);

   /// parses a line that contains a list of extensions
   void ParseExtensions(unsigned int colorIndex, std::string extensions);

private:
   /// mapping from file extension in lowercase to color number
   std::map<std::string, unsigned int> m_colorByExtension;
};


text:
const path = require('path');
const webpack = require('webpack');
const resolve = require('@talend/dynamic-cdn-webpack-plugin/src/resolve-pkg');
const buildFormUtils = require('@talend/react-forms/build-utils');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const mockBackend = require('./mockBackend/server');

/*
 * because we are in dev mode our webpack config do not detect cdn resources in the yarn.lock.
 * so we compute the path of the resources to copy.
 */

function getPath(pkg) {
	const pkgPath = resolve(pkg, { cwd: process.cwd() });
	if (!pkgPath) {
		console.error(`ValueError: can t find pkg of ${pkg}`);
	}
	return pkgPath
		.replace('main.js', '')
		.replace('lib/index.js', '')
		.replace('dist/bootstrap.js', '')
		.replace('dist/TalendIcons.js', '');
}

function getVersion(pkg) {
	return require(`${getPath(pkg)}/package.json`).version;
}

const PKGS = [
	'@talend/assets-api',
	'@talend/design-tokens',
	'@talend/design-system',
	'@talend/design-tokens',
	'@talend/react-bootstrap',
	'@talend/react-components',
	'@talend/react-containers',
	'@talend/react-cmf',
	'@talend/react-cmf-router',
	'@talend/react-dataviz',
	'@talend/react-faceted-search',
	'@talend/react-datagrid',
	'@talend/react-forms',
	'@talend/bootstrap-theme',
	'@talend/icons',
];

const to = pkg => path.relative(process.cwd(), path.resolve(`cdn/${pkg}/${getVersion(pkg)}/dist/`));
const patterns = PKGS.map(pkg => ({
	from: path.resolve(getPath(pkg), 'dist'),
	to: `${to(pkg)}/`,
	info: { minimized: true },
})).concat(buildFormUtils.getWebpackCopyConfig());

const webpackConfig = {
	plugins: [
		new CopyWebpackPlugin({ patterns }),
		new webpack.DefinePlugin({
			'process.env.ICONS_VERSION': JSON.stringify(getVersion('@talend/icons')),
		}),
	],
	output: {
		publicPath: process.env.BASENAME || '/',
	},
	devServer: {
		setupMiddlewares: (middlewares, devServer) => {
			mockBackend(devServer);
			return middlewares;
		},
		historyApiFallback: {
			index: `${process.env.BASENAME || '/'}index.html`,
		},
	},
};

module.exports = webpackConfig;


text:
using MonoGame.Extended;

namespace SeraphimEngine.Script
{
    /// <summary>
    /// Interface IScript
    /// </summary>
    public interface IScript : IUpdate, IDraw
    {
        /// <summary>
        /// Gets a value indicating whether this instance is running.
        /// </summary>
        /// <value><c>true</c> if this instance is running; otherwise, <c>false</c>.</value>
        bool IsRunning { get; }

        /// <summary>
        /// Gets a value indicating whether [run once].
        /// </summary>
        /// <value><c>true</c> if [run once]; otherwise, <c>false</c>.</value>
        bool RunOnce { get; }

        /// <summary>
        /// Starts this instance.
        /// </summary>
        /// <param name="runOnce">if set to <c>true</c> [run once].</param>
        void Start(bool runOnce = false);

        /// <summary>
        /// Stops this instance.
        /// </summary>
        void Stop();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background" >

    <!-- 申请退款界面 -->

    <com.huassit.imenu.android.view.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/navigationView" >

        <LinearLayout
            android:id="@+id/refund_layout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="10dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="退款内容:"
                android:textColor="#555555"
                android:textSize="18sp" />

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/defult_background_shape_stroke"
                android:padding="10dp" >

                <TextView
                    android:id="@+id/refund_store_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_toLeftOf="@+id/tishi"
                    android:singleLine="true"
                    android:text="松和日本料理"
                    android:textColor="#777777"
                    android:textSize="17sp" />

                <TextView
                    android:id="@+id/tishi"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="5dp"
                    android:layout_toLeftOf="@+id/refund_money"
                    android:text="退款金额"
                    android:textColor="#666666"
                    android:textSize="13sp" />

                <TextView
                    android:id="@+id/refund_money"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:text="350.00"
                    android:textColor="@color/orange"
                    android:textSize="13sp" />
            </RelativeLayout>

            <TextView
                android:id="@+id/refund"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="现金退还方式:"
                android:textColor="#555555"
                android:textSize="18sp" />

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/defult_background_shape_stroke"
                android:padding="10dp" >

                <TextView
                    android:id="@+id/refund_action"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:text="原路退回"
                    android:textColor="#666666" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@id/refund_action"
                    android:text="(3-5个工作日)"
                    android:textColor="#999999" />
            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="退款原因:"
                android:textColor="#555555"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="为了帮我们做的更好,请提交退款原因(至少选一项)"
                android:textColor="#555555"
                android:textSize="12sp" />

            <ListView
                android:id="@+id/return_reason_list"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/defult_background_shape_stroke" />

            <TextView
                android:id="@+id/submit"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/blue_button_shape"
                android:gravity="center"
                android:padding="10dp"
                android:text="申请退款"
                android:textColor="#FFF" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>


text:
<!DOCTYPE html>

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

    <title>Fejléc cím</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="source/jquery.fancybox.css?v=2.1.5" media="screen" />
    <link rel="stylesheet" type="text/css" href="source/helpers/jquery.fancybox-buttons.css?v=1.0.5" />

Hívj most

Írj üzenetet

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Hívj most

                        Rólunk

                        Szaktudás

                        Elérhetőség

Szaktudásunk
                        Képekben

Copyright ©


text:
from __future__ import print_function
import argparse
import json
import sys
from dateutil.parser import parse
from eet import EETRequest, EETConfig, config

def eet_file():
    parser = argparse.ArgumentParser(description='EET request through file')
    dic = 'CZ00000019'
    id_shop = 237
    id_register = '/5546/RO24'

    config_kwargs = {
        'url': config.DEFAULT_URL,
        'key': config.DEFAULT_KEY,
        'cert': config.DEFAULT_CERT,
        'dic_commission': None,
        'simple': False,
        'debug': False,

    }

    data = {
        'price_sum': 34113.00,
        'price_sum_normal_vat': 100,
        'normal_vat_sum': 21,
        'number': '0/6460/ZQ42',
    }

    parser.add_argument(
        '-c', '--config',
        help='Config file',
        type=argparse.FileType('r'),
        dest='config',
        default=None
    )

    parser.add_argument(
        '-d', '--dic',
        help='DIC',
        type=str,
        dest='dic',
        default=None
    )

    parser.add_argument(
        '--dic2',
        help='DIC commision',
        type=str,
        dest='dic2',
        default=None
    )

    parser.add_argument(
        '-s', '--shop',
        help='Shop id',
        type=str,
        dest='shop',
        default=None
    )

    parser.add_argument(
        '-r', '--register',
        help='Register id',
        type=str,
        dest='register',
        default=None
    )

    parser.add_argument(
        '-u', '--url',
        help='File with public key',
        type=str,
        dest='url',
        default=None
    )

    parser.add_argument(
        '-e', '--simple',
        help='If is in simple mode',
        type=bool,
        dest='simple',
        default=None
    )

    parser.add_argument(
        '--date',
        help='Datetime of transaction',
        type=str,
        dest='date',
        default=None
    )

    parser.add_argument(
        '-g', '--debug',
        help='Debug mode',
        type=str,
        dest='debug',
        default=None
    )

    parser.add_argument(
        '--key_file',
        help='File with private key',
        type=argparse.FileType('r'),
        dest='key_file',
        default=None
    )

    parser.add_argument(
        '--cert_file',
        help='File with public key',
        type=argparse.FileType('r'),
        dest='cert_file',
        default=None
    )

    parser.add_argument(
        '-o', '--output',
        help='File for output',
        dest='output',
        nargs='?',
        type=argparse.FileType('w'),
        default=sys.stdout
    )

    parser.add_argument(
        '-v', '--verbose',
        help='Verbose',
        default=False,
        dest='verbose',
        action='store_true'
    )

    parser.add_argument(
        '-t', '--test',
        help='Test',
        default=False,
        dest='test',
        action='store_true'
    )

    parser.add_argument(
        'data_file',
        help='File with data',
        nargs='?',
        type=argparse.FileType('r'),
        default=sys.stdin
    )

    args = parser.parse_args()
    if args.config:
        new_config = json.load(args.config)
        config_kwargs.update(new_config)
        if 'dic' in config_kwargs:
            dic = config_kwargs['dic']

        if 'shop' in config_kwargs:
            id_shop = config_kwargs['shop']

        if 'register' in config_kwargs:
            id_register = config_kwargs['register']

        if 'key' in new_config:
            config_kwargs['key'] = config_kwargs['key'].encode('utf8')

        if 'cert' in new_config:
            config_kwargs['cert'] = config_kwargs['cert'].encode('utf8')

    if args.dic:
        dic = args.dic

    if args.dic2:
        config_kwargs['dic_commission'] = args.dic2

    if args.shop:
        id_shop = args.shop

    if args.register:
        id_register = args.register

    if args.url:
        config_kwargs['url'] = args.url

    if args.key_file:
        config_kwargs['key'] = args.key_file.read().encode('utf8')

    if args.cert_file:
        config_kwargs['cert'] = args.cert_file.read().encode('utf8')

    if args.simple:
        config_kwargs['simple'] = args.simple

    if args.debug:
        config_kwargs['debug'] = args.debug

    if not args.test:
        data = json.load(args.data_file)

    if 'date' in data:
        data['date'] = parse(data['date'])

    if 'dic' in config_kwargs:
        del config_kwargs['dic']

    if 'id_shop' in config_kwargs:
        del config_kwargs['id_shop']

    if 'id_register' in config_kwargs:
        del config_kwargs['id_register']

    if 'shop' in config_kwargs:
        del config_kwargs['shop']

    if 'register' in config_kwargs:
        del config_kwargs['register']

    if args.verbose:
        print("Config: ", {
            'dic': dic,
            'id_shop': id_shop,
            'id_register': id_register,
            'kwargs': config_kwargs
        }, file=sys.stderr)
        print("Data: ", data, file=sys.stderr)

    c = EETConfig(
        dic, id_shop, id_register,
        **config_kwargs
    )
    request = EETRequest(c, **data)
    if args.verbose:
        print(request.serialize(), file=sys.stderr)

    response = request.send()
    if args.verbose:
        print(response.raw, file=sys.stderr)

    json.dump({
        'fik': response.fik,
        'bkp': response.bkp,
        'pkp': str(request.code.pkp),
        'error': response.error,
        'warnings': response.warnings
    }, args.output)

if __name__ == '__main__':
    eet_file()


text:
const React = require('react');
const ReactNative = require('react-native');
const {Component, } = React;
const {View, StyleSheet, } = ReactNative;

const StaticContainer = require('react-static-container');

const SceneComponent = (Props) => {
  const {shouldUpdated, ...props, } = Props;
  return <View {...props}>
      <StaticContainer shouldUpdate={shouldUpdated}>
        {props.children}
      </StaticContainer>
  </View>;
};

module.exports = SceneComponent;


text: ### Step 2


text:
package de.ninam.projects.launcher;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class LauncherConfig {
}


text:
package io.reactivej.dcf.common.protocol.leader;

import io.reactivej.dcf.common.topology.GlobalTopologyId;

public class StartTopology extends TopologyCommand {

    public StartTopology(GlobalTopologyId topologyId) {
        super(topologyId);
    }
}


text:
from ceph_deploy.exc import ExecutableNotFound
from ceph_deploy.lib import remoto

def executable_path(conn, executable):
    """
    Remote validator that accepts a connection object to ensure that a certain
    executable is available returning its full path if so.

    Otherwise an exception with thorough details will be raised, informing the
    user that the executable was not found.
    """
    executable_path = conn.remote_module.which(executable)
    if not executable_path:
        raise ExecutableNotFound(executable, conn.hostname)
    return executable_path

def is_systemd(conn):
    """
    Attempt to detect if a remote system is a systemd one or not
    by looking into ``/proc`` just like the ceph init script does::

        # detect systemd
        # SYSTEMD=0
        grep -qs systemd /proc/1/comm && SYSTEMD=1
    """
    return conn.remote_module.grep(
        'systemd',
        '/proc/1/comm'
    )

def is_upstart(conn):
    """
    This helper should only used as a fallback (last resort) as it is not
    guaranteed that it will be absolutely correct.
    """
    # it may be possible that we may be systemd and the caller never checked
    # before so lets do that
    if is_systemd(conn):
        return False

    # get the initctl executable, if it doesn't exist we can't proceed so we
    # are probably not upstart
    initctl = conn.remote_module.which('initctl')
    if not initctl:
        return False

    # finally, try and get output from initctl that might hint this is an upstart
    # system. On a Ubuntu 14.04.2 system this would look like:
    # $ initctl version
    # init (upstart 1.12.1)
    stdout, stderr, _ = remoto.process.check(
        conn,
        [initctl, 'version'],
    )
    result_string = b' '.join(stdout)
    if b'upstart' in result_string:
        return True
    return False

def enable_service(conn, service='ceph'):
    """
    Enable a service on a remote host depending on the type of init system.
    Obviously, this should be done for RHEL/Fedora/CentOS systems.

    This function does not do any kind of detection.
    """
    if is_systemd(conn):
        remoto.process.run(
            conn,
            [
                'systemctl',
                'enable',
                '{service}'.format(service=service),
            ]
        )
    else:
        remoto.process.run(
            conn,
            [
                'chkconfig',
                '{service}'.format(service=service),
                'on',
            ]
        )


text:
@interface PodsDummy_Pods_StemProjectKitTests : NSObject
@end
@implementation PodsDummy_Pods_StemProjectKitTests
@end


text:
/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Classes:
 |	SoReadError class.
 |
 |   Author(s)		: Paul S. Strauss
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#include <Inventor/SoInput.h>
#include <Inventor/errors/SoReadError.h>
#include <stdarg.h>

// Static variables declared in SoReadError.h:
SoType		SoReadError::classTypeId;
SoErrorCB	*SoReadError::handlerCB;
void		*SoReadError::cbData;

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns type id of instance.
//
// Use: public

SoType
SoReadError::getTypeId() const
//
////////////////////////////////////////////////////////////////////////
{
    return classTypeId;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Posts an error.
//
// Use: extender

void
SoReadError::post(const SoInput *in, const char *formatString ...)
//
////////////////////////////////////////////////////////////////////////
{
    SoReadError	error;
    SbString		str, locstr;

    // Same stuff as in base class
    char	buf[10000];
    va_list	ap;

    va_start(ap, formatString);
    vsprintf(buf, formatString, ap);
    va_end(ap);

    str  = "Inventor read error: ";
    str += buf;
    str += "\n";

    in->getLocationString(locstr);
    str += locstr;

    error.setDebugString(str.getString());
    error.handleError();
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns handler callback (and data) to use for a given instance.
//
// Use: protected, virtual

SoErrorCB *
SoReadError::getHandler(void *&data) const
//
////////////////////////////////////////////////////////////////////////
{
    data = cbData;
    return handlerCB;
}


text:
var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
var config = require('../conf');
var ListView = require('./common/__ListView');
Backbone.$ = $;

//** Category模型
var Category = Backbone.Model.extend({
	idAttribute: '_id',
	urlRoot: config.api.host + '/public/product/categories',
	defaults: {
	},
});
//** Category集合
var CategoryCollection = Backbone.Collection.extend({
	model: Category,
	url: config.api.host + '/public/product/categories',
});

//** 列表子视图
var CategoryListView = ListView.extend({

	el: '#list',
	template: _.template($('#tpl-category-item').html()),

	initialize: function(options){
		this.collection = new CategoryCollection();
		ListView.prototype.initialize.apply(this,options);
	},
	getNewItemView: function(model){
		var item = this.template({model: model.toJSON()});
		var $item = $(item);
		$item.find('img').attr('src', model.get('thumbnail'));
		return $item.html();
	},
});

//** 主视图
exports = module.exports = Backbone.View.extend({

	el: '#content',
	template: _.template($('#tpl-category-index').html()),

	initialize: function(options) {
		this.router = options.router;
		this.on('load', this.load, this);
	},

	events: {
		'scroll': 'scroll',
		'click .item': 'categoryView',
	},

	load: function() {
		var that = this;
		this.loaded = true;
		this.render();
		this.listView = new CategoryListView({
			el: '#list',
		});
		this.listView.trigger('load');
	},

	scroll: function() {
		this.listView.scroll();
		return false;
	},

	categoryView: function(evt){
		var id = this.$(evt.currentTarget).closest('.item').attr('id');
		this.router.navigate('/category/'+ id + '/products',{trigger: true});
		return false;
	},

	render: function() {
		this.$el.html(this.template());
		return this;
	},
});


text:
from __future__ import absolute_import, unicode_literals
from __future__ import division, print_function

from PhloxAR.core.image import Image
from PhloxAR.features.blob import BlobMaker
from PhloxAR.segmentation.segmentation_base import SegmentationBase

__all__ = [
    'MOGSegmentation'
]

class MOGSegmentation(SegmentationBase):
    """
    Background subtraction using mixture of gaussians.
    For each pixel store a set of gaussian distributions and try to fit new
    pixels into those distributions. One of the distributions will represent
    the background.

    history - length of the pixel history to be stored
    nMixtures - number of gaussian distributions to be stored per pixel
    backgroundRatio - chance of a pixel being included into the background model
    noiseSigma - noise amount
    learning rate - higher learning rate means the system will adapt faster to
    new backgrounds
    """

    _error = False
    _diff_img = None
    _color_img = None
    _model_img = None
    _ready = False

    # OpenCV default parameters
    history = 200
    nMixtures = 5
    backgroundRatio = 0.7
    noiseSigma = 15
    learningRate = 0.7
    bsMOG = None

    def __init__(self, history=200, nMixtures=5, backgroundRatio=0.7,
                 noiseSigma=15, learningRate=0.7):

        try:
            import cv2
        except ImportError:
            raise ImportError(
                "Cannot load OpenCV library which is required by SimpleCV")
        if not hasattr(cv2, 'BackgroundSubtractorMOG'):
            raise ImportError("A newer version of OpenCV is needed")

        self._error = False
        self._ready = False
        self._diff_img = None
        self._color_img = None
        self._blob_maker = BlobMaker()

        self.history = history
        self.nMixtures = nMixtures
        self.backgroundRatio = backgroundRatio
        self.noiseSigma = noiseSigma
        self.learningRate = learningRate

        self._bsmog = cv2.BackgroundSubtractorMOG(history, nMixtures,
                                                  backgroundRatio, noiseSigma)

    def add_image(self, img):
        """
        Add a single image to the segmentation algorithm
        """
        if img is None:
            return

        self._color_img = img
        self._diff_img = Image(
            self._bsmog.apply(img.cvnarray, None, self.learningRate),
            cv2image=True
        )
        self._ready = True
        return

    def is_ready(self):
        """
        Returns true if the camera has a segmented image ready.
        """
        return self._ready

    def is_error(self):
        """
        Returns true if the segmentation system has detected an error.
        Eventually we'll construct a syntax of errors so this becomes
        more expressive
        """
        return self._error  # need to make a generic error checker

    def reset_error(self):
        """
        Clear the previous error.
        """
        self._error = False
        return

    def reset(self):
        """
        Perform a reset of the segmentation systems underlying data.
        """
        self._model_img = None
        self._diff_img = None

    @property
    def raw_image(self):
        """
        Return the segmented image with white representing the foreground
        and black the background.
        """
        return self._diff_img

    @property
    def segmented_image(self, white_fg=True):
        """
        Return the segmented image with white representing the foreground
        and black the background.
        """
        return self._diff_img

    @property
    def segmented_blobs(self):
        """
        return the segmented blobs from the fg/bg image
        """
        ret = []
        if self._color_img is not None and self._diff_img is not None:
            ret = self._blob_maker.extract_from_binary(self._diff_img,
                                                       self._color_img)
        return ret

    def __getstate__(self):
        state = self.__dict__.copy()
        self._blob_maker = None
        self._diff_img = None
        del state['_blob_maker']
        del state['_diff_img']
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        self._blob_maker = BlobMaker()


text:
Template.home.rendered = function() {
  changePageTitle("Task & time management web app");
  triggerAnalytics();
};


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.Network;

    /// <summary>
    /// Defines values for PcError.
    /// </summary>
    public static class PcError
    {
        public const string InternalError = "InternalError";
        public const string AgentStopped = "AgentStopped";
        public const string CaptureFailed = "CaptureFailed";
        public const string LocalFileFailed = "LocalFileFailed";
        public const string StorageFailed = "StorageFailed";
    }
}


text:
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.PythonTools.Django.TemplateParsing {
    [Export(typeof(IClassifierProvider)), ContentType(TemplateTagContentType.ContentTypeName)]
    class TemplateClassifierProvider : TemplateClassifierProviderBase {
        [ImportingConstructor]
        public TemplateClassifierProvider(IContentTypeRegistryService contentTypeRegistryService, IClassificationTypeRegistryService classificationRegistry)
            : base(TemplateTagContentType.ContentTypeName, contentTypeRegistryService, classificationRegistry) {
        }
    }
}


text:
=====
Usage
=====

To use Bayes Logistic Regression in a project::

    import bayes_logistic

Methods
-------

.. currentmodule:: bayes_logistic

.. autofunction:: bayes_logistic_prob

.. autofunction:: get_pvalues

.. autofunction:: fit_bayes_logistic

======================
scikit-learn interface
======================

For an interface similar to scikit-learn the following classes can be used.

Classes
-------

.. autoclass:: BayesLogisticClassifier

.. autoclass:: BayesLogisticRegressor


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>urTeam - Tu web del deporte</title>
<link rel="shortcut icon" href="/images/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/groups.css">

	{{> navbar_template}}

Usuarios

		{{#foundUsers}}

{{username}} {{surname}} {{nickname}}

		{{/foundUsers}}

Comunidades

		{{#foundCommunities}}

{{name}}

		{{/foundCommunities}}

Events

		{{#foundEvents}}

{{name}}

		{{/foundEvents}}

 {{> footer_template}}


text:
#pragma once

#include "GridPositionsResolver.h"
#include "OrderIterator.h"
#include <wtf/HashMap.h>
#include <wtf/ListHashSet.h>

namespace WebCore {

typedef Vector<RenderBox*, 1> GridCell;
typedef Vector<Vector<GridCell>> GridAsMatrix;
typedef ListHashSet<size_t> OrderedTrackIndexSet;

class GridArea;
class GridPositionsResolver;
class RenderGrid;

class Grid final {
public:
    explicit Grid(RenderGrid&);

    unsigned numTracks(GridTrackSizingDirection) const;

    void ensureGridSize(unsigned maximumRowSize, unsigned maximumColumnSize);
    void insert(RenderBox&, const GridArea&);

    // Note that each in flow child of a grid container becomes a grid item. This means that
    // this method will return false for a grid container with only out of flow children.
    bool hasGridItems() const { return !m_gridItemArea.isEmpty(); }

    // FIXME: move this to SizingData once placeItemsOnGrid() takes it as argument.
    bool hasAnyOrthogonalGridItem() const { return m_hasAnyOrthogonalGridItem; }
    void setHasAnyOrthogonalGridItem(bool hasAnyOrthogonalGridItem) { m_hasAnyOrthogonalGridItem = hasAnyOrthogonalGridItem; }

    GridArea gridItemArea(const RenderBox& item) const;
    void setGridItemArea(const RenderBox& item, GridArea);

    GridSpan gridItemSpan(const RenderBox&, GridTrackSizingDirection) const;

    const GridCell& cell(unsigned row, unsigned column) const { return m_grid[row][column]; }

    int smallestTrackStart(GridTrackSizingDirection) const;
    void setSmallestTracksStart(int rowStart, int columnStart);

    unsigned autoRepeatTracks(GridTrackSizingDirection) const;
    void setAutoRepeatTracks(unsigned autoRepeatRows, unsigned autoRepeatColumns);

    void setAutoRepeatEmptyColumns(std::unique_ptr<OrderedTrackIndexSet>);
    void setAutoRepeatEmptyRows(std::unique_ptr<OrderedTrackIndexSet>);

    unsigned autoRepeatEmptyTracksCount(GridTrackSizingDirection) const;
    bool hasAutoRepeatEmptyTracks(GridTrackSizingDirection) const;
    bool isEmptyAutoRepeatTrack(GridTrackSizingDirection, unsigned) const;

    OrderedTrackIndexSet* autoRepeatEmptyTracks(GridTrackSizingDirection) const;

    OrderIterator& orderIterator() { return m_orderIterator; }

    void setNeedsItemsPlacement(bool);
    bool needsItemsPlacement() const { return m_needsItemsPlacement; };

private:
    friend class GridIterator;

    OrderIterator m_orderIterator;

    int m_smallestColumnStart { 0 };
    int m_smallestRowStart { 0 };

    unsigned m_autoRepeatColumns { 0 };
    unsigned m_autoRepeatRows { 0 };

    bool m_hasAnyOrthogonalGridItem { false };
    bool m_needsItemsPlacement { true };

    GridAsMatrix m_grid;

    HashMap<const RenderBox*, GridArea> m_gridItemArea;
    HashMap<const RenderBox*, size_t> m_gridItemsIndexesMap;

    std::unique_ptr<OrderedTrackIndexSet> m_autoRepeatEmptyColumns;
    std::unique_ptr<OrderedTrackIndexSet> m_autoRepeatEmptyRows;
};

class GridIterator {
    WTF_MAKE_NONCOPYABLE(GridIterator);
public:
    // |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
    // GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
    GridIterator(const Grid&, GridTrackSizingDirection, unsigned fixedTrackIndex, unsigned varyingTrackIndex = 0);

    RenderBox* nextGridItem();
    bool isEmptyAreaEnough(unsigned rowSpan, unsigned columnSpan) const;
    std::unique_ptr<GridArea> nextEmptyGridArea(unsigned fixedTrackSpan, unsigned varyingTrackSpan);

private:
    const GridAsMatrix& m_grid;
    GridTrackSizingDirection m_direction;
    unsigned m_rowIndex;
    unsigned m_columnIndex;
    unsigned m_childIndex;
};

} // namespace WebCore


text:
using System;
using SkidiKit.Core.NodeAction.Common;
using SkidiKit.Core.Signals;

namespace SkidiKit.Core.NodeAction.Instant
{
    public class SendSignal: ActionInstant
    {
        public ISignal Signal { get; }

        public SendSignal(ISignal signal)
        {
            Signal = signal;
        }

        public override NodeActionState StartAction(Drawable target)
        {
            DrawNode node = target as DrawNode;
            if (node == null)
                throw new ArgumentException("Send signal can be started only on DrawNode");
            return new SendSignalActionState(node, this);
        }
    }

    internal class SendSignalActionState: ActionInstantState
    {
        private readonly ISignal _signal;
        private readonly DrawNode _node;

        public SendSignalActionState(DrawNode target, SendSignal action) : base(target, action)
        {
            _signal = action.Signal;
            _node = target;
        }

        public override void Update(float time)
        {
            _node.SendSignal(_signal);
        }
    }
}


text:
import logging
logger = logging.getLogger(__name__)

import MySQLdb

class QAPIMysql(object):

    def __init__(self, host, port, db, user, passwd):
        self.__host = host
        self.__port = int(port)
        self.__db = db
        self.__user = user
        self.__passwd = passwd

    def __get_conncur(self):
        conn = MySQLdb.connect(host=self.__host,
                               port=self.__port,
                               user=self.__user,
                               passwd=self.__passwd,
                               db=self.__db)
        cur = conn.cursor()
        return conn, cur

    @staticmethod
    def __close_conncur(conn, cur):
        conn.commit()
        cur.close()
        conn.close()

    @staticmethod
    def __dict_factory(cur, row):
        dic = {}
        for idx, col in enumerate(cur.description):
            colname = col[0].lower()
            if isinstance(row[idx], bytes):
                dic[colname] = row[idx].decode('utf8')
            elif isinstance(row[idx], str) and 'None' in row[idx]:
                dic[colname] = None
            else:
                dic[colname] = row[idx]
        return dic

    def config_list(self):
        ret = []
        conn, cur = self.__get_conncur()
        try:
            cur.execute("SELECT `epId` FROM `qaconfig`;")
            for row in cur.fetchall():
                ret.append(row[0])
        except:
            raise
        self.__close_conncur(conn, cur)
        return ret

    def config_read(self, userid):
        ret = None
        conn, cur = self.__get_conncur()
        try:
            cur.execute("SELECT host, vhost, prefix, epId, passwd, token FROM qaconfig WHERE epId = '%s';"
                        % str(userid))
            for row in cur.fetchall():
                ret = self.__dict_factory(cur, row)
        except:
            raise
        self.__close_conncur(conn, cur)
        return ret


text:
<!doctype html>

<meta charset="utf-8">
<title></title>

<meta name="keywords" content="">

<meta name="twitter:title" content="">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://oliverychen.github.io/images/default-thumb.png">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="">

<meta property="og:url" content="http://oliverychen.github.io/pages/contact/">
<meta property="og:site_name" content="">

<meta property="og:image" content="http://oliverychen.github.io/images/default-thumb.png">

<link rel="canonical" href="http://oliverychen.github.io/pages/contact/">
<link href="http://oliverychen.github.io/feed.xml" type="application/atom+xml" rel="alternate" title=" Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://oliverychen.github.io/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="shortcut icon" href="http://oliverychen.github.io/favicon.ico">

<link rel="shortcut icon" href="http://oliverychen.github.io/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://oliverychen.github.io/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://oliverychen.github.io/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://oliverychen.github.io/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://oliverychen.github.io/images/apple-touch-icon-144x144-precomposed.png">

Home

Papers

Paintings

Contact

Oliver Y. Chén

For [investors].

For [admissions].


text:
package de.dailab.schaufenster.jpafilter.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface FilterQuery {
 String name()  default "";
 String jpql()  default "";
}


text:
local gears = require("gears")
local awful = require("awful")
awful.rules = require("awful.rules")
require("awful.autofocus")
-- Widget and layout library
wibox = require("wibox")
-- Theme handling library
beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")

local vicious = require("vicious")
-- }}}

-- {{{ Functions
-- {{{ Autostart applications
function run_once( cmd )
   findme = cmd
   first_space = cmd:find(" ")
   if first_space then
      findme = cmd:sub(0, first_space - 1)
   end
   awful.util.spawn_with_shell("pgrep -u $USER -x " .. findme .. " > /dev/null || (" .. cmd .. ")")
end
-- }}}
-- }}}

-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
    naughty.notify({ preset = naughty.config.presets.critical,
                     title = "Oops, there were errors during startup!",
                     text = awesome.startup_errors })
end

-- Handle runtime errors after startup
do
    local in_error = false
    awesome.connect_signal("debug::error", function (err)
        -- Make sure we don't go into an endless error loop
        if in_error then return end
        in_error = true

        naughty.notify({ preset = naughty.config.presets.critical,
                         title = "Oops, an error happened!",
                         text = err })
        in_error = false
    end)
end
-- }}}

-- {{{ Global variables
home_dir           = os.getenv("HOME")
config_dir         = home_dir .. "/.config/awesome"
script_dir         = config_dir .. "/scripts/"
theme_dir          = config_dir .. "/themes/"

terminal           = "roxterm"
editor             = "vim"
editor_cmd         = terminal .. " -e " .. editor
gui_editor         = "gvim"
music_player       = terminal .. " -e cmus"

-- Default modkey.
modkey = "Mod4"
altkey = "Mod1"

widgets = {}
-- }}}

-- {{{ Local variables
-- Table of layouts to cover with awful.layout.inc, order matters.
local layouts =
{
    awful.layout.suit.tile,
    awful.layout.suit.fair,
    awful.layout.suit.tile.left,
    awful.layout.suit.tile.top,
    awful.layout.suit.floating,
}

-- }}}

-- {{{ Theme & Wallpaper
beautiful.init("/home/bedmonds/.config/awesome/themes/dark-matter/theme.lua")
beautiful.wallpaper = "/home/bedmonds/.wallpaper"

if beautiful.wallpaper then
    for s = 1, screen.count() do
        gears.wallpaper.maximized(beautiful.wallpaper, s, true)
    end
end
-- }}}

-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {}
for s = 1, screen.count() do
    -- Each screen has its own tag table.
    tags[s] = awful.tag({ " WEB ", " TERMINAL ", " FILES ", " OTHER " }, s, layouts[1])
end
-- }}}

-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
   { "manual", terminal .. " -e man awesome" },
   { "edit config", editor_cmd .. " " .. awesome.conffile },
   { "restart", awesome.restart },
   { "quit", awesome.quit }
}

widgets.main_menu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon },
                                    { "open terminal", terminal }
                                  }
                        })

mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon,
                                     menu = widgets.main_menu })

-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}

-- {{{ Widget styling

-- Separators
spacer_left = wibox.widget.imagebox()
spacer_left:set_image( beautiful.left )
spacer = wibox.widget.imagebox()
spacer:set_image( beautiful.spr )
spacer_small = wibox.widget.imagebox()
spacer_small:set_image( beautiful.spr_small )

-- }}}

-- {{{ Wibox
-- Create a textclock widget

widgets.text_clock           = awful.widget.textclock()
widgets.tag_list             = {}
widgets.task_list            = {}
widgets.prompt_box           = awful.widget.prompt()
widgets.layout_box           = awful.widget.layoutbox(1)

widgets.tag_list.buttons = awful.util.table.join(
   awful.button({ }, 1, awful.tag.viewonly),
   awful.button({ modkey }, 1, awful.client.movetotag),
   awful.button({ }, 3, awful.tag.viewtoggle),
   awful.button({ modkey }, 3, awful.client.toggletag),
   awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end),
   awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end)
)

widgets.task_list.buttons = awful.util.table.join(
   awful.button({ }, 1, function (c)
      if c == client.focus then
         c.minimized = true
      else
         -- Without this, the following
         -- :isvisible() makes no sense
         c.minimized = false
         if not c:isvisible() then
            awful.tag.viewonly(c:tags()[1])
         end
         -- This will also un-minimize
         -- the client, if needed
            client.focus = c
            c:raise()
      end
   end),
   awful.button({ }, 3, function ()
      if instance then
         instance:hide()
         instance = nil
      else
         instance = awful.menu.clients({ width=250 })
      end
   end),
   awful.button({ }, 4, function ()
      awful.client.focus.byidx(1)
      if client.focus then client.focus:raise() end
   end),
   awful.button({ }, 5, function ()
      awful.client.focus.byidx(-1)
      if client.focus then client.focus:raise() end
   end)
)

widgets.layout_box:buttons(
   awful.util.table.join(
      awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end),
      awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
      awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end),
      awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)
   )
)

widgets.tag_list = awful.widget.taglist(1, awful.widget.taglist.filter.all, widgets.tag_list.buttons)

widgets.task_list = awful.widget.tasklist(1, awful.widget.tasklist.filter.currenttags, widgets.task_list.buttons)

-- Battery monitor
require ( 'laptop/batmon' )

-- Top bar
require( 'gui/top_bar' )

-- Bottom bar
require( 'gui/bottom_bar' )

-- }}}

-- Mouse bindings
require( 'bindings/mouse' )

-- Key bindings
require( 'bindings/keyboard' )

-- {{{ Rules
awful.rules.rules = {
   -- All clients will match this rule.
   { rule = { },
     properties = { border_width = beautiful.border.width,
                    border_color = beautiful.border.color_normal,
                    focus = awful.client.focus.filter,
                    keys = clientkeys,
                    buttons = clientbuttons } },
   { rule = { class = "pinentry" },
     properties = { floating = true } },
   { rule = { class = "gimp" },
     properties = { floating = true } },
    -- Set Firefox to always map on tags number 2 of screen 1.
    -- { rule = { class = "Firefox" },
    --   properties = { tag = tags[1][2] } },
    { rule = { class = "chromium-browser" },
      properties = { tag = tags[1][1] } },

}
-- }}}

-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c, startup)
    -- Enable sloppy focus
    c:connect_signal("mouse::enter", function(c)
        if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
            and awful.client.focus.filter(c) then
            client.focus = c
        end
    end)

    if not startup then
        -- Set the windows at the slave,
        -- i.e. put it at the end of others instead of setting it master.
        -- awful.client.setslave(c)

        -- Put windows in a smart way, only if they does not set an initial position.
        if not c.size_hints.user_position and not c.size_hints.program_position then
            awful.placement.no_overlap(c)
            awful.placement.no_offscreen(c)
        end
    end

    local titlebars_enabled = false
    -- {{{ Title Bars
    if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then
        -- buttons for the titlebar
        local buttons = awful.util.table.join(
                awful.button({ }, 1, function()
                    client.focus = c
                    c:raise()
                    awful.mouse.client.move(c)
                end),
                awful.button({ }, 3, function()
                    client.focus = c
                    c:raise()
                    awful.mouse.client.resize(c)
                end)
                )

        -- Widgets that are aligned to the left
        local left_layout = wibox.layout.fixed.horizontal()
        left_layout:add(awful.titlebar.widget.iconwidget(c))
        left_layout:buttons(buttons)

        -- Widgets that are aligned to the right
        local right_layout = wibox.layout.fixed.horizontal()
        right_layout:add(awful.titlebar.widget.floatingbutton(c))
        right_layout:add(awful.titlebar.widget.maximizedbutton(c))
        right_layout:add(awful.titlebar.widget.stickybutton(c))
        right_layout:add(awful.titlebar.widget.ontopbutton(c))
        right_layout:add(awful.titlebar.widget.closebutton(c))

        -- The title goes in the middle
        local middle_layout = wibox.layout.flex.horizontal()
        local title = awful.titlebar.widget.titlewidget(c)
        title:set_align("center")
        middle_layout:add(title)
        middle_layout:buttons(buttons)

        -- Now bring it all together
        local layout = wibox.layout.align.horizontal()
        layout:set_left(left_layout)
        layout:set_right(right_layout)
        layout:set_middle(middle_layout)

        awful.titlebar(c):set_widget(layout)
    end
    -- }}}
end)

client.connect_signal("focus", function(c)
                                   c.border_color = beautiful.border.color_focus
                                   c.border_width = beautiful.border.width
                               end)
client.connect_signal("unfocus", function(c)
                                   c.border_color = beautiful.border.color_normal
                                   c.border_width = beautiful.border.width
                               end)

-- }}}


text:
#include "pendulumsystem.hpp"

//! Default constructor sets default pendulum properties, and k = 1.0 for three attractors positioned at: \f$(-0.5, \sqrt{3}/2)\f$, \f$(-0.5, -\sqrt{3}/2)\f$, and \f$(1, 0)\f$.
PendulumSystem::PendulumSystem() :
  DISTANCE{0.05},
  MASS{1.0},
  GRAVITY{9.8},
  DRAG{0.2},
  LENGTH{10.0}
{
  attractorList.emplace_back(Attractor{-0.5, std::sqrt(3.0)/2.0, 1.0});
  attractorList.emplace_back(Attractor{-0.5, -std::sqrt(3.0)/2.0, 1.0});
  attractorList.emplace_back(Attractor{1.0, 0.0, 1.0});
}

//! Add an attractor at position (xPosition, yPosition) with attractive force coefficient forceCoeff.
void PendulumSystem::addAttractor(double xPosition, double yPosition, double forceCoeff = 1.0)
{
  attractorList.emplace_back(Attractor{xPosition, yPosition, forceCoeff});
}

//! Set new position and attraction strength for already existing attractor at an index.
void PendulumSystem::setAttractor(int index, double xPosition, double yPosition, double forceCoeff)
{
  attractorList[index].xPosition = xPosition;
  attractorList[index].yPosition = yPosition;
  attractorList[index].forceCoeff = forceCoeff;
}

//! Set all the attractor strengths to the same value.
void PendulumSystem::setAllAttractorStrengths(double forceCoeff)
{
  for (auto &attractor : attractorList) {
    attractor.forceCoeff = forceCoeff;
  }
}

//! Clear all attractors.
void PendulumSystem::clearAttractors()
{
  attractorList.clear();
}


text:
using System;

namespace HyperFastCgi.Helpers.FastCgiProtocol
{
	public enum Role : ushort
	{
		Responder = 1,
		Authorizer = 2,
		Filter = 3
	}

	[Flags]
	public enum BeginRequestFlags : byte
	{
		None = 0,
		KeepAlive = 1
	}

	public struct BeginRequestBody
	{

		#region Private Fields

		private Role role;
		private BeginRequestFlags flags;

		#endregion

		#region Constructors

		public BeginRequestBody (Record record)
		{
			if (record.Type != RecordType.BeginRequest)
				throw new ArgumentException (
					Strings.BeginRequestBody_WrongType,
					"record");

			if (record.BodyLength != 8)
				throw new ArgumentException (
					Strings.BeginRequestBody_WrongSize, "record");

			byte[] body = record.Body;
			role = (Role)Record.ReadUInt16 (body, 0);
			flags = (BeginRequestFlags)body [2];
		}

		public BeginRequestBody (byte[] body)
		{
			role = (Role)Record.ReadUInt16 (body, 0);
			flags = (BeginRequestFlags)body [2];
		}

		#endregion

		#region Public Properties

		public Role Role {
			get { return role; }
		}

		public BeginRequestFlags Flags {
			get { return flags; }
		}

		#endregion

	}
}


text:
package io.quarkus.qute.deployment.include;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.qute.TemplateException;
import io.quarkus.test.QuarkusUnitTest;

public class InsertTagConflictTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withApplicationRoot(root -> root
                    .addAsResource(new StringAsset("{#insert row}{/}"), "templates/base.html")
                    .addAsResource(new StringAsset("Nuke!"),
                            "templates/tags/row.html"))
            .assertException(t -> {
                Throwable e = t;
                TemplateException te = null;
                while (e != null) {
                    if (e instanceof TemplateException) {
                        te = (TemplateException) e;
                        break;
                    }
                    e = e.getCause();
                }
                assertNotNull(te);
                assertTrue(te.getMessage().contains(
                        "Parser error in template [base.html] line 1: {#insert} defined in the {#include} conflicts with an existing section/tag: row"),
                        te.getMessage());
            });;

    @Test
    public void test() {
        fail();
    }
}


text:
layout: page
weight: 0
title: v3 API Python Code Example
group: api-v3
navigation:
  show: true
---

<call-out>

We recommend using SendGrid Python, our client library, [available on GitHub](https://github.com/sendgrid/sendgrid-python), with full documentation.

</call-out>

<call-out>

Do you have an [API Key](https://app.sendgrid.com/settings/api_keys) yet? If not, go get one. You're going to need it to integrate!

</call-out>

## Using SendGrid's Python Library
```python
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
to_email = Email("test@example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "and easy to do anywhere, even with Python")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
```


text:
<?php

declare(strict_types=1);

namespace Zhiyi\Plus\API2\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Zhiyi\Plus\API2\Resources\UserCountsResource;
use Zhiyi\Plus\Models\UserCount as UserCountModel;

class UserCountsController extends Controller
{
    /**
     * Create the Controller instance.
     *
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * The route controller to callable handle.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function count(Request $request): JsonResponse
    {
        $counts = UserCountModel::query()->where('user_id', $request->user()->id)->get();
        $counts = $counts->keyBy('type')->map(function ($count) {
            return $count->total;
        });

        return (new UserCountsResource($counts->all()))
            ->response()
            ->setStatusCode(200);
    }

    /**
     * 重置某项为度数为0.
     * @Author   Wayne
     * @DateTime 2018-04-16
     * @Email    qiaobin@zhiyicx.com
     * @param    Request             $request [description]
     * @return   [type]                       [description]
     */
    public function reset(Request $request)
    {
        $type = $request->input('type');
        if ($type && in_array($type, ['commented', 'liked', 'system', 'group-post-pinned', 'post-comment-pinned', 'feed-comment-pinned', 'news-comment-pinned', 'post-pinned', 'mutual', 'following', 'group-join-pinned'])) {
            $type = 'user-'.$type;
        }

        UserCountModel::where('user_id', $request->user()->id)
            ->when($type, function ($query) use ($type) {
                return $query->where('type', $type);
            })
            ->update([
                'total' => 0,
                'read_at' => new Carbon(),
            ]);

        return response()->json('', 204);
    }
}


text:
// Copyright (c) Costin Morariu. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using RunKeeper.WinRT.HealthGraph.Infrastructure;

namespace RunKeeper.WinRT.HealthGraph.Activities
{
    public class History : INotifyPropertyChanged
    {
        #pragma warning disable CS0067
        // Is used by Fody to add NotifyPropertyChanged on properties.
        public event PropertyChangedEventHandler PropertyChanged;

        public IList<IGrouping<string, ActivityHistoryItemDto>> Items { get; private set; }

        private readonly IModelRepository _serverRepository;

        public History(IModelRepository serverRepository)
        {
            _serverRepository = serverRepository;
        }

        private string _resource;

        public void SetResource(string resource)
        {
            _resource = resource;
        }

        public async Task LoadAsync()
        {
            var nextPagePath = _resource;
            var history = new List<ActivityHistoryItemDto>();
            do
            {
                var page = await _serverRepository.ReadAsyc<ActivityHistoryPageDto>(nextPagePath);
                history.AddRange(page.Items);
                nextPagePath = page.NextPageUrl;
            } while (nextPagePath != null);

            Items = history.GroupBy(x => GetMonthGroupNameFor(x.StartTime))
                .ToList();
        }

        private static string GetMonthGroupNameFor(DateTime startTime)
        {
            return startTime.ToString("MMMM yyyy");
        }
    }
}


text:
<?php

App::import('Lib', 'Flour.init');
class FlourAppModel extends AppModel
{

	/**
	 * Name
	 *
	 * @var string $name
	 * @access public
	 */
	public $name = 'FlourAppModel';

	/**
	 * useDbConfig set explicitly to 'flour'
	 *
	 * @var string useDbConfig
	 * @access public
	 */
	public $useDbConfig = 'flour';

	/**
	 * Attached behaviors
	 *
	 * @var array
	 * @access public
	 */
	public $actsAs = array(
		'Flour.Flexible',
		// 'Flour.Editionable', //TODO: develop editionable behavior
	);

	/**
	 * flour beforeSave
	 *
	 * @access public
	 */
	public function beforeSave()
	{
		parent::beforeSave();
		$this->_addUserdata();
		return true;
	}

	/**
	 * flour soft delete
	 *
	 * @access public
	 */
	public function delete($id = null, $cascade = true) {
		if (!empty($id)) {
			$this->id = $id;
		}
		$id = $this->id;

		if(!$this->hasField('deleted')) {
			return parent::delete($id, $cascade);
		}

		$user = $this->_getUser();
		if($user) {
			$this->data[$this->alias]['deleted_by'] = $user;
		}
		$this->data[$this->alias]['deleted'] = date('Y-m-d H:i:s');

		// TODO: handle cascade delete / soft delete

		return $this->save($this->data);
	}

	/**
	 * flour undelete
	 *
	 * @access public
	 */
	public function undelete($id) {
		$this->id = $id;
		if(!$this->hasField('deleted') || !$this->exists()){
			return false;
		}
		$this->data = $this->read(null, $id);
		$this->_addUserData();
		$this->data[$this->alias]['deleted'] = null;
		$this->data[$this->alias]['deleted_by'] = null;

		return $this->save($this->data);
	}

	/**
	 * flour find
	 *
	 * @var array
	 * @access private
	 * @todo add missing params to fulfill the standard find() signature
	 */
	public function find($type, $options = array())
	{
		if (!isset($options['conditions']) ) {
			$options['conditions'] = array();
		}

		if (!isset($options['contain']) ) {
			// This kills all non-explicit contains like hasMany etc
			// $options['contain'] = array();
		}

		if (!isset($options['order']) ) {
			$options['order'] = array();
		}

		if($this->hasField('deleted') && ! isset($options['conditions'][$this->alias.'.'.$this->primaryKey])) {
			$options['conditions'][$this->alias.'.deleted'] = null;
		}

		switch ($type) {
			case 'active':
				$this->_setActive($options, $type);
				break;
			case 'current':
				$this->_setCurrent($options, $type);
				break;
			case 'editions':
				$this->_setEditions($options, $type);
				break;
			case 'deleted':
				$this->_setDeleted($options, $type);
				break;
		}
		return parent::find($type, $options);
	}

	/**
	 * flour find
	 *
	 * @var array
	 * @access private
	 * @todo add missing params to fulfill the standard find() signature
	 */
	function _setActive(&$options, &$type)
	{
		$this->_setValid($options, $type);
		$options['conditions'] = array_merge(
			$options['conditions'],
			array(
				$this->alias.'.status >' => 0,
			)
		);
		$type = (isset($options['conditions'][$this->alias.'.'.$this->primaryKey]))
			? 'first'
			: 'all';
	}

	/**
	 * undocumented function
	 *
	 * @param string $options
	 * @param string $type
	 * @return void
	 */
	function _setCurrent(&$options, &$type) {
		$slug = (isset($options['slug']))
			? $options['slug']
			: null;

		if(!empty($options['id']))
		{
			$this->id = $options['id'];
		}

		$this->_setValid($options, $type);

		// find all editions with inherited id
		if(isset($this->id) && empty($slug)) {
			$slug = $this->field('slug');
		}

		// find all editions with same slug by reference id:
		if(isset($options['conditions'][$this->alias.'.'.$this->primaryKey])) {
			$slug = $this->field('slug', $options['conditions']);
		}

		// find all editions with given slug
		if(isset($options['conditions'][$this->alias.'.slug'])) {
			$slug = $options['conditions'][$this->alias.'.slug'];
		}

		$options['conditions'] = array_merge(
			$options['conditions'],
			array(
				$this->alias.'.slug' => $slug,
				$this->alias.'.status >' => 0,
			)
		);
		$options['order'] = array_merge(
			$options['order'],
			array(
				$this->alias.'.valid_from' => 'DESC',
			)
		);
		$type = 'first';
	}

	/**
	 * undocumented function
	 *
	 * @param string $options
	 * @param string $type
	 * @return void
	 * @access public
	 */
	function _setEditions(&$options, &$type) {
		$slug = null;

		// find all editions with inherited id
		if(isset($this->id)) {
			$slug = $this->field('slug');
		}

		// find all editions with same slug by reference id:
		if(isset($options['conditions'][$this->alias.'.'.$this->primaryKey])) {
			$slug = $this->field('slug', $options['conditions']);
		}

		// find all editions with given slug
		if(isset($options['conditions'][$this->alias.'.slug'])) {
			$slug = $options['conditions'][$this->alias.'.slug'];
		}

		unset($options['conditions'][$this->alias.'.'.$this->primaryKey]);
		$options['conditions'] = array_merge(
			$options['conditions'],
			array(
				$this->alias.'.slug' => $slug,
			)
		);

		$type = 'all';
	}

	function _setDeleted(&$options, &$type) {
		unset($options['conditions'][$this->alias.'.deleted']);

		$options['conditions'] = array_merge(
			$options['conditions'],
			array( 'NOT' => array(
					$this->alias.'.deleted' => NULL
				),
			)
		);
		$type = 'all';
	}

	function _setValid(&$options, &$type) {
		if(!$this->hasField('valid_from') || !$this->hasField('valid_to')) {
			return;
		}
		$options['conditions'] = array_merge(
			$options['conditions'],
			array(
				'AND' => array(
					array(
						'OR' => array(
							$this->alias.'.valid_from <=' => date('Y-m-d H:i:s'),
							$this->alias.'.valid_from' => null,
						)
					),
					array(
						'OR' => array(
							$this->alias.'.valid_to >=' => date('Y-m-d H:i:s'),
							$this->alias.'.valid_to' => null,
						),
					),
				),
			)
		);
	}

	function _addUserData()
	{
		$user_id = $this->_getUser('id');
		if(!$user_id) return false;

		if(!isset($this->data[$this->alias][$this->primaryKey])) {
			$this->data[$this->alias]['user_id'] = $user_id;
			$this->data[$this->alias]['created_by'] = $user_id;
		}
		$this->data[$this->alias]['modified_by'] = $user_id;
	}

	function _getUser($field = null)
	{
		$user = Configure::read('Flour.User');
		if(!empty($user))
			return (isset($field))
				? $user[$field]
				: $user;

		$user = Configure::read('Auth.User');
		if(!empty($user))
			return (isset($field))
				? $user[$field]
				: $user;

/*
		//TODO: find UserClass, ask for user there.
		if(get_declared_classes())
		$user = Configure::read('Auth.User.id');
		if(!empty($user))
			return (isset($field))
				? $user[$field]
				: $user;
*/
		return false;
	}

	/**
	 * Customized paginateCount method (copied from CakeDC Tags.Taggable Plugin)
	 *
	 * @param array
	 * @param integer
	 * @param array
	 * @return void
	 * @access public
	 */
	public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) {
		$parameters = compact('conditions');
		if ($recursive != $this->recursive) {
			$parameters['recursive'] = $recursive;
		}
		if (isset($extra['type']) && isset($this->_findMethods[$extra['type']])) {
			$extra['operation'] = 'count';
			return $this->find($extra['type'], array_merge($parameters, $extra));
		} else {
			return $this->find('count', array_merge($parameters, $extra));
		}
	}

	/**
	 * Logs all errors in db to flour log, also logs $this->data to investigate the issue
	 *
	 * @return void
	 * @access public
	 */
	public function onError() {
		$db = ConnectionManager::getDataSource('flour');
		$err = $db->lastError();
		$this->log($err, 'flour');
		$this->log($this->data, 'flour');
	}
}


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/saesha/Desktop/SSRR13/Andreas/slam6d/src/scanio/scan_io_uos_rrgbt.cc" "/home/saesha/Desktop/SSRR13/Andreas/slam6d/build/src/scanio/CMakeFiles/scan_io_uos_rrgbt.dir/scan_io_uos_rrgbt.cc.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  "/home/saesha/Desktop/SSRR13/Andreas/slam6d/build/src/scanio/CMakeFiles/pointfilter.dir/DependInfo.cmake"
  )


text:
//[-------------------------------------------------------]
//[ Header guard                                          ]
//[-------------------------------------------------------]
#pragma once

//[-------------------------------------------------------]
//[ Includes                                              ]
//[-------------------------------------------------------]
#include "RendererToolkit/Private/AssetCompiler/IAssetCompiler.h"

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
namespace RendererToolkit
{

	//[-------------------------------------------------------]
	//[ Classes                                               ]
	//[-------------------------------------------------------]
	class SkeletonAssetCompiler final : public IAssetCompiler
	{

	//[-------------------------------------------------------]
	//[ Public definitions                                    ]
	//[-------------------------------------------------------]
	public:
		static constexpr uint32_t CLASS_ID = STRING_ID("RendererToolkit::SkeletonAssetCompiler");

	//[-------------------------------------------------------]
	//[ Public methods                                        ]
	//[-------------------------------------------------------]
	public:
		inline SkeletonAssetCompiler()
		{
			// Nothing here
		}

		inline virtual ~SkeletonAssetCompiler() override
		{
			// Nothing here
		}

	//[-------------------------------------------------------]
	//[ Public virtual RendererToolkit::IAssetCompiler methods ]
	//[-------------------------------------------------------]
	public:
		[[nodiscard]] inline virtual AssetCompilerClassId getAssetCompilerClassId() const override
		{
			return CLASS_ID;
		}

		[[nodiscard]] inline virtual std::string_view getOptionalUniqueAssetFilenameExtension() const override
		{
			// Multiple source asset filename extensions, so no unique source asset filename extension here
			return "";
		}

		[[nodiscard]] virtual std::string getVirtualOutputAssetFilename(const Input& input, const Configuration& configuration) const override;
		[[nodiscard]] virtual bool checkIfChanged(const Input& input, const Configuration& configuration) const override;
		virtual void compile(const Input& input, const Configuration& configuration) const override;

	};

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
} // RendererToolkit


text:
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

def GetRGBColor(colorName):
    '''
        Return the red, green and blue components for a
        color as doubles.
    '''
    rgb = [0.0, 0.0, 0.0]  # black
    vtk.vtkNamedColors().GetColorRGB(colorName, rgb)
    return rgb

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# create implicit function primitives
cone = vtk.vtkCone()
cone.SetAngle(20)

vertPlane = vtk.vtkPlane()
vertPlane.SetOrigin(.1, 0, 0)
vertPlane.SetNormal(-1, 0, 0)

basePlane = vtk.vtkPlane()
basePlane.SetOrigin(1.2, 0, 0)
basePlane.SetNormal(1, 0, 0)

iceCream = vtk.vtkSphere()
iceCream.SetCenter(1.333, 0, 0)
iceCream.SetRadius(0.5)

bite = vtk.vtkSphere()
bite.SetCenter(1.5, 0, 0.5)
bite.SetRadius(0.25)

# combine primitives to build ice-cream cone
theCone = vtk.vtkImplicitBoolean()
theCone.SetOperationTypeToIntersection()
theCone.AddFunction(cone)
theCone.AddFunction(vertPlane)
theCone.AddFunction(basePlane)

theCream = vtk.vtkImplicitBoolean()
theCream.SetOperationTypeToDifference()
theCream.AddFunction(iceCream)
theCream.AddFunction(bite)

# iso-surface to create geometry
theConeSample = vtk.vtkSampleFunction()
theConeSample.SetImplicitFunction(theCone)
theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25)
theConeSample.SetSampleDimensions(60, 60, 60)
theConeSample.ComputeNormalsOff()

theConeSurface = vtk.vtkMarchingContourFilter()
theConeSurface.SetInputConnection(theConeSample.GetOutputPort())
theConeSurface.SetValue(0, 0.0)

coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInputConnection(theConeSurface.GetOutputPort())
coneMapper.ScalarVisibilityOff()

coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)
coneActor.GetProperty().SetColor(GetRGBColor('chocolate'))

# iso-surface to create geometry
theCreamSample = vtk.vtkSampleFunction()
theCreamSample.SetImplicitFunction(theCream)
theCreamSample.SetModelBounds(0, 2.5, -1.25, 1.25, -1.25, 1.25)
theCreamSample.SetSampleDimensions(60, 60, 60)
theCreamSample.ComputeNormalsOff()

theCreamSurface = vtk.vtkMarchingContourFilter()
theCreamSurface.SetInputConnection(theCreamSample.GetOutputPort())
theCreamSurface.SetValue(0, 0.0)

creamMapper = vtk.vtkPolyDataMapper()
creamMapper.SetInputConnection(theCreamSurface.GetOutputPort())
creamMapper.ScalarVisibilityOff()

creamActor = vtk.vtkActor()
creamActor.SetMapper(creamMapper)
creamActor.GetProperty().SetColor(GetRGBColor('mint'))

# Add the actors to the renderer, set the background and size
#
ren1.AddActor(coneActor)
ren1.AddActor(creamActor)
ren1.SetBackground(1, 1, 1)

renWin.SetSize(250, 250)

ren1.ResetCamera()
ren1.GetActiveCamera().Roll(90)
ren1.GetActiveCamera().Dolly(1.5)
ren1.ResetCameraClippingRange()

iren.Initialize()

# render the image
#
renWin.Render()

#iren.Start()


text: {{+partials.standard_extensions_api api:apis.notifications intro:intros.notifications/}}


text:
'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _SvgIcon = require('../../SvgIcon');

var _SvgIcon2 = _interopRequireDefault(_SvgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ActionHighlightOff = function ActionHighlightOff(props) {
  return _react2.default.createElement(
    _SvgIcon2.default,
    props,
    _react2.default.createElement('path', { d: 'M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z' })
  );
};
ActionHighlightOff = (0, _pure2.default)(ActionHighlightOff);
ActionHighlightOff.displayName = 'ActionHighlightOff';
ActionHighlightOff.muiName = 'SvgIcon';

exports.default = ActionHighlightOff;


text:
require 'active_record'

module Starter
  module Templates
    module ActiveRecord
      def model_klass
        'ActiveRecord::Base'
      end

      def initializer
        <<-FILE.strip_heredoc
        # frozen_string_literal: true

        require 'yaml'
        require 'erb'
        require 'active_record'

        config_content = File.read(File.join('config', 'database.yml'))

        db_conf = YAML.safe_load(ERB.new(config_content).result)
        env = ENV['RACK_ENV'] || 'development'

        ActiveRecord::Base.establish_connection db_conf[env]
        logger = if %w[development test].include? env
                   log_dir = File.join(Dir.getwd, 'log')
                   log_file = File.join(log_dir, 'db.log')
                   FileUtils.mkdir(log_dir) unless Dir.exist?(log_dir)
                   Logger.new(File.open(log_file, 'a'))
                 else
                   Logger.new($stdout)
                 end

        ActiveRecord::Base.logger = logger

        # Middleware
        module ActiveRecord
          module Rack
            # ActiveRecord >= 5 removes the Pool management
            class ConnectionManagement
              def initialize(app)
                @app = app
              end

              def call(env)
                response = @app.call(env)
                response[2] = ::Rack::BodyProxy.new(response[2]) do
                  ActiveRecord::Base.clear_active_connections!
                end

                return response
              rescue StandardError
                ActiveRecord::Base.clear_active_connections!
                raise
              end
            end
          end
        end
        FILE
      end

      def rakefile
        <<-FILE.strip_heredoc
        # ActiveRecord migration tasks
        require 'active_record'
        include ActiveRecord::Tasks
        config_dir = File.expand_path('../config', __FILE__)
        config_content = File.join(config_dir, 'database.yml')
        DatabaseTasks.env = ENV['RACK_ENV'] || 'development'
        DatabaseTasks.database_configuration = YAML.load_file(config_content)
        DatabaseTasks.db_dir = 'db'
        DatabaseTasks.migrations_paths = File.join('db', 'migrate')

        ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
        ActiveRecord::Base.establish_connection DatabaseTasks.env.to_sym

        load 'active_record/railties/databases.rake'
        FILE
      end

      def gemfile
        <<-FILE.strip_heredoc
        # DB stuff
        gem 'activerecord', '>= 6'
        gem 'pg'
        FILE
      end

      def migration(klass_name, resource)
        version = "#{::ActiveRecord::VERSION::MAJOR}.#{::ActiveRecord::VERSION::MINOR}"
        <<-FILE.strip_heredoc
        class Create#{klass_name} < ActiveRecord::Migration[#{version}]
          def change
            create_table :#{resource} do |t|

              t.timestamps
            end
          end
        end
        FILE
      end
    end
  end
end