text:
package io.seata.rm;

import io.seata.core.protocol.transaction.UndoLogDeleteRequest;
import io.seata.rm.datasource.DataSourceManager;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.undo.UndoLogManager;
import org.junit.jupiter.api.Test;

import java.sql.Connection;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.anyString;

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

/**
 * @author selfishlover
 */
class RMHandlerATTest {

    @Test
    void hasUndoLogTableTest() {
        RMHandlerAT handler = buildHandler(true);
        UndoLogDeleteRequest request = buildRequest();
        int testTimes = 5;
        for (int i = 0; i < testTimes; i++) {
            handler.handle(request);
        }
        verify(handler, times(1)).checkUndoLogTableExist(any());
        verify(handler, times(testTimes)).deleteUndoLog(any(), any(), any());
    }

    @Test
    void noUndoLogTableTest() {
        RMHandlerAT handler = buildHandler(false);
        UndoLogDeleteRequest request = buildRequest();
        int testTimes = 5;
        for (int i = 0; i < testTimes; i++) {
            handler.handle(request);
        }
        verify(handler, times(1)).checkUndoLogTableExist(any());
        verify(handler, never()).deleteUndoLog(any(), any(), any());
    }

    private RMHandlerAT buildHandler(boolean hasUndoLogTable) {
        RMHandlerAT handler = spy(new RMHandlerAT());
        DataSourceManager dataSourceManager = mock(DataSourceManager.class);
        doReturn(dataSourceManager).when(handler).getResourceManager();

        DataSourceProxy dataSourceProxy = mock(DataSourceProxy.class);
        when(dataSourceManager.get(anyString())).thenReturn(dataSourceProxy);

        Connection connection = mock(Connection.class);
        assertDoesNotThrow(() -> {
            when(dataSourceProxy.getPlainConnection()).thenReturn(connection);
        });

        UndoLogManager manager = mock(UndoLogManager.class);
        when(manager.hasUndoLogTable(any())).thenReturn(hasUndoLogTable);
        doReturn(manager).when(handler).getUndoLogManager(any());

        return handler;
    }

    private UndoLogDeleteRequest buildRequest() {
        UndoLogDeleteRequest request = new UndoLogDeleteRequest();
        request.setResourceId("test");
        request.setSaveDays((short) 1);
        return request;
    }
}


text:
package util

import (
	"fmt"
	"io"
	"strings"

	"github.com/spf13/cobra"

	kcmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
)

func DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string) {
	return func(c *cobra.Command, args []string) {
		c.SetOutput(out)

		if len(args) > 0 {
			kcmdutil.CheckErr(kcmdutil.UsageError(c, fmt.Sprintf(`unknown command "%s"`, strings.Join(args, " "))))
		}

		c.Help()
	}
}

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import pandas as pd

if len(sys.argv) != 4:
    print("This script finds all stressors in both files and only retain the items in base machine.")
    print("Usage: ./retain_base.py <base machine name> <reference machine name> <destination folder>")
    sys.exit()

base_machine = sys.argv[1]
ref_machine = sys.argv[2]
dest = sys.argv[3]

df_base = pd.read_json(base_machine)
df_ref = pd.read_json(ref_machine)

column_prefix = 'ref_'

df_ref.rename(columns = lambda x : column_prefix + x, inplace=True)

df = pd.merge(df_base, df_ref, how='inner', left_on='name', right_on=column_prefix+'name')
df = df.filter(regex='^(?!'+column_prefix+')\w+')

if not os.path.exists(dest):
    os.makedirs(dest)
df.to_json(dest+'/retained.json', orient='records')


text:
layout: page
---

### Weblog Link:  Africa with Us (May 2014 - Present)

* Share my global and domestic experiences about global health leadership, health education, immigrant and refugee health, gender equality and human rights in personal blog. Posted 164 stories as of October 29th 2016.

### Organizer of Science Conference

`Mar.2012-Jan.2014` __Young Generation Technical & Leadership Conference 2012, 2013, 2014, U.S.__

* Launched first science conference for 1st generation of Korean international students in the U.S. and helped them to connect and get involved in Korean-American Scientists and Engineers Association activities in Chicago, IL.
* Won Best Essay Award, "Africa with Us," 1st Place Prize in recognition of exceptional achievement in Los Angeles, CA.
* Organized Graduate Track Committee for Korean-American young professionals and students. Motivated students to prepare and present their own research topics to audience and scheduled guest speaker sessions in Houston, TX.

### Staff Sergeant & Airman Representative (Delta 31)

`May2008-July2010` __Republic of Korea Air Force, South Korea__

* Served full-time at Republic of Korea Air Force more than two years in Daegu, South Korea. Established mission driven-solutions with fellow soldiers for developing communication loop between subordinates and their superiors.
* Named exemplary Airman (Dec. 2009). Received prize for Short Novel: "The Dance," runner-up at Ministry of National Defense Literature Contest (Nov. 2009). Won first place in Book Report Speech Contest (Nov. 2009). Won third place in Patriotism Speech Contest (July 2009).

### Local Committee President & Human Resource National Vice President

`Oct.2004-Sept.2006` __AIESEC (Association Internationale des Étudiants en Sciences Économiques et Commerciales), South Korea__

* Held Pusan Local Committee President position in 2005 and Human Resource National Vice President position in 2006 consecutively at AIESEC Korea, global not-for-profit organization in 126 countries providing education and internship opportunities for university students to eradicate extreme poverty and hunger around the globe.
* Launched, organized and managed AIESEC's global leadership conferences: 2005 Korea-Japan-Taiwan International Conference in Fukuoka, Japan, and 2006 National Leadership Development Seminar in Seoul, South Korea.


text:
enum_t(Id, u32, {
    WIN_MAPPROPERTIES = ID_FIRST,
    WIN_FORCES,
    WIN_UNITSETTINGS,
    WIN_UPGRADESETTINGS,
    WIN_TECHSETTINGS,
    WIN_STRINGEDITOR,
    WIN_WAVEDITOR
});

MapSettingsWindow::MapSettingsWindow() : currTab(Tab::MapProperties)
{

}

MapSettingsWindow::~MapSettingsWindow()
{

}

bool MapSettingsWindow::CreateThis(HWND hParent)
{
    return ClassDialog::CreateModelessDialog(MAKEINTRESOURCE(IDD_MAPSETTINGS), hParent);
}

bool MapSettingsWindow::DestroyThis()
{
    currTab = Tab::MapProperties;
    ClassDialog::DestroyDialog();
    return true;
}

void MapSettingsWindow::ChangeTab(Tab tab)
{
    tabs.SetCurSel((u32)tab);

    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_MAPPROPERTIES), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_FORCES), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UNITSETTINGS), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UPGRADESETTINGS), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_TECHSETTINGS), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_STRINGEDITOR), SW_HIDE);
    ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_WAVEDITOR), SW_HIDE);

    switch ( tab )
    {
        case Tab::MapProperties: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_MAPPROPERTIES), SW_SHOW); break;
        case Tab::Forces: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_FORCES), SW_SHOW); break;
        case Tab::UnitSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UNITSETTINGS), SW_SHOW); break;
        case Tab::UpgradeSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UPGRADESETTINGS), SW_SHOW); break;
        case Tab::TechSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_TECHSETTINGS), SW_SHOW); break;
        case Tab::StringEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_STRINGEDITOR), SW_SHOW); break;
        case Tab::WavEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_WAVEDITOR), SW_SHOW); break;
    }

    currTab = tab;
}

void MapSettingsWindow::RefreshWindow()
{
    mapPropertiesWindow.RefreshWindow();
    forcesWindow.RefreshWindow();
    unitSettingsWindow.RefreshWindow();
    upgradeSettingsWindow.RefreshWindow();
    techSettingsWindow.RefreshWindow();
    stringEditorWindow.RefreshWindow();
    wavEditorWindow.RefreshWindow();
}

BOOL MapSettingsWindow::DlgNotify(HWND hWnd, WPARAM idFrom, NMHDR* nmhdr)
{
    switch ( nmhdr->code )
    {
    case TCN_SELCHANGE:
    {
        Tab selectedTab = (Tab)tabs.GetCurSel();
        switch ( selectedTab )
        {
        case Tab::MapProperties: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_MAPPROPERTIES), SW_SHOW); break;
        case Tab::Forces: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_FORCES), SW_SHOW); break;
        case Tab::UnitSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UNITSETTINGS), SW_SHOW); break;
        case Tab::UpgradeSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UPGRADESETTINGS), SW_SHOW); break;
        case Tab::TechSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_TECHSETTINGS), SW_SHOW); break;
        case Tab::StringEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_STRINGEDITOR), SW_SHOW); break;
        case Tab::WavEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_WAVEDITOR), SW_SHOW); break;
        }
    }
    break;

    case TCN_SELCHANGING:
    {
        Tab selectedTab = (Tab)tabs.GetCurSel();
        switch ( selectedTab )
        {
        case Tab::MapProperties: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_MAPPROPERTIES), SW_HIDE); break;
        case Tab::Forces: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_FORCES), SW_HIDE); break;
        case Tab::UnitSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UNITSETTINGS), SW_HIDE); break;
        case Tab::UpgradeSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_UPGRADESETTINGS), SW_HIDE); break;
        case Tab::TechSettings: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_TECHSETTINGS), SW_HIDE); break;
        case Tab::StringEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_STRINGEDITOR), SW_HIDE); break;
        case Tab::WavEditor: ShowWindow(GetDlgItem(tabs.getHandle(), Id::WIN_WAVEDITOR), SW_HIDE); break;
        }
    }
    break;
    default:
        return FALSE;
        break;
    }
    return TRUE;
}

BOOL MapSettingsWindow::DlgCommand(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    switch ( LOWORD(wParam) )
    {
    case IDCANCEL:
        EndDialog(hWnd, IDCANCEL);
        break;
    default:
        return FALSE;
        break;
    }
    return TRUE;
}

BOOL MapSettingsWindow::DlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch ( msg )
    {
        case WM_ACTIVATE:
            if ( LOWORD(wParam) != WA_INACTIVE )
                chkd.SetCurrDialog(hWnd);
            break;

        case WM_INITDIALOG:
            {
                const std::vector<std::string> tabTitles = {
                    "Map Properties", "Forces", "Unit Settings", "Upgrade Settings",
                    "Tech Settings", "String Editor", "Wav Editor"
                };

                tabs.FindThis(getHandle(), IDC_MAPSETTINGSTABS);
                HANDLE icon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PROGRAM_ICON), IMAGE_ICON, 16, 16, 0);
                tabs.SetSmallIcon(icon);
                tabs.SetFont(defaultFont, false);

                TCITEM item = { };
                item.mask = TCIF_TEXT;
                item.iImage = -1;

                for ( u32 i=0; i<tabTitles.size(); i++ )
                    tabs.InsertTab(i, tabTitles[i]);

                mapPropertiesWindow.CreateThis(tabs.getHandle(), Id::WIN_MAPPROPERTIES);
                forcesWindow.CreateThis(tabs.getHandle(), Id::WIN_FORCES);
                unitSettingsWindow.CreateThis(tabs.getHandle(), Id::WIN_UNITSETTINGS);
                upgradeSettingsWindow.CreateThis(tabs.getHandle(), Id::WIN_UPGRADESETTINGS);
                techSettingsWindow.CreateThis(tabs.getHandle(), Id::WIN_TECHSETTINGS);
                stringEditorWindow.CreateThis(tabs.getHandle(), Id::WIN_STRINGEDITOR);
                wavEditorWindow.CreateThis(tabs.getHandle(), Id::WIN_WAVEDITOR);
                ReplaceChildFonts(defaultFont);
                RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE);
            }
            break;

        case WM_MOUSEWHEEL:
            if ( currTab == Tab::StringEditor )
                SendMessage(GetDlgItem(tabs.getHandle(), Id::WIN_STRINGEDITOR), WM_MOUSEWHEEL, wParam, lParam);
            else
                return FALSE;
            break;

        case WM_CLOSE:
            DestroyThis();
            break;

        default:
            return FALSE;
            break;
    }

    return TRUE;
}


text:
package polarserver

import (
	"fmt"

	"github.com/Jordanzuo/goutil/configUtil"
	"github.com/Jordanzuo/goutil/debugUtil"
	"github.com/Jordanzuo/goutil/logUtil"
	"github.com/Jordanzuo/goutil/xmlUtil"
	"github.com/polariseye/polarserver/common"
	"github.com/polariseye/polarserver/dataBase"
	"github.com/polariseye/polarserver/moduleManage"
	"github.com/polariseye/polarserver/server"
	"github.com/polariseye/polarserver/server/webServer"
	"github.com/polariseye/polarserver/server/webServer/apiHandle"
)

var (
	// 服务管理对象
	serverManagerObj *server.ServerManagerStruct = server.NewServerManager()

	// web服务对象
	webServerObj *webServer.WebServerStruct

	// 配置对象
	configObj *configUtil.XmlConfig

	// 处理对象
	clientHandler *apiHandle.Handle4JsonStruct

	// 客户端Api接口
	clientApiManager *moduleManage.ApiModuleManagerStruct = moduleManage.NewApiModuleManager()

	// 处理对象
	manageHandler *apiHandle.Handle4JsonStruct

	// 后端Api接口
	mangageApiManager *moduleManage.ApiModuleManagerStruct = moduleManage.NewApiModuleManager()
)

func init() {
	mangageApiManager.SetMethodPrefix("M_")
	mangageApiManager.SetTestMethodPrefix("MTest_")

	moduleManage.AddApiManager(clientApiManager)
	moduleManage.AddApiManager(mangageApiManager)
}

// 初始化
// configFileName:配置文件名
// errMsg:错误信息
func Init(configFileName string) (errMsg error) {
	root, errMsg := xmlUtil.LoadFromFile(configFileName)
	if errMsg != nil {
		return
	}

	configObj = configUtil.NewXmlConfig(root)

	// 初始化日志记录
	logUtil.SetLogPath(configObj.DefaultString("Config/LogPath", "", "DefaultLogPath/"))

	// 初始化是否是测试模式
	common.SetIsTest(configObj.DefaultBool("Config/IsTest", "", false))

	// 初始化是否是调试模式
	debugUtil.SetDebug(configObj.DefaultBool("Config/IsDebug", "", false))

	// 数据库配置初始化
	errMsg = initDataBaseFromConfig(configObj)
	if errMsg != nil {
		return errMsg
	}

	// web服务配置初始化
	initWebServerFromConfig(configObj)

	return nil
}

// web服务对象
func WebServerObj() *webServer.WebServerStruct {
	return webServerObj
}

// 服务管理对象
func ServerManagerObj() *server.ServerManagerStruct {
	return serverManagerObj
}

// 配置对象
func ConfigObj() *configUtil.XmlConfig {
	return configObj
}

// 初始化web服务
func initWebServerFromConfig(config *configUtil.XmlConfig) {
	// web服务初始化
	port := config.DefaultInt("Config/WebPort", "", 2017)
	webServerObj = webServer.NewWebServer(int32(port), "web 服务")

	// 初始化客户端Api处理
	clientHandler := apiHandle.NewHandle4Json(clientApiManager)
	webServerObj.AddRouter("/Api/Client", clientHandler.RequestHandle)

	// 初始化后台api处理
	manageHandler := apiHandle.NewHandle4Json(mangageApiManager)
	webServerObj.AddRouter("/Api/Manage", manageHandler.RequestHandle)

	// 注册模块
	ServerManagerObj().Register(webServerObj)
}

// 从配置文件初始化数据库
func initDataBaseFromConfig(config *configUtil.XmlConfig) error {
	dbConnectionNode := config.Node("Config/DbConnection")
	if dbConnectionNode == nil {
		return fmt.Errorf("未找到配置节点:Config/DbConnection")
	}

	connectionData := dbConnectionNode.Children()
	for _, connectionInfo := range connectionData {
		var driver, connectionString string

		driver = connectionInfo.SelectAttr("Driver")
		if driver == "" {
			return fmt.Errorf("数据库配置不合法,不存在节点或其空:Config/DbConnection/%v的属性:Driver", connectionInfo.NodeName)
		}

		connectionString = connectionInfo.InnerText()
		if connectionString == "" {
			return fmt.Errorf("数据库配置不合法,不存在节点:Config/DbConnection/%v不存在连接配置文本", connectionInfo.NodeName)
		}

		errMsg := dataBase.AddConnection(connectionInfo.NodeName, driver, connectionString)
		if errMsg != nil {
			return errMsg
		}
	}

	return nil
}

// 客户端管理对象
func ClientApiManager() *moduleManage.ApiModuleManagerStruct {
	return clientApiManager
}

// 后端管理对象
func MangageApiManager() *moduleManage.ApiModuleManagerStruct {
	return clientApiManager
}


text:
require 'json'

module Rearview
  module Alerts
    class PagerDutyAlert < Base

      def alert(job, result)
        job.alert_keys.each do |key|
          params = PagerDutyAlert.params(key)
          if PagerDutyAlert.key?(params)
            logger.info "#{self} send alert for #{job.inspect} and key #{key} with params #{params}"
            pagerduty_uri = Rearview.config.pagerduty_url
            job_uri       = Rearview::UrlHelper.job_url(job)
            msg           = result[:message]

            description = if msg
                            "#{msg.first(1024)} #{job_uri}"
                          else
                            "Rearview job #{job.id} #{job_uri}"
                          end

            options = { :body =>
              {
                :service_key  => params["token"],
                :event_type   => "trigger",
                :incident_key => "rearview/#{job.id}",
                :description  => description,
                :details     => result
              }.to_json
            }

            HTTParty.post(pagerduty_uri, options)
          end
        end
      end

      def self.params(key)
        uri = URI(key)
        if uri.scheme.present?
          {
            "scheme" => uri.scheme,
            "token" => uri.opaque,
          }
        end
      rescue
        {}
      end

      def self.key?(key)
        p = key_to_params(key)
        valid_scheme?(p["scheme"]) && valid_token?(p["token"])
      end

      def self.valid_token?(token)
        token.present? && token.match(/^\h{32}$/)
      end

      def self.scheme
        "pagerduty"
      end

    end
  end
end


text:
#include "sqlitepp.h"

using namespace Common;

namespace sqlite
{
	//-----------------------------------------------------------------------------------------
	// Class: SQLiteError
	//
	SQLiteError::SQLiteError(int error) : exception(err_descs[error])
	{
	}

	SQLiteError::SQLiteError(const char* e) : exception(e)
	{
	}

	SQLiteError::~SQLiteError()
	{
	}

	//-----------------------------------------------------------------------------------------
	// Class: SQLite
	//
	SQLite::SQLite(const std::string& path_to_db)
	{
		int result = sqlite3_open(path_to_db.c_str(), &sqlhandle);

		if (result != SQLITE_OK) { // some error
			std::string desc = LastError();
			sqlite3_close(sqlhandle);
			throw SQLiteError(desc.c_str());
		}
	}

	SQLite::~SQLite()
	{
		Close();
	}

	void SQLite::Close()
	{
		if (sqlhandle) {
			sqlite3_close(sqlhandle);
			sqlhandle = NULL;
		}
	}

	sqlite3* SQLite::GetSQLite()
	{
		if (!sqlhandle) throw SQLiteError(SQL_ERRCODE_CLOSED);
		return sqlhandle;
	}

	std::unique_ptr<SQLiteQuery> SQLite::NewQuery(const std::wstring& query)
	{
		return std::unique_ptr<SQLiteQuery>(new SQLiteQuery(*this, query));
	}

	const char* SQLite::LastError()
	{
		return sqlite3_errmsg(sqlhandle);
	}

	//-----------------------------------------------------------------------------------------
	// Class: SQLiteObject
	// Purpose: Base class for objects returned to the user
	//
	SQLiteObject::SQLiteObject(SQLite& parent) : parent(parent)
	{
	}

	SQLiteObject::~SQLiteObject()
	{
	}

	//-----------------------------------------------------------------------------------------
	// Class: SQLiteQuery
	// Purpose: Provide an interface for executing prepared queries
	//
	SQLiteQuery::SQLiteQuery(SQLite& parent, const std::wstring& query)
		: SQLiteObject(parent), query(query), stmt(NULL)
	{
		prepare_statement();
	}

	SQLiteQuery::~SQLiteQuery()
	{
		if (stmt) sqlite3_finalize(stmt);
	}

	void SQLiteQuery::prepare_statement()
	{
		// Get a statement handle, on failure abort.
		if (sqlite3_prepare16_v2(parent.GetSQLite(), query.c_str(), -1,
			&stmt, NULL) != SQLITE_OK)
		{
			throw SQLiteError(parent.LastError());
		}
	}

	std::unique_ptr<SQLiteResult> SQLiteQuery::Execute()
	{
		std::unique_ptr<SQLiteResult> out_result(new SQLiteResult());

		while (1)
		{
			int result = sqlite3_step(stmt);
			if (result == SQLITE_DONE) break;

			if (result == SQLITE_ROW) { // data!
				/*if (!out_result) { // no data was expected
					error = SQL_ERRCODE_NDE;
					break;
				}*/
				std::unique_ptr<SQLiteRow> row(new SQLiteRow());

				int columns = sqlite3_column_count(stmt);
				for (int x = 0; x < columns; x++) {
					int type = sqlite3_column_type(stmt, x);
					const char* name = sqlite3_column_name(stmt, x);
					switch (type)
					{
					case SQLITE_INTEGER:
						row->AddColumn(Object::unique_ptr(
							new ObjNumber(sqlite3_column_int(stmt, x))), name);
						break;
					case SQLITE_FLOAT:
						row->AddColumn(Object::unique_ptr(
							new ObjNumber(sqlite3_column_double(stmt, x))), name);
						break;
					case SQLITE_TEXT:
						row->AddColumn(Object::unique_ptr(
							new ObjWString((const wchar_t*)sqlite3_column_text16(stmt, x))),
							name);
						break;
					case SQLITE_BLOB:
						row->AddColumn(Object::unique_ptr(
							new ObjBlob((BYTE*)sqlite3_column_blob(stmt, x),
										sqlite3_column_bytes(stmt, x))),
							name);
						break;
					}
				}
				out_result->AddRow(std::move(row));
			}
			else { // error
				throw SQLiteError(parent.LastError());
			}
		}

		sqlite3_finalize(stmt);
		stmt = NULL;

		return out_result;
	}

	void SQLiteQuery::Reset(const std::wstring& query)
	{
		this->query = query;
		if (stmt) {
			sqlite3_finalize(stmt);
			stmt = NULL;
		}
		prepare_statement();
	}

	void SQLiteQuery::BindValue(const char* name, const SQLiteValue& value)
	{
		BindValue(sqlite3_bind_parameter_index(stmt, name), value);
	}

	void SQLiteQuery::BindValue(int index, const SQLiteValue& value)
	{
		if (!stmt) throw SQLiteError(SQL_ERRCODE_NO_INIT);
		if (!index) throw SQLiteError(SQL_ERRCODE_NO_PARAM);

		int result = 0;
		switch (value.type)
		{
		case TYPE_STRING:
			{
				ObjString& str = static_cast<ObjString&>(*value.object);
				result = sqlite3_bind_text(stmt, index, str.GetValue(),
					-1, SQLITE_TRANSIENT);
			} break;

		case TYPE_WSTRING:
			{
				ObjWString& str = static_cast<ObjWString&>(*value.object);
				result = sqlite3_bind_text16(stmt, index, str.GetValue(),
					-1, SQLITE_TRANSIENT);
			} break;
		case TYPE_INT:
			{
				ObjNumber& num = static_cast<ObjNumber&>(*value.object);
				result = sqlite3_bind_int(stmt, index, (int)num.GetValue());
			}break;
		case TYPE_DOUBLE:
			{
				ObjNumber& num = static_cast<ObjNumber&>(*value.object);
				result = sqlite3_bind_double(stmt, index, num.GetValue());

			}break;
		case TYPE_BLOB:
			{
				ObjBlob& blob = static_cast<ObjBlob&>(*value.object);
				size_t length;
				BYTE* data = blob.GetData(length);
				result = sqlite3_bind_blob(stmt, index, data, length,
					SQLITE_TRANSIENT);

			}break;
		}

		// Handle any errors
		switch (result)
		{
		case SQLITE_OK:
			break;
		default:
			throw SQLiteError(parent.LastError());
			break;
		}
	}

	// --------------------------------------------------------------------
	SQLiteValue::SQLiteValue(const std::string& val)
		: object(new ObjString(val)), type(TYPE_STRING)
	{
	}

	SQLiteValue::SQLiteValue(const std::wstring& val)
		: object(new ObjWString(val)), type(TYPE_WSTRING)
	{
	}

	SQLiteValue::SQLiteValue(const char* val)
		: object(new ObjString(val)), type(TYPE_STRING)
	{
	}

	SQLiteValue::SQLiteValue(const wchar_t* val)
		: object(new ObjWString(val)), type(TYPE_WSTRING)
	{
	}

	SQLiteValue::SQLiteValue(int val)
		: object(new ObjNumber(val)), type(TYPE_INT)
	{
	}

	SQLiteValue::SQLiteValue(double val)
		: object(new ObjNumber(val)), type(TYPE_DOUBLE)
	{
	}

	SQLiteValue::SQLiteValue(BYTE* val, size_t length)
		: object(new ObjBlob(val, length)), type(TYPE_BLOB)
	{
	}

	//-----------------------------------------------------------------------------------------
	// Class: SQLiteRow
	//

	void SQLiteRow::AddColumn(Common::Object::unique_ptr value,
		const std::string& name)
	{
		columns.insert(pair_t(name, std::move(value)));
	}

	Object& SQLiteRow::operator[] (const std::string& key)
	{
		return get(key);
	}

	Object& SQLiteRow::get(const std::string& key)
	{
		auto itr = columns.find(key);
		return *(itr->second);
	}

	size_t SQLiteRow::size()
	{
		return columns.size();
	}

	//-----------------------------------------------------------------------------------------
	// Class: SQLiteResult
	//
	void SQLiteResult::AddRow(std::unique_ptr<SQLiteRow> row)
	{
		rows.push_back(std::move(row));
	}

	SQLiteRow& SQLiteResult::operator[] (size_t i)
	{
		return get(i);
	}

	SQLiteRow& SQLiteResult::get(size_t i)
	{
		return *rows[i];
	}

	size_t SQLiteResult::size()
	{
		return rows.size();
	}
}


text:
package de.bwaldvogel.mongo.oplog;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import org.junit.jupiter.api.Test;

class OperationTypeTest {

    @Test
    void testGetCode() {
        assertThat(OperationType.INSERT.getCode()).isEqualTo("i");
        assertThat(OperationType.UPDATE.getCode()).isEqualTo("u");
        assertThat(OperationType.DELETE.getCode()).isEqualTo("d");
    }

    @Test
    void testFromCode() {
        for (OperationType operationType : OperationType.values()) {
            OperationType operationTypeFromCode = OperationType.fromCode(operationType.getCode());
            assertThat(operationTypeFromCode).isEqualTo(operationType);
        }
    }

    @Test()
    void testFromCode_throwException() {
        assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> OperationType.fromCode("wrongCode"))
            .withMessage("unknown operation type: wrongCode");
    }
}


text:
namespace google {
namespace cloud {
namespace pubsub_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

SchemaServiceMetadata::SchemaServiceMetadata(
    std::shared_ptr<SchemaServiceStub> child)
    : child_(std::move(child)),
      api_client_header_(
          google::cloud::internal::ApiClientHeader("generator")) {}

StatusOr<google::pubsub::v1::Schema> SchemaServiceMetadata::CreateSchema(
    grpc::ClientContext& context,
    google::pubsub::v1::CreateSchemaRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->CreateSchema(context, request);
}

StatusOr<google::pubsub::v1::Schema> SchemaServiceMetadata::GetSchema(
    grpc::ClientContext& context,
    google::pubsub::v1::GetSchemaRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->GetSchema(context, request);
}

StatusOr<google::pubsub::v1::ListSchemasResponse>
SchemaServiceMetadata::ListSchemas(
    grpc::ClientContext& context,
    google::pubsub::v1::ListSchemasRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ListSchemas(context, request);
}

Status SchemaServiceMetadata::DeleteSchema(
    grpc::ClientContext& context,
    google::pubsub::v1::DeleteSchemaRequest const& request) {
  SetMetadata(context, "name=" + request.name());
  return child_->DeleteSchema(context, request);
}

StatusOr<google::pubsub::v1::ValidateSchemaResponse>
SchemaServiceMetadata::ValidateSchema(
    grpc::ClientContext& context,
    google::pubsub::v1::ValidateSchemaRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ValidateSchema(context, request);
}

StatusOr<google::pubsub::v1::ValidateMessageResponse>
SchemaServiceMetadata::ValidateMessage(
    grpc::ClientContext& context,
    google::pubsub::v1::ValidateMessageRequest const& request) {
  SetMetadata(context, "parent=" + request.parent());
  return child_->ValidateMessage(context, request);
}

void SchemaServiceMetadata::SetMetadata(grpc::ClientContext& context,
                                        std::string const& request_params) {
  context.AddMetadata("x-goog-request-params", request_params);
  SetMetadata(context);
}

void SchemaServiceMetadata::SetMetadata(grpc::ClientContext& context) {
  context.AddMetadata("x-goog-api-client", api_client_header_);
  auto const& options = internal::CurrentOptions();
  if (options.has<UserProjectOption>()) {
    context.AddMetadata("x-goog-user-project",
                        options.get<UserProjectOption>());
  }
  auto const& authority = options.get<AuthorityOption>();
  if (!authority.empty()) context.set_authority(authority);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace pubsub_internal
}  // namespace cloud
}  // namespace google


text:
package org.artifactory.common.wicket.component.dnd.select.sorted;

import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.model.IModel;
import org.artifactory.common.wicket.behavior.JavascriptEvent;
import org.artifactory.common.wicket.component.dnd.select.DragDropSelection;
import org.artifactory.common.wicket.contributor.ResourcePackage;

import java.io.Serializable;
import java.util.List;

/**
 * @author Yoav Aharoni
 */
public class SortedDragDropSelection<T extends Serializable> extends DragDropSelection<T> {

    public SortedDragDropSelection(String id, List<T> choices) {
        super(id, choices);
    }

    public SortedDragDropSelection(String id, IModel<T> model, List<T> choices) {
        super(id, model, choices);
    }

    {
        add(ResourcePackage.forJavaScript(SortedDragDropSelection.class));
    }

    @Override
    public String getWidgetClassName() {
        return isEnabled() ? "artifactory.SortedDragDropSelection" : "artifactory.DisabledSortedDragDropSelection";
    }

    @Override
    protected Behavior newOnOrderChangeEventBehavior(String event) {
        // no ajax notification
        return new JavascriptEvent(event, "");
    }

    @Override
    protected boolean isScriptRendered() {
        return true;
    }
}


text:
use error::{Error};
use fmt;
use sync::atomic::{AtomicBool, Ordering};
use thread;

pub struct Flag { failed: AtomicBool }

// Note that the Ordering uses to access the `failed` field of `Flag` below is
// always `Relaxed`, and that's because this isn't actually protecting any data,
// it's just a flag whether we've panicked or not.
//
// The actual location that this matters is when a mutex is **locked** which is
// where we have external synchronization ensuring that we see memory
// reads/writes to this flag.
//
// As a result, if it matters, we should see the correct value for `failed` in
// all cases.

impl Flag {
    pub const fn new() -> Flag {
        Flag { failed: AtomicBool::new(false) }
    }

    #[inline]
    pub fn borrow(&self) -> LockResult<Guard> {
        let ret = Guard { panicking: thread::panicking() };
        if self.get() {
            Err(PoisonError::new(ret))
        } else {
            Ok(ret)
        }
    }

    #[inline]
    pub fn done(&self, guard: &Guard) {
        if !guard.panicking && thread::panicking() {
            self.failed.store(true, Ordering::Relaxed);
        }
    }

    #[inline]
    pub fn get(&self) -> bool {
        self.failed.load(Ordering::Relaxed)
    }
}

pub struct Guard {
    panicking: bool,
}

/// A type of error which can be returned whenever a lock is acquired.
///
/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(1));
///
/// // poison the mutex
/// let c_mutex = mutex.clone();
/// let _ = thread::spawn(move || {
///     let mut data = c_mutex.lock().unwrap();
///     *data = 2;
///     panic!();
/// }).join();
///
/// match mutex.lock() {
///     Ok(_) => unreachable!(),
///     Err(p_err) => {
///         let data = p_err.get_ref();
///         println!("recovered: {}", data);
///     }
/// };
/// ```
///
/// [`Mutex`]: ../../std/sync/struct.Mutex.html
/// [`RwLock`]: ../../std/sync/struct.RwLock.html
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PoisonError<T> {
    guard: T,
}

/// An enumeration of possible errors associated with a [`TryLockResult`] which
/// can occur while trying to aquire a lock, from the [`try_lock`] method on a
/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
///
/// [`Mutex`]: struct.Mutex.html
/// [`RwLock`]: struct.RwLock.html
/// [`TryLockResult`]: type.TryLockResult.html
/// [`try_lock`]: struct.Mutex.html#method.try_lock
/// [`try_read`]: struct.RwLock.html#method.try_read
/// [`try_write`]: struct.RwLock.html#method.try_write
#[stable(feature = "rust1", since = "1.0.0")]
pub enum TryLockError<T> {
    /// The lock could not be acquired because another thread failed while holding
    /// the lock.
    #[stable(feature = "rust1", since = "1.0.0")]
    Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
    /// The lock could not be acquired at this time because the operation would
    /// otherwise block.
    #[stable(feature = "rust1", since = "1.0.0")]
    WouldBlock,
}

/// A type alias for the result of a lock method which can be poisoned.
///
/// The [`Ok`] variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
/// the associated guard, and it can be acquired through the [`into_inner`]
/// method.
///
/// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
/// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
#[stable(feature = "rust1", since = "1.0.0")]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;

/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the [`Err`] type as the lock may not
/// have been acquired for other reasons.
///
/// [`LockResult`]: ../../std/sync/type.LockResult.html
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
#[stable(feature = "rust1", since = "1.0.0")]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for PoisonError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        "PoisonError { inner: .. }".fmt(f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for PoisonError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        "poisoned lock: another task failed inside".fmt(f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Error for PoisonError<T> {
    fn description(&self) -> &str {
        "poisoned lock: another task failed inside"
    }
}

impl<T> PoisonError<T> {
    /// Creates a `PoisonError`.
    ///
    /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
    ///
    /// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
    /// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
    #[stable(feature = "sync_poison", since = "1.2.0")]
    pub fn new(guard: T) -> PoisonError<T> {
        PoisonError { guard: guard }
    }

    /// Consumes this error indicating that a lock is poisoned, returning the
    /// underlying guard to allow access regardless.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashSet;
    /// use std::sync::{Arc, Mutex};
    /// use std::thread;
    ///
    /// let mutex = Arc::new(Mutex::new(HashSet::new()));
    ///
    /// // poison the mutex
    /// let c_mutex = mutex.clone();
    /// let _ = thread::spawn(move || {
    ///     let mut data = c_mutex.lock().unwrap();
    ///     data.insert(10);
    ///     panic!();
    /// }).join();
    ///
    /// let p_err = mutex.lock().unwrap_err();
    /// let data = p_err.into_inner();
    /// println!("recovered {} items", data.len());
    /// ```
    #[stable(feature = "sync_poison", since = "1.2.0")]
    pub fn into_inner(self) -> T { self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// reference to the underlying guard to allow access regardless.
    #[stable(feature = "sync_poison", since = "1.2.0")]
    pub fn get_ref(&self) -> &T { &self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// mutable reference to the underlying guard to allow access regardless.
    #[stable(feature = "sync_poison", since = "1.2.0")]
    pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<PoisonError<T>> for TryLockError<T> {
    fn from(err: PoisonError<T>) -> TryLockError<T> {
        TryLockError::Poisoned(err)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for TryLockError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
            TryLockError::WouldBlock => "WouldBlock".fmt(f)
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for TryLockError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
            TryLockError::WouldBlock => "try_lock failed because the operation would block"
        }.fmt(f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Error for TryLockError<T> {
    fn description(&self) -> &str {
        match *self {
            TryLockError::Poisoned(ref p) => p.description(),
            TryLockError::WouldBlock => "try_lock failed because the operation would block"
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            TryLockError::Poisoned(ref p) => Some(p),
            _ => None
        }
    }
}

pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
                           -> LockResult<U>
                           where F: FnOnce(T) -> U {
    match result {
        Ok(t) => Ok(f(t)),
        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
    }
}


text:
Frontend JSON workspace, a Chrome extension

[Chrome Store](https://chrome.google.com/webstore/detail/bang-json-workspace/dfmpfciemnocjnpfddbefbhhamhjcmgl)

License
-------

    Copyright (c) 2015, Groupon, Inc.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    Neither the name of GROUPON nor the names of its contributors may be
    used to endorse or promote products derived from this software without
    specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Hightlights:

##### Custom Javascript expression can be applied onto JSON response directly
Supporting [Underscore](http://underscorejs.org/), [Backbone](http://backbonejs.org), [d3](http://d3js.org), and [jquery](http://jquery.com)
![screen shot 2015-01-21 at 00 29 58](https://cloud.githubusercontent.com/assets/4080835/5832066/9d032356-a104-11e4-9243-2a35e7cf3fae.png)

##### Check JSON array's scheme on the fly
![screen shot 2](https://github.groupondev.com/github-enterprise-assets/0000/1817/0000/9724/4b65e138-c688-11e4-878b-92b1bfa2b951.png)

##### Browse easily within an array
![screen shot 1](https://github.groupondev.com/github-enterprise-assets/0000/1817/0000/9723/88c06770-c687-11e4-8981-d54f0bb0212b.png)

##### Url editing utility for quick poking around an unfamiliar API
![screen shot 2015-01-26 at 13 02 30](https://cloud.githubusercontent.com/assets/4080835/5906227/97593b06-a55b-11e4-8a9b-645ee01a7e1a.png)

[Available in Chrome Store](https://chrome.google.com/webstore/detail/bang-json-workspace/dfmpfciemnocjnpfddbefbhhamhjcmgl)

# How to build
> I use Grunt as the task managing tool

1. Make sure you have node.js and npm installed
2. `npm install`
3. `npm run build` or `grunt`

# How to test
`npm test` or `grunt testClient`

# How to load the developing code into Chrome locally

Load the plugin from `dist` folder following the steps below

> a. Visit chrome://extensions in your browser (or open up the Chrome menu by clicking the icon to the far right of the Omnibox.  The menu's icon is three horizontal bars. and select Extensions under the Tools menu to get to the same place).
>
> b. Ensure that the Developer mode checkbox in the top right-hand corner is checked.
>
> c. Click Load unpacked extension… to pop up a file-selection dialog.
>
> d. Navigate to the directory in which your extension files live, and select it.
>
> https://developer.chrome.com/extensions/getstarted#unpacked


text:
package droplet_runner_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestDropletRunner(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "DropletRunner Suite")
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <bytecodeTargetLevel>
      <module name="wasabi-core_main" target="1.8" />
      <module name="wasabi-core_test" target="1.8" />
      <module name="wasabi-samples_main" target="1.8" />
      <module name="wasabi-samples_test" target="1.8" />
      <module name="wasabi_main" target="1.8" />
      <module name="wasabi_test" target="1.8" />
    </bytecodeTargetLevel>
  </component>
</project>


text:
#include <VRThreadGroupNode.h>
#include <iostream>

namespace MinVR {

VRThreadGroupNode::VRThreadGroupNode(const std::string& name, bool asyncEnabled) : VRDisplayNode(name), threadGroup(NULL), async(true), asyncEnabled(asyncEnabled) {
}

VRThreadGroupNode::~VRThreadGroupNode() {
	// Terminate render thread loop
	threadGroup->startThreadAction(THREADACTION_Terminate, NULL, NULL);

	// Delete render threads
	for (int f = 0; f < renderThreads.size(); f++) {
		delete renderThreads[f];
	}

	// Delete thread group
	if (threadGroup) {
		delete threadGroup;
	}
}

void VRThreadGroupNode::render(VRDataIndex* renderState,
		VRRenderHandler* renderHandler) {

	// If the threadGroup has not been created, create the render threads
	if (!threadGroup) {
		async = asyncEnabled;
		int numThreads = getChildren().size();
		threadGroup = new VRThreadGroup(numThreads);

		for (int f = 0; f < numThreads; f++) {
			renderThreads.push_back(new VRRenderThread(getChildren()[f], threadGroup));
			renderThreads[f]->threadId = f;
		}
	}

	if (async) {
		// Let threads know they are ready for rendering
			VRDataIndex rstate;
			threadGroup->startThreadAction(THREADACTION_Render, &rstate, renderHandler);
			threadGroup->waitForComplete();
	}
	else {
		VRDisplayNode::render(renderState, renderHandler);
	}

}

void VRThreadGroupNode::waitForRenderToComplete(VRDataIndex* renderState) {
	if (async) {
		// Let threads know we are waiting for them to finish rendering
		VRDataIndex rstate;
		threadGroup->startThreadAction(THREADACTION_WaitForRenderToComplete, &rstate, NULL);
		threadGroup->waitForComplete();
	}
	else {
		VRDisplayNode::waitForRenderToComplete(renderState);
	}
}

void VRThreadGroupNode::displayFinishedRendering(VRDataIndex* renderState) {
	if (async) {
		// Let threads know that we should display the results
		VRDataIndex rstate;
		threadGroup->startThreadAction(THREADACTION_DisplayFinishedRendering, &rstate, NULL);
		threadGroup->waitForComplete();
	}
	else {
		VRDisplayNode::displayFinishedRendering(renderState);
	}

	async = asyncEnabled;
}

VRDisplayNode* VRThreadGroupNode::create(VRMainInterface* vrMain,
		VRDataIndex* config, const std::string& nameSpace) {
	bool asyncEnabled = int(config->getValue("AsyncEnabled", nameSpace));
	return new VRThreadGroupNode(nameSpace, asyncEnabled);
}

} /* namespace MinVR */


text:
package com.thoughtworks.go.server.security.providers;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.PluginRoleConfig;
import com.thoughtworks.go.config.SecurityAuthConfig;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationExtension;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationMetadataStore;
import com.thoughtworks.go.plugin.access.authorization.models.AuthenticationResponse;
import com.thoughtworks.go.plugin.access.authorization.models.User;
import com.thoughtworks.go.server.security.AuthorityGranter;
import com.thoughtworks.go.server.security.userdetail.GoUserPrinciple;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.server.service.PluginRoleService;
import com.thoughtworks.go.server.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;

import java.util.Collections;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isNotBlank;

public class PluginAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    private final AuthorizationExtension authorizationExtension;
    private final AuthorizationMetadataStore store;
    private final AuthorityGranter authorityGranter;
    private GoConfigService configService;
    private PluginRoleService pluginRoleService;
    private UserService userService;

    @Autowired
    public PluginAuthenticationProvider(AuthorizationExtension authorizationExtension, AuthorityGranter authorityGranter, GoConfigService configService,
                                        PluginRoleService pluginRoleService, UserService userService) {
        this.authorizationExtension = authorizationExtension;
        this.store = AuthorizationMetadataStore.instance();
        this.authorityGranter = authorityGranter;
        this.configService = configService;
        this.pluginRoleService = pluginRoleService;
        this.userService = userService;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        assertPasswordNotBlank(authentication);
        User user = getUserDetailsFromAuthorizationPlugins(username, authentication);

        if (user == null) {
            removeAnyAssociatedPluginRolesFor(username);
            throw new UsernameNotFoundException("Unable to authenticate user: " + username);
        }

        userService.addUserIfDoesNotExist(toDomainUser(user));
        GoUserPrinciple goUserPrinciple = new GoUserPrinciple(user.getUsername(), user.getDisplayName(), "",
                authorityGranter.authorities(user.getUsername()), loginName(username, authentication));
        return goUserPrinciple;
    }

    private void assertPasswordNotBlank(UsernamePasswordAuthenticationToken authentication) {
        String password = (String) authentication.getCredentials();

        if (StringUtils.isBlank(password)) {
            throw new BadCredentialsException("Empty Password");
        }
    }

    private com.thoughtworks.go.domain.User toDomainUser(User user) {
        return new com.thoughtworks.go.domain.User(user.getUsername(), user.getDisplayName(), user.getEmailId());
    }

    private void removeAnyAssociatedPluginRolesFor(String username) {
        pluginRoleService.revokeAllRolesFor(username);
    }

    private User getUserDetailsFromAuthorizationPlugins(String username, UsernamePasswordAuthenticationToken authentication) {
        String loginName = loginName(username, authentication);
        String password = (String) authentication.getCredentials();

        for (SecurityAuthConfig authConfig : configService.security().securityAuthConfigs()) {
            String pluginId = authConfig.getPluginId();

            if (!store.doesPluginSupportPasswordBasedAuthentication(pluginId)) {
                continue;
            }

            final List<PluginRoleConfig> roleConfigs = configService.security().getRoles().pluginRoleConfigsFor(authConfig.getId());

            try {
                LOGGER.debug("[Authenticate] Authenticating user: `{}` using the authorization plugin: `{}`", loginName, pluginId);
                AuthenticationResponse response = authorizationExtension.authenticateUser(pluginId, loginName, password, Collections.singletonList(authConfig), roleConfigs);
                User user = ensureDisplayNamePresent(response.getUser());
                if (user != null) {
                    pluginRoleService.updatePluginRoles(pluginId, user.getUsername(), CaseInsensitiveString.caseInsensitiveStrings(response.getRoles()));
                    LOGGER.debug("[Authenticate] Successfully authenticated user: `{}` using the authorization plugin: `{}`", loginName, pluginId);
                    return user;
                }
            } catch (Exception e) {
                LOGGER.error("[Authenticate] Error while authenticating user: `{}` using the authorization plugin: {} ", loginName, pluginId);
            }
            LOGGER.debug("[Authenticate] Authentication failed for user: `{}` using the authorization plugin: `{}`", loginName, pluginId);
        }
        return null;
    }

    @Override
    public boolean supports(Class authentication) {
        if (store.getPluginsThatSupportsPasswordBasedAuthentication().size() > 0) {
            return super.supports(authentication);
        }

        return false;
    }

    private User ensureDisplayNamePresent(User user) {
        if (user == null) {
            return null;
        }

        if (isNotBlank(user.getDisplayName())) {
            return user;
        }

        return new User(user.getUsername(), user.getUsername(), user.getEmailId());
    }

    private String loginName(String username, UsernamePasswordAuthenticationToken authenticationToken) {
        Object principal = authenticationToken.getPrincipal();

        if (!(principal instanceof GoUserPrinciple)) {
            return username;
        }

        String loginName = ((GoUserPrinciple) principal).getLoginName();
        return isNotBlank(loginName) ? loginName : username;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- The MIB Compiler</title>

User's Guide
Reference Manual
Release Notes
PDF
Top
Simple Network Management Protocol (SNMP)
User's Guide
Version 5.2.2

Expand All
Contract All
Chapters

SNMP Introduction

              Top of chapter

Scope and Purpose

Prerequisites

Definitions

About This Manual

Where to Find More Information

Agent Functional Description

              Top of chapter

Features

SNMPv1, SNMPv2 and SNMPv3

Operation

Sub-agents and MIB Loading

Contexts and Communities

Management of the Agent

Notifications

Discovery

Manager Functional Description

              Top of chapter

Features

Operation

MIB loading

The MIB Compiler

              Top of chapter

Operation

Importing MIBs

MIB Consistency Checking

.hrl File Generation

Emacs Integration

Compiling from a Shell or a Makefile

Deviations from the Standard

Running the application

              Top of chapter

Configuring the application

Modifying the Configuration Files

Starting the application

Debugging the application

Definition of Agent Configuration Files

              Top of chapter

Agent Information

Contexts

System Information

Communities

MIB Views for VACM

Security data for USM

Notify Definitions

Target Address Definitions

Target Parameters Definitions

Definition of Manager Configuration Files

              Top of chapter

Manager Information

Users

Agents

Security data for USM

Agent Implementation Example

              Top of chapter

MIB

Default Implementation

Manual Implementation

Manager Implementation Example

              Top of chapter

The example manager

A simple standard test

Instrumentation Functions

              Top of chapter

Instrumentation Functions

Using the ExtraArgument

Default Instrumentation

Atomic Set

Definition of Instrumentation Functions

              Top of chapter

Variable Instrumentation

Table Instrumentation

Definition of Agent Net if

              Top of chapter

Mandatory Functions

Messages

Definition of Manager Net if

              Top of chapter

Mandatory Functions

Messages

Audit Trail Log

              Top of chapter

Agent Logging

Manager Logging

Advanced Agent Topics

              Top of chapter

When to use a Sub-agent

Agent Semantics

Sub-agents and Dependencies

Distributed Tables

Fault Tolerance

Using Mnesia Tables as SNMP Tables

Deviations from the Standard

SNMP Appendix A

              Top of chapter

Appendix A

SNMP Appendix B

              Top of chapter

Appendix B

4 The MIB Compiler

The chapter The MIB Compiler describes the MIB compiler
    and contains the following topics:

Operation

Import

Consistency checking between MIBs

.hrl file generation

Emacs integration

Deviations from the standard

Note

When importing MIBs, ensure that the imported MIBs as well as the
      importing MIB are compiled using the same version of the
      SNMP-compiler.

4.1
        Operation

The MIB must be written as a text file in SMIv1 or SMIv2 using
      an ASN.1 notation before
      it will be compiled. This text file must have the same name as the MIB,
      but with the suffix .mib. This is necessary for handling
      the IMPORT statement.

The association file, which contains the names of
      instrumentation functions for the MIB, should have the suffix
      .funcs. If the compiler does not find the association file,
      it gives a warning message and uses default instrumentation
      functions.  (See Default Instrumentation for more details).

The MIB compiler is started with a call to
      snmpc:compile(<mibname>). For example:

snmpc:compile("RFC1213-MIB").

The output is a new file which is called <mibname>.bin.

The MIB compiler understands both SMIv1 and SMIv2 MIBs.  It
      uses the MODULE-IDENTITY statement to determinate if the MIB is
      written in SMI version 1 or 2.

4.2
        Importing MIBs

The compiler handles the IMPORT statement. It is important to
      import the compiled file and not the ASN.1 (source) file. A MIB must
      be recompiled to make changes visible to other MIBs importing it.

The compiled files of the imported MIBs must be present in the
      current directory, or a directory in the current path. The path is
      supplied with the {i, Path} option, for example:

snmpc:compile("MY-MIB",
       [{i, ["friend_mibs/", "../standard_mibs/"]}]).

It is also possible to import MIBs from OTP applications in an
      "include_lib" like fashion with the il
      option. Example:

snmpc:compile("MY-MIB",
       [{il, ["snmp/priv/mibs/", "myapp/priv/mibs/"]}]).

finds the latest version of the snmp and myapp
      applications in the OTP system and uses the expanded paths as
      include paths.

Note that an SMIv2 MIB can import an SMIv1 MIB and vice versa.

The following MIBs are built-ins of the Erlang SNMP compiler:
      SNMPv2-SMI, RFC-1215, RFC-1212, SNMPv2-TC, SNMPv2-CONF, and
      RFC1155-SMI. They cannot therefore be compiled separately.

4.3
        MIB Consistency Checking

When an MIB is compiled, the compiler detects if several
      managed objects use the same OBJECT IDENTIFIER. If that is
      the case, it issues an error message. However, the compiler cannot
      detect Oid conflicts between different MIBs. These kinds of
      conflicts generate an error at load time. To avoid this, the
      following function can be used to do consistency checking between
      MIBs:

erl>snmpc:is_consistent(ListOfMibNames).

ListOfMibNames is a list of compiled MIBs, for example
      ["RFC1213-MIB", "MY-MIB"]. The function also performs
      consistency checking of trap definitions.

4.4
        .hrl File Generation

It is possible to generate an .hrl file which contains
      definitions of Erlang constants from a compiled MIB file. This
      file can then be included in Erlang source code. The file will
      contain constants for:

object Identifiers for tables, table entries and variables

column numbers

enumerated values

default values for variables and table columns.

Use the following command to  generate a .hrl file from an MIB:

erl>snmpc:mib_to_hrl(MibName).

4.5
        Emacs Integration

With the Emacs editor, the next-error (C-X `)
      function can be used indicate where a compilation error occurred,
      provided the error message is described by a line number.

Use M-x compile to compile an MIB from inside Emacs, and
      enter:

 erl -s snmpc compile <MibName> -noshell

An example of <MibName> is RFC1213-MIB.

4.6
        Compiling from a Shell or a Makefile

The erlc commands can be used to compile SNMP MIBs. Example:

 erlc MY-MIB.mib

All the standard erlc flags are supported, e.g.

 erlc -I mymibs -o mymibs -W MY-MIB.mib

The flags specific to the MIB compiler can be specified by
      using the + syntax:

 erlc +'{group_check,false}' MY-MIB.mib

4.7
        Deviations from the Standard

In some aspects the Erlang MIB compiler does not follow or
      implement the SMI fully. Here are the differences:

Tables must be written in the following order:
          tableObject, entryObject, column1, ...,
          columnN (in order).

Integer values, for example in the SIZE expression
          must be entered in decimal syntax, not in hex or bit syntax.

Symbolic names must be unique within a MIB and within a
          system.

Hyphens are allowed in SMIv2 (a pragmatic approach).  The
          reason for this is that according to SMIv2, hyphens are allowed
          for objects converted from SMIv1, but not for others.  This is
          impossible to check for the compiler.

If a word is a keyword in any of SMIv1 or SMIv2, it is a
          keyword in the compiler (deviates from SMIv1 only).

Indexes in a table must be objects, not types (deviates
          from SMIv1 only).

A subset of all semantic checks on types are
          implemented. For example, strictly the TimeTicks may not
          be sub-classed but the compiler allows this (standard MIBs must
          pass through the compiler) (deviates from SMIv2 only).

The MIB.Object syntax is not implemented (since all
          objects must be unique anyway).

Two different names cannot define the same OBJECT IDENTIFIER.

The type checking in the SEQUENCE construct is non-strict
          (i.e. subtypes may be specified).  The reason for this is
          that some standard MIBs use this.

A definition has normally a status field. When the status field
       has the value deprecated, then the MIB-compiler will ignore this
       definition. With the MIB-compiler option {deprecated,true}
       the MIB-compiler does not ignore the deprecated definitions.

An object has a DESCRIPTIONS field. The descriptions-field will
       not be included in the compiled mib by default. In order to get
       the description, the mib must be compiled with the option
      description.

Copyright © 1997-2016 Ericsson AB. All Rights Reserved.


text:
function logger() {}

function log(msg) {
    console.log(convertToJsonIfRequired(msg));
}

logger.prototype.log = function (msg) {
        console.log(convertToJsonIfRequired(msg));
        }

        logger.prototype.init = function (logLevel) {
            this.currentLogLevel = logLevel;
        }

        logger.prototype.logInfo = function (msg) {
            if (this.checkIfShouldLog(this.LogLevels.Info)) {
                log('iiiii==>' + convertToJsonIfRequired(msg));
            }
        }

        logger.prototype.logError = function (msg) {
            if (this.checkIfShouldLog(this.LogLevels.Error)) {
                log('eeeee==>' + convertToJsonIfRequired(msg));
            }
        }

        logger.prototype.logWarn = function (msg) {
            if (this.checkIfShouldLog(this.LogLevels.Warn)) {
                log('wwwww==>' + convertToJsonIfRequired(msg));
            }
        }

        logger.prototype.logException = function (msg) {
            if (this.checkIfShouldLog(this.LogLevels.Exception)) {
                log('###############==>' + convertToJsonIfRequired(msg));
            }
        }

        logger.prototype.LogLevels = {
            None: 9999,
            Info: 1,
            Warn: 2,
            Error: 3,
            Exception: 4
        }

        logger.prototype.checkIfShouldLog = function (targetLogLevel) {
            if (this.currentLogLevel === 0) {
                return false;
            }

            if (this.currentLogLevel <= targetLogLevel) {
                return true;
            }
            return false;
        }

        function convertToJsonIfRequired(obj) {
            if (typeof obj === 'object') {
                return JSON.stringify(obj);
            } else {
                return obj;
            }
        }

        module.exports = logger;


text:
angular.module('project')
.controller('CollaboratorsController', ['$scope', function($scope) {
    $scope.template = 'collaborators';
}]);


text:
'use strict';
angular.module('com.module.servers')
  .run(function($rootScope, Multicraft_daemonServer) {
    $rootScope.addMenu('Servers',
      'app.servers.list', 'fa-file');

    Multicraft_daemonServer.find(function(data) {
      console.log(data);
      $rootScope.addDashboardBox('Multicraft_daemonServer',
        'bg-yellow', 'ion-ios7-cart-outline', data.length,
        'app.servers.list');
    });

  });


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

<title>Uses of Class org.timepicker.Ball</title>
<meta name="date" content="2013-06-05">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.timepicker.Ball

Packages that use Ball

Package
Description

org.timepicker

Uses of Ball in org.timepicker

Fields in org.timepicker declared as Ball

Modifier and Type
Field and Description

(package private) Ball
PeriodActivity.b

Ball

(package private) Ball
MainActivity.b

First ball

(package private) Ball
MainActivity.b1

Second ball

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.zhuohua.teacher.dao;

import java.util.List;

import com.zhuohua.teacher.model.Student;

public interface StudentDao {
	public Student get(String sno);

	public List<Student> findByClassNo(String classNo);
}


text:
package gtkui

import "github.com/gotk3/gotk3/glib"

type uiTask func() (result interface{})

func runOnUIThreadAndWait(task uiTask) interface{} {
	resultChannel := make(chan interface{})
	defer close(resultChannel)

	glib.IdleAdd(func() bool {
		resultChannel <- task()
		return false
	})

	return <-resultChannel
}


text:
<?xml version="1.0" ?><para version="5.0" xml:lang="zh" xmlns="http://docbook.org/ns/docbook">

Description of SNMP configuration options

    <col width="50%"/>
    <col width="50%"/>

        Configuration option = Default value
        描述

        [snmp]

        <option>power_timeout</option> = <replaceable>10</replaceable>
        (IntOpt) Seconds to wait for power action to be completed

</para>


text:
"""
This file acts as a login shell for the door user.
It updates the modified time on AUTH_FILE to be AUTH_TIMEOUT seconds in the future

doorvim.py uses AUTH_FILE to decide to unlock the door. It unlocks only if the file's
last-modified time is in the future. Additionally it deletes the file after unlocking
the door, to prevent people slipping in after you.
"""

from __future__ import print_function

import os
import time
import argparse

AUTH_FILE = "/home/door/doorvim/.auth"
LOG_FILE = "/home/door/doorvim/visitors.log"
MAX_TIMEOUT = 60*60*24 # seconds (1 day)
LOG = None

def main():
  def success(message):
    msg = "Success\n" + message
    print(msg)
    LOG.info(msg)
    exit(0)
  def fail(message):
    msg = "Doorvim Error\n" + message
    print(msg)
    LOG.warn(msg)
    exit(0)
  def nonnegint(s):
    i = int(s)
    if i < 0:
      raise ValueError("Negative integers not allowed here")
    return i

  parser = argparse.ArgumentParser(description="Authenticate doorvim")
  parser.add_argument('-c', metavar="MM:SS", dest='timeout',
                      help="Allow doorvim to open the door for the next TIMEOUT duration of time")
  args = parser.parse_args()
  if args.timeout is None:
    args.timeout = raw_input("Timeout? > ")
  LOG.info("Got Login request for " + args.timeout)
  try:
    if ":" in args.timeout:
      minutes, seconds = args.timeout.split(":")
      timeout = nonnegint(minutes) * 60 + nonnegint(seconds)
    else:
      timeout = nonnegint(args.timeout)
  except (ValueError, TypeError):
    fail("Invalid duration:", args.timeout)
  else:
    if timeout > MAX_TIMEOUT:
      fail("Timeout too large:", args.timeout)
    elif timeout == 0:
      try:
        os.remove(AUTH_FILE)
      except OSError as e:
        if e.errno != 2:
          fail("Deauthentication Failed!\n" + str(e))
      success("Doorvim no longer authenticated")
    else:
      expiry = time.time() + timeout
      try:
        with open(AUTH_FILE, 'a'):
          os.chmod(AUTH_FILE, 0o660) # chmod first!
          os.utime(AUTH_FILE, (expiry, expiry))
      except (IOError, OSError) as e:
        fail("Doorvim Authentication Failed!", e, sep='\n')
      else:
        hours, timeout = divmod(timeout, 3600)
        minutes, seconds = divmod(timeout, 60)
        if hours > 0:
          success("Doorvim now authenticated for\n{}h {}m {}s".format(hours, minutes, seconds))
        elif minutes > 0:
          success("Doorvim now authenticated for\n{}m {}s".format(minutes, seconds))
        else:
          success("Doorvim now authenticated for\n{}s".format(seconds))

if __name__ == '__main__':
  logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG)
  logging.info("Starting {} as {}".format(__file__, __name__))
  LOG = logging.getLogger(__name__)
  try:
    main()
  except Exception as e:
    LOG.error(e)
    raise
  finally:
    logging.shutdown()


text:
title: Getting Started
page_title: Getting Started | RadTabStrip for ASP.NET AJAX Documentation
description: Getting Started
slug: tabstrip/getting-started/getting-started
tags: getting,started
published: True
position: 0
---

# Getting Started

This tutorial will walk you through creating a **RadTabStrip** and shows how to:

* Use the **RadTabStrip** item builder to add items to **RadTabStrip**.

* Set properties on the items in the tab strip.

* Apply a skin to specify the look and feel of the tab strip.

* Use **RadMultiPage** to represent the content of tab pages.

* Add pages to a **RadMultiPage** control.

* Add controls to a page in a **RadMultiPage** control.

## Creating a tab strip using the RadTabStrip Item Builder

1. Drag a **RadTabStrip** control from the toolbox onto your Web page. The **RadTabStrip** [Smart Tag]({%slug tabstrip/design-time/smart-tag%}) should appear automatically:
![Smart Tag](images/tabstrip_smarttag.png)

1. On the Smart Tag, choose **Build RadTabStrip.** The [RadTabStrip Item Builder]({%slug tabstrip/design-time/radtabstrip-item-builder%}) appears:
![Item Builder](images/tabstrip_itembuilder.png)**

1. Click the **Add root item** button (![Add root item](images/tabstrip_addrootitem.png)) to add a root item to your tab strip.

1. The right pane of the **RadTabStrip Item Builder** displays the properties for your new root item. Change its **Text** property to "Calendar": ![Item Properties](images/tabstrip_itemproperties.png)

1. Click the **Add root item** button three more times to add three more root items to your tab strip. Set their properties as follows:

* On the first new item (the second root item), set the **Text** property to "Colors".

* On the next new item, set the **Text** property to "Quote" and the **IsBreak** property to **True**.

* On the last new item, set the **Text** property to "Web Sites".The **RadTabStrip Item Builder** should now look like the following screen shot:![Root Items](images/tabstrip_rootitems.png)

1. Select the "Web Sites" root item, and then click the **Add child item** button (![Add child item](images/tabstrip_addchilditem.png)) to add a child to that root item. With the child item selected, set the following properties:

* Set the **Text** property to "Telerik".

* Set the **NavigateUrl** property to "http://www.Telerik.com".
![Child Item Properties](images/tabstrip_childitemproperties.png)

1. Select the "Web Sites" root item again, and add another child item.

* Set its **Text** property to "Google".

* Set its **NavigateUrl** property to `http://www.Google.com`.The **RadTabStrip Item Builder** should now look like the following:
![Item Builder With Items](images/tabstrip_radtabstripitembuilderwithitems.png)

1. Click OK to exit the **RadTabStrip Item Builder**.

1. Back in the **RadTabStrip** Smart Tag, use the **Skin** drop-down to change the [skin ]({%slug tabstrip/appearance-and-styling/skins%}) for the **RadTabStrip** to "Outlook":
![Choose Skin](images/tabstrip_chooseskin.png)

1. The appearance of the **RadTabStrip** in the designer changes to reflect the new skin:  You can also click on the tabs even in design time:

1. Right click on the **RadTabStrip**, and from its context menu, choose **Properties**.

1. In the Properties pane, set the **ReorderTabsOnSelect** property to **True**:
![Reorder tabs on select](images/tabstrip_reordertabsonselect.png)

## Creating a RadMultiPage control

1. On the **RadTabStrip** Smart Tag, click the **Add RadMultiPage** link:
![Add RadMultipage](images/tabstrip_addradmultipage.png)

1. A **RadMultiPage** control appears on the Web page below the **RadTabStrip**. On the **RadMultiPage** Smart Tag, click the "Add RadPageView" link three times, to add three pages to the **RadMultiPage** control:Once you have added the RadPageView you can add pageviews to it using the RadPageView's **SmartTag**
![TabStrip and multipage](images/tabstrip_andmultipage.png)

1. On the first **RadPageView** control ("RadPageView1"),

1. Delete the text that appeared by default.

1. Drag a **RadCalendar** control from the toolbox onto the surface of the **RadPageView**.

1. Set the **Skin** property of the **RadCalendar** control to "Outlook" so that it matches the look and feel of the tab strip:
![RadPageView with Calendar](images/tabstrip_radpageviewwithcalendar.png)

1. On the second **RadPageView** control ("RadPageView1"), drag a **RadColorPicker** control from the toolbox onto the surface of the **RadPageView**:
![RadPageView with ColorPicker](images/tabstrip_radpageviewwithcolorpicker.png)

1. On the third **RadPageView** control ("RadPageView3"), type the text of a quotation onto the surface of the control:
![RadPageView with Quote](images/tabstrip_radpageviewwithquote.png)

1. Run the application. The tab strip appears, containing two rows: the first three items appear in the first row, and the fourth item in a second row. This is because you set the **IsBreak** property to **True** for the third item, creating a break before the fourth item.
![TabStrip Two Rows](images/tabstrip_tworows.png)

1. Click on one of the first three tabs. The tab moves down to the bottom row (because the **ReorderTabsOnSelect** property is **True**) and the corresponding page from the **RadMultiPage** control appears:
![Expanded tab](images/tabstrip_expandedtab.png)

1. Click on the "Web Sites" tab. It moves down to the bottom row and displays tabs for the two child items:
![Child Tabs](images/tabstrip_displaychildtabs.png)

1. Click on one of the child items. The Web page changes to the page you specified using the **NavigateUrl** property.

# See Also

 * [Binding to a Data Source]({%slug tabstrip/getting-started/binding-to-a-data-source%})


text:
"""
This module prints three FedEx Ground shipping labels for the label
certification process. See your FedEx Label Developer Tool Kit documentation
for more details.
"""
import logging
from cert_config import CONFIG_OBJ, SHIPPER_CONTACT_INFO, SHIPPER_ADDRESS, LABEL_SPECIFICATION
from cert_config import transfer_config_dict
from cert_config import LabelPrinterClass
from fedex.services.ship_service import FedexProcessShipmentRequest

logging.basicConfig(level=logging.INFO)

shipment = FedexProcessShipmentRequest(CONFIG_OBJ)
shipment.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
shipment.RequestedShipment.ServiceType = 'FEDEX_GROUND'
shipment.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
shipment.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

# Shipper contact info.
transfer_config_dict(shipment.RequestedShipment.Shipper.Contact,
                     SHIPPER_CONTACT_INFO)

# Shipper address.
transfer_config_dict(shipment.RequestedShipment.Shipper.Address,
                     SHIPPER_ADDRESS)

# Recipient contact info.
shipment.RequestedShipment.Recipient.Contact.PersonName = 'Recipient Name'
shipment.RequestedShipment.Recipient.Contact.CompanyName = 'Recipient Company'
shipment.RequestedShipment.Recipient.Contact.PhoneNumber = '9012637906'

# Recipient address
shipment.RequestedShipment.Recipient.Address.StreetLines = ['Address Line 1']
shipment.RequestedShipment.Recipient.Address.City = 'Herndon'
shipment.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'VA'
shipment.RequestedShipment.Recipient.Address.PostalCode = '20171'
shipment.RequestedShipment.Recipient.Address.CountryCode = 'US'

shipment.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

# Label config.
transfer_config_dict(shipment.RequestedShipment.LabelSpecification,
                     LABEL_SPECIFICATION)

package1_weight = shipment.create_wsdl_object_of_type('Weight')
package1_weight.Value = 1.0
package1_weight.Units = "LB"
package1 = shipment.create_wsdl_object_of_type('RequestedPackageLineItem')
package1.Weight = package1_weight
shipment.add_package(package1)

if __name__ == "__main__":
    shipment.send_request()
    device = LabelPrinterClass(shipment)
    device.print_label()

    shipment.RequestedShipment.Recipient.Address.StreetLines = ['456 Peach St']
    shipment.RequestedShipment.Recipient.Address.City = 'Atlanta'
    shipment.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'GA'
    shipment.RequestedShipment.Recipient.Address.PostalCode = '30303'
    shipment.RequestedShipment.Recipient.Address.CountryCode = 'US'

    shipment.send_request()
    device = LabelPrinterClass(shipment)
    device.print_label()

    shipment.RequestedShipment.Recipient.Address.StreetLines = ['987 Main St']
    shipment.RequestedShipment.Recipient.Address.City = 'Boston'
    shipment.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'MA'
    shipment.RequestedShipment.Recipient.Address.PostalCode = '02115'
    shipment.RequestedShipment.Recipient.Address.CountryCode = 'US'

    shipment.send_request()
    device = LabelPrinterClass(shipment)
    device.print_label()


text:
description: Describes how to use the fluentd logging driver.
keywords: Fluentd, docker, logging, driver
redirect_from:
- /engine/reference/logging/fluentd/
- /reference/logging/fluentd/
- /engine/admin/logging/fluentd/
title: Fluentd logging driver
---

The `fluentd` logging driver sends container logs to the
[Fluentd](http://www.fluentd.org/) collector as structured log data. Then, users
can use any of the [various output plugins of
Fluentd](http://www.fluentd.org/plugins) to write these logs to various
destinations.

In addition to the log message itself, the `fluentd` log
driver sends the following metadata in the structured log message:

| Field            | Description                                                                                |
|:-----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------|
| `container_id`   | The full 64-character container ID.                                                                                |
| `container_name` | The container name at the time it was started. If you use `docker rename` to rename a container, the new name is not reflected in the journal entries. |
| `source`         | `stdout` or `stderr`                                                                                |
| `log`            | The container log                                                                                |

The `docker logs` command is not available for this logging driver.

## Usage

Some options are supported by specifying `--log-opt` as many times as needed:

 - `fluentd-address`: specify a socket address to connect to the Fluentd daemon, ex `fluentdhost:24224` or `unix:///path/to/fluentd.sock`
 - `tag`: specify a tag for fluentd message, which interprets some markup, ex {% raw %}`{{.ID}}`, `{{.FullID}}` or `{{.Name}}` `docker.{{.ID}}`{% endraw %}

 To use the `fluentd` driver as the default logging driver, set the `log-driver`
 and `log-opt` keys to appropriate values in the `daemon.json` file, which is
 located in `/etc/docker/` on Linux hosts or
 `C:\ProgramData\docker\config\daemon.json` on Windows Server. For more about
 +configuring Docker using `daemon.json`, see
 +[daemon.json](/engine/reference/commandline/dockerd.md#daemon-configuration-file).

The following example sets the log driver to `fluentd` and sets the
`fluentd-address` option.

 ```json
 {
   "log-driver": "fluentd",
   "log-opts": {
     "fluentd-address": "fluentdhost:24224"
   }
 }
 ```

 Restart Docker for the changes to take effect.

To set the logging driver for a specific container, pass the
`--log-driver` option to `docker run`:

    docker run --log-driver=fluentd ...

Before using this logging driver, launch a Fluentd daemon. The logging driver
connects to this daemon through `localhost:24224` by default. Use the
`fluentd-address` option to connect to a different address.

    docker run --log-driver=fluentd --log-opt fluentd-address=fluentdhost:24224

If container cannot connect to the Fluentd daemon, the container stops
immediately unless the `fluentd-async-connect` option is used.

## Options

Users can use the `--log-opt NAME=VALUE` flag to specify additional Fluentd logging driver options.

### fluentd-address

By default, the logging driver connects to `localhost:24224`. Supply the
`fluentd-address` option to connect to a different address. `tcp`(default) and `unix` sockets are supported.

    docker run --log-driver=fluentd --log-opt fluentd-address=fluentdhost:24224
    docker run --log-driver=fluentd --log-opt fluentd-address=tcp://fluentdhost:24224
    docker run --log-driver=fluentd --log-opt fluentd-address=unix:///path/to/fluentd.sock

Two of the above specify the same address, because `tcp` is default.

### tag

By default, Docker uses the first 12 characters of the container ID to tag log messages.
Refer to the [log tag option documentation](log_tags.md) for customizing
the log tag format.

### labels, env, and env-regex

The `labels` and `env` options each take a comma-separated list of keys. If
there is collision between `label` and `env` keys, the value of the `env` takes
precedence. Both options add additional fields to the extra attributes of a
logging message.

The `env-regex` option is similar to and compatible with `env`. Its value is a
regular expression to match logging-related environment variables. It is used
for advanced [log tag options](log_tags.md).

### fluentd-async-connect

Docker connects to Fluentd in the background. Messages are buffered until the
connection is established.

### fluentd-buffer-limit

The amount of data to buffer before flushing to disk. Defaults to the amount of RAM
available to the container.

### fluentd-retry-wait

How long to wait between retries. Defaults to 1 second.

### fluentd-max-retries

The maximum number of retries. Defaults to 10.

### fluentd-sub-second-precision

Generates event logs in nanosecond resolution. Defaults to false.

## Fluentd daemon management with Docker

About `Fluentd` itself, see [the project webpage](http://www.fluentd.org)
and [its documents](http://docs.fluentd.org/).

To use this logging driver, start the `fluentd` daemon on a host. We recommend
that you use [the Fluentd docker
image](https://hub.docker.com/r/fluent/fluentd/). This image is
especially useful if you want to aggregate multiple container logs on each
host then, later, transfer the logs to another Fluentd node to create an
aggregate store.

### Test container loggers

1. Write a configuration file (`test.conf`) to dump input logs:

        <source>
          @type forward
        </source>

        <match *>
          @type stdout
        </match>

2. Launch Fluentd container with this configuration file:

        $ docker run -it -p 24224:24224 -v /path/to/conf/test.conf:/fluentd/etc/test.conf -e FLUENTD_CONF=test.conf fluent/fluentd:latest

3. Start one or more containers with the `fluentd` logging driver:

        $ docker run --log-driver=fluentd your/application


text:
package team.tr.permitlog;

import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.TimePicker;

public class DriveTimeFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    //This creates a new dialog so that the user can pick the date:
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //Get the default time from the arguments:
        int hour = getArguments().getInt("hour");
        int minute = getArguments().getInt("minute");
        //Return a TimePickerDialog which has a default time of what was set in the constructor:
        return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hour, int minute) {
        //Call the setDate method on the activity so they can deal with the time:
        ((CustomDriveDialog)getActivity()).setTime(hour, minute);
    }
}


text:
$.toast({ text: "test" });

$.toast({ text: "test", heading: "Test Heading" });

$.toast({ text: "test", showHideTransition: "fade" });
$.toast({ text: "test", showHideTransition: "slide" });
$.toast({ text: "test", showHideTransition: "plain" });

$.toast({ text: "test", allowToastClose: false });
$.toast({ text: "test", allowToastClose: true });

$.toast({ text: "test", hideAfter: 5});
$.toast({ text: "test", hideAfter: false});

$.toast({ text: "test", loader: true });
$.toast({ text: "test", loader: false });

$.toast({ text: "test", loaderBg: "#9EC600" });

$.toast({ text: "test", stack: 5});
$.toast({ text: "test", stack: false});

$.toast({ text: "test", position: "bottom-left" });
$.toast({ text: "test", position: "bottom-right" });
$.toast({ text: "test", position: "bottom-center" });
$.toast({ text: "test", position: "top-right" });
$.toast({ text: "test", position: "top-left" });
$.toast({ text: "test", position: "top-center" });
$.toast({ text: "test", position: "mid-center" });
$.toast({ text: "test", position: { left : "auto", right : 20, top : 20, bottom : "auto" } });
$.toast({ text: "test", position: { left : 20, right : "auto", top : "auto", bottom : 20 } });

$.toast({ text: "test", bgColor: "#9EC600" });

$.toast({ text: "test", textColor: "#9EC600" });

$.toast({ text: "test", textAlign: "left" });
$.toast({ text: "test", textAlign: "right" });
$.toast({ text: "test", textAlign: "center" });

$.toast({ text: "test", icon: "info" });
$.toast({ text: "test", icon: "warning" });
$.toast({ text: "test", icon: "error" });
$.toast({ text: "test", icon: "success" });

$.toast({
    text: 'Triggers the events',
    beforeShow: () => {},
    afterShown: () => {},
    beforeHide: () => {},
    afterHidden: () => {}
});


text:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('js',function(){
  gulp.src('ToProgress.js')
    .pipe(uglify())
    .pipe(rename('ToProgress.min.js'))
    .pipe(gulp.dest('./'))
});

gulp.watch('./ToProgress.js', ['js']);

gulp.task('default', ['js']);


text:
'use strict';

import db from '../db';
import helpers from '../helpers';

const controller = {

	/** Muestra el estado del servidor */
	async getServerStatus(req, res, next) {
		try {
			res.locals.serverStatus = await helpers.getStatus();
			next();
		} catch (error) {
			helpers.submitError('helper.getServerStatus', error);
			res.locals.serverStatus = false;
			next();
		}
	},

	/** Añade el local con la información de los jugadores en línea */
	async getPlayersOnline(req, res, next) {
		try {
			const onlinePlayers = await db('MEMB_STAT').count('ConnectStat').where({
				ConnectStat: 1
			});
			res.locals.onlinePlayers = onlinePlayers[0][''];
			next();
		} catch (error) {
			helpers.submitError('helper.getPlayersOnline', error);
		}
	},

	async getBannedAccounts(req, res, next) {
		try {
			const bannedList = await db('Character').count('Name').where('ctlcode', 17).orWhere('ctlcode', 1);
			res.locals.bannedList = bannedList[0][''];
			next();
		} catch (error) {
			req.flash('error', 'Hubo un error, contacta a un administrador.');
			res.redirect('/');
			helpers.submitError('serverinfoController.getStadistics', error);
		}
	},

	async getCreatedAccounts(req, res, next) {
		try {
			const createdAccounts = await db('MEMB_INFO').count('memb_guid');
			res.locals.createdAccounts = createdAccounts[0][''];
			next();
		} catch (error) {
			req.flash('error', 'Hubo un error, contacta a un administrador.');
			res.redirect('/');
			helpers.submitError('serverinfoController.getCreatedAccounts', error);
		}
	},

	async getCreatedCharacters(req, res, next) {
		try {
			const createdCharacters = await db('Character').count('Name');
			res.locals.createdCharacters = createdCharacters[0][''];
			next();
		} catch (error) {
			req.flash('error', 'Hubo un error, contacta a un administrador.');
			res.redirect('/');
			helpers.submitError('serverinfoController.getStadistics', error);
		}
	},

	async getCreatedGuilds(req, res, next) {
		try {
			const createdGuilds = await db('Guild').count('G_Name');
			res.locals.createdGuilds = createdGuilds[0][''];
			next();
		} catch (error) {
			req.flash('error', 'Hubo un error, contacta a un administrador.');
			res.redirect('/');
			helpers.submitError('serverinfoController.getStadistics', error);
		}
	},

	async getAdmins(req, res, next) {
		try {
			const admins = await db('Character').select('Name', 'AccountID').where('ctlcode', 24)
				.orWhere('ctlcode', 8)
				.orWhere('ctlcode', 32);
			res.locals.adminListCount = admins.length;
			res.locals.adminsOnline = 0;
			for (let admin in admins) {
				let accountID = admins[admin]['AccountID'];
				const adminsOnline = await db('MEMB_STAT').where({
					memb___id: accountID,
					ConnectStat: 1
				});
				if (adminsOnline.length) {
					res.locals.adminsOnline++;
				}
			}
			next();
		} catch (error) {
			req.flash('error', 'Hubo un error, contacta a un administrador.');
			res.redirect('/');
			helpers.submitError('serverinfoController.getAdmins', error);
		}
	},

};

export default controller;