text:
package as;

import org.apache.flex.compiler.clients.MXMLC;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.utils.*;
import utils.FlashplayerSecurityHandler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * Base class for AS feature tests which compile AS code with MXMLC and run it in the standalone Flash Player.
 * Copied and modified from MXMLFeatureTestsBase.java
 */
public class ASFeatureTestsBase
{
	private static final String NAMESPACE_2009 = "http://ns.adobe.com/mxml/2009";

	protected File generateTempFile(String source)
	{
        // Write the MXML into a temp file.
        ITestAdapter testAdapter = TestAdapterFactory.getTestAdapter();
        String tempDir = testAdapter.getTempDir();
        File tempASFile = null;
        try
        {
            tempASFile = File.createTempFile(getClass().getSimpleName(), ".as", new File(tempDir));
            tempASFile.deleteOnExit();

            BufferedWriter out = new BufferedWriter(new FileWriter(tempASFile));
            String className = tempASFile.getName();
            // chop off .as
            className = className.substring(0, className.length() - 3);

            source = source.replaceAll("%0", className);
            out.write(source);
            out.close();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
            fail("Error generating test code");
        }
        return tempASFile;
	}

	protected String compile(File tempASFile, String source, boolean withFramework, boolean withRPC, boolean withSpark, String[] otherOptions, boolean checkExitCode)
	{
        System.out.println("Generating test:");

        ITestAdapter testAdapter = TestAdapterFactory.getTestAdapter();
        // Build the list of SWCs to compile against on the library path.
        List<String> swcs = new ArrayList<String>();
        if (withFramework)
        {
            swcs.add(testAdapter.getFlexArtifact("framework").getPath());
            swcs.add(testAdapter.getFlexArtifactResourceBundle("framework").getPath());
        }
        if (withRPC)
        {
            swcs.add(testAdapter.getFlexArtifact("rpc").getPath());
            swcs.add(testAdapter.getFlexArtifactResourceBundle("rpc").getPath());
        }
        if (withSpark)
        {
            swcs.add(testAdapter.getFlexArtifact("spark").getPath());
            swcs.add(testAdapter.getFlexArtifactResourceBundle("spark").getPath());
        }

        List<String> args = new ArrayList<String>();
        args.add("-external-library-path=" + testAdapter.getPlayerglobal().getPath());
        if(swcs.size() > 0) {
            String libraryPath = "-library-path=" + StringUtils.join(swcs.toArray(new String[swcs.size()]), ",");
            args.add(libraryPath);
        }
        if (withFramework || withRPC || withSpark)
            args.add("-namespace=" + NAMESPACE_2009 + "," + testAdapter.getFlexManifestPath("mxml-2009"));
        if (otherOptions != null)
        {
            Collections.addAll(args, otherOptions);
        }
        args.add(tempASFile.getAbsolutePath());

        // Use MXMLC to compile the MXML file against playerglobal.swc and possibly other SWCs.
        MXMLC mxmlc = new MXMLC();
        StringBuffer cmdLine = new StringBuffer();
        for(String arg : args) {
            cmdLine.append(arg).append(" ");
        }

        System.out.println("Compiling test:\n" + cmdLine.toString());
        int exitCode = mxmlc.mainNoExit(args.toArray(new String[args.size()]));

        // Check that there were no compilation problems.
        List<ICompilerProblem> problems = mxmlc.getProblems().getProblems();
        StringBuilder sb = new StringBuilder(checkExitCode ? "Unexpected compilation problems:\n" : "");
        for (ICompilerProblem problem : problems)
        {
            sb.append(problem.toString());
            sb.append('\n');
        }

        System.out.println("After compile:\n" + sb.toString());
        if (checkExitCode)
            assertThat(sb.toString(), exitCode, is(0));
        return sb.toString();

	}

    protected void compileAndExpectErrors(String source, boolean withFramework, boolean withRPC, boolean withSpark, String[] otherOptions, String errors)
    {
        File tempASFile = generateTempFile(source);
        String results = compile(tempASFile, source, withFramework, withRPC, withSpark, otherOptions, false);
        assertThat(results, is(errors));
    }
	protected void compileAndRun(String source, boolean withFramework, boolean withRPC, boolean withSpark, String[] otherOptions)
	{
	    int exitCode = 0;
	    File tempASFile = generateTempFile(source);
	    compile(tempASFile, source, withFramework, withRPC, withSpark, otherOptions, true);
        ITestAdapter testAdapter = TestAdapterFactory.getTestAdapter();
		// Check the existence of the flashplayer executable
		File playerExecutable = testAdapter.getFlashplayerDebugger();
		if(!playerExecutable.isFile() || !playerExecutable.exists()) {
			fail("The flashplayer executable " + testAdapter.getFlashplayerDebugger().getPath() + " doesn't exist.");
		}

		// Run the SWF in the standalone player amd wait until the SWF calls System.exit().
		String swf = FilenameNormalization.normalize(tempASFile.getAbsolutePath());
		swf = swf.replace(".as", ".swf");
		String[] runArgs = new String[] { testAdapter.getFlashplayerDebugger().getPath(), swf };
		try
		{
			System.out.println("Executing test:\n" + Arrays.toString(runArgs));

			// TODO: Hack to add the directory containing the temp swf to the flashplayer trust.
			new FlashplayerSecurityHandler().trustFile(tempASFile.getParentFile());

			exitCode = executeCommandWithTimeout(runArgs, 20);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			// If we just print the stacktrace the exitCode is still 0 and the test will pass.
			fail("Got exception");
		}

	    // Check that the runtime exit code was 0, meaning that no asserts failed.
		assertThat(exitCode, is(0));
	}

	protected void compileAndRun(String source)
	{
		compileAndRun(source, false, false, false, null);
	}

	public static int executeCommandWithTimeout(String[] args, long timeoutInSeconds) throws Exception {
		ExecutorService service = Executors.newSingleThreadExecutor();
		Process process = Runtime.getRuntime().exec(args);
		try {
			Callable<Integer> call = new CallableProcess(process);
			Future<Integer> future = service.submit(call);
			return future.get(timeoutInSeconds, TimeUnit.SECONDS);
		} catch (ExecutionException e) {
			throw new Exception("Process failed to execute", e);
		} catch (TimeoutException e) {
			process.destroy();
			throw new Exception("Process timed out", e);
		} finally {
			service.shutdown();
		}
	}

	private static class CallableProcess implements Callable<Integer> {
		private Process p;

		public CallableProcess(Process process) {
			p = process;
		}

		public Integer call() throws Exception {
			return p.waitFor();
		}
	}

	/**
	 * Combines various code snippets to make a complete one-file MXML Sprite-based application.
	 */
    protected String getAS(String[] imports, String[] declarations, String[] testCode, String[] extraCode)
    {
        String[] template = new String[]
        {
            "package {",
            "import flash.display.Sprite;",
            "import flash.events.Event;",
            "import flash.system.System;",
            "%1",
            "public class %0 extends flash.display.Sprite",
            "{",
            "    public function %0()",
            "    {",
            "        loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);",
            "    }",
            "    %2",
            "    private function initHandler(e:flash.events.Event):void",
            "    {",
            "        %3",
            "        System.exit(0);",
            "    }",
            "    private function assertEqual(message:String, actualValue:*, expectedValue:*):void",
            "    {",
            "        if (actualValue !== expectedValue)",
            "        {",
            "            trace(message, actualValue, expectedValue);",
            "            System.exit(1);",
            "        }",
            "    }",
            "}",
            "}",
            "%4"
        };
        String source = StringUtils.join(template, "\n");
        source = source.replace("%1", StringUtils.join(imports, "\n"));
        source = source.replace("%2", StringUtils.join(declarations, "\n        "));
        source = source.replace("%3", StringUtils.join(testCode, "\n"));
        source = source.replace("%4", StringUtils.join(extraCode, "\n"));
        return source;
    }

}


text:
package com.pragbits.bitbucketserver;

public class PluginMetadata {

    public static String getPluginKey() {
        return "com.pragbits.stash.stash2slack";
    }

    public static String getCompleteModuleKey(String moduleKey) {
        return getPluginKey() + ":" + moduleKey;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.qf.teach.project.zhihudaily.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.qf.teach.project.zhihudaily.R;
import com.qf.teach.project.zhihudaily.c.API;
import com.qf.teach.project.zhihudaily.entity.StoryInfo;
import com.qf.teach.project.zhihudaily.entity.ThemeStoryInfo;

public class ContentActivity extends Activity implements Listener<JSONObject>, OnClickListener {
	private static final String TAG = "ContentActivity";

	// ¿Ø¼þÏà¹Ø
	private Button btnShare;
	private WebView webContent;

	// ²ÎÊýÏà¹Ø
	private long id;
	private String tag;

	// ÍøÂçÏà¹Ø
	private RequestQueue mQueue;

	// Êý¾ÝÏà¹Ø
	private StoryInfo storyInfo;
	private ThemeStoryInfo themeStoryInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_content);

		initParams();
		initView();
		initData();
		initShareSDK();
	}

	/**
	 * ³õ'»¯²ÎÊý
	 */
	private void initParams() {
		id = getIntent().getLongExtra("id", 0);
		tag = getIntent().getStringExtra("tag");

		Log.d(TAG, String.valueOf(id));
	}

	private void initView() {
		btnShare = (Button) findViewById(R.id.btn_share);
		btnShare.setOnClickListener(this);

		webContent = (WebView) findViewById(R.id.web_content);
	}

	private void initData() {
		mQueue = Volley.newRequestQueue(getApplicationContext());
		mQueue.add(new JsonObjectRequest(Method.GET, String.format(API.getStory(), id), null, this, null));
	}

	/**
	 * ³õ'»¯ShareSDK
	 */
	private void initShareSDK() {
		ShareSDK.initSDK(this);
	}

	/* -------------------- ÍøÂçÇëÇó -------------------- */

	@Override
	public void onResponse(JSONObject response) {
		try {
			// Ö÷ÌâÄÚÈݽâÎö
			if (response.has("theme_name")) {
				themeStoryInfo = new ThemeStoryInfo();
				themeStoryInfo.setBody(response.getString("body"));
				themeStoryInfo.setEditor_avatar(response.getString("editor_avatar"));
				themeStoryInfo.setEditor_id(response.getLong("editor_id"));
				themeStoryInfo.setEditor_name(response.getString("editor_name"));
				themeStoryInfo.setGa_prefix(response.getString("ga_prefix"));
				themeStoryInfo.setId(response.getLong("id"));
				themeStoryInfo.setShare_url(response.getString("share_url"));
				themeStoryInfo.setTheme_id(response.getLong("theme_id"));
				themeStoryInfo.setTheme_image(response.getString("theme_image"));
				themeStoryInfo.setTheme_name(response.getString("theme_name"));
				themeStoryInfo.setTitle(response.getString("title"));
				themeStoryInfo.setType(response.getInt("type"));

				// JS
				JSONArray arrayJs = response.getJSONArray("js");
				if (arrayJs != null && arrayJs.length() > 0) {
					String[] js = new String[arrayJs.length()];
					for (int i = 0; i < arrayJs.length(); i++) {
						js[i] = arrayJs.getString(i);
					}
					themeStoryInfo.setJs(js);
				}

				// CSS
				JSONArray arrayCss = response.getJSONArray("css");
				if (arrayCss != null && arrayCss.length() > 0) {
					String[] css = new String[arrayCss.length()];
					for (int i = 0; i < arrayCss.length(); i++) {
						css[i] = arrayCss.getString(i);
					}
					themeStoryInfo.setCss(css);
				}

				// ¼ÓÔØHTML
				String body = null;
				if (themeStoryInfo.getCss() != null && themeStoryInfo.getCss().length > 0) {
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < themeStoryInfo.getCss().length; i++) {
						sb.append("<link rel=\"stylesheet\" href=\"");
						sb.append(themeStoryInfo.getCss()[i]);
						sb.append("\">");
					}
					body = String.format("%s%s", sb.toString(), themeStoryInfo.getBody());
				} else {
					body = themeStoryInfo.getBody();
				}

				webContent.loadDataWithBaseURL(null, body, "text/html", "UTF-8", null);
			} else {
				// Ê×Ò³ÄÚÈݽâÎö
				storyInfo = new StoryInfo();
				storyInfo.setBody(response.getString("body"));
				storyInfo.setGa_prefix(response.getString("ga_prefix"));
				storyInfo.setId(response.getLong("id"));
				storyInfo.setImage(response.getString("image"));
				storyInfo.setImage_source(response.getString("image_source"));
				storyInfo.setShare_url(response.getString("share_url"));
				storyInfo.setTitle(response.getString("title"));
				storyInfo.setType(response.getInt("type"));

				// JS
				JSONArray arrayJs = response.getJSONArray("js");
				if (arrayJs != null && arrayJs.length() > 0) {
					String[] js = new String[arrayJs.length()];
					for (int i = 0; i < arrayJs.length(); i++) {
						js[i] = arrayJs.getString(i);
					}
					storyInfo.setJs(js);
				}

				// CSS
				JSONArray arrayCss = response.getJSONArray("css");
				if (arrayCss != null && arrayCss.length() > 0) {
					String[] css = new String[arrayCss.length()];
					for (int i = 0; i < arrayCss.length(); i++) {
						css[i] = arrayCss.getString(i);
					}
					storyInfo.setCss(css);
				}

				// ¼ÓÔØHTML
				String body = null;
				if (storyInfo.getCss() != null && storyInfo.getCss().length > 0) {
					StringBuffer sb = new StringBuffer();
					for (int i = 0; i < storyInfo.getCss().length; i++) {
						sb.append("<link rel=\"stylesheet\" href=\"");
						sb.append(storyInfo.getCss()[i]);
						sb.append("\">");
					}
					body = String.format("%s%s", sb.toString(), storyInfo.getBody());
				} else {
					body = storyInfo.getBody();
				}

				// ÉèÖö¥²¿Í¼Æ¬
				if (storyInfo.getImage() != null && storyInfo.getImage().length() > 0) {
					body = body.replace("

", "

");
				}

				// webContent.getSettings().setJavaScriptEnabled(true);
				// webContent.loadUrl("file:///android_asset/index.html");

				webContent.loadDataWithBaseURL(null, body, "text/html", "UTF-8", null);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/* -------------------- ÍøÂçÇëÇó -------------------- */

	/* -------------------- µã»÷'þ -------------------- */

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_share:
			OnekeyShare oks = new OnekeyShare();
			// ¹Ø±ÕssoÊÚȨ
			oks.disableSSOWhenAuthorize();

			// ·ÖÏíʱNotificationµÄͼ±êºÍÎÄ×Ö
			oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
			// title±êÌ⣬ӡÏó±Ê¼Ç¡¢ÓÊÏä¡¢ÐÅÏ¢¡¢Î¢ÐÅ¡¢ÈËÈËÍøºÍQQ¿Õ¼äʹÓÃ
			oks.setTitle(getString(R.string.share));
			// titleUrlÊDZêÌâµÄÍøÂçÁ´½Ó£¬½öÔÚÈËÈËÍøºÍQQ¿Õ¼äʹÓÃ
			oks.setTitleUrl("http://www.funtl.com");

			if (tag.equals("main")) {
				oks.setText(storyInfo.getTitle() + ":" + storyInfo.getShare_url());
			} else if (tag.equals("content")) {
				oks.setText(themeStoryInfo.getTitle() + ":" + themeStoryInfo.getShare_url());
			}

			// imagePathÊÇͼƬµÄ±¾µØ·¾¶£¬Linked-InÒÔÍâµÄƽ̨¶¼Ö§³Ö´Ë²ÎÊý
			oks.setImagePath("/sdcard/test.jpg");// È·±£SDcardÏÂÃæ´æÔÚ´ËÕÅͼƬ
			// url½öÔÚ΢ÐÅ£¨°üÀ¨ºÃÓѺÍÅóÓÑȦ£©ÖÐʹÓÃ
			oks.setUrl("http://www.funtl.com");
			// commentÊÇÎÒ¶ÔÕâÌõ·ÖÏíµÄÆÀÂÛ£¬½öÔÚÈËÈËÍøºÍQQ¿Õ¼äʹÓÃ
//			oks.setComment("ÎÒÊDzâÊÔÆÀÂÛÎı¾");
			// siteÊÇ·ÖÏí´ËÄÚÈݵÄÍøÕ¾Ãû³Æ£¬½öÔÚQQ¿Õ¼äʹÓÃ
			oks.setSite(getString(R.string.app_name));
			// siteUrlÊÇ·ÖÏí´ËÄÚÈݵÄÍøÕ¾µØÖ·£¬½öÔÚQQ¿Õ¼äʹÓÃ
			oks.setSiteUrl("http://www.funtl.com");

			// Æô¶¯·ÖÏíGUI
			oks.show(this);
			break;
		default:
			break;
		}
	}

	/* -------------------- µã»÷'þ -------------------- */

}


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

<TITLE>
Uses of Class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler
</TITLE>

<META NAME="date" CONTENT="2014-05-22">

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

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

Uses of CbSettingsHandler in ca.cumulonimbus.pressurenetsdk

Methods in ca.cumulonimbus.pressurenetsdk that return CbSettingsHandler

 CbSettingsHandler
CbSettingsHandler.getSettings()

 CbSettingsHandler
CbDataSender.getSettings()

Methods in ca.cumulonimbus.pressurenetsdk with parameters of type CbSettingsHandler

 void
CbDataSender.setSettings(CbSettingsHandler settings,
            CbLocationManager locationManager,
            Messenger notifyMessenger,
            boolean fromUser)

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


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

<title>CalaisAPI</title>
<meta name="date" content="2016-12-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bounswe.digest.semantic

Class CalaisAPI

java.lang.Object

org.bounswe.digest.semantic.CalaisAPI

public class CalaisAPI
extends java.lang.Object

CalaisAPI

Field Summary

Fields

Modifier and Type
Field and Description

private static java.lang.String
CALAIS_URL

org.apache.commons.httpclient.HttpClient
client

java.lang.String
input

java.lang.String
output

static java.lang.String
uniqueAccessKey

Constructor Summary

Constructors

Constructor and Description

CalaisAPI()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

private org.apache.commons.httpclient.methods.PostMethod
createPostMethod()

private void
doRequest(java.lang.String query,
         org.apache.commons.httpclient.methods.PostMethod method)

org.json.JSONObject
extractTags(java.lang.String queryText)

Extracts entities with respect to given text.

java.lang.String
getOutput()

private void
postFile(java.lang.String query,
        org.apache.commons.httpclient.methods.PostMethod method)

void
run()

private void
saveResponse(java.lang.String query,
            org.apache.commons.httpclient.methods.PostMethod method)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

CALAIS_URL

private static final java.lang.String CALAIS_URL

See Also:

Constant Field Values

uniqueAccessKey

public static final java.lang.String uniqueAccessKey

See Also:

Constant Field Values

input

public java.lang.String input

output

public java.lang.String output

client

public org.apache.commons.httpclient.HttpClient client

Constructor Detail

CalaisAPI

public CalaisAPI()

Method Detail

createPostMethod

private org.apache.commons.httpclient.methods.PostMethod createPostMethod()

run

public void run()

doRequest

private void doRequest(java.lang.String query,
                       org.apache.commons.httpclient.methods.PostMethod method)

saveResponse

private void saveResponse(java.lang.String query,
                          org.apache.commons.httpclient.methods.PostMethod method)
                   throws java.io.IOException

Throws:

java.io.IOException

getOutput

public java.lang.String getOutput()

postFile

private void postFile(java.lang.String query,
                      org.apache.commons.httpclient.methods.PostMethod method)
               throws java.io.IOException

Throws:

java.io.IOException

extractTags

public org.json.JSONObject extractTags(java.lang.String queryText)

Extracts entities with respect to given text.

Parameters:

queryText -

Returns:

JSONArray : JSONObject : JSONArray | {"label":["labels"]}

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.Security.Claims;
using ASPNETCoreIdentitySample.Entities.Identity;
using Microsoft.AspNetCore.Identity;

namespace ASPNETCoreIdentitySample.Services.Contracts.Identity;

public interface IApplicationUserStore : IDisposable
{
    #region BaseClass

    /// <summary>
    /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called.
    /// </summary>
    /// <value>
    /// True if changes should be automatically persisted, otherwise false.
    /// </value>
    bool AutoSaveChanges { get; set; }

    /// <summary>
    /// Creates the specified <paramref name="user"/> in the user store.
    /// </summary>
    /// <param name="user">The user to create.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the creation operation.</returns>
    Task<IdentityResult> CreateAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Updates the specified <paramref name="user"/> in the user store.
    /// </summary>
    /// <param name="user">The user to update.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns>
    Task<IdentityResult> UpdateAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Deletes the specified <paramref name="user"/> from the user store.
    /// </summary>
    /// <param name="user">The user to delete.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns>
    Task<IdentityResult> DeleteAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Finds and returns a user, if any, who has the specified <paramref name="userId"/>.
    /// </summary>
    /// <param name="userId">The user ID to search for.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userId"/> if it exists.
    /// </returns>
    Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken = default);

    /// <summary>
    /// Finds and returns a user, if any, who has the specified normalized user name.
    /// </summary>
    /// <param name="normalizedUserName">The normalized user name to search for.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="normalizedUserName"/> if it exists.
    /// </returns>
    Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default);

    /// <summary>
    /// A navigation property for the users the store contains.
    /// </summary>
    IQueryable<User> Users { get; }

    /// <summary>
    /// Return a role with the normalized name if it exists.
    /// </summary>
    /// <param name="normalizedRoleName">The normalized role name.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The role if it exists.</returns>
    Task<Role> FindRoleAsync(string normalizedRoleName, CancellationToken cancellationToken);

    /// <summary>
    /// Return a user role for the userId and roleId if it exists.
    /// </summary>
    /// <param name="userId">The user's id.</param>
    /// <param name="roleId">The role's id.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The user role if it exists.</returns>
    Task<UserRole> FindUserRoleAsync(int userId, int roleId, CancellationToken cancellationToken);

    /// <summary>
    /// Return a user with the matching userId if it exists.
    /// </summary>
    /// <param name="userId">The user's id.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The user if it exists.</returns>
    Task<User> FindUserAsync(int userId, CancellationToken cancellationToken);

    /// <summary>
    /// Return a user login with the matching userId, provider, providerKey if it exists.
    /// </summary>
    /// <param name="userId">The user's id.</param>
    /// <param name="loginProvider">The login provider name.</param>
    /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The user login if it exists.</returns>
    Task<UserLogin> FindUserLoginAsync(int userId, string loginProvider, string providerKey, CancellationToken cancellationToken);

    /// <summary>
    /// Return a user login with  provider, providerKey if it exists.
    /// </summary>
    /// <param name="loginProvider">The login provider name.</param>
    /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The user login if it exists.</returns>
    Task<UserLogin> FindUserLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken);

    /// <summary>
    /// Adds the given <paramref name="normalizedRoleName"/> to the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to add the role to.</param>
    /// <param name="normalizedRoleName">The role to add.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task AddToRoleAsync(User user, string normalizedRoleName, CancellationToken cancellationToken = default);

    /// <summary>
    /// Removes the given <paramref name="normalizedRoleName"/> from the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to remove the role from.</param>
    /// <param name="normalizedRoleName">The role to remove.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task RemoveFromRoleAsync(User user, string normalizedRoleName, CancellationToken cancellationToken = default);

    /// <summary>
    /// Retrieves the roles the specified <paramref name="user"/> is a member of.
    /// </summary>
    /// <param name="user">The user whose roles should be retrieved.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>A <see cref="Task{TResult}"/> that contains the roles the user is a member of.</returns>
    Task<IList<string>> GetRolesAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Returns a flag indicating if the specified user is a member of the give <paramref name="normalizedRoleName"/>.
    /// </summary>
    /// <param name="user">The user whose role membership should be checked.</param>
    /// <param name="normalizedRoleName">The role to check membership of</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>A <see cref="Task{TResult}"/> containing a flag indicating if the specified user is a member of the given group. If the
    /// user is a member of the group the returned value with be true, otherwise it will be false.</returns>
    Task<bool> IsInRoleAsync(User user, string normalizedRoleName, CancellationToken cancellationToken = default);

    /// <summary>
    /// Get the claims associated with the specified <paramref name="user"/> as an asynchronous operation.
    /// </summary>
    /// <param name="user">The user whose claims should be retrieved.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a user.</returns>
    Task<IList<Claim>> GetClaimsAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Adds the <paramref name="claims"/> given to the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to add the claim to.</param>
    /// <param name="claims">The claim to add to the user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task AddClaimsAsync(User user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default);

    /// <summary>
    /// Replaces the <paramref name="claim"/> on the specified <paramref name="user"/>, with the <paramref name="newClaim"/>.
    /// </summary>
    /// <param name="user">The user to replace the claim on.</param>
    /// <param name="claim">The claim replace.</param>
    /// <param name="newClaim">The new claim replacing the <paramref name="claim"/>.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task ReplaceClaimAsync(User user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default);

    /// <summary>
    /// Removes the <paramref name="claims"/> given from the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to remove the claims from.</param>
    /// <param name="claims">The claim to remove.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task RemoveClaimsAsync(User user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default);

    /// <summary>
    /// Adds the <paramref name="login"/> given to the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to add the login to.</param>
    /// <param name="login">The login to add to the user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task AddLoginAsync(User user, UserLoginInfo login, CancellationToken cancellationToken = default);

    /// <summary>
    /// Removes the <paramref name="loginProvider"/> given from the specified <paramref name="user"/>.
    /// </summary>
    /// <param name="user">The user to remove the login from.</param>
    /// <param name="loginProvider">The login to remove from the user.</param>
    /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
    Task RemoveLoginAsync(User user, string loginProvider, string providerKey, CancellationToken cancellationToken = default);

    /// <summary>
    /// Retrieves the associated logins for the specified <param ref="user"/>.
    /// </summary>
    /// <param name="user">The user whose associated logins to retrieve.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> for the asynchronous operation, containing a list of <see cref="UserLoginInfo"/> for the specified <paramref name="user"/>, if any.
    /// </returns>
    Task<IList<UserLoginInfo>> GetLoginsAsync(User user, CancellationToken cancellationToken = default);

    /// <summary>
    /// Retrieves the user associated with the specified login provider and login provider key.
    /// </summary>
    /// <param name="loginProvider">The login provider who provided the <paramref name="providerKey"/>.</param>
    /// <param name="providerKey">The key provided by the <paramref name="loginProvider"/> to identify a user.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
    /// </returns>
    Task<User> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken = default);

    /// <summary>
    /// Gets the user, if any, associated with the specified, normalized email address.
    /// </summary>
    /// <param name="normalizedEmail">The normalized email address to return the user for.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address.
    /// </returns>
    Task<User> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default);

    /// <summary>
    /// Retrieves all users with the specified claim.
    /// </summary>
    /// <param name="claim">The claim whose users should be retrieved.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> contains a list of users, if any, that contain the specified claim.
    /// </returns>
    Task<IList<User>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default);

    /// <summary>
    /// Retrieves all users in the specified role.
    /// </summary>
    /// <param name="normalizedRoleName">The role whose users should be retrieved.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>
    /// The <see cref="Task"/> contains a list of users, if any, that are in the specified role.
    /// </returns>
    Task<IList<User>> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken = default);

    /// <summary>
    /// Find a user token if it exists.
    /// </summary>
    /// <param name="user">The token owner.</param>
    /// <param name="loginProvider">The login provider for the token.</param>
    /// <param name="name">The name of the token.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
    /// <returns>The user token if it exists.</returns>
    Task<UserToken> FindTokenAsync(User user, string loginProvider, string name, CancellationToken cancellationToken);

    /// <summary>
    /// Add a new user token.
    /// </summary>
    /// <param name="token">The token to be added.</param>
    /// <returns></returns>
    Task AddUserTokenAsync(UserToken token);

    /// <summary>
    /// Remove a new user token.
    /// </summary>
    /// <param name="token">The token to be removed.</param>
    /// <returns></returns>
    Task RemoveUserTokenAsync(UserToken token);

    #endregion

    #region CustomMethods

    // Add custom methods here

    #endregion
}


text:
/*
 * AppDelegate.m
 *
 *  Created on: Oct 30, 2013
 *      Author: Billy
 */

#import "AppDelegate.h"
#import <Carbon/Carbon.h>
#import <Quartz/Quartz.h>

#define TargetApplicationName               @"iPhone Simulator"
#define TargetApplicationBundleIdentifier   @"com.apple.iphonesimulator"

@interface AppDelegate ()
{
    IBOutlet NSMenu *menu;
    IBOutlet NSMenuItem *targetApplicationActivateMenuItem;
    NSStatusItem *statusItem;

    CFMachPortRef portRef;
    CFRunLoopSourceRef runLoopSourceRef;

    CGFloat windowTitleBarHeight;
    CGRect targetWindowBounds;
    CGRect normalizedTargetWindowBounds;
    CGEventFlags eventFlags;
    CGPoint currentScreenPosition;
    CGPoint cursorPosition;

    enum {
        UnknownGesture,
        Rotation,
        Magnification,
    } gesture;

    CGFloat gestureValue;
    CGFloat gestureMinValue;
    CGFloat gestureMaxValue;

    BOOL mouseIsDown;
    BOOL isTouchscreenMode;

    enum {
        Inactive,
        Ready,
        Active
    } touchStatus;
}

@property (assign) IBOutlet NSWindow *window;
@property (nonatomic, assign) BOOL eventTapEnabled;
@property (nonatomic, retain) NSRunningApplication *targetApplication;
- (CGRect)targetApplicationBounds;
@end

@implementation AppDelegate
@synthesize window;
@synthesize eventTapEnabled;
@synthesize targetApplication;

- (void)dealloc
{
    [[NSWorkspace sharedWorkspace].notificationCenter removeObserver:self];
    self.eventTapEnabled = NO;
    self.targetApplication = nil;
    [menu release];
    [targetApplicationActivateMenuItem release];
    [statusItem release];
    [super dealloc];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    windowTitleBarHeight = window.frame.size.height - [window.contentView frame].size.height;
    window.showsToolbarButton = YES;
    [window orderOut:self];
    statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
    statusItem.highlightMode = YES;
    statusItem.image = [NSImage imageNamed:@"iconTemplate.png"];
    statusItem.image.size = NSMakeSize(21, 21);
    statusItem.menu = menu;
    [[NSWorkspace sharedWorkspace].notificationCenter addObserver:self selector:@selector(workspaceDidActivateApplication:) name:NSWorkspaceDidActivateApplicationNotification object:nil];
    [self didActivateApplication:[NSWorkspace sharedWorkspace].frontmostApplication];
}

- (IBAction)showAbout:(id)sender
{
    [NSApp orderFrontStandardAboutPanel:sender];
}

- (IBAction)terminate:(id)sender
{
    [NSApp terminate:sender];
}

- (void)activateTargetApplication:(id)sender
{
    [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:TargetApplicationBundleIdentifier options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:NULL];
}

- (void)didActivateApplication:(NSRunningApplication *)application
{
    self.targetApplication = [application.bundleIdentifier isEqualToString:TargetApplicationBundleIdentifier] ? application : nil;

    if(targetApplication == nil)
        self.eventTapEnabled = NO;
    else
    {
        while(CGRectIsEmpty([self targetApplicationBounds]))
            [NSThread sleepForTimeInterval:0.1];

        self.eventTapEnabled = YES;
    }
}

- (void)workspaceDidActivateApplication:(NSNotification *)notification
{
    [self didActivateApplication:[[notification userInfo] objectForKey:NSWorkspaceApplicationKey]];
}

- (void)setEventTapEnabled:(BOOL)eventTapEnabled_
{
    [targetApplicationActivateMenuItem setAction:(eventTapEnabled_ ? nil : @selector(activateTargetApplication:))];

    if(eventTapEnabled_ != eventTapEnabled)
    {
        if(eventTapEnabled_)
        {
            mouseIsDown = NO;
            isTouchscreenMode = NO;
            touchStatus = Inactive;
            portRef = CGEventTapCreate(kCGHIDEventTap, kCGTailAppendEventTap, kCGEventTapOptionDefault, NSFlagsChangedMask | NSMouseMovedMask | NSLeftMouseDownMask | NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSEventMaskGesture, (CGEventTapCallBack)eventTapCallback, self);
            runLoopSourceRef = CFMachPortCreateRunLoopSource(NULL, portRef, 0);
            CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSourceRef, kCFRunLoopCommonModes);
        }
        else if(runLoopSourceRef != nil && CFRunLoopContainsSource(CFRunLoopGetMain(), runLoopSourceRef, kCFRunLoopCommonModes))
        {
            CFRunLoopRemoveSource(CFRunLoopGetMain(), runLoopSourceRef, kCFRunLoopCommonModes);

            if(portRef != nil)
            {
                CFMachPortInvalidate(portRef);
                CFRelease(portRef);
                portRef = nil;
            }

            if(runLoopSourceRef != nil)
            {
                CFRelease(runLoopSourceRef);
                runLoopSourceRef = nil;
            }
        }

        eventTapEnabled = eventTapEnabled_;
    }
}

- (CGRect)targetApplicationBounds
{
    NSArray *windowInfoList = (NSArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
    normalizedTargetWindowBounds = CGRectZero;

    for(NSDictionary *windowInfo in windowInfoList)
    {
        if([[windowInfo valueForKey:(NSString *)kCGWindowOwnerPID] intValue] == targetApplication.processIdentifier)
        {
            CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[windowInfo valueForKey:(NSString *)kCGWindowBounds], &targetWindowBounds);
            normalizedTargetWindowBounds = targetWindowBounds;
            normalizedTargetWindowBounds.origin.y += normalizedTargetWindowBounds.size.height;
            normalizedTargetWindowBounds.size.height -= windowTitleBarHeight;
            targetWindowBounds.origin.y = [NSScreen mainScreen].frame.size.height - (targetWindowBounds.origin.y + targetWindowBounds.size.height);
            targetWindowBounds.size.height -= windowTitleBarHeight;
            break;
        }
    }

    CFRelease(windowInfoList);
    return normalizedTargetWindowBounds;
}

- (void)sendFlagsChangedEvent:(CGEventFlags)flags
{
    if(flags != eventFlags)
    {
        CGEventRef eventRef = CGEventCreate(NULL);
        CGEventSetType(eventRef, kCGEventFlagsChanged);
        CGEventSetFlags(eventRef, flags);
        CGEventPost(kCGHIDEventTap, eventRef);
        CFRelease(eventRef);
        eventFlags = flags;
    }
}

- (void)sendMouseEvent:(CGEventType)eventType atPosition:(CGPoint)position
{
    BOOL send = YES;

    switch(eventType)
    {
        case kCGEventLeftMouseDragged:
            if(!mouseIsDown)
                [self sendMouseEvent:kCGEventLeftMouseDown atPosition:position];

            break;

        case kCGEventMouseMoved:
            if(mouseIsDown)
                [self sendMouseEvent:kCGEventLeftMouseUp atPosition:position];

            break;

        case kCGEventLeftMouseDown:
            send = !mouseIsDown;
            mouseIsDown = YES;
            break;

        case kCGEventLeftMouseUp:
            send = mouseIsDown;
            mouseIsDown = NO;
            break;

        default:
            send = NO;
            break;
    }

    if(send)
    {
        CGEventRef eventRef = CGEventCreateMouseEvent(NULL, eventType, position, 0);
        CGEventSetFlags(eventRef, eventFlags);
        CGEventPost(kCGHIDEventTap, eventRef);
        CFRelease(eventRef);
    }

    CGWarpMouseCursorPosition([self screenPosition:cursorPosition]);
}

enum {
    RotateLeft,
    RotateRight,
    ShakeGesture,
    Home,
    Lock,
    Dummy
};

- (void)triggerHardwareCommand:(int)command
{
    CGKeyCode keyCode;
    CGEventFlags flags = kCGEventFlagMaskCommand;

    switch(command)
    {
        case RotateLeft:
            keyCode = kVK_LeftArrow;
            break;

        case RotateRight:
            keyCode = kVK_RightArrow;
            break;

        case ShakeGesture:
            keyCode = kVK_ANSI_Z;
            flags |= kCGEventFlagMaskControl;
            break;

        case Home:
            keyCode = kVK_ANSI_H;
            flags |= kCGEventFlagMaskShift;
            break;

        case Lock:
            keyCode = kVK_ANSI_L;
            break;

        default:
            return;
    }

    CGEventRef eventRef = CGEventCreateKeyboardEvent(NULL, keyCode, true);
    CGEventSetFlags(eventRef, flags);
    CGEventPost(kCGHIDEventTap, eventRef);
    CFRelease(eventRef);
}

- (CGPoint)screenPosition:(CGPoint)normalizedPosition
{
    CGPoint screenPosition;
    screenPosition.x = normalizedTargetWindowBounds.origin.x + (normalizedTargetWindowBounds.size.width * normalizedPosition.x);
    screenPosition.y = normalizedTargetWindowBounds.origin.y - (normalizedTargetWindowBounds.size.height * normalizedPosition.y);
    return screenPosition;
}

- (CGPoint)normalizedPosition
{
    CGPoint screenPosition = [NSEvent mouseLocation];

    if(CGRectContainsPoint(targetWindowBounds, screenPosition))
        return CGPointMake((screenPosition.x - targetWindowBounds.origin.x) / targetWindowBounds.size.width, (screenPosition.y - targetWindowBounds.origin.y) / targetWindowBounds.size.height);

    return CGPointMake(0.5, 0.5);
}

static CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef eventRef, AppDelegate *appDelegate)
{
    NSEvent *event = [NSEvent eventWithCGEvent:eventRef];

    switch(type)
    {
        case NSEventTypeGesture:
            switch(event.type)
            {
                case NSEventTypeGesture:
                {
                    NSArray *touches = [event touchesMatchingPhase:NSTouchPhaseAny inView:nil].allObjects;

                    if(touches.count == 1)
                    {
                        NSTouch *touch = touches.firstObject;
                        NSUInteger modifierFlags = event.modifierFlags & (NSShiftKeyMask | NSControlKeyMask);

                        if(touch.phase == NSTouchPhaseBegan)
                            appDelegate->isTouchscreenMode = (modifierFlags != 0) && (event.modifierFlags & NSAlternateKeyMask) == 0;

                        if(appDelegate->isTouchscreenMode)
                        {
                            CGEventType eventType = kCGEventNull;
                            CGPoint position;

                            switch(touch.phase)
                            {
                                case NSTouchPhaseBegan:
                                    [appDelegate targetApplicationBounds];
                                    [appDelegate sendFlagsChangedEvent:0];
                                    appDelegate->touchStatus = (modifierFlags & NSControlKeyMask) ? Ready : Active;

                                    if(appDelegate->touchStatus == Ready)
                                    {
                                        CGEventFlags flags = kCGEventFlagMaskAlternate;

                                        if((modifierFlags & NSShiftKeyMask))
                                        {
                                            flags |= kCGEventFlagMaskShift;
                                            appDelegate->cursorPosition = touch.normalizedPosition;
                                            position.x = 0.5;
                                            position.y = 0.5;
                                        }
                                        else
                                        {
                                            appDelegate->cursorPosition = [appDelegate normalizedPosition];
                                            position.x = 0.5 + touch.normalizedPosition.x - appDelegate->cursorPosition.x;
                                            position.y = 0.5 + touch.normalizedPosition.y - appDelegate->cursorPosition.y;
                                        }

                                        [appDelegate sendFlagsChangedEvent:kCGEventFlagMaskAlternate];
                                        [appDelegate sendMouseEvent:kCGEventMouseMoved atPosition:[appDelegate screenPosition:position]];
                                        position = [appDelegate screenPosition:touch.normalizedPosition];
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            if(appDelegate->touchStatus == Ready)
                                            {
                                                [appDelegate sendFlagsChangedEvent:(kCGEventFlagMaskAlternate | kCGEventFlagMaskShift)];
                                                [appDelegate sendMouseEvent:kCGEventMouseMoved atPosition:position];
                                                [appDelegate sendFlagsChangedEvent:flags];
                                                [appDelegate sendMouseEvent:kCGEventLeftMouseDown atPosition:position];
                                                appDelegate->touchStatus = Active;
                                            }
                                        });

                                        break;
                                    }

                                case NSTouchPhaseMoved:
                                    if(appDelegate->touchStatus == Active)
                                    {
                                        eventType = kCGEventLeftMouseDragged;
                                        position = [appDelegate screenPosition:touch.normalizedPosition];
                                        appDelegate->currentScreenPosition = position;

                                        if(appDelegate->eventFlags != kCGEventFlagMaskAlternate)
                                            appDelegate->cursorPosition = touch.normalizedPosition;
                                    }

                                    break;

                                case NSTouchPhaseEnded:
                                case NSTouchPhaseCancelled:
                                    appDelegate->touchStatus = Inactive;
                                    [appDelegate sendFlagsChangedEvent:0];
                                    eventType = kCGEventLeftMouseUp;
                                    position = appDelegate->currentScreenPosition;
                                    break;

                                default:
                                    break;
                            }

                            [appDelegate sendMouseEvent:eventType atPosition:position];
                        }
                    }

                    break;
                }

                case NSEventTypeBeginGesture:
                    appDelegate->gestureValue = 0;
                    appDelegate->gestureMinValue = 0;
                    appDelegate->gestureMaxValue = 0;
                    appDelegate->gesture = UnknownGesture;
                    break;

                case NSEventTypeMagnify:
                    if(appDelegate->gesture == Magnification)
                    {
                        appDelegate->gestureValue += event.magnification;

                        if(event.magnification < 0)
                            appDelegate->gestureMinValue += event.magnification;
                        else
                            appDelegate->gestureMaxValue += event.magnification;
                    }
                    else if(appDelegate->gesture == UnknownGesture)
                        appDelegate->gesture = Magnification;

                    break;

                case NSEventTypeRotate:
                    if(appDelegate->gesture == Rotation)
                    {
                        appDelegate->gestureValue += event.rotation;

                        if(event.rotation < 0)
                            appDelegate->gestureMinValue += event.rotation;
                        else
                            appDelegate->gestureMaxValue += event.rotation;
                    }
                    else if(appDelegate->gesture == UnknownGesture)
                        appDelegate->gesture = Rotation;

                    break;

                case NSEventTypeEndGesture:
                {
                    int command = Dummy;

                    if(appDelegate->gesture == Magnification)
                    {
                        if(appDelegate->gestureMinValue < -0.5 && appDelegate->gestureMaxValue > 0.5)
                            command = ShakeGesture;
                        else if(appDelegate->gestureValue > 0.5)
                            command = Lock;
                        else if(appDelegate->gestureValue < -0.5)
                            command = Home;
                    }
                    else if(appDelegate->gesture == Rotation)
                    {
                        if(appDelegate->gestureMinValue < -20 && appDelegate->gestureMaxValue > 20)
                            command = ShakeGesture;
                        else if(appDelegate->gestureValue > 20)
                            command = RotateLeft;
                        else if(appDelegate->gestureValue < -20)
                            command = RotateRight;
                    }

                    [appDelegate triggerHardwareCommand:command];
                    break;
                }

                default:
                    break;
            }

            break;

        case NSFlagsChanged:
            if((event.modifierFlags & 0x20000000) || appDelegate->touchStatus == Inactive)
                return eventRef;

            break;

        case NSMouseMoved:
        case NSLeftMouseDown:
        case NSLeftMouseDragged:
        case NSLeftMouseUp:
            if(CGEventGetIntegerValueField(eventRef, kCGMouseEventSubtype) != kCGEventMouseSubtypeDefault && appDelegate->isTouchscreenMode)
                break;

        default:
            return eventRef;
    }

    return NULL;
}

@end


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

<title>ary</title>
<meta name='robots' content='noindex,nofollow' />
<meta name='generator' content='GLOBAL-6.5.2' />
<meta http-equiv='Content-Style-Type' content='text/css' />
<link rel='stylesheet' type='text/css' href='../style.css' />

ary                24 stdlib.c       _UWORD _check_sum(void* ary, _UWORD sz)
ary                26 stdlib.c           _UWORD* p = (_UWORD*)ary;


text:
#ifndef MRCP_H
#define MRCP_H

/**
 * @file mrcp.h
 * @brief MRCP Core Definitions
 */

#include <apt.h>
#include <apt_dir_layout.h>

/** Library export/import defines */
#ifdef WIN32
#ifdef MRCP_STATIC_LIB
#define MRCP_DECLARE(type)   type __stdcall
#else
#ifdef MRCP_LIB_EXPORT
#define MRCP_DECLARE(type)   __declspec(dllexport) type __stdcall
#else
#define MRCP_DECLARE(type)   __declspec(dllimport) type __stdcall
#endif
#endif
#else
#define MRCP_DECLARE(type) type
#endif

#endif /* MRCP_H */


text:
require 'pp'

module RbVmomi
module BasicTypes

BUILTIN = %w(ManagedObject DataObject TypeName PropertyPath ManagedObjectReference MethodName MethodFault LocalizedMethodFault KeyValue)

class Base
  class << self
    attr_reader :wsdl_name

    def init wsdl_name=self.name
      @wsdl_name = wsdl_name
    end

    def to_s
      @wsdl_name
    end
  end

  init
end

class ObjectWithProperties < Base
  class << self
    attr_accessor :props_desc

    def init name=self.name, props=[]
      super name
      @props_desc = props
      @props_desc.each do |d|
        sym = d['name'].to_sym
        define_method(sym) { _get_property sym }
        define_method(:"#{sym}=") { |x| _set_property sym, x }
      end
    end

    def full_props_desc
      @full_props_desc ||= (self == ObjectWithProperties ? [] : superclass.full_props_desc) + props_desc
    end

    def find_prop_desc name
      full_props_desc.find { |x| x['name'] == name.to_s }
    end
  end

  def _get_property sym
    fail 'unimplemented'
  end

  def _set_property sym, val
    fail 'unimplemented'
  end

  init
end

class ObjectWithMethods < ObjectWithProperties
  class << self
    attr_accessor :methods_desc

    def init name=self.name, props=[], methods={}
      super name, props
      @methods_desc = methods

      @methods_desc.each do |k,d|
        sym = k.to_sym
        define_method(sym) { |*args| _call sym, *args }
        define_method(:"#{sym}!") { |*args| _call sym, *args }
      end
    end

    # XXX cache
    def full_methods_desc
      (self == ObjectWithMethods ? {} : superclass.full_methods_desc).merge methods_desc
    end
  end

  init
end

class DataObject < ObjectWithProperties
  attr_reader :props

  def initialize props={}
    @props = Hash[props.map { |k,v| [k.to_sym, v] }]
    self.class.full_props_desc.each do |desc|
      #fail "missing required property #{desc['name'].inspect} of #{self.class.wsdl_name}" if @props[desc['name'].to_sym].nil? and not desc['is-optional']
    end
    @props.each do |k,v|
      fail "unexpected property name #{k}" unless self.class.find_prop_desc(k)
    end
  end

  def initialize_copy(source)
    super
    @props = @props.dup
  end

  def _get_property sym
    @props[sym]
  end

  def [] sym
    _get_property sym
  end

  def _set_property sym, val
    @props[sym] = val
  end

  def []= sym, val
    _set_property sym, val
  end

  def == o
    return false unless o.class == self.class
    keys = (props.keys + o.props.keys).uniq
    keys.all? { |k| props[k] == o.props[k] }
  end

  alias eql? ==

  def hash
    props.hash
  end

  def pretty_print q
    q.text self.class.wsdl_name
    q.group 2 do
      q.text '('
      q.breakable
      props = @props.sort_by { |k,v| k.to_s }
      q.seplist props, nil, :each do |k, v|
        q.group do
          q.text k.to_s
          q.text ': '
          q.pp v
        end
      end
    end
    q.breakable
    q.text ')'
  end

  init
end

class ManagedObject < ObjectWithMethods
  def initialize connection, ref
    super()
    @connection = connection
    @soap = @connection # XXX deprecated
    @ref = ref
  end

  def _connection
    @connection
  end

  def _ref
    @ref
  end

  def _get_property sym
    ret = @connection.propertyCollector.RetrieveProperties(:specSet => [{
      :propSet => [{ :type => self.class.wsdl_name, :pathSet => [sym.to_s] }],
      :objectSet => [{ :obj => self }],
    }])[0]

    if ret.propSet.empty?
      return nil if ret.missingSet.empty?
      raise ret.missingSet[0].fault
    else
      ret.propSet[0].val
    end
  end

  def _set_property sym, val
    fail 'unimplemented'
  end

  def _call method, o={}
    fail "parameters must be passed as a hash" unless o.is_a? Hash
    desc = self.class.full_methods_desc[method.to_s] or fail "unknown method"
    @connection.call method, desc, self, o
  end

  def to_s
    "#{self.class.wsdl_name}(#{@ref.inspect})"
  end

  def pretty_print pp
    pp.text to_s
  end

  def [] k
    _get_property k
  end

  def == x
    x.class == self.class and x._ref == @ref
  end

  alias eql? ==

  def hash
    [self.class, @ref].hash
  end

  init 'ManagedObject'
end

class Enum < Base
  class << self
    attr_accessor :values

    def init name=self.name, values=[]
      super name
      @values = values
    end
  end

  attr_reader :value

  def initialize value
    @value = value
  end

  init
end

class MethodFault < DataObject
  init 'MethodFault', [
    {
      'name' => 'faultCause',
      'wsdl_type' => 'LocalizedMethodFault',
      'is-array' => false,
      'is-optional' => true,
    }, {
      'name' => 'faultMessage',
      'wsdl_type' => 'LocalizableMessage',
      'is-array' => true,
      'is-optional' => true,
    },
  ]

  def self.=== exn
    exn.class == RbVmomi::Fault and self <= exn.fault.class
  end
end

class LocalizedMethodFault < DataObject
  init 'LocalizedMethodFault', [
    {
      'name' => 'fault',
      'wsdl_type' => 'MethodFault',
      'is-array' => false,
      'is-optional' => false,
    }, {
      'name' => 'localizedMessage',
      'wsdl_type' => 'xsd:string',
      'is-array' => false,
      'is-optional' => true,
    },
  ]

  def exception
    RbVmomi::Fault.new(self.localizedMessage, self.fault)
  end
end

class RuntimeFault < MethodFault
  init
end

class MethodName < String
  def self.wsdl_name; 'MethodName' end
end

class PropertyPath < String
  def self.wsdl_name; 'PropertyPath' end
end

class TypeName < String
  def self.wsdl_name; 'TypeName' end
end

class ManagedObjectReference
  def self.wsdl_name; 'ManagedObjectReference' end
end

class Boolean
  def self.wsdl_name; 'xsd:boolean' end
end

class AnyType
  def self.wsdl_name; 'xsd:anyType' end
end

class Binary
  def self.wsdl_name; 'xsd:base64Binary' end
end

class ::Class
  def wsdl_name; self.class.name end
end

class ::String
  def self.wsdl_name; 'xsd:string' end
end

class ::Integer
  def self.wsdl_name; 'xsd:int' end
end

class ::Float
  def self.wsdl_name; 'xsd:float' end
end

class KeyValue
  def self.wsdl_name; 'xsd:float' end
  attr_accessor :key, :value

  def initialize k, v
    @key = k
    @value = v
  end

  def [] i
    if i == 0 then @key
    elsif i == 1 then @value
    else fail "invalid index #{i.inspect}"
    end
  end
end

end
end


text: ACCOUNT_NAME = 'Office Spot'


text:
require 'fog/atmos/core'

module Fog
  module Storage
    class Atmos < Fog::Service
      requires :atmos_storage_endpoint,
               :atmos_storage_secret,
               :atmos_storage_token
      recognizes :persistent

      model_path 'fog/atmos/models/storage'
      model       :directory
      collection  :directories
      model       :file
      collection  :files

      request_path 'fog/atmos/requests/storage'
      # request :delete_container
      request :get_namespace
      request :head_namespace
      request :post_namespace
      request :put_namespace
      request :delete_namespace

      module Utils
        ENDPOINT_REGEX = /(https*):\/\/([a-zA-Z0-9\.\-]+)(:[0-9]+)?(\/.*)?/

        def ssl?
          protocol = @endpoint.match(ENDPOINT_REGEX)[1]
          raise ArgumentError, 'Invalid endpoint URL' if protocol.nil?

          return true if protocol == 'https'
          return false if protocol == 'http'

          raise ArgumentError, "Unknown protocol #{protocol}"
        end

        def port
          port = @endpoint.match(ENDPOINT_REGEX)[3]
          return ssl? ? 443 : 80 if port.nil?
          port.split(':')[1].to_i
        end

        def host
          @endpoint.match(ENDPOINT_REGEX)[2]
        end

        def api_path
          @endpoint.match(ENDPOINT_REGEX)[4]
        end

        def setup_credentials(options)
          @storage_token = options[:atmos_storage_token]
          @storage_secret = options[:atmos_storage_secret]
          @storage_secret_decoded = Base64.decode64(@storage_secret)
          @endpoint = options[:atmos_storage_endpoint]
          @prefix = self.ssl? ? 'https' : 'http'
          @storage_host = self.host
          @storage_port = self.port
          @api_path = self.api_path
        end
      end

      class Mock
        include Utils

        def initialize(options={})
          setup_credentials(options)
        end

        def request(options)
          raise "Atmos Storage mocks not implemented"
        end

      end

      class Real
        include Utils

        def initialize(options={})
          setup_credentials(options)
          @connection_options = options[:connection_options] || {}
          @hmac               = Fog::HMAC.new('sha1', @storage_secret_decoded)
          @persistent = options.fetch(:persistent, false)

          @connection = Fog::XML::Connection.new("#{@prefix}://#{@storage_host}:#{@storage_port}",
              @persistent, @connection_options)
        end

        def uid
          @storage_token#.split('/')[-1]
        end

        def sign(string)
          value = @hmac.sign(string)
          Base64.encode64( value ).chomp()
        end

        def reload
          @connection.reset
        end

        def request(params, &block)
          req_path = params[:path]
          # Force set host and port
          params.merge!({
                          :host     => @storage_host,
                          :path     => "#{@api_path}/rest/#{params[:path]}",
                        })
          # Set default method and headers
          params = {:method => 'GET', :headers => {}}.merge params

          params[:headers]["Content-Type"] ||= "application/octet-stream"

          # Add request date
          params[:headers]["date"] = Time.now().httpdate()
          params[:headers]["x-emc-uid"] = @storage_token

          # Build signature string
          signstring = ""
          signstring += params[:method]
          signstring += "\n"
          signstring += params[:headers]["Content-Type"]
          signstring += "\n"
          if( params[:headers]["range"] )
            signstring += params[:headers]["range"]
          end
          signstring += "\n"
          signstring += params[:headers]["date"]
          signstring += "\n"

          signstring += "/rest/" + URI.unescape( req_path ).downcase
          query_str = params[:query].map{|k,v| "#{k}=#{v}"}.join('&')
          signstring += '?' + query_str unless query_str.empty?
          signstring += "\n"

          customheaders = {}
          params[:headers].each { |key,value|
            case key
            when 'x-emc-date', 'x-emc-signature'
              #skip
            when /^x-emc-/
              customheaders[ key.downcase ] = value
            end
          }
          header_arr = customheaders.sort()

          header_arr.each { |key,value|
            # Values are lowercase and whitespace-normalized
            signstring += key + ":" + value.strip.chomp.squeeze( " " ) + "\n"
          }

          digest = @hmac.sign(signstring.chomp())
          signature = Base64.encode64( digest ).chomp()
          params[:headers]["x-emc-signature"] = signature

          params.delete(:host) #invalid excon request parameter

          parse = params.delete(:parse)

          begin
            response = @connection.request(params, &block)
          rescue Excon::Errors::HTTPStatusError => error
            raise case error
            when Excon::Errors::NotFound
              Fog::Storage::Atmos::NotFound.slurp(error)
            else
              error
            end
          end
          unless response.body.empty?
            if parse
              document = Fog::ToHashDocument.new
              parser = Nokogiri::XML::SAX::PushParser.new(document)
              parser << response.body
              parser.finish
              response.body = document.body
            end
          end
          response
        end

      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
  <package name="integration" extends="struts1-default" namespace="/integration">

    <interceptors>
      <interceptor name="gangsterForm" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor">
        <param name="className">org.apache.struts2.showcase.integration.GangsterForm</param>
        <param name="name">gangsterForm</param>
      </interceptor>
      <interceptor name="gangsterValidation" class="org.apache.struts2.s1.ActionFormValidationInterceptor">
        <param name="pathnames">/org/apache/struts/validator/validator-rules.xml,/WEB-INF/validation.xml</param>
      </interceptor>

      <interceptor-stack name="integration">
        <interceptor-ref name="staticParams"/>
        <interceptor-ref name="gangsterForm"/>
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="actionForm-reset"/>
        <interceptor-ref name="basicStack"/>
        <interceptor-ref name="gangsterValidation"/>
        <interceptor-ref name="workflow"/>
      </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="integration"/>
    <default-action-ref name="editGangster"/>

    <!-- Display entry page that uses Model-Driven technique -->
    <action name="editGangster" class="org.apache.struts2.s1.Struts1Action">
      <param name="className">org.apache.struts2.showcase.integration.EditGangsterAction</param>
      <result>/WEB-INF/integration/modelDriven.jsp</result>
    </action>

    <!-- Display the result page whose content is populated using the Model-Driven technique -->
    <action name="saveGangster" class="org.apache.struts2.s1.Struts1Action">
      <param name="className">org.apache.struts2.showcase.integration.SaveGangsterAction</param>
      <param name="validate">true</param>
      <result name="input">/WEB-INF/integration/modelDriven.jsp</result>
      <result>/WEB-INF/integration/modelDrivenResult.jsp</result>
    </action>

  </package>
</struts>


text:
/*-------------------------------------------------------------------------
  Copyright (c) 2011 David Gobbi.

  Contributed to the VisualizationToolkit by the author in May 2011
  under the terms of the Visualization Toolkit 2008 copyright.
-------------------------------------------------------------------------*/

/**
 * This file contains extra utilities for parsing and wrapping.
 */

#ifndef VTK_PARSE_EXTRAS_H
#define VTK_PARSE_EXTRAS_H

#include "vtkParseData.h"
#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Skip over a sequence of characters that begin with an alphabetic
 * character or an underscore, and include only alphanumeric
 * characters or underscores. Return the number of characters.
 */
size_t vtkParse_IdentifierLength(const char *text);

/**
 * Skip over a name, including any namespace prefixes and
 * any template arguments.  Return the number of characters.
 * Examples are "name", "::name", "name<arg>", "name::name2",
 * "::name::name2<arg1,arg2>".
 */
size_t vtkParse_NameLength(const char *text);

/**
 * Skip over a name, including any template arguments, but stopping
 * if a '::' is encoutered.  Return the number of characters.
 * Examples are "name" and "name<arg>"
 */
size_t vtkParse_UnscopedNameLength(const char *text);

/**
 * Skip over a literal, which may be a number, a char in single
 * quotes, a string in double quotes, or a name, or a name followed
 * by arguments in parentheses.
 */
size_t vtkParse_LiteralLength(const char *text);

/**
 * Get a type from a type name, and return the number of characters used.
 * If the "classname" argument is not NULL, then it is used to return
 * the short name for the type, e.g. "long int" becomes "long", while
 * typedef names and class names are returned unchanged.  If "const"
 * appears in the type name, then the const bit flag is set for the
 * type, but "const" will not appear in the returned classname.
 */
size_t vtkParse_BasicTypeFromString(
  const char *text, unsigned int *type,
  const char **classname, size_t *classname_len);

/**
 * Generate a ValueInfo by parsing the type from the provided text.
 * Only simple text strings are supported, e.g. "const T **".
 * Returns the number of characters consumed.
 */
size_t vtkParse_ValueInfoFromString(
  ValueInfo *val, StringCache *cache, const char *text);

/**
 * Generate a declaration string from a ValueInfo struct.  If the
 * "nf" arg is set, the returned string must be freed.
 * Only simple text strings are supported, e.g. "const T **".
 * The variable or typedef name, if present, is ignored.
 */
const char *vtkParse_ValueInfoToString(ValueInfo *val, int *nf);

/**
 * Expand a typedef within a variable, parameter, or typedef declaration.
 * The expansion is done in-place.
 */
void vtkParse_ExpandTypedef(ValueInfo *valinfo, ValueInfo *typedefinfo);

/**
 * Expand any unrecognized types within a variable, parameter, or typedef
 * that match any of the supplied typedefs. The expansion is done in-place.
 */
void vtkParse_ExpandTypedefs(
  ValueInfo *valinfo, StringCache *cache,
  int n, const char *name[], const char *val[],
  ValueInfo *typedefinfo[]);

/**
 * Wherever one of the specified names exists inside a Value or inside
 * a Dimension size, replace it with the corresponding val string.
 * This is used to replace constants with their values.
 */
void vtkParse_ExpandValues(
  ValueInfo *valinfo, StringCache *cache,
  int n, const char *name[], const char *val[]);

/**
 * Search and replace, return the initial string if no replacements
 * occurred, else return a new string allocated with malloc. */
const char *vtkParse_StringReplace(
  const char *str1, int n, const char *name[], const char *val[]);

/**
 * Extract the class name and template args from a templated
 * class type ID.  Returns the full number of characters that
 * were consumed during the decomposition.
 */
size_t vtkParse_DecomposeTemplatedType(
  const char *text, const char **classname,
  int n, const char ***args, const char *defaults[]);

/**
 * Free the list of strings returned by ExtractTemplateArgs.
 */
void vtkParse_FreeTemplateDecomposition(
  const char *classname, int n, const char **args);

/**
 * Instantiate a class template by substituting the provided arguments
 * for the template parameters. If "n" is less than the number of template
 * parameters, then default parameter values (if present) will be used.
 * If an error occurs, the error will be printed to stderr and NULL will
 * be returned.
 */
void vtkParse_InstantiateClassTemplate(
  ClassInfo *data, StringCache *cache, int n, const char *args[]);

/**
 * Instantiate a function or class method template by substituting the
 * provided arguments for the template parameters.  If "n" is less than
 * the number of template parameters, then default parameter values
 * (if present) will be used.  If an error occurs, the error will be
 * printed to stderr and NULL will be returned.
 */
void vtkParse_IntantiateFunctionTemplate(
  FunctionInfo *data, int n, const char *args[]);

/**
 * Get a zero-terminated array of the types in vtkTemplateMacro.
 */
const char **vtkParse_GetTemplateMacroTypes();

/**
 * Get a zero-terminated array of the types in vtkArray.
 */
const char **vtkParse_GetArrayTypes();

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif


text:
using System;

public class ArrayMain
{
  public class Queue
  {
    int max, current;
    int[] queue;

    /* Método contrutor da fila recebe o tamanho */
    public Queue(int max)
    {
      /* Inicia a fila com o tamanho determinado */
      this.queue = new int[max];

      this.max = max;
      this.current = -1;
    }

    /* Verifica se a fila não está cheia e adiciona o elemento.  */
    public void Enqueue(int element)
    {
      if(this.current + 1 == this.max) return;

      this.queue[++this.current] = element;
    }

    /* Verifica se a fila não está vazia e remove um elemento. */
    public int Dequeue()
    {
      if(this.current == -1) throw new Exception("Empty");

      int element = this.queue[0];
      for(int i = 0; i < this.current;i++)
      {
        this.queue[i] = this.queue[i+1];
      }

      this.queue[this.current--] = 0;

      return element;
    }
  }

  public static void Main()
  {
    Queue queue = new Queue(5);
    queue.Enqueue(1);
    queue.Enqueue(2);
    queue.Enqueue(3);
    queue.Enqueue(4);
    queue.Enqueue(5);

    Console.WriteLine("Dequeue > {0}", queue.Dequeue());
    Console.WriteLine("Dequeue > {0}", queue.Dequeue());
    Console.WriteLine("Dequeue > {0}", queue.Dequeue());
    Console.WriteLine("Dequeue > {0}", queue.Dequeue());
    Console.WriteLine("Dequeue > {0}", queue.Dequeue());

    /* Gera Exception por não ter mais elementos na fila. */
    //Console.WriteLine("Dequeue > {0}", queue.Dequeue());
  }
}


text:
const fs = require('fs')
const os = require('os')
const net = require('net')
const Web3 = require('web3')
const Promise = require('bluebird')
const chalk = require('chalk')

const client = net.Socket()
const contractPrefix = '<stdin>:'
var IPCPath
if (process.platform === 'win32') {
  IPCPath = '\\\\.\\pipe\\geth.ipc'
} else if (process.platform === 'darwin') {
  IPCPath = os.homedir() + '/Library/Ethereum/geth.ipc'
} else {
  IPCPath = os.homedir() + '.ethereum'
}

const web3 = new Web3(new Web3.providers.IpcProvider(IPCPath, client))

function unlockAccount (account, password) {
  return new Promise(function (resolve, reject) {
    web3.personal.unlockAccount(account, password, function (err, result) {
      if (err) {
        console.error(chalk.red('Failed to unlock account', account))
        return reject(err)
      }
      console.log('Successfully unlocked account', account)
      resolve()
    })
  })
}

function readContract (path) {
  return function () {
    return new Promise(function (resolve, reject) {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          console.error(chalk.red('Failed to read contract at:', path))
          return reject(err)
        }
        console.log('Read contract at:', path)
        resolve(data)
      })
    })
  }
}

function compileContract (contractName) {
  return function (sourceCode) {
    return new Promise(function (resolve, reject) {
      web3.eth.compile.solidity(sourceCode, function (err, result) {
        if (err) {
          console.error(chalk.red('Failed to compile contract', contractName))
          return reject(err)
        }

        console.log('Successfully compiled contract', contractName)
        var compiled = result[contractPrefix + contractName]
        var contract = web3.eth.contract(compiled.info.abiDefinition)
        contract.byteCode = compiled.code
        resolve(contract)
      })
    })
  }
}

function contractAt (address) {
  return function (contract) {
    return Promise.resolve(contract.at(address))
  }
}

function print (msg) {
  console.log(msg)
  return Promise.resove()
}

function done () {
  console.log('Done')
  process.exit(0)
}

function handleError (err) {
  console.error(chalk.red(err))
  process.exit(-1)
}

module.exports = {
  unlockAccount: unlockAccount,
  readContract: readContract,
  compileContract: compileContract,
  contractAt: contractAt,
  print: print,
  done: done,
  handleError: handleError,
  web3: web3
}


text:
<?php
/**
 * @namespace
 */
namespace Test;

use Kaltura\Client\Type\MediaEntryFilterForPlaylist;
use Kaltura\Client\Type\MediaEntryFilter;
use Kaltura\Client\Type\UploadedFileTokenResource;
use Kaltura\Client\Enum\EntryStatus;
use Kaltura\Client\Enum\MediaType;
use Kaltura\Client\Type\MediaEntry;
use Kaltura\Client\Enum\UploadTokenStatus;
use Kaltura\Client\Type\UploadToken;

class Zend2ClientTester
{
	const UPLOAD_VIDEO_FILENAME = 'DemoVideo.flv';
	const UPLOAD_IMAGE_FILENAME = 'DemoImage.jpg';
	const ENTRY_NAME = 'Media entry uploaded from Zend Framework 2 client library';

	/**
	 * @var \Kaltura\Client\Client
	 */
	protected $_client;

	public function __construct(\Kaltura\Client\Client $client)
	{
		$this->_client = $client;
	}

	public function run()
	{
		$methods = get_class_methods($this);
		foreach($methods as $method)
		{
			if (strpos($method, 'test') === 0)
			{
				try
				{
					// use the client logger interface to log
					$this->_client->getConfig()->getLogger()->log('Running '.$method);
					$this->$method();
				}
				catch(Exception $ex)
				{

					$this->_client->getConfig()->getLogger()->log($method . ' failed with error: ' . $ex->getMessage());
					return;
				}
			}
		}
	}

	public function testSyncFlow()
	{
		$this->_client->getSystemService();

		// add upload token
		$uploadToken = new UploadToken();
		$uploadToken->fileName = self::UPLOAD_VIDEO_FILENAME;
		$uploadToken = $this->_client->getUploadTokenService()->add($uploadToken);
		$this->assertTrue(strlen($uploadToken->id) > 0);
    	$this->assertEqual($uploadToken->fileName, self::UPLOAD_VIDEO_FILENAME);
    	$this->assertEqual($uploadToken->status, UploadTokenStatus::PENDING);
    	$this->assertEqual($uploadToken->partnerId, $this->_client->getConfig()->getPartnerId());
    	$this->assertEqual($uploadToken->fileSize, null);

    	// add media entry
    	$entry = new MediaEntry();
    	$entry->name = self::ENTRY_NAME;
    	$entry->mediaType = MediaType::VIDEO;
    	$entry = $this->_client->getMediaService()->add($entry);
    	$this->assertTrue(strlen($entry->id) > 0);
    	$this->assertTrue($entry->status === EntryStatus::NO_CONTENT);
    	$this->assertTrue($entry->name === self::ENTRY_NAME);
    	$this->assertTrue($entry->partnerId === $this->_client->getConfig()->getPartnerId());

    	// add uploaded token as resource
    	$resource = new UploadedFileTokenResource();
    	$resource->token = $uploadToken->id;
    	$entry = $this->_client->getMediaService()->addContent($entry->id, $resource);
    	$this->assertTrue($entry->status === EntryStatus::IMPORT);

    	// upload file using the upload token
    	$uploadFilePath = dirname(__FILE__) . '/../resources/' . self::UPLOAD_VIDEO_FILENAME;
    	$uploadToken = $this->_client->getUploadTokenService()->upload($uploadToken->id, $uploadFilePath);
    	$this->assertTrue($uploadToken->status === UploadTokenStatus::CLOSED);

    	// get flavor by entry
    	$flavorArray = $this->_client->getFlavorAssetService()->getByEntryId($entry->id);
    	$this->assertTrue(count($flavorArray) > 0);
    	$foundSource = false;
    	foreach($flavorArray as $flavor)
    	{
    		if ($flavor->flavorParamsId !== 0)
    			continue;

    		$this->assertTrue($flavor->isOriginal);
    		$this->assertTrue($flavor->entryId === $entry->id);
    		$foundSource = true;
    	}
    	$this->assertTrue($foundSource);

    	// count media entries
    	$mediaFilter = new MediaEntryFilter();
    	$mediaFilter->idEqual = $entry->id;
    	$mediaFilter->statusNotEqual = EntryStatus::DELETED;
    	$entryCount = $this->_client->getMediaService()->count($mediaFilter);
    	$this->assertTrue($entryCount === 1);

    	// delete media entry
    	$this->_client->getMediaService()->delete($entry->id);

    	sleep(5); // wait for the status to update

    	// count media entries again
		$entryCount = $this->_client->getMediaService()->count($mediaFilter);
    	$this->assertEqual($entryCount, 0);
	}

	public function testReturnedArrayObjectUsingPlaylistExecute()
	{
		// add image entry
    	$imageEntry = $this->addImageEntry();

    	// execute playlist from filters
    	$playlistFilter = new MediaEntryFilterForPlaylist();
    	$playlistFilter->idEqual = $imageEntry->id;
    	$filterArray = array();
    	$filterArray[] = $playlistFilter;
    	$playlistExecute = $this->_client->getPlaylistService()->executeFromFilters($filterArray, 10);
    	$this->assertEqual(count($playlistExecute), 1);
    	$firstPlaylistEntry = $playlistExecute[0];
    	$this->assertEqual($firstPlaylistEntry->id, $imageEntry->id);

    	$this->_client->getMediaService()->delete($imageEntry->id);
	}

	public function testServeUrl()
	{
		$serveUrl = $this->_client->getDataService()->serve("12345", 5, true);
    	$expected = sprintf(
    		'service=%s&action=%s&apiVersion=%s&format=%s&clientTag=%s&entryId=%s&version=%s&forceProxy=%s&partnerId=%s&ks=%s',
    		'data',
    		'serve',
    		$this->_client->getApiVersion(),
    		2,
	    	$this->_client->getConfig()->getClientTag(),
	    	'12345',
	    	5,
	    	1,
    		$this->_client->getConfig()->getPartnerId(),
	    	rawurlencode($this->_client->getKs()));

	    	echo($serveUrl.PHP_EOL);
	    	echo($expected.PHP_EOL);
    	$this->assertTrue(strpos($serveUrl, $expected) !== false);
	}

	public function addImageEntry()
	{
		$entry = new MediaEntry();
    	$entry->name = self::ENTRY_NAME;
    	$entry->mediaType = MediaType::IMAGE;
    	$entry = $this->_client->getMediaService()->add($entry);

    	$uploadToken = new UploadToken();
		$uploadToken->fileName = self::UPLOAD_IMAGE_FILENAME;
		$uploadToken = $this->_client->getUploadTokenService()->add($uploadToken);

    	$uploadFilePath = dirname(__FILE__) . '/../resources/' . self::UPLOAD_IMAGE_FILENAME;
    	$uploadToken = $this->_client->getUploadTokenService()->upload($uploadToken->id, $uploadFilePath);

		$resource = new UploadedFileTokenResource();
    	$resource->token = $uploadToken->id;
    	$entry = $this->_client->getMediaService()->addContent($entry->id, $resource);

    	return $entry;
	}

	protected function assertTrue($v)
	{
		if ($v !== true)
		{
			$backtrace = debug_backtrace();
			$msg = 'Assert failed on line: ' . $backtrace[0]['line'];
			throw new Exception($msg);
		}
	}

	protected function assertEqual($actual, $expected)
	{
		if ($actual !== $expected)
		{
			$backtrace = debug_backtrace();
			$msg = sprintf(
				"Assert failed on line: {$backtrace[0]['line']}, expecting [%s] of type [%s], actual is [%s] of type [%s]",
				$expected,
				gettype($expected),
				$actual,
				gettype($actual));
			throw new Exception($msg);
		}
	}
}


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

/**
 * @fileoverview A thick wrapper around elements with stroke and fill.
 * @author robbyw@google.com (Robby Walker)
 */

goog.provide('goog.graphics.ext.StrokeAndFillElement');

goog.require('goog.graphics.ext.Element');

/**
 * Interface for a graphics element that has a stroke and fill.
 * This is the base interface for ellipse, rectangle and other
 * shape interfaces.
 * You should not construct objects from this constructor. Use a subclass.
 * @param {goog.graphics.ext.Group} group Parent for this element.
 * @param {goog.graphics.StrokeAndFillElement} wrapper The thin wrapper to wrap.
 * @constructor
 * @extends {goog.graphics.ext.Element}
 */
goog.graphics.ext.StrokeAndFillElement = function(group, wrapper) {
  goog.graphics.ext.Element.call(this, group, wrapper);
};
goog.inherits(
    goog.graphics.ext.StrokeAndFillElement, goog.graphics.ext.Element);

/**
 * Sets the fill for this element.
 * @param {goog.graphics.Fill?} fill The fill object.
 */
goog.graphics.ext.StrokeAndFillElement.prototype.setFill = function(fill) {
  this.getWrapper().setFill(fill);
};

/**
 * Sets the stroke for this element.
 * @param {goog.graphics.Stroke?} stroke The stroke object.
 */
goog.graphics.ext.StrokeAndFillElement.prototype.setStroke = function(stroke) {
  this.getWrapper().setStroke(stroke);
};

/**
 * Redraw the rectangle.  Called when the coordinate system is changed.
 * @protected
 * @override
 */
goog.graphics.ext.StrokeAndFillElement.prototype.redraw = function() {
  this.getWrapper().reapplyStroke();
};


text:
using System.Diagnostics;
using JetBrains.Annotations;
using Prexonite.Modular;

namespace Prexonite.Compiler.Ast
{
    [DebuggerNonUserCode]
    public class AstCreateClosure : AstExpr
    {
        [NotNull] private readonly EntityRef.Function _implementation;

        public AstCreateClosure(ISourcePosition position, EntityRef.Function implementation)
            : base(position)
        {
            _implementation = implementation;
        }

        public EntityRef.Function Implementation
        {
            get { return _implementation; }
        }

        protected override void DoEmitCode(CompilerTarget target, StackSemantics stackSemantics)
        {
            if (stackSemantics == StackSemantics.Effect)
                return;

            PFunction targetFunction;
            MetaEntry sharedNamesEntry;
            if (target.Loader.ParentApplication.TryGetFunction(_implementation.Id, _implementation.ModuleName, out targetFunction)
                && (!targetFunction.Meta.TryGetValue(PFunction.SharedNamesKey, out sharedNamesEntry)
                    || !sharedNamesEntry.IsList
                        || sharedNamesEntry.List.Length == 0))
                target.Emit(Position,OpCode.ldr_func, _implementation.Id, target.ToInternalModule(_implementation.ModuleName));
            else
                target.Emit(Position,OpCode.newclo, _implementation.Id, target.ToInternalModule(_implementation.ModuleName));
        }

        #region AstExpr Members

        public override bool TryOptimize(CompilerTarget target, out AstExpr expr)
        {
            expr = null;
            return false;
        }

        #endregion
    }
}