text:
import json
import unittest
from unittest import mock

from airflow.providers.amazon.aws.hooks.glue import GlueJobHook

try:
    from moto import mock_iam
except ImportError:
    mock_iam = None

class TestGlueJobHook(unittest.TestCase):
    def setUp(self):
        self.some_aws_region = "us-west-2"

    @unittest.skipIf(mock_iam is None, 'mock_iam package not present')
    @mock_iam
    def test_get_iam_execution_role(self):
        hook = GlueJobHook(
            job_name='aws_test_glue_job', s3_bucket='some_bucket', iam_role_name='my_test_role'
        )
        iam_role = hook.get_client_type('iam').create_role(
            Path="/",
            RoleName='my_test_role',
            AssumeRolePolicyDocument=json.dumps(
                {
                    "Version": "2012-10-17",
                    "Statement": {
                        "Effect": "Allow",
                        "Principal": {"Service": "glue.amazonaws.com"},
                        "Action": "sts:AssumeRole",
                    },
                }
            ),
        )
        iam_role = hook.get_iam_execution_role()
        assert iam_role is not None
        assert "Role" in iam_role
        assert "Arn" in iam_role['Role']
        assert iam_role['Role']['Arn'] == "arn:aws:iam::123456789012:role/my_test_role"

    @mock.patch.object(GlueJobHook, "get_iam_execution_role")
    @mock.patch.object(GlueJobHook, "get_conn")
    def test_get_or_create_glue_job(self, mock_get_conn, mock_get_iam_execution_role):
        mock_get_iam_execution_role.return_value = mock.MagicMock(Role={'RoleName': 'my_test_role'})
        some_script = "s3:/glue-examples/glue-scripts/sample_aws_glue_job.py"
        some_s3_bucket = "my-includes"

        mock_glue_job = mock_get_conn.return_value.get_job()['Job']['Name']
        glue_job = GlueJobHook(
            job_name='aws_test_glue_job',
            desc='This is test case job from Airflow',
            script_location=some_script,
            iam_role_name='my_test_role',
            s3_bucket=some_s3_bucket,
            region_name=self.some_aws_region,
        ).get_or_create_glue_job()
        assert glue_job == mock_glue_job

    @mock.patch.object(GlueJobHook, "get_iam_execution_role")
    @mock.patch.object(GlueJobHook, "get_conn")
    def test_get_or_create_glue_job_worker_type(self, mock_get_conn, mock_get_iam_execution_role):
        mock_get_iam_execution_role.return_value = mock.MagicMock(Role={'RoleName': 'my_test_role'})
        some_script = "s3:/glue-examples/glue-scripts/sample_aws_glue_job.py"
        some_s3_bucket = "my-includes"

        mock_glue_job = mock_get_conn.return_value.get_job()['Job']['Name']
        glue_job = GlueJobHook(
            job_name='aws_test_glue_job',
            desc='This is test case job from Airflow',
            script_location=some_script,
            iam_role_name='my_test_role',
            s3_bucket=some_s3_bucket,
            region_name=self.some_aws_region,
            create_job_kwargs={'WorkerType': 'G.2X', 'NumberOfWorkers': 60},
        ).get_or_create_glue_job()
        assert glue_job == mock_glue_job

    @mock.patch.object(GlueJobHook, "get_iam_execution_role")
    @mock.patch.object(GlueJobHook, "get_conn")
    def test_init_worker_type_value_error(self, mock_get_conn, mock_get_iam_execution_role):
        mock_get_iam_execution_role.return_value = mock.MagicMock(Role={'RoleName': 'my_test_role'})
        some_script = "s3:/glue-examples/glue-scripts/sample_aws_glue_job.py"
        some_s3_bucket = "my-includes"

        with self.assertRaises(
            ValueError,
            msg="ValueError should be raised for specifying the num_of_dpus and worker type together!",
        ):
            GlueJobHook(
                job_name='aws_test_glue_job',
                desc='This is test case job from Airflow',
                script_location=some_script,
                iam_role_name='my_test_role',
                s3_bucket=some_s3_bucket,
                region_name=self.some_aws_region,
                num_of_dpus=20,
                create_job_kwargs={'WorkerType': 'G.2X', 'NumberOfWorkers': 60},
            )

    @mock.patch.object(GlueJobHook, "get_job_state")
    @mock.patch.object(GlueJobHook, "get_or_create_glue_job")
    @mock.patch.object(GlueJobHook, "get_conn")
    def test_initialize_job(self, mock_get_conn, mock_get_or_create_glue_job, mock_get_job_state):
        some_data_path = "s3://glue-datasets/examples/medicare/SampleData.csv"
        some_script_arguments = {"--s3_input_data_path": some_data_path}
        some_run_kwargs = {"NumberOfWorkers": 5}
        some_script = "s3:/glue-examples/glue-scripts/sample_aws_glue_job.py"
        some_s3_bucket = "my-includes"

        mock_get_or_create_glue_job.Name = mock.Mock(Name='aws_test_glue_job')
        mock_get_conn.return_value.start_job_run()

        mock_job_run_state = mock_get_job_state.return_value
        glue_job_hook = GlueJobHook(
            job_name='aws_test_glue_job',
            desc='This is test case job from Airflow',
            iam_role_name='my_test_role',
            script_location=some_script,
            s3_bucket=some_s3_bucket,
            region_name=self.some_aws_region,
        )
        glue_job_run = glue_job_hook.initialize_job(some_script_arguments, some_run_kwargs)
        glue_job_run_state = glue_job_hook.get_job_state(glue_job_run['JobName'], glue_job_run['JobRunId'])
        assert glue_job_run_state == mock_job_run_state, 'Mocks but be equal'

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>org.apache.helix</groupId>
    <artifactId>helix</artifactId>
    <version>0.7.2-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>helix-ipc</artifactId>
  <packaging>bundle</packaging>

  <name>Apache Helix :: IPC</name>

  <properties>
    <osgi.import>
      javax.management*,
      org.apache.commons.math*;version="[2.1,3)",
      org.apache.log4j*;version="[1.2,2)",
      *
    </osgi.import>
    <osgi.ignore>
      org.apache.helix.tools*
    </osgi.ignore>
    <osgi.export>org.apache.helix.resolver*,org.apache.helix.ipc*;version="${project.version};-noimport:=true</osgi.export>
  </properties>

  <dependencies>
      <dependency>
          <groupId>org.apache.helix</groupId>
          <artifactId>helix-core</artifactId>
      </dependency>
      <dependency>
          <groupId>io.netty</groupId>
          <artifactId>netty-all</artifactId>
          <version>4.0.21.Final</version>
      </dependency>
      <dependency>
          <groupId>com.codahale.metrics</groupId>
          <artifactId>metrics-core</artifactId>
          <version>3.0.1</version>
      </dependency>
      <dependency>
          <groupId>org.apache.helix</groupId>
          <artifactId>helix-core</artifactId>
          <type>test-jar</type>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.testng</groupId>
          <artifactId>testng</artifactId>
          <scope>test</scope>
          <exclusions>
              <exclusion>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
  </dependencies>
  <build>
    <!--
    <resources>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>${basedir}</directory>
      </resource>
    </resources>
    -->
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>appassembler-maven-plugin</artifactId>
        <configuration>
          <programs>
          </programs>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
            <descriptor>src/assemble/assembly.xml</descriptor>
          </descriptors>
          <!--
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          -->
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using Xunit;
using YouTrackSharp.Tests.Infrastructure;

namespace YouTrackSharp.Tests.Integration.Projects
{
    public partial class ProjectCustomFieldsServiceTests
    {
        public class DeleteProjectCustomField
        {
            [Fact]
            public async Task Valid_Connection_Deletes_CustomField_For_Project()
            {
                // Arrange
                var connection = Connections.Demo1Token;
                var service = connection.ProjectCustomFieldsService();

                // Act & Assert
                bool acted;
                await service.DeleteProjectCustomField("DP1", "TestField");
                acted = true;

                Assert.True(acted);
            }

            [Fact]
            public async Task Invalid_Connection_Throws_UnauthorizedConnectionException()
            {
                // Arrange
                var service = Connections.UnauthorizedConnection.ProjectCustomFieldsService();

                // Act & Assert
                await Assert.ThrowsAsync<UnauthorizedConnectionException>(
                    async () => await service.DeleteProjectCustomField("DP1", "TestField"));
            }
        }
    }
}


text:
package com.bxf.hradmin.common.model;

import java.io.Serializable;

/**
 * QueryCond
 *
 * @since 2016-06-09
 * @author Bo-Xuan Fan
 */
public abstract class QueryCond implements Serializable {
    private static final long serialVersionUID = 2392186992502397377L;

    protected int limit = 10;
    protected int activePage = 0;
    protected String order;
    protected String sort;
    /**
     * is ascending or descending
     */
    protected boolean isAsc;

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getActivePage() {
        return activePage;
    }

    public void setActivePage(int activePage) {
        this.activePage = activePage;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public boolean isAsc() {
        return isAsc;
    }

    public void setAsc(boolean isAsc) {
        this.isAsc = isAsc;
    }
}


text:
class AzStoreItemScetchesController < ApplicationController

  filter_access_to :index, :new, :create
  filter_access_to :all, :attribute_check => true

  layout "main"

  # GET /az_store_item_scetches
  # GET /az_store_item_scetches.xml
  def index
    @az_store_item_scetches = AzStoreItemScetch.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @az_store_item_scetches }
    end
  end

  # GET /az_store_item_scetches/1
  # GET /az_store_item_scetches/1.xml
  def show
    @az_store_item_scetch = AzStoreItemScetch.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @az_store_item_scetch }
    end
  end

  # GET /az_store_item_scetches/new
  # GET /az_store_item_scetches/new.xml
  def new
    @az_store_item_scetch = AzStoreItemScetch.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @az_store_item_scetch }
    end
  end

  # GET /az_store_item_scetches/1/edit
  def edit
    @az_store_item_scetch = AzStoreItemScetch.find(params[:id])
  end

  # POST /az_store_item_scetches
  # POST /az_store_item_scetches.xml
  def create
    @az_store_item_scetch = AzStoreItemScetch.new(params[:az_store_item_scetch])

    respond_to do |format|
      if @az_store_item_scetch.save
        format.html { redirect_to(@az_store_item_scetch, :notice => 'AzStoreItemScetch was successfully created.') }
        format.xml  { render :xml => @az_store_item_scetch, :status => :created, :location => @az_store_item_scetch }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @az_store_item_scetch.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /az_store_item_scetches/1
  # PUT /az_store_item_scetches/1.xml
  def update
    @az_store_item_scetch = AzStoreItemScetch.find(params[:id])

    respond_to do |format|
      if @az_store_item_scetch.update_attributes(params[:az_store_item_scetch])
        format.html { redirect_to(@az_store_item_scetch, :notice => 'AzStoreItemScetch was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @az_store_item_scetch.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /az_store_item_scetches/1
  # DELETE /az_store_item_scetches/1.xml
  def destroy
    @az_store_item_scetch = AzStoreItemScetch.find(params[:id])
    @az_store_item_scetch.destroy

    respond_to do |format|
      format.html { redirect_to(az_store_item_scetches_url) }
      format.xml  { head :ok }
    end
  end
end


text:
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __C_IRR_DEVICE_WIN32_H_INCLUDED__
#define __C_IRR_DEVICE_WIN32_H_INCLUDED__

#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_WINDOWS_DEVICE_

#include "CIrrDeviceStub.h"
#include "IrrlichtDevice.h"
#include "IImagePresenter.h"

#define WIN32_LEAN_AND_MEAN
#if !defined(_IRR_XBOX_PLATFORM_)
	#include <windows.h>
	#include <mmsystem.h> // For JOYCAPS
	#include <windowsx.h>
#endif
#if !defined(GET_X_LPARAM)
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
#endif

namespace irr
{
	struct SJoystickWin32Control;

	class CIrrDeviceWin32 : public CIrrDeviceStub, video::IImagePresenter
	{
	friend struct SJoystickWin32Control;
	public:

		//! constructor
		CIrrDeviceWin32(const SIrrlichtCreationParameters& params);

		//! destructor
		virtual ~CIrrDeviceWin32();

		//! runs the device. Returns false if device wants to be deleted
		virtual bool run();

		//! Cause the device to temporarily pause execution and let other processes to run
		// This should bring down processor usage without major performance loss for Irrlicht
		virtual void yield();

		//! Pause execution and let other processes to run for a specified amount of time.
		virtual void sleep(u32 timeMs, bool pauseTimer);

		//! sets the caption of the window
		virtual void setWindowCaption(const wchar_t* text);

		//! returns if window is active. if not, nothing need to be drawn
		virtual bool isWindowActive() const;

		//! returns if window has focus
		virtual bool isWindowFocused() const;

		//! returns if window is minimized
		virtual bool isWindowMinimized() const;

		//! presents a surface in the client area
		virtual bool present(video::IImage* surface, void* windowId=0, core::rect<s32>* src=0);

		//! notifies the device that it should close itself
		virtual void closeDevice();

		//! \return Returns a pointer to a list with all video modes
		//! supported by the gfx adapter.
		video::IVideoModeList* getVideoModeList();

		//! Notifies the device, that it has been resized
		void OnResized();

		//! Sets if the window should be resizable in windowed mode.
		virtual void setResizable(bool resize=false);

		//! Minimizes the window.
		virtual void minimizeWindow();

		//! Maximizes the window.
		virtual void maximizeWindow();

		//! Restores the window size.
		virtual void restoreWindow();

		//! Activate any joysticks, and generate events for them.
		virtual bool activateJoysticks(core::array<SJoystickInfo> & joystickInfo);

		//! Set the current Gamma Value for the Display
		virtual bool setGammaRamp( f32 red, f32 green, f32 blue, f32 brightness, f32 contrast );

		//! Get the current Gamma Value for the Display
		virtual bool getGammaRamp( f32 &red, f32 &green, f32 &blue, f32 &brightness, f32 &contrast );

		//! Remove all messages pending in the system message loop
		virtual void clearSystemMessages();

		//! Get the device type
		virtual E_DEVICE_TYPE getType() const
		{
				return EIDT_WIN32;
		}

		//! Compares to the last call of this function to return double and triple clicks.
		//! \return Returns only 1,2 or 3. A 4th click will start with 1 again.
		virtual u32 checkSuccessiveClicks(s32 mouseX, s32 mouseY, EMOUSE_INPUT_EVENT inputEvent )
		{
			// we just have to make it public
			return CIrrDeviceStub::checkSuccessiveClicks(mouseX, mouseY, inputEvent );
		}

		//! switchs to fullscreen
		bool switchToFullScreen(bool reset=false);

		//! Check for and show last Windows API error to help internal debugging.
		//! Does call GetLastError and on errors formats the errortext and displays it in a messagebox.
		static void ReportLastWinApiError();

		// convert an Irrlicht texture to a windows cursor
		HCURSOR TextureToCursor(HWND hwnd, irr::video::ITexture * tex, const core::rect<s32>& sourceRect, const core::position2d<s32> &hotspot);

		//! Implementation of the win32 cursor control
		class CCursorControl : public gui::ICursorControl
		{
		public:

			CCursorControl(CIrrDeviceWin32* device, const core::dimension2d<u32>& wsize, HWND hwnd, bool fullscreen);
			~CCursorControl();

			//! Changes the visible state of the mouse cursor.
			virtual void setVisible(bool visible)
			{
				CURSORINFO info;
				info.cbSize = sizeof(CURSORINFO);
				BOOL gotCursorInfo = GetCursorInfo(&info);
				while ( gotCursorInfo )
				{
#ifdef CURSOR_SUPPRESSED
					// new flag for Windows 8, where cursor
					// might be suppressed for touch interface
					if (info.flags == CURSOR_SUPPRESSED)
					{
						visible=false;
						break;
					}
#endif
					if ( (visible && info.flags == CURSOR_SHOWING) || // visible
						(!visible && info.flags == 0 ) ) // hidden
					{
						break;
					}
					// this only increases an internal
					// display counter in windows, so it
					// might have to be called some more
					const int showResult = ShowCursor(visible);
					// if result has correct sign we can
					// stop here as well
					if (( !visible && showResult < 0 ) ||
						(visible && showResult >= 0))
						break;
					// yes, it really must be set each time
					info.cbSize = sizeof(CURSORINFO);
					gotCursorInfo = GetCursorInfo(&info);
				}
				IsVisible = visible;
			}

			//! Returns if the cursor is currently visible.
			virtual bool isVisible() const
			{
				_IRR_IMPLEMENT_MANAGED_MARSHALLING_BUGFIX;
				return IsVisible;
			}

			//! Sets the new position of the cursor.
			virtual void setPosition(const core::position2d<f32> &pos)
			{
				setPosition(pos.X, pos.Y);
			}

			//! Sets the new position of the cursor.
			virtual void setPosition(f32 x, f32 y)
			{
				if (!UseReferenceRect)
					setPosition(core::round32(x*WindowSize.Width), core::round32(y*WindowSize.Height));
				else
					setPosition(core::round32(x*ReferenceRect.getWidth()), core::round32(y*ReferenceRect.getHeight()));
			}

			//! Sets the new position of the cursor.
			virtual void setPosition(const core::position2d<s32> &pos)
			{
				setPosition(pos.X, pos.Y);
			}

			//! Sets the new position of the cursor.
			virtual void setPosition(s32 x, s32 y)
			{
				if (UseReferenceRect)
				{
					SetCursorPos(ReferenceRect.UpperLeftCorner.X + x,
								 ReferenceRect.UpperLeftCorner.Y + y);
				}
				else
				{
					RECT rect;
					if (GetWindowRect(HWnd, &rect))
						SetCursorPos(x + rect.left + BorderX, y + rect.top + BorderY);
				}

				CursorPos.X = x;
				CursorPos.Y = y;
			}

			//! Returns the current position of the mouse cursor.
			virtual const core::position2d<s32>& getPosition()
			{
				updateInternalCursorPosition();
				return CursorPos;
			}

			//! Returns the current position of the mouse cursor.
			virtual core::position2d<f32> getRelativePosition()
			{
				updateInternalCursorPosition();

				if (!UseReferenceRect)
				{
					return core::position2d<f32>(CursorPos.X * InvWindowSize.Width,
						CursorPos.Y * InvWindowSize.Height);
				}

				return core::position2d<f32>(CursorPos.X / (f32)ReferenceRect.getWidth(),
						CursorPos.Y / (f32)ReferenceRect.getHeight());
			}

			//! Sets an absolute reference rect for calculating the cursor position.
			virtual void setReferenceRect(core::rect<s32>* rect=0)
			{
				if (rect)
				{
					ReferenceRect = *rect;
					UseReferenceRect = true;

					// prevent division through zero and uneven sizes

					if (!ReferenceRect.getHeight() || ReferenceRect.getHeight()%2)
						ReferenceRect.LowerRightCorner.Y += 1;

					if (!ReferenceRect.getWidth() || ReferenceRect.getWidth()%2)
						ReferenceRect.LowerRightCorner.X += 1;
				}
				else
					UseReferenceRect = false;
			}

			/** Used to notify the cursor that the window was resized. */
			virtual void OnResize(const core::dimension2d<u32>& size)
			{
				WindowSize = size;
				if (size.Width!=0)
					InvWindowSize.Width = 1.0f / size.Width;
				else
					InvWindowSize.Width = 0.f;

				if (size.Height!=0)
					InvWindowSize.Height = 1.0f / size.Height;
				else
					InvWindowSize.Height = 0.f;
			}

			/** Used to notify the cursor that the window resizable settings changed. */
			void updateBorderSize(bool fullscreen, bool resizable)
			{
			   if (!fullscreen)
			   {
				  if (resizable)
				  {
					 BorderX = GetSystemMetrics(SM_CXSIZEFRAME);
					 BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYSIZEFRAME);
				  }
				  else
				  {
					 BorderX = GetSystemMetrics(SM_CXDLGFRAME);
					 BorderY = GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYDLGFRAME);
				  }
			   }
			   else
			   {
				  BorderX = BorderY = 0;
			   }
			}

			//! Sets the active cursor icon
			virtual void setActiveIcon(gui::ECURSOR_ICON iconId);

			//! Gets the currently active icon
			virtual gui::ECURSOR_ICON getActiveIcon() const
			{
				return ActiveIcon;
			}

			//! Add a custom sprite as cursor icon.
			virtual gui::ECURSOR_ICON addIcon(const gui::SCursorSprite& icon);

			//! replace the given cursor icon.
			virtual void changeIcon(gui::ECURSOR_ICON iconId, const gui::SCursorSprite& icon);

            //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work.
			virtual core::dimension2di getSupportedIconSize() const;

            void update();

		private:

			//! Updates the internal cursor position
			void updateInternalCursorPosition()
			{
				POINT p;
				if (!GetCursorPos(&p))
				{
					DWORD xy = GetMessagePos();
					p.x = GET_X_LPARAM(xy);
					p.y = GET_Y_LPARAM(xy);
				}

				if (UseReferenceRect)
				{
					CursorPos.X = p.x - ReferenceRect.UpperLeftCorner.X;
					CursorPos.Y = p.y - ReferenceRect.UpperLeftCorner.Y;
				}
				else
				{
					RECT rect;
					if (GetWindowRect(HWnd, &rect))
					{
						CursorPos.X = p.x-rect.left-BorderX;
						CursorPos.Y = p.y-rect.top-BorderY;
					}
					else
					{
						// window seems not to be existent, so set cursor to
						// a negative value
						CursorPos.X = -1;
						CursorPos.Y = -1;
					}
				}
			}

            CIrrDeviceWin32* Device;
			core::position2d<s32> CursorPos;
			core::dimension2d<u32> WindowSize;
			core::dimension2d<f32> InvWindowSize;
			HWND HWnd;

			s32 BorderX, BorderY;
			core::rect<s32> ReferenceRect;
			bool UseReferenceRect;
			bool IsVisible;

			struct CursorFrameW32
			{
				CursorFrameW32() : IconHW(0) {}
				CursorFrameW32(HCURSOR icon) : IconHW(icon) {}

				HCURSOR IconHW;	// hardware cursor
			};

			struct CursorW32
			{
				CursorW32() {}
				explicit CursorW32(HCURSOR iconHw, u32 frameTime=0) : FrameTime(frameTime)
				{
					Frames.push_back( CursorFrameW32(iconHw) );
				}
				core::array<CursorFrameW32> Frames;
				u32 FrameTime;
			};

			core::array<CursorW32> Cursors;
			gui::ECURSOR_ICON ActiveIcon;
			u32 ActiveIconStartTime;

			void initCursors();
		};

		//! returns the win32 cursor control
		CCursorControl* getWin32CursorControl();

	private:

		//! create the driver
		void createDriver();

		//! Process system events
		void handleSystemMessages();

		void getWindowsVersion(core::stringc& version);

		void resizeIfNecessary();

		HWND HWnd;

		bool ChangedToFullScreen;
		bool Resized;
		bool ExternalWindow;
		CCursorControl* Win32CursorControl;
		DEVMODE DesktopMode;

		SJoystickWin32Control* JoyControl;
	};

} // end namespace irr

#endif // _IRR_COMPILE_WITH_WINDOWS_DEVICE_
#endif // __C_IRR_DEVICE_WIN32_H_INCLUDED__


text:
package zipkin2.server.internal.elasticsearch;

import com.linecorp.armeria.client.ClientRequestContext;
import com.linecorp.armeria.client.HttpClient;
import com.linecorp.armeria.client.SimpleDecoratingHttpClient;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import java.util.Objects;

/**
 * Adds basic auth username and password to every request.
 *
 *
Ref:  How
 * Elasticsearch security works

 */
final class BasicAuthInterceptor extends SimpleDecoratingHttpClient {

  final BasicCredentials basicCredentials;

  BasicAuthInterceptor(HttpClient client, BasicCredentials basicCredentials) {
    super(client);
    this.basicCredentials = basicCredentials;
  }

  @Override
  public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception {
    String credentials = basicCredentials.getCredentials();
    if (credentials != null) {
      ctx.addAdditionalRequestHeader(HttpHeaderNames.AUTHORIZATION, credentials);
    }
    return unwrap().execute(ctx, req);
  }
}


text:
    <md-progress-circular class="md-accent" md-mode="indeterminate" ng-show="q.tracker.active()"></md-progress-circular>

没有更多数据了~


text:
package com.example.helloandroidcamera2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class CameraActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, Camera2BasicFragment.newInstance())
                    .commit();
        }
    }
}


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

<title>Uses of Interface org.apache.hadoop.mapred.InputSplit (Hadoop 2.6.0-mr1-cdh5.4.2 API)</title>
<meta name="date" content="2015-05-19">
<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 Interface
org.apache.hadoop.mapred.InputSplit

Packages that use InputSplit

Package
Description

org.apache.hadoop.contrib.index.example

org.apache.hadoop.examples

Hadoop example code.

org.apache.hadoop.examples.terasort

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

org.apache.hadoop.mapred

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

org.apache.hadoop.mapred.join

Given a set of sorted datasets keyed with the same class and yielding equal
partitions, it is possible to effect a join of those datasets prior to the map.

org.apache.hadoop.mapred.lib

Library of generally useful mappers, reducers, and partitioners.

org.apache.hadoop.mapred.lib.db

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

org.apache.hadoop.mapreduce.split

org.apache.hadoop.streaming

<tt>Hadoop Streaming</tt> is a utility which allows users to create and run
Map-Reduce jobs with any executables (e.g.

Uses of InputSplit in org.apache.hadoop.contrib.index.example

Methods in org.apache.hadoop.contrib.index.example with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<DocumentID,LineDocTextAndOp>
LineDocInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Uses of InputSplit in org.apache.hadoop.examples

Classes in org.apache.hadoop.examples that implement InputSplit

Modifier and Type
Class and Description

static class
SleepJob.EmptySplit

Methods in org.apache.hadoop.examples that return InputSplit

Modifier and Type
Method and Description

InputSplit[]
SleepJob.SleepInputFormat.getSplits(JobConf conf,
         int numSplits)

Methods in org.apache.hadoop.examples with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<org.apache.hadoop.io.IntWritable,org.apache.hadoop.io.IntWritable>
SleepJob.SleepInputFormat.getRecordReader(InputSplit ignored,
               JobConf conf,
               Reporter reporter)

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

Methods in org.apache.hadoop.examples.terasort that return InputSplit

Modifier and Type
Method and Description

InputSplit[]
TeraInputFormat.getSplits(JobConf conf,
         int splits)

Methods in org.apache.hadoop.examples.terasort with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<org.apache.hadoop.io.Text,org.apache.hadoop.io.Text>
TeraInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Uses of InputSplit in org.apache.hadoop.mapred

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

Modifier and Type
Class and Description

class
FileSplit

A section of an input file.

class
MultiFileSplit

Deprecated.

Use CombineFileSplit instead

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

Modifier and Type
Method and Description

InputSplit
Task.TaskReporter.getInputSplit()

InputSplit
Reporter.getInputSplit()

Get the InputSplit object for a map.

InputSplit[]
InputFormat.getSplits(JobConf job,
         int numSplits)

Logically split the set of input files for the job.

InputSplit[]
MultiFileInputFormat.getSplits(JobConf job,
         int numSplits)

Deprecated.

InputSplit[]
FileInputFormat.getSplits(JobConf job,
         int numSplits)

Splits files returned by FileInputFormat.listStatus(JobConf) when
 they're too big.

Methods in org.apache.hadoop.mapred with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<K,V>
InputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Get the RecordReader for the given InputSplit.

RecordReader<org.apache.hadoop.io.BytesWritable,org.apache.hadoop.io.BytesWritable>
SequenceFileAsBinaryInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

RecordReader<K,V>
SequenceFileInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

RecordReader<K,V>
SequenceFileInputFilter.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Create a record reader for the given split

RecordReader<org.apache.hadoop.io.Text,org.apache.hadoop.io.Text>
KeyValueTextInputFormat.getRecordReader(InputSplit genericSplit,
               JobConf job,
               Reporter reporter)

abstract RecordReader<K,V>
MultiFileInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Deprecated.

abstract RecordReader<K,V>
FileInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

RecordReader<org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text>
TextInputFormat.getRecordReader(InputSplit genericSplit,
               JobConf job,
               Reporter reporter)

RecordReader<org.apache.hadoop.io.Text,org.apache.hadoop.io.Text>
SequenceFileAsTextInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

void
Task.TaskReporter.setInputSplit(InputSplit split)

Uses of InputSplit in org.apache.hadoop.mapred.join

Classes in org.apache.hadoop.mapred.join that implement InputSplit

Modifier and Type
Class and Description

class
CompositeInputSplit

This InputSplit contains a set of child InputSplits.

Methods in org.apache.hadoop.mapred.join that return InputSplit

Modifier and Type
Method and Description

InputSplit
CompositeInputSplit.get(int i)

Get ith child InputSplit.

InputSplit[]
CompositeInputFormat.getSplits(JobConf job,
         int numSplits)

Build a CompositeInputSplit from the child InputFormats by assigning the
 ith split from each child to the ith composite split.

Methods in org.apache.hadoop.mapred.join with parameters of type InputSplit

Modifier and Type
Method and Description

void
CompositeInputSplit.add(InputSplit s)

Add an InputSplit to this collection.

ComposableRecordReader<K,V>
ComposableInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

ComposableRecordReader<K,TupleWritable>
CompositeInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Construct a CompositeRecordReader for the children of this InputFormat
 as defined in the init expression.

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

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

Modifier and Type
Class and Description

class
CombineFileSplit

A sub-collection of input files.

Methods in org.apache.hadoop.mapred.lib that return InputSplit

Modifier and Type
Method and Description

InputSplit[]
CombineFileInputFormat.getSplits(JobConf job,
         int numSplits)

InputSplit[]
NLineInputFormat.getSplits(JobConf job,
         int numSplits)

Logically splits the set of input files for the job, splits N lines
 of the input as one split.

InputSplit[]
DelegatingInputFormat.getSplits(JobConf conf,
         int numSplits)

Methods in org.apache.hadoop.mapred.lib with parameters of type InputSplit

Modifier and Type
Method and Description

abstract RecordReader<K,V>
CombineFileInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

This is not implemented yet.

RecordReader<org.apache.hadoop.io.LongWritable,org.apache.hadoop.io.Text>
NLineInputFormat.getRecordReader(InputSplit genericSplit,
               JobConf job,
               Reporter reporter)

RecordReader<K,V>
DelegatingInputFormat.getRecordReader(InputSplit split,
               JobConf conf,
               Reporter reporter)

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

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

Modifier and Type
Class and Description

protected static class
DBInputFormat.DBInputSplit

A InputSplit that spans a set of rows

Methods in org.apache.hadoop.mapred.lib.db that return InputSplit

Modifier and Type
Method and Description

InputSplit[]
DBInputFormat.getSplits(JobConf job,
         int chunks)

Logically split the set of input files for the job.

Methods in org.apache.hadoop.mapred.lib.db with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<org.apache.hadoop.io.LongWritable,T>
DBInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Get the RecordReader for the given InputSplit.

Uses of InputSplit in org.apache.hadoop.mapreduce.split

Methods in org.apache.hadoop.mapreduce.split with parameters of type InputSplit

Modifier and Type
Method and Description

static void
JobSplitWriter.createSplitFiles(org.apache.hadoop.fs.Path jobSubmitDir,
                org.apache.hadoop.conf.Configuration conf,
                org.apache.hadoop.fs.FileSystem fs,
                InputSplit[] splits)

Uses of InputSplit in org.apache.hadoop.streaming

Methods in org.apache.hadoop.streaming with parameters of type InputSplit

Modifier and Type
Method and Description

RecordReader<org.apache.hadoop.io.Text,org.apache.hadoop.io.Text>
StreamInputFormat.getRecordReader(InputSplit genericSplit,
               JobConf job,
               Reporter reporter)

RecordReader
AutoInputFormat.getRecordReader(InputSplit split,
               JobConf job,
               Reporter reporter)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2009 The Apache Software Foundation


text:
document.open();
document.write('
');
document.write('
');
document.write("
");
document.write('
');
document.write('
');
document.write("
Date : September 30, 2014

");
document.write("Location : Boston, MA");
document.write('
');
document.write('
');
document.write("
   High | 17℃

");
document.write("   Low  | 13℃");
document.write('
');
document.write('
');
document.close();


text:
This notification is used to tell the user to wait while some longer action is performed. The default action is to show a hourglass instead of the normal cursor.

iVars:

block		- the code to execute


text:
Sahara Dashboard Configuration Guide
====================================

After installing the Sahara dashboard, there are a few extra configurations
that can be made.

Dashboard configurations are applied through Horizon's local_settings.py file.
The sample configuration file is available `from the Horizon repository. <https://opendev.org/openstack/horizon/src/branch/master/openstack_dashboard/local/local_settings.py.example>`_

1. Networking
-------------

Depending on the Networking backend (Neutron) used in the
cloud, Sahara panels will determine automatically which input fields should be
displayed.

If you wish to disable floating IP options during node group template
creation, add the following parameter:

Example:

.. sourcecode:: python

    SAHARA_FLOATING_IP_DISABLED = True
..

2. Different endpoint
---------------------

Sahara UI panels normally use ``data-processing`` endpoint from Keystone to
talk to Sahara service. In some cases it may be useful to switch to another
endpoint, for example use locally installed Sahara instead of the one on the
OpenStack controller.

To switch the UI to another endpoint the endpoint should be registered in the
first place.

Local endpoint example:

.. code-block::

    $ openstack service create --name sahara_local --description \
      "Sahara Data Processing (local installation)" \
      data_processing_local

    $ openstack endpoint create --region RegionOne \
      data_processing_local public http://127.0.0.1:8386/v1.1/%\(project_id\)s

    $ openstack endpoint create --region RegionOne \
      data_processing_local internal  http://127.0.0.1:8386/v1.1/%\(project_id\)s

    $ openstack endpoint create --region RegionOne \
      data_processing_local admin http://127.0.0.1:8386/v1.1/%\(project_id\)s
..

Then the endpoint name should be changed in ``sahara.py`` under the module of
`sahara-dashboard/sahara_dashboard/api/sahara.py
<https://opendev.org/openstack/sahara-dashboard/src/branch/master/sahara_dashboard/api/sahara.py>`__.

.. sourcecode:: python

    # "type" of Sahara service registered in keystone
    SAHARA_SERVICE = 'data_processing_local'

3. Hiding health check info
---------------------------

Sahara UI panels normally contain some information about cluster health. If
the relevant functionality has been disabled in the Sahara service, then
operators may prefer to not have any references to health at all in the UI,
since there would not be any usable health information in that case.

The visibility of health check info can be toggled via the
``SAHARA_VERIFICATION_DISABLED`` parameter, whose default value is False,
meaning that the health check info will be visible.

Example:

.. sourcecode:: python

    SAHARA_VERIFICATION_DISABLED = True
..


text:
var fs = require('fs'),
	vm = require('vm'),
	path = require('path'),
	Canvas = require('canvas');

__dirname = path.resolve(__dirname, '../src/');

// Create the context within which we will run the source files:
var context = vm.createContext({
	options: {
		server: true,
		parser: 'acorn',
		version: 'dev'
	},
	fs: fs,
	// Node Canvas library: https://github.com/learnboost/node-canvas
	Canvas: Canvas,
	HTMLCanvasElement: Canvas,
	Image: Canvas.Image,
	// Copy over global variables:
    console: console,
	require: require,
	__dirname: __dirname,
	__filename: __filename,
	// Used to load and run source files within the same context:
	include: function(uri) {
		var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
		// For relative includes, we save the current directory and then
		// add the uri directory to __dirname:
		var oldDirname = __dirname;
		__dirname = path.resolve(__dirname, path.dirname(uri));
		vm.runInContext(source, context, uri);
		__dirname = oldDirname;
	}
});

// Load Paper.js library files:
context.include('paper.js');

context.Base.each(context, function(val, key) {
	if (val && val.prototype instanceof context.Base) {
		val._name = key;
		// Export all classes through PaperScope:
		context.PaperScope.prototype[key] = val;
	}
});
context.PaperScope.prototype['Canvas'] = context.Canvas;

require.extensions['.pjs'] = function(module, uri) {
	var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
	var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
				 'var __filename = \'' + uri + '\';';
	vm.runInContext(envVars, context);
	var scope = new context.PaperScope();
	context.PaperScript.evaluate(source, scope);
	module.exports = scope;
};

module.exports = new context.PaperScope();


text:
Latest LEMP Stack Installation on Ubuntu Server using Ansible
--------
There's a blog post that I wrote to go along with this. [Check it out!]

This role is helpful to install Nginx, PHP and MySQL(LEMP) on Ubuntu server 14.04 LTS.

[LEMP Installation Tutorial] - This step by step tutorial explains the installation and configuration of LEMP Stack on Ubuntu server.

### To use this Role:

Edit the `site.yml` file, mentioned this role:

```yaml
---
- hosts: server
  become: yes
  gather_facts: yes
  roles:
    - LEMP
```
After that edit the `defaults/main.yml` file:

> Change the `mysql_port` & `mysql_bind_address` if you are using non-standard/modified setting.
>
> Edit the `mysql_root_pass` for MySQL root password.
>
> Give the maximum nginx connections and server_name as well (default is 1024 connections and localhost as server_name)

After Editing the file, it will look like this:
```yaml
---
 mysql_port: 3306 #Default is 3306, please change it if you are using non-standard
 mysql_bind_address: "127.0.0.1" #Change it to "0.0.0.0",if you want to listen everywhere
 mysql_root_pass: mypassword #MySQL Root Password
 connections: 1024 #Nginx Connection
 server_name: localhost #Nginx server_name, change it to your website e.g: rbgeek.com
```

Then run this command:

```
ansible-playbook -i hosts -u arbab site.yml
```
**Note:** Please don't forget to change `arbab` with your username

[LEMP Installation Tutorial]:https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04
[Check it out!]:https://rbgeek.wordpress.com/2015/02/22/installing-the-lemp-stack-on-ubuntu-using-ansible


text:
package com.cisco.collab.dobby.relay.api.ping;

import javax.ws.rs.Path;

import org.springframework.stereotype.Component;

import com.cisco.collab.dobby.relay.api.ping.model.Pong;
import com.cisco.collab.dobby.relay.api.ping.resource.ProtectedPingResource;

@Component
@Path("ping")
public class ProtectedPingService implements ProtectedPingResource {

    public GetPingResponse getPing(String authorization) throws Exception {
        Pong pong = new Pong();
        pong.setMessage("Hello World");
        return GetPingResponse.withJsonOK(pong);
    }

}


text:
title: Analytics Support
page_title: Analytics Support - UI for WinForms Documentation
description: When you are creating an application for a broad audience, integrating some kind of analytics framework is crucial, because you will need to analyze the usage data of the application and its features and most probably you will need to know about any application crashes or other errors occurred during the execution.
slug: winforms/analytics/analytics-support
tags: telerik,analytics,support
published: True
position: 0
previous_url: telerik-analytics-integration
---

# Application Analytics

When you are creating an application for a broad audience, integrating some kind of analytics framework is crucial, because you will need to analyze the usage data of the application and its features and most probably you will need to know about any application crashes or other errors occurred during the execution. Using Analytics you will be able to trace certain features of the controls and get statistics about their usage.

This article will discuss the following topics:

* [ITraceMonitor Interface](#itracemonitor-interface)
* [How Analytics Works](#how-analytics-works)
* [Traceable Features](#traceable-features)

>note With the discontinuation of the Telerik Platform as of R2 2018 SP1 (version 2018.2.621) we've also removed the two dependent assemblies from our suite - EQATEC.Analytics.Monitor.dll and Telerik.WinControls.Analytics.dll. The respective NuGet packages have been removed as well. Instead, the ITraceMonitor interface should be used as explained below.

## ITraceMonitor Interface

With the R1 2014 release UI for WinForms exposes the **ITraceMonitor** interface which represents a monitor receiving trace events from the UI for WinForms controls.

You need to implement the following methods in order to receive trace events from the controls used in your application:

 * **TrackAtomicFeature**: This method is called when an atomic feature is executed.
 * **TrackFeatureStart**: This method is called when a feature is initiated.
 * **TrackFeatureEnd**: This method is called when a feature finishes execution.
 * **TrackFeatureCancel**: This method is called when a feature is canceled.
 * **TrackError**: Traces an error in a specified feature.
 * **TrackValue**: This method is called when a value connected with a specific feature is tracked.

Once you've created your implementation of the interface in accordance to your provider of choice you need to set the static TraceMonitor.**AnalyticsMonitor** property as per the example below.

#### ITraceMonitor Instance

{{source=..\SamplesCS\Analytics\AnalyticsForm.cs region=ITraceMonitorInstance}}
{{source=..\SamplesVB\Analytics\AnalyticsForm.vb region=ITraceMonitorInstance}}
````C#
ControlTraceMonitor.AnalyticsMonitor = new CustomAnalitycsMonitor();

````
````VB.NET
ControlTraceMonitor.AnalyticsMonitor = New CustomAnalitycsMonitor()

````

{{endregion}}

## How Analytics Works

Each control has analytics enabled by default, on control basis analytics can be disabled by setting the control`s **EnableAnalytics** property to *false*. Having analytics enabled, all one needs to do to start tracing the application usage is to set the **AnalyticsName** property for each control. Note that the value which is set will be used in the dashboard.

#### Set AnalyticsName

{{source=..\SamplesCS\Analytics\AnalyticsForm.cs region=SetAnalyticsName}}
{{source=..\SamplesVB\Analytics\AnalyticsForm.vb region=SetAnalyticsName}}
````C#
this.radButton1.EnableAnalytics = true; // default value
this.radButton1.AnalyticsName = "Save Button";

````
````VB.NET
Me.RadButton1.EnableAnalytics = True
' default value
Me.RadButton1.AnalyticsName = "Save Button"

````

{{endregion}}

You can then go to the dashboard of your analytics provider, where you will find information and statistics for the registered features for different periods of time.

#### Disable Analytics

{{source=..\SamplesCS\Analytics\AnalyticsForm.cs region=DisableAnalytics}}
{{source=..\SamplesVB\Analytics\AnalyticsForm.vb region=DisableAnalytics}}
````C#
this.radButton1.EnableAnalytics = false;

````
````VB.NET
Me.RadButton1.EnableAnalytics = False

````

{{endregion}}

## Traceable Features

Currently only few controls support analytics out of the box. Note that only user interactions will be tracked - initial values and values from Bindings are not supported. You can find below a list of the controls and their features that support tracing:

| Control | Traceable events and methods |
| ------ | ------ |
|**ColorPicker**|SelectionChanged|
|**RadAutocompleteBox**|InsertText|
|**RadBindingNavigator**|MoveToFirst, MoveToPrevious, MoveToNext, MoveToLast|
|**RadButton**|Click|
|**RadBulletGraph**|ValueChanged|
|**RadCalendar**|SelectionChaned, Navigation, ViewChanged|
|**RadCarousel**|Selection|
|**RadChartView**|Zoom, Pan, SelectionChanged|
|**RadCheckedDropDownList**|Checked, Popup open close|
|**RadCollapsiblePanel**|Expand, Collapse|
|**RadColorBox**|SelectionChanged|
|**RadContextMenu**|Open, Close, Click (RadContextMenu.DropDown)|
|**RadDataEntry**|Editing, Insert/Delete, MoveToFirst, MoveToPrevious, MoveToNext, MoveToLast|
|**RadDataLayout**|Customize open, Item rearrange (via drag and drop, resize or context menu)|
|**RadDateTimePicker**|ValueChanged|
|**RadDiagram**|Move, Resize, Add, Delete|
|**RadDock**|Save layout, Load layout, Float a pane, Dock a pane, Add window, Remove window|
|**RadDropDownButton**|DropDownOpened, DropDownClosed|
|**RadDropdownList**|SelectionChanged,  DropDownOpened, DropDownClosed|
|**RadForm**|SelectionChanged, DropDownOpened, DropDownClosed|
|**RadGanttView**|Collapse task, Expand task, Edit task, Selected task|
|**RadGridView**|MoveToFirst, MoveToPrevious, MoveToNext,  MoveToLast,|
|**RadGridView** - Paging|MoveToFirst, MoveToPrevious, MoveToNext, MoveToLast|
|**RadLayoutControl**|Customize open, Item rearrange (via drag and drop, resize or context menu)|
|**RadLinearGauge**|ValueChanged|
|**RadListControl**|SelectionChanged|
|**RadMasketEditBox**|SelectionChanged|
|**RadMenu**|Click|
|**RadPageView** - ExplorerBar|Expand, Collapse, SelectionChanged| Collapse, SelectionChanged|
|**RadPageView** - Strip|SelectionChanged|
|**RadPanorama**|Reordering, Scrolling|
|**RadPdfViewer**|Load Document, Print, Print Preview|
|**RadPivotGrid**|Begin refresh, Complete refresh, Expand group header, Collapse group header, DragDrop field, Export|
|**RadPopupEditor**|Popup open close|
|**RadPropertyGrid**|Sorting, Grouping, Editing, Searching, Expanding Groups, Expanding nested definition|
|**RadRadialGauge**|ValueChanged|
|**RadRadioButton**|Checked, Unchecked|
|**RadRibbonBar**|SelectionChanged|
|**RadRichTextBox**|Open Document, Save Document|
|**RadRichTextEditor**|New, Open, Save, Print, PrintPreview|
|**RadScheduler**|ViewChanged, Import, Export, Editing, Creating, DragAndDrop, Resize, ShowDialog|
|**RadSpinEditor**|SelectionChanged|
|**RadSpreadSheet**|Open Document, Save Document, Hyperlink Click|
|**RadTimePicker**|ValueChanged|
|**RadToggleButton**|Checked,  Unchecked|
|**RadToggleSwitch**|Checked, Unchecked|
|**RadTrackBar**|SelectionChanged|
|**RadTreeView**|Select, Expand/Collapse, SelectionChanged, Edit, NodeRemoved|
|**RadWaitingBar**|StartWaiting, EndWaiting|
|**Exporting features in controls**|All export providers(including async exports) - when export operation is completed|

# See Also

* [Google Analytics Integration]({%slug winforms/analytics/google-analytics-integration%})


text:
<!doctype html>

  <title>core-animated-pages</title>

  <link href="nested-animated-pages.html" rel="import">

  <polymer-element name="nested-demo">
  <template>

    <core-animated-pages selected="{{page}}" transitions="hero-transition cross-fade">

thing 1

thing 2

      <nested-animated-pages page="{{subpage}}" on-nested-back="{{back}}"></nested-animated-pages>

    </core-animated-pages>
  </template>

  </polymer-element>

  <nested-demo></nested-demo>


text:
SlotParticleEffectPacket::SlotParticleEffectPacket()
{
	networkIdentity = -1;
	slot = -1;
	shipSlot = -1;
	active = false;
	inEditMode = false;
	translationOffset = AglVector3();
	forwardDirection = AglVector3();
	moduleType = EntityType::ShipModuleStart;
}

Packet SlotParticleEffectPacket::pack()
{
	Packet packet(static_cast<char>(PacketType::SlotParticleEffectPacket));
	packet << networkIdentity
		<< slot
		<< shipSlot
		<< active
		<< inEditMode
		<< translationOffset
		<< forwardDirection
		<< moduleType;

	return packet;
}

void SlotParticleEffectPacket::unpack( Packet& p_packet )
{
	p_packet	>> networkIdentity
				>> slot
				>> shipSlot
				>> active
				>> inEditMode
				>> translationOffset
				>> forwardDirection
				>> moduleType;
}


text:
import ReactTestUtils from 'react-dom/test-utils';

// Update the text value of an input or textarea, and simulate the React
// change event.
export default function changeTextValue(el, value) {
  ReactTestUtils.Simulate.change(el, {target: {value}});
}


text:
<?php

namespace IdeHelper\Annotator\ClassAnnotatorTask;

use ReflectionClass;
use Throwable;

/**
 * Classes that use ModelAwareTrait should automatically have used tables - via loadModel() call - annotated.
 */
class ModelAwareClassAnnotatorTask extends AbstractClassAnnotatorTask implements ClassAnnotatorTaskInterface {

	/**
	 * Deprecated: $content, use $this->content instead.
	 *
	 * @param string $path
	 * @param string $content
	 * @return bool
	 */
	public function shouldRun(string $path, string $content): bool {
		if (strpos($path, DS . 'src' . DS) === false) {
			return false;
		}
		if (preg_match('#\buse ModelAwareTrait\b#', $content)) {
			return true;
		}

		/** @var class-string|null $className */
		$className = $this->getClassName($path, $content);
		if (!$className) {
			return false;
		}

		try {
			return (new ReflectionClass($className))->hasMethod('loadModel');
		} catch (Throwable $exception) {
			return false;
		}
	}

	/**
	 * @param string $path
	 * @return bool
	 */
	public function annotate(string $path): bool {
		$models = $this->getUsedModels($this->content);

		$annotations = $this->getModelAnnotations($models, $this->content);

		return $this->annotateContent($path, $this->content, $annotations);
	}

	/**
	 * @param string $content
	 *
	 * @return array<string>
	 */
	protected function getUsedModels(string $content): array {
		preg_match_all('/\$this-\>loadModel\(\'([a-z.]+)\'/i', $content, $matches);
		if (empty($matches[1])) {
			return [];
		}

		$models = $matches[1];

		return array_unique($models);
	}

	/**
	 * @param string $path
	 * @param string $content
	 *
	 * @return string|null
	 */
	protected function getClassName(string $path, string $content): ?string {
		preg_match('#^namespace (.+)\b#m', $content, $matches);
		if (!$matches) {
			return null;
		}

		$className = pathinfo($path, PATHINFO_FILENAME);

		return $matches[1] . '\\' . $className;
	}

}


text:
/* global describe:true, it:true */

// Test setup:
import { expect, ineeda, NOOP, sinon } from '@tractor/unit-test';

// Dependencies:
import { FileStructure } from '@tractor/file-structure';
import { MochaSpecFile } from './files/mocha-spec-file';

// Under test:
import { serve } from './serve';

describe('@tractor-plugins/mocha-specs - serve:', () => {
    it('should create a new FileStructure', () => {
        let mochaSpecsFileStructure = null;
        let config = {
            mochaSpecs: {
                directory: './tractor/mocha-specs'
            }
        };
        let di = ineeda({
            call: () => NOOP,
            constant: constants => {
                mochaSpecsFileStructure = constants.mochaSpecsFileStructure;
            }
        });

        serve(config, di);

        expect(mochaSpecsFileStructure).to.be.an.instanceof(FileStructure);
    });

    it('should add the FileStructure to the DI container', () => {
        let config = {
            mochaSpecs: {
                directory: './tractor/mocha-specs'
            }
        };
        let di = ineeda({
            call: () => NOOP,
            constant: NOOP
        });

        serve(config, di);

        expect(di.constant.callCount > 0).to.equal(true);
    });

    it('should add the MochaSpecFile type to the FileStructure', () => {
        let config = {
            mochaSpecs: {
                directory: './tractor/mocha-specs'
            }
        };
        let di = ineeda({
            call: () => NOOP,
            constant: NOOP
        });

        sinon.stub(FileStructure.prototype, 'addFileType');

        serve(config, di);

        expect(FileStructure.prototype.addFileType).to.have.been.calledWith(MochaSpecFile);

        FileStructure.prototype.addFileType.restore();
    });
});


text:
<?php

namespace REBELinBLUE\Deployer\View\Presenters;

use RuntimeException;

/**
 * View presenter for calculating the runtime in a readable format.
 */
trait RuntimePresenter
{
    /**
     * Converts a number of seconds into a more human readable format.
     *
     * @throws RuntimeException
     * @return string
     */
    public function presentReadableRuntime()
    {
        if (!$this->getWrappedObject() instanceof RuntimeInterface) {
            throw new RuntimeException(
                'Model ' . get_class($this->getWrappedObject()) . ' must implement RuntimeInterface'
            );
        }

        $seconds = $this->getWrappedObject()->runtime();

        $units = [
            'hour'   => 3600,
            'minute' => 60,
            'second' => 1,
        ];

        if ($seconds === 0) {
            return $this->translator->choice('deployments.second', 0, ['time' => 0]);
        }

        // If the runtime is more than 3 hours show a simple message
        if ($seconds >= $units['hour'] * 3) {
            return $this->translator->trans('deployments.very_long_time');
        }

        $readable = '';
        foreach ($units as $name => $divisor) {
            if ($quot = (int) ($seconds / $divisor)) {
                $readable .= $this->translator->choice('deployments.' . $name, $quot, ['time' => $quot]) . ', ';
                $seconds -= $quot * $divisor;
            }
        }

        return substr($readable, 0, -2);
    }
}


text:
#region File header

#endregion

#region Using directives

using System;
using System.Linq;
using System.Text;

#endregion

namespace CG.Linq
{
    /// <summary>
    /// This class contains extension methods related to the <see cref="Sort"/>
    /// type.
    /// </summary>
    public static class SortExtensions
    {
        // *******************************************************************
        // Public methods.
        // *******************************************************************

        #region Public methods

        /// <summary>
        /// This method converts an array of <see cref="Sort"/> parameters
        /// into a sort-order SQL expression.
        /// </summary>
        /// <param name="sorts">The dictionary to use for the operation.</param>
        /// <param name="prefix">An optional column prefix, use this when the
        /// column names have a prefix in the select - like this: e.[Key],
        /// which would require a prefix of 'e'.</param>
        /// <returns>The sort order SQL expression.</returns>
        public static string ToSortExp(
            this Sort[] sorts,
            string prefix = ""
            )
        {
            // Loop and build the order by clause.
            var sb = new StringBuilder("ORDER BY ");
            for (int x = 0; x < sorts.Length; x++)
            {
                // Get the next sort.
                var sort = sorts.ElementAt(x);

                // Add the column name.
                if (string.IsNullOrEmpty(prefix))
                    sb.AppendFormat("[{0}]", sort.SortOn);
                else
                    sb.AppendFormat("{0}.[{1}]", prefix, sort.SortOn);

                // What's the sort direction?
                if (sort.SortDirection == SortDirection.Descending)
                    sb.Append(" DESC");

                // Add a comma for all but the last sort.
                if (x == sorts.Length - 1)
                    sb.Append(" ");
                else
                    sb.Append(", ");
            }

            // Return the resulting SQL snippet.
            return sb.ToString();
        }

        #endregion
    }
}


text:
package io.apiman.gateway.engine.vertxebinmemory.apis;

import io.apiman.gateway.engine.beans.Api;
import io.apiman.gateway.engine.beans.Client;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.DeliveryOptions;

/**
 * Publishes mutating events onto the event bus for listeners to consume. A UUID is sent to avoid circular
 * calls.
 *
 * @author Marc Savy {@literal <msavy@redhat.com>}
 */
public class EBRegistryProxy {
    Vertx vertx;
    DeliveryOptions options;
    String address;
    private String uuid;

    public static final String REGISTER = "register"; //$NON-NLS-1$
    public static final String UNREGISTER = "unregister"; //$NON-NLS-1$
    public static final String PUBLISH = "publish"; //$NON-NLS-1$
    public static final String RETIRE = "retire"; //$NON-NLS-1$

    public EBRegistryProxy(Vertx vertx, String address, String uuid) {
        this.vertx = vertx;
        this.address = address;
        this.uuid = uuid;
    }

    public void registerClient(Client client) {
        vertx.eventBus().publish(address, new VxClient(client, REGISTER, uuid).asJson());
    }

    public void unregisterClient(Client client) {
        vertx.eventBus().publish(address, new VxClient(client, UNREGISTER, uuid).asJson());
    }

    public void publishApi(Api api) {
        System.out.println("publishing api on " + address); //$NON-NLS-1$
        vertx.eventBus().publish(address, new VxApi(api, PUBLISH, uuid).asJson());
    }

    public void retireApi(Api api) {
        vertx.eventBus().publish(address, new VxApi(api, RETIRE, uuid).asJson());
    }
}


text:
<!DOCTYPE html>

  <title>The Mashing</title>
  <link rel="stylesheet" href="frameworks/bootstrap.min.css">
  <link rel="stylesheet" href="css/style.css">

The Mashing

Ports

          <select class="form-control" id="serial-select">
          </select>

            <button id="choose-serial-port" class="btn btn-default">Choose</button>


text:
package pg_test

import (
	"bytes"
	"database/sql/driver"
	"net"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/go-pg/pg"

	. "github.com/onsi/ginkgo"
	. "gopkg.in/check.v1"
)

func TestUnixSocket(t *testing.T) {
	opt := pgOptions()
	opt.Network = "unix"
	opt.Addr = "/var/run/postgresql/.s.PGSQL.5432"
	opt.TLSConfig = nil
	db := pg.Connect(opt)
	defer db.Close()

	_, err := db.Exec("SELECT 'test_unix_socket'")
	if err != nil {
		t.Fatal(err)
	}
}

func TestGocheck(t *testing.T) { TestingT(t) }

var _ = Suite(&DBTest{})

type DBTest struct {
	db *pg.DB
}

func (t *DBTest) SetUpTest(c *C) {
	t.db = pg.Connect(pgOptions())
}

func (t *DBTest) TearDownTest(c *C) {
	c.Assert(t.db.Close(), IsNil)
}

func (t *DBTest) TestQueryZeroRows(c *C) {
	res, err := t.db.Query(pg.Discard, "SELECT 1 WHERE 1 != 1")
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, 0)
}

func (t *DBTest) TestQueryOneErrNoRows(c *C) {
	_, err := t.db.QueryOne(pg.Discard, "SELECT 1 WHERE 1 != 1")
	c.Assert(err, Equals, pg.ErrNoRows)
}

func (t *DBTest) TestQueryOneErrMultiRows(c *C) {
	_, err := t.db.QueryOne(pg.Discard, "SELECT generate_series(0, 1)")
	c.Assert(err, Equals, pg.ErrMultiRows)
}

func (t *DBTest) TestExecOne(c *C) {
	res, err := t.db.ExecOne("SELECT 'test_exec_one'")
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, 1)
}

func (t *DBTest) TestExecOneErrNoRows(c *C) {
	_, err := t.db.ExecOne("SELECT 1 WHERE 1 != 1")
	c.Assert(err, Equals, pg.ErrNoRows)
}

func (t *DBTest) TestExecOneErrMultiRows(c *C) {
	_, err := t.db.ExecOne("SELECT generate_series(0, 1)")
	c.Assert(err, Equals, pg.ErrMultiRows)
}

func (t *DBTest) TestScan(c *C) {
	var dst int
	_, err := t.db.QueryOne(pg.Scan(&dst), "SELECT 1")
	c.Assert(err, IsNil)
	c.Assert(dst, Equals, 1)
}

func (t *DBTest) TestExec(c *C) {
	res, err := t.db.Exec("CREATE TEMP TABLE test(id serial PRIMARY KEY)")
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, -1)

	res, err = t.db.Exec("INSERT INTO test VALUES (1)")
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, 1)
}

func (t *DBTest) TestStatementExec(c *C) {
	res, err := t.db.Exec("CREATE TEMP TABLE test(id serial PRIMARY KEY)")
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, -1)

	stmt, err := t.db.Prepare("INSERT INTO test VALUES($1)")
	c.Assert(err, IsNil)
	defer stmt.Close()

	res, err = stmt.Exec(1)
	c.Assert(err, IsNil)
	c.Assert(res.RowsAffected(), Equals, 1)
}

func (t *DBTest) TestLargeWriteRead(c *C) {
	src := bytes.Repeat([]byte{0x1}, 1e6)
	var dst []byte
	_, err := t.db.QueryOne(pg.Scan(&dst), "SELECT ?", src)
	c.Assert(err, IsNil)
	c.Assert(dst, DeepEquals, src)
}

func (t *DBTest) TestIntegrityError(c *C) {
	_, err := t.db.Exec("DO $$BEGIN RAISE unique_violation USING MESSAGE='foo'; END$$;")
	c.Assert(err.(pg.Error).IntegrityViolation(), Equals, true)
}

type customStrSlice []string

func (s customStrSlice) Value() (driver.Value, error) {
	return strings.Join(s, "\n"), nil
}

func (s *customStrSlice) Scan(v interface{}) error {
	if v == nil {
		*s = nil
		return nil
	}

	b := v.([]byte)

	if len(b) == 0 {
		*s = []string{}
		return nil
	}

	*s = strings.Split(string(b), "\n")
	return nil
}

func (t *DBTest) TestScannerValueOnStruct(c *C) {
	src := customStrSlice{"foo", "bar"}
	dst := struct{ Dst customStrSlice }{}
	_, err := t.db.QueryOne(&dst, "SELECT ? AS dst", src)
	c.Assert(err, IsNil)
	c.Assert(dst.Dst, DeepEquals, src)
}

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

type badConnError string

func (e badConnError) Error() string   { return string(e) }
func (e badConnError) Timeout() bool   { return false }
func (e badConnError) Temporary() bool { return false }

type badConn struct {
	net.TCPConn

	readDelay, writeDelay time.Duration
	readErr, writeErr     error
}

var _ net.Conn = &badConn{}

func (cn *badConn) Read([]byte) (int, error) {
	if cn.readDelay != 0 {
		time.Sleep(cn.readDelay)
	}
	if cn.readErr != nil {
		return 0, cn.readErr
	}
	return 0, badConnError("bad connection")
}

func (cn *badConn) Write([]byte) (int, error) {
	if cn.writeDelay != 0 {
		time.Sleep(cn.writeDelay)
	}
	if cn.writeErr != nil {
		return 0, cn.writeErr
	}
	return 0, badConnError("bad connection")
}

func perform(n int, cbs ...func(int)) {
	var wg sync.WaitGroup
	for _, cb := range cbs {
		for i := 0; i < n; i++ {
			wg.Add(1)
			go func(cb func(int), i int) {
				defer GinkgoRecover()
				defer wg.Done()

				cb(i)
			}(cb, i)
		}
	}
	wg.Wait()
}

func eventually(fn func() error, timeout time.Duration) (err error) {
	done := make(chan struct{})
	var exit int32
	go func() {
		for atomic.LoadInt32(&exit) == 0 {
			err = fn()
			if err == nil {
				close(done)
				return
			}
			time.Sleep(timeout / 100)
		}
	}()

	select {
	case <-done:
		return nil
	case <-time.After(timeout):
		atomic.StoreInt32(&exit, 1)
		return err
	}
}


text:
package io.github.dmmn_games.earth_2045.npcs;

import io.github.dmmn_games.earth_2045.user.User;
import java.io.Serializable;

public class Enemy implements Serializable {

    private boolean alive;
    private String name;
    private int health;

    public Enemy(boolean alive, String name, int health) {
        this.alive = alive;
        this.name = name;
        this.health = health;
    }

    public void shoot(User user) {

        user.receiveDamage(10);

    }

    public void receiveDamage(int damage) {

        health = health - damage;
        if (health <= 0) {
            alive = false;

        }

    }

    public int getHealth() {
        return this.health;
    }

    public boolean isAlive() {
        return alive;
    }

    public String getName() {
        return name;
    }

    public int getDamage(){

        return 10;
    }

}


text:
<?php

require __DIR__ . '/../../bootstrap.php';

use App\Model\Entity\User;
use Kdyby\Doctrine\EntityManager;
use Markatom\RestApp\Utils\RequestBuilder;
use Markatom\RestApp\Utils\ResponseTester;
use Markatom\RestApp\Routing\AuthorizationException;
use Tester\Assert;

loadSqlDump(__DIR__ . '/../../files/dump.sql');

$em = $dic->getByType('Kdyby\Doctrine\EntityManager');

$sessionToken = logUserIn($em->getDao(User::getClassName())->find(3)); // user markatom, registered

$request = RequestBuilder::target('frontend', 1, 'users', 'update', RequestBuilder::METHOD_PUT) // specify target
    ->setParam("id",3)
    ->setHeader('X-Session-Token', $sessionToken) // set session token
    ->create(); // create request

Assert::exception(function () use ($request) {
    handleRequest($request);
}, 'Markatom\RestApp\Routing\AuthorizationException');

$sessionToken = logUserIn($em->getDao(User::getClassName())->find(1)); // user pepa, admin

//Test update user
$data = [
    "role" => [
        "slug" => "admin"
    ]
];

$request = RequestBuilder::target('frontend', 1, 'users', 'update', RequestBuilder::METHOD_PUT) // specify target
    ->setHeader('X-Session-Token', $sessionToken) // set session token
    ->setParam("id",3)
    ->setJsonPost($data)
    ->create(); // create request

$response = handleRequest($request);

ResponseTester::test($response)
    ->assertHttpStatus(ResponseTester::HTTP_OK)
    ->assertJson([
        "id"        => 3,
        "username"  => "markatom",
        "email"     => "tomas.markacz@gmail.com",
        "lastLogin" => "2014-10-16 20:34:39",
        "role"      => [
            "id"   => 1,
            "name" => "Administrátor",
            "slug" => "admin"
        ]
    ]);

loadSqlDump(__DIR__ . '/../../files/dump.sql');


text:
FreeTDS 0.91, required for connecting to MS SQLServer 2005 or 2008.

# Usage

You'll need this inside your Gemfile:

    gem 'activerecord-sqlserver-adapter'
    gem 'tiny_tds'

Example `database.yml`:

    production:
      adapter: sqlserver
      host: [host_or_ip]
      port: [port]
      database: [database]
      username: [username]
      password: [password]

# Note

Made by a Chef noob. Please use with caution.


text:
<?xml version="1.0" encoding="UTF-8"?><concept xmlns="http://www.w3.org/2004/02/skos/core#">
      <prefLabel>INFORMATION MODEL</prefLabel>
      <definition>A conceptual model of the information needed to support a business function or
         process.</definition>
   </concept>


text:
#================================================================#
# Prepare Environment

# Import system modules
import sys, string, os, win32com.client

# Create the Geoprocessor object
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")

# Set the necessary product code
gp.SetProduct("ArcInfo")

# Check out any necessary licenses
gp.CheckOutExtension("spatial")

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

#----------------------------------------#
# Script Arguments

Temp_Workspace                           = "C:\\WorkSpace\\temp"

try:
    #INPUTS
    Spatial_Units_Raster                 = sys.argv[1] # raster containing country code
    Attribute_Lookup_Table               = sys.argv[2] # dbf containing countries and all attributes of interest
    Attribute_Lookupt_Table_Join_Item    = sys.argv[3] # country code
    Attribute_Lookup_Table_Value_Item    = sys.argv[4] # the variable of interest
    Aux_Raster                           = sys.argv[5] # landcover
    Weighting_Table                      = sys.argv[6] # Table relating land cover classes to relative weights
    Weighting_Table_Join_Field           = sys.argv[7] # column with landcover codes
    Weighting_Table_Weight_Field         = sys.argv[8] # column with relative wieghts
    #OUTPUTS
    Combined_Raster                      = sys.argv[9] # output of aml, input to gp script
    Combined_Raster_Table                = sys.argv[10] # output of aml, input to gp script
    Output_Raster                        = sys.argv[11] # the dasymetric map
except:
    #INPUTS
    Spatial_Units_Raster                 = "C:\\WorkSpace\\FAO\\dasym\\units\\units_as"
    Attribute_Lookup_Table               = "C:\\WorkSpace\\FAO\\dasym\\lookups\\faocia.dbf"
    Attribute_Lookupt_Table_Join_Item    = "CODE"
    Attribute_Lookup_Table_Value_Item    = "FERT"
    Aux_Raster                           = "C:\\WorkSpace\\clipped_rusle_inputs\\as_igbp"
    Weighting_Table                      = "C:\\WorkSpace\\FAO\\dasym\\weights\\C.dbf"
    Weighting_Table_Join_Field           = "LANDCOVER"
    Weighting_Table_Weight_Field         = "WEIGHT"

    #OUTPUTS
    Combined_Raster                      = Temp_Workspace + "\\ctpc"
    Combined_Raster_Table                = Temp_Workspace + "\\ctpc.dbf"
    Output_Raster                        = "C:\\WorkSpace\\FAO\\dasym\\outputs\\as_fertC"

#--------------------------------#
# Constants
Joined_Output_Table_Name                 = "combine_weight_join"
Joined_Output_Table                      = Temp_Workspace + "\\" + Joined_Output_Table_Name + ".dbf"
Combine_Reclass                          = Temp_Workspace + "\\combine2_rcl"
Temp_Raster                              = Temp_Workspace + "\\temp_dasy"
Combined_Raster_Table_Variable_Field     = "VOI" # Should be constant

#================================================================#
# Main

#---------------------------------#
# Call the AML as the first step
#  b/c ArcGIS can't handle raster attribute tables
amlPath = os.path.dirname(sys.argv[0]) + "\\"
sCommandLine  = "arc.exe \"&run\" \"" + amlPath + "dasym_combine.aml \" "
sCommandLine += Spatial_Units_Raster + " " + Attribute_Lookup_Table + " "
sCommandLine += Attribute_Lookupt_Table_Join_Item + " " + Attribute_Lookup_Table_Value_Item + " "
sCommandLine += Aux_Raster + " "
sCommandLine += Combined_Raster + " " + Combined_Raster_Table + " " + Temp_Workspace + "'"
os.system(sCommandLine)

# gp.AddMessage(" ****** Combined Layers")
print " ****** Combined Layers"

#------------------------------------------------#
# Determine the column names based on user input

base = os.path.basename(Combined_Raster_Table)
split = base.split(".")
combinedPrefix = split[0]

base = os.path.basename(Weighting_Table)
split = base.split(".")
weightedPrefix = split[0]

base = os.path.basename(Aux_Raster)
split = base.split(".")
auxprefix = split[0]
auxprefix = auxprefix[:10]

Variable_Field = combinedPrefix + "_VOI" # "ctfc_VOI"  # Combined_Raster_Table _ VOI
Variable_Field = Variable_Field[:10]
Weight_Field   = weightedPrefix + "_" + Weighting_Table_Weight_Field # "TFC_WEIGHT"
Weight_Field   = Weight_Field[:10]
Count_Field    = combinedPrefix + "_COUNT"   # Combined_Raster_Table _ COUNT
Count_Field    = Count_Field[:10]
Value_Field    = combinedPrefix + "_VALUE"   # Combined_Raster_Table _ VALU
Value_Field    = Value_Field[:10]

Combined_Raster_Table_Join_Field  = auxprefix.upper() # "LANDCOVER2" # Name of aux raster truncated and caps

try:
    #------------------------------------------------#
    # Join Tables and create new output table
    gp.MakeTableView_management(Combined_Raster_Table, "ctable")
    gp.AddJoin_management("ctable", Combined_Raster_Table_Join_Field, Weighting_Table, Weighting_Table_Join_Field, "KEEP_ALL")
    gp.TableToTable_conversion("ctable", Temp_Workspace, Joined_Output_Table_Name)

    print " ****** Created joined table"

    #------------------------------------------------#
    # Add fields
    gp.AddField_management(Joined_Output_Table, "totalpc", "DOUBLE", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
    gp.AddField_management(Joined_Output_Table, "valuepp", "LONG", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "")
    gp.MakeTableView_management(Joined_Output_Table, "jtable")

    print " ****** Added Fields and reloaded table view"

    #------------------------------------------------#
    # Calculate Total of Variable Per Auxillary Data Class
    gp.CalculateField_management("jtable", "totalpc", "[" + Variable_Field + "] * [" + Weight_Field + "]")

    # Calculate Value of variable per pixel
    gp.CalculateField_management("jtable", "valuepp", "int( [totalpc] * 10000.0 / [" + Count_Field + "]) ")

    print " ****** Calculated New Fields"

    #------------------------------------------------#
    # Reclass by Table...
    gp.ReclassByTable_sa(Combined_Raster, "jtable", Value_Field , Value_Field, "valuepp", Temp_Raster , "DATA")

    print " ****** Reclassed Raster"

    #------------------------------------------------#
    # Scale Raster to original units
    Map_Algebra_expression = Temp_Raster + " / 10000.0"
    gp.SingleOutputMapAlgebra_sa(Map_Algebra_expression, Output_Raster)

    print " ****** Scaled raster"

except:
    print gp.GetMessages()
    sys.exit(1)


text:
Ext.define('doweown.view.Main', {
    extend: 'Ext.tab.Panel',
    xtype: 'main',
    requires: [
        'Ext.TitleBar',
	'Ext.form.Panel',
	'Ext.form.FieldSet',
	'Ext.field.Select',
        'doweown.view.History',
	'doweown.store.LibraryStore'
    ],
    config: {
        tabBarPosition: 'bottom',
        items: [
            {
                title: 'Scan',
                iconCls: 'search',
                //styleHtmlContent: false,
                scrollable: false,
		layout: 'fit',

                items: [{
			   xtype: 'navigationview',
                	   itemId: 'mainscreen',
                	   id: 'mainscreen',
			   items: [{
			     	title: 'Do We Own This?',
				padding: '5 10 10 10',
		    	     	items: [
				  { xtype: 'container', html: 'Do We Own This? is an app that you can use to see if a book is in the Harvard Library. Simply scan a book\'s barcode or enter in its ISBN number to find out!' , padding: '10 5 10 5'},
				  { xtype: 'spacer' , padding: 10},
				  { xtype: 'container', html: 'Scan a book\'s ISBN barcode:', padding: '0 10 0 10'},
			 	  { xtype: 'spacer' , padding: 10},
				  { xtype: 'button', itemId: 'scanBtn', text: 'Press Here to Scan', padding: '0 10 0 10'},
				  { xtype: 'spacer', padding: 10},
				  { xtype: 'container', html: 'Or enter an ISBN number below:', padding: '0 10 0 10'},
				  { xtype: 'spacer', padding: 10 },
				  { xtype: 'textfield', itemId: 'isbnField', label: 'ISBN:', maxLength: 13, padding: '0 10 5 10'}
				]
			    }]
		  }]

            },
            {
		itemId: 'hitlist',
                title: 'History',
                iconCls: 'bookmarks',
		//styleHtmlContent: false,
		layout: 'fit',

               items: [{
			xtype: 'navigationview',
			itemId: 'historynav',
			id: 'historynav',
			title: 'History',
			items: [
				{ xtype: 'history'}
			]

               }]
            },
	    {
		itemId: 'prefs',
		title: 'Prefs',
		iconCls: 'settings',
		layout: 'fit',

		items: [{
			xtype: 'formpanel',
			itemId: 'prefsform',
			items: [
			  { xtype: 'titlebar', title: 'Settings', docked: 'top' },
		   	  { xtype: 'fieldset',
			    title: 'Enter your email settings here.',
	            	    items: [
				{xtype: 'textfield', name: 'firstname', label: 'First
Name'},
				{xtype: 'textfield', name: 'lastname', label: 'Last
Name'},
				{xtype: 'textfield', name: 'email', label: 'E-mail'},
				{xtype: 'selectfield', name: 'library', label: 'Library', store: 'LibraryStore', displayField: 'name', valueField: 'libcode'},
                                {xtype: 'textfield', name: 'school', label: 'School /
Unit'},
                                {xtype: 'selectfield', name: 'affiliation', label: 'Affiliation',
				 options: [
				   {text: 'Harvard Faculty', value: 'Harvard Faculty' },
				   {text: 'Harvard Undergraduate Student', value: 'Harvard Undergraduate Student' },
				   {text: 'Harvard Graduate Student', value: 'Harvard Graduate Student' },
                                   {text: 'Harvard Staff', value: 'Harvard Staff' },
				   {text: 'Harvard Alumnus/a', value: 'Harvard Alumnus/a' },
                                   {text: 'Harvard Other', value: 'Harvard Other' },
                                   {text: 'Other Institution Faculty', value: 'Other Institution Faculty' },
                                   {text: 'Other Institution Undergraduate Student', value: 'Other Institution Undergraduate Student' },
				   {text: 'Other Institution Graduate Student', value: 'Other Institution Graduate Student' },
                                   {text: 'High School Student', value: 'High School Student' },
				   {text: 'Independent Researcher', value: 'Independent Researcher' },
                                   {text: 'Other', value: 'Other' }
				 ]
				}
			   ]
		   	  },
			  { xtype: 'toolbar',
			    layout: { pack: 'center' },
			    ui: 'plain',
			    items: [
				{ xtype: 'spacer'},
				{xtype: 'button', text: 'Reset', ui: 'decline', itemId: 'resetBtn' },
				{ xtype: 'spacer'},
				{xtype: 'button', text: 'Save', ui: 'confirm', itemId: 'saveBtn' },
				{ xtype: 'spacer'}
			    ]
			  }
			]
		}]
	     },
	     {
		itemId: 'about',
                title: 'About',
                iconCls: 'info',
                layout: 'fit',
		scrollable: true,

		items: [
			{ xtype: 'titlebar', title: 'About', docked: 'top' },
			{ xtype: 'spacer'},
			{ xtype: 'panel', styleHtmlContent: true, scrollable: true,
			  html: '
Do we own this?
' +
				'A mobile app for library collection development' +
                      		'
Version: ' + doweown.config.Config.getVersion() +
				'
Project Team:
' +
				'Thomas Ma, Bibliographic Services Manager, Information and Technical Services
' +
				'Chip Goines, Digital Library Software Engineer, Library Technology Services
' +
				'Donna Viscuglia, Senior Cataloger, ITS
' +
				'Mariko Honshuku, Librarian for Japanese Law, Law Library
' +
                      		'
Produced by: The Harvard Library Lab, ' +
				   'https://osc.hul.harvard.edu/liblab
' +
				'Contact us:
 ' +
				'General Questions | ' +
				'Technical Support

' +
				'License: GNU GPL v3.0
'

			 }
		]

	     }
        ]
    }
});


text:
#pragma once

#include "ui_OgreScriptEditor.h"
#include "OgreAssetEditorModuleApi.h"
#include "AssetFwd.h"

#include <QWidget>

class QPushButton;
class QLineEdit;
class QTextEdit;

//class PropertyTableWidget;

/// Text editing tool for OGRE material and particle scripts.
class ASSET_EDITOR_MODULE_API OgreScriptEditor : public QWidget, public Ui::OgreScriptEditor
{
    Q_OBJECT

public:
    OgreScriptEditor(const AssetPtr &scriptAsset, Framework *fw, QWidget *parent = 0);
    ~OgreScriptEditor();

    void SetScriptAsset(const AssetPtr &scriptAsset);

public slots:
    void Open();

private:
    /// Creates the text edit field for raw editing.
    void CreateTextEdit();

    /// Creates the property table for material property editing.
    /// @todo Regression. Re-implement or remove.
//    void CreatePropertyEditor();

    Framework *framework;
    AssetWeakPtr asset;
    QTextEdit *textEdit; ///< Text edit field used in raw edit mode.
//    PropertyTableWidget *propertyTable; ///< Table widget for editing material properties.

private slots:
    /// Saves changes made to the asset.
    void Save();

    /// Saves as new.
    void SaveAs();

    /// Validates the script name.
    /** @param name Name. */
    void ValidateScriptName(const QString &name);

    /// Validates the property's new value.
    /** @param row Row of the cell.
        @param column Column of the cell. */
    /// @todo Regression. Re-implement or remove.
//    void PropertyChanged(int row, int column);

    void OnAssetTransferSucceeded(AssetPtr asset);
    void OnAssetTransferFailed(IAssetTransfer *transfer, QString reason);
};


text:
package com.warouss.webservice.client.gen;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 *
 */
@WebService(name = "PersonService", targetNamespace = "http://www.person.com/schema")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface PersonService {

    /**
     *
     * @param arg0
     * @return
     *     returns boolean
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://www.person.com/schema/PersonService/addPersonRequest", output = "http://www.person.com/schema/PersonService/addPersonResponse")
    public boolean addPerson(
        @WebParam(name = "arg0", partName = "arg0")
        Person arg0);

    /**
     *
     * @param arg0
     * @return
     *     returns boolean
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://www.person.com/schema/PersonService/deletePersonRequest", output = "http://www.person.com/schema/PersonService/deletePersonResponse")
    public boolean deletePerson(
        @WebParam(name = "arg0", partName = "arg0")
        Person arg0);

    /**
     *
     * @param arg0
     * @return
     *     returns com.warouss.webservice.client.gen.Person
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://www.person.com/schema/PersonService/getPersonRequest", output = "http://www.person.com/schema/PersonService/getPersonResponse")
    public Person getPerson(
        @WebParam(name = "arg0", partName = "arg0")
        long arg0);

    /**
     *
     * @return
     *     returns com.warouss.webservice.client.gen.PersonArray
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://www.person.com/schema/PersonService/getAllPersonsRequest", output = "http://www.person.com/schema/PersonService/getAllPersonsResponse")
    public PersonArray getAllPersons();

}


text:
package com.javalearning.elasticsearchtest;

import com.google.common.collect.Lists;
import com.javalearning.elasticsearchexample.model.Book;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by renqun.yuan on 2015/11/1.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/elasticsearch-config.xml")
public class ElasticSearchTemplateTest {
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Before
    public void before() {

    }

    @Test
    public void saveTest() {
        Book book = new Book();
        book.setId("56");
        book.setAuthors(Lists.newArrayList("ray", "yrq"));
        book.setName("el_template33");
        book.setPrice((double) 10);
        book.setPublishDate(new Date());
        IndexQueryBuilder indexQueryBuilder = new IndexQueryBuilder();
        indexQueryBuilder.withObject(book).withId(book.getId());
        String documentId = elasticsearchTemplate.index(indexQueryBuilder.build());
        System.out.println(documentId);
    }

    @Test
    public void queryTest() {
        CriteriaQuery criteriaQuery = new CriteriaQuery(null);
        Criteria criteria = Criteria.where("id").is("1");
        criteriaQuery.addCriteria(criteria);
        Book book = elasticsearchTemplate.queryForObject(criteriaQuery, Book.class);
        System.out.println(book);
    }
}


text:
//
//  XianShiAnimalViewController.m
//  CodeDemos
//
//  Created by qddios2 on 17/3/27.
//  Copyright © 2017年 lvguifeng. All rights reserved.
//

#import "XianShiAnimalViewController.h"

@interface XianShiAnimalViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSArray *images;

@end

@implementation XianShiAnimalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    self.images = @[[UIImage imageNamed:@"1.jpeg"],
                    [UIImage imageNamed:@"2.jpeg"],
                    [UIImage imageNamed:@"3.jpeg"],
                    [UIImage imageNamed:@"sufei.jpeg"]];
    self.imageView.image = self.images.lastObject;

}
- (IBAction)switchImageAction:(id)sender {

    [UIView transitionWithView:self.imageView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        UIImage *currentImage = self.imageView.image;
        NSUInteger index = [self.images indexOfObject:currentImage];
        index = (index + 1) % self.images.count;
        self.imageView.image = self.images[index];
    } completion:^(BOOL finished) {

    }];
}
- (IBAction)performTransionAction:(id)sender
{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0.6);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *coverImage = UIGraphicsGetImageFromCurrentImageContext();
    UIView *converView  = [[UIImageView alloc] initWithImage:coverImage];
    converView.frame = self.view.bounds;
    [self.view addSubview:converView];

    CGFloat red = arc4random() / (CGFloat)INT_MAX;
    CGFloat blue = arc4random() / (CGFloat)INT_MAX;
    CGFloat gree = arc4random() / (CGFloat)INT_MAX;
    self.view.backgroundColor = [UIColor colorWithRed:red green:gree blue:blue alpha:1];
    [UIView animateWithDuration:1.0 animations:^{
        CGAffineTransform transform = CGAffineTransformMakeScale(0.5, 0.5);
        transform = CGAffineTransformRotate(transform, M_PI_2);
        converView.transform = transform;
        converView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [converView removeFromSuperview];
        [self switchImageAction:nil];
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
"use strict";
require("typings-test");
var plugins = {
    gulp: require("gulp"),
    gulpFunction: require("gulp-function"),
    gulpTypings: require("../dist/index.js")
};
describe("gulp-typings", function () {
    it("should install typings", function (done) {
        this.timeout(10000);
        plugins.gulp.src("./test/typings.json")
            .pipe(plugins.gulpTypings())
            .pipe(plugins.gulpFunction(function () {
            done();
        }, "atEnd"));
    });
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLFFBQU8sY0FBYyxDQUFDLENBQUE7QUFDdEIsSUFBSSxPQUFPLEdBQUc7SUFDVixJQUFJLEVBQUUsT0FBTyxDQUFDLE1BQU0sQ0FBQztJQUNyQixZQUFZLEVBQUUsT0FBTyxDQUFDLGVBQWUsQ0FBQztJQUN0QyxXQUFXLEVBQUUsT0FBTyxDQUFDLGtCQUFrQixDQUFDO0NBQzNDLENBQUM7QUFFRixRQUFRLENBQUMsY0FBYyxFQUFDO0lBQ3BCLEVBQUUsQ0FBQyx3QkFBd0IsRUFBQyxVQUFTLElBQUk7UUFDckMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxLQUFLLENBQUMsQ0FBQztRQUNwQixPQUFPLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxxQkFBcUIsQ0FBQzthQUNsQyxJQUFJLENBQUMsT0FBTyxDQUFDLFdBQVcsRUFBRSxDQUFDO2FBQzNCLElBQUksQ0FBQyxPQUFPLENBQUMsWUFBWSxDQUFDO1lBQ3ZCLElBQUksRUFBRSxDQUFDO1FBQ1gsQ0FBQyxFQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUE7SUFDbkIsQ0FBQyxDQUFDLENBQUE7QUFDTixDQUFDLENBQUMsQ0FBQyJ9


text:
using System;
using ServiceStack.Redis;
using ServiceStack.Text;
using ServiceStack.Logging;
using ServiceStack.Discovery.Redis;
using System.Diagnostics;

namespace ServiceStack.SimpleCloudControl
{
    /// <summary>
    /// Provides a simple wrapper around standard PubSub channel that will allow SCC plug-ins to communicate without expense of a bunch of seperate PubSubs
    /// Requires RedisServiceDiscoveryFeature to be registered being to this plugin, all SCC plug-ins should be loaded after.
    /// </summary>
    public class SimpleCloudControlFeature : IPlugin, IDisposable
    {
        public const string RedisServiceDiscoveryMetaKey = "SimpleCloudControl";
        public string RedisPrefix { get; set; } = "scc";
        public RedisServiceDiscoveryFeature RSDFeature { get; private set; }
        public Guid NodeId
        {
            get { return RSDFeature.NodeId; }
        }
        private readonly ILog Log = LogManager.GetLogger(typeof(SimpleCloudControlFeature));

        protected IRedisPubSubServer PubSubLink { get; set; }

        public void Register(IAppHost appHost)
        {
            RSDFeature = appHost.GetPlugin<RedisServiceDiscoveryFeature>();
            if (RSDFeature == null)
            {
                throw new Exception("RedisServiceDiscoveryFeature registration is required for SimpleCloudControl to function.");
            }
            RSDFeature.Config.Meta[RedisServiceDiscoveryMetaKey] = RedisPrefix;
            PubSubLink = new RedisPubSubServer(appHost.TryResolve<IRedisClientsManager>(), RedisPrefix);
            PubSubLink.OnMessage = OnMessage;
            PubSubLink.OnError = OnError;
            PubSubLink.Start();
            appHost.OnDisposeCallbacks.Add(a => Dispose());
        }

        private void OnError(Exception e)
        {
            Log.Error("SimpleCloudControl PubSub Exception", e);
        }

        public void SendMessage(object dto)
        {
            if (dto == null)
                return;
            HostContext.AppHost.GetRedisClient().PublishMessage(RedisPrefix, "{0}:{1}".Fmt(dto.GetType().FullName, dto.ToJson()));
            Debug.Print("SCC SendMessage {0}".Fmt(dto.GetType().FullName));

        }

        private void OnMessage(string channel, string msg)
        {
            if (!msg.IsEmpty() && msg.Contains(":"))
            {
                var data = msg.SplitOnFirst(":");
                var type = Type.GetType(data[0]);
                Debug.Print("SCC OnMessage {0}".Fmt(type.FullName));
                HostContext.AppHost.ExecuteService(JsonSerializer.DeserializeFromString(data[1], type)); //just push along like any other message
            }
        }

        public void Dispose()
        {
            PubSubLink.Dispose();
        }
    }
}