text:
<?php

if ( ! function_exists('site_url'))
{

	/**
	 * Return a site URL to use in views
	 *
	 * @param string|array     $path
	 * @param string|null      $scheme
	 * @param \Config\App|null $altConfig Alternate configuration to use
	 *
	 * @return string
	 */
	function site_url($path = '', string $scheme = null, \Config\App $altConfig = null): string
	{
		// convert segment array to string
		if (is_array($path))
		{
			$path = implode('/', $path);
		}

		// use alternate config if provided, else default one
		$config = empty($altConfig) ? new \Config\App() : $altConfig;

		$base = base_url();

		// Add index page, if so configured
		if ( ! empty($config->indexPage))
		{
			$path = rtrim($base, '/').'/'.rtrim($config->indexPage, '/').'/'.$path;
		}
		else
		{
			$path = rtrim($base, '/').'/'.$path;
		}

		$url = new \CodeIgniter\HTTP\URI($path);

		// allow the scheme to be over-ridden; else, use default
		if ( ! empty($scheme))
		{
			$url->setScheme($scheme);
		}

		return (string) $url;
	}

}

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

if ( ! function_exists('base_url'))
{

	/**
	 * Return the base URL to use in views
	 *
	 * @param  string|array $path
	 * @param  string       $scheme
	 * @return string
	 */
	function base_url($path = '', string $scheme = null): string
	{
		// convert segment array to string
		if (is_array($path))
		{
			$path = implode('/', $path);
		}

		// We should be using the set baseURL the user set
		// otherwise get rid of the path because we have
		// no way of knowing the intent...
		$config = \CodeIgniter\Services::request()->config;

		if (! empty($config->baseURL))
		{
			$url = new \CodeIgniter\HTTP\URI($config->baseURL);
		}
		else
		{
			$url = \CodeIgniter\Services::request()->uri;
			$url->setPath('/');
		}

		unset($config);

		// Merge in the path set by the user, if any
		if ( ! empty($path))
		{
			$url = $url->resolveRelativeURI($path);
		}

		if ( ! empty($scheme))
		{
			$url->setScheme($scheme);
		}

		return (string) $url;
	}

}

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

if ( ! function_exists('current_url'))
{

	/**
	 * Current URL
	 *
	 * Returns the full URL (including segments) of the page where this
	 * function is placed
	 *
	 * @param boolean $returnObject True to return an object instead of a strong
	 *
	 * @return string|URI
	 */
	function current_url(bool $returnObject = false)
	{
		return $returnObject === true ? \CodeIgniter\Services::request()->uri : (string) \CodeIgniter\Services::request()->uri;
	}

}

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

if (! function_exists('previous_url'))
{
    /**
     * Returns the previous URL the current visitor was on. For security reasons
     * we first check in a saved session variable, if it exists, and use that.
     * If that's not available, however, we'll use a sanitized url from $_SERVER['HTTP_REFERER']
     * which can be set by the user so is untrusted and not set by certain browsers/servers.
     *
     * @param bool $returnObject
     *
     * @return \CodeIgniter\HTTP\URI|mixed|string
     */
    function previous_url(bool $returnObject = false)
    {
        // Grab from the session first, if we have it,
        // since it's more reliable and safer.
        // Otherwise, grab a sanitized version from $_SERVER.
        $referer = $_SESSION['_ci_previous_url']
                   ?? \CodeIgniter\Services::request()->getServer('HTTP_REFERER', FILTER_SANITIZE_URL);

        $referer = empty($referer)
            ? site_url('/')
            : $referer;

        return $returnObject
            ? new \CodeIgniter\HTTP\URI($referer)
            : $referer;
    }
}

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

if ( ! function_exists('uri_string'))
{

	/**
	 * URL String
	 *
	 * Returns the path part of the current URL
	 *
	 * @return string
	 */
	function uri_string(): string
	{
		return \CodeIgniter\Services::request()->uri->getPath();
	}

}

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

if ( ! function_exists('index_page'))
{

	/**
	 * Index page
	 *
	 * Returns the "index_page" from your config file
	 *
	 * @param  \Config\App|null $altConfig Alternate configuration to use
	 * @return string
	 */
	function index_page(\Config\App $altConfig = null): string
	{
		// use alternate config if provided, else default one
		$config = empty($altConfig) ? new \Config\App() : $altConfig;

		return $config->indexPage;
	}

}

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

if ( ! function_exists('anchor'))
{

	/**
	 * Anchor Link
	 *
	 * Creates an anchor based on the local URL.
	 *
	 * @param  string    the URL
	 * @param  string    the link title
	 * @param  mixed    any attributes
	 * @param  \Config\App|null         $altConfig Alternate configuration to use
	 * @return string
	 */
	function anchor($uri = '', $title = '', $attributes = '', \Config\App $altConfig = null): string
	{
		// use alternate config if provided, else default one
		$config = empty($altConfig) ? new \Config\App() : $altConfig;

		$title = (string) $title;

		$site_url = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config));
		// eliminate trailing slash
		$site_url = rtrim($site_url, '/');

		if ($title === '')
		{
			$title = $site_url;
		}

		if ($attributes !== '')
		{
			$attributes = stringify_attributes($attributes);
		}

		return ''.$title.'';
	}

}

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

if ( ! function_exists('anchor_popup'))
{

	/**
	 * Anchor Link - Pop-up version
	 *
	 * Creates an anchor based on the local URL. The link
	 * opens a new window based on the attributes specified.
	 *
	 * @param  string    the URL
	 * @param  string    the link title
	 * @param  mixed    any attributes
	 * @param  \Config\App|null         $altConfig Alternate configuration to use
	 * @return string
	 */
	function anchor_popup($uri = '', $title = '', $attributes = false, \Config\App $altConfig = null): string
	{
		// use alternate config if provided, else default one
		$config = empty($altConfig) ? new \Config\App() : $altConfig;

		$title = (string) $title;
		$site_url = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, '', $config);
		$site_url = rtrim($site_url, '/');

		if ($title === '')
		{
			$title = $site_url;
		}

		if ($attributes === false)
		{
			return '".$title.'';
		}

		if ( ! is_array($attributes))
		{
			$attributes = array ($attributes);

			// Ref: http://www.w3schools.com/jsref/met_win_open.asp
			$window_name = '_blank';
		}
		elseif ( ! empty($attributes['window_name']))
		{
			$window_name = $attributes['window_name'];
			unset($attributes['window_name']);
		}
		else
		{
			$window_name = '_blank';
		}

		foreach (array ('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0') as
				$key => $val)
		{
			$atts[$key] = isset($attributes[$key]) ? $attributes[$key] : $val;
			unset($attributes[$key]);
		}

		$attributes = stringify_attributes($attributes);

		return ''.$title.'';
	}

}

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

if ( ! function_exists('mailto'))
{

	/**
	 * Mailto Link
	 *
	 * @param  string    the email address
	 * @param  string    the link title
	 * @param  mixed    any attributes
	 * @return string
	 */
	function mailto($email, $title = '', $attributes = ''): string
	{
		$title = (string) $title;

		if ($title === '')
		{
			$title = $email;
		}

		return ''.$title.'';
	}

}

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

if ( ! function_exists('safe_mailto'))
{

	/**
	 * Encoded Mailto Link
	 *
	 * Create a spam-protected mailto link written in Javascript
	 *
	 * @param  string    the email address
	 * @param  string    the link title
	 * @param  mixed    any attributes
	 * @return string
	 */
	function safe_mailto($email, $title = '', $attributes = ''): string
	{
		$title = (string) $title;

		if ($title === '')
		{
			$title = $email;
		}

		$x = str_split('<a href="mailto:', 1);

		for ($i = 0, $l = strlen($email); $i < $l; $i ++ )
		{
			$x[] = '|'.ord($email[$i]);
		}

		$x[] = '"';

		if ($attributes !== '')
		{
			if (is_array($attributes))
			{
				foreach ($attributes as $key => $val)
				{
					$x[] = ' '.$key.'="';
					for ($i = 0, $l = strlen($val); $i < $l; $i ++ )
					{
						$x[] = '|'.ord($val[$i]);
					}
					$x[] = '"';
				}
			}
			else
			{
				for ($i = 0, $l = strlen($attributes); $i < $l; $i ++ )
				{
					$x[] = $attributes[$i];
				}
			}
		}

		$x[] = '>';

		$temp = array ();
		for ($i = 0, $l = strlen($title); $i < $l; $i ++ )
		{
			$ordinal = ord($title[$i]);

			if ($ordinal < 128)
			{
				$x[] = '|'.$ordinal;
			}
			else
			{
				if (count($temp) === 0)
				{
					$count = ($ordinal < 224) ? 2 : 3;
				}

				$temp[] = $ordinal;
				if (count($temp) === $count)
				{
					$number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64);
					$x[] = '|'.$number;
					$count = 1;
					$temp = array ();
				}
			}
		}

		$x[] = '<';
		$x[] = '/';
		$x[] = 'a';
		$x[] = '>';

		$x = array_reverse($x);

		// improve obfuscation by eliminating newlines & whitespace
		$output = "';

		return $output;
	}

}

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

if ( ! function_exists('auto_link'))
{

	/**
	 * Auto-linker
	 *
	 * Automatically links URL and Email addresses.
	 * Note: There's a bit of extra code here to deal with
	 * URLs or emails that end in a period. We'll strip these
	 * off and add them after the link.
	 *
	 * @param  string    the string
	 * @param  string    the type: email, url, or both
	 * @param  bool    whether to create pop-up links
	 * @return string
	 */
	function auto_link($str, $type = 'both', $popup = false): string
	{
		// Find and replace any URLs.
		if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[^\s()<>;]+\w#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER))
		{
			// Set our target HTML if using popup links.
			$target = ($popup) ? ' target="_blank"' : '';

			// We process the links in reverse order (last -> first) so that
			// the returned string offsets from preg_match_all() are not
			// moved as we add more HTML.
			foreach (array_reverse($matches) as $match)
			{
				// $match[0] is the matched string/link
				// $match[1] is either a protocol prefix or 'www.'
				//
                // With PREG_OFFSET_CAPTURE, both of the above is an array,
				// where the actual value is held in [0] and its offset at the [1] index.
				$a = ''.$match[0][0].'';
				$str = substr_replace($str, $a, $match[0][1], strlen($match[0][0]));
			}
		}

		// Find and replace any emails.
		if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE))
		{
			foreach (array_reverse($matches[0]) as $match)
			{
				if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== false)
				{
					$str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0]));
				}
			}
		}

		return $str;
	}

}

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

if ( ! function_exists('prep_url'))
{

	/**
	 * Prep URL - Simply adds the http:// part if no scheme is included.
	 *
	 * Formerly used URI, but that does not play nicely with URIs missing
	 * the scheme.
	 *
	 * @param  string    the URL
	 * @return string
	 */
	function prep_url($str = ''): string
	{
		if ($str === 'http://' OR $str === '')
		{
			return '';
		}

		$url = parse_url($str);

		if ( ! $url OR ! isset($url['scheme']))
		{
			return 'http://'.$str;
		}

		return $str;
	}

}

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

if ( ! function_exists('url_title'))
{

	/**
	 * Create URL Title
	 *
	 * Takes a "title" string as input and creates a
	 * human-friendly URL string with a "separator" string
	 * as the word separator.
	 *
	 * @todo   Remove old 'dash' and 'underscore' usage in 3.1+.
	 * @param  string $str       Input string
	 * @param  string $separator Word separator (usually '-' or '_') (usually '-' or '_')
	 *             (usually '-' or '_')
	 * @param  bool   $lowercase Whether to transform the output string to lowercase
	 * @return string
	 */
	function url_title($str, $separator = '-', $lowercase = false): string
	{
		if ($separator === 'dash')
		{
			$separator = '-';
		}
		elseif ($separator === 'underscore')
		{
			$separator = '_';
		}

		$q_separator = preg_quote($separator, '#');

		$trans = array (
			'&.+?;' => '',
			'[^\w\d _-]' => '',
			'\s+' => $separator,
			'('.$q_separator.')+' => $separator
		);

		$str = strip_tags($str);
		foreach ($trans as $key => $val)
		{
			//			$str = preg_replace('#'.$key.'#i'.( UTF8_ENABLED ? 'u' : ''), $val, $str);
			$str = preg_replace('#'.$key.'#iu', $val, $str);
		}

		if ($lowercase === true)
		{
			$str = strtolower($str);
		}

		return trim(trim($str, $separator));
	}

}

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


text:
package com.twinone.locker.lock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.twinone.locker.LockerAnalytics;
import com.twinone.locker.R;
import com.twinone.locker.ui.MainActivity;
import com.twinone.locker.util.PrefUtils;
import com.twinone.locker.version.VersionManager;
import com.twinone.locker.version.VersionUtils;
import com.twinone.util.Analytics;

public class AppLockService extends Service {

	/**
	 * Sent to {@link MainActivity} when the service has been completely started
	 * and is running
	 */
	public static final String BROADCAST_SERVICE_STARTED = "com.twinone.locker.intent.action.service_started";
	/**
	 * Sent to {@link MainActivity} when the service has been stopped
	 */
	public static final String BROADCAST_SERVICE_STOPPED = "com.twinone.locker.intent.action.service_stopped";
	/**
	 * This category allows the receiver to receive actions relating to the
	 * state of the service, such as when it is started or stopped
	 */
	public static final String CATEGORY_STATE_EVENTS = "com.twinone.locker.intent.category.service_start_stop_event";

	private static final int REQUEST_CODE = 0x1234AF;
	public static final int NOTIFICATION_ID = 0xABCD32;
	private static final String TAG = "AppLockService";

	/** Use this action to stop the intent */
	private static final String ACTION_STOP = "com.twinone.locker.intent.action.stop_lock_service";
	/** Starts the alarm */
	private static final String ACTION_START = "com.twinone.locker.intent.action.start_lock_service";
	/**
	 * When specifying this action, the service will initialize everything
	 * again.

	 * This has only effect if the service was explicitly started using
	 * {@link #getRunIntent(Context)}
	 */
	public static final String ACTION_RESTART = "com.twinone.locker.intent.action.restart_lock_service";

	private static final String EXTRA_FORCE_RESTART = "com.twinone.locker.intent.extra.force_restart";
	private ActivityManager mActivityManager;

	/** 0 for disabled */
	private long mShortExitMillis;

	private boolean mRelockScreenOff;
	private boolean mShowNotification;

	private boolean mExplicitStarted;
	private boolean mAllowDestroy;
	private boolean mAllowRestart;
	private Handler mHandler;
	private BroadcastReceiver mScreenReceiver;

	/**
	 * This map contains locked apps in the form

	 * <PackageName, ShortExitEndTime>
	 */
	private Map<String, Boolean> mLockedPackages;
	private Map<String, Runnable> mUnlockMap;

	@Override
	public IBinder onBind(Intent i) {
		return new LocalBinder();
	}

	public class LocalBinder extends Binder {
		public AppLockService getInstance() {
			return AppLockService.this;
		}
	}

	private final class ScreenReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
				Log.i(TAG, "Screen ON");
				// Trigger package again
				mLastPackageName = "";
				startAlarm(AppLockService.this);
			}
			if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
				Log.i(TAG, "Screen OFF");
				stopAlarm(AppLockService.this);
				if (mRelockScreenOff) {
					lockAll();
				}
			}
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");
	}

	/**
	 * Starts everything, including notification and repeating alarm
	 *
	 * @return True if all OK, false if the service is not allowed to start (the
	 *         caller should stop the service)
	 */
	private boolean init() {
		Log.d(TAG, "init");
		if (new PrefUtils(this).isCurrentPasswordEmpty()) {
			Log.w(TAG, "Not starting service, current password empty");
			return false;
		}
		if (new VersionManager(this).isDeprecated()) {
			Log.i(TAG, "Not starting AlarmService for deprecated version");
			new VersionUtils(this).showDeprecatedNotification();
			return false;
		}

		mHandler = new Handler();
		mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

		mUnlockMap = new HashMap<String, Runnable>();
		mLockedPackages = new HashMap<String, Boolean>();
		mScreenReceiver = new ScreenReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(mScreenReceiver, filter);

		final Set<String> apps = PrefUtils.getLockedApps(this);
		for (String s : apps) {
			mLockedPackages.put(s, true);
		}
		PrefUtils prefs = new PrefUtils(this);
		boolean delay = prefs.getBoolean(R.string.pref_key_delay_status,
				R.bool.pref_def_delay_status);

		if (delay) {
			int secs = prefs.parseInt(R.string.pref_key_delay_time,
					R.string.pref_def_delay_time);
			mShortExitMillis = secs * 1000;
		}

		mRelockScreenOff = prefs.getBoolean(
				R.string.pref_key_relock_after_screenoff,
				R.bool.pref_def_relock_after_screenoff);

		startNotification();
		startAlarm(this);

		// Tell MainActivity we're done
		Intent i = new Intent(BROADCAST_SERVICE_STARTED);
		i.addCategory(CATEGORY_STATE_EVENTS);
		sendBroadcast(i);
		return true;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// Log.d(TAG, "test");
		if (intent == null || ACTION_START.equals(intent.getAction())) {
			if (!mExplicitStarted) {
				Log.d(TAG, "explicitStarted = false");
				if (init() == false) {
					doStopSelf();
					return START_NOT_STICKY;
				}
				mExplicitStarted = true;
			}
			checkPackageChanged();
		} else if (ACTION_RESTART.equals(intent.getAction())) {
			if (mExplicitStarted
					|| intent.getBooleanExtra(EXTRA_FORCE_RESTART, false)) {
				Log.d(TAG,
						"ACTION_RESTART (force="
								+ intent.getBooleanExtra(EXTRA_FORCE_RESTART,
										false));
				// init();
				doRestartSelf(); // not allowed, so service will restart
			} else {
				doStopSelf();
			}
		} else if (ACTION_STOP.equals(intent.getAction())) {
			Log.d(TAG, "ACTION_STOP");
			doStopSelf();
		}

		return START_STICKY;
	}

	private String mLastPackageName;

	// private String mLastCompleteName;

	private void checkPackageChanged() {
		final RunningTaskInfo top = getTopTask();
		final String packageName = top.topActivity.getPackageName();
		// final String completeName = packageName + "/"
		// + top.topActivity.getShortClassName();

		if (!packageName.equals(mLastPackageName)) {
			Log.d(TAG, "appchanged " + " (" + mLastPackageName + ">"
					+ packageName + ")");

			onAppClose(mLastPackageName, packageName);
			onAppOpen(packageName, mLastPackageName);
		}

		// prepare for next call
		mLastPackageName = packageName;
		// mLastCompleteName = completeName;
	}

	private void onAppOpen(final String open, final String close) {
		if (mLockedPackages.containsKey(open)) {
			onLockedAppOpen(open, close);
		}
	}

	private void onLockedAppOpen(final String open, final String close) {
		final boolean locked = mLockedPackages.get(open);
		// Log.d(TAG, "onLockedAppOpen (locked=" + locked + ")");
		if (locked) {
			showLocker(open);
		}
		removeRelockTimer(open);
	}

	private void showLocker(String packageName) {
		Intent intent = LockService.getLockIntent(this, packageName);
		intent.setAction(LockService.ACTION_COMPARE);
		intent.putExtra(LockService.EXTRA_PACKAGENAME, packageName);
		startService(intent);

	}

	private void onAppClose(String close, String open) {
		if (mLockedPackages.containsKey(close)) {
			onLockedAppClose(close, open);
		}
	}

	private void onLockedAppClose(String close, String open) {
		setRelockTimer(close);
		if (getPackageName().equals(close) || getPackageName().equals(open)) {
			// Don't interact with own app
			return;
		}

		if (mLockedPackages.containsKey(open)) {
			// The newly opened app needs a lock screen, so don't hide previous
			return;
		}
		LockService.hide(this);
	}

	private void setRelockTimer(String packageName) {
		boolean locked = mLockedPackages.get(packageName);
		if (!locked) {
			if (mShortExitMillis != 0) {
				Runnable r = new RelockRunnable(packageName);
				mHandler.postDelayed(r, mShortExitMillis);
				mUnlockMap.put(packageName, r);
			} else {
				lockApp(packageName);
			}
		}
	}

	private void removeRelockTimer(String packageName) {
		// boolean locked = mLockedPackages.get(packageName);
		// if (!locked) {
		if (mUnlockMap.containsKey(packageName)) {
			mHandler.removeCallbacks(mUnlockMap.get(packageName));
			mUnlockMap.remove(packageName);
		}
	}

	/** This class will re-lock an app */
	private class RelockRunnable implements Runnable {
		private final String mPackageName;

		public RelockRunnable(String packageName) {
			mPackageName = packageName;
		}

		@Override
		public void run() {
			lockApp(mPackageName);
		}
	}

	List<RunningTaskInfo> mTestList = new ArrayList<RunningTaskInfo>();

	private RunningTaskInfo getTopTask() {
		return mActivityManager.getRunningTasks(1).get(0);
	}

	/**
	 * Unlock a single application. Should be called by {@link LockActivity}
	 *
	 * @param appName
	 */
	public void unlockApp(String packageName) {
		Log.d(TAG, "unlocking app (packageName=" + packageName + ")");
		if (mLockedPackages.containsKey(packageName)) {
			mLockedPackages.put(packageName, false);
		}
	}

	private void lockAll() {
		for (Map.Entry<String, Boolean> entry : mLockedPackages.entrySet()) {
			entry.setValue(true);
		}
	}

	public void lockApp(String packageName) {
		if (mLockedPackages.containsKey(packageName)) {
			mLockedPackages.put(packageName, true);
		}
	}

	private void startNotification() {

		// Start foreground anyway
		startForegroundWithNotification();

		mShowNotification = new PrefUtils(this).getBoolean(
				R.string.pref_key_show_notification,
				R.bool.pref_def_show_notification);

		// If the user doesn't want a notification (default), remove it
		if (!mShowNotification) {
			// Retain foreground state
			HelperService.removeNotification(this);

			// Remove foreground
			// stopForeground(true);
		}
	}

	@SuppressLint("InlinedApi")
	private void startForegroundWithNotification() {
		Log.d(TAG, "showNotification");

		boolean hide = new PrefUtils(this).getBoolean(
				R.string.pref_key_hide_notification_icon,
				R.bool.pref_def_hide_notification_icon);
		int priority = hide ? Notification.PRIORITY_MIN
				: Notification.PRIORITY_DEFAULT;
		Intent i = new Intent(this, MainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
		String title = getString(R.string.notification_title);
		String content = getString(R.string.notification_state_locked);
		NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
		nb.setSmallIcon(R.drawable.ic_launcher);
		nb.setContentTitle(title);
		nb.setContentText(content);
		nb.setWhen(System.currentTimeMillis());
		nb.setContentIntent(pi);
		nb.setOngoing(true);
		nb.setPriority(priority);

		startForeground(NOTIFICATION_ID, nb.build());
	}

	public static final void start(Context c) {
		new Analytics(c).increment(LockerAnalytics.SERVICE_START);
		startAlarm(c);
	}

	/**
	 *
	 * @param c
	 * @return The new state for the service, true for running, false for not
	 *         running
	 */
	public static boolean toggle(Context c) {
		if (isRunning(c)) {
			stop(c);
			return false;
		} else {
			start(c);
			return true;
		}

	}

	public static boolean isRunning(Context c) {
		ActivityManager manager = (ActivityManager) c
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (AppLockService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	/** Starts the service */
	private static final void startAlarm(Context c) {
		AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
		PendingIntent pi = getRunIntent(c);
		SharedPreferences sp = PrefUtils.prefs(c);
		String defaultPerformance = c.getString(R.string.pref_val_perf_normal);
		String s = sp.getString(c.getString(R.string.pref_key_performance),
				defaultPerformance);
		if (s.length() == 0)
			s = "0";
		long interval = Long.parseLong(s);
		Log.d(TAG, "Scheduling alarm (interval=" + interval + ")");
		long startTime = SystemClock.elapsedRealtime();
		am.setRepeating(AlarmManager.ELAPSED_REALTIME, startTime, interval, pi);
	}

	private static PendingIntent running_intent;

	private static final PendingIntent getRunIntent(Context c) {
		if (running_intent == null) {
			Intent i = new Intent(c, AppLockService.class);
			i.setAction(ACTION_START);
			running_intent = PendingIntent.getService(c, REQUEST_CODE, i, 0);
		}
		return running_intent;
	}

	private static final void stopAlarm(Context c) {
		AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
		am.cancel(getRunIntent(c));
	}

	/** Stop this service, also stopping the alarm */
	public static final void stop(Context c) {
		stopAlarm(c);
		new Analytics(c).increment(LockerAnalytics.SERVICE_STOP);
		Intent i = new Intent(c, AppLockService.class);
		i.setAction(ACTION_STOP);
		c.startService(i);
	}

	/**
	 * Re-initialize everything.

	 * This has only effect if the service was explicitly started using
	 * {@link #start(Context)}
	 */
	public static final void restart(Context c) {
		Intent i = new Intent(c, AppLockService.class);
		i.setAction(ACTION_RESTART);
		c.startService(i);
	}

	/**
	 * Forces the service to stop and then start again. This means that if the
	 * service was already stopped, it will just start
	 */
	public static final void forceRestart(Context c) {
		Intent i = new Intent(c, AppLockService.class);
		i.setAction(ACTION_RESTART);
		i.putExtra(EXTRA_FORCE_RESTART, true);
		c.startService(i);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy: (mAllowRestart=" + mAllowRestart + ")");
		if (mScreenReceiver != null)
			unregisterReceiver(mScreenReceiver);
		if (mShowNotification)
			stopForeground(true);

		if (mAllowRestart) {
			start(this);
			mAllowRestart = false;
			return;
		}

		Log.i(TAG, "onDestroy (mAllowDestroy=" + mAllowDestroy + ")");
		if (!mAllowDestroy) {
			Log.d(TAG, "Destroy not allowed, restarting service");
			start(this);
		} else {
			// Tell MainActivity we're stopping
			Intent i = new Intent(BROADCAST_SERVICE_STOPPED);
			i.addCategory(CATEGORY_STATE_EVENTS);
			sendBroadcast(i);
		}
		mAllowDestroy = false;
	}

	private void doStopSelf() {
		stopAlarm(this);
		mAllowDestroy = true;
		stopForeground(true);
		stopSelf();
	}

	private void doRestartSelf() {
		Log.d(TAG, "Setting allowrestart to true");
		mAllowRestart = true;
		stopSelf();
	}

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * 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.
 */
package org.hyperledger.jackson;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
import org.hyperledger.common.Transaction;
import org.hyperledger.common.WireFormat;
import org.hyperledger.common.WireFormatter;

import java.io.IOException;
import java.util.Objects;

public class TransactionDeserializer extends FromStringDeserializer<Transaction> implements ContextualDeserializer {
    final WireFormatter formatter;

    protected TransactionDeserializer(WireFormatter formatter) {
        super(Transaction.class);
        this.formatter = formatter;
    }

    @Override
    protected Transaction _deserialize(String value, DeserializationContext ctxt) throws IOException {
        throw new IllegalStateException("This method should be implemented by a subclass");
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        if (property != null) {
            JsonFormat.Value format = ctxt.getAnnotationIntrospector().findFormat(property.getMember());
            if (format != null && Objects.equals(TransactionSerializer.BASE64_FORMAT, format.getPattern())) {
                return new Base64TransactionDeserializer(formatter);
            }
        }

        return new HexTransactionDeserializer(formatter);
    }

    private static class HexTransactionDeserializer extends TransactionDeserializer {
        private HexTransactionDeserializer(WireFormatter formatter) {
            super(formatter);
        }

        @Override
        protected Transaction _deserialize(String value, DeserializationContext ctxt) throws IOException {
            return formatter.fromWireDump(value);
        }
    }

    private static class Base64TransactionDeserializer extends TransactionDeserializer {
        private Base64TransactionDeserializer(WireFormatter formatter) {
            super(formatter);
        }

        @Override
        protected Transaction _deserialize(String value, DeserializationContext ctxt) throws IOException {
            byte[] bytes = ctxt.getConfig().getBase64Variant().decode(value);
            return formatter.fromWire(new WireFormat.Reader(bytes));
        }
    }
}


text:
- Add GearVR and Daydream support
- Update dependencies
- Fix datgui problems with components lifecycle in SettingsPanel

## v0.1.0 (April 16, 2017)

- Initial public release


text:
#region Namespaces
using Autodesk.Revit.DB;
using System;
#endregion // Namespaces

namespace FireRatingCloud
{
  class DoorData : FireRating.DoorData
  {
    /// <summary>
    /// Access the Revit Element ALL_MODEL_MARK
    /// built-in parameter.
    /// </summary>
    public const BuiltInParameter BipMark
      = BuiltInParameter.ALL_MODEL_MARK;

    /// <summary>
    /// DoorData constructor to generate the data to
    /// serialise for the REST POST or PUT request.
    /// </summary>
    public DoorData(
      Element door,
      string project_id_arg,
      Guid paramGuid,
      uint timestamp )
    {
      Document doc = door.Document;

      _id = door.UniqueId;

      project_id = project_id_arg;

      level = doc.GetElement( door.LevelId ).Name;

      tag = door.get_Parameter( BipMark ).AsString();

      firerating = door.get_Parameter( paramGuid )
        .AsDouble();

      modified = timestamp;
    }
  }
}


text:
var app = angular.module("clientBrowser", ['ngRoute'])
	.controller("MainController", MainController);

function MainController($rootScope, $timeout) {
	$rootScope.isCollapsed = false;
	$rootScope.alertMsg = "";
	$rootScope.alertType = "";
	$rootScope.showAlert = function(type, msg){
		$rootScope.alertType = type;
		$rootScope.alertMsg = msg;
		$rootScope.isCollapsed = true;
		$timeout(function(){
			$rootScope.isCollapsed = false;
		}, 5000)
	}
}


text:
package com.mauriciotogneri.dry.compiler.runtime.statements;

import com.mauriciotogneri.dry.compiler.runtime.Context;
import com.mauriciotogneri.dry.compiler.runtime.Expression;
import com.mauriciotogneri.dry.compiler.runtime.constant.Constant;

import java.util.Optional;

public class Return implements Statement
{
    private final Expression expression;

    public Return(Expression expression)
    {
        this.expression = expression;
    }

    @Override
    public Optional<Constant> execute(Context context)
    {
        return Optional.of(expression.evaluate(context));
    }
}


text:
package system_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

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

	boshlog "github.com/cloudfoundry/bosh-utils/logger"
	. "github.com/cloudfoundry/bosh-utils/system"
)

var _ = Describe("execProcess", func() {
	Describe("TerminateNicely", func() {
		var (
			buildDir string
			logger   boshlog.Logger
		)

		BeforeEach(func() {
			logger = boshlog.NewLogger(boshlog.LevelNone)
		})

		hasProcessesFromBuildDir := func() (bool, string) {
			// Make sure to show all processes on the system
			output, err := exec.Command("ps", "-A", "-o", "pid,args").Output()
			Expect(err).ToNot(HaveOccurred())

			// Cannot check for PID existence directly because
			// PID could have been recycled by the OS; make sure it's not the same process
			for _, line := range strings.Split(strings.TrimSpace(string(output)), "\n") {
				if strings.Contains(line, buildDir) {
					return true, line
				}
			}

			return false, ""
		}

		expectProcessesToNotExist := func() {
			exists, ps := hasProcessesFromBuildDir()
			Expect(exists).To(BeFalse(), "Expected following process to not exist %s", ps)
		}

		BeforeEach(func() {
			var (
				err error
			)

			buildDir, err = ioutil.TempDir("", "TerminateNicely")
			Expect(err).ToNot(HaveOccurred())

			exesToCompile := []string{
				"exe_exits",
				"child_ignore_term",
				"child_term",
				"parent_ignore_term",
				"parent_term",
			}

			for _, exe := range exesToCompile {
				dst := filepath.Join(buildDir, exe)
				src := filepath.Join("exec_cmd_runner_fixtures", exe+".go")
				err := exec.Command("go", "build", "-o", dst, src).Run()
				Expect(err).ToNot(HaveOccurred())
			}
		})

		AfterEach(func() {
			os.RemoveAll(buildDir)
		})

		Context("when parent and child terminate after receiving SIGTERM", func() {
			It("sends term signal to the whole group and returns with exit status that parent exited", func() {
				command := exec.Command(filepath.Join(buildDir, "parent_term"))
				process := NewExecProcess(command, logger)
				err := process.Start()
				Expect(err).ToNot(HaveOccurred())

				// Wait for script to start and output pids
				time.Sleep(2 * time.Second)

				waitCh := process.Wait()

				err = process.TerminateNicely(1 * time.Minute)
				Expect(err).ToNot(HaveOccurred())

				result := <-waitCh
				Expect(result.Error).To(HaveOccurred())

				// Parent exit code is returned
				// bash adds 128 to signal status as exit code
				Expect(result.ExitStatus).To(Equal(13))

				// Term signal was sent to all processes in the group
				Expect(result.Stdout).To(ContainSubstring("Parent received SIGTERM"))
				Expect(result.Stdout).To(ContainSubstring("Child received SIGTERM"))

				// All processes are gone
				expectProcessesToNotExist()
			})
		})

		Context("when parent and child do not exit after receiving SIGTERM in small amount of time", func() {
			It("sends kill signal to the whole group and returns with ? exit status", func() {
				command := exec.Command(filepath.Join(buildDir, "parent_ignore_term"))
				process := NewExecProcess(command, logger)
				err := process.Start()
				Expect(err).ToNot(HaveOccurred())

				// Wait for script to start and output pids
				time.Sleep(2 * time.Second)

				waitCh := process.Wait()

				err = process.TerminateNicely(2 * time.Second)
				Expect(err).ToNot(HaveOccurred())

				result := <-waitCh
				Expect(result.Error).To(HaveOccurred())

				// Parent exit code is returned
				Expect(result.ExitStatus).To(Equal(128 + 9))

				// Term signal was sent to all processes in the group before kill
				Expect(result.Stdout).To(ContainSubstring("Parent received SIGTERM"))
				Expect(result.Stdout).To(ContainSubstring("Child received SIGTERM"))

				// Parent and child are killed
				expectProcessesToNotExist()
			})
		})

		Context("when parent and child already exited before calling TerminateNicely", func() {
			It("returns without an error since all processes are gone", func() {
				command := exec.Command(filepath.Join(buildDir, "exe_exits"))
				process := NewExecProcess(command, logger)
				err := process.Start()
				Expect(err).ToNot(HaveOccurred())

				// Wait for script to exit
				for i := 0; i < 20; i++ {
					if exists, _ := hasProcessesFromBuildDir(); !exists {
						break
					}
					if i == 19 {
						Fail("Expected process did not exit fast enough")
					}
					time.Sleep(500 * time.Millisecond)
				}

				waitCh := process.Wait()

				err = process.TerminateNicely(2 * time.Second)
				Expect(err).ToNot(HaveOccurred())

				result := <-waitCh
				Expect(result.Error).ToNot(HaveOccurred())
				Expect(result.Stdout).To(Equal(""))
				Expect(result.Stderr).To(Equal(""))
				Expect(result.ExitStatus).To(Equal(0))
			})
		})
	})
})


text:
<?php

declare (strict_types=1);
namespace Rector\PostRector\Rector;

use PhpParser\Node;
use Rector\PostRector\Collector\NodesToReplaceCollector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
final class NodeToReplacePostRector extends \Rector\PostRector\Rector\AbstractPostRector
{
    /**
     * @var \Rector\PostRector\Collector\NodesToReplaceCollector
     */
    private $nodesToReplaceCollector;
    public function __construct(\Rector\PostRector\Collector\NodesToReplaceCollector $nodesToReplaceCollector)
    {
        $this->nodesToReplaceCollector = $nodesToReplaceCollector;
    }
    public function getPriority() : int
    {
        return 1100;
    }
    public function leaveNode(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        foreach ($this->nodesToReplaceCollector->getNodes() as [$nodeToFind, $replacement]) {
            if ($node === $nodeToFind) {
                return $replacement;
            }
        }
        return null;
    }
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Replaces nodes on weird positions', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
class SomeClass
{
    public function run($value)
    {
        return 1;
    }
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class SomeClass
{
    public function run($value)
    {
        return $value;
    }
}
CODE_SAMPLE
)]);
    }
}


text:
@interface YPEventsViewController : UIViewController <RSDFDatePickerViewDelegate, RSDFDatePickerViewDataSource, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSString *viewName;

@end


text:
<<<<<<< HEAD:library/src/androidTest/java/com/google/android/exoplayer/extractor/ExtractorTest.java
package com.google.android.exoplayer.extractor;

import com.google.android.exoplayer.C;
=======
package com.google.android.exoplayer2.extractor;

import com.google.android.exoplayer2.C;
>>>>>>> google/release-v2:library/src/androidTest/java/com/google/android/exoplayer2/extractor/ExtractorTest.java
import junit.framework.TestCase;

/**
 * Unit test for {@link Extractor}.
 */
public class ExtractorTest extends TestCase {

  public static void testConstants() {
    // Sanity check that constant values match those defined by {@link C}.
    assertEquals(C.RESULT_END_OF_INPUT, Extractor.RESULT_END_OF_INPUT);
    // Sanity check that the other constant values don't overlap.
    assertTrue(C.RESULT_END_OF_INPUT != Extractor.RESULT_CONTINUE);
    assertTrue(C.RESULT_END_OF_INPUT != Extractor.RESULT_SEEK);
  }

}


text:
@interface ComGoogleCommonBaseUtf8 ()

+ (jint)encodedLengthGeneralWithJavaLangCharSequence:(id<JavaLangCharSequence>)sequence
                                             withInt:(jint)start;

+ (jboolean)isWellFormedSlowPathWithByteArray:(IOSByteArray *)bytes
                                      withInt:(jint)off
                                      withInt:(jint)end;

+ (NSString *)unpairedSurrogateMsgWithInt:(jint)i;

- (instancetype)init;

@end

__attribute__((unused)) static jint ComGoogleCommonBaseUtf8_encodedLengthGeneralWithJavaLangCharSequence_withInt_(id<JavaLangCharSequence> sequence, jint start);

__attribute__((unused)) static jboolean ComGoogleCommonBaseUtf8_isWellFormedSlowPathWithByteArray_withInt_withInt_(IOSByteArray *bytes, jint off, jint end);

__attribute__((unused)) static NSString *ComGoogleCommonBaseUtf8_unpairedSurrogateMsgWithInt_(jint i);

__attribute__((unused)) static void ComGoogleCommonBaseUtf8_init(ComGoogleCommonBaseUtf8 *self);

__attribute__((unused)) static ComGoogleCommonBaseUtf8 *new_ComGoogleCommonBaseUtf8_init() NS_RETURNS_RETAINED;

__attribute__((unused)) static ComGoogleCommonBaseUtf8 *create_ComGoogleCommonBaseUtf8_init();

@implementation ComGoogleCommonBaseUtf8

+ (jint)encodedLengthWithJavaLangCharSequence:(id<JavaLangCharSequence>)sequence {
  return ComGoogleCommonBaseUtf8_encodedLengthWithJavaLangCharSequence_(sequence);
}

+ (jint)encodedLengthGeneralWithJavaLangCharSequence:(id<JavaLangCharSequence>)sequence
                                             withInt:(jint)start {
  return ComGoogleCommonBaseUtf8_encodedLengthGeneralWithJavaLangCharSequence_withInt_(sequence, start);
}

+ (jboolean)isWellFormedWithByteArray:(IOSByteArray *)bytes {
  return ComGoogleCommonBaseUtf8_isWellFormedWithByteArray_(bytes);
}

+ (jboolean)isWellFormedWithByteArray:(IOSByteArray *)bytes
                              withInt:(jint)off
                              withInt:(jint)len {
  return ComGoogleCommonBaseUtf8_isWellFormedWithByteArray_withInt_withInt_(bytes, off, len);
}

+ (jboolean)isWellFormedSlowPathWithByteArray:(IOSByteArray *)bytes
                                      withInt:(jint)off
                                      withInt:(jint)end {
  return ComGoogleCommonBaseUtf8_isWellFormedSlowPathWithByteArray_withInt_withInt_(bytes, off, end);
}

+ (NSString *)unpairedSurrogateMsgWithInt:(jint)i {
  return ComGoogleCommonBaseUtf8_unpairedSurrogateMsgWithInt_(i);
}

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  ComGoogleCommonBaseUtf8_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, "I", 0x9, 0, 1, -1, -1, -1, -1 },
    { NULL, "I", 0xa, 2, 3, -1, -1, -1, -1 },
    { NULL, "Z", 0x9, 4, 5, -1, -1, -1, -1 },
    { NULL, "Z", 0x9, 4, 6, -1, -1, -1, -1 },
    { NULL, "Z", 0xa, 7, 6, -1, -1, -1, -1 },
    { NULL, "LNSString;", 0xa, 8, 9, -1, -1, -1, -1 },
    { NULL, NULL, 0x2, -1, -1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  methods[0].selector = @selector(encodedLengthWithJavaLangCharSequence:);
  methods[1].selector = @selector(encodedLengthGeneralWithJavaLangCharSequence:withInt:);
  methods[2].selector = @selector(isWellFormedWithByteArray:);
  methods[3].selector = @selector(isWellFormedWithByteArray:withInt:withInt:);
  methods[4].selector = @selector(isWellFormedSlowPathWithByteArray:withInt:withInt:);
  methods[5].selector = @selector(unpairedSurrogateMsgWithInt:);
  methods[6].selector = @selector(init);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "encodedLength", "LJavaLangCharSequence;", "encodedLengthGeneral", "LJavaLangCharSequence;I", "isWellFormed", "[B", "[BII", "isWellFormedSlowPath", "unpairedSurrogateMsg", "I" };
  static const J2ObjcClassInfo _ComGoogleCommonBaseUtf8 = { "Utf8", "com.google.common.base", ptrTable, methods, NULL, 7, 0x11, 7, 0, -1, -1, -1, -1, -1 };
  return &_ComGoogleCommonBaseUtf8;
}

@end

jint ComGoogleCommonBaseUtf8_encodedLengthWithJavaLangCharSequence_(id<JavaLangCharSequence> sequence) {
  ComGoogleCommonBaseUtf8_initialize();
  jint utf16Length = [((id<JavaLangCharSequence>) nil_chk(sequence)) java_length];
  jint utf8Length = utf16Length;
  jint i = 0;
  while (i < utf16Length && [sequence charAtWithInt:i] < (jint) 0x80) {
    i++;
  }
  for (; i < utf16Length; i++) {
    jchar c = [sequence charAtWithInt:i];
    if (c < (jint) 0x800) {
      utf8Length += (JreURShift32(((jint) 0x7f - c), 31));
    }
    else {
      utf8Length += ComGoogleCommonBaseUtf8_encodedLengthGeneralWithJavaLangCharSequence_withInt_(sequence, i);
      break;
    }
  }
  if (utf8Length < utf16Length) {
    @throw new_JavaLangIllegalArgumentException_initWithNSString_(JreStrcat("$J", @"UTF-8 length does not fit in int: ", (utf8Length + (JreLShift64(1LL, 32)))));
  }
  return utf8Length;
}

jint ComGoogleCommonBaseUtf8_encodedLengthGeneralWithJavaLangCharSequence_withInt_(id<JavaLangCharSequence> sequence, jint start) {
  ComGoogleCommonBaseUtf8_initialize();
  jint utf16Length = [((id<JavaLangCharSequence>) nil_chk(sequence)) java_length];
  jint utf8Length = 0;
  for (jint i = start; i < utf16Length; i++) {
    jchar c = [sequence charAtWithInt:i];
    if (c < (jint) 0x800) {
      utf8Length += JreURShift32(((jint) 0x7f - c), 31);
    }
    else {
      utf8Length += 2;
      if (JavaLangCharacter_MIN_SURROGATE <= c && c <= JavaLangCharacter_MAX_SURROGATE) {
        if (JavaLangCharacter_codePointAtWithJavaLangCharSequence_withInt_(sequence, i) == c) {
          @throw new_JavaLangIllegalArgumentException_initWithNSString_(ComGoogleCommonBaseUtf8_unpairedSurrogateMsgWithInt_(i));
        }
        i++;
      }
    }
  }
  return utf8Length;
}

jboolean ComGoogleCommonBaseUtf8_isWellFormedWithByteArray_(IOSByteArray *bytes) {
  ComGoogleCommonBaseUtf8_initialize();
  return ComGoogleCommonBaseUtf8_isWellFormedWithByteArray_withInt_withInt_(bytes, 0, ((IOSByteArray *) nil_chk(bytes))->size_);
}

jboolean ComGoogleCommonBaseUtf8_isWellFormedWithByteArray_withInt_withInt_(IOSByteArray *bytes, jint off, jint len) {
  ComGoogleCommonBaseUtf8_initialize();
  jint end = off + len;
  ComGoogleCommonBasePreconditions_checkPositionIndexesWithInt_withInt_withInt_(off, end, ((IOSByteArray *) nil_chk(bytes))->size_);
  for (jint i = off; i < end; i++) {
    if (IOSByteArray_Get(bytes, i) < 0) {
      return ComGoogleCommonBaseUtf8_isWellFormedSlowPathWithByteArray_withInt_withInt_(bytes, i, end);
    }
  }
  return true;
}

jboolean ComGoogleCommonBaseUtf8_isWellFormedSlowPathWithByteArray_withInt_withInt_(IOSByteArray *bytes, jint off, jint end) {
  ComGoogleCommonBaseUtf8_initialize();
  jint index = off;
  while (true) {
    jint byte1;
    do {
      if (index >= end) {
        return true;
      }
    }
    while ((byte1 = IOSByteArray_Get(nil_chk(bytes), index++)) >= 0);
    if (byte1 < (jbyte) (jint) 0xE0) {
      if (index == end) {
        return false;
      }
      if (byte1 < (jbyte) (jint) 0xC2 || IOSByteArray_Get(bytes, index++) > (jbyte) (jint) 0xBF) {
        return false;
      }
    }
    else if (byte1 < (jbyte) (jint) 0xF0) {
      if (index + 1 >= end) {
        return false;
      }
      jint byte2 = IOSByteArray_Get(bytes, index++);
      if (byte2 > (jbyte) (jint) 0xBF || (byte1 == (jbyte) (jint) 0xE0 && byte2 < (jbyte) (jint) 0xA0) || (byte1 == (jbyte) (jint) 0xED && (jbyte) (jint) 0xA0 <= byte2) || IOSByteArray_Get(bytes, index++) > (jbyte) (jint) 0xBF) {
        return false;
      }
    }
    else {
      if (index + 2 >= end) {
        return false;
      }
      jint byte2 = IOSByteArray_Get(bytes, index++);
      if (byte2 > (jbyte) (jint) 0xBF || (JreRShift32(((JreLShift32(byte1, 28)) + (byte2 - (jbyte) (jint) 0x90)), 30)) != 0 || IOSByteArray_Get(bytes, index++) > (jbyte) (jint) 0xBF || IOSByteArray_Get(bytes, index++) > (jbyte) (jint) 0xBF) {
        return false;
      }
    }
  }
}

NSString *ComGoogleCommonBaseUtf8_unpairedSurrogateMsgWithInt_(jint i) {
  ComGoogleCommonBaseUtf8_initialize();
  return JreStrcat("$I", @"Unpaired surrogate at index ", i);
}

void ComGoogleCommonBaseUtf8_init(ComGoogleCommonBaseUtf8 *self) {
  NSObject_init(self);
}

ComGoogleCommonBaseUtf8 *new_ComGoogleCommonBaseUtf8_init() {
  J2OBJC_NEW_IMPL(ComGoogleCommonBaseUtf8, init)
}

ComGoogleCommonBaseUtf8 *create_ComGoogleCommonBaseUtf8_init() {
  J2OBJC_CREATE_IMPL(ComGoogleCommonBaseUtf8, init)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(ComGoogleCommonBaseUtf8)


text:
/*
 * minimap
 * https://github.com/dryas/impactjs-minimap
 *
 * v1.1.0
 *
 * A plugin for the ImpactJS engine to display minimaps and a radar for entities.
 *
 * Benjamin Kaiser
 * me@benjaminkaiser.biz
 * http://www.benjaminkaiser.biz
 *
 * This work is licensed under the MIT License (MIT). To view a copy of this license, visit https://github.com/dryas/impactjs-minimap/blob/master/LICENSE.
 *
 * It would be very nice when you inform me, with an short email, when you are using this plugin in a project. Thanks.
 */

ig.module(
	'plugins.minimap.minimap'
)
.requires(
	'impact.game'
)
.defines(function() {
	ig.Game.inject({

	// Cache for the map canvases:
	maps: [],

	/*
	 * drawMiniMap(name, posx, posy, entities = [])
	 *
	 * Draws a map on the screen.
	 *
	 * Parameters:
	 *      name           = Name of the map to display (same as
	 *                       used on generateMiniMap())
	 *      posx           = Position (X) where the map should be displayed
	 *      posy           = Position (Y) where the map should be displayed
	 *      entities       = Array of entities which position should be
	 *                       displayed on the map
	 *      showviewport   = [true/false] Show the current viewport on Map
	 *      viewportcolor  = Define color of screenclipping
	 */
	drawMiniMap: function(name, posx, posy, entities, showviewport, viewportcolor)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [drawMiniMap()]: no name parameter set";

		// Optional parameters "posx" and "posy". Set to ("posx", "posy") 0 by default:
		posx = typeof posx !== 'undefined' ? posx : 0;
		posy = typeof posy !== 'undefined' ? posy : 0;

		// Optional parameter "viewport" and "viewportcolor":
		viewport = typeof viewport !== 'undefined' ? viewport : false;
		viewportcolor = typeof viewportcolor !== 'undefined' ? viewportcolor : '#f0f';

		// Get scaling factor:
		var s = ig.system.scale;

		// Get canvas and 2d context:
		var ctx = ig.system.context;

		// Save current state of the canvas:
		ctx.save();

		// Draw minimap background:
		ctx.drawImage(this.maps[name], posx, posy);

		// Draw entities position on the minimap:
		if (typeof entities !== 'undefined')
		{
			for(var entityid = 0; entityid < entities.length; entityid++)
			{
				// Get entities by type:
				var entity = this.getEntitiesByType(entities[entityid]);

				for (i=0; i < entity.length; i++)
				{
					// Calculate x and y:
					x = posx + (this.maps[name + '_offsetX'] * s) + (((this.maps[name].width - ((this.maps[name + '_offsetX'] * 2) * s))) * (entity[i].pos.x / ig.game.collisionMap.pxWidth));
					y = posy + (this.maps[name + '_offsetY'] * s) + (((this.maps[name].height - ((this.maps[name + '_offsetY'] * 2) * s)))* (entity[i].pos.y / ig.game.collisionMap.pxHeight));

					// Draw entity as dot on the map or use an icon:
					if (typeof entity[i].miniMap['icon'] !== 'undefined')
					{
						typeof entity[i].miniMap['iconOffset']['x'] !== 'undefined' ? entity[i].miniMap['iconOffset']['x'] : 0;
						typeof entity[i].miniMap['iconOffset']['y'] !== 'undefined' ? entity[i].miniMap['iconOffset']['y'] : 0;

						var mapIcon = new ig.Image(entity[i].miniMap['icon']);

						// Draw Icon:
						mapIcon.draw(
							(x / s) + (this.maps[name].width / ig.game.collisionMap.width / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.width / 2) + entity[i].miniMap['iconOffset']['x'],
							(y / s) + (this.maps[name].height / ig.game.collisionMap.height / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.height / 2) + entity[i].miniMap['iconOffset']['y']
						);
					}
					else
					{
						typeof entity[i].miniMap['mapSize'] !== 'undefined' ? entity[i].miniMap['mapSize'] : 5;
						typeof entity[i].miniMap['mapColor'] !== 'undefined' ? entity[i].miniMap['mapColor'] : '#FFFFFF';

						ctx.fillStyle = entity[i].miniMap['mapColor'];

						// Draw square:
						ctx.fillRect(
							x + ((this.maps[name].width / ig.game.collisionMap.width) / 2) - (entity[i].miniMap['mapSize'] / 2),
							y + ((this.maps[name].height / ig.game.collisionMap.height) / 2) - (entity[i].miniMap['mapSize'] / 2),
							entity[i].miniMap['mapSize'],
							entity[i].miniMap['mapSize']
						);
					}
				}
			}
		}

		// Draw viewport:
		if (showviewport)
		{
			// Load background map data:
			var bglayers = ig.game.backgroundMaps;

			// Get the current layer:
			var map = bglayers[0];

			var viewportx = ((this.maps[name].width / s * (ig.system.width / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetX'] * 2);
			var viewporty = ((this.maps[name].width / s * (ig.system.height / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetY'] * 2);
			// Add 0.5 to the starting position (workaround to draw sharp shapes):
			var xa = ((this.maps[name + '_offsetX'] * s) + (this.maps[name].width - (this.maps[name + '_offsetX'] * s * 2)) * (map.scroll.x / ig.game.collisionMap.pxWidth)) + posx + + 0.5;
			var ya = ((this.maps[name + '_offsetY'] * s) + (this.maps[name].height - (this.maps[name + '_offsetY'] * s * 2)) * (map.scroll.y / ig.game.collisionMap.pxHeight)) + posy + 0.5;

			ctx.lineWidth = 1;
			ctx.strokeStyle = viewportcolor;
			ctx.strokeRect(
				xa,
				ya,
				viewportx,
				viewporty
			);
		}

		// Restore former state of the canvas:
		ctx.restore();
	},

	/*
	 * generateMiniMap(name, width, height, layer = [0])
	 *
	 * Generates a map, needs to be called in the init function.
	 *
	 * Parameters:
	 *      name      = Name of the map to generate (need to be used at
	 *                  drawMiniMap())
	 *      width     = Width of the minimap
	 *      height    = Height of the minimap
	 *      layer     = Array of layer ids that should be displayed on
	 *                  the generated map
	 *
	 * ATTENTION: Do NOT call it in the draw function because this will have
	 *            a big impact on performance, if the map needs to be redrawn
	 *            on every frame!
	 */
	generateMiniMap: function(name, width, height, layer)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no name parameter set";
		if (typeof width === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no width parameter set";
		if (typeof height === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no height parameter set";

		// Optional parameter "layer". Set to (Layer) 0 by default:
		layer = typeof layer !== 'undefined' ? layer : [0];

		// Get scaling factor:
		var s = ig.system.scale;

		// create the minimap canvas
		var maptemp = ig.$new('canvas');
		maptemp.width = width * s;
		maptemp.height = height * s;

		// Get the canvas 2d context for map creation:
		var ctx = maptemp.getContext('2d');

		// Set solid background color for map:
		if(ig.game.clearColor)
		{
			ctx.fillStyle = ig.game.clearColor;
			ctx.fillRect(0, 0, maptemp.width, maptemp.height);
		}

		// Load background map data:
		var bglayers = ig.game.backgroundMaps;

		// Cycle through all layers that should be included in the map:
		for(var layerid = 0; layerid < layer.length; layerid++)
		{
			// Get the current layer:
			var map = bglayers[layer[layerid]];

			// Set fixed tilesize factor:
			var fWidth = 4;
			var fHeight = 4;

			// Calculate size of the tileset:
			var w = map.tiles.width * s;
			var h = map.tiles.height * s;
			var ws = w / map.tilesize * fWidth;
			var hs = h / map.tilesize * fHeight;

			// Resize tileset of the current map:
			var ts = ig.$new('canvas');
			var tsctx = ts.getContext('2d');
			ts.width = ws;
			ts.height = hs;
			tsctx.drawImage(map.tiles.data, 0, 0, w, h, 0, 0, ws, hs);

			this.maps[name + '_offsetX'] = Math.floor((width - (map.width * Math.floor(width / map.width))) / 2);
			this.maps[name + '_offsetY'] = Math.floor((height - (map.height * Math.floor(height / map.height))) / 2);

			// draw the map
			var tile = 0;

			for(var x = 0; x < map.width; x++)
			{
				for(var y = 0; y < map.height; y++)
				{
					// Does a tile exists on this position?
					if((tile = map.data[y][x]))
					{
						ctx.drawImage(
							ts,
							Math.floor(((tile-1) * s) % (ws/fWidth)) * fWidth,
							(Math.floor((tile-1) * s / (ws/fHeight)) * fHeight) * s,
							fWidth * s,
							fHeight * s,
							((x * Math.floor(width / map.width)) + this.maps[name + '_offsetX']) * s,
							((y * Math.floor(height / map.height)) + this.maps[name + '_offsetY']) * s,
							Math.floor(width / map.width) * s,
							Math.floor(height / map.height) * s
						);
					}
				}
			}

			// Cache map:
			this.maps[name] = maptemp;
		}
	}
	})
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="pref_language_options">
        <item>@string/pref_language_label_auto</item>
        <item>@string/pref_language_label_english</item>
        <item>@string/pref_language_label_chinese</item>
    </string-array>

    <string-array name="pref_language_values">
        <item>@string/pref_language_auto</item>
        <item>@string/pref_language_english</item>
        <item>@string/pref_language_chinese</item>
    </string-array>

    <string-array name="pref_resolution_options">
        <item>@string/pref_resolution_label_high</item>
        <item>@string/pref_resolution_label_medium</item>
        <item>@string/pref_resolution_label_low</item>
    </string-array>

    <string-array name="pref_resolution_values">
        <item>@string/pref_resolution_high</item>
        <item>@string/pref_resolution_medium</item>
        <item>@string/pref_resolution_low</item>
    </string-array>

    <string-array name="image_operations">
        <item>@string/action_save_image</item>
    </string-array>

</resources>


text:
package gtrie_test

import (
	"bufio"
	"github.com/MathieuTurcotte/go-trie/gtrie"
	"io"
	"log"
	"os"
	"strings"
	"testing"
)

func TestCreateUnsortedWords(t *testing.T) {
	_, err := gtrie.Create([]string{"ab", "ef", "cd"})

	if err == nil {
		t.Errorf("expected error when creating trie from unsorted words")
	}
}

func TestTrie(t *testing.T) {
	words := []string{"abfg", "acfg", "adfg"}
	missings := []string{"", "foo", "été", "adfgg", "adf"}

	trie, err := gtrie.Create(words)
	if err != nil {
		log.Fatal(err)
	} else if trie == nil {
		log.Fatal("returned trie was nil")
	}

	// Ensure that stored words are accepted.
	for _, word := range words {
		if !trie.Accepts(word) {
			t.Errorf("expected %s to be accepted", word)
		}
	}

	// Ensure that missings words aren't accepted.
	for _, word := range missings {
		if trie.Accepts(word) {
			t.Errorf("expected %s to be rejected", word)
		}
	}

	// Ensure that the graph is minimal by counting the number of nodes.
	size := gtrie.Size(trie)
	if size != 5 {
		t.Errorf("expected size of 5 but got %s", size)
	}
}

// Test behavior with a large dictionary.
func TestAccept(t *testing.T) {
	words := readWords("words.txt")
	trie, err := gtrie.Create(readWords("words.txt"))
	if err != nil {
		log.Fatal(err)
	}

	for _, word := range words {
		if !trie.Accepts(word) {
			t.Error(word)
		}
	}
}

func BenchmarkAccepts(b *testing.B) {
	b.StopTimer()

	words := []string{"evropenescului", "simulantilor", "zburdalniciilor"}
	trie, err := gtrie.Create(readWords("words.txt"))
	if err != nil {
		b.Fatal(err)
	}

	b.StartTimer()

	for i := 0; i < b.N; i++ {
		for _, word := range words {
			if !trie.Accepts(word) {
				b.Fatal(word)
			}
		}
	}
}

func readWords(filename string) (words []string) {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)

	for {
		word, rerr := reader.ReadString('\n')
		if rerr != nil {
			if rerr == io.EOF {
				break
			} else {
				log.Fatal(err)
			}
		}
		words = append(words, strings.TrimSpace(word))
	}
	return
}


text:
@extends('layouts.default')

@section('css')
    <link rel="stylesheet" href="/css/wangEditor.css">
@stop

@section('content')
    @if (Auth::check())

微博列表

                @include('shared/feed')

                    @include('shared.user_info', ['user' => Auth::user()])

                    @include('shared.stats', ['user' => Auth::user()])

    @else

                @include('shared/feed')

                    了解更多?

    @endif
@stop

@section('js')

@stop


text:
"""
Script that plots framewise displacement(fd),  RMS signal derivative (DVARS),
and meanSignal per subject per run and indicates potential outliers (motion-
induced artifacts) based on commonly used threshold of 0.2-0.5mm for FD and
0.3-0.5% for DVARS. 0.5 was used for DVARS and 0.5 was used for FD.
"""
import sys
import json
# Paths
pathtodata = '../../data/'
pathtofig = '../../results/figures/'
pathtofunction = '../utils/functions'
pathtographing = '../utils/graphing'
# Append fuction path
sys.path.append(pathtofunction)
# Import function
from basic_util import loadnib_dict, loadtxt_dict

# Append graphing path
sys.path.append(pathtographing)
# Import function

from graphoutlier_functions import plot_dvars, plot_fd, plot_meanSig

# load outlier files
dvars_out = json.load(open("../../results/texts/dvarsOutliers.txt"))
fd_out = json.load(open("../../results/texts/fdOutliers.txt"))

# need to create two loops, one for 1-9 and one for 10-16
# because of folder naming difference.

for i in range(1,10):
    for j in range(1,4):
        # set general path for reaching dvars and fd files
        # also path for saving files
        txtpath= pathtodata+'ds005/sub00'+`i`+'/BOLD/task001_run00'+`j`+'/QA/'
        # dvars path and name, call function
        dvarsfile=txtpath+'dvars.txt'
        dvarsfigname=pathtofig+'dvars_sub'+`i`+'run'+`j`+'.png'
        dvars_dict = loadtxt_dict(dvarsfile, dvarsfigname)
        dvars_outliers = dvars_out['sub'+`i`+'run'+`j`]
        plot_dvars(dvars_dict, dvars_outliers, saveit=True)
        # fd path and name, call function
        fdfile=txtpath+'fd.txt'
        fdfigname=pathtofig+'fd_sub'+`i`+'run'+`j`+'.png'
        fd_dict = loadtxt_dict(fdfile, fdfigname)
        fd_outliers = fd_out['sub'+`i`+'run'+`j`]
        plot_fd(fd_dict, fd_outliers, saveit=True)
        # mean path and name, call function
        niipath=pathtodata+'ds005/sub00'+`i`+'/BOLD/task001_run00'+`j`
        meandata=niipath+'/bold.nii.gz'
        meanfigname=pathtofig+'mean_sub'+`i`+'run'+`j`+'.png'
        data_dict = loadnib_dict(meandata, meanfigname)
        plot_meanSig(data_dict, saveit=True)

for i in range(10,17):
    for j in range(1,4):
        # set general path for reaching dvars and fd files
        # also path for saving files
        txtpath=pathtodata+'ds005/sub0'+`i`+'/BOLD/task001_run00'+`j`+'/QA/'
        # dvars path and name, call function
        dvarsfile=txtpath+'dvars.txt'
        dvarsfigname=pathtofig+'dvars_sub'+`i`+'run'+`j`+'.png'
        dvars_dict = loadtxt_dict(dvarsfile, dvarsfigname)
        dvars_outliers = dvars_out['sub'+`i`+'run'+`j`]
        plot_dvars(dvars_dict, dvars_outliers, saveit=True)
        # fd path and name, call function
        fdfile=txtpath+'fd.txt'
        fdfigname=pathtofig+'fd_sub'+`i`+'run'+`j`+'.png'
        fd_dict = loadtxt_dict(fdfile, fdfigname)
        fd_outliers = fd_out['sub'+`i`+'run'+`j`]
        plot_fd(fd_dict, fd_outliers, saveit=True)
        # mean path and name, call function
        niipath=pathtodata+'ds005/sub0'+`i`+'/BOLD/task001_run00'+`j`
        meandata=niipath+'/bold.nii.gz'
        meanfigname=pathtofig+'mean_sub'+`i`+'run'+`j`+'.png'
        data_dict = loadnib_dict(meandata, meanfigname)
        plot_meanSig(data_dict, saveit=True)


text:
@interface NSFileHandleViewController : SYViewController

@end


text:
<?php

namespace Vinicius73\ModelShield;

use Illuminate\Support\Collection;

class Manager
{
    /**
     * @var string
     */
    private $path;

    /**
     * @var Collection
     */
    private $rules;

    public function __construct(array $config)
    {
        $this->path = array_get($config, 'path');
        $this->rules = new Collection();
    }

    /**
     * @param string $key
     *
     * @return array
     */
    protected function loadRules($key)
    {
        if (!$this->rules->has($key)):
            $this->rules->put($key, $this->loadRulesFromFile($key));
        endif;

        return $this->rules->get($key);
    }

    /**
     * @param $key
     *
     * @return array
     */
    protected function loadRulesFromFile($key)
    {
        $file = $this->path.$key.'.php';

        /*
         * @TODO make Exception
         */

        return include $file;
    }

    /**
     * @param string $key
     * @param bool   $creating
     *
     * @return array
     */
    public function getRules($key, $creating = true)
    {
        switch ($creating):
            case true:
                return $this->getRulesCreating($key);
        break;
        case false:
                return $this->getRulesUpdating($key);
        break;
        default:
                return [];
        break;
        endswitch;
    }

    /**
     * @param string $key
     *
     * @return array
     */
    public function getRulesDefault($key)
    {
        $rules = $this->loadRules($key);

        return array_get($rules, 'default', []);
    }

    /**
     * @param string $key
     *
     * @return array
     */
    public function getRulesCreating($key)
    {
        $rules = $this->loadRules($key);

        $default = array_get($rules, 'default', []);
        $creating = array_get($rules, 'creating', []);

        return array_merge($default, $creating);
    }

    /**
     * @param string $key
     *
     * @return array
     */
    public function getRulesUpdating($key)
    {
        $rules = $this->loadRules($key);

        $default = array_get($rules, 'default', []);
        $updating = array_get($rules, 'updating', []);

        return array_merge($default, $updating);
    }

   /**
    * @param $key
    *
    * @return array
    */
   public function getCustomMessages($key)
   {
       $rules = $this->loadRules($key);

       return array_get($rules, 'custom_messages', []);
   }

   /**
    * @param $key
    *
    * @return array
    */
   public function getAttributeNames($key)
   {
       $rules = $this->loadRules($key);

       return array_get($rules, 'attribute_names', []);
   }
}


text:
package stainless
package extraction
package innerclasses

import inox.utils.Graphs._

trait DependencyGraph extends methods.DependencyGraph {
  protected val trees: innerclasses.Trees
  import trees._
  import symbols.given

  protected class LocalClassCollector extends ClassCollector(trees) with OOSelfTreeTraverser {

    var localClasses: Set[LocalClassDef] = Set.empty

    def traverse(lmd: LocalMethodDef): Unit = traverse(lmd.toFunDef)

    override def traverse(expr: Expr): Unit = expr match {
      case FunctionInvocation(id, _, _) =>
        register(id)
        super.traverse(expr)

      case MethodInvocation(_, id, _, _) =>
        register(id)
        super.traverse(expr)

      case LetClass(lcds, body) =>
        localClasses = localClasses ++ lcds.toSet

        lcds foreach (_.parents foreach traverse)
        lcds foreach (_.methods foreach traverse)
        lcds foreach (_.fields foreach traverse)
        traverse(body)

      case LocalClassConstructor(lct: LocalClassType, args) =>
        lct.ancestors foreach traverse
        lct.tps foreach traverse
        args foreach traverse

      case LocalClassSelector(expr, _, tpe) =>
        traverse(expr)
        traverse(tpe)

      case LocalMethodInvocation(receiver, _, _, tps, args) =>
        traverse(receiver)
        tps foreach traverse
        args foreach traverse

      case _ =>
        super.traverse(expr)
    }
  }

  private def collectClasses(fd: FunDef): (Set[Identifier], Set[LocalClassDef]) = {
    val collector = new LocalClassCollector
    collector.traverse(fd)
    (collector.result, collector.localClasses)
  }

  private def laws(cd: LocalClassDef): Set[Identifier] = {
    cd.globalAncestors.map(_.cd).reverse.foldLeft(Map[Symbol, Identifier]()) {
      case (laws, cd) =>
        val methods = cd.methods
        val newLaws = methods
          .filter(id => symbols.getFunction(id).flags.exists(_.name == "law"))
          .map(id => id.symbol -> id)
        laws -- methods.map(_.symbol) ++ newLaws
    }.values.toSet
  }

  override protected def computeDependencyGraph: DiGraph[Identifier, SimpleEdge[Identifier]] = {
    var g = super.computeDependencyGraph

    symbols.functions.values foreach { fd =>
      val (deps, lcds) = collectClasses(fd)
      deps foreach { dep => g += SimpleEdge(fd.id, dep) }
      lcds foreach { lcd =>
        laws(lcd) foreach { law => g += SimpleEdge(law, fd.id) }
        g += SimpleEdge(fd.id, lcd.id)
      }
    }

    g
  }

}


text:
* Optional:
  * `id`: document-unique id for the tag.
  * `valueVar`: the scripting-variable name to which each value of a collection or property will be bound. Default `id` + "Value", or "cValue" if no id was specified.

### Currently Implemented:
Nothing.

### Planned:
* _forEachInList_: Evaluates its body for each member of an indexed collection.
  * Required attributes:
    * `collection`: the `java.util.List` over which the tag will iterate. This should be a JSP expression or an EL value expression.
  * Optional attributes:
    * `from`: the first index for which to evaluate the tag's body. Default `0`.
    * `to`: the last index for which to evaluate the tag's body. Default `collection.size() - 1`.
    * `step`: the quantity by which the index should be incremented for each iteration. Default `1`.
    * `indexVar`: the scripting-variable name to which the current index will be bound. Default `id` + "Index", or "cIndex" if no id was specified.
  * Scripting variables:
    * `cIndex`: the current index into the collection. Nested scope.
    * `cValue`: the value in the collection at the current index. Nested scope.
* _forEachIndexedProperty_: Evaluates its body for each value of an indexed property on a Java Bean.
  * Required attributes:
    * `name`: the name of the bean variable, as declared in a prior scriptlet or `<jsp:useBean id="name">`.
    * `property`: the name of the indexed property to access.
  * Optional attributes:
    * `from`: the first index for which to evaluate the tag's body. Default `0`.
    * `to`: the last index for which to evaluate the tag's body. Default `n`, where `n` is the last index of the property.
    * `step`: the quantity by which the index should be incremented for each iteration. Default `1`.
    * `indexVar`: the scripting-variable name to which the current index will be bound. Default `id` + "Index", or "cIndex" if no id was specified.
  * Scripting variables:
    * `cIndex`: the current index into the property. Nested scope.
    * `cValue`: the value of the property at the current index. Nested scope.
* _forEachInMap_: Evaluates its body for each key-value pair in a Map.
  * Required attributes:
    * `collection`: the `java.util.Map` over which the tag will iterate. This should be a JSP expression or an EL value expression.
  * Optional attributes:
    * `keyVar`: the scripting-variable name to which the current key will be bound. Default `id` + "Key", or "cKey" if no id was specified.
  * Scripting variables:
    * `cKey`: the current key on the map. Nested scope.
    * `cValue`: the value in the map for the current key. Nested scope.
* _forEachMappedProperty_: Evaluates its body for each key-value pair of a mapped property on a Java Bean. Mapped properties are not strictly part of the Java Beans Framework, but they're an extremely common extension.
  * Required attributes:
    * `name`: the name of the bean variable, as declared in a prior scriptlet or `<jsp:useBean id="name">`.
    * `property`: the name of the mapped property to access.
  * Optional attributes:
    * `keyVar`: the scripting-variable name to which the current key will be bound. Default `id` + "Key", or "cKey" if no id was specified.
  * Scripting variables:
    * `cKey`: the current key on the property. Nested scope.
    * `cValue`: the value of the property for the current key. Nested scope.


text:
package it.cure.core.implem.security;

import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * This is a secure envelope for buffer
 *
 * It is needed to manage the length of the buffer after the encrypting process. The routine getting the
 * packet fill a predetermined buffer so the returned buffer would be different in length respect to the encrypted  buffer
 * raising a BadPaddingException.
 *
 * The envelope object is a trick to serialize/deserialize an object of certain size!
 *
 *
 */
public class SecEnvelope implements Serializable{

	private static final long serialVersionUID = -3526755881940960726L;
	private byte[] cryptedBuffer;
	private int idxKey;

	/**
	 * Constructor
	 *
	 * @param bufferToEncrypt
	 * @param key
	 * @param keyIndex
	 *
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 */
	public SecEnvelope(byte[] bufferToEncrypt, byte[] key, int keyIndex) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		super();

		this.idxKey = keyIndex;
		this.cryptedBuffer = SecUtils.encrypt(key, bufferToEncrypt);
	}

	/**
	 * Get the decrypted buffer
	 * @param key
	 *
	 * @return the cryptedBuffer
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 */
	public byte[] getDecryptedBuffer(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		return SecUtils.decrypt(key, cryptedBuffer);
	}

	/**
	 * @return the idxKey
	 */
	public int getIdxKey() {
		return idxKey;
	}

}


text:
class "hudchattextbox" ( gui.textbox )

function hudchattextbox:hudchattextbox( parent, name )
	gui.textbox.textbox( self, parent, name, "" )
	self.hudchat = parent

	self:setEditable( false )
	self:setMultiline( true )
	self:setScheme( "Chat" )

	self.borderOpacity = 0
end

function hudchattextbox:drawForeground()
	local property = "textbox.outlineColor"
	local width    = self:getWidth()
	local height   = self:getHeight()
	local color    = color( self:getScheme( property ) )
	color.a        = color.a * self.borderOpacity
	graphics.setColor( color )
	graphics.setLineWidth( 1 )
	graphics.rectangle( "line", 0, 0, width, height )
end

function hudchattextbox:getHudChat()
	return self.hudchat
end

function hudchattextbox:invalidateLayout()
	local parent = self:getHudChat()
	self:setWidth( parent:getWidth() - 2 * 36 )
	self:setHeight( parent:getHeight() - 46 - 9 - 2 * 36 )

	gui.panel.invalidateLayout( self )
end

function hudchattextbox:setHideTime( duration )
	self.hideTime = duration
end

gui.register( hudchattextbox, "hudchattextbox" )