text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Adminlogin extends CI_Controller
{
	public function __construct()
    {
    	parent::__construct();
		/*require_once APPPATH.'../vendor/autoload.php';
		$client = new Google_Client();
		$client->setApplicationName($this->config->item('applicationName'));
		$client->setDeveloperKey($this->config->item('developerKey'));
        $client->setClientSecret($this->config->item('clientSecret'));
        $client->setClientId($this->config->item('clientId'));
        $client->setRedirectUri("http://localhost/crannyapplocal/admin/googlelogin");
        $client->addScope("https://www.googleapis.com/auth/userinfo.email");

        if ($client->getAccessToken()) {
          $userData = $objOAuthService->userinfo->get();
          $access_token = $client->getAccessToken();
        } else {
          $authUrl = $client->createAuthUrl();
          echo 'Google Login';
        }
        die();*/
		$this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
		$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
		$this->output->set_header('Cache-Control: post-check=0, pre-check=0',false);
		$this->output->set_header('Pragma: no-cache');
		$this->load->database();
		$this->load->model('adminuserModel');
  	}

    /**
    * Check if the user is logged in, if he's not,
    * send him to the login page
    * @return void
    */
	function dashboard()
	{
		if($this->session->userdata('is_logged_in'))
		{
			$data['mainContent'] = 'admin/dashboardPage';
			$this->load->view('admin/includes/template', $data);
		}
		else
		{
			redirect('admin/login');
		}
	}

	function index()
	{
		if($this->session->userdata('is_logged_in'))
		{
			$data['mainContent'] = 'admin/dashboardPage';
			$this->load->view('admin/includes/template', $data);
		}
		else
		{
            $authUrl = '';
            $redirect_uri = "http://localhost/crannyapplocal/admin/login";
			require_once APPPATH.'../vendor/autoload.php';
            $client = new Google_Client();
            $client->setApplicationName($this->config->item('applicationName'));
            $client->setDeveloperKey($this->config->item('developerKey'));
            $client->setClientSecret($this->config->item('clientSecret'));
            $client->setClientId($this->config->item('clientId'));
            $client->setRedirectUri($redirect_uri);
            $client->addScope("https://www.googleapis.com/auth/userinfo.email");

            // Send Client Request
            $objOAuthService = new Google_Service_Oauth2($client);

            // Add Access Token to Session
            if (isset($_GET['code'])) {
              $client->authenticate($_GET['code']);
              $_SESSION['access_token'] = $client->getAccessToken();
              $client->setAccessToken($_SESSION['access_token']);
              $userData = $objOAuthService->userinfo->get();
              //header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
              $uemail = $userData->email;
              // check in database if this email exists
              $is_emailExist = $this->adminuserModel->findDuplicateEmail($uemail);
              if($is_emailExist)
              {
                $data = array(
                  'username' => $userData->name,
                  'is_logged_in' => true,
                  'user_id' => '',//$userinfo[0]['adminuser_id'],
                  'usertype' => ''//$userinfo[0]['user_role']
                );
                $this->session->set_userdata($data);
                redirect('admin/dashboard');
              }
              else
              {
                unset($_SESSION['access_token']);
                redirect('admin/login');
              }
              //print '
'; print_r($userData); print_r($_SESSION);exit;
            }
            else {
              $authUrl = $client->createAuthUrl();
              $data['authUrl'] = $authUrl;
            }

            /*// Set Access Token to make Request
            if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
              $client->setAccessToken($_SESSION['access_token']);
              $userData = $objOAuthService->userinfo->get();
              print '
';
              print_r($userData);
              print_r($_SESSION);
              exit;
            }

            if ($client->getAccessToken()) {
              $userData = $objOAuthService->userinfo->get();
              $access_token = $client->getAccessToken();
              $_SESSION['access_token'] = $client->getAccessToken();
            } else {
              $authUrl = $client->createAuthUrl();
              //echo 'Google Login';
              $data['authUrl'] = $authUrl;
            }*/

			$this->load->view('admin/login', $data);
        }

	}  //// End Of Index Function

	public function googleLoginSubmit ()
	{
	    require_once APPPATH.'../vendor/autoload.php';
        $client = new Google_Client();
        $client->setApplicationName($this->config->item('applicationName'));
		$client->setDeveloperKey($this->config->item('developerKey'));
        $client->setClientSecret($this->config->item('clientSecret'));
        $client->setClientId($this->config->item('clientId'));
        //$client->setRedirectUri("http://localhost/crannyapplocal/admin/googlelogin");
        //$client->addScope("https://www.googleapis.com/auth/userinfo.email");

        // Send Client Request
        $objOAuthService = new Google_Service_Oauth2($client);
        $userData = $objOAuthService->userinfo->get();
        if ($client->getAccessToken()) {
          $userData = $objOAuthService->userinfo->get();
          $access_token = $client->getAccessToken();
        } else {
          $authUrl = $client->createAuthUrl();
        }
	    echo "
"; print_r($userData);
    	exit;
		//$this->load->view('google', $data);
    }

	/*** encript the password
    * @return mixed    */
	function __encrip_password($password)
	{
		return base64_encode($password);
	}

	/**
    * check the username and the password with the database
    * @return void
    */
	function validateCredentials()
	{
		$username = $this->input->post('username');
		$password = $this->__encrip_password($this->input->post('password'));
		// echo $username." ".$password;
		$userinfo = $this->adminuserModel->validate($username,$password);
		//echo '
'; print_r($userinfo); exit;
	    if($userinfo)
		{
			$data = array(
				'username' => $userinfo[0]['user_name'],
				'is_logged_in' => true,
				'user_id' => $userinfo[0]['adminuser_id'],
				'usertype' => $userinfo[0]['user_role']
			);
			$this->session->set_userdata($data);

			$remember = $this->input->post('remember_me');
			//print_r($this->session->userdata()); exit;
			if($remember)
			{
				$cookie = array(
					'name'   => 'remember_me',
					'value'  => $username,
					'expire' => '86500'
				);
				$this->input->set_cookie($cookie);

				$cookie1 = array(
					'name'   => 'remember_pass',
					'value'  => $password,
					'expire' => '86500'
				);

				$this->input->set_cookie($cookie1);
			}
			elseif(!$remember)
			{
				if($this->input->cookie('remember_me')!='')
				{
					$cookie = array(
						'name'   => 'remember_me',
						'value'  => $username,
						'expire' => ''
					);
					$this->input->set_cookie($cookie);
				}
				if($this->input->cookie('remember_pass')!='')
				{
					$cookie1 = array(
						'name'   => 'remember_pass',
						'value'  => $password,
						'expire' => ''
					);
					$this->input->set_cookie($cookie1);
				}
			}
			redirect('admin/dashboard');
		}
		else // incorrect username or password
		{
			$username = '';
			if($this->input->cookie('remember_me')!='')
			{
				$username = $this->input->cookie('remember_me');

			}
			$data['username'] = $username;
			$data['uname_error'] = "Invalid email or password.";
			$this->load->view('admin/login', $data);
		}
	}

	/**
    * Destroy the session, and logout the user.
    * @return void
    */

	function logout()
	{
	   $this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
       $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
       $this->output->set_header('Cache-Control: post-check=0, pre-check=0',false);
       $this->output->set_header('Pragma: no-cache');
	   $data = array(
				     'username' => '',
				     'is_logged_in' => false,
					 'user_id' => '',
					 'usertype' => ''
		            );
		$this->session->unset_userdata($data);
        $this->session->sess_destroy();
		unset($_SESSION['access_token']);
		redirect('admin');
	}

    /**
    * The method just loads the forgot password view
    * @return void
    */
	function forgot()
	{
		$this->load->view('admin/forgot');
	}

	/**
    * check the username  with the database
    * @return void
    */
	function forgot_validateCredentials()
	{
		$username = $this->input->post('email_id');
		$is_valid = $this->adminuserModel->forgot_validate($username);

		if($is_valid)
		{
			/** for generate 4 digit password */
			$alphabet = "0123456789";
			$newpass = array(); //remember to declare $pass as an array
			$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
			//exit;
			for ($i = 0; $i < 6; $i++)
			{
				$n = rand(0, $alphaLength);
				$newpass[] = $alphabet[$n];
			}
			//print_r($newpass);

			$pass = implode("",$newpass);
			//	exit;

			$data['report'] = $this->adminuserModel->update_validate($username,$this->__encrip_password($pass));
			$data['query'] = $this->adminuserModel->get_all();
			//echo $data['query'][0]['email']; exit;
			/* echo $data['query'][0]['name'];*/

			if ($data['report'] > 0)
			{
				//$new_password = $pass; // New password create
				$template_details = array(
											 'name' => "Admin",
											 'email' => $data['query'][0]['email'],
											 'link' =>  base_url(),
											 'path' =>  base_url().'assets/images/',
											 'password' => $pass,
											 'admin_email' => $this->config->item('admin_email')
										   );
				 //echo '
'; print_r( $template_details );

				$msg = $this->parser->parse('mail_templetes/forgotpassword',$template_details, TRUE);
				/*echo $msg;
				exit;*/
				$project_name = $this->config->item('project_name');
				$this->email->from($this->config->item('from_email'), $project_name);
				$this->email->to($data['query'][0]['email']);
				$this->email->subject($project_name." - Reset Password");
				$this->email->message($msg);
				$send = $this->email->send();

				//redirect('admin/login');

				$data['succ_msg'] = "We have reset the password and send it to your registered email address.";
			}
			$this->load->view('admin/forgot', $data);
		}
		else // incorrect username
		{
		   $data['uname_error'] = "Email does not exist.";
		   $this->load->view('admin/forgot', $data);
		}
	}

	/*************************************************************** ADD Data *******************************************************/

	function add()
    {
		//if save button was clicked, get the data sent via post
		if ($this->input->server('REQUEST_METHOD') === 'POST')
		{
			$this->form_validation->set_rules('name', 'name', 'required');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]');
			$this->form_validation->set_rules('email', 'email', 'required|valid_email');
			//$this->form_validation->set_rules('number', 'Contact Number', 'required|max_length[15]|min_length[10]');
			$this->form_validation->set_error_delimiters('
', '');

			if ($this->form_validation->run() == FALSE) // validation hasn't been passed
			{
				//$data['mainContent'] = 'admin/adminuser/authorAdd';
				//$this->load->view('admin/includes/template', $data);
			}
			else // passed validation proceed to post success logic
			{
				$is_emailExist = $this->adminuserModel->findDuplicateEmail($this->input->post('email'));
				$is_nameExist = $this->adminuserModel->findDuplicateName($this->input->post('name'));

				if($is_emailExist)
				{
					/*$this->session->set_flashdata('flash_message', 'Email already Exist.');
					$this->session->set_flashdata('flash_type', 'error');

					redirect('admin/adminuser/add');   // or whatever logic needs to occur*/

					$msg= 'Email '.EXIST;
					$msgtype= 'error';

					//$data['mainContent'] = 'admin/adminuser/authorAdd';
					//$this->load->view('admin/includes/template', $data);
				}
				elseif($is_nameExist)
				{
					/*$this->session->set_flashdata('flash_message', 'Name already Exist.');
					$this->session->set_flashdata('flash_type', 'error');

					redirect('admin/adminuser/add');   // or whatever logic needs to occur*/

					$msg= 'Name '.EXIST;
					$msgtype= 'error';
				}
				else
				{

					// build array for the model
					//$encrypted_string = ENCODE($pass, ('my_random_salt'.'my_secret_password'));
					$form_data = array(
									'name' => set_value('name'),
									'email' => $this->input->post('email'),
									'password' => base64_encode($this->input->post('password')),
									'isActive' => $this->input->post('isActive')

								);

					// run insert model to write data to db

					if ($this->adminuserModel->setAdminloginData($form_data) == TRUE) // the information has therefore been successfully saved in the db
					{
						$this->session->set_flashdata('flash_message', 'User'.ADDMSG);
						$this->session->set_flashdata('flash_type', 'success');

						redirect('admin/adminuser');   // or whatever logic needs to occur
					}
					else
					{
					   $this->session->set_flashdata('flash_message', 'ErrorWhile Saving Data.');
					   $this->session->set_flashdata('flash_type', 'error');
					}

				}

			}
		}
		$data['message']=isset($msg)?$msg:'';
		$data['messagetype']=isset($msgtype)?$msgtype:'';
		$data['mainContent'] = 'admin/adminuser/adminuserAdd';
		$this->load->view('admin/includes/template', $data);
	}  /// End Of ADD Function

	/************************************************************ Update item by his id  * @return void ************************/
    public function update()
    {
		//admin id
		$id = $this->uri->segment(4);

		//if save button was clicked, get the data sent via post
		if ($this->input->server('REQUEST_METHOD') === 'POST')
		{
			//form validation
			$this->form_validation->set_rules('name', 'name', 'required');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]');
			$this->form_validation->set_rules('email', 'email', 'required|valid_email');
			//$this->form_validation->set_rules('number', 'Contact Number', 'required|max_length[15]|min_length[10]');
			$this->form_validation->set_error_delimiters('
', '');

			//if the form has passed through the validation
			if ($this->form_validation->run())
			{

				$is_nameExist = $this->adminuserModel->GetDuplicateName($this->input->post('name'),$id); // return 1 or blank
				$is_emailExist = $this->adminuserModel->GetDuplicateEmail($this->input->post('email'),$id); // return 1 or blank
				//echo $is_nameExist;
				//exit;
				if($is_nameExist)
				{
					/*$this->session->set_flashdata('flash_message', 'Name'.EXIST);
					$this->session->set_flashdata('flash_type', 'error');

					redirect('admin/adminuser/update/'.$id);   // or whatever logic needs to occur*/
					$msg= 'Name '.EXIST;
					$msgtype= 'error';
				}
				else if($is_emailExist)
				{
					/*$this->session->set_flashdata('flash_message', 'Email'.EXIST);
					$this->session->set_flashdata('flash_type', 'error');

					redirect('admin/adminuser/update/'.$id);   // or whatever logic needs to occur*/
					$msg= 'Email '.EXIST;
					$msgtype= 'error';
				}
				else
				{

					// build array for the model
					$form_data = array(
									'name' => set_value('name'),
									'email' => $this->input->post('email'),
									'password' => base64_encode($this->input->post('password')),
									'isActive' => $this->input->post('isActive')
								);
					// End Slider Image upload
					//if the insert has returned true then we show the flash message
					if($this->adminuserModel->setUpdatedAdminloginData($id, $form_data) == TRUE)
					{
						$this->session->set_flashdata('flash_message', 'User'.UPDATEMSG);
						$this->session->set_flashdata('flash_type', 'success');

					}
					else
					{
						$this->session->set_flashdata('flash_message', 'ErrorWhile Saving Data.');
						$this->session->set_flashdata('flash_type', 'error');
					}
					redirect('admin/adminuser');

				}//// End of $is_nameExist this condition

			}//validation run

		}
		// product data
		$data['message']=isset($msg)?$msg:'';
		$data['messagetype']=isset($msgtype)?$msgtype:'';

		$data['adminuser'] = $this->adminuserModel->get_adminuser_by_id($id);

		// load the view
		$data['mainContent'] = 'admin/adminuser/adminuserEdit';
		$this->load->view('admin/includes/template', $data);

    } // End Of Update Function

    /**
    * Delete author by his id
    * @return void
    */
    public function delete()
    {
		$id = $this->input->post('id');
		if($this->adminuserModel->deleteadminuserData($id) == true)
		{
			/*  $this->session->set_flashdata('flash_message', 'delete');
		 	 $this->session->set_flashdata('flash_type', 'success');*/
		}
		else
		{
			/*	$this->session->set_flashdata('flash_message', 'error');
			$this->session->set_flashdata('flash_type', 'error');*/
		}

		echo "User";
		//  redirect('admin/authors');
    } // End Of Delete Function

	/**
    * Delete authors by his id
    * @return void
    */
    public function deleteSelected()
    {
		if ($this->input->server('REQUEST_METHOD') === 'POST')
		{
			// authors id array
			$id = $this->input->post('itemId');
			// $this->adminuserModel->deleteauthorData($id);
			if($this->adminuserModel->deleteadminuserData($id) == true)
			{
				/*$this->session->set_flashdata('flash_message', 'User'.DELETEMSG);
				$this->session->set_flashdata('flash_type', 'success');*/
			}
			else
			{
				/*$this->session->set_flashdata('flash_message', 'error');
				$this->session->set_flashdata('flash_type', 'error');*/
			}
			//redirect('admin/adminuser');

			echo "User";
		}
	} // End of Selected Delete

	/* Change status */
	public function changestatus()
    {
		$data['adminuser'] = $this->adminuserModel->get_adminuser_by_id($this->input->post('id'));
		echo $status = ($data['adminuser'][0]['isActive']==1)?0:1;

		$data_to_store = array(
			'isActive' => $status,
		);
		$this->adminuserModel->setUpdatedAdminloginData($this->input->post('id'), $data_to_store);

    } // End of update status

	///////////// Chnage Page Size For Paginarion //////////
	function chagepagesize()
    {
	  $limit = $this->input->post('limit');
	  $data = array('pagesize' => $limit);
	  $this->db->where('module','adminuser');
	  $this->db->update('pagesize',$data);

	  $report = array();
	  $report['error'] = $this->db->error();
	  $report['message'] = $this->db->error();

	  if($report !== 0)
	  {
			return true;
	  }
	  else
	  {
			return false;
	  }
	}
	/* delete profile pic. */
	public function deleteimage()
    {
		$upload_path = $this->config->item('base_path').'assets/uploads/adminuser';
		$id = $this->input->post('admin_id');
		$data_to_store = array(
			'profile_pic' => '',
		);
		$this->adminuserModel->deleteadminuserimage($upload_path,$id,$data_to_store);

    }

	////// For Export Data To Excel ///////
	public function exportToexcel()
	{
			$data['export'] = $this->adminuserModel->getAllAdminlogin();
			$this->load->view('admin/adminuser/admin_excel', $data);
	}
}
?>


text:
#ifndef StyleMarqueeData_h
#define StyleMarqueeData_h

#include "Length.h"
#include "RenderStyleConstants.h"
#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>

namespace WebCore {

class StyleMarqueeData : public RefCounted<StyleMarqueeData> {
public:
    static PassRefPtr<StyleMarqueeData> create() { return adoptRef(new StyleMarqueeData); }
    PassRefPtr<StyleMarqueeData> copy() const { return adoptRef(new StyleMarqueeData(*this)); }

    bool operator==(const StyleMarqueeData& o) const;
    bool operator!=(const StyleMarqueeData& o) const
    {
        return !(*this == o);
    }

    Length increment;
    int speed;

    int loops; // -1 means infinite.

    unsigned behavior : 2; // EMarqueeBehavior
    EMarqueeDirection direction : 3; // not unsigned because EMarqueeDirection has negative values

private:
    StyleMarqueeData();
    StyleMarqueeData(const StyleMarqueeData&);
};

} // namespace WebCore

#endif // StyleMarqueeData_h

redpajama_set_name: RedPajamaGithub


text:
package org.sagebionetworks.repo.model.json;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

import com.fasterxml.jackson.annotation.JsonAnySetter;

/**
 * Generic object that catches all unmapped fields from a json object into a dedicated otherProperties map. The
 * {@link #setOtherProperty(String, Object)} will be invoked by the jackson deserializer when a field is not mapped to
 * any property in the object. Extend this object only when using jackson.
 *
 * @author Marco
 */
public class CatchAllJsonObject {

	private Map<String, Object> otherProperties;

	@JsonAnySetter
	public void setOtherProperty(String property, Object value) {
		if (otherProperties == null) {
			otherProperties = new LinkedHashMap<>();
		}
		otherProperties.put(property, value);
	}

	public Map<String, Object> getOtherProperties() {
		return otherProperties;
	}

	public void setOtherProperties(Map<String, Object> otherProperties) {
		this.otherProperties = otherProperties;
	}

	@Override
	public int hashCode() {
		return Objects.hash(otherProperties);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CatchAllJsonObject other = (CatchAllJsonObject) obj;
		return Objects.equals(otherProperties, other.otherProperties);
	}

	@Override
	public String toString() {
		return "SESJsonObject [otherProperties=" + otherProperties + "]";
	}

}


text: * Forked love-launcher to work with meld


text:
<?php

namespace Koremutake;

use PHPUnit_Framework_Testcase;

class KoremutakeTest extends PHPUnit_Framework_Testcase
{
    /**
     * Provider for returning pairs encoded/decoded pairs.
     */
    public function translationPairProvider()
    {
        return [
            ['ba', 0],
            ['be', 1],
            ['tre', 127],
            ['beba', 128],
            ['bebe', 129],
            ['koremutake', 10610353957],
        ];
    }

    public function testConstants()
    {
        $this->assertEquals(Koremutake::LENGTH, count(Koremutake::PHONEMES));
    }

    /**
     * @dataProvider translationPairProvider
     */
    public function testEncode($encoded, $decoded)
    {
        $this->assertEquals($encoded, Koremutake::encode($decoded));
    }

    /**
     * @dataProvider translationPairProvider
     */
    public function testDecode($encoded, $decoded)
    {
        $this->assertEquals($decoded, Koremutake::decode($encoded));
    }

    /**
     * @expectedException Koremutake\UnexpectedTokenException
     */
    public function testUnexpectedToken()
    {
        Koremutake::decode('zz');
    }
}


text:
<?= t('Remove user from group "%s"', $group['name']) ?>

<?= t('Do you really want to remove the user "%s" from the group "%s"?', $user['name'] ?: $user['username'], $group['name']) ?>

        <?= $this->url->link(t('Yes'), 'GroupListController', 'removeUser', array('group_id' => $group['id'], 'user_id' => $user['id']), true, 'btn btn-red') ?>
        <?= t('or') ?>
        <?= $this->url->link(t('cancel'), 'GroupListController', 'users', array('group_id' => $group['id']), false, 'close-popover') ?>


text:
'use strict';

// Configuration for our Mocha test suite.
module.exports = {
  color: true,
  // Run tests in parallel.
  parallel: true,
  // Recurse through all tests in the test directory.
  recursive: true,
};


text:
/**
 * template
 * @author guanbingchang@wanda.cn
 */

import list from './list/list';
import add from './add/add';
import detail from './detail/detail';
import edit from './edit/edit';

let templateModule =  angular.module('app.template', [
   	list.name,
    add.name,
    detail.name,
    edit.name
]);

export default templateModule;


text:
const Task            = require('../../../tasks/-task');
const CordovaRaw      = require('./raw');
const logger          = require('../../../utils/logger');

module.exports = Task.extend({
  project: undefined,

  run() {
    logger.info('Running cordova prepare');
    let prepare = new CordovaRaw({
      project: this.project,
      api: 'prepare',
    });

    return prepare.run({ fetch: true });
  }
});


text:
const util = require('util');
const miniSuite = require('./lib/miniSuite');

function toUnixNewline(str) {
  return str.replace(/\r\n|\r/g, '\n');
}
function toWindowNewLine(str) {
  return str.replace(/\r\n|\r|\n/g, '\r\n');
}
function inspect(value, depth){
  console.log(util.inspect(value, false, depth || 10));
}

const assertResult = miniSuite.getSuite('assertResult', {
  'defined': function (result, assert) {
    assert.ok(result, 'result');
    assert.isObject(result, 'result');
  },
  'timing': function (result, assert) {
    assert.isNumber(result.start, 'start');
    assert.isNumber(result.end, 'end');
    assert.isNumber(result.duration, 'duration');
  },
  'paths': function (result, assert) {
    assert.isString(result.cwd, 'cwd');
    assert.isString(result.src, 'src');
  },
  'output': function (result, assert) {
    assert.isObject(result.res, 'res');
    assert.isString(result.output, 'output');
    assert.isObject(result.parsed, 'parsed');
  },
  'tasks': function (result, assert) {
    assert.isArray(result.tasks, 'tasks');
  },
  'options': function (result, assert) {
    assert.isObject(result.options, 'options');
  }
});

module.exports = {
  toWindowNewLine: toWindowNewLine,
  toUnixNewline: toUnixNewline,
  inspect: inspect,
  assertResult: assertResult
};


text:
package etcd

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"
)

var logger *etcdLogger

func SetLogger(l *log.Logger) {
	logger = &etcdLogger{l}
}

func GetLogger() *log.Logger {
	return logger.log
}

type etcdLogger struct {
	log *log.Logger
}

func (p *etcdLogger) Debug(args ...interface{}) {
	msg := "DEBUG: " + fmt.Sprint(args)
	p.log.Println(msg)
}

func (p *etcdLogger) Debugf(f string, args ...interface{}) {
	msg := "DEBUG: " + fmt.Sprintf(f, args)
	// Append newline if necessary
	if !strings.HasSuffix(msg, "\n") {
		msg = msg + "\n"
	}
	p.log.Print(msg)
}

func (p *etcdLogger) Warning(args ...interface{}) {
	msg := "WARNING: " + fmt.Sprint(args)
	p.log.Println(msg)
}

func (p *etcdLogger) Warningf(f string, args ...interface{}) {
	msg := "WARNING: " + fmt.Sprintf(f, args)
	// Append newline if necessary
	if !strings.HasSuffix(msg, "\n") {
		msg = msg + "\n"
	}
	p.log.Print(msg)
}

func init() {
	// Default logger uses the go default log.
	SetLogger(log.New(ioutil.Discard, "go-etcd", log.LstdFlags))
}


text:
import { SlackBot } from "../../bot/bot";

export interface AppLocal {
    bot: SlackBot;
}


text:
RSpec.describe Module do
  describe "#class_name" do
    it "returns just the name of the class/module" do
      expect(YARD::CodeObjects::Base.class_name).to eq "Base"
    end
  end

  describe "#namespace" do
    it "returns everything before the class name" do
      expect(YARD::CodeObjects::Base.namespace_name).to eq "YARD::CodeObjects"
    end
  end
end


text:
<?php

use app\modules\user\assets\TokenRequestAsset;

$this->title = Yii::t('user','check account\'s status');
$this->params['breadcrumbs'][] = ['label' => Yii::t('site','login'), 'url' => ['login']];
$this->params['breadcrumbs'][] = $this->title;

TokenRequestAsset::register($this);

?>

<div id="request-token">
    <?= $requestForm ?>
</div>


text:
require 'json'
require 'net/http'
require 'percy/capybara'
require 'capybara'
require 'selenium/webdriver'

ENV['PERCY_DEBUG'] = '0'
ENV['WEBSERVER_QUIET'] = '--quiet'
# CSS widths: iPhone: 375, Pixel: 411, Desktop: 1400.
DEFAULT_WIDTHS = [375, 411, 1400]
VIEWPORT_WIDTH = 1400
VIEWPORT_HEIGHT = 100000
HOST = 'localhost'
PORT = '8000'
WEBSERVER_TIMEOUT_SECS = 15
CONFIGS = %w(canary prod)
AMP_RUNTIME_FILE = 'dist/amp.js'
AMP_3P_FRAME_FILE = 'dist.3p/current/integration.js'
BUILD_STATUS_URL = 'https://amphtml-percy-status-checker.appspot.com/status'
BUILD_PROCESSING_POLLING_INTERVAL_SECS = 5 # Poll every 5 seconds
BUILD_PROCESSING_PROGRESS_POLLS = 12 # Print a message every minute
BUILD_PROCESSING_TIMEOUT_SECS = 60 * 10 # Wait for up to 10 minutes
PERCY_BUILD_URL = 'https://percy.io/ampproject/amphtml/builds'
OUT = ENV['TRAVIS'] ? '/dev/null' : :out

# Colorize logs.
def red(text); "\e[31m#{text}\e[0m"; end
def cyan(text); "\e[36m#{text}\e[0m"; end
def green(text); "\e[32m#{text}\e[0m"; end
def yellow(text); "\e[33m#{text}\e[0m"; end

# Logs a message to the console.
#
# Args:
# - mode: 'verbose', 'info', 'warning', or 'error'.
# - message: Message to print on the console.
def log(mode, message)
  if mode == 'verbose' and not ENV['TRAVIS']
    puts green('VERBOSE: ') + message
  end
  if mode == 'info'
    puts green('INFO: ') + message
  end
  if mode == 'warning'
    puts yellow('WARNING: ') + message
  end
  if mode == 'error'
    puts red('ERROR: ') + message
  end
end

# Launches a background AMP webserver for unminified js using gulp.
#
# Returns:
# - Process ID of server process.
def launch_web_server
  webserver_cmd =
      "gulp serve --host #{HOST} --port #{PORT} #{ENV['WEBSERVER_QUIET']}"
  spawn(webserver_cmd, :out => OUT)
end

# Checks if a webserver is up and running.
#
# Returns:
# - true if the server returns an OK (200) response code.
def is_web_server_running
  http = Net::HTTP.start(HOST, PORT)
  response = http.head('/')
  response.code == '200'
rescue SystemCallError
  false
end

# Waits for the webserver to start up.
#
# Returns:
# - true if webserver is running.
def wait_for_web_server
  tries = 0
  until is_web_server_running
    sleep(1)
    tries += 1
    break if tries > WEBSERVER_TIMEOUT_SECS
  end
  is_web_server_running
end

# Checks the current status of a Percy build.
#
# Args:
# - build_id: ID of the ongoing Percy build.
# Returns:
# - The full response from the build status server.
def get_build_status(build_id)
  status_uri = URI("#{BUILD_STATUS_URL}?build_id=#{build_id}")
  Net::HTTP.start(status_uri.host, status_uri.port, use_ssl: true) do |https|
    request = Net::HTTP::Get.new(status_uri)
    response = https.request(request)
    if response.code == '200'
      return JSON.parse(response.body)
    end
  end
rescue SystemCallError
  # Fail gracefully, and wait for the next attempt.
  return
end

# Waits for Percy to finish processing a build.
#
# Args:
# - build_id: ID of the ongoing Percy build.
# Returns:
# - The eventual status of the Percy build.
def wait_for_build_completion(build_id)
  log('info',
      'Waiting for Percy build ' + cyan("#{build_id}") + ' to be processed...')
  tries = 0
  until %w(finished failed).include?(
      (status = get_build_status(build_id))['state'])
    sleep(BUILD_PROCESSING_POLLING_INTERVAL_SECS)
    tries += 1
    if tries % BUILD_PROCESSING_PROGRESS_POLLS == 0
      log('info',
          'Still waiting for Percy build ' + cyan("#{build_id}") +
          ' to be processed...')
    end
    break if tries > (
        BUILD_PROCESSING_TIMEOUT_SECS / BUILD_PROCESSING_POLLING_INTERVAL_SECS)
  end
  status
end

# Verifies that a Percy build succeeded and didn't contain any visual diffs.
#
# Args:
# - status: The eventual status of the Percy build.
# - build_id: ID of the Percy build.
def verify_build_status(status, build_id)
  if status['state'] == 'failed'
    raise "Percy build failed: #{status['failure_reason']}"
  end
  if %w(pending processing).include?(status['state'])
    raise "Percy build not processed after #{BUILD_PROCESSING_TIMEOUT_SECS}s"
  end
  if status['total_comparisons_diff'] != 0
    branches = %w(master release canary amp-release)
    if branches.any? { |branch| status['branch'].include? branch }
      # If there are visual diffs on master or a release branch, fail Travis.
      # For master, print instructions for how to approve new visual changes.
      if status['branch'] === 'master'
        log('error',
            'Found visual diffs. If the changes are intentional, you must ' +
            'approve the build at ' + cyan("#{PERCY_BUILD_URL}/#{build_id}") +
            ' in order to update the baseline snapshots.')
      end
      raise "Found visual diffs on branch #{status['branch']}."
    else
      # For PR branches, just print a warning since the diff may be intentional,
      # with instructions for how to approve the new snapshots so they are used
      # as the baseline for future visual diff builds.
      log('warning',
          'Percy build ' + cyan("#{build_id}") + ' contains visual diffs.')
      log('warning',
          'If they are intentional, you must first approve the build at ' +
          cyan("#{PERCY_BUILD_URL}/#{build_id}") +
          ' to allow your PR to be merged.')
      log('warning',
          'You must then wait for your merged PR to be tested on master, and ' +
          'approve the next "master" build at ' + cyan("#{PERCY_BUILD_URL}") +
          ' in order to update the visual diff baseline snapshots.')
    end
  else
    log('info',
        'Percy build ' + cyan("#{build_id}") + ' contains no visual diffs.')
  end
end

# Closes the webserver process with the given process ID.
#
# Args:
# - pid: Process ID of the webserver.
def close_web_server(pid)
  Process.kill('INT', pid)
  Process.wait(pid, Process::WNOHANG)
  sleep(0.1)  # The child node process has an asynchronous stdout. See #10409.
end

# Loads all the visual tests from a well-known pseudo-json config file.
def load_visual_tests_config_json
  json_file = File.open(
      File.join(
          File.dirname(__FILE__),
          '../../test/visual-diff/visual-tests'),
      'r')
  json_file.read
end

# Configures the Chrome browser (optionally in headless mode)
def configure_browser
  if ARGV.include? '--headless'
    chrome_args = %w[--no-sandbox --disable-extensions --headless --disable-gpu]
  else
    chrome_args = %w[--no-sandbox --disable-extensions]
  end
  options = Selenium::WebDriver::Chrome::Options.new
  chrome_args.each do |option|
    options.add_argument(option)
  end
  options.add_emulation(
    device_metrics: {
      width: VIEWPORT_WIDTH,
      height: VIEWPORT_HEIGHT,
      pixelRatio: 1,
      touch: false
    }
  )
  Capybara.register_driver :chrome do |app|
    http_client = Selenium::WebDriver::Remote::Http::Default.new
    http_client.read_timeout = 120

    Capybara::Selenium::Driver.new(
      app,
      browser: :chrome,
      http_client: http_client,
      options: options,
      driver_opts: {log_path: 'chromedriver.log'}
    )
  end
  Capybara.default_driver = :chrome
  Capybara.javascript_driver = :chrome
end

# Initializes the Capybara driver
#
# Args:
# - assets_dir: Path relative to amphtml/ that contains all asset files
# - assets_base_url: Path relative to server root from where assets are served
def initialize_capybara(assets_dir, assets_base_url)
  Capybara.default_max_wait_time = 5
  Capybara.run_server = false
  Capybara.app_host = "http://#{HOST}:#{PORT}"
  Percy::Capybara.use_loader(
      :filesystem, assets_dir: assets_dir, base_url: assets_base_url)
  page = Capybara::Session.new(:chrome)
end

# Runs the visual tests.
#
# Args:
# - visualTestsConfig: JSON object containing the config for the visual tests.
def run_visual_tests(visual_tests_config)
  Percy.config.default_widths = DEFAULT_WIDTHS
  assets_base_url = visual_tests_config['assets_base_url']
  assets_dir = File.expand_path(
      "../../../#{visual_tests_config['assets_dir']}",
      __FILE__)
  page = initialize_capybara(assets_dir, assets_base_url)
  build = Percy::Capybara.initialize_build
  build_id = build['data']['id']
  File.write('PERCY_BUILD_ID', build_id)
  log('info', 'Started Percy build ' + cyan("#{build_id}") + '...')
  generate_snapshots(page, visual_tests_config['webpages'])
  result = Percy::Capybara.finalize_build
  if result['success']
    log('info',
        'Build ' + cyan("#{build_id}") + ' is now being processed by Percy.')
  else
    log('error', 'Percy build ' + cyan("#{build_id}") + ' failed!')
    raise 'Build failure'
  end
end

# Cleans up any existing AMP config from the runtime and 3p frame.
def cleanup_amp_config
  log('verbose', 'Cleaning up existing AMP config')
  cmd_runtime = "gulp prepend-global --target #{AMP_RUNTIME_FILE} --remove"
  cmd_3p_frame = "gulp prepend-global --target #{AMP_3P_FRAME_FILE} --remove"
  system(cmd_runtime, :out => OUT)
  system(cmd_3p_frame, :out => OUT)
end

# Applies the AMP config to the runtime and 3p frame.
#
# Args:
# - config: Config to apply. One of 'canary' or 'prod'.
def apply_amp_config(config)
  log('verbose', 'Switching to the ' + cyan("#{config}") + ' AMP config')
  cmd_runtime = "gulp prepend-global --local_dev " +
      "--target #{AMP_RUNTIME_FILE} --#{config}"
  cmd_3p_frame = "gulp prepend-global --local_dev " +
      "--target #{AMP_3P_FRAME_FILE} --#{config}"
  system(cmd_runtime, :out => OUT)
  system(cmd_3p_frame, :out => OUT)
end

# Sets the AMP config, launches a server, and generates Percy snapshots for a
# set of given webpages.
#
# Args:
# - page: Page object used by Percy for snapshotting.
# - webpages: JSON object containing details about the pages to snapshot.
def generate_snapshots(page, webpages)
  # Include a blank snapshot on master, to allow for PR builds to be skipped.
  if ARGV.include? '--master'
    Percy::Capybara.snapshot(page, name: 'Blank page')
  end
  cleanup_amp_config
  CONFIGS.each do |config|
    apply_amp_config(config)
    log('verbose',
        'Generating snapshots using the ' + cyan("#{config}") + ' AMP config')
    begin
      pid = launch_web_server
      unless wait_for_web_server
        log('error', 'Failed to start webserver')
        raise 'Webserver launch failure'
      end
      page.visit('/')
      snapshot_webpages(page, webpages, config)
    ensure
      close_web_server(pid)
    end
  end
end

# Generates Percy snapshots for a set of given webpages.
#
# Args:
# - page: Page object used by Percy for snapshotting.
# - webpages: JSON object containing details about the pages to snapshot.
# - config: Config being used. One of 'canary' or 'prod'.
def snapshot_webpages(page, webpages, config)
  webpages.each do |webpage|
    url = webpage['url']
    if url.include? 'examples/visual-tests/amp-by-example/' and
        !ARGV.include? '--master'
      next
    end
    name = "#{webpage['name']} (#{config})"
    forbidden_css = webpage['forbidden_css']
    loading_incomplete_css = webpage['loading_incomplete_css']
    loading_complete_css = webpage['loading_complete_css']
    enable_experiments(page, webpage['experiments'])
    log('verbose', 'Navigating to page ' + yellow(url) + '...')
    page.visit(url)
    verify_css_elements(
        page,
        url,
        forbidden_css,
        loading_incomplete_css,
        loading_complete_css)
    Percy::Capybara.snapshot(page, name: name)
    clear_experiments(page)
  end
end

# Verifies that all CSS elements are as expected before taking a snapshot.
#
# Args:
# - page: Page object used by Percy for snapshotting.
# - url: URL to be snapshotted.
# - forbidden_css:
#       Array of CSS elements that must not be found in the page.
# - loading_incomplete_css:
#       Array of CSS elements that must eventually be removed from the page.
# - loading_complete_css:
#       Array of CSS elements that must eventually appear on the page.
def verify_css_elements(
    page, url, forbidden_css, loading_incomplete_css, loading_complete_css)
  page.has_no_css?('.i-amphtml-loader-dot')  # Implicitly waits for page load.
  if forbidden_css
    forbidden_css.each do |css|
      if page.has_css?(css)  # No implicit wait.
        log('error', cyan("#{url}") + ' has CSS element ' + cyan("#{css}"))
        raise 'Invalid CSS element'
      end
    end
  end
  if loading_incomplete_css
    loading_incomplete_css.each do |css|
      unless page.has_no_css?(css) # Implicitly waits for element to disappear.
        log('error',
            cyan("#{url}") + ' still has CSS element ' + cyan("#{css}"))
        raise 'Invalid CSS element'
      end
    end
  end
  if loading_complete_css
    loading_complete_css.each do |css|
      unless page.has_css?(css) # Implicitly waits for element to appear.
        log('error',
            cyan("#{url}") + ' does not yet have CSS element ' + cyan("#{css}"))
        raise 'Missing CSS element'
      end
    end
  end
end

# Enables the given AMP experiments.
#
# Args:
# - page: Page object used by Percy for snapshotting.
# - experiments: List of experiments to enable.
def enable_experiments(page, experiments)
  if experiments
    page.driver.browser.manage.add_cookie(
        :name => 'AMP_EXP', :value => experiments.join('%2C'))
    log('verbose', 'Setting AMP experiments ' + cyan(experiments.join(', ')))
  end
end

# Clears all AMP experiment cookies.
#
# Args:
# - page: Page object used by Percy for snapshotting.
def clear_experiments(page)
  page.driver.browser.manage.delete_all_cookies
end

# Enables debugging if requested via command line.
def set_debugging_level
  if ARGV.include? '--debug'
    ENV['PERCY_DEBUG'] = '1'
    Selenium::WebDriver.logger.level = :debug
    ENV['WEBSERVER_QUIET'] = ''
  end
  if ARGV.include? '--percy_debug'
    ENV['PERCY_DEBUG'] = '1'
  end
  if ARGV.include? '--chrome_debug'
    Selenium::WebDriver.logger.level = :debug
  end
  if ARGV.include? '--webserver_debug'
    ENV['WEBSERVER_QUIET'] = ''
  end
end

# Enables us to require percy checks on GitHub, and yet, not have to do a full
# build for every PR.
def create_empty_build
  log('info',
      'Skipping visual diff tests and generating a blank Percy build...')
  Percy.config.default_widths = [375]
  blank_assets_dir = File.expand_path(
      '../../../examples/visual-tests/blank-page',
      __FILE__)
  page = initialize_capybara(blank_assets_dir, '')
  build = Percy::Capybara.initialize_build
  Percy::Capybara.snapshot(page, name: 'Blank page')
  Percy::Capybara.finalize_build
end

# Launches a webserver, loads test pages, and generates Percy snapshots.
def main
  if ARGV.include? '--verify'
    build_id = File.open('PERCY_BUILD_ID', 'r').read
    status = wait_for_build_completion(build_id)
    verify_build_status(status, build_id)
    exit
  end
  configure_browser
  if ARGV.include? '--skip'
    create_empty_build
    exit
  end
  unless ENV['PERCY_PROJECT'] && ENV['PERCY_TOKEN']
    log('error', 'Could not find ' + cyan('PERCY_PROJECT') + ' and ' +
        cyan('PERCY_TOKEN') + ' environment variables.')
    raise 'Missing environment variables'
  end
  set_debugging_level
  visual_tests_config_json = load_visual_tests_config_json
  visual_tests_config = JSON.parse(visual_tests_config_json)
  run_visual_tests(visual_tests_config)
end

if __FILE__ == $0
  main
end


text:
'use strict';

var Backbone = require('backbone');

module.exports = Backbone.View.extend({
  tagName: 'div',
  className: 'message-item',
  render: function() {

    var timestamp = window.layerSample.dateFormat(this.model.sentAt);
    var parts = '';

    if (!this.model.isDestroyed) {
      this.model.parts.forEach(function(part) {
        switch(part.mimeType) {
          case 'text/plain':
            parts += '
' + part.body + '
';
            break;
          case 'text/quote':
            parts += '
' + part.body + '
';
            break;
        }
      });

      this.$el.append('

' +
                      '
' +
                        '' + this.model.sender.displayName + '' +
                        '
' + parts + '
' +
                      '
' +
                      '
' + timestamp +
                        '' + this.getMessageStatus() + '' +
                      '
');
    }
  },
  getMessageStatus: function() {
    switch (this.model.readStatus) {
      case 'NONE':
        return 'unread';
      case 'SOME':
        return 'read by some';
      case 'ALL':
        return 'read';
      default:
        return 'unread';
    }
  },
  getMessageParts: function(part) {
    var bubbleType = '';

    switch (part.mimeType) {
      case 'text/plain':
        bubbleType = 'text';
        break;
      case 'text/quote':
        bubbleType = 'quote';
        break;
    }

    return '
' + part.body + '
';
  }
});


text:
package org.kaazing.mina.netty.channel;

import static org.jboss.netty.channel.Channels.succeededFuture;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.WriteCompletionEvent;

/**
 * The default {@link WriteCompletionEvent} implementation.
 */
public class DefaultWriteCompletionEventEx implements WriteCompletionEvent {

    private Channel channel;
    private long writtenAmount;

    /**
     * Initializes the instance.
     */
    public void init(Channel channel, long writtenAmount) {
        if (channel == null) {
            throw new NullPointerException("channel");
        }
        if (writtenAmount <= 0) {
            throw new IllegalArgumentException(
                    "writtenAmount must be a positive integer: " + writtenAmount);
        }

        this.channel = channel;
        this.writtenAmount = writtenAmount;
    }

    @Override
    public Channel getChannel() {
        return channel;
    }

    @Override
    public ChannelFuture getFuture() {
        return succeededFuture(getChannel());
    }

    @Override
    public long getWrittenAmount() {
        return writtenAmount;
    }

    @Override
    public String toString() {
        String channelString = getChannel().toString();
        StringBuilder buf = new StringBuilder(channelString.length() + 32);
        buf.append(channelString);
        buf.append(" WRITTEN_AMOUNT: ");
        buf.append(getWrittenAmount());
        return buf.toString();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bothalia 2: 88 (1927)

#### Original name
Puccinia alepideae Doidge

### Remarks
null


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light.NoActionBar">
        <item name="colorPrimary">@android:color/holo_blue_bright</item>
        <item name="colorPrimaryDark">@android:color/holo_blue_dark</item>
        <item name="windowActionBar">false</item>
    </style>

    <!-- Button style -->
    <style name="CalcButton">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:textSize">20sp</item>
        <item name="android:layout_margin">3dp</item>
        <item name="android:background">@drawable/button_shape</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

</resources>


text:
package fr.pizzeria.ihm;

public class SupprimerPizzaAction extends Action {

	public SupprimerPizzaAction(IhmHelper helper) {
		super("Supprimer une pizza", helper);
	}

	@Override
	public void execute() {
		System.out.println("Vous voulez supprimez une pizza veuillez choisir laquelle (Code)");
		String ancienCode = helper.getScanner().next();
		helper.getStockage().delete(ancienCode);

		System.out.println("Pizza supprimer avec succes \n");

	}

}


text:
layout: news_item
title: Giovanna Guidoboni, lauréate d'une Chaire Gutenberg
date: 2014-10-13
author: Vincent
fullname: Vincent Huber
categories: [news]
tags: [cemosis]
---

[Madame Giovanna Guidoboni](http://www.cemosis.fr/home/actualites/bienvenueagiovannaguidoboni), professeur à l'université de Purdue (IUPUI) et titulaire d'une chaire d'attractivité Labex IRMIA/IUPUI, vient d'obtenir une prestigieuse Chaire Gutenberg.

En collaboration avec Christophe Prud'homme et son équipe, elle travaille sur la modélisation des flux sanguins cérébraux, oculaires et leurs interactions.

Lancé à l'initiative du Cercle Gutenberg, le programme des [Chaires Gutenberg](http://www.region-alsace.eu/article/les-chaires-gutenberg) est financé par la Région Alsace et la Communauté Urbaine de Strasbourg pour faciliter l'accueil en Alsace, pendant une période d'environ un an, de chercheurs de niveau international invités par des établissements d'enseignement supérieur et de recherche.
Ils y mèneront un programme de recherche en liaison avec un ou plusieurs laboratoire(s) alsacien(s) et pourront participer à l'enseignement, organiser des séminaires et donner des conférences dont, si possible, certaines seront destinées à un public plus large que les seuls spécialistes.
Tous les champs disciplinaires sont éligibles.

Plus d'informations sur la procédure de demande de chaires Gutenberg et sur les anciens titulaires : [ici](http://www.alsace.cnrs.fr/archive_actu/SCOM/ChairesGutenberg2014.pdf).


text:
namespace DAVA
{
class UIScrollViewContainer;

class UIScrollSystem : public UISystem
{
public:
    UIScrollSystem();
    ~UIScrollSystem() override;

    void ScheduleScrollToControl(UIControl* control);
    void ScheduleScrollToControlWithAnimation(UIControl* control, float32 animationTime);

protected:
    void RegisterControl(UIControl* control) override;
    void UnregisterControl(UIControl* control) override;
    void RegisterComponent(UIControl* control, UIComponent* component) override;
    void UnregisterComponent(UIControl* control, UIComponent* component) override;

    void Process(DAVA::float32 elapsedTime) override;
    void ForceProcessControl(float32 elapsedTime, UIControl* control) override;

private:
    struct ScheduledControl
    {
        ScheduledControl(UIControl* control_, bool withAnimation_ = false, float32 animationTime_ = 0.3f)
            : withAnimation(withAnimation_)
            , animationTime(animationTime_)
        {
            control = control_;
        }

        RefPtr<UIControl> control;
        bool withAnimation = false;
        float32 animationTime = 0;
    };

    void PrepareForScreenshotImpl(UIControl* control);
    void ScheduleScrollToControlImpl(UIControl* control, bool withAnimation, float32 animationTime);
    void ScrollToScheduledControl(const ScheduledControl& c);
    Vector<UIScrollViewContainer*> scrollViewContainers;

    Vector<ScheduledControl> scheduledControls;
};
}


text:
#include <byebug.h>

static VALUE mByebug;   /* Ruby Byebug Module object */

static VALUE tracing = Qfalse;
static VALUE post_mortem = Qfalse;
static VALUE verbose = Qfalse;

static VALUE catchpoints = Qnil;
static VALUE breakpoints = Qnil;
static VALUE tracepoints = Qnil;

static VALUE raised_exception = Qnil;

static ID idPuts;
static ID idEmpty;

/* Hash table with active threads and their associated contexts */
VALUE threads = Qnil;

/*
 *  call-seq:
 *    Byebug.breakpoints -> array
 *
 *  Returns an array of breakpoints.
 */
static VALUE
Breakpoints(VALUE self)
{
  UNUSED(self);

  if (NIL_P(breakpoints))
    breakpoints = rb_ary_new();

  return breakpoints;
}

/*
 *  call-seq:
 *    Byebug.catchpoints -> array
 *
 *  Returns an array of catchpoints.
 */
static VALUE
Catchpoints(VALUE self)
{
  UNUSED(self);

  return catchpoints;
}

/*
 *  call-seq:
 *    Byebug.raised_exception -> exception
 *
 *  Returns raised exception when in post_mortem mode.
 */
static VALUE
Raised_exception(VALUE self)
{
  UNUSED(self);

  return raised_exception;
}

#define IS_STARTED  (catchpoints != Qnil)
static void
check_started()
{
  if (!IS_STARTED)
  {
    rb_raise(rb_eRuntimeError, "Byebug is not started yet.");
  }
}

static void
trace_print(rb_trace_arg_t * trace_arg, debug_context_t * dc,
            const char *file_filter, const char *debug_msg)
{
  char *fullpath = NULL;
  const char *basename;
  int filtered = 0;
  const char *event = rb_id2name(SYM2ID(rb_tracearg_event(trace_arg)));

  VALUE rb_path = rb_tracearg_path(trace_arg);
  const char *path = NIL_P(rb_path) ? "" : RSTRING_PTR(rb_path);

  int line = NUM2INT(rb_tracearg_lineno(trace_arg));

  VALUE rb_mid = rb_tracearg_method_id(trace_arg);
  const char *mid = NIL_P(rb_mid) ? "(top level)" : rb_id2name(SYM2ID(rb_mid));

  VALUE rb_cl = rb_tracearg_defined_class(trace_arg);
  VALUE rb_cl_name = NIL_P(rb_cl) ? rb_cl : rb_mod_name(rb_cl);
  const char *defined_class = NIL_P(rb_cl_name) ? "" : RSTRING_PTR(rb_cl_name);

  if (!trace_arg)
    return;

  if (file_filter)
  {
#ifndef _WIN32
    fullpath = realpath(path, NULL);
#endif
    basename = fullpath ? strrchr(fullpath, '/') : path;

    if (!basename || strncmp(basename + 1, file_filter, strlen(file_filter)))
      filtered = 1;

#ifndef _WIN32
    free(fullpath);
#endif
  }

  if (!filtered)
  {
    if (debug_msg)
      rb_funcall(mByebug, idPuts, 1,
                 rb_sprintf("[#%d] %s\n", dc->thnum, debug_msg));
    else
      rb_funcall(mByebug, idPuts, 1,
                 rb_sprintf("%*s [#%d] %s@%s:%d %s#%s\n", dc->calced_stack_size,
                            "", dc->thnum, event, path, line, defined_class,
                            mid));
  }
}

static void
cleanup(debug_context_t * dc)
{
  dc->stop_reason = CTX_STOP_NONE;

  release_lock();
}

#define EVENT_TEARDOWN cleanup(dc);

#define EVENT_SETUP                                     \
  debug_context_t *dc;                                  \
  VALUE context;                                        \
  rb_trace_arg_t *trace_arg;                            \
                                                        \
  UNUSED(data);                                         \
                                                        \
  if (!is_living_thread(rb_thread_current()))           \
    return;                                             \
                                                        \
  thread_context_lookup(rb_thread_current(), &context); \
  Data_Get_Struct(context, debug_context_t, dc);        \
                                                        \
  if (CTX_FL_TEST(dc, CTX_FL_IGNORE))                   \
    return;                                             \
                                                        \
  acquire_lock(dc);                                     \
                                                        \
  trace_arg = rb_tracearg_from_tracepoint(trace_point); \
  if (verbose == Qtrue)                                 \
    trace_print(trace_arg, dc, 0, 0);                   \

/* Functions that return control to byebug after the different events */

static VALUE
call_at(VALUE context_obj, debug_context_t * dc, ID mid, int argc, VALUE a0,
        VALUE a1)
{
  struct call_with_inspection_data cwi;
  VALUE argv[2];

  argv[0] = a0;
  argv[1] = a1;

  cwi.dc = dc;
  cwi.context_obj = context_obj;
  cwi.id = mid;
  cwi.argc = argc;
  cwi.argv = &argv[0];

  return call_with_debug_inspector(&cwi);
}

static VALUE
call_at_line(VALUE context_obj, debug_context_t * dc, VALUE file, VALUE line)
{
  return call_at(context_obj, dc, rb_intern("at_line"), 2, file, line);
}

static VALUE
call_at_tracing(VALUE context_obj, debug_context_t * dc, VALUE file, VALUE line)
{
  return call_at(context_obj, dc, rb_intern("at_tracing"), 2, file, line);
}

static VALUE
call_at_breakpoint(VALUE context_obj, debug_context_t * dc, VALUE breakpoint)
{
  dc->stop_reason = CTX_STOP_BREAKPOINT;
  return call_at(context_obj, dc, rb_intern("at_breakpoint"), 1, breakpoint, 0);
}

static VALUE
call_at_catchpoint(VALUE context_obj, debug_context_t * dc, VALUE exp)
{
  dc->stop_reason = CTX_STOP_CATCHPOINT;
  return call_at(context_obj, dc, rb_intern("at_catchpoint"), 1, exp, 0);
}

static VALUE
call_at_return(VALUE context_obj, debug_context_t * dc, VALUE file, VALUE line)
{
  dc->stop_reason = CTX_STOP_BREAKPOINT;
  return call_at(context_obj, dc, rb_intern("at_return"), 2, file, line);
}

static void
call_at_line_check(VALUE context_obj, debug_context_t * dc, VALUE breakpoint,
                   VALUE file, VALUE line)
{
  dc->stop_reason = CTX_STOP_STEP;

  if (breakpoint != Qnil)
    call_at_breakpoint(context_obj, dc, breakpoint);

  reset_stepping_stop_points(dc);
  call_at_line(context_obj, dc, file, line);
}

/* TracePoint API event handlers */

static void
line_event(VALUE trace_point, void *data)
{
  VALUE brkpnt, file, line, binding;

  EVENT_SETUP;

  file = rb_tracearg_path(trace_arg);
  line = rb_tracearg_lineno(trace_arg);
  binding = rb_tracearg_binding(trace_arg);

  if (RTEST(tracing))
    call_at_tracing(context, dc, file, line);

  if (!CTX_FL_TEST(dc, CTX_FL_IGNORE_STEPS))
    dc->steps = dc->steps <= 0 ? -1 : dc->steps - 1;

  if (dc->calced_stack_size <= dc->dest_frame)
  {
    dc->dest_frame = dc->calced_stack_size;
    CTX_FL_UNSET(dc, CTX_FL_IGNORE_STEPS);

    dc->lines = dc->lines <= 0 ? -1 : dc->lines - 1;
  }

  if (dc->steps == 0 || dc->lines == 0)
    call_at_line_check(context, dc, Qnil, file, line);

  brkpnt = Qnil;

  if (!NIL_P(breakpoints))
    brkpnt = find_breakpoint_by_pos(breakpoints, file, line, binding);

  if (!NIL_P(brkpnt))
    call_at_line_check(context, dc, brkpnt, file, line);

  EVENT_TEARDOWN;
}

static void
call_event(VALUE trace_point, void *data)
{
  VALUE brkpnt, klass, msym, mid, binding, self, file, line;

  EVENT_SETUP;

  if (dc->calced_stack_size <= dc->dest_frame)
    CTX_FL_UNSET(dc, CTX_FL_IGNORE_STEPS);

  dc->calced_stack_size++;

  dc->steps_out = dc->steps_out <= 0 ? -1 : dc->steps_out + 1;

  /* nil method_id means we are at top level so there can't be a method
   * breakpoint here. Just leave then. */
  msym = rb_tracearg_method_id(trace_arg);
  if (NIL_P(msym))
  {
    EVENT_TEARDOWN;
    return;
  }

  mid = SYM2ID(msym);
  klass = rb_tracearg_defined_class(trace_arg);
  binding = rb_tracearg_binding(trace_arg);
  self = rb_tracearg_self(trace_arg);
  file = rb_tracearg_path(trace_arg);
  line = rb_tracearg_lineno(trace_arg);

  brkpnt = Qnil;

  if (!NIL_P(breakpoints))
    brkpnt = find_breakpoint_by_method(breakpoints, klass, mid, binding, self);

  if (!NIL_P(brkpnt))
  {
    call_at_breakpoint(context, dc, brkpnt);
    call_at_line(context, dc, file, line);
  }

  EVENT_TEARDOWN;
}

static void
return_event(VALUE trace_point, void *data)
{
  EVENT_SETUP;

  dc->calced_stack_size--;

  if (dc->steps_out == 1)
    dc->steps = 1;
  else if ((dc->steps_out == 0) && (CTX_FL_TEST(dc, CTX_FL_STOP_ON_RET)))
  {
    VALUE file, line;

    reset_stepping_stop_points(dc);
    file = rb_tracearg_path(trace_arg);
    line = rb_tracearg_lineno(trace_arg);
    call_at_return(context, dc, file, line);
  }

  dc->steps_out = dc->steps_out <= 0 ? -1 : dc->steps_out - 1;

  EVENT_TEARDOWN;
}

static void
raw_call_event(VALUE trace_point, void *data)
{
  EVENT_SETUP;

  dc->calced_stack_size++;

  EVENT_TEARDOWN;
}

static void
raw_return_event(VALUE trace_point, void *data)
{
  EVENT_SETUP;

  dc->calced_stack_size--;

  EVENT_TEARDOWN;
}

static void
raise_event(VALUE trace_point, void *data)
{
  VALUE expn_class, ancestors, path, lineno, pm_context;
  int i;
  debug_context_t *new_dc;

  EVENT_SETUP;

  path = rb_tracearg_path(trace_arg);
  lineno = rb_tracearg_lineno(trace_arg);
  raised_exception = rb_tracearg_raised_exception(trace_arg);

  if (post_mortem == Qtrue)
  {
    pm_context = context_dup(dc);
    rb_ivar_set(raised_exception, rb_intern("@__bb_context"), pm_context);

    Data_Get_Struct(pm_context, debug_context_t, new_dc);
    rb_debug_inspector_open(context_backtrace_set, (void *)new_dc);
  }

  if (catchpoints == Qnil || dc->calced_stack_size == 0
      || RHASH_TBL(catchpoints)->num_entries == 0)
  {
    EVENT_TEARDOWN;
    return;
  }

  expn_class = rb_obj_class(raised_exception);
  ancestors = rb_mod_ancestors(expn_class);
  for (i = 0; i < RARRAY_LENINT(ancestors); i++)
  {
    VALUE ancestor_class, module_name, hit_count;

    ancestor_class = rb_ary_entry(ancestors, i);
    module_name = rb_mod_name(ancestor_class);
    hit_count = rb_hash_aref(catchpoints, module_name);

    /* increment exception */
    if (hit_count != Qnil)
    {
      rb_hash_aset(catchpoints, module_name, INT2FIX(FIX2INT(hit_count) + 1));
      call_at_catchpoint(context, dc, raised_exception);
      call_at_line(context, dc, path, lineno);
      break;
    }
  }

  EVENT_TEARDOWN;
}

/* Setup TracePoint functionality */

static void
register_tracepoints(VALUE self)
{
  int i;
  VALUE traces = tracepoints;

  UNUSED(self);

  if (NIL_P(traces))
  {
    int line_msk = RUBY_EVENT_LINE;
    int call_msk = RUBY_EVENT_CALL;
    int ret_msk = RUBY_EVENT_RETURN | RUBY_EVENT_B_RETURN | RUBY_EVENT_END;
    int raw_call_msk = RUBY_EVENT_C_CALL | RUBY_EVENT_B_CALL | RUBY_EVENT_CLASS;
    int raw_ret_msk = RUBY_EVENT_C_RETURN;
    int raise_msk = RUBY_EVENT_RAISE;

    VALUE tpLine = rb_tracepoint_new(Qnil, line_msk, line_event, 0);
    VALUE tpCall = rb_tracepoint_new(Qnil, call_msk, call_event, 0);
    VALUE tpReturn = rb_tracepoint_new(Qnil, ret_msk, return_event, 0);
    VALUE tpCCall = rb_tracepoint_new(Qnil, raw_call_msk, raw_call_event, 0);
    VALUE tpCReturn = rb_tracepoint_new(Qnil, raw_ret_msk, raw_return_event, 0);
    VALUE tpRaise = rb_tracepoint_new(Qnil, raise_msk, raise_event, 0);

    traces = rb_ary_new();
    rb_ary_push(traces, tpLine);
    rb_ary_push(traces, tpCall);
    rb_ary_push(traces, tpReturn);
    rb_ary_push(traces, tpCCall);
    rb_ary_push(traces, tpCReturn);
    rb_ary_push(traces, tpRaise);

    tracepoints = traces;
  }

  for (i = 0; i < RARRAY_LENINT(traces); i++)
    rb_tracepoint_enable(rb_ary_entry(traces, i));
}

static void
clear_tracepoints(VALUE self)
{
  int i;

  UNUSED(self);

  for (i = RARRAY_LENINT(tracepoints) - 1; i >= 0; i--)
    rb_tracepoint_disable(rb_ary_entry(tracepoints, i));
}

/* Byebug's Public API */

/*
 *  call-seq:
 *    Byebug.contexts -> array
 *
 *   Returns an array of all contexts.
 */
static VALUE
Contexts(VALUE self)
{
  volatile VALUE list;
  volatile VALUE new_list;
  VALUE context;
  threads_table_t *t_tbl;
  debug_context_t *dc;
  int i;

  UNUSED(self);

  check_started();

  new_list = rb_ary_new();
  list = rb_funcall(rb_cThread, rb_intern("list"), 0);

  for (i = 0; i < RARRAY_LENINT(list); i++)
  {
    VALUE thread = rb_ary_entry(list, i);

    thread_context_lookup(thread, &context);
    rb_ary_push(new_list, context);
  }

  Data_Get_Struct(threads, threads_table_t, t_tbl);
  st_clear(t_tbl->tbl);

  for (i = 0; i < RARRAY_LENINT(new_list); i++)
  {
    context = rb_ary_entry(new_list, i);
    Data_Get_Struct(context, debug_context_t, dc);
    st_insert(t_tbl->tbl, dc->thread, context);
  }

  return new_list;
}

/*
 *  call-seq:
 *    Byebug.thread_context(thread) -> context
 *
 *   Returns context of the thread passed as an argument.
 */
static VALUE
Thread_context(VALUE self, VALUE thread)
{
  VALUE context;

  UNUSED(self);

  check_started();

  thread_context_lookup(thread, &context);

  return context;
}

/*
 *  call-seq:
 *    Byebug.current_context -> context
 *
 *  Returns the current context.
 *    Note: Byebug.current_context.thread == Thread.current
 */
static VALUE
Current_context(VALUE self)
{
  VALUE context;

  UNUSED(self);

  thread_context_lookup(rb_thread_current(), &context);

  return context;
}

/*
 *  call-seq:
 *    Byebug.started? -> bool
 *
 *  Returns +true+ byebug is started.
 */
static VALUE
Started(VALUE self)
{
  UNUSED(self);

  return IS_STARTED;
}

/*
 *  call-seq:
 *    Byebug.stop -> bool
 *
 *  This method disables byebug. It returns +true+ if byebug was already
 *  disabled, otherwise it returns +false+.
 */
static VALUE
Stop(VALUE self)
{
  UNUSED(self);

  if (IS_STARTED)
  {
    clear_tracepoints(self);

    breakpoints = Qnil;
    catchpoints = Qnil;

    return Qfalse;
  }

  return Qtrue;
}

static VALUE
Stoppable(VALUE self)
{
  VALUE context;
  debug_context_t *dc;

  if (!IS_STARTED)
    return Qfalse;

  if (breakpoints != Qnil && rb_funcall(breakpoints, idEmpty, 0) == Qfalse)
    return Qfalse;

  if (catchpoints != Qnil && rb_funcall(catchpoints, idEmpty, 0) == Qfalse)
    return Qfalse;

  if (post_mortem == Qtrue)
    return Qfalse;

  context = Current_context(self);
  if (context != Qnil)
  {
    Data_Get_Struct(context, debug_context_t, dc);

    if (dc->steps > 0)
      return Qfalse;
  }

  return Qtrue;
}

/*
 *  call-seq:
 *    Byebug.start -> bool
 *
 *  The return value is the value of !Byebug.started? before issuing the
 *  +start+; That is, +true+ is returned, unless byebug was previously started.
 */
static VALUE
Start(VALUE self)
{
  if (IS_STARTED)
    return Qfalse;

  catchpoints = rb_hash_new();

  threads = create_threads_table();

  register_tracepoints(self);

  return Qtrue;
}

/*
 *  call-seq:
 *    Byebug.debug_load(file, stop = false) -> nil
 *
 *  Same as Kernel#load but resets current context's frames.
 *  +stop+ parameter forces byebug to stop at the first line of code in +file+
 */
static VALUE
Debug_load(int argc, VALUE * argv, VALUE self)
{
  VALUE file, stop, context;
  debug_context_t *dc;
  VALUE status = Qnil;
  int state = 0;

  UNUSED(self);

  if (rb_scan_args(argc, argv, "11", &file, &stop) == 1)
    stop = Qfalse;

  Start(self);

  context = Current_context(self);
  Data_Get_Struct(context, debug_context_t, dc);

  dc->calced_stack_size = 1;

  if (RTEST(stop))
    dc->steps = 1;

  rb_load_protect(file, 0, &state);
  if (0 != state)
  {
    status = rb_errinfo();
    reset_stepping_stop_points(dc);
  }

  return status;
}

/*
 *  call-seq:
 *    Byebug.tracing? -> bool
 *
 *  Returns +true+ if global tracing is enabled.
 */
static VALUE
Tracing(VALUE self)
{
  UNUSED(self);

  return tracing;
}

/*
 *  call-seq:
 *    Byebug.tracing = bool
 *
 *  Sets the global tracing flag.
 */
static VALUE
Set_tracing(VALUE self, VALUE value)
{
  UNUSED(self);

  tracing = RTEST(value) ? Qtrue : Qfalse;
  return value;
}

/*
 *  call-seq:
 *    Byebug.post_mortem? -> bool
 *
 *  Returns +true+ if post-mortem debugging is enabled.
 */
static VALUE
Post_mortem(VALUE self)
{
  UNUSED(self);

  return post_mortem;
}

/*
 *  call-seq:
 *    Byebug.post_mortem = bool
 *
 *  Sets post-moterm flag.
 */
static VALUE
Set_post_mortem(VALUE self, VALUE value)
{
  UNUSED(self);

  post_mortem = RTEST(value) ? Qtrue : Qfalse;
  return value;
}

/*
 *  call-seq:
 *    Byebug.add_catchpoint(exception) -> exception
 *
 *  Adds a new exception to the catchpoints array.
 */
static VALUE
Add_catchpoint(VALUE self, VALUE value)
{
  UNUSED(self);

  if (TYPE(value) != T_STRING)
    rb_raise(rb_eTypeError, "value of a catchpoint must be String");

  rb_hash_aset(catchpoints, rb_str_dup(value), INT2FIX(0));
  return value;
}

/*
 *   Document-class: Byebug
 *
 *   == Summary
 *
 *   This is a singleton class allows controlling byebug. Use it to start/stop
 *   byebug, set/remove breakpoints, etc.
 */
void
Init_byebug()
{
  mByebug = rb_define_module("Byebug");

  rb_define_module_function(mByebug, "add_catchpoint", Add_catchpoint, 1);
  rb_define_module_function(mByebug, "breakpoints", Breakpoints, 0);
  rb_define_module_function(mByebug, "catchpoints", Catchpoints, 0);
  rb_define_module_function(mByebug, "contexts", Contexts, 0);
  rb_define_module_function(mByebug, "current_context", Current_context, 0);
  rb_define_module_function(mByebug, "debug_load", Debug_load, -1);
  rb_define_module_function(mByebug, "post_mortem?", Post_mortem, 0);
  rb_define_module_function(mByebug, "post_mortem=", Set_post_mortem, 1);
  rb_define_module_function(mByebug, "raised_exception", Raised_exception, 0);
  rb_define_module_function(mByebug, "start", Start, 0);
  rb_define_module_function(mByebug, "started?", Started, 0);
  rb_define_module_function(mByebug, "stop", Stop, 0);
  rb_define_module_function(mByebug, "stoppable?", Stoppable, 0);
  rb_define_module_function(mByebug, "thread_context", Thread_context, 1);
  rb_define_module_function(mByebug, "tracing?", Tracing, 0);
  rb_define_module_function(mByebug, "tracing=", Set_tracing, 1);

  Init_threads_table(mByebug);
  Init_context(mByebug);
  Init_breakpoint(mByebug);

  rb_global_variable(&breakpoints);
  rb_global_variable(&catchpoints);
  rb_global_variable(&tracepoints);
  rb_global_variable(&raised_exception);
  rb_global_variable(&threads);

  idPuts = rb_intern("puts");
  idEmpty = rb_intern("empty?");
}


text:
"""Test suite for phlurl_watcher."""
# =============================================================================
#                                   TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
# cover those concerns.
#
# Concerns:
# [ A] can dump and load again from empty watcher
# [ A] can dump and load again from watcher with one element
# -----------------------------------------------------------------------------
# Tests:
# [ A] test_A_Breathing
# =============================================================================

from __future__ import absolute_import

import unittest

import phlsys_fs

import phlurl_watcher

class _MockRequesterObject(object):

    def __init__(self):
        self._request_count = 0

    def get(self, url):
        # make sure the result is different each time
        self._request_count += 1
        return str(self._request_count) + url

    def get_many(self, url_list):
        result = {}
        for url in url_list:
            result[url] = self.get(url)
        return result

class Test(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_A_Breathing(self):

        with phlsys_fs.chtmpdir_context():

            requester = _MockRequesterObject()
            url = 'http://host.test'
            cache_path = 'phlurl_watcher_cache.json'

            # initialise without existing cache
            watcher_cache_wrapper = phlurl_watcher.FileCacheWatcherWrapper(
                cache_path, requester)
            watcher = watcher_cache_wrapper.watcher

            # check that we can test and consume the content change
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

            # save and reload from the cache
            watcher_cache_wrapper.save()
            watcher_cache_wrapper = phlurl_watcher.FileCacheWatcherWrapper(
                cache_path, requester)
            watcher = watcher_cache_wrapper.watcher

            # check that the content is still considered unchanged
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

            # check that refreshing resets the changed flags
            watcher.refresh()

            # check that we can test and consume the content change
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

            # update the content
            watcher.refresh()

            # save and reload from the cache
            watcher_cache_wrapper.save()
            watcher_cache_wrapper = phlurl_watcher.FileCacheWatcherWrapper(
                cache_path, requester)
            watcher = watcher_cache_wrapper.watcher

            # check that we can consume the change
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.peek_has_url_recently_changed(url))
            self.assertTrue(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.has_url_recently_changed(url))
            self.assertFalse(watcher.peek_has_url_recently_changed(url))

# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# 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.
# ------------------------------ END-OF-FILE ----------------------------------


text:
/**
 * tactile.js
 * @author Jack Pattishall
 *
 * Current touch events supported are: tap, drag (including dragstart, dragend), swipe
 *
 * Usage:
 * $(SELECTOR).tact({
 *     dragstart: function(e){ .. },
 *     drag: function(e){ .. },
 *     dragend: function(e){ .. },
 *     swipe: function(e){ .. },
 *     tap: function(e){ .. },
 * });
 *
 * The event object passed to the callback(s) will include a gesture object
 * with the following properties:
 *
 * Shared properties
 * - e.gesture.type (event type, e.g. drag, swipe, tap)
 * - e.gesture.id (touch ID)
 * - e.gesture.start (touch event start time)
 *
 * Drag/swipe specific
 * - e.gesture.dir (direction, left and right, expressed in numerical values (l:1, r: -1))
 *
 * To enable, disable, or destroy the plugin, call the following methods:
 * $(SELECTOR).tact('disable');
 * $(SELECTOR).tact('enable');
 * $(SELECTOR).tact('destroy');
 */

// TODO: Add support for IE Pointer Events
(function($) {
    'use strict';

    // CONST
    var DATATACT = '__TACTILE',
        TACT_LISTENER_IS_BOUND = '__TACTILE_LISTENER_BOUND',

        // Minimum number of pixels a user moves before dragging starts
        DRAG_THRESHOLD = 10,

        // Maximum duration between touchstart and touchend to determine tap
        TAP_THRESHOLD = 150,

        // Maximum number of pixels a user can move between taps
        TAP_DISTANCE = 10,

        // Slope to determine if user is swiping
        SLOPE = 0.5,

        // Velocity of finger movement to determine user swiping
        VELOCITY = 0.5,

        EVENTS = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];

    /**
     * Our object of touch handlers
     */
    var _touchHandlers = {

            /**
             * TouchStart
             * @param {Touch Event} e
             */
            touchstart: function(e) {
                var s = this.settings,
                    t = e.changedTouches[0];

                // Reset touch related variables
                s.dY = 0;
                s.dX = 0;
                s.scroll = 0;
                s.dir = 0;

                s.userDragging = false;

                // Set initial touch properties
                s.sX = Math.abs(t.screenX);
                s.sY = Math.abs(t.screenY);
                s.sT = new Date().getTime();

                s.id = t.identifier;
            },

            /**
             * TouchMove
             * @param {Touch Event} e
             */
            touchmove: function(e) {
                var $el = this.$el,
                    s = this.settings,
                    t = e.changedTouches[0];

                // Ignore scrolling
                if (s.scroll) {
                    return;
                }

                // Set direction
                s.dir = s.dX >= (t.screenX - s.sX) ? -1 : 1;

                // Update points
                s.dX = t.screenX - s.sX;
                s.dY = t.screenY - s.sY;

                // Is scroll intended?
                if (!s.userDragging && (Math.abs(s.dY / s.dX) > SLOPE)) {
                    s.scroll = 1;
                    return;
                }

                // Handle drag callbacks
                if (s.userDragging || (s.listenDrag && (Math.abs(s.dY) > DRAG_THRESHOLD || Math.abs(s.dX) >= DRAG_THRESHOLD))) {
                    e.gesture = this._extendGestureObj(s);
                    e.preventDefault();

                    if (!s.userDragging) {
                        s.sX = t.screenX;
                        s.sY = t.screenY;

                        e.gesture = this._extendGestureObj(s);
                        e.gesture.type = 'dragstart';
                        $el.trigger('tact:dragstart', e);
                        s.userDragging = true;
                    } else {
                        e.gesture.type = 'drag';
                        $el.trigger('tact:drag', e);
                    }
                }
            },

            /**
             * TouchEnd
             * @param {Touch Event} e
             */
            touchend: function(e) {
                var $el = this.$el,
                    s = this.settings,
                    t = e.changedTouches[0],
                    d = new Date().getTime(),
                    pX = Math.abs(t.screenX),
                    pY = Math.abs(t.screenY),
                    swipeTriggered = false,
                    diffT,
                    diffP;

                diffT = d - s.sT;

                // Delta between start/end points
                diffP = Math.floor(Math.sqrt(((pX - s.sX) * (pX - s.sX) + (pY - s.sY) * (pY - s.sY))));

                e.gesture = this._extendGestureObj(s);

                e.gesture.end = d;
                e.gesture.duration = diffT;

                // Determine if user swiped, and handle callback
                if ((Math.abs(s.sX - pX) / Math.abs(s.sT - d)) > VELOCITY) {
                    e.gesture.velocity = (Math.abs(s.sX - pX) / Math.abs(s.sT - d));
                    e.gesture.type = 'swipe';
                    swipeTriggered = true;
                    $el.trigger('tact:swipe', e);
                }

                // Determine if user dragged, and handle callback
                if (s.userDragging) {
                    s.userDragging = false;
                    e.gesture.type = 'dragend';
                    e.gesture.swipe = swipeTriggered;
                    $el.trigger('tact:dragend', e);
                }

                // Determine if user tapped, and handle callback
                if (TAP_THRESHOLD > diffT && TAP_DISTANCE > diffP) {
                    delete e.gesture.dir;
                    delete e.gesture.delta;

                    e.gesture.type = 'tap';
                    $el.trigger('tact:tap', e);
                }
            },

            /**
             * TouchCancel
             * @param {Touch Event} e
             *
            */
            touchcancel: function(e) {
                // Call touchend
                this.handlers.touchend(e);
                //this.touchend(e);
            }
        };

    /**
     * Returns touch handler (touchstart, touchmove, touchend, touchcancel) to bind to el
     * @param {String} evtType
     * @param {Object} ctx
     */
    var _createTouchEvtHandler = function _createTouchEvtHandler(action, ctx, evtType) {
        var $el = ctx.$el,
            hasListener = $el.data(TACT_LISTENER_IS_BOUND),
            touchHandlerFunc;

        if (action === 1 && (hasListener === undefined || hasListener === false)) {
            touchHandlerFunc = function(e) {
                _touchHandlers[evtType].call(ctx, e);
            };
            ctx.handlers[evtType] = touchHandlerFunc;
        } else {
            touchHandlerFunc = ctx.handlers[evtType];
        }

        return touchHandlerFunc;
    };

    /**
     * Returns Tact Handler to bind to el for triggering touch events
     * @param {String} cb
     * @param {Object} map
     * @param {Object} ctx
     */
    var _createTactHandler = function _createTactHandler(cb, map, ctx) {
        return function(triggerEvt, origEvt) {
            if (ctx.settings.enabled) {
                map[cb].call(ctx.$el[0], origEvt);
            }
        };
    };

    /**
     * Binds TouchEvents to element
     * @param {HTML Element} el
     * @param {Key-Value object} callbackMap (Callbacks to be called at end of touch events)
     * @param {Number} binding (1 - Binding, 0 - Unbinding events)
     */
    function Tact(el, callbackMap) {
        this.settings = {};
        this.$el = $(el);
        this.handlers = {};

        if (!document.addEventListener) { return; }

        this._bindEvents(1, callbackMap);
    }

    Tact.prototype._bindEvents = function(binding, callbackMap) {
        var t = this,
            action = binding === 1 ? 'add' : 'remove',
            el = this.$el.get(0),
            cb,
            i,
            len;

        for (i = 0, len = EVENTS.length; i < len; i++) {
            el[action + 'EventListener'](EVENTS[i], _createTouchEvtHandler(binding, this, EVENTS[i]));
        }

        this.$el.data(TACT_LISTENER_IS_BOUND, !!binding);

        if (action === 'add') {
            if (callbackMap) {
                this.settings.enabled = 1;
                for (cb in callbackMap) {
                    if (callbackMap.hasOwnProperty(cb)) {
                        if (typeof callbackMap[cb] === 'function') {
                            this.$el.on('tact:' + cb + '.tact', _createTactHandler(cb, callbackMap, t));
                        }
                        if (cb.indexOf('drag') > -1) {
                            this.settings.listenDrag = true;
                        }
                    }
                }
            }
        }
    };

    /**
     * Returns shared gesture properties across event types
     * @param {Object} settingsObj
     */
    Tact.prototype._extendGestureObj = function(settings) {
        var obj = {};

        obj.dir = settings.dir;
        obj.id = settings.id;
        obj.start = settings.sT;
        obj.delta = {};
        obj.delta.x = settings.dX;
        obj.delta.y = settings.dY;

        return obj;
    };

    // Exposed public method
    $.fn.extend({
        tact: function(callbackMap) {
            // Determine if user is attempting to enable/disable/destroy plugin
            if (typeof callbackMap === 'string' || callbackMap instanceof String) {
                // Enable/Disable
                if (callbackMap === 'enable') {
                    return this.each(function() {
                        var data = $(this).data(DATATACT);
                        if (data && data.settings) {
                            data.settings.enabled = 1;
                        }
                    });
                }
                if (callbackMap === 'disable') {
                    return this.each(function() {
                        var data = $(this).data(DATATACT);
                        if (data && data.settings) {
                            data.settings.enabled = 0;
                        }
                    });
                }
                // Destroy
                if (callbackMap === 'destroy') {
                    return this.each(function() {
                        var data = $(this).data(DATATACT);
                        if (data) {
                            data._bindEvents(0);
                            $(this).off('.tact');
                            $(this).removeData(DATATACT);
                        }
                    });
                }
                return this;
            }

            return this.each(function() {
                var $this = $(this),
                    tact;

                if ($this.data(DATATACT) === undefined) {
                    $this.data(DATATACT, new Tact(this, callbackMap));
                } else {
                    tact = $this.data(DATATACT);
                    tact._bindEvents(1, callbackMap);
                }
            });

        }
    });
}(jQuery));


text:
package role

import (
	"time"
)

// Role represents user roles.
// Key's stringID is encoded "Context" key.
// And the "ContextID" is an encoded "Context" key for multilang usage purpose.
type Role struct {
	ID        string    `datastore:"-"`
	ContextID string    `datastore:"-" json:"contextID"`
	RoleTypes []string  `datastore:"-" json:"-"`
	Created   time.Time `json:"-"`
}

// Roles is a map of role pointers with role IDs as their keys.
type Roles map[string]*Role


text:
package com.appsingularity.postmansample.test;

import android.content.Context;
import android.os.Parcel;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.appsingularity.postman.Postman;
import com.appsingularity.postman.annotations.PostmanEnabled;

import java.util.ArrayList;
import java.util.List;

@PostmanEnabled
public class ModelStrings extends Model {
    String mString;
    String[] mStringArray;
    List<String> mStringList;
    ArrayList<String> mStringArrayList;

    public ModelStrings() {
    }

    @NonNull
    @Override
    public String getName() {
        return "Strings";
    }

    @Override
    public void setup() {
        mString = "Some string";
        mStringArray = new String[]{"string 1", null, "string 3"};
        mStringList = new ArrayList<>();
        mStringList.add("string 1");
        mStringList.add(null);
        mStringList.add("string 3");
        mStringArrayList = new ArrayList<>();
        mStringArrayList.add("string 1");
        mStringArrayList.add(null);
        mStringArrayList.add("string 3");
    }

    @Override
    public void showResults(@NonNull Context context, @NonNull ViewGroup layout) {
        LayoutInflater inflater = LayoutInflater.from(context);
        addNewRow(context, inflater, layout, "String", "Some string".equals(mString));
        boolean ok;
        if (mStringArray != null) {
            ok = mStringArray.length == 3;
            ok = ok & "string 1".equals(mStringArray[0]);
            ok = ok & mStringArray[1] == null;
            ok = ok & "string 3".equals(mStringArray[2]);
        } else {
            ok = false;
        }
        addNewRow(context, inflater, layout, "String[]", ok);
        if (mStringList != null) {
            ok = mStringList.size() == 3;
            ok = ok & "string 1".equals(mStringList.get(0));
            ok = ok & mStringList.get(1) == null;
            ok = ok & "string 3".equals(mStringList.get(2));
        } else {
            ok = false;
        }
        addNewRow(context, inflater, layout, "List<String>", ok);
        if (mStringArrayList != null) {
            ok = mStringArrayList.size() == 3;
            ok = ok & "string 1".equals(mStringArrayList.get(0));
            ok = ok & mStringArrayList.get(1) == null;
            ok = ok & "string 3".equals(mStringArrayList.get(2));
        } else {
            ok = false;
        }
        addNewRow(context, inflater, layout, "ArrayList<String>", ok);
    }

    protected ModelStrings(Parcel in) {
        Postman.receive(ModelStrings.class, this, in);
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        Postman.ship(ModelStrings.class, this, dest, flags);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<ModelStrings> CREATOR = new Creator<ModelStrings>() {
        @Override
        public ModelStrings createFromParcel(Parcel in) {
            return new ModelStrings(in);
        }

        @Override
        public ModelStrings[] newArray(int size) {
            return new ModelStrings[size];
        }
    };

}


text:
<?php

namespace greevex\gss\lib;
/**
 * @author greevex
 * @date: 10/1/14 6:10 PM
 */

class blockParser
{
    private $blockName;
    private $blockData = [
        'name' => null,
        'input' => [],
        'started' => false,
        'ended' => false,
        'contents' => []
    ];

    /**
     * @param $blockName
     *
     * @return self
     */
    public static function factory($blockName)
    {
        static $instances = [];
        if(!isset($instances[$blockName])) {
            $instances[$blockName] = new self($blockName);
        }

        return $instances[$blockName];
    }

    public function __construct($blockName)
    {
        $this->blockName = $blockName;
        $this->blockData['name'] = $this->blockName;
    }

    public function dump()
    {
        $copy = $this->blockData;
        unset($copy['started']);
        unset($copy['ended']);
        return $copy;
    }

    public function eatLineTokens($lineTokens)
    {
        foreach($lineTokens as $lineTokenKey => $lineToken) {
            if($lineToken['type'] != 'WHITESPACE') {
                break;
            }
            array_shift($lineTokens);
        }
        $ftoken = $lineTokens[0];
        /** @var foreachParser $foreachParser */
        /** @var variableMethodParser $variableMethod */
        /** @var inputParser $inputParser */
        /** @var foreachParser $foreachParser */
        switch($ftoken['type']) {
            case 'INPUT':
                if($this->checkInstances($lineTokens)) {
                    break;
                }
                $this->setEnded();
                $inputParser = new inputParser($lineTokens);
                $this->blockData['input'] = $inputParser->dump();
                if(!$inputParser::CAN_WAIT) {
                    unset($inputParser);
                }
                break;
            case 'VARIABLE_METHOD':
                if($this->checkInstances($lineTokens)) {
                    break;
                }
                $this->setEnded();
                $variableMethod = new variableMethodParser($lineTokens);
                $this->blockData['contents'][] = $variableMethod->dump();
                if(!$variableMethod::CAN_WAIT) {
                    unset($variableMethod);
                }
                break;
            case 'VARIABLE':
            case 'VARIABLE_PATH':
                if($this->checkInstances($lineTokens)) {
                    break;
                }
                $this->setEnded();
                $variableAction = new variableAction($lineTokens);
                $this->blockData['contents'][] = $variableAction->dump();
                if(!$variableAction::CAN_WAIT) {
                    unset($variableAction);
                }
                break;
            case 'OBJECT':
                if($this->checkInstances($lineTokens)) {
                    break;
                }
                $this->setEnded();
                new actionParser($lineTokens);
                break;
            case 'FOREACH':
                $this->setEnded();
                new foreachParser($lineTokens);
                break;
            case 'IF':
                $this->setEnded();
                new ifParser($lineTokens);
                break;
            case 'RETURN':
                $this->setEnded();
                $returnParser = new returnParser($lineTokens);
                $this->blockData['return'] = $returnParser->dump();
                if(!$returnParser::CAN_WAIT) {
                    unset($returnParser);
                }
                break;
            case 'WHITESPACE':
                break;
            default:
                if($this->checkInstances($lineTokens)) {
                    break;
                }
                $this->setEnded();
                return error::throwNewException("Unexpected {$ftoken['type']}", $ftoken['line'], $ftoken['pos']);
                break;
        }

        return true;
    }

    protected function checkInstances($lineTokens)
    {
        if(foreachParser::hasInstance()) {
            $status = foreachParser::getInstance()->eatParams($lineTokens);
            if(!$status) {
                $this->blockData['contents'][] = foreachParser::getInstance()->dump();
                foreachParser::getInstance()->dropInstance();
            }
            return $status;
        }
        if(actionParser::hasInstance()) {
            $status = actionParser::getInstance()->eatParams($lineTokens);
            if(!$status) {
                $this->blockData['contents'][] = actionParser::getInstance()->dump();
                actionParser::getInstance()->dropInstance();
            }
            return $status;
        }
        if(ifParser::hasInstance()) {
            $status = ifParser::getInstance()->eatParams($lineTokens);
            if(!$status) {
                $this->blockData['contents'][] = ifParser::getInstance()->dump();
                ifParser::getInstance()->dropInstance();
            }
            return $status;
        }
        return false;
    }

    public function setStarted($lineNumber)
    {
        $this->blockData['started'] = true;
        $this->blockData['line'] = $lineNumber;
    }

    public function setEnded()
    {
        $this->blockData['ended'] = true;
        if(foreachParser::hasInstance()) {
            $this->blockData['contents'][] = foreachParser::getInstance()->dump();
            foreachParser::getInstance()->dropInstance();
        }
        if(actionParser::hasInstance()) {
            $this->blockData['contents'][] = actionParser::getInstance()->dump();
            actionParser::getInstance()->dropInstance();
        }
        if(ifParser::hasInstance()) {
            $this->blockData['contents'][] = ifParser::getInstance()->dump();
            ifParser::getInstance()->dropInstance();
        }
    }
}