text:
/* vi: set sw=4 ts=4: */
/*
 * Calendar implementation for busybox
 *
 * See original copyright at the end of this file
 *
 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
 */

/* BB_AUDIT SUSv3 compliant with -j and -y extensions (from util-linux). */
/* BB_AUDIT BUG: The output of 'cal -j 1752' is incorrect.  The upstream
 * BB_AUDIT BUG: version in util-linux seems to be broken as well. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cal.html */

/* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
 *
 * Major size reduction... over 50% (>1.5k) on i386.
 */

//usage:#define cal_trivial_usage
//usage:       "[-jy] [[MONTH] YEAR]"
//usage:#define cal_full_usage "\n\n"
//usage:       "Display a calendar\n"
//usage:     "\n	-j	Use julian dates"
//usage:     "\n	-y	Display the entire year"

#include "libbb.h"
#include "unicode.h"

/* We often use "unsigned" intead of "int", it's easier to div on most CPUs */

#define	THURSDAY		4		/* for reformation */
#define	SATURDAY		6		/* 1 Jan 1 was a Saturday */

#define	FIRST_MISSING_DAY	639787		/* 3 Sep 1752 */
#define	NUMBER_MISSING_DAYS	11		/* 11 day correction */

#define	MAXDAYS			42		/* max slots in a month array */
#define	SPACE			-1		/* used in day array */

static const unsigned char days_in_month[] ALIGN1 = {
	0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

static const unsigned char sep1752[] ALIGN1 = {
		 1,	2,	14,	15,	16,
	17,	18,	19,	20,	21,	22,	23,
	24,	25,	26,	27,	28,	29,	30
};

/* Set to 0 or 1 in main */
#define julian ((unsigned)option_mask32)

/* leap year -- account for Gregorian reformation in 1752 */
static int leap_year(unsigned yr)
{
	if (yr <= 1752)
		return !(yr % 4);
	return (!(yr % 4) && (yr % 100)) || !(yr % 400);
}

/* number of centuries since 1700, not inclusive */
#define	centuries_since_1700(yr) \
	((yr) > 1700 ? (yr) / 100 - 17 : 0)

/* number of centuries since 1700 whose modulo of 400 is 0 */
#define	quad_centuries_since_1700(yr) \
	((yr) > 1600 ? ((yr) - 1600) / 400 : 0)

/* number of leap years between year 1 and this year, not inclusive */
#define	leap_years_since_year_1(yr) \
	((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))

static void center(char *, unsigned, unsigned);
static void day_array(unsigned, unsigned, unsigned *);
static void trim_trailing_spaces_and_print(char *);

static void blank_string(char *buf, size_t buflen);
static char *build_row(char *p, unsigned *dp);

#define	DAY_LEN		3		/* 3 spaces per day */
#define	J_DAY_LEN	(DAY_LEN + 1)
#define	WEEK_LEN	20		/* 7 * 3 - one space at the end */
#define	J_WEEK_LEN	(WEEK_LEN + 7)
#define	HEAD_SEP	2		/* spaces between day headings */

int cal_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cal_main(int argc UNUSED_PARAM, char **argv)
{
	struct tm zero_tm;
	time_t now;
	unsigned month, year, flags, i;
	char *month_names[12];
	/* normal heading: */
	/* "Su Mo Tu We Th Fr Sa" */
	/* -j heading: */
	/* " Su  Mo  Tu  We  Th  Fr  Sa" */
	char day_headings[ENABLE_UNICODE_SUPPORT ? 28 * 6 : 28];
	IF_UNICODE_SUPPORT(char *hp = day_headings;)
	char buf[40];

	init_unicode();

	flags = getopt32(argv, "jy");
	/* This sets julian = flags & 1: */
	option_mask32 &= 1;
	month = 0;
	argv += optind;

	if (!argv[0]) {
		struct tm *ptm;

		time(&now);
		ptm = localtime(&now);
		year = ptm->tm_year + 1900;
		if (!(flags & 2)) { /* no -y */
			month = ptm->tm_mon + 1;
		}
	} else {
		if (argv[1]) {
			if (argv[2]) {
				bb_show_usage();
			}
			if (!(flags & 2)) { /* no -y */
				month = xatou_range(*argv, 1, 12);
			}
			argv++;
		}
		year = xatou_range(*argv, 1, 9999);
	}

	blank_string(day_headings, sizeof(day_headings) - 7 + 7*julian);

	i = 0;
	do {
		zero_tm.tm_mon = i;
		/* full month name according to locale */
		strftime(buf, sizeof(buf), "%B", &zero_tm);
		month_names[i] = xstrdup(buf);

		if (i < 7) {
			zero_tm.tm_wday = i;
			/* abbreviated weekday name according to locale */
			strftime(buf, sizeof(buf), "%a", &zero_tm);
#if ENABLE_UNICODE_SUPPORT
			if (julian)
				*hp++ = ' ';
			{
				char *two_wchars = unicode_conv_to_printable_fixedwidth(/*NULL,*/ buf, 2);
				strcpy(hp, two_wchars);
				free(two_wchars);
			}
			hp += strlen(hp);
			*hp++ = ' ';
#else
			strncpy(day_headings + i * (3+julian) + julian, buf, 2);
#endif
		}
	} while (++i < 12);
	IF_UNICODE_SUPPORT(hp[-1] = '\0';)

	if (month) {
		unsigned row, len, days[MAXDAYS];
		unsigned *dp = days;
		char lineout[30];

		day_array(month, year, dp);
		len = sprintf(lineout, "%s %d", month_names[month - 1], year);
		printf("%*s%s\n%s\n",
			   ((7*julian + WEEK_LEN) - len) / 2, "",
			   lineout, day_headings);
		for (row = 0; row < 6; row++) {
			build_row(lineout, dp)[0] = '\0';
			dp += 7;
			trim_trailing_spaces_and_print(lineout);
		}
	} else {
		unsigned row, which_cal, week_len, days[12][MAXDAYS];
		unsigned *dp;
		char lineout[80];

		sprintf(lineout, "%u", year);
		center(lineout,
			   (WEEK_LEN * 3 + HEAD_SEP * 2)
			   + julian * (J_WEEK_LEN * 2 + HEAD_SEP
						   - (WEEK_LEN * 3 + HEAD_SEP * 2)),
			   0);
		puts("\n");		/* two \n's */
		for (i = 0; i < 12; i++) {
			day_array(i + 1, year, days[i]);
		}
		blank_string(lineout, sizeof(lineout));
		week_len = WEEK_LEN + julian * (J_WEEK_LEN - WEEK_LEN);
		for (month = 0; month < 12; month += 3-julian) {
			center(month_names[month], week_len, HEAD_SEP);
			if (!julian) {
				center(month_names[month + 1], week_len, HEAD_SEP);
			}
			center(month_names[month + 2 - julian], week_len, 0);
			printf("\n%s%*s%s", day_headings, HEAD_SEP, "", day_headings);
			if (!julian) {
				printf("%*s%s", HEAD_SEP, "", day_headings);
			}
			bb_putchar('\n');
			for (row = 0; row < (6*7); row += 7) {
				for (which_cal = 0; which_cal < 3-julian; which_cal++) {
					dp = days[month + which_cal] + row;
					build_row(lineout + which_cal * (week_len + 2), dp);
				}
				/* blank_string took care of nul termination. */
				trim_trailing_spaces_and_print(lineout);
			}
		}
	}

	fflush_stdout_and_exit(EXIT_SUCCESS);
}

/*
 * day_array --
 *	Fill in an array of 42 integers with a calendar.  Assume for a moment
 *	that you took the (maximum) 6 rows in a calendar and stretched them
 *	out end to end.  You would have 42 numbers or spaces.  This routine
 *	builds that array for any month from Jan. 1 through Dec. 9999.
 */
static void day_array(unsigned month, unsigned year, unsigned *days)
{
	unsigned long temp;
	unsigned i;
	unsigned day, dw, dm;

	memset(days, SPACE, MAXDAYS * sizeof(int));

	if ((month == 9) && (year == 1752)) {
		/* Assumes the Gregorian reformation eliminates
		 * 3 Sep. 1752 through 13 Sep. 1752.
		 */
		unsigned j_offset = julian * 244;
		size_t oday = 0;

		do {
			days[oday+2] = sep1752[oday] + j_offset;
		} while (++oday < sizeof(sep1752));

		return;
	}

	/* day_in_year
	 * return the 1 based day number within the year
	 */
	day = 1;
	if ((month > 2) && leap_year(year)) {
		++day;
	}

	i = month;
	while (i) {
		day += days_in_month[--i];
	}

	/* day_in_week
	 * return the 0 based day number for any date from 1 Jan. 1 to
	 * 31 Dec. 9999.  Assumes the Gregorian reformation eliminates
	 * 3 Sep. 1752 through 13 Sep. 1752.  Returns Thursday for all
	 * missing days.
	 */
	temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1) + day;
	if (temp < FIRST_MISSING_DAY) {
		dw = ((temp - 1 + SATURDAY) % 7);
	} else {
		dw = (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
	}

	if (!julian) {
		day = 1;
	}

	dm = days_in_month[month];
	if ((month == 2) && leap_year(year)) {
		++dm;
	}

	do {
		days[dw++] = day++;
	} while (--dm);
}

static void trim_trailing_spaces_and_print(char *s)
{
	char *p = s;

	while (*p) {
		++p;
	}
	while (p != s) {
		--p;
		if (!isspace(*p)) {
			p[1] = '\0';
			break;
		}
	}

	puts(s);
}

static void center(char *str, unsigned len, unsigned separate)
{
	unsigned n = strlen(str);
	len -= n;
	printf("%*s%*s", (len/2) + n, str, (len/2) + (len % 2) + separate, "");
}

static void blank_string(char *buf, size_t buflen)
{
	memset(buf, ' ', buflen);
	buf[buflen-1] = '\0';
}

static char *build_row(char *p, unsigned *dp)
{
	unsigned col, val, day;

	memset(p, ' ', (julian + DAY_LEN) * 7);

	col = 0;
	do {
		day = *dp++;
		if (day != SPACE) {
			if (julian) {
				++p;
				if (day >= 100) {
					*p = '0';
					p[-1] = (day / 100) + '0';
					day %= 100;
				}
			}
			val = day / 10;
			if (val > 0) {
				*p = val + '0';
			}
			*++p = day % 10 + '0';
			p += 2;
		} else {
			p += DAY_LEN + julian;
		}
	} while (++col < 7);

	return p;
}

/*
 * Copyright (c) 1989, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Kim Letkeman.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


text:
<?php if(!$this->tpl_var['userhash']){ ?>
<?php $this->_compileInclude('header'); ?>

<?php $this->_compileInclude('nav'); ?>

			<?php $this->_compileInclude('menu'); ?>

<?php } ?>

<a href="index.php?<?php echo $this->tpl_var['_app']; ?>-master"><?php echo $this->tpl_var['apps'][$this->tpl_var['_app']]['appname']; ?> /

<a href="index.php?<?php echo $this->tpl_var['_app']; ?>-master-module">用户模型 /

修改模型

	    	<form action="?user-master-module-modify" method="post" class="form-horizontal">
				<fieldset>
					<legend><?php echo $this->tpl_var['module']['modulename']; ?></legend>

						模型名称:

							<input type="text" size="40" name="args[modulename]" needle="needle" datatype="username" id="modulename" value="<?php echo $this->tpl_var['module']['modulename']; ?>"/>

				        模型描述:

		          			<textarea rows="7" class="input-xxlarge" name="args[moduledescribe]" id="moduledescribe"><?php echo $this->tpl_var['module']['moduledescribe']; ?></textarea>

							<button class="btn btn-primary" type="submit">提交</button>
				        	<input type="hidden" name="moduleid" value="<?php echo $this->tpl_var['module']['moduleid']; ?>"/>
				        	<input type="hidden" name="modifymodule" value="1"/>
							<input type="hidden" name="page" value="<?php echo $this->tpl_var['page']; ?>"/>
							<?php $aid = 0;
 foreach($this->tpl_var['search'] as $key => $arg){
 $aid++; ?>
							<input type="hidden" name="search[<?php echo $key; ?>]" value="<?php echo $arg; ?>"/>
							<?php } ?>

				</fieldset>
			</form>
<?php if(!$this->tpl_var['userhash']){ ?>

<?php } ?>

redpajama_set_name: RedPajamaGithub


text:
var Sequelize = require('sequelize');

if (process.env.DATABASE_URL) {
  var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/);

  Sequelize.DB = new Sequelize(match[5], match[1], match[2], {
    dialect: 'postgres',
    protocol: 'postgres',
    port: match[4],
    host: match[3],
    logging: true
  });
} else {
  Sequelize.DB = new Sequelize('database', 'username', 'password', {
    dialect: 'sqlite',
    storage: 'db.sqlite',
    logging: false
  });
}

require('./models');

Sequelize.DB.authenticate();


text:
import os
from setuptools import setup

setup(
    name="SIDR",
    version="0.0.2a2",
    author="Duncan Murdock",
    author_email="me@duncanmurdock.name",
    description=("Sequence Idenification using Decision tRees; a tool to classify DNA reads using machine learning models."),
    license="MIT",
    keywords="console tool bioinformatics",
    url="https://github.com/damurdock/SIDR",
    packages=['sidr', 'tests'],
    classifiers=[
        "Development Status :: 3 - Alpha",
        'Environment :: Console',
        "Topic :: Scientific/Engineering :: Bio-Informatics",
        "License :: OSI Approved :: MIT License",
        "Intended Audience :: Science/Research",
    ],
    install_requires=["NumPy<=1.14.5", "SciPy", "pysam>=0.8.1", "BioPython", "scikit-learn", "click", "pandas"],
    long_description=open("README.rst").read(),
    entry_points={
        'console_scripts': [
            'sidr = sidr.cli:cli',
        ],
    })


text:
'use strict';

const assert = require('assert');
const Pool = require('../lib/pool.js').Pool;

describe('Pool', function() {
  const callbackTask = (param, callback) => {
    setImmediate(() => callback(null, param * 2));
  };

  const promiseTask = param => Promise.resolve(param * 2);

  it('should work promise style', function() {
    const pool = new Pool({ limit: 5 });
    const task = pool.promise.wrap(promiseTask);
    const tasks = [];
    let running = 0;
    let maxRun = 0;
    for (let i = 0; i < 100; i++) {
      tasks.push(task(i).on('run', () => {
        running++;
        maxRun = Math.max(running, maxRun);
      }).then(r => {
        running--;
        assert.equal(r, i * 2);
      }));
    }
    return Promise.all(tasks).then(() => assert.equal(maxRun, 5));
  });

  it('should work callback style', function() {
    const pool = new Pool({ limit: 5 });
    const task = pool.wrap(callbackTask);
    const tasks = [];
    let running = 0;
    let maxRun = 0;
    for (let i = 0; i < 100; i++) {
      tasks.push(task(i, (e, r) => {
        running--;
        assert.equal(r, i * 2);
      }).on('run', () => {
        running++;
        maxRun = Math.max(running, maxRun);
      }));
    }
    return Promise.all(tasks).then(() => assert.equal(maxRun, 5));
  });

  it('should emit timeout when a task exceeds the timeout limit', function(done) {
    const pool = new Pool({ timeout: 100 });
    const task = pool.wrap(() => {})();
    pool.on('timeout', (emitted) => {
      assert.equal(task, emitted);
      done();
    });
  });
});


text:
<?php
namespace app\controllers;

use app\helpers\GoogleSpreadsheetClient;
use Google_Client;
use Google_Service_Sheets;
use Google_Service_Sheets_ValueRange;
use Google_Service_Sheets_ValueServiceOptions;
use Yii;
use yii\base\Exception;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use GuzzleHttp\Psr7;
use yii\web\HttpException;

class VolunteersController extends Controller
{
    public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    private function buildItemData($item, $answer) {
        $result = [];
        if ($item['type'] === 'text') {
            array_push($result, ['question' => $item['title'], 'answer' => $answer]);
        }
        else if ($item['type'] === 'date') {
            array_push($result, ['question' => $item['title'], 'answer' => $answer]);
        }
        else if ($item['type'] === 'checkbox') {
            array_push($result, ['question' => $item['title'], 'answer' => $answer ? 'да' : 'нет']);
        }
        else if ($item['type'] === 'textarea') {
            array_push($result, ['question' => $item['title'], 'answer' => $answer]);
        }
        else if ($item['type'] === 'group') {
            if ($item['subtype'] === 'checkbox') {
                foreach($item['items'] as $subitem) {
                    $answerTexts = [];
                    foreach($item['options'] as $option) {
                        if ($answer[$subitem['name']][$option['name']] === true) {
                            array_push($answerTexts, $option['title']);
                        }
                    }
                    array_push($result, ['question' => $subitem['title'], 'answer' => implode(', ', $answerTexts)]);
                }
            }
            else if ($item['subtype'] === 'scale') {
                foreach($item['items'] as $subitem) {
                    array_push($result, ['question' => $subitem['title'], 'answer' => $answer[$subitem['name']]]);
                }
            }
        }
        else if ($item['type'] === 'radio') {
            $answerOption = array_values(array_filter($item['options'], function ($option) use ($answer) {
                return $option['value'] === $answer;
            }))[0];
            array_push($result, ['question' => $item['title'], 'answer' => $answerOption['title']]);
        }
        return $result;
    }

    private function buildPageData($page, $answers) {
        return $this->buildItemListData($page['items'], $answers[$page['name']]);
    }

    private function buildItemListData($itemList, $answers) {
        $result = [];
        foreach($itemList as $item) {
            if (isset($item['name'])) {
                $result = array_merge($result, $this->buildItemData($item, $answers[$item['name']]));
            }
            else if ($item['type'] === 'row') {
                $result = array_merge($result, $this->buildItemListData($item['content'], $answers));
            }
        }
        return $result;
    }

    private function buildData($pages, $answers) {
        $result = [];
        foreach($pages as $page) {
            $result = array_merge($result, $this->buildPageData($page, $answers));
        }
        return $result;
    }

    public function actionSendQuestionnaire() {
        $config = parse_ini_file(Yii::getAlias('@app') .  '/env.ini', true);

        Yii::$app->language = 'ru-RU';

        $settings = json_decode(\Yii::t('texts', 'volunteers/questionnaire/settings'), true);
        $response = json_decode(Yii::$app->request->getRawBody(), true);

        if ($settings['version'] !== $response['version']) {
            throw new BadRequestHttpException('Questionnaire and response versions are different');
        }

        $pages = $settings['pages'];
        $answers = $response['answers'];

        $userData = $this->buildData($pages, $answers);

        $DOC_ID = @$config['questionnaire_google_docid'] ?: null;
        $SHEET = 'version' . $settings['version'];

        define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
        define('CLIENT_SECRET_PATH', Yii::getAlias('@app') . '/questionnaire-google-secret.json');
        define('SCOPES', implode(' ', array(
            Google_Service_Sheets::SPREADSHEETS)
        ));

        $client = new Google_Client();
        $client->setApplicationName(APPLICATION_NAME);
        $client->setScopes(SCOPES);
        $client->setAuthConfig(CLIENT_SECRET_PATH);
        $client->setAccessType('offline');

        // Get the API client and construct the service object.
        $spreadsheet = new GoogleSpreadsheetClient($DOC_ID, $client);

        // Generate header it it doesn't exists
        $value = $spreadsheet->readCell($SHEET, 'A1');
        if ($value === null) {
            $header = ['language'];
            foreach($userData as $item) {
                array_push($header, $item['question']);
            }
            if (count($header) < 0) {
                throw new BadRequestHttpException('It should be at least one answer to generate table header');
            }
            $spreadsheet->updateRange(
                $SHEET,
                'A1:' . $spreadsheet->columnIndexToName(count($header) - 1) .  '1',
                [$header]
            );
        }

        // Generate answer row and append it to a table
        $row = [$answers['language']];
        foreach($userData as $item) {
            array_push($row, $item['answer']);
        }
        if (count($row) < 0) {
            throw new BadRequestHttpException('It should be at least one answer to write response');
        }
        $spreadsheet->appendRange(
            $SHEET,
            'A1:' . $spreadsheet->columnIndexToName(count($row) - 1) .  '1',
            [$row]
        );

    }
}


text:
'use strict';

/**
 * 定义用户控制器
 */
define(function(require, exports, module) {

    module.exports = function(app) {

        //var xhr = require('common/service/xhr');

        app.register.controller('userListCtrl', function($scope, $http, $rootScope) {
			$rootScope.title = "UserList Page";
			$scope.name = "Lo Page";
        });
    }
});


text:
package com.adobe.acs.commons.packaging;

import org.osgi.annotation.versioning.ProviderType;

import org.apache.jackrabbit.vault.fs.api.PathFilterSet;
import org.apache.jackrabbit.vault.packaging.JcrPackage;
import org.apache.jackrabbit.vault.packaging.JcrPackageManager;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.Version;
import org.apache.sling.api.resource.Resource;

import javax.jcr.RepositoryException;
import javax.jcr.Session;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Helper interface for dynamic package creation.
 */
@ProviderType
@SuppressWarnings("squid:S1214")
public interface PackageHelper {
    /**
     * JCR Path to default ACS thumbnail resource.
     */
    String DEFAULT_PACKAGE_THUMBNAIL_RESOURCE_PATH =
            "/apps/acs-commons/components/utilities/packager/definition/package-thumbnail.png";

    /**
     *  None: If conflicting package exists; fail to create a new package.
     *  Replace: If a conflicting package exists; remove that package and create a new w updated params.
     *  IncrementVersion: If a conflict package exists; increment the package minor version to the next free minor.
     */
    @SuppressWarnings("squid:S00115")
    enum ConflictResolution {
        None,
        Replace,
        IncrementVersion
    }

    /**
     * Adds the thumbnail resource to the package as the package thumbnail.
     *
     * If the thumbnailResource is null or not a valid thumbnail resource, a default ACS Package thumbnail will be
     * used.
     *
     * @param jcrPackage The package to add the thumbnail to.
     * @param thumbnailResource The JCR resource that is the thumbnail to be used as the package's thumbnail
     */
    void addThumbnail(JcrPackage jcrPackage, Resource thumbnailResource);

    /**
     * Derives the next package version to use based on the input params and the existing package versions matching
     * the input Package group and name. Next version increments "minor" version only.
     *
     * Ex. 1.0.0 ~> 1.1.0
     *     3.22.0 ~> 3.23.0
     *
     * If the param version's major is greater than the largest existing package version in jcr,
     * then the param version will be used.
     *
     * Ex. param ~> 2.0.0, largest in jcr ~> 1.40.0; returned version will be 2.0.0
     *
     * @param jcrPackageManager JcrPackageManager object
     * @param groupName package group name
     * @param name package name
     * @param version package version
     * @return the next version based on existing versions in the jcr
     * @throws RepositoryException
     */
    Version getNextVersion(JcrPackageManager jcrPackageManager, String groupName, String name,
                           String version) throws RepositoryException;

    /**
     * Deletes the package node from the repository. This does NOT uninstall the package, rather deletes the
     * package node under /etc/packages/[package-group]
     *
     * @param jcrPackageManager JcrPackageManager object
     * @param groupName package group name
     * @param name package name
     * @param version package version
     * @throws RepositoryException
     */
    void removePackage(JcrPackageManager jcrPackageManager,
                       String groupName, String name, String version) throws RepositoryException;

    /**
     *
     * @param pathFilterSets the pathFilterSets that define package
     * @param session JCR Session obj; must have access to create packages under /etc/packages
     * @param groupName package group name
     * @param name package name
     * @param version package version
     * @param conflictResolution determines how package creation will be handled in the event of an existing package
     *                           of the same package group, package name, and version class
     * @param packageDefinitionProperties properties that will be added to the package definition
     * @return the jcr package that was created, or null
     * @throws IOException
     * @throws RepositoryException
     */
    JcrPackage createPackageFromPathFilterSets(final Collection<PathFilterSet> pathFilterSets, final Session session,
                                               final String groupName, final String name, String version,
                                               final ConflictResolution conflictResolution,
                                               final Map<String, String> packageDefinitionProperties)
            throws IOException, RepositoryException;

    /**
     *
     * @param resources the resources to include in the package
     * @param session JCR Session obj; must have access to create packages under /etc/packages
     * @param groupName package group name
     * @param name package name
     * @param version package version
     * @param conflictResolution determines how package creation will be handled in the event of an existing package
     *                           of the same package group, package name, and version class
     * @param packageDefinitionProperties properties that will be added to the package definition
     * @return the jcr package that was created, or null
     * @throws IOException
     * @throws RepositoryException
     */
    JcrPackage createPackage(final Collection<Resource> resources, final Session session,
                                     final String groupName, final String name, String version,
                                     final ConflictResolution conflictResolution,
                                     final Map<String, String> packageDefinitionProperties)
            throws IOException, RepositoryException;

    /**
     * returns a list of the JCR resource paths includes in the built JcrPackage
     * @param jcrPackage the jcr package
     * @return a list of absolute (starting with /) paths of the JCR resources included in the package
     * @throws IOException
     * @throws RepositoryException
     */
    List<String> getContents(JcrPackage jcrPackage) throws IOException, RepositoryException, PackageException;

    /**
     * Returns the JSON to return in the event of a successful packaging.
     *
     * @param jcrPackage the successfully created jcr package
     * @return a string representation of JSON to write to response
     */
    String getSuccessJSON(JcrPackage jcrPackage) throws RepositoryException;

    /**
     * Returns the JSON to return reporting what the packager definition will include for filterSet roots.
     *
     * @param resources the resources that represent the filterSet roots
     * @return a string representation of JSON to write to response
     */
    String getPreviewJSON(final Collection<Resource> resources);

    /**
     * Returns the JSON to return reporting what the packager definition will include for the filterSets.
     *
     * @param pathFilterSets the pathFilterSets of the package
     * @return a string representation of JSON to write to response
     */
    String getPathFilterSetPreviewJSON(final Collection<PathFilterSet> pathFilterSets);

    /**
     * Returns the JSON to return in the event of an unsuccessful packaging.
     *
     * @param msg the error message to display
     * @return a string representation of JSON to write to response
     */
    String getErrorJSON(String msg);

    /**
     * Returns the JSON to return reporting what the packager definition will include for filterSet roots.
     *
     * @param paths the paths that represent the filterSet roots
     * @return a string representation of JSON to write to response
     */
    String getPreviewJSONForPaths(Collection<String> paths);

    /**
    *
    * @param paths the resources to include in the package
    * @param session JCR Session obj; must have access to create packages under /etc/packages
    * @param groupName package group name
    * @param name package name
    * @param version package version
    * @param conflictResolution determines how package creation will be handled in the event of an existing package
    *                           of the same package group, package name, and version class
    * @param packageDefinitionProperties properties that will be added to the package definition
    * @return the jcr package that was created, or null
    * @throws IOException
    * @throws RepositoryException
    */
    JcrPackage createPackageForPaths(Collection<String> paths, Session session, String groupName, String name,
            String version, ConflictResolution conflictResolution, Map<String, String> packageDefinitionProperties) throws IOException, RepositoryException;
}


text:
First off all, you need `config.txt` for the bot to work.
Copy paste this to the file config.txt
```
[Token]
token = your token here

[Settings]
prefix = >
```


text:
var objectMap = function (o, handler) {
    var res = {};
    for (var key in o) {
        res[key] = handler(o[key])
    }
    return res;
};

var ReportsViewModel = function () {
    var self = this;
    var url = "/Home/GetAllReports";
    var datafromserver = "";
    //
    /*var getSubStationName = function (Id) {
        var urlSubName = "/Home/GetSubStationById/" + Id;
        $.getJSON(urlSubName, {}, function (data) {
            var sub = new SubStation(data);
            return meter;
        });
    };*/

    var getAllReports = function () {
        $.getJSON(url, {}, function (data) {

            /**
                        var datastr = JSON.stringify(ko.toJS(data));
            **/
            var objectsArray = ko.utils.arrayMap(data, function (item) {

                var reports = new Reports(item);
                return reports;
            });

            self.ReportsArray(objectsArray);

        });
    };

    self.ReportsArray = ko.observableArray([]);

    function Reports(data) {
        var self = this;
        self.Id = data.Id;
        self.Name = data.Name;

        var date = new Date(parseInt(data.ReportDate.substr(6)));
        self.ReportDate = date.toISOString().substring(0, 10);

        self.CreatedDate = data.CreatedDate;
        //self.ReportDate = data.ReportDate;
        self.SupplierId = data.SupplierId;
    }

    function Supplier(data) {
        var self = this;
        self.Id = data.Id;
        self.Name = data.Name;
    }

    // Public operations

    getAllReports();
}

ko.applyBindings(new ReportsViewModel())


text:
/// http.js --- Deals with HTTP requests in the browser
//
// Copyright (c) 2012 Quildreen Motta
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// Module iris.http

//// -- Dependencies ----------------------------------------------------------
var utils  = require('./utils')
var cassie = require('cassie')

//// -- Aliases ---------------------------------------------------------------
var keys               = Object.keys
var call               = Function.prototype.call
var to_array           = call.bind([].slice)
var class_of           = call.bind({}.toString)
var serialise          = utils.serialise
var build_query_string = utils.build_query_string
var register           = cassie.register
var Promise            = cassie.Promise

//// -- Helpers ---------------------------------------------------------------

///// Function make_xhr
// Creates a new XMLHttpRequest object that can be used for the current
// engine.
//
// make-xhr :: () -> XMLHttpRequest
var make_xhr = function() {
                 return 'XMLHttpRequest' in this?
                        /* W3C? */ function() {
                                     return new XMLHttpRequest() }
                        :
                        /* IE? */  function() {
                                     return new ActiveXObject('Microsoft.XMLHTTP') }}()

///// Function object_p
// Is the given `subject' an `Object'?
//
// object? :: a -> Bool
function object_p(subject) {
  return class_of(subject) == '[object Object]' }

///// Function status_type
// Returns the firendly HTTP status name for the class of HTTP statuses
// the given `status' belongs to.
//
// status-type :: Number -> String
function status_type(status) {
  var type = status.toString().charAt(0) - 1
  return statuses[type] }

///// Function serialise_for_type
// Serialises the given data according to the specified MIME type.
//
// serialise-for-type :: String, { String -> String } -> String
function serialise_for_type(mime, data) {
  return mime == 'application/json'?  JSON.stringify(data)
  :      /* otherwise */              serialise(data) }

///// Function normalise_status
// Normalises HTTP response statuses for IE.
//
// normalise-status :: Number -> Number
function normalise_status(status) {
  return status == 1223?   204
  :      /* otherwise */   status }

// Whether the engine supports XHR2's `timeout' attribute
//
// support-timeout? :: Bool
var support_timeout_p = 'timeout' in make_xhr()

// A regular expression matching successful HTTP response codes
//
// success :: RegExp
var success = /2\d{2}/

// A regular expression matching client and server error HTTP response
// codes.
//
// error :: RegExp
var error = /[45]\d{2}/

// A list of friendly name for the classes of HTTP status codes.
//
// statuses :: [String]
var statuses = [ 'information'
               , 'success'
               , 'redirected'
               , 'client-error'
               , 'server-error' ]

// A list of friendly name for a request's lifecycle's state.
//
// state-map :: [String]
var state_map = [ 'unsent'
                , 'opened'
                , 'headers-received'
                , 'loading'
                , 'completed' ]

//// -- Public interface ------------------------------------------------------

///// Data active
// A list of all active promises for HTTP requests.
//
// active :: [PromiseP]
var active = []

///// Object PromiseP <| Promise
// A promise for an HTTP request.
//
// PromiseP :: Promise <| { "client"  -> XMLHttpRequest
//                        , "uri"     -> String
//                        , "options" -> { String -> String }}
var PromiseP = Promise.derive({

  ////// Function init
  // Initialises an instance of a PromiseP.
  //
  // init! :: @this:Object* -> this
  init:
  function _init(client, uri, options) {
    Promise.init.call(this)
    this.client  = client
    this.uri     = uri
    this.options = options

    return this }

  ////// Function fire
  // Immediately invokes all functions registered for the given `event',
  // even if the promise hasn't been resolved yet.
  //
  // Different from flushing, the invoked callbacks are not removed from
  // the event's list of callbacks. So a callback may `fire' multiple
  // times.
  //
  // fire :: @this:PromiseP, String, Any... -> this
, fire:
  function _fire(event) {
    var args, callbacks, i, len
    args      = to_array(arguments, 1)
    callbacks = this.callbacks[event] || []

    for (i = 0, len = callbacks.length; i < len; ++i)
      callbacks[i].apply(this, args)

    return this }

  ////// Function forget
  // Aborts a request and resolves the promise with a `forgotten`
  // failure.
  //
  // forget :: @this:PromiseP* -> this
, forget:
  function _forget() {
    this.client.abort()
    return this.flush('forgotten', 'failed').fail('forgotten') }

  ////// Function timeout
  // Specifies the maximum amount of time (in seconds) the promise can
  // take to be fulfilled. If it takes more time than time, the promise
  // fails with a `timeout' error.
  //
  // timeout :: @this:PromiseP*, Number -> this
, timeout: support_timeout_p?  function _timeout(delay) {
                                 this.timeout = delay * 1000
                                 return this }

         : /* otherwise */     function _timeout(delay) {
                                 this.clearTimer()
                                 this.timer = setTimeout( function() {
                                                            this.flush('timeouted', 'failed')
                                                                .fail('timeouted')
                                                            this.forget() }.bind(this)
                                                        , delay * 1000 )
                                 return this }

  ////// Function clear_timer
  // Stops the timer for the promise. If one was previously set by
  // invoking `timeout'.
  //
  // clear-timer :: @this:Promise* -> this
, clearTimer: support_timeout_p?  function _clear_timer() {
                                     this.timeout = 0
                                     return this }

             : /* otherwise */     Promise.clearTimer

// Generalised HTTP statuses
, information : register('status:information')
, success     : register('status:success')
, redirected  : register('status:redirected')
, clientError : register('status:client-error')
, serverError : register('status:server-error')

// Ready states
, unsent          : register('state:unsent')
, opened          : register('state:opened')
, headersReceived : register('state:headers-received')
, loading         : register('state:loading')
, completed       : register('state:completed')

// General failure statuses
, errored : register('errored')
})
PromiseP.clear_timer = PromiseP.clearTimer

///// Function request
// Makes an HTTP request to the given URI, and returns a `PromiseP' that
// such request will be fulfilled.
//
// Any actual work is carried over after the promise is returned from
// this method. As such, the user can freely manipulate the promise
// object synchronously before the connection with the endpoint is even
// opened.
//
// Aside from the event queues flushed after the promise has been
// fulfilled (or failed), the promise will also fire events from time to
// time, or depending on certain occurrences — as soon as they
// happen. Callbacks registered for those events may be invoked more
// than once, and may be invoked before the promise is fulfilled.
//
// request :: String, { String -> String } -> PromiseP
function request(uri, options) {
  var client, promise, method, serialise_body_p, mime
  options          = options         || {}
  options.headers  = options.headers || {}
  method           = (options.method || 'GET').toUpperCase()
  uri              = build_uri(uri, options.query, options.body)

  options.headers['X-Requested-With'] = 'XMLHttpRequest'

  serialise_body_p = object_p(options.body)
  if (serialise_body_p) {
    mime = options.headers['Content-Type'] || 'application/x-www-form-urlencoded'
    options.body = serialise_for_type(mime, options.body)
    options.headers['Content-Type'] = mime }

  client  = make_xhr()
  promise = PromiseP.make(client, uri, options)

  setup_listeners()

  setTimeout(function() {
    client.open(method, uri, true, options.username, options.password)
    setup_headers(options.headers || {})
    client.send(options.body) })

  active.push(promise)

  return promise

  // Sticks a serialised query and body object at the end of an URI.
  // build-uri :: String, { String -> String }, { String -> String }? -> String
  function build_uri(uri, query, body) {
    uri = build_query_string(uri, query)
    return method == 'GET'?  build_query_string(uri, body)
    :      /* otherwise */   uri }

  // Setups the headers for the HTTP request
  // setup-headers :: { String -> String | [String] } -> Undefined
  function setup_headers(headers) {
    keys(headers).forEach(function(key) {
      client.setRequestHeader(key, headers[key]) })}

  // Generates a handler for the given type of error
  // make-error-handler :: String -> Event -> Undefined
  function make_error_handler(type) { return function(ev) {
    promise.flush(type, 'failed').fail(type, ev) }}

  // Invokes an error handler for the given type
  // raise :: String -> Undefined
  function raise(type) {
    make_error_handler(type)() }

  // Setups the event listeners for the HTTP request client
  // setup-listeners :: () -> Undefined
  function setup_listeners() {
    client.onerror            = make_error_handler('errored')
    client.onabort            = make_error_handler('forgotten')
    client.ontimeout          = make_error_handler('timeouted')
    client.onloadstart        = function(ev){ promise.fire('load:start', ev)    }
    client.onprogress         = function(ev){ promise.fire('load:progress', ev) }
    client.onloadend          = function(ev){ promise.fire('load:end', ev)      }
    client.onload             = function(ev){ promise.fire('load:success', ev)  }
    client.onreadystatechange = function(  ){
                                  var response, status, state
                                  state = client.readyState

                                  promise.fire('state:' + state_map[state])

                                  if (state == 4) {
                                    var binding_state = success.test(status)? 'ok'
                                                      : error.test(status)?   'failed'
                                                      : /* otherwise */       'any'

                                    response = client.responseText
                                    status   = normalise_status(client.status)
                                    active.splice(active.indexOf(promise), 1)
                                    promise.flush('status:' + status)
                                           .flush('status:' + status_type(status))

                                      status == 0?           raise('errored')
                                    : success.test(status)?  promise.bind(response, status)
                                    : error.test(status)?    promise.fail(response, status)
                                    : /* otherwise */        promise.done([response, status]) }}}
}

////// Function request_with_method
// Generates a specialised request function for the given method.
//
// request-with-method :: String -> String, { String -> String } -> PromiseP
function request_with_method(method) { return function(uri, options) {
  options = options || { }
  options.method = method.toUpperCase()
  return request(uri, options) }}

//// -- Exports ---------------------------------------------------------------
module.exports = { PromiseP: PromiseP
                 , request:  request
                 , active:   active
                 , get:      request_with_method('GET')
                 , post:     request_with_method('POST')
                 , put:      request_with_method('PUT')
                 , head:     request_with_method('HEAD')
                 , delete_:  request_with_method('DELETE')
                 , options:  request_with_method('OPTIONS')

                 , internal: { make_xhr: make_xhr }}


text:
require "spec_helper"

describe PDF::Reader::WidthCalculator::Composite do
  it_behaves_like "a WidthCalculator duck type" do
    let!(:font)       { double(:cid_default_width => 50,
                                :cid_widths        => [10,[30,40]])
                      }
    subject           { PDF::Reader::WidthCalculator::Composite.new(font)}
  end
end

describe PDF::Reader::WidthCalculator::Composite, "#glyph_width" do
  context "when font#cid_default_width is defined" do
    let!(:font)       { double(:cid_default_width => 50,
                                :cid_widths        => [10,[30,40]])
                      }
    subject           { PDF::Reader::WidthCalculator::Composite.new(font)}

    context "when the glyph code is provided in cid_widths" do
      it "should return the correct width" do
        subject.glyph_width(10).should == 30
      end
    end
    context "when the glyph code is equal to greater than font#first_char" do
      it "should return the default width" do
        subject.glyph_width(9).should == 50
      end
    end
  end
end


text:
To avoid confusion with alternative route search we talk not about ALT but about
the 'landmarks' algorithm. The landmarks algorithm is like CH a post-import
process which makes routing faster. It is disable by default. To enable it
set e.g. `prepare.lm.weightings=fastest` in the configuration.

The interesting part is that we just have to set a special landmarks WeightApproximator
for (bidirectional) A* and are done. It is important that although a weight
**approximation** is used the landmarks algorithm is still not heuristic per
default. You can make it faster and more heuristical behaving when you set
the epsilon parameter lower than 1.

Currently we limit routing requests using the landmark algorithm, then it is
not possible to cross the borders between EU, Africa, and Asia. All other algorithms are
not affected by this limitation. For landmarks this limitation is important
as we store the weight approximation in a short (two bytes) and for large distances
more bytes would be necessary but e.g. for the world wide case this would
mean several additional GB per weighting.

Furthermore this short value has the problem that smaller distances cannot be
differentiated sometimes which could lead to very slightly suboptimal routes.
If just small areas (country or city) are imported this can be avoided via setting a
the maximum weighting explicitely.


text:
SELECT store_key, order_number, date_ordered
FROM ros.store_orders_fact
WHERE EXISTS (
  SELECT 1
  FROM ros.vendor_dimension
  WHERE ros.vendor_dimension.vendor_key = ros.store_orders_fact.vendor_key)
  AND date_ordered = '2003-01-02';


text:
function trace = l2add( model, trace, toAdd )
%L2ADD Summary of this function goes here
%   Detailed explanation goes here

    if isempty(toAdd)
        return
    end

    % one single result to add
    if ~iscell(toAdd{1})
        try
            interval = toAdd{1};
            if length(toAdd) == 2
                if ispredicate(toAdd{2})
                    pred = toAdd{2};
                else
                    pred = predicate(toAdd{2});
                end
            else
                pred = predicate(toAdd{2}, toAdd{3});
            end
        catch err
            throw(MException('L2:Add', 'Unable to interpret predicate to add.'));
        end

        [validated, err] = model.validate(pred);
        if ~validated
            throw(err);
        end

        try
            for i=interval
                if i > length(trace)
                    trace(i).(pred.name) = [];
                end
                if ~l2.exists(trace, i, pred)
                    trace(i).(pred.name) = [trace(i).(pred.name) pred];
                end
            end
        catch err
            throw(MException('L2:Add', 'Unable to cope with time point ''%i''.', i));
        end

    % cell array with multiple results to add
    else
        for i=1:length(toAdd)
            try
                trace = l2add(model, trace, toAdd{i});
            catch err
                throwAsCaller(err)
            end
        end
    end
end


text:
from __future__ import absolute_import
import os.path

from setuptools import setup
from setuptools import find_packages

from dist_utils import fetch_requirements
from dist_utils import apply_vagrant_workaround

from inquirer_runner import __version__

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
REQUIREMENTS_FILE = os.path.join(BASE_DIR, "requirements.txt")

install_reqs, dep_links = fetch_requirements(REQUIREMENTS_FILE)

apply_vagrant_workaround()
setup(
    name="stackstorm-runner-inquirer",
    version=__version__,
    description=(
        "Inquirer action runner for StackStorm event-driven automation platform"
    ),
    author="StackStorm",
    author_email="info@stackstorm.com",
    license="Apache License (2.0)",
    url="https://stackstorm.com/",
    install_requires=install_reqs,
    dependency_links=dep_links,
    test_suite="tests",
    zip_safe=False,
    include_package_data=True,
    packages=find_packages(exclude=["setuptools", "tests"]),
    package_data={"inquirer_runner": ["runner.yaml"]},
    scripts=[],
    entry_points={
        "st2common.runners.runner": [
            "inquirer = inquirer_runner.inquirer_runner",
        ],
    },
)


text:
    height: 100px;
}

#content textarea.text {
    height: 150px;
}

#mapContainer {
    float: left;
    height: 300px;
    width: 700px;
    margin-top: 5px;
    margin-left: 5px;
    padding: 20px;
    border-width: 3px;
    border-color: #dddddd;
    border-style: solid;
}

#markerContainer {
    float: left;
    font-weight: bold;
    margin-top: 5px;
    height: 70px;
    width: 30px;
    padding: 20px;
    background: #dddddd;
}
#locationContainer:after {
    width: 100%
}
#locationContainer:after {
    content: "";
    display: block;
    clear: both;
}

#addressContainer {
    margin: 10px;
}
#addressContainer label {
    display: inline;
    padding-right: 5px;
}

.dropping_area {
    border-color: gray;
    border-style: dashed;
    border-width: 5px;
}

#bulk_drop {
    width: 500px;
    height: 200px;
}
#bulk_drop .decoration2 {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 500px;
    height: 200px;
}

#bulk_drop .uploader_text {
    font-size: 13px;
    font-weight: bold;
}
#bulk_drop.hover {
    background-color: #ff8;
}


text:
unsigned int Factorial(unsigned int number) {
	return number <= 1 ? number : Factorial(number - 1)*number;
}

TEST_CASE("Factorials are computed", "[factorial]") {
	REQUIRE(Factorial(1) == 1);
	REQUIRE(Factorial(2) == 2);
	REQUIRE(Factorial(3) == 6);
	REQUIRE(Factorial(10) == 3628800);
}
#endif


text:
:D

We're calling them ["pipeable operators"](./pipeable-operators.md), because no one knows what the heck "lettable" means.


text:
package com.ckelsel.android.training;

import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;

import com.ckelsel.android.training.Drag.MoveImgActivity;
import com.ckelsel.android.training.FragmentSample.fragmenthosttab.FragmentTabHostActivity;
import com.ckelsel.android.training.Navigation.navigation;
import com.ckelsel.android.training.AsyncTask.DownloadActivity;
import com.ckelsel.android.training.FragmentSample.dynamic.NewsActivity;
import com.ckelsel.android.training.FragmentSample.statics.StaticFragmentTitle;
import com.ckelsel.android.training.service.DownloadIntentServiceActivity;
import com.ckelsel.android.training.service.LocalServiceActivity;

import java.lang.reflect.Field;

import butterknife.ButterKnife;

public class MainActivity extends ActionBarActivity implements SampleListFragment.OnFragmentInteractionListener {
    private static final String TAG = "MainActivity";

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

        ButterKnife.bind(this);

        getThreeDots();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        addSample();
    }

    private void addSample() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.frame_layout, SampleListFragment.newInstance());
        ft.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return super.onCreateOptionsMenu(menu);
    }

    private void getThreeDots() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");

            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        }
        catch (Exception e) {
            // presumably, not relevant
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        switch (item.getItemId()) {
            case R.id.action_settings:
                Log.i("", "action_settings");
                return true;
                //break;

            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void startActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    @Override
    public void onFragmentInteraction(String id) {
        Log.d(TAG, "onFragmentInteraction " + id);

        DummyContent.DummyItem item = DummyContent.ITEM_MAP.get(id);
        switch (item.toString()) {
            case "Dynamic Fragment":
                startActivity(NewsActivity.class);
                break;
            case "Static Fragment":
                startActivity(StaticFragmentTitle.class);
                break;
            case "Async Task":
                startActivity(DownloadActivity.class);
                break;
            case "Navigation Drawer":
                startActivity(navigation.class);
                break;
            case "FragmentTabHost":
                startActivity(FragmentTabHostActivity.class);
                break;
            case "DownloadIntentServiceActivity":
                startActivity(DownloadIntentServiceActivity.class);
                break;
            case "LocalServiceActivity":
                startActivity(LocalServiceActivity.class);
                break;
            case "MoveImgActivity":
                startActivity(MoveImgActivity.class);
                break;

        }
    }
}


text:
using variant_type = mapbox::util::variant<int, double, bool>;

#include "binary_visitor_impl.hpp"


text:
Session.set("counter", 0);

Template.counter.helpers({
    counter : function () {
        return Session.get("counter");
    }
});

Template.counter.events({
    'click input': function () {
        console.log("You pressed the button");

        var counter = Session.get("counter");
        counter = counter + 1;
        console.log(counter);
        Session.set("counter", counter);
    }
});


text:
using System;

namespace AR.Drone.Client.Configuration
{

    public class GeneralSection : SectionBase
    {
        public GeneralSection(Settings settings) : base(settings, "general")
        {
        }

        public Int32 ConfigurationVersion
        {
            get { return GetInt32("num_version_config"); }
        }

        public Int32 HardwareVersion
        {
            get { return GetInt32("num_version_mb"); }
        }

        public String FirmwareVersion
        {
            get { return GetString("num_version_soft"); }
        }

        public String DroneSerial
        {
            get { return GetString("drone_serial"); }
        }

        public String FirmwareBuildDate
        {
            get { return GetString("soft_build_date"); }
        }

        public String Motor1Soft
        {
            get { return GetString("motor1_soft"); }
        }

        public String Motor1Hard
        {
            get { return GetString("motor1_hard"); }
        }

        public String Motor1Supplier
        {
            get { return GetString("motor1_supplier"); }
        }

        public String Motor2Soft
        {
            get { return GetString("motor2_soft"); }
        }

        public String Motor2Hard
        {
            get { return GetString("motor2_hard"); }
        }

        public String Motor2Supplier
        {
            get { return GetString("motor2_supplier"); }
        }

        public String Motor3Soft
        {
            get { return GetString("motor3_soft"); }
        }

        public String Motor3Hard
        {
            get { return GetString("motor3_hard"); }
        }

        public String Motor3Supplier
        {
            get { return GetString("motor3_supplier"); }
        }

        public String Motor4Soft
        {
            get { return GetString("motor4_soft"); }
        }

        public String Motor4Hard
        {
            get { return GetString("motor4_hard"); }
        }

        public String Motor4Supplier
        {
            get { return GetString("motor4_supplier"); }
        }

        public String ARDroneName
        {
            get { return GetString("ardrone_name"); }
            set { Set("ardrone_name", value); }
        }

        public Int32 FlyingTime
        {
            get { return GetInt32("flying_time"); }
        }

        public Boolean NavdataDemo
        {
            get { return GetBoolean("navdata_demo"); }
            set { Set("navdata_demo", value); }
        }

        public NavdataOptions NavdataOptions
        {
            get { return GetEnum<NavdataOptions>("navdata_options"); }
            set { SetEnum<NavdataOptions>("navdata_options", value); }
        }

        public Int32 ComWatchdog
        {
            get { return GetInt32("com_watchdog"); }
            set { Set("com_watchdog", value); }
        }

        public Boolean Video
        {
            get { return GetBoolean("video_enable"); }
            set { Set("video_enable", value); }
        }

        public Boolean Vision
        {
            get { return GetBoolean("vision_enable"); }
            set { Set("vision_enable", value); }
        }

        public Int32 BatteryVoltageMin
        {
            get { return GetInt32("vbat_min"); }
            set { Set("vbat_min", value); }
        }

        public Int32 LocalTime
        {
            get { return GetInt32("localtime"); }
            set { Set("localtime", value); }
        }
    }

    public class ControlSection : SectionBase
    {
        public ControlSection(Settings settings) : base(settings, "control")
        {
        }

        public String AccsOffset
        {
            get { return GetString("accs_offset"); }
        }

        public String AccsGains
        {
            get { return GetString("accs_gains"); }
        }

        public String GyrosOffset
        {
            get { return GetString("gyros_offset"); }
        }

        public String GyrosGains
        {
            get { return GetString("gyros_gains"); }
        }

        public String Gyros110Offset
        {
            get { return GetString("gyros110_offset"); }
        }

        public String Gyros110Gains
        {
            get { return GetString("gyros110_gains"); }
        }

        public String MagnetoOffset
        {
            get { return GetString("magneto_offset"); }
        }

        public Single MagnetoRadius
        {
            get { return GetSingle("magneto_radius"); }
        }

        public Single GyroOffsetThrX
        {
            get { return GetSingle("gyro_offset_thr_x"); }
        }

        public Single GyroOffsetThrY
        {
            get { return GetSingle("gyro_offset_thr_y"); }
        }

        public Single GyroOffsetThrZ
        {
            get { return GetSingle("gyro_offset_thr_z"); }
        }

        public Int32 PwmRefGyros
        {
            get { return GetInt32("pwm_ref_gyros"); }
        }

        public Int32 OsctunValue
        {
            get { return GetInt32("osctun_value"); }
        }

        public Boolean OsctunTest
        {
            get { return GetBoolean("osctun_test"); }
        }

        public Int32 ControlLevel
        {
            get { return GetInt32("control_level"); }
            set { Set("control_level", value); }
        }

        public Single EulerAngleMax
        {
            get { return GetSingle("euler_angle_max"); }
            set { Set("euler_angle_max", value); }
        }

        public Int32 AltitudeMax
        {
            get { return GetInt32("altitude_max"); }
            set { Set("altitude_max", value); }
        }

        public Int32 AltitudeMin
        {
            get { return GetInt32("altitude_min"); }
            set { Set("altitude_min", value); }
        }

        public Single ControliPhoneTilt
        {
            get { return GetSingle("control_iphone_tilt"); }
            set { Set("control_iphone_tilt", value); }
        }

        public Single ControlVzMax
        {
            get { return GetSingle("control_vz_max"); }
            set { Set("control_vz_max", value); }
        }

        public Single ControlYaw
        {
            get { return GetSingle("control_yaw"); }
            set { Set("control_yaw", value); }
        }

        public Boolean Outdoor
        {
            get { return GetBoolean("outdoor"); }
            set { Set("outdoor", value); }
        }

        public Boolean FlightWithoutShell
        {
            get { return GetBoolean("flight_without_shell"); }
            set { Set("flight_without_shell", value); }
        }

        public Boolean AutonomousFlight
        {
            get { return GetBoolean("autonomous_flight"); }
        }

        public Boolean ManualTrim
        {
            get { return GetBoolean("manual_trim"); }
            set { Set("manual_trim", value); }
        }

        public Single IndoorEulerAngleMax
        {
            get { return GetSingle("indoor_euler_angle_max"); }
            set { Set("indoor_euler_angle_max", value); }
        }

        public Single IndoorControlVzMax
        {
            get { return GetSingle("indoor_control_vz_max"); }
            set { Set("indoor_control_vz_max", value); }
        }

        public Single IndoorControlYaw
        {
            get { return GetSingle("indoor_control_yaw"); }
            set { Set("indoor_control_yaw", value); }
        }

        public Single OutdoorEulerAngleMax
        {
            get { return GetSingle("outdoor_euler_angle_max"); }
            set { Set("outdoor_euler_angle_max", value); }
        }

        public Single OutdoorControlVzMax
        {
            get { return GetSingle("outdoor_control_vz_max"); }
            set { Set("outdoor_control_vz_max", value); }
        }

        public Single OutdoorControlYaw
        {
            get { return GetSingle("outdoor_control_yaw"); }
            set { Set("outdoor_control_yaw", value); }
        }

        public Int32 FlyingMode
        {
            get { return GetInt32("flying_mode"); }
            set { Set("flying_mode", value); }
        }

        public Int32 HoveringRange
        {
            get { return GetInt32("hovering_range"); }
            set { Set("hovering_range", value); }
        }

        public FlightAnimation FlightAnimation
        {
            get { return GetFlightAnimation("flight_anim"); }
            set { Set("flight_anim", value); }
        }
    }

    public class NetworkSection : SectionBase
    {
        public NetworkSection(Settings settings) : base(settings, "network")
        {
        }

        public String SsidSinglePlayer
        {
            get { return GetString("ssid_single_player"); }
            set { Set("ssid_single_player", value); }
        }

        public String SsidMultiPlayer
        {
            get { return GetString("ssid_multi_player"); }
            set { Set("ssid_multi_player", value); }
        }

        public Int32 WifiMode
        {
            get { return GetInt32("wifi_mode"); }
            set { Set("wifi_mode", value); }
        }

        public Int32 WifiRate
        {
            get { return GetInt32("wifi_rate"); }
            set { Set("wifi_rate", value); }
        }

        public String OwnerMac
        {
            get { return GetString("owner_mac"); }
            set { Set("owner_mac", value); }
        }
    }

    public class PicSection : SectionBase
    {
        public PicSection(Settings settings) : base(settings, "pic")
        {
        }

        public Int32 UltrasoundFreq
        {
            get { return GetInt32("ultrasound_freq"); }
            set { Set("ultrasound_freq", value); }
        }

        public Int32 UltrasoundWatchdog
        {
            get { return GetInt32("ultrasound_watchdog"); }
            set { Set("ultrasound_watchdog", value); }
        }

        public Int32 Version
        {
            get { return GetInt32("pic_version"); }
        }
    }

    public class VideoSection : SectionBase
    {
        public VideoSection(Settings settings) : base(settings, "video")
        {
        }

        public Int32 CamifFps
        {
            get { return GetInt32("camif_fps"); }
        }

        public Int32 CodecFps
        {
            get { return GetInt32("codec_fps"); }
            set { Set("codec_fps", value); }
        }

        public Int32 CamifBuffers
        {
            get { return GetInt32("camif_buffers"); }
        }

        public Int32 Trackers
        {
            get { return GetInt32("num_trackers"); }
        }

        public VideoCodecType Codec
        {
            get { return GetEnum<VideoCodecType>("video_codec"); }
            set { SetEnum<VideoCodecType>("video_codec", value); }
        }

        public Int32 Slices
        {
            get { return GetInt32("video_slices"); }
            set { Set("video_slices", value); }
        }

        public Int32 LiveSocket
        {
            get { return GetInt32("video_live_socket"); }
            set { Set("video_live_socket", value); }
        }

        public Int32 StorageSpace
        {
            get { return GetInt32("video_storage_space"); }
        }

        public Int32 Bitrate
        {
            get { return GetInt32("bitrate"); }
            set { Set("bitrate", value); }
        }

        public Int32 MaxBitrate
        {
            get { return GetInt32("max_bitrate"); }
            set { Set("max_bitrate", value); }
        }

        public VideoBitrateControlMode BitrateCtrlMode
        {
            get { return GetEnum<VideoBitrateControlMode>("bitrate_ctrl_mode"); }
            set { SetEnum<VideoBitrateControlMode>("bitrate_ctrl_mode", value); }
        }

        public Int32 BitrateStorage
        {
            get { return GetInt32("bitrate_storage"); }
            set { Set("bitrate_storage", value); }
        }

        public VideoChannelType Channel
        {
            get { return GetEnum<VideoChannelType>("video_channel"); }
            set { SetEnum<VideoChannelType>("video_channel", value); }
        }

        public Boolean OnUsb
        {
            get { return GetBoolean("video_on_usb"); }
            set { Set("video_on_usb", value); }
        }

        public Int32 FileIndex
        {
            get { return GetInt32("video_file_index"); }
            set { Set("video_file_index", value); }
        }
    }

    public class LedsSection : SectionBase
    {
        public LedsSection(Settings settings) : base(settings, "leds")
        {
        }

        public LedAnimation LedAnimation
        {
            get { return GetLedAnimation("leds_anim"); }
            set { Set("leds_anim", value); }
        }
    }

    public class DetectSection : SectionBase
    {
        public DetectSection(Settings settings) : base(settings, "detect")
        {
        }

        public Int32 EnemyColors
        {
            get { return GetInt32("enemy_colors"); }
            set { Set("enemy_colors", value); }
        }

        public Int32 GroundstripeColors
        {
            get { return GetInt32("groundstripe_colors"); }
            set { Set("groundstripe_colors", value); }
        }

        public Int32 EnemyWithoutShell
        {
            get { return GetInt32("enemy_without_shell"); }
            set { Set("enemy_without_shell", value); }
        }

        public Int32 Type
        {
            get { return GetInt32("detect_type"); }
            set { Set("detect_type", value); }
        }

        public Int32 DetectionsSelectH
        {
            get { return GetInt32("detections_select_h"); }
            set { Set("detections_select_h", value); }
        }

        public Int32 DetectionsSelectVHsync
        {
            get { return GetInt32("detections_select_v_hsync"); }
            set { Set("detections_select_v_hsync", value); }
        }

        public Int32 DetectionsSelectV
        {
            get { return GetInt32("detections_select_v"); }
            set { Set("detections_select_v", value); }
        }
    }

    public class SyslogSection : SectionBase
    {
        public SyslogSection(Settings settings) : base(settings, "syslog")
        {
        }

        public Int32 Output
        {
            get { return GetInt32("output"); }
            set { Set("output", value); }
        }

        public Int32 MaxSize
        {
            get { return GetInt32("max_size"); }
            set { Set("max_size", value); }
        }

        public Int32 NbFiles
        {
            get { return GetInt32("nb_files"); }
            set { Set("nb_files", value); }
        }
    }

    public class UserboxSection : SectionBase
    {
        public UserboxSection(Settings settings) : base(settings, "userbox")
        {
        }

        public UserboxCommand Command
        {
            get { return GetUserboxCommand("userbox_cmd"); }
            set { Set("userbox_cmd", value); }
        }
    }

    public class GpsSection : SectionBase
    {
        public GpsSection(Settings settings) : base(settings, "gps")
        {
        }

        public Double Latitude
        {
            get { return GetDouble("latitude"); }
        }

        public Double Longitude
        {
            get { return GetDouble("longitude"); }
        }

        public Double Altitude
        {
            get { return GetDouble("altitude"); }
        }
    }

    public class CustomSection : SectionBase
    {
        public CustomSection(Settings settings) : base(settings, "custom")
        {
        }

        public String ApplicationId
        {
            get { return GetString("application_id"); }
            set { Set("application_id", value); }
        }

        public String ApplicationDescription
        {
            get { return GetString("application_desc"); }
            set { Set("application_desc", value); }
        }

        public String ProfileId
        {
            get { return GetString("profile_id"); }
            set { Set("profile_id", value); }
        }

        public String ProfileDescription
        {
            get { return GetString("profile_desc"); }
            set { Set("profile_desc", value); }
        }

        public String SessionId
        {
            get { return GetString("session_id"); }
            set { Set("session_id", value); }
        }

        public String SessionDescription
        {
            get { return GetString("session_desc"); }
            set { Set("session_desc", value); }
        }
    }
}


text:
"""
XMPP shell: XMPP interface for the Pelix shell

This module depends on the sleekxmpp package: http://sleekxmpp.com/

:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.5.8
:status: Beta

..

    Copyright 2014 isandlaTech

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

# Module version
__version_info__ = (0, 5, 8)
__version__ = ".".join(str(x) for x in __version_info__)

# Documentation strings format
__docformat__ = "restructuredtext en"

# ------------------------------------------------------------------------------

# iPOPO decorators
from pelix.ipopo.decorators import ComponentFactory, Requires, Property, \
    Validate, Invalidate
from pelix.ipopo.constants import use_ipopo

# Shell constants
import pelix.shell
import pelix.shell.beans as beans

# Pelix utilities
import pelix.framework
import pelix.misc.xmpp
import pelix.threadpool
import pelix.utilities

# Standard library
import collections
import logging
import sys

try:
    # Python 2
    from StringIO import StringIO
except ImportError:
    # Python 3
    from io import StringIO

# ------------------------------------------------------------------------------

# Logger
_logger = logging.getLogger(__name__)

# ------------------------------------------------------------------------------

class _XmppOutStream(object):
    """
    File-like XMPP output. For shell IOHandler use only
    """
    def __init__(self, client, target):
        """
        Sets up the stream

        :param client: XMPP client
        :param target: Output target JID
        """
        self._client = client
        self._target = target
        self._buffer = StringIO()

    def write(self, data):
        """
        Writes data to a buffer
        """
        self._buffer.write(data)

    def flush(self):
        """
        Sends buffered data to the target
        """
        # Flush buffer
        content = self._buffer.getvalue()
        self._buffer = StringIO()

        if content:
            # Send message
            self._client.send_message(self._target, content, mtype="chat")

class _XmppInStream(object):
    """
    File-like XMPP input. For shell IOHandler use only
    """
    def __init__(self, xmpp_ui, source_jid):
        """
        Sets up the object

        :param xmpp_ui: The IPopoXMPPShell object
        """
        self._ui = xmpp_ui
        self._jid = source_jid

    def readline(self):
        """
        Waits for a line from the XMPP client
        """
        # Wait for content from the user
        return self._ui.read_from(self._jid)

# ------------------------------------------------------------------------------

@ComponentFactory(pelix.shell.FACTORY_XMPP_SHELL)
@Requires("_shell", pelix.shell.SERVICE_SHELL)
@Property("_host", "shell.xmpp.server", "localhost")
@Property("_port", "shell.xmpp.port", 5222)
@Property("_jid", "shell.xmpp.jid")
@Property("_password", "shell.xmpp.password")
@Property("_use_tls", "shell.xmpp.tls", "1")
@Property("_use_ssl", "shell.xmpp.ssl", "0")
class IPopoXMPPShell(object):
    """
    The iPOPO XMPP Shell, based on the Pelix Shell
    """
    def __init__(self):
        """
        Sets up the component
        """
        # Injected fields
        self._shell = None
        self._host = None
        self._port = 5222
        self._jid = None
        self._password = None
        self._use_tls = True
        self._use_ssl = False

        # XMPP Bot
        self.__bot = None

        # Shell sessions: JID -> ShellSession
        self.__sessions = {}

        # Waiting for a message from the given JID
        self.__waiting = {}

        # Task queue thread
        self.__pool = pelix.threadpool.ThreadPool(1, logname="XMPPShell")

    def __normalize_int(self, value, default=0):
        """
        Normalizes an integer value
        """
        try:
            return int(value)
        except (ValueError, TypeError):
            return default

    @Validate
    def validate(self, context):
        """
        Component validated
        """
        # Normalize values
        self._port = self.__normalize_int(self._port, 5222)
        self._use_tls = bool(self.__normalize_int(self._use_tls, 1))
        self._use_ssl = bool(self.__normalize_int(self._use_ssl, 0))

        # Start the thread pool
        self.__pool.start()

        _logger.info("""XMPP shell:
- JID: %s
- pass: %s
- host: %s
- port: %s""", self._jid, self._password, self._host, self._port)

        # Create the bot. Negative priority avoids listening to human messages
        self.__bot = pelix.misc.xmpp.BasicBot(self._jid, self._password, -10)

        # Register to events
        self.__bot.add_event_handler("message", self.__on_message)
        self.__bot.add_event_handler("session_start", self.__on_start)
        self.__bot.add_event_handler("session_end", self.__on_end)
        self.__bot.add_event_handler("socket_error", self.__on_error)
        self.__bot.add_event_handler("got_offline", self.__on_offline)

        # Connect to the server
        self.__bot.connect(self._host, self._port, False,
                           self._use_tls, self._use_ssl)

    @Invalidate
    def invalidate(self, context):
        """
        Component invalidated
        """
        # Stop the thread pool
        self.__pool.stop()

        # Disconnect the bot
        self.__bot.disconnect()
        self.__bot = None

        # Clean up
        self.__sessions.clear()

    def __on_error(self, error):
        """
        A socket error occurred

        :param error: The socket error
        """
        _logger.exception("A socket error occurred: %s", error)

    def __on_start(self, _):
        """
        XMPP session started
        """
        _logger.info("XMPP shell connected with JID: %s",
                     self.__bot.boundjid.full)

    def __on_end(self, _):
        """
        XMPP session ended
        """
        _logger.info("XMPP shell disconnected from %s",
                     self.__bot.boundjid.full)

    def __on_offline(self, data):
        """
        XMPP client got offline
        :param data: Message stanza
        """
        source_jid = data['from'].full
        try:
            # Unsubscribe to presence events
            self.__bot.sendPresence(pto=source_jid, ptype='unsubscribe')

            # Delete the corresponding session
            del self.__sessions[source_jid]
        except KeyError:
            # Unknown JID
            pass

    def __on_message(self, data):
        """
        Got an XMPP message

        :param data: Message stanza (see SleekXMPP)
        """
        if data['type'] in ('normal', 'chat'):
            # Got a message
            body = data['body'].strip()
            if body:
                # Valid content, check the sender
                sender = data['from'].full
                try:
                    # Are we listening to this JID ?
                    event = self.__waiting[sender].popleft()
                except (KeyError, IndexError):
                    # Not waiting for a message from this JID,
                    # treat the message in a the task thread
                    self.__pool.enqueue(self.handle_message, sender, body)
                else:
                    # Set the event, with the content of the message as data
                    event.set(body)

    def handle_message(self, source_jid, content):
        """
        Handles an XMPP message and reply to the source

        :param source_jid: JID of the message sender
        :param content: Content of the message
        """
        try:
            # Use the existing session
            session = self.__sessions[source_jid]
        except KeyError:
            # Subscribe to presence messages
            self.__bot.sendPresence(pto=source_jid, ptype='subscribe')

            # Create and store the session
            session = self.__sessions[source_jid] = beans.ShellSession(
                beans.IOHandler(
                    _XmppInStream(self, source_jid),
                    _XmppOutStream(self.__bot, source_jid)),
                {"xmpp.jid": source_jid})

        self._shell.execute(content, session)

    def read_from(self, jid):
        """
        Returns the next message read from the given JID

        :param jid: Source JID
        :return: The next content send by this JID
        """
        # Prepare an event
        event = pelix.utilities.EventData()
        self.__waiting.setdefault(jid, collections.deque()).append(event)

        # Wait for the event to be set...
        event.wait()

        # Return the message content
        return event.data

# ------------------------------------------------------------------------------

def main(server, port, jid=None, password=None, use_tls=False, use_ssl=False):
    """
    Starts a framework with a remote shell and starts an interactive console.

    :param server: XMPP server host
    :param port: XMPP server port
    :param jid: Shell JID
    :param password: Shell JID password
    :param use_tls: Use STARTTLS
    :param use_ssl: Use an SSL connection
    """
    # Start a Pelix framework
    framework = pelix.framework.create_framework(('pelix.ipopo.core',
                                                  'pelix.shell.core',
                                                  'pelix.shell.ipopo',
                                                  'pelix.shell.console',
                                                  'pelix.shell.xmpp'))
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate a Remote Shell
    with use_ipopo(context) as ipopo:
        ipopo.instantiate(pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell",
                          {"shell.xmpp.server": server,
                           "shell.xmpp.port": port,
                           "shell.xmpp.jid": jid,
                           "shell.xmpp.password": password,
                           "shell.xmpp.tls": use_tls,
                           "shell.xmpp.ssl": use_ssl})

    try:
        framework.wait_for_stop()
    except KeyboardInterrupt:
        # Stop server on interruption
        framework.stop()

if __name__ == '__main__':
    # Prepare arguments
    import argparse
    parser = argparse.ArgumentParser(description="Pelix XMPP Shell")
    parser.add_argument("-j", "--jid", dest="jid", help="Jabber ID")
    parser.add_argument("--password", dest="password", help="JID password")
    parser.add_argument("-v", "--verbose", action="store_true", dest="verbose",
                        help="Set loggers at debug level")
    parser.add_argument("-s", "--server", dest="server",
                        help="XMPP server host")
    parser.add_argument("-p", "--port", dest="port", type=int, default=5222,
                        help="XMPP server port")
    parser.add_argument("--tls", dest="use_tls", action="store_true",
                        help="Use a STARTTLS connection")
    parser.add_argument("--ssl", dest="use_ssl", action="store_true",
                        help="Use an SSL connection")

    # Parse them
    args = parser.parse_args()

    # Prepare the logger
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
        logging.getLogger("sleekxmpp").setLevel(logging.WARNING)

    if not args.server and not args.jid:
        _logger.error("No JID nor server given. Abandon.")
        sys.exit(1)

    # Get the password if necessary
    _password = args.password
    if args.jid and not args.password:
        try:
            import getpass
        except ImportError:
            _logger.error("getpass() unavailable: give a password in "
                          "command line")
        else:
            try:
                _password = getpass.getpass()
            except getpass.GetPassWarning:
                pass

    # Get the server from the JID, if necessary
    _server = args.server
    if not _server:
        import sleekxmpp
        _server = sleekxmpp.JID(args.jid).domain

    # Run the entry point
    main(_server, args.port, args.jid, _password, args.use_tls, args.use_ssl)


text:
package com.sonyericsson.extras.liveware.extension.util;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * This extension of TextView renders text on a single line, and fades end if
 * text does not fit. NOTE! This view only supports a single text line and only
 * handles gravity left.
 */
public class AefTextView extends TextView {
    public AefTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AefTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Force single line, see also setHorizontalFadingEdgeEnabled below
        setHorizontallyScrolling(true);

        // remove new lines if any
        String text = getText().toString();
        text = text.replaceAll("\\r?\\n", " ");
        setText(text);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        float textWidth = getPaint().measureText(getText().toString());
        float availableWidth = getMeasuredWidth();

        // fade if too long text
        setHorizontalFadingEdgeEnabled(textWidth > availableWidth);
    }
}


text:
package com.example.h264dec.display;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.opengl.GLSurfaceView;
import android.util.Log;
import android.view.Surface;
import android.view.Surface.OutOfResourcesException;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class AndroidVideoWindowImpl {
	private SurfaceView mVideoRenderingView;
	//private SurfaceView mVideoPreviewView;

	private boolean useGLrendering;
	private Bitmap mBitmap;

	private Surface mSurface;
	private VideoWindowListener mListener;
	private Renderer renderer;

	/**
	 * Utility listener interface providing callback for Android events
	 * useful to Mediastreamer.
	 */
	public static interface VideoWindowListener{
		void onVideoRenderingSurfaceReady(AndroidVideoWindowImpl vw, SurfaceView surface);
		void onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl vw);
	};

	/**
	 * @param renderingSurface Surface created by the application that will be used to render decoded video stream
	 * @param previewSurface Surface created by the application used by Android's Camera preview framework
	 */
	public AndroidVideoWindowImpl(SurfaceView renderingSurface) {
		mVideoRenderingView = renderingSurface;
		//mVideoPreviewView = previewSurface;

		useGLrendering = (renderingSurface instanceof GLSurfaceView);

		mBitmap = null;
		mSurface = null;
		mListener = null;
	}

	public void init() {
		// register callback for rendering surface events
		mVideoRenderingView.getHolder().addCallback(new Callback(){
			public void surfaceChanged(SurfaceHolder holder, int format,
					int width, int height) {
				Log.i("GLES","Video display surface is being changed.");
				if (!useGLrendering) {
					synchronized(AndroidVideoWindowImpl.this){
						mBitmap=Bitmap.createBitmap(width,height,Config.RGB_565);
						mSurface=holder.getSurface();
					}
				}
				if (mListener!=null) mListener.onVideoRenderingSurfaceReady(AndroidVideoWindowImpl.this, mVideoRenderingView);
				Log.w("GLES","Video display surface changed");
			}

			public void surfaceCreated(SurfaceHolder holder) {
				Log.w("GLES","Video display surface created");
			}

			public void surfaceDestroyed(SurfaceHolder holder) {
				Log.d("GLES","IN Video display surface destroyed");
				if (!useGLrendering) {
					synchronized(AndroidVideoWindowImpl.this){
						mSurface=null;
						mBitmap=null;
					}
				}
				if (mListener!=null)
					mListener.onVideoRenderingSurfaceDestroyed(AndroidVideoWindowImpl.this);
				Log.d("GLES","OUT Video display surface destroyed");
			}
		});
		// register callback for preview surface events
		/*if (mVideoPreviewView != null) {
			mVideoPreviewView.getHolder().addCallback(new Callback(){
				public void surfaceChanged(SurfaceHolder holder, int format,
						int width, int height) {
					Log.i("GLES","Video preview surface is being changed.");
					if (mListener!=null)
						mListener.onVideoPreviewSurfaceReady(AndroidVideoWindowImpl.this, mVideoPreviewView);
					Log.w("GLES","Video preview surface changed");
				}

				public void surfaceCreated(SurfaceHolder holder) {
					Log.w("GLES","Video preview surface created");
				}

				public void surfaceDestroyed(SurfaceHolder holder) {
					if (mListener!=null)
						mListener.onVideoPreviewSurfaceDestroyed(AndroidVideoWindowImpl.this);
					Log.d("GLES","Video preview surface destroyed");
				}
			});
		}*/

		if (useGLrendering) {
			renderer = new Renderer();
			((GLSurfaceView)mVideoRenderingView).setRenderer(renderer);
			((GLSurfaceView)mVideoRenderingView).setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
		}
	}

	public void release() {
		//mSensorMgr.unregisterListener(this);
	}

	public void setListener(VideoWindowListener l){
		mListener=l;
	}
	public Surface getSurface(){
		if (useGLrendering)
			Log.e("GLES","View class does not match Video display filter used (you must use a non-GL View)");
		return mVideoRenderingView.getHolder().getSurface();
	}
	public Bitmap getBitmap(){
		if (useGLrendering)
			Log.e("GLES","View class does not match Video display filter used (you must use a non-GL View)");
		return mBitmap;
	}

	public void setOpenGLESDisplay(int ptr) {
		if (!useGLrendering)
			Log.e("GLES","View class does not match Video display filter used (you must use a GL View)");
		renderer.setOpenGLESDisplay(ptr);
	}

	public void requestRender() {
		((GLSurfaceView)mVideoRenderingView).requestRender();
	}

	//Called by the mediastreamer2 android display filter
	public synchronized void update(){
		if (mSurface!=null){
			try {
				Canvas canvas=mSurface.lockCanvas(null);
				canvas.drawBitmap(mBitmap, 0, 0, null);
				mSurface.unlockCanvasAndPost(canvas);

			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (OutOfResourcesException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

    private static class Renderer implements GLSurfaceView.Renderer {
    	int ptr;
    	boolean initPending;
    	int width, height;

    	public Renderer() {
    		ptr = 0;
    		initPending = false;
    	}

    	public void setOpenGLESDisplay(int ptr) {
    		/*
    		 * Synchronize this with onDrawFrame:
    		 * - they are called from different threads (Rendering thread and Linphone's one)
    		 * - setOpenGLESDisplay can modify ptr while onDrawFrame is using it
    		 */
    		synchronized (this) {
	    		if (this.ptr != 0 && ptr != this.ptr) {
	    			initPending = true;
	    		}
	    		this.ptr = ptr;
    		}
    	}

        public void onDrawFrame(GL10 gl) {
        	/*
        	 * See comment in setOpenGLESDisplay
        	 */
        	synchronized (this) {
	        	if (ptr == 0)
	        		return;
	        	if (initPending) {
	            	OpenGLESDisplay.init(ptr, width, height);
	            	initPending = false;
	        	}
	            OpenGLESDisplay.render(ptr);
        	}
        }

        public void onSurfaceChanged(GL10 gl, int width, int height) {
        	/* delay init until ptr is set */
        	this.width = width;
        	this.height = height;
        	initPending = true;
        }

        public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        }
    }

	public static int rotationToAngle(int r) {
		switch (r) {
		case Surface.ROTATION_0:
			return 0;
		case Surface.ROTATION_90:
			return 90;
		case Surface.ROTATION_180:
			return 180;
		case Surface.ROTATION_270:
			return 270;
		}
		return 0;
	}
}


text: export const primaryColor = '#60ACEB';


text:
__inline__ uint64 _hwtime()
{
	unsigned int lo, hi;
	__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
	return (uint64)hi << 32 | lo;
}

#elif defined(_MSC_VER)

__declspec(naked) __inline uint64 __cdecl _hwtime()
{
	__asm {
		rdtsc
			ret; return value at EDX:EAX
	}
}

#endif

#elif (defined(__GNUC__) && defined(__x86_64__))

__inline__ uint64 _hwtime()
{
	unsigned long val;
	__asm__ __volatile__ ("rdtsc" : "=A" (val));
	return val;
}

#elif (defined(__GNUC__) && defined(__ppc__))

__inline__ uint64 _hwtime()
{
	unsigned long long retval;
	unsigned long junk;
	__asm__ __volatile__ ("\n\
						  1:      mftbu   %1\n\
						  mftb    %L0\n\
						  mftbu   %0\n\
						  cmpw    %0,%1\n\
						  bne     1b"
						  : "=r" (retval), "=r" (junk));
	return retval;
}

#else

//#error Need implementation of sqlite3Hwtime() for your platform.

// To compile without implementing sqlite3Hwtime() for your platform, you can remove the above #error and use the following
// stub function.  You will lose timing support for many of the debugging and testing utilities, but it should at
// least compile and run.
__inline__ uint64 _hwtime() { return ((uint64)0); }

#endif

#endif


text:
package com.github.bingoohuang.springrediscache;

import com.google.common.base.Optional;
import com.google.common.base.Throwables;

import java.util.concurrent.Callable;

public class RedisCacheConnector {
    static final ThreadLocal<Optional<Object>> THREADLOCAL = new ThreadLocal<Optional<Object>>();
    static final Object CLEARTAG = new Object();

    /**
     * Clear the cache related to callable.
     * First the local cache is cleared.
     * Then check the redis with local, is their values are equal, then the redis cache will be cleared.
     * Other the redis cache will be left.
     * @param callable
     * @param <T>
     */
    public static <T> void clearCache(Callable<T> callable) {
        connectCache(callable, CLEARTAG);
    }

    public static <T> T connectCache(Callable<T> callable, Object cachedValue) {
        THREADLOCAL.set(Optional.fromNullable(cachedValue));
        try {
            return callable.call();
        } catch (Exception e) {
            throw Throwables.propagate(e);
        } finally {
            THREADLOCAL.remove();
        }
    }

    /**
     * 刷新老缓存,并取得新值。
     * @param callable
     * @param <T>
     * @return
     */
    public static <T> T refreshCache(Callable<T> callable) {
        clearCache(callable);

        try {
            return callable.call();
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }
}


text:
package com.timgroup.stanislavski.matchers;

import java.util.Collection;
import java.util.Iterator;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;

import com.google.common.collect.Lists;
import com.timgroup.stanislavski.reflection.MethodCall;
import com.timgroup.stanislavski.reflection.MethodCallArgument;

public final class AMethodCall<C> extends TypeSafeDiagnosingMatcher<MethodCall> {
    private final String methodName;
    private final Class<C> targetClass;
    private final Collection<AnArgument<?>> arguments = Lists.newLinkedList();

    public static interface MethodNameBinder {
        <C> AMethodCall<C> of(Class<C> interfaceClass);
    }

    public static AMethodCall.MethodNameBinder to(final String methodName) {
        return new MethodNameBinder() {
            @Override public <C> AMethodCall<C> of(Class<C> targetClass) { return new AMethodCall<C>(methodName, targetClass); }
        };
    }

    private AMethodCall(String methodName, Class<C> targetClass) {
        this.methodName = methodName;
        this.targetClass = targetClass;
    }

    public AMethodCall<C> with(AnArgument<?> anArgument) {
        arguments.add(anArgument);
        return this;
    }

    public AMethodCall<C> and(AnArgument<?> anArgument) {
        arguments.add(anArgument);
        return this;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(" a method call to the method ").appendValue(methodName).appendText(" on class ").appendValue(targetClass);
        if (arguments.size() > 0) {
            description.appendText(" with arguments ").appendValueList("[", ",", "]", arguments);
        }
    }

    @Override
    protected boolean matchesSafely(MethodCall item, Description mismatchDescription) {
        if (!item.targetClass().equals(targetClass)) {
            mismatchDescription.appendText(" the target class was ").appendValue(targetClass);
            return false;
        }
        if (!item.name().equals(methodName)) {
            mismatchDescription.appendText(" the method called was ").appendText(methodName);
            return false;
        }
        if (arguments.size() != item.arguments().size()) {
            mismatchDescription.appendText(" the number of arguments was ").appendValue(item.arguments().size());
            return false;
        }
        Iterator<AnArgument<?>> matcherIterator = arguments.iterator();
        Iterator<MethodCallArgument<?>> argumentIterator = item.arguments().iterator();
        int argumentIndex = 0;
        while (matcherIterator.hasNext()) {
            AnArgument<?> matcher = matcherIterator.next();
            MethodCallArgument<?> argument = argumentIterator.next();
            argumentIndex += 1;
            if (!matcher.matches(argument)) {
                mismatchDescription.appendText(" argument [").appendValue(argumentIndex).appendText("]");
                matcher.describeMismatch(argument, mismatchDescription);
                return false;
            }
        }
        return true;
    }
}