text:
This plugin allows you to specify a set of tools to manage inline styles on React elements.

## How to use
* Install plugin
```
npm install --save gluestick-plugin-radium
```
* Define (and configure) plugin in `src/gluestick.plugins.js`:
```javascript
export default [
  'gluestick-plugin-radium'
]
```

## Example usage
```javascript
import React, { Component } from "react";

export default class Home extends Component {
  render () {
    return (
        <div style={styles.base}>Home</div>
    );
  }
}

const styles = {
  base: {
    color: "blue",
  },
};
```


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="org.xdty.authenticator.ExportActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/export_text"
            android:text="@string/export_key_to_storage"
            android:padding="10dp"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/export_button"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="@string/export_button_text" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/import_text"
            android:text="@string/import_key_from_storage"
            android:padding="10dp"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/import_button"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="@string/import_button_text"
            android:layout_below="@+id/export_button"/>
    </LinearLayout>
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserService} from './browser_service.js';
import {HistoryQuery, HistoryEntry, QueryResult} from './externs.js';
import {QueryState} from './externs.js';

Polymer({
  is: 'history-query-manager',

  properties: {
    /** @type {QueryState} */
    queryState: {
      type: Object,
      notify: true,
      value() {
        return {
          // Whether the most recent query was incremental.
          incremental: false,
          // A query is initiated by page load.
          querying: true,
          searchTerm: '',
        };
      },
    },

    /** @type {QueryResult} */
    queryResult: {
      type: Object,
      notify: true,
    },

    /** @type {?HistoryRouterElement} */
    router: Object,
  },

  observers: [
    'searchTermChanged_(queryState.searchTerm)',
  ],

  /** @private {!Object<string, !function(!Event)>} */
  documentListeners_: {},

  /** @override */
  attached() {
    this.documentListeners_['change-query'] = this.onChangeQuery_.bind(this);
    this.documentListeners_['query-history'] = this.onQueryHistory_.bind(this);

    for (const e in this.documentListeners_) {
      document.addEventListener(e, this.documentListeners_[e]);
    }
  },

  /** @override */
  detached() {
    for (const e in this.documentListeners_) {
      document.removeEventListener(e, this.documentListeners_[e]);
    }
  },

  initialize() {
    this.queryHistory_(false /* incremental */);
  },

  /**
   * @param {boolean} incremental
   * @private
   */
  queryHistory_(incremental) {
    this.set('queryState.querying', true);
    this.set('queryState.incremental', incremental);

    const browserService = BrowserService.getInstance();
    const promise = incremental ?
        browserService.queryHistoryContinuation() :
        browserService.queryHistory(this.queryState.searchTerm);
    // Ignore rejected (cancelled) queries.
    promise.then(result => this.onQueryResult_(result), () => {});
  },

  /**
   * @param {!Event} e
   * @private
   */
  onChangeQuery_(e) {
    const changes = /** @type {{search: ?string}} */ (e.detail);
    let needsUpdate = false;

    if (changes.search !== null &&
        changes.search !== this.queryState.searchTerm) {
      this.set('queryState.searchTerm', changes.search);
      needsUpdate = true;
    }

    if (needsUpdate) {
      this.queryHistory_(false);
      if (this.router) {
        this.router.serializeUrl();
      }
    }
  },

  /**
   * @param {!Event} e
   * @private
   */
  onQueryHistory_(e) {
    this.queryHistory_(/** @type {boolean} */ (e.detail));
    return false;
  },

  /**
   * @param {{info: !HistoryQuery,
   *          value: !Array<!HistoryEntry>}} results List of results with
   *     information about the query.
   * @private
   */
  onQueryResult_(results) {
    this.set('queryState.querying', false);
    this.set('queryResult.info', results.info);
    this.set('queryResult.results', results.value);
    this.fire('query-finished');
  },

  /** @private */
  searchTermChanged_() {
    // TODO(tsergeant): Ignore incremental searches in this metric.
    if (this.queryState.searchTerm) {
      BrowserService.getInstance().recordAction('Search');
    }
  },
});


text:
title: Bulgaria
published: true
featured_image_path:
featured_image_attribution:
geocode: BGR
iso_code: BG
territory: false
state_party: true
signed_but_not_ratified: false
signed_date: 1999-02-10T00:00:00.000Z
ratified_or_acceded_date: 2002-04-11T00:00:00.000Z
entry_into_force_date: 2002-07-01T00:00:00.000Z
ratified_apic_date: 2006-07-28T00:00:00.000Z
genocide: '[Bulgarian Criminal Code, Chapter 14, Article 416](https://iccdb.hrlc.net/data/doc/172/keyword/46/)'
crimes_against_humanity: '[Bulgarian Criminal Code, Chapter 14, Article 417-418](https://iccdb.hrlc.net/data/doc/172/keyword/1/)'
aggression: '[Bulgarian Criminal Code, Chapter 14, Article 409](https://iccdb.hrlc.net/data/doc/172/keyword/1/)'
war_crimes: '[Bulgarian Criminal Code, Chapter 14, Articles 410-412, 414-415](https://iccdb.hrlc.net/data/doc/172/keyword/145/)'
note:
slug: bulgaria
---


text:
package pl.java.scalatech.common;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.assertj.core.util.Maps;
import org.junit.Before;

import com.google.common.collect.Lists;

import pl.java.scalatech.pojo.Person;

public abstract class DataPrepareTest {
    protected List<Person> persons;
    protected List<Integer> values = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    protected Map<Integer, Person> maps = Maps.newHashMap();
    protected Random random = new Random();
    protected List<String> names = Lists.newArrayList("slawek", "bak", "agnieszka", "slawek", "bak", "bak", "tyson");

    @Before
    public void init() {
        persons = Lists.newArrayList(new Person("slawek", "przodownik", new BigDecimal(12)), new Person("slawek", "przodownik2", new BigDecimal(23)),
                new Person("aga", "poka", new BigDecimal(6)), new Person("kalina", "bak", new BigDecimal(13)));
        maps.put(1, new Person("slawek", "przodownik", new BigDecimal(12)));
        maps.put(2, new Person("slawek", "przodownik2", new BigDecimal(23)));
        maps.put(3, new Person("aga", "poka", new BigDecimal(6)));
        maps.put(4, new Person("kalina", "bak", new BigDecimal(13)));
    }
}


text:
package csdn.shimiso.eim.activity;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import csdn.shimiso.eim.manager.XmppConnectionManager;

/**
 *
 * ÍêÕûµÄÍ˳öÓ¦ÓÃ.
 *
 * @author shimiso
 */
public class EimApplication extends Application {
	private List<Activity> activityList = new LinkedList<Activity>();

	// Ìí¼ÓActivityµ½ÈÝÆ÷ÖÐ
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	// ±éÀúËùÓÐActivity²¢finish
	public void exit() {
		XmppConnectionManager.getInstance().disconnect();
		for (Activity activity : activityList) {
			activity.finish();
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/comment_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="@dimen/xc_article_padding">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/xc_article_padding"
            android:paddingLeft="@dimen/xc_article_padding"
            android:paddingRight="@dimen/xc_article_padding"
            android:paddingTop="@dimen/xc_article_padding"
            android:text="热门榜单-HotRanking" />

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="1.0px"
            android:contentDescription="@null"
            android:paddingLeft="@dimen/xc_article_padding"
            android:paddingRight="@dimen/xc_article_padding"
            android:scaleType="fitXY"
            android:src="@color/divider" />
    </LinearLayout>

    <com.huijimuhe.commonlayout.widget.NoScrollRecyclerView
        android:id="@+id/hot_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent"
        android:divider="@android:color/transparent"
        android:dividerHeight="0.0dip"
        android:fadingEdge="none"
        android:fadingEdgeLength="0.0dip"
        android:listSelector="@android:color/transparent"
        android:paddingLeft="7.0dip"
        android:paddingRight="7.0dip"
        android:scrollbars="none" />
</LinearLayout>


text:
package org.unitils.orm.common.util;

import java.lang.reflect.Method;
import java.util.Set;

import org.unitils.core.util.ResourceConfig;

/**
 * Object wrapping all configuration needed for defining a persistence unit for a test object
 *
 * @author Filip Neven
 * @author Tim Ducheyne
 */
public class OrmConfig implements ResourceConfig {

	/**
	 * Config files used for configuring this ORM persistence unit
	 */
	private Set<String> configFiles;

	/**
	 * Custom configuration method that performs additional programmatic configuration
	 */
	private Method configMethod;

	/**
	 * Creates a new instance
	 *
	 * @param configFiles
	 * @param configMethod
	 */
	public OrmConfig(Set<String> configFiles, Method configMethod) {
		this.configFiles = configFiles;
		this.configMethod = configMethod;
	}

	public Set<String> getConfigFiles() {
		return configFiles;
	}

	public Method getConfigMethod() {
		return configMethod;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((configFiles == null) ? 0 : configFiles.hashCode());
		result = prime * result
				+ ((configMethod == null) ? 0 : configMethod.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final OrmConfig other = (OrmConfig) obj;
		if (configFiles == null) {
			if (other.configFiles != null)
				return false;
		} else if (!configFiles.equals(other.configFiles))
			return false;
		if (configMethod == null) {
			if (other.configMethod != null)
				return false;
		} else if (!configMethod.equals(other.configMethod))
			return false;
		return true;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Mozlite.Data.Metadata;
using Mozlite.Data.Query;

namespace Mozlite.Data.Internal
{
    /// <summary>
    /// 实体数据库操作基类。
    /// </summary>
    /// <typeparam name="TModel">实体模型。</typeparam>
    public abstract class RepositoryBase<TModel> : IRepositoryBase<TModel>
    {
        /// <summary>
        /// 日志接口。
        /// </summary>
        protected ILogger Logger { get; }

        /// <summary>
        /// SQL辅助接口。
        /// </summary>
        protected ISqlHelper SqlHelper { get; }

        /// <summary>
        /// 脚本生成接口。
        /// </summary>
        protected ISqlGenerator SqlGenerator { get; }
        private readonly IExecutor _executor;
        /// <summary>
        /// 当前模型的实体类型。
        /// </summary>
        protected IEntityType Entity { get; }

        /// <summary>
        /// 初始化类<see cref="RepositoryBase{TModel}"/>。
        /// </summary>
        /// <param name="executor">数据库执行接口。</param>
        /// <param name="logger">日志接口。</param>
        /// <param name="entityType">模型实例接口。</param>
        /// <param name="sqlHelper">SQL辅助接口。</param>
        /// <param name="sqlGenerator">脚本生成器。</param>
        protected RepositoryBase(IExecutor executor, ILogger logger, IEntityType entityType, ISqlHelper sqlHelper, ISqlGenerator sqlGenerator)
        {
            Logger = logger;
            SqlHelper = sqlHelper;
            SqlGenerator = sqlGenerator;
            _executor = executor;
            Entity = entityType;
        }

        /// <summary>
        /// 执行没有返回值的查询实例对象。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="parameters">参数实例对象。</param>
        /// <param name="commandType">命令类型。</param>
        /// <returns>返回是否有执行影响到数据行。</returns>
        public bool ExecuteNonQuery(string commandText, object parameters = null,
                CommandType commandType = CommandType.Text)
            => _executor.ExecuteNonQuery(commandText, parameters, commandType);

        /// <summary>
        /// 查询实例对象。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="parameters">参数实例对象。</param>
        /// <param name="commandType">命令类型。</param>
        /// <returns>返回数据库读取实例接口。</returns>
        public DbDataReader ExecuteReader(string commandText, object parameters = null, CommandType commandType = CommandType.Text)
            => _executor.ExecuteReader(commandText, parameters, commandType);

        /// <summary>
        /// 查询数据库聚合值。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="parameters">参数实例对象。</param>
        /// <param name="commandType">命令类型。</param>
        /// <returns>返回聚合值实例对象。</returns>
        public object ExecuteScalar(string commandText, object parameters = null, CommandType commandType = CommandType.Text)
            => _executor.ExecuteScalar(commandText, parameters, commandType);

        /// <summary>
        /// 执行SQL语句。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="parameters">参数匿名类型。</param>
        /// <param name="commandType">SQL类型。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回影响的行数。</returns>
        public Task<bool> ExecuteNonQueryAsync(string commandText, object parameters = null, CommandType commandType = CommandType.Text,
            CancellationToken cancellationToken = new CancellationToken())
            => _executor.ExecuteNonQueryAsync(commandText, parameters, commandType, cancellationToken);

        /// <summary>
        /// 执行SQL语句。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="commandType">SQL类型。</param>
        /// <param name="parameters">参数匿名类型。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回数据库读取器实例对象。</returns>
        public Task<DbDataReader> ExecuteReaderAsync(string commandText, object parameters = null, CommandType commandType = CommandType.Text,
            CancellationToken cancellationToken = new CancellationToken())
            => _executor.ExecuteReaderAsync(commandText, parameters, commandType, cancellationToken);

        /// <summary>
        /// 执行SQL语句。
        /// </summary>
        /// <param name="commandText">SQL字符串。</param>
        /// <param name="commandType">SQL类型。</param>
        /// <param name="parameters">参数匿名类型。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回单一结果实例对象。</returns>
        public Task<object> ExecuteScalarAsync(string commandText, object parameters = null, CommandType commandType = CommandType.Text,
            CancellationToken cancellationToken = new CancellationToken())
            => _executor.ExecuteScalarAsync(commandText, parameters, commandType, cancellationToken);

        /// <summary>
        /// 获取当前条件下的数量。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <returns>返回当前数量值。</returns>
        public int Count(Expression<Predicate<TModel>> expression)
        {
            var sql = SqlGenerator.Scalar(Entity, "COUNT", null, expression);
            return Convert.ToInt32(ExecuteScalar(sql.ToString()));
        }

        /// <summary>
        /// 获取当前条件下的数量。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回当前数量值。</returns>
        public async Task<int> CountAsync(Expression<Predicate<TModel>> expression, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Scalar(Entity, "COUNT", null, expression);
            return Convert.ToInt32(await ExecuteScalarAsync(sql.ToString(), cancellationToken: cancellationToken));
        }

        /// <summary>
        /// 新建实例对象。
        /// </summary>
        /// <param name="model">模型实例对象。</param>
        /// <returns>返回是否成功新建实例。</returns>
        public bool Create(TModel model)
        {
            var sql = SqlGenerator.Create(Entity);
            if (Entity.Identity != null)
            {
                var id = ExecuteScalar(sql.ToString(), sql.CreateParameters(model));
                if (id != null)
                {
                    Entity.Identity.Set(model, Convert.ToInt32(id));
                    return true;
                }
                return false;
            }
            return ExecuteNonQuery(sql.ToString(), sql.CreateParameters(model));
        }

        /// <summary>
        /// 新建实例对象。
        /// </summary>
        /// <param name="model">模型实例对象。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否成功新建实例。</returns>
        public async Task<bool> CreateAsync(TModel model, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Create(Entity);
            if (Entity.Identity != null)
            {
                var id = await ExecuteScalarAsync(sql.ToString(), sql.CreateParameters(model), cancellationToken: cancellationToken);
                if (id != null)
                {
                    if (Entity.Identity.ClrType == typeof(int))
                        Entity.Identity.Set(model, Convert.ToInt32(id));
                    else if (Entity.Identity.ClrType == typeof(long))
                        Entity.Identity.Set(model, Convert.ToInt64(id));
                    else if (Entity.Identity.ClrType == typeof(short))
                        Entity.Identity.Set(model, Convert.ToInt16(id));
                    return true;
                }
                return false;
            }
            return await ExecuteNonQueryAsync(sql.ToString(), sql.CreateParameters(model), cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 更新模型实例,此实例必须包含自增长ID或主键实例对象。
        /// </summary>
        /// <param name="model">模型实例对象。</param>
        /// <returns>返回是否更新成功。</returns>
        public bool Update(TModel model)
        {
            var sql = SqlGenerator.Update(Entity);
            return ExecuteNonQuery(sql.ToString(), sql.CreateParameters(model));
        }

        /// <summary>
        /// 更新模型实例,此实例必须包含自增长ID或主键实例对象。
        /// </summary>
        /// <param name="model">模型实例对象。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否更新成功。</returns>
        public async Task<bool> UpdateAsync(TModel model, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Update(Entity);
            return await ExecuteNonQueryAsync(sql.ToString(), sql.CreateParameters(model), cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 根据条件更新相应的模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="statement">更新选项实例。</param>
        /// <returns>返回是否更新成功。</returns>
        public bool Update(Expression<Predicate<TModel>> expression, object statement)
        {
            var sql = SqlGenerator.Update(Entity, statement, expression);
            return ExecuteNonQuery(sql.ToString(), sql.Parameters);
        }

        /// <summary>
        /// 更新所有模型实例对象。
        /// </summary>
        /// <param name="statement">更新选项实例。</param>
        /// <returns>返回是否更新成功。</returns>
        public bool Update(object statement)
            => Update(null, statement);

        /// <summary>
        /// 根据条件更新相应的模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="statement">更新选项实例。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否更新成功。</returns>
        public async Task<bool> UpdateAsync(Expression<Predicate<TModel>> expression, object statement, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Update(Entity, statement, expression);
            return await ExecuteNonQueryAsync(sql.ToString(), sql.Parameters, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 更新所有的模型实例对象。
        /// </summary>
        /// <param name="statement">更新选项实例。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否更新成功。</returns>
        public Task<bool> UpdateAsync(object statement, CancellationToken cancellationToken = new CancellationToken())
            => UpdateAsync(null, statement, cancellationToken);

        /// <summary>
        /// 根据条件删除模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <returns>判断是否删除成功。</returns>
        public bool Delete(Expression<Predicate<TModel>> expression = null)
        {
            var sql = SqlGenerator.Delete(Entity, expression);
            return ExecuteNonQuery(sql.ToString());
        }

        /// <summary>
        /// 根据条件删除模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>判断是否删除成功。</returns>
        public Task<bool> DeleteAsync(Expression<Predicate<TModel>> expression = null, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Delete(Entity, expression);
            return ExecuteNonQueryAsync(sql.ToString(), cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 通过条件表达式获取模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <returns>返回模型实例对象。</returns>
        public TModel Find([NotNull]Expression<Predicate<TModel>> expression)
        {
            Check.NotNull(expression, nameof(expression));
            var sql = SqlGenerator.List(Entity, expression);
            return ReadSql(sql);
        }

        /// <summary>
        /// 读取模型实例。
        /// </summary>
        /// <param name="sql">SQL语句。</param>
        /// <returns>返回模型实例。</returns>
        protected TModel ReadSql(SqlScript sql)
        {
            using (var reader = ExecuteReader(sql.ToString(), sql.Parameters))
            {
                if (reader.Read())
                    return Entity.Read<TModel>(reader);
            }
            return default(TModel);
        }

        /// <summary>
        /// 读取模型实例。
        /// </summary>
        /// <param name="sql">SQL语句。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回模型实例。</returns>
        protected async Task<TModel> ReadSqlAsync(SqlScript sql, CancellationToken cancellationToken = new CancellationToken())
        {
            using (var reader = await ExecuteReaderAsync(sql.ToString(), sql.Parameters, cancellationToken: cancellationToken))
            {
                if (await reader.ReadAsync(cancellationToken))
                    return Entity.Read<TModel>(reader);
            }
            return default(TModel);
        }

        /// <summary>
        /// 通过条件表达式获取模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回模型实例对象。</returns>
        public async Task<TModel> FindAsync(Expression<Predicate<TModel>> expression, CancellationToken cancellationToken = new CancellationToken())
        {
            Check.NotNull(expression, nameof(expression));
            var sql = SqlGenerator.List(Entity, expression);
            return await ReadSqlAsync(sql, cancellationToken);
        }

        /// <summary>
        /// 通过条件表达式获取模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <returns>返回模型实例对象。</returns>
        public IEnumerable<TModel> Load(Expression<Predicate<TModel>> expression = null)
        {
            var sql = SqlGenerator.List(Entity, expression);
            return LoadSql(sql);
        }

        /// <summary>
        /// 读取模型实例列表。
        /// </summary>
        /// <param name="sql">SQL语句。</param>
        /// <returns>返回模型实例列表。</returns>
        protected IEnumerable<TModel> LoadSql(SqlScript sql)
        {
            var models = new List<TModel>();
            using (var reader = ExecuteReader(sql.ToString(), sql.Parameters))
            {
                while (reader.Read())
                    models.Add(Entity.Read<TModel>(reader));
            }
            return models;
        }

        /// <summary>
        /// 读取模型实例列表。
        /// </summary>
        /// <param name="sql">SQL语句。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回模型实例列表。</returns>
        protected async Task<IEnumerable<TModel>> LoadSqlAsync(SqlScript sql, CancellationToken cancellationToken = new CancellationToken())
        {
            var models = new List<TModel>();
            using (var reader = await ExecuteReaderAsync(sql.ToString(), sql.Parameters, cancellationToken: cancellationToken))
            {
                while (await reader.ReadAsync(cancellationToken))
                    models.Add(Entity.Read<TModel>(reader));
            }
            return models;
        }

        /// <summary>
        /// 通过条件表达式获取模型实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回模型实例对象。</returns>
        public async Task<IEnumerable<TModel>> LoadAsync(Expression<Predicate<TModel>> expression = null, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.List(Entity, expression);
            return await LoadSqlAsync(sql, cancellationToken);
        }

        /// <summary>
        /// 通过条件表达式判断是否存在实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <returns>返回判断结果。</returns>
        public bool Any(Expression<Predicate<TModel>> expression = null)
        {
            var sql = SqlGenerator.Any(Entity, expression);
            return ExecuteScalar(sql.ToString()) != null;
        }

        /// <summary>
        /// 通过条件表达式判断是否存在实例对象。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回判断结果。</returns>
        public async Task<bool> AnyAsync(Expression<Predicate<TModel>> expression = null, CancellationToken cancellationToken = new CancellationToken())
        {
            var sql = SqlGenerator.Any(Entity, expression);
            return await ExecuteScalarAsync(sql.ToString(), cancellationToken: cancellationToken) != null;
        }

        /// <summary>
        /// 自增加更新。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="columns">更新列表达式。</param>
        /// <param name="value">每个属性更新的量。</param>
        /// <returns>返回是否更新成功。</returns>
        public virtual bool IncreaseBy(Expression<Predicate<TModel>> expression, Expression<Func<TModel, object>> columns, object value)
        {
            var columnNames = columns.GetPropertyAccessList().Select(p => p.Name).ToArray();
            var sql = SqlGenerator.IncreaseBy(Entity, expression, columnNames);
            return ExecuteNonQuery(sql.ToString(), new { Value = value });
        }

        /// <summary>
        /// 自增加更新。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="columns">更新列表达式。</param>
        /// <param name="value">每个属性更新的量。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否更新成功。</returns>
        public virtual Task<bool> IncreaseByAsync(Expression<Predicate<TModel>> expression, Expression<Func<TModel, object>> columns, object value,
            CancellationToken cancellationToken = new CancellationToken())
        {
            var columnNames = columns.GetPropertyAccessList().Select(p => p.Name).ToArray();
            var sql = SqlGenerator.IncreaseBy(Entity, expression, columnNames);
            return ExecuteNonQueryAsync(sql.ToString(), new { Value = value }, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// 自减少更新。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="columns">更新列表达式。</param>
        /// <param name="value">每个属性更新的量。</param>
        /// <returns>返回是否更新成功。</returns>
        public virtual bool DecreaseBy(Expression<Predicate<TModel>> expression, Expression<Func<TModel, object>> columns, object value)
        {
            var columnNames = columns.GetPropertyAccessList().Select(p => p.Name).ToArray();
            var sql = SqlGenerator.DecreaseBy(Entity, expression, columnNames);
            return ExecuteNonQuery(sql.ToString(), new { Value = value });
        }

        /// <summary>
        /// 自减少更新。
        /// </summary>
        /// <param name="expression">条件表达式。</param>
        /// <param name="columns">更新列表达式。</param>
        /// <param name="value">每个属性更新的量。</param>
        /// <param name="cancellationToken">取消标记。</param>
        /// <returns>返回是否更新成功。</returns>
        public virtual Task<bool> DecreaseByAsync(Expression<Predicate<TModel>> expression, Expression<Func<TModel, object>> columns, object value,
            CancellationToken cancellationToken = new CancellationToken())
        {
            var columnNames = columns.GetPropertyAccessList().Select(p => p.Name).ToArray();
            var sql = SqlGenerator.DecreaseBy(Entity, expression, columnNames);
            return ExecuteNonQueryAsync(sql.ToString(), new { Value = value }, cancellationToken: cancellationToken);
        }
    }
}


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

using System;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Storage.Common.Cmdlet;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Xunit;

namespace Microsoft.WindowsAzure.Commands.Storage.Test.Common.Cmdlet
{
    public class SetAzureStorageServiceLoggingTest : StorageTestBase
    {
        /// <summary>
        /// StorageCmdletBase command
        /// </summary>
        public SetAzureStorageServiceLoggingCommand command = null;

        public SetAzureStorageServiceLoggingTest()
        {
            command = new SetAzureStorageServiceLoggingCommand
            {
                CommandRuntime = new MockCommandRuntime()
            };
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void GetLoggingOperationsTest()
        {
            Assert.Equal(LoggingOperations.None, command.GetLoggingOperations("none"));
            Assert.Equal(LoggingOperations.All, command.GetLoggingOperations("all"));
            Assert.Equal(LoggingOperations.Read, command.GetLoggingOperations("Read"));
            Assert.Equal(LoggingOperations.Write, command.GetLoggingOperations("WrIte"));
            Assert.Equal(LoggingOperations.Delete, command.GetLoggingOperations("DELETE"));
            Assert.Equal(LoggingOperations.Read | LoggingOperations.Delete,
                command.GetLoggingOperations("Read, DELETE"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("DELETE,xxx"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("DELETE,all"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("DELETE,none"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("all,none"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("allnone"));
            AssertThrows<ArgumentException>(() => command.GetLoggingOperations("stdio"));
        }
    }
}


text:
from scrapy import Spider, signals
from scrapy.exceptions import DontCloseSpider

from . import connection

class RedisMixin(object):
    """Mixin class to implement reading urls from a redis queue."""
    redis_key = None  # use default '<spider>:start_urls'

    def setup_redis(self):
        """Setup redis connection and idle signal.

        This should be called after the spider has set its crawler object.
        """
        if not self.redis_key:
            self.redis_key = '%s:start_urls' % self.name

        self.server = connection.from_settings(self.crawler.settings)
        # idle signal is called when the spider has no requests left,
        # that's when we will schedule new requests from redis queue
        self.crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)
        self.crawler.signals.connect(self.item_scraped, signal=signals.item_scraped)
        self.log("Reading URLs from redis list '%s'" % self.redis_key)

    def next_request(self):
        """Returns a request to be scheduled or none."""
        use_set = self.settings.getbool('REDIS_SET')

        if use_set:
            url = self.server.spop(self.redis_key)
        else:
            url = self.server.lpop(self.redis_key)

        if url:
            return self.make_requests_from_url(url)

    def schedule_next_request(self):
        """Schedules a request if available"""
        req = self.next_request()
        if req:
            self.crawler.engine.crawl(req, spider=self)

    def spider_idle(self):
        """Schedules a request if available, otherwise waits."""
        self.schedule_next_request()
        raise DontCloseSpider

    def item_scraped(self, *args, **kwargs):
        """Avoids waiting for the spider to  idle before scheduling the next request"""
        self.schedule_next_request()

class RedisSpider(RedisMixin, Spider):
    """Spider that reads urls from redis queue when idle."""

    def _set_crawler(self, crawler):
        super(RedisSpider, self)._set_crawler(crawler)
        self.setup_redis()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.src.frugalinnovationlab.Entity;

import java.io.Serializable;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.CascadeType;

/**
 *
 * @author Sony
 */
@Entity
@Table(name = "user_roles")
@NamedQueries({
    @NamedQuery(name = "UserRoles.findAll", query = "SELECT u FROM UserRoles u"),
    @NamedQuery(name = "UserRoles.findByName", query = "SELECT u FROM UserRoles u WHERE u.name = :name")})
public class UserRoles implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @ManyToMany(cascade=CascadeType.ALL, mappedBy = "userRolesSet")
    private Set<Users> usersSet;

    public UserRoles() {
    }

    public UserRoles(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Users> getUsersSet() {
        return usersSet;
    }

    public void setUsersSet(Set<Users> usersSet) {
        this.usersSet = usersSet;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (name != null ? name.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserRoles)) {
            return false;
        }
        UserRoles other = (UserRoles) object;
        if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.src.frugalinnovationlab.Entity.UserRoles[ name=" + name + " ]";
    }

}


text:
<head>
    <meta charset="utf-8">
    <title>Frank DelPidio | Web Developer</title>
    <link rel="stylesheet" href="/css/normalize.css" >
    <link href='http://fonts.googleapis.com/css?family=Changa+One|Open+Sans:400italic,700italic,400,700,800' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/css/animate.css">
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/css/bachparty.css">
    <link rel="stylesheet" href="/css/responsive.css">
    <script language="JavaScript" type="text/javascript" src="/js/jquery-1.11.3.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>


text:
package org.apache.ofbiz.catalina.container;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.catalina.Cluster;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Manager;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.filters.RequestDumperFilter;
import org.apache.catalina.ha.tcp.ReplicationValve;
import org.apache.catalina.ha.tcp.SimpleTcpCluster;
import org.apache.catalina.loader.WebappLoader;
import org.apache.catalina.startup.ContextConfig;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.tribes.group.GroupChannel;
import org.apache.catalina.tribes.membership.McastService;
import org.apache.catalina.tribes.transport.MultiPointSender;
import org.apache.catalina.tribes.transport.ReplicationTransmitter;
import org.apache.catalina.tribes.transport.nio.NioReceiver;
import org.apache.catalina.util.ServerInfo;
import org.apache.catalina.valves.AccessLogValve;
import org.apache.catalina.webresources.StandardRoot;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.apache.tomcat.util.scan.StandardJarScanner;
import org.apache.ofbiz.base.component.ComponentConfig;
import org.apache.ofbiz.base.concurrent.ExecutionPool;
import org.apache.ofbiz.base.container.Container;
import org.apache.ofbiz.base.container.ContainerConfig;
import org.apache.ofbiz.base.container.ContainerConfig.Configuration.Property;
import org.apache.ofbiz.base.container.ContainerException;
import org.apache.ofbiz.base.location.FlexibleLocation;
import org.apache.ofbiz.base.start.Start;
import org.apache.ofbiz.base.start.StartupCommand;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.SSLUtil;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.UtilXml;
import org.w3c.dom.Document;

/*
 * --- Access Log Pattern Information - From Tomcat 5 AccessLogValve.java
 *
Patterns for the logged message may include constant text or any of the
 * following replacement strings, for which the corresponding information
 * from the specified Response is substituted:

 *

 *
%a - Remote IP address
 *
%A - Local IP address
 *
%b - Bytes sent, excluding HTTP headers, or '-' if no bytes
 *     were sent
 *
%B - Bytes sent, excluding HTTP headers
 *
%h - Remote host name
 *
%H - Request protocol
 *
%l - Remote logical username from identd (always returns '-')
 *
%m - Request method
 *
%p - Local port
 *
%q - Query string (prepended with a '?' if it exists, otherwise
 *     an empty string
 *
%r - First line of the request
 *
%s - HTTP status code of the response
 *
%S - User session ID
 *
%t - Date and time, in Common Log Format format
 *
%u - Remote user that was authenticated
 *
%U - Requested URL path
 *
%v - Local server name
 *
%D - Time taken to process the request, in millis
 *
%T - Time taken to process the request, in seconds
 *

 *
In addition, the caller can specify one of the following aliases for
 * commonly utilized patterns:

 *

 *
common - %h %l %u %t "%r" %s %b
 *
combined -
 *   %h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"
 *

 *
 *

 * There is also support to write information from the cookie, incoming
 * header, the Session or something else in the ServletRequest.

 * It is modeled after the apache syntax:
 *

 *
%{xxx}i for incoming headers
 *
%{xxx}c for a specific cookie
 *
%{xxx}r xxx is an attribute in the ServletRequest
 *
%{xxx}s xxx is an attribute in the HttpSession
 *

 *

 */

/**
 * CatalinaContainer -  Tomcat
 *
 */
public class CatalinaContainer implements Container {

    public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
    public static final String J2EE_SERVER = "OFBiz Container 3.1";
    public static final String J2EE_APP = "OFBiz";
    public static final String module = CatalinaContainer.class.getName();
    private static final ThreadGroup CATALINA_THREAD_GROUP = new ThreadGroup("CatalinaContainer");

    // load the JSSE properties (set the trust store)
    static {
        SSLUtil.loadJsseProperties();
    }

    private Tomcat tomcat = null;
    protected Map<String, ContainerConfig.Configuration.Property> clusterConfig = new HashMap<String, ContainerConfig.Configuration.Property>();

    protected boolean contextReloadable = false;
    protected boolean crossContext = false;
    protected boolean distribute = false;

    protected String catalinaRuntimeHome;

    private String name;

    @Override
    public void init(List<StartupCommand> ofbizCommands, String name, String configFile) throws ContainerException {
        this.name = name;
        // get the container config
        ContainerConfig.Configuration cc = ContainerConfig.getConfiguration(name, configFile);
        if (cc == null) {
            throw new ContainerException("No catalina-container configuration found in container config!");
        }

        // embedded properties
        boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
        //int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);

        // grab some global context settings
        this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
        this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
        this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);

        this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");

        // set catalina_home
        System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
        System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty(Globals.CATALINA_HOME_PROP));

        // create the instance of embedded Tomcat
        System.setProperty("catalina.useNaming", String.valueOf(useNaming));
        tomcat = new Tomcat();
        tomcat.setBaseDir(System.getProperty("ofbiz.home"));

        // configure JNDI in the StandardServer
        StandardServer server = (StandardServer) tomcat.getServer();
        if (useNaming) {
            tomcat.enableNaming();
        }
        try {
            server.setGlobalNamingContext(new InitialContext());
        } catch (NamingException e) {
            throw new ContainerException(e);
        }

        // create the engine
        List<ContainerConfig.Configuration.Property> engineProps = cc.getPropertiesWithValue("engine");
        if (UtilValidate.isEmpty(engineProps)) {
            throw new ContainerException("Cannot load CatalinaContainer; no engines defined.");
        }
        if (engineProps.size() > 1) {
            throw new ContainerException("Cannot load CatalinaContainer; more than one engine configuration found; only one is supported.");
        }
        createEngine(engineProps.get(0));

        // create the connectors
        List<ContainerConfig.Configuration.Property> connectorProps = cc.getPropertiesWithValue("connector");
        if (UtilValidate.isEmpty(connectorProps)) {
            throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
        }
        for (ContainerConfig.Configuration.Property connectorProp: connectorProps) {
            createConnector(connectorProp);
        }
    }

    public boolean start() throws ContainerException {
        // load the web applications
        loadComponents();

        // Start the Tomcat server
        try {
            tomcat.getServer().start();
        } catch (LifecycleException e) {
            throw new ContainerException(e);
        }

        for (Connector con: tomcat.getService().findConnectors()) {
            Debug.logInfo("Connector " + con.getProtocol() + " @ " + con.getPort() + " - " +
                (con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
        }
        Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
        return true;
    }

    private Engine createEngine(ContainerConfig.Configuration.Property engineConfig) throws ContainerException {
        if (tomcat == null) {
            throw new ContainerException("Cannot create Engine without Tomcat instance!");
        }

        ContainerConfig.Configuration.Property defaultHostProp = engineConfig.getProperty("default-host");
        if (defaultHostProp == null) {
            throw new ContainerException("default-host element of server property is required for catalina!");
        }

        String engineName = engineConfig.name;
        String hostName = defaultHostProp.value;

        tomcat.setHostname(hostName);
        Engine engine = tomcat.getEngine();
        engine.setName(engineName);

        // set the JVM Route property (JK/JK2)
        String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
        if (jvmRoute != null) {
            engine.setJvmRoute(jvmRoute);
        }

        // create a default virtual host; others will be created as needed
        Host host = tomcat.getHost();
        configureHost(host);

        // configure clustering
        List<ContainerConfig.Configuration.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
        if (clusterProps != null && clusterProps.size() > 1) {
            throw new ContainerException("Only one cluster configuration allowed per engine");
        }

        if (UtilValidate.isNotEmpty(clusterProps)) {
            ContainerConfig.Configuration.Property clusterProp = clusterProps.get(0);
            createCluster(clusterProp, host);
            clusterConfig.put(engineName, clusterProp);
        }

        // configure the CrossSubdomainSessionValve
        boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
        if (enableSessionValve) {
            CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
            ((StandardEngine)engine).addValve(sessionValve);
        }

        // configure the access log valve
        String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
        AccessLogValve al = null;
        if (logDir != null) {
            al = new AccessLogValve();
            if (!logDir.startsWith("/")) {
                logDir = System.getProperty("ofbiz.home") + "/" + logDir;
            }
            File logFile = new File(logDir);
            if (!logFile.isDirectory()) {
                throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
            }
            al.setDirectory(logFile.getAbsolutePath());
        }

        // configure the SslAcceleratorValve
        String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
        if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
            Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
            SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
            sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
            ((StandardEngine)engine).addValve(sslAcceleratorValve);
        }

        String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
        if (al != null && UtilValidate.isNotEmpty(alp2)) {
            al.setPattern(alp2);
        }

        String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
        if (al != null && UtilValidate.isNotEmpty(alp3)) {
            al.setPrefix(alp3);
        }

        boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
        if (al != null) {
            al.setRotatable(alp5);
        }

        if (al != null) {
            ((StandardEngine)engine).addValve(al);
        }

        return engine;
    }

    private static Host createHost(String hostName) {
        Host host = new StandardHost();
        host.setName(hostName);
        configureHost(host);
        return host;
    }
    private static void configureHost(Host host) {
        host.setAppBase(CATALINA_HOSTS_HOME);
        host.setDeployOnStartup(false);
        host.setBackgroundProcessorDelay(5);
        host.setAutoDeploy(false);
        ((StandardHost)host).setWorkDir(new File(System.getProperty(Globals.CATALINA_HOME_PROP), "work" + File.separator + host.getName()).getAbsolutePath());
    }

    protected Cluster createCluster(ContainerConfig.Configuration.Property clusterProps, Host host) throws ContainerException {
        String defaultValveFilter = ".*\\.gif;.*\\.js;.*\\.jpg;.*\\.htm;.*\\.html;.*\\.txt;.*\\.png;.*\\.css;.*\\.ico;.*\\.htc;";

        ReplicationValve clusterValve = new ReplicationValve();
        clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));

        String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
        String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
        int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
        int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
        int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);

        if (mca == null || mcp == -1) {
            throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
        }

        McastService mcast = new McastService();
        if (mcb != null) {
            mcast.setMcastBindAddress(mcb);
        }

        mcast.setAddress(mca);
        mcast.setPort(mcp);
        mcast.setMcastDropTime(mcd);
        mcast.setFrequency(mcf);

        String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
        int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
        int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
        int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
        //String tls = getPropertyValue(clusterProps, "", "");

        if (tlp == -1) {
            throw new ContainerException("Cluster configuration requires tcp-listen-port property");
        }

        NioReceiver listener = new NioReceiver();
        listener.setAddress(tla);
        listener.setPort(tlp);
        listener.setSelectorTimeout(tlt);
        listener.setMaxThreads(tlc);
        listener.setMinThreads(tlc);
        //listener.setIsSenderSynchronized(false);

        ReplicationTransmitter trans = new ReplicationTransmitter();
        try {
            MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
            trans.setTransport(mps);
        } catch (Exception exc) {
            throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
        }
        String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
        //int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
        // removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
        // removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);

        SimpleTcpCluster cluster = new SimpleTcpCluster();
        cluster.setClusterName(clusterProps.name);
        Manager manager = null;
        try {
            manager = (Manager)Class.forName(mgrClassName).newInstance();
        } catch (Exception exc) {
            throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
        }
        //cluster.setManagerClassName(mgrClassName);
        //host.setManager(manager);
        //cluster.registerManager(manager);
        cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
        //cluster.setDebug(debug);
        // removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
        // removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);

        GroupChannel channel = new GroupChannel();
        channel.setChannelReceiver(listener);
        channel.setChannelSender(trans);
        channel.setMembershipService(mcast);

        cluster.setChannel(channel);
        cluster.addValve(clusterValve);
        // removed since 5.5.9? cluster.setPrintToScreen(true);

        // set the cluster to the host
        host.setCluster(cluster);
        Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);

        return cluster;
    }

    protected Connector createConnector(ContainerConfig.Configuration.Property connectorProp) throws ContainerException {
        if (tomcat == null) {
            throw new ContainerException("Cannot create Connector without Tomcat instance!");
        }
        Connector connector = null;
        if (UtilValidate.isNotEmpty(connectorProp.properties)) {
            String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
            int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0) + Start.getInstance().getConfig().portOffset;

            // set the protocol and the port first
            connector = new Connector(protocol);
            connector.setPort(port);
            // then set all the other parameters
            for (ContainerConfig.Configuration.Property prop: connectorProp.properties.values()) {
                if ("protocol".equals(prop.name) || "port".equals(prop.name)) {
                    // protocol and port are already set
                    continue;
                }
                if (IntrospectionUtils.setProperty(connector, prop.name, prop.value)) {
                    if (prop.name.indexOf("Pass") != -1) {
                        // this property may be a password, do not include its value in the logs
                        Debug.logInfo("Tomcat " + connector + ": set " + prop.name, module);
                    } else {
                        Debug.logInfo("Tomcat " + connector + ": set " + prop.name + "=" + prop.value, module);
                    }
                } else {
                    Debug.logWarning("Tomcat " + connector + ": ignored parameter " + prop.name, module);
                }
            }

            tomcat.getService().addConnector(connector);
        }
        return connector;
    }

    private Callable<Context> createContext(final ComponentConfig.WebappInfo appInfo) throws ContainerException {
        Debug.logInfo("Creating context [" + appInfo.name + "]", module);
        final Engine engine = tomcat.getEngine();

        List<String> virtualHosts = appInfo.getVirtualHosts();
        final Host host;
        if (UtilValidate.isEmpty(virtualHosts)) {
            host = tomcat.getHost();
        } else {
            // assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
            Iterator<String> vhi = virtualHosts.iterator();
            String hostName = vhi.next();

            org.apache.catalina.Container childContainer = engine.findChild(hostName);
            if (childContainer instanceof Host) {
                host = (Host)childContainer;
            } else {
                host = createHost(hostName);
                engine.addChild(host);
            }
            while (vhi.hasNext()) {
                host.addAlias(vhi.next());
            }
        }
        return new Callable<Context>() {
            public Context call() throws ContainerException, LifecycleException {
                StandardContext context = configureContext(engine, host, appInfo);
                host.addChild(context);
                return context;
            }
        };
    }

    private StandardContext configureContext(Engine engine, Host host, ComponentConfig.WebappInfo appInfo) throws ContainerException {
        // webapp settings
        Map<String, String> initParameters = appInfo.getInitParameters();

        // set the root location (make sure we set the paths correctly)
        String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
        location = location.replace('\\', '/');
        if (location.endsWith("/")) {
            location = location.substring(0, location.length() - 1);
        }

        // get the mount point
        String mount = appInfo.mountPoint;
        if (mount.endsWith("/*")) {
            mount = mount.substring(0, mount.length() - 2);
        }

        final String webXmlFilePath = new StringBuilder().append("file:///").append(location).append("/WEB-INF/web.xml").toString();
        boolean appIsDistributable = distribute;
        URL webXmlUrl = null;
        try {
            webXmlUrl = FlexibleLocation.resolveLocation(webXmlFilePath);
        } catch (MalformedURLException e) {
            throw new ContainerException(e);
        }
        File webXmlFile = new File(webXmlUrl.getFile());
        if (webXmlFile.exists()) {
            Document webXmlDoc = null;
            try {
                webXmlDoc = UtilXml.readXmlDocument(webXmlUrl);
            } catch (Exception e) {
                throw new ContainerException(e);
            }
            appIsDistributable = webXmlDoc.getElementsByTagName("distributable").getLength() > 0;
        } else {
            Debug.logInfo(webXmlFilePath + " not found.", module);
        }
        final boolean contextIsDistributable = distribute && appIsDistributable;

        // create the web application context
        StandardContext context = new StandardContext();
        context.setParent(host);
        context.setDocBase(location);
        context.setPath(mount);
        context.addLifecycleListener(new ContextConfig());
        Tomcat.initWebappDefaults(context);
        // configure persistent sessions
        // important: the call to context.setManager(...) must be done after Tomcat.initWebappDefaults(...)
        Property clusterProp = clusterConfig.get(engine.getName());
        if (clusterProp != null && contextIsDistributable) {
            Manager sessionMgr = null;
            String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
            try {
                sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
            } catch (Exception exc) {
                throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
            }
            context.setManager(sessionMgr);
        }

        JarScanner jarScanner = context.getJarScanner();
        if (jarScanner instanceof StandardJarScanner) {
            StandardJarScanner standardJarScanner = (StandardJarScanner) jarScanner;
            standardJarScanner.setJarScanFilter(new FilterJars());
            standardJarScanner.setScanClassPath(true);
        }

        context.setJ2EEApplication(J2EE_APP);
        context.setJ2EEServer(J2EE_SERVER);
        context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));

        context.setDisplayName(appInfo.name);
        context.setDocBase(location);

        StandardRoot resources = new StandardRoot(context);
        resources.setAllowLinking(true);
        context.setResources(resources);

        context.setReloadable(contextReloadable);

        context.setDistributable(contextIsDistributable);

        context.setCrossContext(crossContext);
        context.setPrivileged(appInfo.privileged);
        context.getServletContext().setAttribute("_serverId", appInfo.server);
        context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());

        // request dumper filter
        String enableRequestDump = initParameters.get("enableRequestDump");
        if ("true".equals(enableRequestDump)) {
            // create the Requester Dumper Filter instance
            FilterDef requestDumperFilterDef = new FilterDef();
            requestDumperFilterDef.setFilterClass(RequestDumperFilter.class.getName());
            requestDumperFilterDef.setFilterName("RequestDumper");
            FilterMap requestDumperFilterMap = new FilterMap();
            requestDumperFilterMap.setFilterName("RequestDumper");
            requestDumperFilterMap.addURLPattern("*");
            context.addFilterMap(requestDumperFilterMap);
        }

        // set the init parameters
        for (Map.Entry<String, String> entry: initParameters.entrySet()) {
            context.addParameter(entry.getKey(), entry.getValue());
        }

        return context;
    }

    protected void loadComponents() throws ContainerException {
        if (tomcat == null) {
            throw new ContainerException("Cannot load web applications without Tomcat instance!");
        }

        // load the applications
        List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
        List<String> loadedMounts = new ArrayList<String>();
        if (webResourceInfos == null) {
            return;
        }

        ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(CATALINA_THREAD_GROUP, "catalina-startup", Runtime.getRuntime().availableProcessors(), 0, true);
        try {
            List<Future<Context>> futures = new ArrayList<Future<Context>>();

            for (int i = webResourceInfos.size(); i > 0; i--) {
                ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
                String engineName = appInfo.server;
                List<String> virtualHosts = appInfo.getVirtualHosts();
                String mount = appInfo.getContextRoot();
                List<String> keys = new ArrayList<String>();
                if (virtualHosts.isEmpty()) {
                    keys.add(engineName + ":DEFAULT:" + mount);
                } else {
                    for (String virtualHost: virtualHosts) {
                        keys.add(engineName + ":" + virtualHost + ":" + mount);
                    }
                }
                if (!keys.removeAll(loadedMounts)) {
                    // nothing was removed from the new list of keys; this
                    // means there are no existing loaded entries that overlap
                    // with the new set
                    if (!appInfo.location.isEmpty()) {
                        futures.add(executor.submit(createContext(appInfo)));
                    }
                    loadedMounts.addAll(keys);
                } else {
                    appInfo.setAppBarDisplay(false); // disable app bar display on overridden apps
                    Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
                }
            }
            ExecutionPool.getAllFutures(futures);
        } finally {
            executor.shutdown();
        }
    }

    public void stop() throws ContainerException {
        try {
            tomcat.stop();
        } catch (LifecycleException e) {
            // don't throw this; or it will kill the rest of the shutdown process
            Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
        }
    }

    public String getName() {
        return name;
    }
}


text:
<?php
defined('BASEPATH') or die('Restricted directy access');

class Countries_model extends CI_Model
{

	function get_countries($order_field='pais_id',$sort_order='asc')
	{
		$this->db->order_by($order_field,$sort_order);
		return $this->db->get('paises')->result();
	}

	function insert_country($data)
	{
		$this->db->insert('paises',$data);
	}

	function delete_country($id)
	{
		$this->db->where('pais_id',$id);
		$this->db->delete('paises');
	}

	public function get_country($id)
	{
		$this->db->where('pais_id',$id);
		return $this->db->get('paises')->row();
	}

	public function update_country($data,$id)
	{
		$this->db->where('pais_id',$id);
		$this->db->update('paises',$data);
	}
}


text:
package de.adito.propertly.reactive.api.builder;

import de.adito.propertly.core.spi.*;
import io.reactivex.rxjava3.core.Observable;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * a BuilderPropertyPitObservable is a Observable that
 * contains a PropertyPitProvider as value and will trigger,
 * if propertyAdded/propertyOrderChanged/propertyRemoved is fired
 *
 * @param
 Parent of the containing PropertyPitProvider
 * @param <S> Self-Type of the containing PropertyPitProvider
 * @param <T> Value-Type the containing PropertyPitProvider can contain
 * @author w.glanzer, 09.11.2018
 */
public interface IBuilderPropertyPitObservable
    extends IBuilderObservable<S>
{

  /**
   * Emits a single Property, identified by the given PropertyDescription.

   * If the property is not found in this pit, the resulting BuilderPropertyObservable will be empty.

   * The PropertyObservable will trigger, if the property will be added/changed/removed
   *
   * @param pDescription Description to identify the property to observe on
   * @param <T2>         Value-Type of the property and it's description
   * @return the IBuilderPropertyObservable, not <tt>null</tt>
   */
  @NotNull <T2> IBuilderPropertyObservable<S, T2> emitProperty(@NotNull IPropertyDescription<? super S, T2> pDescription);

  /**
   * Emits a single Property, identified by the given Name.

   * If the property is not found in this pit, the resulting BuilderPropertyObservable will be empty.

   * The PropertyObservable will trigger, if the property will be added/changed/removed
   *
   * @param pName Name to identify the property to observe on
   * @return the IBuilderPropertyObservable, not <tt>null</tt>
   */
  @NotNull IBuilderPropertyObservable<S, T> emitProperty(@NotNull String pName);

  /**
   * Emits a child PropertyPitProvider, identified by the given PropertyDescription.

   * If the property is not found in this pit, the resulting BuilderPropertyPitObservable will be empty

   * The PropertyPitObservable will trigger, if the property that contains the searched pit will be added/changed/removed or
   * the pit itself does something like propertyAdded/propertyOrderChanged/propertyRemoved.
   *
   * @param pDescription Description to identify the property (with an PropertyPitProvider as value-type) to observe on
   * @param <S2>         Value-Type of the property -> It has to be a subtype of PropertyPitProvider!
   * @return IBuilderPropertyPitObservable, not <tt>null</tt>
   */
  @NotNull <P2 extends IPropertyPitProvider, S2 extends IPropertyPitProvider<P2, S2, T2>, T2>
  IBuilderPropertyPitObservable<P2, S2, T2> emitPropertyPit(@NotNull IPropertyDescription<? super S, S2> pDescription);

  /**
   * Emits all properties this PropertyPitProvider has.
   *
   * @return IBuilderPropertyListObservable, not <tt>null</tt>
   */
  @NotNull
  IBuilderPropertyListObservable<S, T> emitProperties();

  /**
   * Returns a new PropertyObservable of our hierarchy property
   *
   * @return the PropertyObservable
   */
  @NotNull
  IBuilderPropertyObservable<IPropertyPitProvider, ?> emitHierarchyValue();

  /**
   * Emits all values of all properties this PropertyPit has.
   * It calls {@link IBuilderPropertyPitObservable#emitProperties()} first, to retrieve a list of all properties,
   * and then emits their values with {@link IBuilderPropertyListObservable#emitValues()}
   * The resulting Observable is not distincted automatically.
   * It does not contain any NULL-Values. If you have the need to, use {@link IBuilderPropertyPitObservable#emitPropertyValues(boolean)}
   *
   * @return the Observable containing all values as list, not <tt>null</tt>
   */
  @NotNull
  default Observable<Optional<List<T>>> emitPropertyValues()
  {
    return emitProperties().emitValues();
  }

  /**
   * Emits all values of all properties this PropertyPit has.
   * It calls {@link IBuilderPropertyPitObservable#emitProperties()} first, to retrieve a list of all properties,
   * and then emits their values with {@link IBuilderPropertyListObservable#emitValues()}
   * The resulting Observable is not distincted automatically.
   *
   * @param pIncludeNullValues <tt>true</tt>, if the inner list should contain NULL-Values, if a property has <tt>null</tt> as a value
   * @return the Observable containing all values as list, not <tt>null</tt>
   */
  @NotNull
  default Observable<Optional<List<T>>> emitPropertyValues(boolean pIncludeNullValues)
  {
    return emitProperties().emitValues(pIncludeNullValues);
  }

}


text:
CCircularQueue::CCircularQueue():mQueueHead(0),mQueueTail(0)
{
	memset(mQueue, 0, sizeof(mQueue));
}

CCircularQueue::~CCircularQueue()
{
}

BOOL CCircularQueue::Begin()
{
	memset(mQueue, 0, sizeof(mQueue));
	mQueueHead	= 0;
	mQueueTail	= 0;
	return TRUE;
}

BOOL CCircularQueue::End()
{
	return TRUE;
}

BYTE* CCircularQueue::Push(VOID* object, BYTE* data, DWORD dataLength)
{
	CThreadSync Sync;

	if (!object || !data) return NULL;

	DWORD TempTail = (mQueueTail + 1) % MAX_QUEUE_LENGTH;

	if (TempTail == mQueueHead) return NULL;

	mQueue[TempTail].Object = object;
	mQueue[TempTail].DataLength = dataLength;
	memcpy(mQueue[TempTail].Data, data, dataLength);

	mQueueTail = TempTail;

	return mQueue[TempTail].Data;
}

BYTE* CCircularQueue::Push(VOID* object, DWORD protocol, BYTE* data, DWORD dataLength)
{
	CThreadSync Sync;

	if (!object || !data) return NULL;

	DWORD TempTail = (mQueueTail + 1) % MAX_QUEUE_LENGTH;

	if (TempTail == mQueueHead) return NULL;

	mQueue[TempTail].Object = object;
	mQueue[TempTail].DataLength	= dataLength;
	mQueue[TempTail].Protocol = protocol;
	memset(mQueue[TempTail].Data, 0, sizeof(mQueue[TempTail].Data));
	memcpy(mQueue[TempTail].Data, data, dataLength);

	mQueueTail = TempTail;

	return mQueue[TempTail].Data;
}

BYTE* CCircularQueue::Push(VOID* object, BYTE* data, DWORD dataLength, LPCSTR remoteAddress, USHORT remotePort)
{
	CThreadSync Sync;

	if (!object || !data) return NULL;

	DWORD TempTail = (mQueueTail + 1) % MAX_QUEUE_LENGTH;

	if (TempTail == mQueueHead) return NULL;

	mQueue[TempTail].Object = object;
	mQueue[TempTail].DataLength	= dataLength;
	mQueue[TempTail].RemotePort	= remotePort;
	memset(mQueue[TempTail].RemoteAddress, 0, sizeof(mQueue[TempTail].RemoteAddress));
	strncpy(mQueue[TempTail].RemoteAddress, remoteAddress, sizeof(mQueue[TempTail].RemoteAddress));
	memset(mQueue[TempTail].Data, 0, sizeof(mQueue[TempTail].Data));
	memcpy(mQueue[TempTail].Data, data, dataLength);

	mQueueTail = TempTail;

	return mQueue[TempTail].Data;
}

BYTE* CCircularQueue::Push(VOID* object, DWORD protocol, BYTE* data, DWORD dataLength, LPCSTR remoteAddress, USHORT remotePort)
{
	CThreadSync Sync;

	if (!object || !data) return NULL;

	DWORD TempTail = (mQueueTail + 1) % MAX_QUEUE_LENGTH;

	if (TempTail == mQueueHead) return NULL;

	mQueue[TempTail].Object = object;
	mQueue[TempTail].DataLength	= dataLength;
	mQueue[TempTail].RemotePort	= remotePort;
	mQueue[TempTail].Protocol = protocol;
	memset(mQueue[TempTail].RemoteAddress, 0, sizeof(mQueue[TempTail].RemoteAddress));
	strncpy(mQueue[TempTail].RemoteAddress, remoteAddress, sizeof(mQueue[TempTail].RemoteAddress));
	memset(mQueue[TempTail].Data, 0, sizeof(mQueue[TempTail].Data));
	memcpy(mQueue[TempTail].Data, data, dataLength);

	mQueueTail = TempTail;

	return mQueue[TempTail].Data;
}

BOOL CCircularQueue::Pop()
{
	CThreadSync Sync;

	if (mQueueHead == mQueueTail) return FALSE;

	DWORD TempHead = (mQueueHead + 1) % MAX_QUEUE_LENGTH;

	mQueueHead = TempHead;

	return TRUE;
}

BOOL CCircularQueue::Pop(VOID** object, BYTE* data, DWORD& dataLength)
{
	CThreadSync Sync;

	if (!object || !data) return FALSE;

	if (mQueueHead == mQueueTail) return FALSE;

	DWORD TempHead = (mQueueHead + 1) % MAX_QUEUE_LENGTH;

	dataLength = mQueue[TempHead].DataLength;
	*object	= mQueue[TempHead].Object;
	memcpy(data, mQueue[TempHead].Data, mQueue[TempHead].DataLength);

	mQueueHead = TempHead;

	return TRUE;
}

BOOL CCircularQueue::Pop(VOID** object, DWORD& protocol, BYTE* data, DWORD& dataLength)
{
	CThreadSync Sync;

	if (!object || !data) return FALSE;

	if (mQueueHead == mQueueTail) return FALSE;

	DWORD TempHead = (mQueueHead + 1) % MAX_QUEUE_LENGTH;

	dataLength = mQueue[TempHead].DataLength;
	*object = mQueue[TempHead].Object;
	protocol = mQueue[TempHead].Protocol;
	memcpy(data, mQueue[TempHead].Data, mQueue[TempHead].DataLength);

	mQueueHead = TempHead;

	return TRUE;
}

BOOL CCircularQueue::Pop(VOID** object, BYTE* data, DWORD& dataLength, LPSTR remoteAddress, USHORT& remotePort)
{
	CThreadSync Sync;

	if (!object || !data) return FALSE;

	if (mQueueHead == mQueueTail) return FALSE;

	DWORD TempHead = (mQueueHead + 1) % MAX_QUEUE_LENGTH;

	dataLength = mQueue[TempHead].DataLength;
	*object = mQueue[TempHead].Object;
	remotePort = mQueue[TempHead].RemotePort;
	strncpy(remoteAddress, mQueue[TempHead].RemoteAddress, sizeof(mQueue[TempHead].RemoteAddress));
	memcpy(data, mQueue[TempHead].Data, mQueue[TempHead].DataLength);

	mQueueHead = TempHead;

	return TRUE;
}

BOOL CCircularQueue::Pop(VOID** object, DWORD& protocol, BYTE* data, DWORD& dataLength, LPSTR remoteAddress, USHORT& remotePort)
{
	CThreadSync Sync;

	if (!object || !data) return FALSE;

	if (mQueueHead == mQueueTail) return FALSE;

	DWORD TempHead = (mQueueHead + 1) % MAX_QUEUE_LENGTH;

	dataLength = mQueue[TempHead].DataLength;
	*object = mQueue[TempHead].Object;
	remotePort = mQueue[TempHead].RemotePort;
	protocol = mQueue[TempHead].Protocol;
	strncpy(remoteAddress, mQueue[TempHead].RemoteAddress, sizeof(mQueue[TempHead].RemoteAddress));
	memcpy(data, mQueue[TempHead].Data, mQueue[TempHead].DataLength);

	mQueueHead = TempHead;

	return TRUE;
}

BOOL CCircularQueue::IsEmpty()
{
	CThreadSync Sync;

	if (mQueueHead == mQueueTail) return TRUE;

	return FALSE;
}


text:
local mkstr = ZO_CreateStringId
local SI = mFSHConfig.SI

-- Bait Type
mkstr(SI.GUTS,                              "Boyaux")
mkstr(SI.INSECTS,                           "Morceaux D'insectes")
mkstr(SI.WORMS,                             "Vers")
mkstr(SI.MINNOW,                            "Méné")
mkstr(SI.FISHROE,                           "Œufs de Poisson")
mkstr(SI.CHUB,                              "Chevesne")
mkstr(SI.CRAWLERS,                          "Rampants")
mkstr(SI.SHAD,                              "Shad")

mkstr(SI.AREUSEDIN,                         " À utiliser dans ")

--Where
mkstr(SI.RIVERS,                           "les Rivières")
mkstr(SI.LAKES,                            "les Lacs")
mkstr(SI.SEA,                              "la Mer")
mkstr(SI.FOULWATER,                        "les Eaux peu profondes")

---Msg-
mkstr(SI.GUTSMSG,                           " pour attraper: Poisson Spatule, Sableflanc et Shad.")
mkstr(SI.INSECTSMSG,                        " pour attraper: Saumon, Betta D'eau Douce et Œufs de Poisson.")
mkstr(SI.WORMSMSG,                          " pour attraper: Perche  Perlée, Nagelongue et Méné.")
mkstr(SI.MINNOWMSG,                         " pour attraper: Poisson Spatule, Sableflanc et Shad.")
mkstr(SI.FISHROEMSG,                        " pour attraper: Poisson Carnassier, Trodh et Chevesne.")
mkstr(SI.CHUBMSG,                           " pour attraper: Perche  Perlée, Nagelongue et Méné.")
mkstr(SI.CRAWLERSMSG,                       " pour attraper: Poisson Carnassier, Trodh et Chevesne.")
mkstr(SI.SHADMSG,                           " pour attraper: Saumon, Betta D'eau Douce et Œufs de Poisson.")

--Misc
mkstr(SI.MOREBAIT,                             "Besoin de plus d'appât!")
mkstr(SI.REELIN,                               "|cFF0000 Reel In!")
mkstr(SI.SHESABITER,                           "|cFF0000 Le poisson mord!")
mkstr(SI.SENDMELOGS,                           "Envoyer @ Awesomebilly le nom de l'appât et ce nombre: ")

-- OPTIONS MENU
mkstr(SI.FISHOPTIONS,                         "Options pêche")
mkstr(SI.RECEIVEBAITALERTS,                   "Recevez des alertes Bait?")
mkstr(SI.BAITMSG,                             "Cela vous informer que appât à utiliser")

mkstr(SI.RECEIVEREELALERTS,                   "Recevez des alertes Reel?")
mkstr(SI.REELMSG,                             "Cela vous alerter lorsque la bobine dans")

mkstr(SI.BUGFOUND,                            "Vous avez trouvé un bug??!")
mkstr(SI.MISSINGSTUFF,                        "Cela permet journaux pour des choses qui me manque! \ n S'il vous plaît signaler ce qui imprimé dans les journaux à @ awesomebilly")

mkstr(SI.ONLYGOOD,                            "Les seules bonnes dons sont \ n ")
mkstr(SI.DONATIONS,                           "dons d'or ;) ")
mkstr(SI.BADASS,                              "@Awesomebilly (NA)")

--Various App
mkstr(SI.APPNAME,                             "Luminary: ")
mkstr(SI.BETA,                                " Cet addon est en version beta. Les traductions de Google Translate and @wookiefrag ")
mkstr(SI.BUGSQUASHER,                         "  Si vous trouvez un bug s'il vous plaît activer l'enregistrement ci-dessus ")
mkstr(SI.REPORTTHATSHITYO,                    "\n\n\n S'il vous plaît rapporter tous les bugs que vous trouvez.")


text:
package br.com.triadworks.issuetracker.dao;

import java.util.List;

import br.com.triadworks.issuetracker.model.Usuario;

public interface UsuarioDao {

	public List<Usuario> listaTudo();

	public void salva(Usuario usuario);

	public void atualiza(Usuario usuario);

	public void remove(Usuario usuario);

	public Usuario buscaPor(String login, String senha);

	public Usuario carrega(Long id);

}


text:
<?php

/**
 * Represents a sandbox node.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Twig_Node_Sandbox extends Twig_Node
{
    public function __construct(Twig_Node $body, $lineno, $tag = null)
    {
        parent::__construct(array('body' => $body), array(), $lineno, $tag);
    }

    public function compile(Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            ->write("\$sandbox = \$this->env->getExtension('sandbox');\n")
            ->write("if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {\n")
            ->indent()
            ->write("\$sandbox->enableSandbox();\n")
            ->outdent()
            ->write("}\n")
            ->subcompile($this->getNode('body'))
            ->write("if (!\$alreadySandboxed) {\n")
            ->indent()
            ->write("\$sandbox->disableSandbox();\n")
            ->outdent()
            ->write("}\n")
        ;
    }
}


text:
package com.hotels.styx.support.configuration

import java.nio.file.Path
import java.util

import com.hotels.styx.{NettyExecutor, StyxServer}
import com.hotels.styx.StyxServerSupport._
import com.hotels.styx.api.extension.service.spi.StyxService
import com.hotels.styx.api.plugins.spi.Plugin
import com.hotels.styx.config.Config
import com.hotels.styx.infrastructure.configuration.yaml.YamlConfiguration
import com.hotels.styx.proxy.ProxyServerConfig
import com.hotels.styx.startup.StyxServerComponents
import com.hotels.styx.support.ResourcePaths

import scala.collection.JavaConverters._

case class Connectors(httpConnectorConfig: HttpConnectorConfig,
                      httpsConnectorConfig: HttpsConnectorConfig) {
  def asJava: com.hotels.styx.server.netty.NettyServerConfig.Connectors = {
    val httpAsJava = Option(httpConnectorConfig).map(_.asJava).orNull
    val httpsAsJava = Option(httpsConnectorConfig).map(_.asJava).orNull

    new com.hotels.styx.server.netty.NettyServerConfig.Connectors(httpAsJava, httpsAsJava)
  }
}

sealed trait StyxBaseConfig {
  def logbackXmlLocation: Path
  def additionalServices: Map[String, StyxService]
  def plugins: Map[String, Plugin]

  def startServer(backendsRegistry: StyxService): StyxServer

  def startServer(): StyxServer

  def services(backendsRegistry: StyxService): Map[String, StyxService] = if (additionalServices.nonEmpty) {
    this.additionalServices
  } else {
    Map("backendServiceRegistry" -> backendsRegistry)
  }
}

object StyxBaseConfig {
  val defaultLogbackXml = ResourcePaths.fixturesHome(this.getClass, "/logback.xml")
  val globalBossExecutor = NettyExecutor.create("StyxServer-Boss", 1)
  val globalWorkerExecutor = NettyExecutor.create("StyxServer-Worker", 1)

}

case class StyxConfig(proxyConfig: ProxyConfig = ProxyConfig(),
                      plugins: Map[String, Plugin] = Map.empty,
                      logbackXmlLocation: Path = StyxBaseConfig.defaultLogbackXml,
                      yamlText: String = "originRestrictionCookie: \"originRestrictionCookie\"\n",
                      adminPort: Int = 0,
                      additionalServices: Map[String, StyxService] = Map.empty
                     ) extends StyxBaseConfig {

  override def startServer(backendsRegistry: StyxService): StyxServer = {

    val proxyConfig = this.proxyConfig.copy(connectors = Connectors(httpConnectorWithPort(), httpsConnectorWithPort()))

    val proxyConfigBuilder = new ProxyServerConfig.Builder()
      .setConnectors(proxyConfig.connectors.asJava)
      .setBossThreadsCount(proxyConfig.bossThreadCount)
      .setClientWorkerThreadsCount(proxyConfig.workerThreadsCount)
      .setKeepAliveTimeoutMillis(proxyConfig.keepAliveTimeoutMillis)
      .setMaxChunkSize(proxyConfig.maxChunkSize)
      .setMaxConnectionsCount(proxyConfig.maxConnectionsCount)
      .setMaxHeaderSize(proxyConfig.maxHeaderSize)
      .setMaxInitialLength(proxyConfig.maxInitialLength)
      .setNioAcceptorBacklog(proxyConfig.nioAcceptorBacklog)
      .setRequestTimeoutMillis(proxyConfig.requestTimeoutMillis)
      .setClientWorkerThreadsCount(proxyConfig.clientWorkerThreadsCount)
      .setCompressResponses(proxyConfig.compressResponses)

    val styxConfig = newStyxConfig(this.yamlText,
      proxyConfigBuilder,
      newAdminServerConfigBuilder(newHttpConnConfig(adminPort))
    )

    val java: util.Map[String, StyxService] = services(backendsRegistry).asJava

    val styxServer = new StyxServer(
      serverComponents(styxConfig, backendsRegistry, this.plugins)
        .additionalServices(java)
        .loggingSetUp(this.logbackXmlLocation.toString).build())
    styxServer.startAsync().awaitRunning()
    styxServer
  }

  override def startServer(): StyxServer = {

    val proxyConfig = this.proxyConfig.copy(connectors = Connectors(httpConnectorWithPort(), httpsConnectorWithPort()))

    val proxyConfigBuilder = new ProxyServerConfig.Builder()
      .setConnectors(proxyConfig.connectors.asJava)
      .setBossThreadsCount(proxyConfig.bossThreadCount)
      .setClientWorkerThreadsCount(proxyConfig.workerThreadsCount)
      .setKeepAliveTimeoutMillis(proxyConfig.keepAliveTimeoutMillis)
      .setMaxChunkSize(proxyConfig.maxChunkSize)
      .setMaxConnectionsCount(proxyConfig.maxConnectionsCount)
      .setMaxHeaderSize(proxyConfig.maxHeaderSize)
      .setMaxInitialLength(proxyConfig.maxInitialLength)
      .setNioAcceptorBacklog(proxyConfig.nioAcceptorBacklog)
      .setRequestTimeoutMillis(proxyConfig.requestTimeoutMillis)
      .setClientWorkerThreadsCount(proxyConfig.clientWorkerThreadsCount)

    val styxConfig = newStyxConfig(this.yamlText,
      proxyConfigBuilder,
      newAdminServerConfigBuilder(newHttpConnConfig(adminPort))
    )

    val coreConfig = newCoreConfig(styxConfig, this.plugins)
      .loggingSetUp(this.logbackXmlLocation.toString)

    val styxServer = new StyxServer(coreConfig.build())
    styxServer.startAsync().awaitRunning()
    styxServer
  }

  private def httpConnectorWithPort() = this.proxyConfig.connectors.httpConnectorConfig

  private def httpsConnectorWithPort() = this.proxyConfig.connectors.httpsConnectorConfig
}

case class StyxYamlConfig(yamlConfig: String,
                          logbackXmlLocation: Path = StyxBaseConfig.defaultLogbackXml,
                          additionalServices: Map[String, StyxService] = Map.empty,
                          plugins: Map[String, Plugin] = Map.empty
                         ) extends StyxBaseConfig {

  override def startServer(backendsRegistry: StyxService): StyxServer = {
    val config: YamlConfiguration = Config.config(yamlConfig)
    val styxConfig = com.hotels.styx.StyxConfig.fromYaml(yamlConfig)

    val styxServer = new StyxServer(new StyxServerComponents.Builder()
      .styxConfig(styxConfig)
      .additionalServices(services(backendsRegistry).asJava)
      .loggingSetUp(logbackXmlLocation.toString)
      .build())

    styxServer.startAsync().awaitRunning()
    styxServer
  }

  override def startServer(): StyxServer = {
    val config: YamlConfiguration = Config.config(yamlConfig)
    val styxConfig = com.hotels.styx.StyxConfig.fromYaml(yamlConfig)

    val styxServer = new StyxServer(new StyxServerComponents.Builder()
      .styxConfig(styxConfig)
      .loggingSetUp(logbackXmlLocation.toString)
      .build())

    styxServer.startAsync().awaitRunning()
    styxServer
  }
}


text:
<?php

namespace Ticketmatic\Endpoints\Settings\System;

use Ticketmatic\Client;
use Ticketmatic\ClientException;
use Ticketmatic\Json;
use Ticketmatic\Model\ContactAddressType;
use Ticketmatic\Model\ContactAddressTypeQuery;

/**
 * Address types allow you to attach a type to different addresses.
 *
 * ## Help Center
 *
 * Full documentation can be found in the Ticketmatic Help Center
 * (https://apps.ticketmatic.com/#/knowledgebase/api/settings_system_contactaddresstypes).
 */
class Contactaddresstypes
{

    /**
     * Get a list of contact address types
     *
     * @param Client $client
     * @param \Ticketmatic\Model\ContactAddressTypeQuery|array $params
     *
     * @throws ClientException
     *
     * @return ContactaddresstypesList
     */
    public static function getlist(Client $client, $params = null) {
        if ($params == null || is_array($params)) {
            $params = new ContactAddressTypeQuery($params == null ? array() : $params);
        }
        $req = $client->newRequest("GET", "/{accountname}/settings/system/contactaddresstypes");

        $req->addQuery("filter", $params->filter);
        $req->addQuery("includearchived", $params->includearchived);
        $req->addQuery("lastupdatesince", $params->lastupdatesince);

        $result = $req->run("json");
        return ContactaddresstypesList::fromJson($result);
    }

    /**
     * Get a single contact address type
     *
     * @param Client $client
     * @param int $id
     *
     * @throws ClientException
     *
     * @return \Ticketmatic\Model\ContactAddressType
     */
    public static function get(Client $client, $id) {
        $req = $client->newRequest("GET", "/{accountname}/settings/system/contactaddresstypes/{id}");
        $req->addParameter("id", $id);

        $result = $req->run("json");
        return ContactAddressType::fromJson($result);
    }

    /**
     * Create a new contact address type
     *
     * @param Client $client
     * @param \Ticketmatic\Model\ContactAddressType|array $data
     *
     * @throws ClientException
     *
     * @return \Ticketmatic\Model\ContactAddressType
     */
    public static function create(Client $client, $data) {
        if ($data == null || is_array($data)) {
            $d = new ContactAddressType($data == null ? array() : $data);
            $data = $d->jsonSerialize();
        }
        $req = $client->newRequest("POST", "/{accountname}/settings/system/contactaddresstypes");
        $req->setBody($data, "json");

        $result = $req->run("json");
        return ContactAddressType::fromJson($result);
    }

    /**
     * Modify an existing contact address type
     *
     * @param Client $client
     * @param int $id
     * @param \Ticketmatic\Model\ContactAddressType|array $data
     *
     * @throws ClientException
     *
     * @return \Ticketmatic\Model\ContactAddressType
     */
    public static function update(Client $client, $id, $data) {
        if ($data == null || is_array($data)) {
            $d = new ContactAddressType($data == null ? array() : $data);
            $data = $d->jsonSerialize();
        }
        $req = $client->newRequest("PUT", "/{accountname}/settings/system/contactaddresstypes/{id}");
        $req->addParameter("id", $id);

        $req->setBody($data, "json");

        $result = $req->run("json");
        return ContactAddressType::fromJson($result);
    }

    /**
     * Remove a contact address type
     *
     * Contact address types are archivable: this call won't actually delete the object
     * from the database. Instead, it will mark the object as archived, which means it
     * won't show up anymore in most places.
     *
     * Most object types are archivable and can't be deleted: this is needed to ensure
     * consistency of historical data.
     *
     * @param Client $client
     * @param int $id
     *
     * @throws ClientException
     */
    public static function delete(Client $client, $id) {
        $req = $client->newRequest("DELETE", "/{accountname}/settings/system/contactaddresstypes/{id}");
        $req->addParameter("id", $id);

        $req->run("json");
    }

    /**
     * Fetch translatable fields
     *
     * Returns a dictionary with string values in all languages for each translatable
     * field.
     *
     * See translations (api/coreconcepts/translations) for more information.
     *
     * @param Client $client
     * @param int $id
     *
     * @throws ClientException
     *
     * @return string[]
     */
    public static function translations(Client $client, $id) {
        $req = $client->newRequest("GET", "/{accountname}/settings/system/contactaddresstypes/{id}/translate");
        $req->addParameter("id", $id);

        $result = $req->run("json");
        return $result;
    }

    /**
     * Update translations
     *
     * Sets updated translation strings.
     *
     * See translations (api/coreconcepts/translations) for more information.
     *
     * @param Client $client
     * @param int $id
     * @param string[]|array $data
     *
     * @throws ClientException
     *
     * @return string[]
     */
    public static function translate(Client $client, $id, $data) {
        $req = $client->newRequest("PUT", "/{accountname}/settings/system/contactaddresstypes/{id}/translate");
        $req->addParameter("id", $id);

        $req->setBody($data, "json");

        $result = $req->run("json");
        return $result;
    }
}


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package gorilla/rpc/json provides a codec for JSON-RPC over HTTP services.

To register the codec in a RPC server:

	import (
		"http"
		"github.com/gorilla/rpc/RpcHTTP"
		"github.com/gorilla/rpc/RpcHTTP/json"
	)

	func init() {
		s := rpc.NewServer()
		s.RegisterCodec(json.NewCodec(), "application/json")
		// [...]
		http.Handle("/rpc", s)
	}

A codec is tied to a content type. In the example above, the server will use
the JSON codec for requests with "application/json" as the value for the
"Content-Type" header.

This package follows the JSON-RPC 1.0 specification:

	http://json-rpc.org/wiki/specification

Request format is:

	method:
		The name of the method to be invoked, as a string in dotted notation
		as in "Service.Method".
	params:
		An array with a single object to pass as argument to the method.
	id:
		The request id, a uint. It is used to match the response with the
		request that it is replying to.

Response format is:

	result:
		The Object that was returned by the invoked method,
		or null in case there was an error invoking the method.
	error:
		An Error object if there was an error invoking the method,
		or null if there was no error.
	id:
		The same id as the request it is responding to.

Check the gorilla/rpc documentation for more details:

	http://gorilla-web.appspot.com/pkg/rpc
*/
package jsonrpc


text:
package com.andrewvora.apps.rideatlanta.data.local.notifications;

import com.andrewvora.apps.rideatlanta.data.local.common.BaseDbContract;

/**
 * Created by faytx on 10/23/2016.
 * @author Andrew Vorakrajangthiti
 */

public interface NotificationsDbContract {

    final class NotificationsTable implements BaseDbContract {
        public static final String TABLE_NAME = "notifications";

        public static final String COLUMN_NOTIFICATION_ID = "notification_id";
        public static final String COLUMN_ALERT_DATE = "alert_date";
        public static final String COLUMN_MESSAGE = "message";

        public static final String CREATE_STATEMENT = String.format(
                "CREATE TABLE %s (%s %s PRIMARY KEY, %s %s, %s %s, %s %s)",
                TABLE_NAME,
                _ID, TYPE_STRING,
                COLUMN_NOTIFICATION_ID, TYPE_STRING,
                COLUMN_ALERT_DATE, TYPE_STRING,
                COLUMN_MESSAGE, TYPE_STRING
        );

        public static String[] getColumns() {
            return new String[] {
                    _ID,
                    COLUMN_NOTIFICATION_ID,
                    COLUMN_ALERT_DATE,
                    COLUMN_MESSAGE
            };
        }
    }
}


text:
package ru.rkhaustov.chess;

/**
 * @author rvkhaustov
 * @version 1.0
 * @since 05.2017
 */
public class FigureNotFoundException extends RuntimeException {
    /**
     *
     * @param msg - text message.
     */
    public FigureNotFoundException(String msg) {
        super(msg);
    }

}


text:
module Stubhub
  class VenueZoneSection < Document;end
end