text:
<?php

namespace A2F\SofiaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\component\HttpFoundation\Request;
use Symfony\component\HttpFoundation\Response;
use A2F\SofiaBundle\Entity\INCIDENT;
use A2F\SofiaBundle\Entity\USER;
use A2F\SofiaBundle\Entity\CLIENT;
use Symfony\Component\Security\Core\SecurityContext;

Class DefaultController extends Controller
    {

    public function dispatchAction()
        {
            if($this->get("security.context")->isGranted("ROLE_DBA"))
            {
                return $this->redirect($this->generateUrl("a2fSofia_a2flandingpage"));
            }
            elseif ($this->get("security.context")->isGranted("ROLE_REQ"))
            {
                $user = $this->getUser();
                $client = $user->getClient()->getId();

                return $this->redirect($this->generateUrl("a2fSofia_clientlandingpage", array("id"=>$client)));
            }

        }

    public function indexA2fAction()
            {
                //fixer la limite du noùbre de resultats pour l'accordéon
                $limit = 5;

                //Récupérer les données des CONTRATS via le repo
                $contractRepo = $this->getDoctrine()
                             ->getManager()
                             ->getRepository("A2FSofiaBundle:CONTRACT");

                //Chercher les 5 contrats qui s'afficheront, classés par GTI et par date d'expiration la plus proche
                $contracts = $contractRepo->findAllContracts($limit);

                //On fait la même chose pour les incidents
                $incidentRepo = $this->getDoctrine()
                                    ->getManager()
                                    ->getRepository("A2FSofiaBundle:INCIDENT");

                $incidents5 = $incidentRepo->findAllIncidents($limit);
                $incidents = $incidentRepo->findAllIncidents(null);

                return $this->render("A2FSofiaBundle:Global:a2flandingpage.html.twig", array("contracts"=>$contracts, "incidentsFive"=>$incidents5, "incidents"=>$incidents));
            }
        public function indexClientAction($id)
            {
            $incidentRepo = $this->getDoctrine()
                                    ->getManager()
                                    ->getRepository("A2FSofiaBundle:INCIDENT");

            //liste des 5 derniers incidents d'un client
                $limit=5;
                $statuses= array("Nouveau", "Attribué", "En attente", "Clos");
                $statusCount=array();

                foreach($statuses as $status)
                {
                    $statusCount = count($incidentRepo->findAllIncidentsByClientAndByStatus($id, $status));
                }

                $notificationRepo = $this->getDoctrine()
                                         ->getManager()
                                         ->getRepository("A2FSofiaBundle:NOTIFICATION");

                $notifications = $notificationRepo->findAllNotificationsByClient($limit, $id);

                return $this->render("A2FSofiaBundle:Global:clientlandingpage.html.twig", array("statuses"=>$statusCount, "notifications"=>$notifications));
            }
    }


text:
package com.orionplatform.math;

import com.orionplatform.core.abstraction.OrionRuntimeException;

public abstract class MathError extends OrionRuntimeException
{
    private static final String DefaultErrorMessage = "There is a mathematical problem.";

    public MathError()
    {
        super(DefaultErrorMessage);
    }

    public MathError(String message)
    {
        super(message);
    }

    public MathError(String errorMessage, Object... arguments)
    {
        super(String.format(errorMessage, arguments));
    }

    public MathError(Throwable cause, String errorMessage, Object... arguments)
    {
        super(String.format(errorMessage, arguments), cause);
    }

    public MathError(Throwable cause)
    {
        super(cause, DefaultErrorMessage);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'writeexcel'
require 'stringio'

module Ruby2xlsx
  class Base
    # Constructs a new ejs engine based on given xlsx", :root => true, :view_path => "/path/to/views" })
    #
    def initialize(source, options = {})
      @source = source
      @options = options
      @compiled = false
      @io = ::StringIO.new
    end

    def workbook
      @workbook ||= ::WriteExcel.new(@io)
    end

    def worksheet
      @worksheet ||= add_worksheet(worksheet_name)
    end

    def add_worksheet(*args)
      @worksheet = workbook.add_worksheet(*args)
    end

    def render(*args)
      workbook.close
      @io.string
    end

    def worksheet_name
      'somename'
    end

    def method_missing(m, *args, &block)
      if worksheet.respond_to?(m)
        worksheet.send(m, *args, &block)
      elsif workbook.respond_to?(m)
        workbook.send(m, *args, &block)
      else
        super
      end
    end
  end
end


text:
published: true
---
## 2017-2018  Announcement for  LMEC 2017-2018 Students

 [here]({{site.url}}/assets/lmecGradesNov2017.pdf) Results of last
 written Mathematics exam.


text:
class CreateReviewFeedbacks < ActiveRecord::Migration[4.2]
  def self.up
    create_table 'review_feedbacks', force: true do |t|
      t.column 'assignment_id', :integer
      t.column 'review_id', :integer
      t.column 'user_id', :integer
      t.column 'feedback_at', :datetime
      t.column 'txt', :text
    end

    add_index 'review_feedbacks', ['assignment_id'], name: 'fk_review_feedback_assignments'

    execute "alter table review_feedbacks
               add constraint fk_review_feedback_assignments
               foreign key (assignment_id) references assignments(id)"

    add_index 'review_feedbacks', ['review_id'], name: 'fk_review_feedback_reviews'

    execute "alter table review_feedbacks
               add constraint fk_review_feedback_reviews
               foreign key (review_id) references reviews(id)"
  end

  def self.down
    drop_table 'review_feedbacks'
  end
end


text:
Package for performing hyperparameter optimization with [Spearmint](https://github.com/HIPS/Spearmint).

Requirements:  Those specified in the [Spearmint](https://github.com/HIPS/Spearmint) package:

* [NumPy](http://www.numpy.org/)
* [scikit learn](http://scikit-learn.org/stable/index.html)
* [pymongo](https://api.mongodb.org/python/current)
* [MongoDB](https://www.mongodb.org)

Installation:

* Install [Spearmint](https://github.com/HIPS/Spearmint/blob/master/README.md)

Usage:

 1) Set your experimental settings (see `${nmt_keras_path}/spearmint/config.json` for an example)

 * **_WARNING!_**: It is highly recommendable to specify an absolute path to the data files in `config.py` when launching spearmint!

 2) Run the `launch_spearmint.sh` script. It will execute the following steps:

 * Get NMT-Keras directory:

 ```bash
    cd nmt-keras
    nmt_keras_path=`pwd`
 ```

 * Create directory for storing the database:

 ```bash
 mkdir ${nmt_keras_path}/spearmint/db
 ```

 * Start the Mongo database:

 ```bash
 mongod --fork --logpath ${nmt_keras_path}/spearmint/db/log --dbpath ${nmt_keras_path}/spearmint/db
 ```

  * Remove eventual instances of previous experiments

 ```bash
  ${spearmint_path}/spearmint/cleanup.sh ${nmt_keras_path}/spearmint/
 ```

 * Lauch Spearmint! Assuming that it is installed under `${spearmint_path}`:

    ```bash
    cd ${nmt_keras_path}; nohup python ${spearmint_path}/spearmint/main.py ${dest_dir} --config=${nmt_keras_path}/meta-optimizers/spearmint/config.json >> ${dest_dir}/logs/out.log 2> ${dest_dir}/logs/out.err &
    ```

 * The results will appear at `${nmt_keras_path}/spearmint/output`


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Kohana_Pagination {

	// Merged configuration settings
	protected $config = array(
		'current_page'      => array('source' => 'query_string', 'key' => 'page'),
		'total_items'       => 0,
		'items_per_page'    => 10,
		'view'              => 'pagination/basic',
		'auto_hide'         => TRUE,
		'first_page_in_url' => FALSE,
	);

	// Current page number
	protected $current_page;

	// Total item count
	protected $total_items;

	// How many items to show per page
	protected $items_per_page;

	// Total page count
	protected $total_pages;

	// Item offset for the first item displayed on the current page
	protected $current_first_item;

	// Item offset for the last item displayed on the current page
	protected $current_last_item;

	// Previous page number; FALSE if the current page is the first one
	protected $previous_page;

	// Next page number; FALSE if the current page is the last one
	protected $next_page;

	// First page number; FALSE if the current page is the first one
	protected $first_page;

	// Last page number; FALSE if the current page is the last one
	protected $last_page;

	// Query offset
	protected $offset;

	// Request object
	protected $_request;

	// Route to use for URIs
	protected $_route;

	// Parameters to use with Route to create URIs
	protected $_route_params = array();

	/**
	 * Creates a new Pagination object.
	 *
	 * @param   array  configuration
	 * @return  Pagination
	 */
	public static function factory(array $config = array(), Request $request = NULL)
	{
		return new Pagination($config, $request);
	}

	/**
	 * Creates a new Pagination object.
	 *
	 * @param   array  configuration
	 * @return  void
	 */
	public function __construct(array $config = array(), Request $request = NULL)
	{
		// Overwrite system defaults with application defaults
		$this->config = $this->config_group() + $this->config;

		// Assing Request
		if ($request === NULL)
		{
			$request = Request::current();
		}

		$this->_request = $request;

		// Assign default Route
		$this->_route = $request->route();

		// Assign default route params
		$this->_route_params = $request->param();

		// Pagination setup
		$this->setup($config);
	}

	/**
	 * Retrieves a pagination config group from the config file. One config group can
	 * refer to another as its parent, which will be recursively loaded.
	 *
	 * @param   string  pagination config group; "default" if none given
	 * @return  array   config settings
	 */
	public function config_group($group = 'default')
	{
		// Load the pagination config file
		$config_file = Kohana::$config->load('pagination');

		// Initialize the $config array
		$config['group'] = (string) $group;

		// Recursively load requested config groups
		while (isset($config['group']) AND isset($config_file->$config['group']))
		{
			// Temporarily store config group name
			$group = $config['group'];
			unset($config['group']);

			// Add config group values, not overwriting existing keys
			$config += $config_file->$group;
		}

		// Get rid of possible stray config group names
		unset($config['group']);

		// Return the merged config group settings
		return $config;
	}

	/**
	 * Loads configuration settings into the object and (re)calculates pagination if needed.
	 * Allows you to update config settings after a Pagination object has been constructed.
	 *
	 * @param   array   configuration
	 * @return  object  Pagination
	 */
	public function setup(array $config = array())
	{
		if (isset($config['group']))
		{
			// Recursively load requested config groups
			$config += $this->config_group($config['group']);
		}

		// Overwrite the current config settings
		$this->config = $config + $this->config;

		// Only (re)calculate pagination when needed
		if ($this->current_page === NULL
			OR isset($config['current_page'])
			OR isset($config['total_items'])
			OR isset($config['items_per_page']))
		{
			// Retrieve the current page number
			if ( ! empty($this->config['current_page']['page']))
			{
				// The current page number has been set manually
				$this->current_page = (int) $this->config['current_page']['page'];
			}
			else
			{
				$query_key = $this->config['current_page']['key'];

				switch ($this->config['current_page']['source'])
				{
					case 'query_string':
						$this->current_page = ($this->_request->query($query_key) !== NULL)
							? (int) $this->_request->query($query_key)
							: 1;
						break;

					case 'route':
						$this->current_page = (int) $this->_request->param($query_key, 1);
						break;
				}
			}

			// Calculate and clean all pagination variables
			$this->total_items        = (int) max(0, $this->config['total_items']);
			$this->items_per_page     = (int) max(1, $this->config['items_per_page']);
			$this->total_pages        = (int) ceil($this->total_items / $this->items_per_page);
			$this->current_page       = (int) min(max(1, $this->current_page), max(1, $this->total_pages));
			$this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items);
			$this->current_last_item  = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items);
			$this->previous_page      = ($this->current_page > 1) ? $this->current_page - 1 : FALSE;
			$this->next_page          = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : FALSE;
			$this->first_page         = ($this->current_page === 1) ? FALSE : 1;
			$this->last_page          = ($this->current_page >= $this->total_pages) ? FALSE : $this->total_pages;
			$this->offset             = (int) (($this->current_page - 1) * $this->items_per_page);
		}

		// Chainable method
		return $this;
	}

	/**
	 * Generates the full URL for a certain page.
	 *
	 * @param   integer  page number
	 * @return  string   page URL
	 */
	public function url($page = 1)
	{
		// Clean the page number
		$page = max(1, (int) $page);

		// No page number in URLs to first page
		if ($page === 1 AND ! $this->config['first_page_in_url'])
		{
			$page = NULL;
		}

		switch ($this->config['current_page']['source'])
		{
			case 'query_string':

				return URL::site($this->_request->uri($this->_route_params).
					$this->query(array($this->config['current_page']['key'] => $page)));

			case 'route':

				return URL::site($this->_request->uri(array_merge($this->_route_params,
					array($this->config['current_page']['key'] => $page))).$this->query());
		}

		return '#';
	}

	/**
	 * Checks whether the given page number exists.
	 *
	 * @param   integer  page number
	 * @return  boolean
	 * @since   3.0.7
	 */
	public function valid_page($page)
	{
		// Page number has to be a clean integer
		if ( ! Valid::digit($page))
			return FALSE;

		return $page > 0 AND $page <= $this->total_pages;
	}

	/**
	 * Renders the pagination links.
	 *
	 * @param   mixed   string of the view to use, or a Kohana_View object
	 * @return  string  pagination output (HTML)
	 */
	public function render($view = NULL)
	{
		// Automatically hide pagination whenever it is superfluous
		if ($this->config['auto_hide'] === TRUE AND $this->total_pages <= 1)
			return '';

		if ($view === NULL)
		{
			// Use the view from config
			$view = $this->config['view'];
		}

		if ( ! $view instanceof View)
		{
			// Load the view file
			$view = View::factory($view);
		}

		// Pass on the whole Pagination object
		return $view->set(get_object_vars($this))->set('page', $this)->render();
	}

	/**
	 * Request setter / getter
	 *
	 * @param	Request
	 * @return	Request	If used as getter
	 * @return	$this	Chainable as setter
	 */
	public function request(Request $request = NULL)
	{
		if ($request === NULL)
			return $this->_request;

		$this->_request = $request;

		return $this;
	}

	/**
	 * Route setter / getter
	 *
	 * @param	Route
	 * @return	Route	Route if used as getter
	 * @return	$this	Chainable as setter
	 */
	public function route(Route $route = NULL)
	{
		if ($route === NULL)
			return $this->_route;

		$this->_route = $route;

		return $this;
	}

	/**
	 * Route parameters setter / getter
	 *
	 * @param	array	Route parameters to set
	 * @return	array	Route parameters if used as getter
	 * @return	$this	Chainable as setter
	 */
	public function route_params(array $route_params = NULL)
	{
		if ($route_params === NULL)
			return $this->_route_params;

		$this->_route_params = $route_params;

		return $this;
	}

	/**
	 * URL::query() replacement for Pagination use only
	 *
	 * @param	array	Parameters to override
	 * @return	string
	 */
	public function query(array $params = NULL)
	{
		if ($params === NULL)
		{
			// Use only the current parameters
			$params = $this->_request->query();
		}
		else
		{
			// Merge the current and new parameters
			$params = array_merge($this->_request->query(), $params);
		}

		if (empty($params))
		{
			// No query parameters
			return '';
		}

		// Note: http_build_query returns an empty string for a params array with only NULL values
		$query = http_build_query($params, '', '&');

		// Don't prepend '?' to an empty string
		return ($query === '') ? '' : ('?'.$query);
	}

	/**
	 * Renders the pagination links.
	 *
	 * @return  string  pagination output (HTML)
	 */
	public function __toString()
	{
		try
		{
			return $this->render();
		}
		catch(Exception $e)
		{
			Kohana_Exception::handler($e);
			return '';
		}
	}

	/**
	 * Returns a Pagination property.
	 *
	 * @param   string  property name
	 * @return  mixed   Pagination property; NULL if not found
	 */
	public function __get($key)
	{
		return isset($this->$key) ? $this->$key : NULL;
	}

	/**
	 * Updates a single config setting, and recalculates pagination if needed.
	 *
	 * @param   string  config key
	 * @param   mixed   config value
	 * @return  void
	 */
	public function __set($key, $value)
	{
		$this->setup(array($key => $value));
	}

} // End Pagination


text:
namespace bd = bandit::detail;

go_bandit([]() {
  describe("posix failure formatter", [&]() {
    failure_formatter::posix formatter;

    it("formats assertions with file and line number", [&]() {
      bd::assertion_exception exception("message", "file", 321);
      AssertThat(formatter.format(exception), Equals("file:321: message"));
    });

    it("formats assertions without file and line number", [&]() {
      bd::assertion_exception exception("message");
      AssertThat(formatter.format(exception), Equals("message"));
    });
  });
});


text:
package com.tiny.demo.firstlinecode.service;

import android.os.AsyncTask;
import android.os.Environment;

import com.tiny.demo.firstlinecode.common.utils.LogUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 87959 on 2017/5/24.
 */

public class DownloadTask extends AsyncTask<String, Integer, Integer> {
    public static final int TYPE_SUCCESS = 0;
    public static final int TYPE_FAILED = 1;
    public static final int TYPE_PAUSED = 2;
    public static final int TYPE_CANCELED = 3;

    private DownloadListener listener;

    private boolean isCanceled = false;

    private boolean isPaused = false;

    private int lastProgress;

    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    //准备工作,可进行UI操作
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    //子线程中执行的操作,不可更新UI
    @Override
    protected Integer doInBackground(String... params) {
        InputStream is = null;
        RandomAccessFile savedFile = null;
        File file = null;
        try {
            long downloadedLength = 0;
            String downloadUrl = params[0];
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            LogUtils.e("download directory --> " + directory);
            file = new File(directory + fileName);
            if (file.exists()) {            //继续下载
                downloadedLength = file.length();
            }

            long contentLength = getContentLength(downloadUrl);
            if (contentLength == 0) {
                return TYPE_FAILED;
            } else if (contentLength == downloadedLength) {
                //已下载字节和文件总字节相等,说明已经下载完了
                return TYPE_SUCCESS;
            }

            //开始下载
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    //断点下载,指定从哪个字节开始下载
                    .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                    .url(downloadUrl)
                    .build();
            Response response = client.newCall(request).execute();
            if (request != null) {
                is = response.body().byteStream();
                savedFile = new RandomAccessFile(file, "rw");
                savedFile.seek(downloadedLength);//跳过已下载的字节
                byte[] b = new byte[1024];
                int total = 0;
                int len;
                while ((len = is.read(b)) != -1) {
                    if (isCanceled) {
                        return TYPE_CANCELED;
                    } else if (isPaused) {
                        return TYPE_PAUSED;
                    } else {
                        total += len;
                        savedFile.write(b, 0, len);
                        //计算已下载的百分比
                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (savedFile != null) {
                    savedFile.close();
                }
                if (isCanceled && file != null) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

    /**
     * 获取待下载文件的总长度
     *
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    private long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        }
        return 0;
    }

    //可进行UI操作, 在doInBackground中调用publishProgress(Integer... values)方法之后,会立即执行下面的这个方法。
    @Override
    protected void onProgressUpdate(Integer... values) {
//        super.onProgressUpdate(values);
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    //当doInBackground方法执行完毕,并通过return语句进行返回时,这个方法会很快调用。
    //此时任务一般已经完成,可以进行UI操作,比如说提醒任务执行的结果,以及关闭掉进度条对话框等。
    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        switch (integer) {
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSED:
                listener.onPaused();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }

    public void pauseDownload() {
        isPaused = true;
    }

    public void cancelDownload() {
        isCanceled = true;
    }
}


text: Some implementations of machine learning algorithms in C


text:
const icon=require('./img/s1.png');
const Image=`<img src="${icon}">`;
export default Image;


text:
    if(root.getMessageAge() > oldMessageAge+1){
        //if there is an unknown node between the previous node and this one create an empty node
        retString += "\\node (" + std::to_string(index) + ") at (" + std::to_string(x) + "," + std::to_string(y) + ") {};\n";
        std::pair<std::string, int> subRet = toTikzHelper(lowerX, upperX, y-yStep, yStep, oldMessageAge+1, index+1);
        retString += subRet.first;
        retInt = subRet.second;
        retString += "\\draw (" + std::to_string(index) + ") -- (" + std::to_string(index+1) + ");\n";


text:
import house_vote_to_JSON as house
import senate_vote_to_JSON as senate

def get_voting_data(senate_or_house, congress_number):
    if senate_or_house == 'senate':
        data = senate.get_senate_roll_call_vote(congress_number)
        # TODO: prune and format the data
        return data
    elif senate_or_house == 'house':
        data = house.get_house_roll_call_vote_data(congress_number)
        # TODO: prune and format the data
        return data
    else:
        print 'please make sure you have input a correct parameter'
        print 'the first parameter of this function should be either\'senate\' or \'house\''


text:
(function() {
    'use strict';

    describe('show new message', function() {
        var loginPage = require("../login/loginPage.js");
        var menuPage = require("../menu/menuPage.js");
        var messagesPage = require("./messagesPage.js");
        var threadPage = require("./threadPage.js");
        var newMessagePage = require("./newMessagePage.js");

        describe('when authenticated', function() {

            beforeEach(function() {
                loginPage.get();
                loginPage.doLogin('nancyann', 'abcd1234');
                menuPage.toMessages();
                messagesPage.toThread(2);
                threadPage.toNewMessage();
            });

            it('should navigate to new message page', function() {
                expect(browser.getLocationAbsUrl()).toMatch("/newMessage");
                expect(newMessagePage.pageTitle.getText()).toEqual("New message");
                expect(newMessagePage.form).toBeDefined();
            });

            it('should show that message is required after being dirty', function() {
                newMessagePage.setMessage('message');
                newMessagePage.setMessage('');
                expect(newMessagePage.inputMessageErrorMessage.getText()).toEqual('Message required');
                expect(newMessagePage.submit.isEnabled()).toEqual(false);
            });

            it('should be able to send message when message is set', function() {
                newMessagePage.setMessage('message');
                expect(newMessagePage.submit.isEnabled()).toEqual(true);
            });

            it('should redirect to thread page after successfully sending new message', function() {
                newMessagePage.doSend('message');
                expect(browser.getLocationAbsUrl()).toMatch("/thread");
            });

            it('should redirect back to thread page when pressing back button', function() {
                newMessagePage.backButton.click();
                expect(browser.getLocationAbsUrl()).toMatch(/\/thread/);
            });

        });

        describe('when authenticated but cannot send new messages', function() {

            beforeEach(function () {
                loginPage.get();
                loginPage.doLogin('messagesNoNewMessage', '1234');
                menuPage.toMessages();
                messagesPage.toThread(2);
                threadPage.toNewMessage();
            });

            it('should not redirect but display error message', function () {
                newMessagePage.doSend('message');
                expect(browser.getLocationAbsUrl()).toMatch("/newMessage");
                expect(newMessagePage.errorMessage.getText()).toEqual("Failed to send message.");
            });

        });

    });
}());


text:
"""Functions for dealing with schedule blocks.

---

Copyright (c) 2013, University Radio York.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import datetime
import fnmatch
import functools
import itertools

import lass.common.config
import lass.common.time

def annotate(timeslots):
    """Annotates timeslots with their schedule blocks.

    Each timeslot is augmented with a new attribute 'block' that points either
    to None (in the case of the timeslot having no attached block) or a dict
    with keys 'name' and 'type' denoting the block's descriptive name and
    internal type key, respectively.

    Args:
        timeslots: A list of timeslots to be annotated as described above.  The
            timeslots must be sorted in chronological order with respect to
            start time.

    Returns:
        Nothing; the timeslots are modified in-place.
    """
    conf = block_config()
    time_context = lass.common.time.context_from_config()

    if timeslots:
        start_date = time_context.schedule_date_of(timeslots[0].start)
        range_blocks = range_iter(
            conf['range_blocks'],
            start_date,
            time_context
        )
        next_range_block = make_next_range_block_function(range_blocks)

        for timeslot in timeslots:
            range_block, next_range_block = next_range_block(timeslot)
            name_block = name_block_for_timeslot(timeslot, conf)

            # Name blocks take precedence if available.
            block_name = name_block if name_block is not None else range_block
            timeslot.block = (
                None
                if block_name is None
                else dict(conf['blocks'][block_name], name=block_name)
            )

def range_iter(blocks, start_date, time_context):
    """Produces an iterator that returns range blocks in succession.

    The iterator will produce 2-tuples of the form (active datetime,
    block name) where the latter may be None (signifying the absence of
    active range-block). The former starts at the first block on
    start_date and continues forwards on each block change point, the
    date advancing by one day each time the block list is exhausted and
    restarted.

    Args:
        blocks: An iterable consisting of 3-tuples (or equivalents) of
        the form (hour, minute, name), in ascending chronological order
        from midnight and with hour and minute representing a local time
        at which the block referred to by 'name' is to be active.

    Returns:
        An "infinite" iterable (actually bounded by the maximum allowed
        date!) that will provide the above tuples.
    """
    date = start_date
    while True:
        yield from (
            (
                time_context.combine_as_local(
                    date,
                    datetime.time(hour=int(h), minute=int(m), second=0)
                ), name
            ) for (h, m, name) in blocks
        )
        date += datetime.timedelta(days=1)

def block_config():
    """Retrieves the default block configuration."""
    return lass.common.config.from_yaml('sitewide/blocks')

def name_block_for_timeslot(timeslot, block_config):
    """Retrieves the name-based block match for this timeslot, if any.

    If multiple matches are found, the first is retrieved, even if it
    is an exclusion match (block is None).

    Args:
        timeslot: The timeslot whose first name block match should be
            returned.
        block_config: The block configuration that defines the name
            blocks.

    Returns:
        Either None, signifying that this timeslot has no name block,
        or otherwise the name of the name block in which this timeslot
        resides.
    """
    return next(
        (
            block for pattern, block in block_config['name_blocks']
            if name_block_match(timeslot, pattern)
        ),
        None
    )

def name_block_match(timeslot, pattern):
    """Returns True if the timeslot matches the name block pattern."""
    match = False

    if hasattr(timeslot, 'text'):
        title = timeslot.text.get('title', [''])[0]
        # Match case insensitively
        match = fnmatch.fnmatch(title.lower(), pattern.lower())

    return match

def make_next_range_block_function(iterator):
    """Makes a function that takes a timeslot and gets its range block.

    The function returned here is a slightly strange function, in that
    it returns not only the range block for a timeslot but another
    function, which will return the range block for the next timeslot.
    This is because each function records the block that was active in
    the last timeslot, as well as the next block.

    Args:
        iterator: The iterator (from 'range_iter', usually) that will
            supply the range blocks.  This should not be used outside of
            the returned function.

    Returns:
        A function that takes in a timeslot and returns a tuple
        (timeslot block name, next function).  The function should not
        be called again and should be replaced with the next function.
        See the inline definition of 'f' below for details.

    """
    def f(this_start, this_name, next_start, next_name, timeslot):
        """Returns the range block a timeslot exists within.

        This function will advance the range block iterator.

        Args:
            timeslot: The timeslot whose range block should be given.
                All timeslots must be presented in ascending
                chronological order.
            this_start: The start time of the block 'this_name'.
            this_name: The name of the block that was active during the
                last timeslot.
            next_start: The time at which 'next' becomes active.
            next_name: The name of the next block to become active.

        Returns:
            A tuple whose first item is the range block active at the
            start of 'timeslot' and whose second is the function to use
            to retrieve the next timeslot's block.
        """
        # Spin the iterator until the next block is after this timeslot
        # (which means the current block is the one the timeslot is in).
        while next_start <= timeslot.start:
            this_start, this_name = next_start, next_name
            next_start, next_name = next(iterator)

        # There should always be a this_start, because there should always
        # be at least one block that starts on or before the show.
        # (TODO(mattbw): This is a possible configuration error, check there.)
        assert this_start is not None, 'Block start is None.'
        assert this_start < next_start, 'Block starts are in wrong order.'

        return (
            this_name,
            functools.partial(f, this_start, this_name, next_start, next_name)
        )

    # Make sure there's an initial "next block" for the first
    # invocation.
    return functools.partial(f, None, None, *next(iterator))


text:
'use strict';

import cyspriter from '../../lib/';
import postcss from 'postcss';
import * as fs from 'fs';
import * as path from 'path';

describe('Should create a sprite with css rules', function() {
  this.timeout(5000);

  let rmDir = function rmDir(dirPath, removeSelf) {
    if (removeSelf === undefined)
      removeSelf = true;
    try {
      var files = fs.readdirSync(dirPath);
    }
    catch (e) {
      return;
    }
    if (files.length > 0)
      for (var i = 0, l = files.length; i < l; i++) {
        var filePath = dirPath + '/' + files[i];
        if (fs.statSync(filePath).isFile())
          fs.unlinkSync(filePath);
        else
          rmDir(filePath);
      }
    if (removeSelf)
      fs.rmdirSync(dirPath);
  };

  beforeEach(done => {
    rmDir(path.resolve(
      global.ROOT_TEST, 'sprites'), false);
    done();
  });

  afterEach(done => {
    rmDir(path.resolve(
      global.ROOT_TEST, 'sprites'), false);
    done();
  });

  it('Should create correctly without options not required', (done) => {
    let pluginOptions = {
      src: './test/fixtures',
      dest: './test/sprites',
      relativeTo: './test/fixtures',
      cacheBuster: false
    };
    let processCss = postcss(
      cyspriter(pluginOptions)
    );
    let css = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.css'), {encoding: 'utf8'});
    let cssExpected = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.expected.css'), {encoding: 'utf8'});

    processCss
      .process(css)
      .then(result => {
        let spriteCreated =
          fs.existsSync(path.resolve(global.ROOT_TEST, 'sprites', 'icons.png'));
        spriteCreated.should.be.ok();
        cssExpected.should.be.equal(result.css);

        done();
      }).catch((err) => {
      done(err);
    });
  });

  it('Should create correctly with required global options', (done) => {
    let pluginOptions = {
      src: './test/fixtures',
      dest: './test/sprites',
      relativeTo: './test/fixtures',
      cacheBuster: false
    };
    let processCss = postcss(
      cyspriter(pluginOptions)
    );
    let css = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.css'), {encoding: 'utf8'});
    let cssExpected = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.expected.css'), {encoding: 'utf8'});

    processCss
      .process(css)
      .then(result => {
        let spriteCreated =
          fs.existsSync(path.resolve(global.ROOT_TEST, 'sprites', 'icons.png'));
        spriteCreated.should.be.ok();
        cssExpected.should.be.equal(result.css);

        done();
      }).catch((err) => {
      done(err);
    });
  });

  it('Should create correctly with optional global options', (done) => {
    let pluginOptions = {
      src: './test/fixtures',
      dest: './test/sprites',
      relativeTo: './test/fixtures',
      cacheBuster: false,
      padding: 10,
      includeSize: false
    };
    let processCss = postcss(
      cyspriter(pluginOptions)
    );
    let css = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.globOpts.css'), {encoding: 'utf8'});
    let cssExpected = fs
      .readFileSync(path.resolve(
        global.ROOT_TEST, 'fixtures', 'test.globOpts.expected.css'),
        {encoding: 'utf8'});

    processCss
      .process(css)
      .then(result => {
        let spriteCreated =
          fs.existsSync(path.resolve(global.ROOT_TEST, 'sprites', 'icons.png'));
        spriteCreated.should.be.ok();
        cssExpected.should.be.equal(result.css);

        done();
      }).catch((err) => {
      done(err);
    });
  });

  it('Should create correctly with retina and specific options for sprite',
    (done) => {
      let pluginOptions = {
        src: './test/fixtures',
        dest: './test/sprites',
        relativeTo: './test/fixtures',
        cacheBuster: false,
        padding: 10
      };
      let processCss = postcss(
        cyspriter(pluginOptions)
      );
      let css = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST,
          'fixtures', 'test.spriteOpts.css'), {encoding: 'utf8'});
      let cssExpected = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST, 'fixtures', 'test.spriteOpts.expected.css'),
          {encoding: 'utf8'});

      processCss
        .process(css)
        .then(result => {
          let spriteCreated =
            fs.existsSync(
              path.resolve(global.ROOT_TEST, 'sprites', 'retina.png'));
          spriteCreated.should.be.ok();
          cssExpected.should.be.equal(result.css);

          done();
        }).catch((err) => {
        done(err);
      });
    });

  it('Should create correctly with magic selector',
    (done) => {
      let pluginOptions = {
        src: './test/fixtures',
        dest: './test/sprites',
        relativeTo: './test/fixtures',
        cacheBuster: false,
        padding: 10
      };
      let processCss = postcss(
        cyspriter(pluginOptions)
      );
      let css = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST,
          'fixtures', 'test.magicSelector.css'), {encoding: 'utf8'});
      let cssExpected = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST, 'fixtures', 'test.magicSelector.expected.css'),
          {encoding: 'utf8'});

      processCss
        .process(css)
        .then(result => {
          let spriteCreated =
            fs.existsSync(
              path.resolve(global.ROOT_TEST, 'sprites', 'magic.png'));
          spriteCreated.should.be.ok();
          cssExpected.should.equal(result.css);

          done();
        }).catch((err) => {
        done(err);
      });
    });

  it('Should create correctly multiple sprites',
    (done) => {
      let pluginOptions = {
        src: './test/fixtures',
        dest: './test/sprites',
        relativeTo: './test/fixtures',
        cacheBuster: false,
        padding: 10
      };
      let processCss = postcss(
        cyspriter(pluginOptions)
      );
      let css = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST,
          'fixtures', 'test.multi.css'), {encoding: 'utf8'});
      let cssExpected = fs
        .readFileSync(path.resolve(
          global.ROOT_TEST, 'fixtures', 'test.multi.expected.css'),
          {encoding: 'utf8'});

      processCss
        .process(css)
        .then(result => {
          let sprite1Created =
            fs.existsSync(
              path.resolve(global.ROOT_TEST, 'sprites', 'retina.png'));
          let sprite2Created =
            fs.existsSync(
              path.resolve(global.ROOT_TEST, 'sprites', 'magic.png'));
          let sprite3Created =
            fs.existsSync(
              path.resolve(global.ROOT_TEST, 'sprites', 'icons.png'));
          sprite1Created.should.be.ok();
          sprite2Created.should.be.ok();
          sprite3Created.should.be.ok();
          cssExpected.should.equal(result.css);

          done();
        }).catch((err) => {
        done(err);
      });
    });
});


text:
#include "Math/Transform.hpp"
#include "Math/Euler.hpp"
#include "Math/Matrix3x3.hpp"
#include "Math/Vector4.hpp"

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

namespace Ocular
{
    namespace Math
    {
        //----------------------------------------------------------------------------------
        // CONSTRUCTORS
        //----------------------------------------------------------------------------------

        Transform::Transform(Vector3f const& position, Quaternion const& rotation, Vector3f const& scale)
            : m_Position(position),
              m_Rotation(rotation),
              m_Scale(scale),
              m_DirtyFlags(0)
        {
            OCULAR_EXPOSE(m_Position);
            OCULAR_EXPOSE(m_Rotation);
            OCULAR_EXPOSE(m_Scale);
        }

        Transform::Transform()
            : m_Scale(Vector3f(1.0f, 1.0f, 1.0f)),
              m_DirtyFlags(0)
        {
            OCULAR_EXPOSE(m_Position);
            OCULAR_EXPOSE(m_Rotation);
            OCULAR_EXPOSE(m_Scale);
        }

        Transform::~Transform()
        {

        }

        //----------------------------------------------------------------------------------
        // PUBLIC METHODS
        //----------------------------------------------------------------------------------

        void Transform::refresh()
        {
            m_ModelMatrix = Matrix4x4(m_Position, m_Rotation, m_Scale);
        }

        //----------------------------------------------------------------
        // Getters and Setters
        //----------------------------------------------------------------

        uint32_t Transform::getDirtyFlags(bool const clearFlags)
        {
            const uint32_t result = m_DirtyFlags;

            if(clearFlags)
            {
                m_DirtyFlags = 0;
            }

            return result;
        }

        void Transform::setPosition(Vector3f const& position)
        {
            m_Position = position;
            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Position);

            refresh();
        }

        void Transform::setPosition(float const x, float const y, float const z)
        {
            m_Position.x = x;
            m_Position.y = y;
            m_Position.z = z;

            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Position);

            refresh();
        }

        Vector3f const& Transform::getPosition() const
        {
            return m_Position;
        }

        void Transform::setRotation(Quaternion const& rotation)
        {
            m_Rotation = rotation;
            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Rotation);

            refresh();
        }

        Quaternion const& Transform::getRotation() const
        {
            return m_Rotation;
        }

        void Transform::setScale(Vector3f const& scale)
        {
            m_Scale = scale;
            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Scale);

            refresh();
        }

        Vector3f const& Transform::getScale() const
        {
            return m_Scale;
        }

        Vector3f Transform::getForwards() const
        {
            Vector3f result;
            Matrix3x3 mat(m_Rotation);

            mat.getCol(2, result);

            return result;
        }

        Vector3f Transform::getUp() const
        {
            Vector3f result;
            Matrix3x3 mat(m_Rotation);

            mat.getCol(1, result);

            return result;
        }

        Vector3f Transform::getRight() const
        {
            Vector3f result;
            Matrix3x3 mat(m_Rotation);

            mat.getCol(0, result);

            return result;
        }

        Matrix4x4 const& Transform::getModelMatrix() const
        {
            return m_ModelMatrix;
        }

        //----------------------------------------------------------------
        // Movement
        //----------------------------------------------------------------

        void Transform::translate(Vector3f const& translation, bool local)
        {
            if(local)
            {
                m_Position += (Matrix3x3(m_Rotation) * translation);
            }
            else
            {
                m_Position += translation;
            }

            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Position);
            refresh();
        }

        void Transform::moveForward(float const delta)
        {
            translate(getForwards() * delta);
        }

        void Transform::moveUp(float const delta)
        {
            translate(getUp() * delta);
        }

        void Transform::moveRight(float const delta)
        {
            translate(getRight() * delta);
        }

        //----------------------------------------------------------------
        // Rotation
        //----------------------------------------------------------------

        void Transform::rotate(float const angle, Vector3f const& axis)
        {
            m_Rotation = Quaternion::Rotate(m_Rotation, angle, axis);
            refresh();

            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Rotation);
        }

        void Transform::rotate(Math::Quaternion const& rotation)
        {
            m_Rotation = m_Rotation * rotation;
            refresh();

            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Rotation);
        }

        void Transform::lookAt(Vector3f const& point, Vector3f const& upVector)
        {
            m_Rotation = Quaternion::CreateLookAtRotation(m_Position, point, upVector).getConjugate();
            refresh();

            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Position);
            m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Rotation);
        }

        //----------------------------------------------------------------
        // Inherited Methods
        //----------------------------------------------------------------

        void Transform::onLoad(Core::BuilderNode const* node)
        {
            ObjectIO::onLoad(node);
            refresh();
        }

        void Transform::onVariableModified(std::string const& varName)
        {
            if(Utils::String::IsEqual(varName, "m_Position"))
            {
                m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Position);
            }
            else if(Utils::String::IsEqual(varName, "m_Rotation"))
            {
                m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Rotation);
            }
            else if(Utils::String::IsEqual(varName, "m_Scale"))
            {
                m_DirtyFlags |= static_cast<uint32_t>(DirtyFlags::Scale);
            }
        }

        //----------------------------------------------------------------------------------
        // PROTECTED METHODS
        //----------------------------------------------------------------------------------

        //----------------------------------------------------------------------------------
        // PRIVATE METHODS
        //----------------------------------------------------------------------------------
    }
}


text:
This example shows how to setup **Kubernetes-On-Nomad** on four CoreOS Vagrant servers.
You need Vagrant installed and it's only been tested on VirtulaBox.

The example uses the new `cluster` command.

You need `bash >= 4` to run `kon`. If you're on OSX you can install a newer version of
`bash` using [Homebrew](https://brew.sh/) and `brew install bash`.

First you need to clone the project:
```
$ git clone https://github.com/TheNatureOfSoftware/kubernetes-on-nomad.git
$ cd kubernetes-on-arm/examples/coreos
```

Kubernetes-On-Nomad (`kon`) uses a configuration file `kon.conf` for setting up a cluster.
You can generate a sample configuration file by running:
```
$ kon generate init
```

For this example there's already a [kon.conf](./kon.conf) configuration file.

The configuration tells `kon` which nodes should be used as Nomad and Consul servers:
```
# This a comma separated list of servers <region>:<datacenter>:<hostname>:<IP address>
KON_SERVERS=swe:east:core-01:172.17.8.101
```
and witch servers should be used as `etcd` servers:
```
ETCD_SERVERS=http://172.17.8.101:2379
ETCD_INITIAL_CLUSTER=core-01=http://172.17.8.101:2380
ETCD_INITIAL_CLUSTER_TOKEN=etcd-initial-token-dc1
```

The configuration also lists all nodes that will be used as Kubernetes nodes.
Kubernetes nodes are called **minions**, to separate them from Nomad nodes.
There are three `minions` in this example. The format is the same as for `KON_SERVERS`.
```
KON_MINIONS=swe:east:core-02:172.17.8.102,swe:east:core-03:172.17.8.103,swe:east:core-04:172.17.8.104
```

First we need to boot up all our servers. This step and the configuration `KON_VAGRANT_SSH=true` in `kon.conf` is the only Vagrant specific about this example.

Run:
```
$ vagrant up
```

When all servers are up and running it's time to start our Nomad cluster.

Make sure your in the right spot and use `kon` to start the cluster:
```
$ pwd
.../kubernetes-on-nomad/examples/coreos
$ bash ../../kon.sh --config ./kon.conf cluster apply
```

When the `cluster apply`-command is done, login on any node and check the state.

First login:
```
$ vagrant ssh core-03
core@core-03 ~ $ # Switch to root
core@core-03 ~ $ sudo -u root -i
```
and check the cluster state using the `view state`-command:
```
core-03 ~ # eval $(kon --quiet nomad env)
core-03 ~ # kon --quiet view state
Components                              State
-----------------------                 ----------
certificates
config                                  OK
consul                                  Running
etcd                                    NotConfigured
kube-apiserver
kube-controller-manager
kube-proxy
kube-scheduler
kubeconfig
kubelet
nomad                                   Running
```
As you can see Consul and Nomad are running and `kon.conf` has been stored in Consul. All `DNS` queries on the host are delegated to Consul. You can test this by issuing the following:
```
core-03 ~ # dig +short google.com
172.217.18.142
core-03 ~ # dig +short nomad.service.east.consul
172.17.8.101
```

We now have a Nomad cluster with Consul. Before we can start Kubernetes we
need to configure and start `etcd`:
```
core-03 ~ # kon -yes etcd config && kon etcd start && kon --quiet view state
```
```
Components                              State
-----------------------                 ----------
certificates
config                                  OK
consul                                  Running
etcd                                    Running
kube-apiserver                          Stopped
kube-controller-manager                 Stopped
kube-proxy                              Stopped
kube-scheduler                          Stopped
kubeconfig
kubelet                                 Stopped
kubernetes                              Stopped
nomad                                   Running
```

The last step is to configure and start Kubernetes:
```
core-03 ~ # kon kubernetes config && kon kubernetes start && watch kon --quiet view state
```
```
Every 2.0s: kon --quiet view state                                                                                Tue Oct 24 14:05:19 2017

Components                              State
-----------------------                 ----------
certificates                            OK
config                                  OK
consul                                  Running
etcd                                    Running
kube-apiserver                          Running
kube-controller-manager                 Running
kube-proxy                              Running
kube-scheduler                          Running
kubeconfig                              OK
kubelet                                 Running
kubernetes                              Running
kubernetes/minion/core-02               Ready
kubernetes/minion/core-03               Ready
kubernetes/minion/core-04               Ready
nomad                                   Running
```

You now have a Kubernetes cluster, up and running on Nomad, to play around with.
I encourage you to try out what happens if you kill the `apiserver`, or any other
component, in the Kubernetes control plane. Or why not shutdown one of the servers (except `core-01`)?


text:
using namespace stim;

std::string stim::run_captured_stim_main(std::vector<const char *> flags, const char *std_in_content) {
    // Setup input.
    RaiiTempNamedFile raii_temp_file;
    if (std_in_content != nullptr) {
        raii_temp_file.write_contents(std_in_content);
        flags.push_back("--in");
        flags.push_back(raii_temp_file.path.data());
    }
    flags.insert(flags.begin(), "[PROGRAM_LOCATION_IGNORE]");

    // Setup output.
    testing::internal::CaptureStdout();
    testing::internal::CaptureStderr();
    int result;
    try {
        result = stim::main(flags.size(), flags.data());
    } catch (const std::exception &e) {
        return "[exception=" + std::string(e.what()) + "]" + testing::internal::GetCapturedStdout() +
               testing::internal::GetCapturedStderr();
    }
    std::string out = testing::internal::GetCapturedStdout();
    std::string err = testing::internal::GetCapturedStderr();
    if (!err.empty()) {
        return out + "[stderr=" + err + "]";
    }
    if (result != EXIT_SUCCESS) {
        return "[exit code != EXIT_SUCCESS]";
    }

    return out;
}

std::string stim::trim(std::string text) {
    size_t s = 0;
    size_t e = text.size();
    while (s < e && std::isspace(text[s])) {
        s++;
    }
    while (s < e && std::isspace(text[e - 1])) {
        e--;
    }
    return text.substr(s, e - s);
}

bool stim::matches(std::string actual, std::string pattern) {
    // Hackily work around C++ regex not supporting multiline matching.
    std::replace(actual.begin(), actual.end(), '\n', 'X');
    std::replace(pattern.begin(), pattern.end(), '\n', 'X');
    return std::regex_match(actual, std::regex("^" + pattern + "$"));
}

TEST(main, help_modes) {
    ASSERT_TRUE(matches(run_captured_stim_main({"--help"}, ""), ".*Available stim commands.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({"help"}, ""), ".*Available stim commands.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({}, ""), ".+stderr.+No mode.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({"--sample", "--repl"}, ""), ".+stderr.+More than one mode.+"));
    ASSERT_TRUE(
        matches(run_captured_stim_main({"--sample", "--repl", "--detect"}, ""), ".+stderr.+More than one mode.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({"--help", "dhnsahddjoidsa"}, ""), ".*Unrecognized.*"));
    ASSERT_TRUE(matches(run_captured_stim_main({"--help", "H"}, ""), ".+Hadamard.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({"--help", "--sample"}, ""), ".*Samples measurements from a circuit.+"));
    ASSERT_TRUE(matches(run_captured_stim_main({"--help", "sample"}, ""), ".*Samples measurements from a circuit.+"));
}

TEST(main, bad_flag) {
    ASSERT_EQ(
        trim(run_captured_stim_main({"--gen", "--unknown"}, "")),
        trim("[stderr=\033[31mUnrecognized command line argument --unknown for `stim gen`.\n"
             "Recognized command line arguments for `stim gen`:\n"
             "    --after_clifford_depolarization\n"
             "    --after_reset_flip_probability\n"
             "    --before_measure_flip_probability\n"
             "    --before_round_data_depolarization\n"
             "    --code\n"
             "    --distance\n"
             "    --in\n"
             "    --out\n"
             "    --rounds\n"
             "    --task\n"
             "\033[0m]\n"));
}


text:
namespace Aversive {
namespace String {

template<char... CHARS>
class CompilString : public Interface<String, CompilString<CHARS...>> {
private:
  template<char ARG1, char... ARGS>
  struct Helper {
    static constexpr inline char get(unsigned int i) {
      return (i == 0) ? ARG1 : Helper<ARGS...>::get(i-1);
    }

    static constexpr inline unsigned int len(void) {
      return 1+Helper<ARGS...>::len();
    }
  };

  template<char ARG1>
  struct Helper<ARG1> {
    static constexpr inline char get(unsigned int i) {
      return (i == 0) ? ARG1 : 0;
    }

    static constexpr inline unsigned int len(void) {
      return 1;
    }
  };

public:
  inline CompilString(void) {}

public:
  inline char operator[](unsigned int i) const {
    return Helper<CHARS...>::get(i);
  }

  inline unsigned int len(void) const {
    return Helper<CHARS...>::len();
  }
};

}
}

#endif//AVERSIVE_STRING_COMPIL_HPP


text:
package quasar.std

import slamdata.Predef._
import quasar._
import quasar.common.data.Data
import quasar.frontend.logicalplan.{LogicalPlan => LP, _}

import matryoshka._
import matryoshka.implicits._
import scalaz._, Scalaz._
import shapeless.{Data => _, :: => _, _}

trait StringLib extends Library {

  val Concat = BinaryFunc(
    Mapping,
    "Concatenates two (or more) string values",
    new Func.Simplifier {
      def apply[T]
        (orig: LP[T])
        (implicit TR: Recursive.Aux[T, LP], TC: Corecursive.Aux[T, LP]) =
        orig match {
          case InvokeUnapply(_, Sized(Embed(Constant(Data.Str(""))), Embed(second))) =>
            second.some
          case InvokeUnapply(_, Sized(Embed(first), Embed(Constant(Data.Str(""))))) =>
            first.some
          case _ => None
        }
    })

  val Like = TernaryFunc(
    Mapping,
    "Determines if a string value matches a pattern.",
    noSimplification)

  val Search = TernaryFunc(
    Mapping,
    "Determines if a string value matches a regular expression. If the third argument is true, then it is a case-insensitive match.",
    noSimplification)

  val Length = UnaryFunc(
    Mapping,
    "Counts the number of characters in a string.",
    noSimplification)

  val Lower = UnaryFunc(
    Mapping,
    "Converts the string to lower case.",
    noSimplification)

  val Upper = UnaryFunc(
    Mapping,
    "Converts the string to upper case.",
    noSimplification)

  /** Substring which always gives a result, no matter what offsets are provided.
    * Reverse-engineered from MongoDb's \$substr op, for lack of a better idea
    * of how this should work. Note: if `start` < 0, the result is `""`.
    * If `length` < 0, then result includes the rest of the string. Otherwise
    * the behavior is as you might expect.
    */
  def safeSubstring(str: String, start: Int, length: Int): String =
    if (start < 0 || start > str.length) ""
    else if (length < 0) str.substring(start, str.length)
    else str.substring(start, (start + length) min str.length)

  val Substring: TernaryFunc = TernaryFunc(
    Mapping,
    "Extracts a portion of the string",
    new Func.Simplifier {
      def apply[T]
        (orig: LP[T])
        (implicit TR: Recursive.Aux[T, LP], TC: Corecursive.Aux[T, LP]) =
        orig match {
          case InvokeUnapply(f @ TernaryFunc(_, _, _), Sized(
            Embed(Constant(Data.Str(str))),
            Embed(Constant(Data.Int(from))),
            for0)) if from != 0 =>
              if (from < 0 || from > str.length) Constant[T](Data.Str("")).some
              else
                Invoke(f, Func.Input3(
                  Constant[T](Data.Str(str.substring(from.intValue))).embed,
                  Constant[T](Data.Int(0)).embed,
                  for0)).some
          case _ => None
        }
    })

  val Split = BinaryFunc(
    Mapping,
    "Splits a string into an array of substrings based on a delimiter.",
    noSimplification)

  val Boolean = UnaryFunc(
    Mapping,
    "Converts the strings "true" and "false" into boolean values. This is a partial function – arguments that don't satisfy the constraint have undefined results.",
    noSimplification)

  val Integer = UnaryFunc(
    Mapping,
    "Converts strings containing integers into integer values. This is a partial function – arguments that don't satisfy the constraint have undefined results.",
    noSimplification)

  val Decimal = UnaryFunc(
    Mapping,
    "Converts strings containing decimals into decimal values. This is a partial function – arguments that don't satisfy the constraint have undefined results.",
    noSimplification)

  val Number = UnaryFunc(
    Mapping,
    "Converts strings containing numbers into number values. This is a partial function – arguments that don't satisfy the constraint have undefined results.",
    noSimplification)

  val Null = UnaryFunc(
    Mapping,
    "Converts strings containing "null" into the null value. This is a partial function – arguments that don't satisfy the constraint have undefined results.",
    noSimplification)

  val ToString: UnaryFunc = UnaryFunc(
    Mapping,
    "Converts any primitive type to a string.",
    noSimplification)
}

object StringLib extends StringLib


text:
export = GoogleImages;

declare namespace GoogleImages {
    type SearchImageSize = "icon" | "small" | "medium" | "large" | "xlarge" | "xxlarge" | "huge";
    type SearchImageType = "clipart" | "face" | "lineart" | "news" | "photo";
    type SearchDominantColor = "black" | "blue" | "brown" | "gray" | "green" | "pink" | "purple" | "teal" | "white" | "yellow";
    type SearchColorType = "color" | "gray" | "mono";
    type SearchSafe = "high" | "medium" | "off";

    interface SearchOptions {
        page?: number | undefined;
        size?: SearchImageSize | undefined;
        type?: SearchImageType | undefined;
        dominantColor?: SearchDominantColor | undefined;
        colorType?: SearchColorType | undefined;
        safe?: SearchSafe | undefined;
    }

    interface Image {
        url: string;
        type: string;
        width: number;
        height: number;
        size: number;
        thumbnail: {
            url: string,
            width: number,
            height: number
        };
    }
}

declare class GoogleImages {
    constructor(engineId: string, apiKey: string);

    search(searchTerm: string, options?: GoogleImages.SearchOptions): Promise<GoogleImages.Image[]>;
}


text:
import unittest
from sikuli import *
from org.sikuli.script import JButtons

class TestScreen(unittest.TestCase):

   @classmethod
   def setUpClass(cls):
      pass

   @classmethod
   def tearDownClass(cls):
      pass

   def testCapture(self):
      simg = SCREEN.capture(0, 0, 100, 100)
      #simg = SCREEN.capture("message")

   def testContains(self):
       screen = Screen()
       w, h = screen.w//2, screen.h//2
       x, y = screen.x + w, screen.y + h

       self.assertIn((x, y), screen)
       self.assertIn(Location(x, y) in screen)
       self.assertIn((x, y, w, h) in screen)
       self.assertIn(Region(x, y, w, h) in screen)
       self.assertFalse((-1, -1) in screen)

       # test overlap case
       overlap = (-1, y, screen.w, h)
       self.assertFalse(overlap in screen,
                        "Overlapping region {} is not completely within {}"
                        "".format(overlap, screen))

   def testInt(self):
       self.assertEqual(int(Screen()), 0,
                        "Screen should be default screen with an id of 0")

   def testBool(self):
       self.assertTrue(bool(Screen()))
       self.assertFalse(bool(Screen(-1)))


text:
.class Lcom/android/server/MountService$7$3;
.super Ljava/lang/Thread;
.source "MountService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/MountService$7;->onReceive(Landroid/content/Context;Landroid/content/Intent;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/server/MountService$7;

# direct methods
.method constructor <init>(Lcom/android/server/MountService$7;)V
    .locals 0

    .prologue
    .line 1150
    iput-object p1, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    invoke-direct {p0}, Ljava/lang/Thread;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 11

    .prologue
    .line 1152
    # getter for: Lcom/android/server/MountService;->OMADM_SYNC_LOCK:Ljava/lang/Object;
    invoke-static {}, Lcom/android/server/MountService;->access$3500()Ljava/lang/Object;

    move-result-object v8

    monitor-enter v8

    .line 1153
    :try_start_0
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    # getter for: Lcom/android/server/MountService;->mVolumes:Ljava/util/ArrayList;
    invoke-static {v7}, Lcom/android/server/MountService;->access$2400(Lcom/android/server/MountService;)Ljava/util/ArrayList;

    move-result-object v7

    invoke-virtual {v7}, Ljava/util/ArrayList;->size()I

    move-result v3

    .line 1154
    .local v3, "length":I
    const/4 v5, 0x0

    .line 1155
    .local v5, "path":Ljava/lang/String;
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    if-ge v1, v3, :cond_4

    .line 1156
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    # getter for: Lcom/android/server/MountService;->mVolumes:Ljava/util/ArrayList;
    invoke-static {v7}, Lcom/android/server/MountService;->access$2400(Lcom/android/server/MountService;)Ljava/util/ArrayList;

    move-result-object v7

    invoke-virtual {v7, v1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Landroid/os/storage/StorageVolume;

    invoke-virtual {v7}, Landroid/os/storage/StorageVolume;->getPath()Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v5

    .line 1158
    :try_start_1
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    invoke-virtual {v7, v5}, Lcom/android/server/MountService;->getVolumeState(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v4

    .line 1159
    .local v4, "mCurState":Ljava/lang/String;
    const-string v7, "MountService"

    invoke-static {v7, v4}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 1160
    const-string v7, "mounted"

    invoke-virtual {v4, v7}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v7

    if-eqz v7, :cond_2

    .line 1164
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    const/4 v9, 0x1

    const/4 v10, 0x1

    invoke-virtual {v7, v5, v9, v10}, Lcom/android/server/MountService;->unmountVolume(Ljava/lang/String;ZZ)V

    .line 1167
    const/4 v2, 0x0

    .local v2, "j":I
    :goto_1
    const/16 v7, 0x14

    if-ge v2, v7, :cond_0

    .line 1168
    const-wide/16 v9, 0x3e8

    invoke-static {v9, v10}, Lcom/android/server/MountService$7$3;->sleep(J)V

    .line 1169
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    invoke-virtual {v7, v5}, Lcom/android/server/MountService;->getVolumeState(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v4

    .line 1170
    const-string v7, "unmounted"

    invoke-virtual {v4, v7}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v7

    if-eqz v7, :cond_1

    .line 1171
    const-string v7, "MountService"

    const-string v9, "Unmount Succeeded!"

    invoke-static {v7, v9}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 1180
    .end local v2    # "j":I
    :cond_0
    :goto_2
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    invoke-virtual {v7, v5}, Lcom/android/server/MountService;->formatVolume(Ljava/lang/String;)I

    move-result v6

    .line 1181
    .local v6, "ret":I
    if-nez v6, :cond_3

    .line 1182
    const-string v7, "MountService"

    const-string v9, "SD format Succeed!"

    invoke-static {v7, v9}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 1155
    .end local v4    # "mCurState":Ljava/lang/String;
    .end local v6    # "ret":I
    :goto_3
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 1167
    .restart local v2    # "j":I
    .restart local v4    # "mCurState":Ljava/lang/String;
    :cond_1
    add-int/lit8 v2, v2, 0x1

    goto :goto_1

    .line 1176
    .end local v2    # "j":I
    :cond_2
    const-string v7, "shared"

    invoke-virtual {v4, v7}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v7

    if-eqz v7, :cond_0

    .line 1177
    iget-object v7, p0, Lcom/android/server/MountService$7$3;->this$1:Lcom/android/server/MountService$7;

    iget-object v7, v7, Lcom/android/server/MountService$7;->this$0:Lcom/android/server/MountService;

    const-string v9, "ums"

    const/4 v10, 0x0

    # invokes: Lcom/android/server/MountService;->doShareUnshareVolume(Ljava/lang/String;Ljava/lang/String;Z)V
    invoke-static {v7, v5, v9, v10}, Lcom/android/server/MountService;->access$1100(Lcom/android/server/MountService;Ljava/lang/String;Ljava/lang/String;Z)V
    :try_end_1
    .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    goto :goto_2

    .line 1186
    .end local v4    # "mCurState":Ljava/lang/String;
    :catch_0
    move-exception v0

    .line 1187
    .local v0, "ex":Ljava/lang/Exception;
    :try_start_2
    const-string v7, "MountService"

    const-string v9, "SD format exception"

    invoke-static {v7, v9, v0}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_3

    .line 1190
    .end local v0    # "ex":Ljava/lang/Exception;
    .end local v1    # "i":I
    .end local v3    # "length":I
    .end local v5    # "path":Ljava/lang/String;
    :catchall_0
    move-exception v7

    monitor-exit v8
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    throw v7

    .line 1184
    .restart local v1    # "i":I
    .restart local v3    # "length":I
    .restart local v4    # "mCurState":Ljava/lang/String;
    .restart local v5    # "path":Ljava/lang/String;
    .restart local v6    # "ret":I
    :cond_3
    :try_start_3
    const-string v7, "MountService"

    const-string v9, "SD format Failed!"

    invoke-static {v7, v9}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;)I
    :try_end_3
    .catch Ljava/lang/Exception; {:try_start_3 .. :try_end_3} :catch_0
    .catchall {:try_start_3 .. :try_end_3} :catchall_0

    goto :goto_3

    .line 1190
    .end local v4    # "mCurState":Ljava/lang/String;
    .end local v6    # "ret":I
    :cond_4
    :try_start_4
    monitor-exit v8
    :try_end_4
    .catchall {:try_start_4 .. :try_end_4} :catchall_0

    .line 1191
    return-void
.end method


text:
using Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PublisherConnections
{
    /// <summary>
    /// Batch rejects one or more publisher connections.
    ///
    /// A bidder will not receive bid requests from publishers associated with rejected publisher
    /// connections.
    /// </summary>
    public class BatchRejectPublisherConnections : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public BatchRejectPublisherConnections()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example batch rejects one or more publisher connections.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "publisher_connection_ids"};
            bool showHelp = false;

            string accountId = null;
            IList<string> publisherConnectionIds = new List<string>();

            OptionSet options = new OptionSet {
                "Batch rejects one or more publisher connections to a given bidder account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource for which the " +
                     "publisher connections are being rejected."),
                    a => accountId = a
                },
                {
                    "p|publisher_connection_ids=",
                    ("[Required] One or more resource IDs for the bidders.publisherConnections " +
                     "resource that are being rejected. Specify this argument for each value " +
                     "you intend to include. Values specified must be valid URLs. These will be " +
                     "used to construct the publisher connection names passed in the " +
                     "publisherConnections.batchReject request body"),
                    p => publisherConnectionIds.Add(p)
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["publisher_connection_ids"] =
                publisherConnectionIds.Count > 0 ? publisherConnectionIds : null;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"bidders/{accountId}";

            IList<string> publisherConnectionIds =
                (IList<string>) parsedArgs["publisher_connection_ids"];
            IList<string> publisherConnectionNames = new List<string>();

            foreach (string publisherConnectionId in publisherConnectionIds)
            {
                publisherConnectionNames.Add(
                    $"bidders/{accountId}/publisherConnections/{publisherConnectionId}");
            }

            BatchRejectPublisherConnectionsRequest body =
                new BatchRejectPublisherConnectionsRequest();
            body.Names = publisherConnectionNames;

            BiddersResource.PublisherConnectionsResource.BatchRejectRequest request =
                rtbService.Bidders.PublisherConnections.BatchReject(body, parent);
            BatchRejectPublisherConnectionsResponse response = null;

            Console.WriteLine(
                "Batch rejecting publisher connections for bidder with name: {0}",
                parent);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $"Real-time Bidding API returned error response:\n{exception.Message}");
            }

            foreach (PublisherConnection publisherConnection in response.PublisherConnections)
            {
                Utilities.PrintPublisherConnection(publisherConnection);
            }
        }
    }
}


text:
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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.
 */
/*
 * $Id: ExpressionOwner.java,v 1.1.2.1 2005/08/01 01:30:12 jeffsuttor Exp $
 */
package com.sun.org.apache.xpath.internal;

/**
 * Classes that implement this interface own an expression, which
 * can be rewritten.
 */
public interface ExpressionOwner
{
  /**
   * Get the raw Expression object that this class wraps.
   *
   * @return the raw Expression object, which should not normally be null.
   */
  public Expression getExpression();

  /**
   * Set the raw expression object for this object.
   *
   * @param exp the raw Expression object, which should not normally be null.
   */
  public void setExpression(Expression exp);

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\projects\OpenTribes\Core/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\projects\OpenTribes\Core /

vendor /

swiftmailer /

swiftmailer /

lib /

classes /

Swift.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

0.00%

0 / 3

      CRAP

10.00%

2 / 20

      Swift

0.00%

0 / 1

0.00%

0 / 3

      68.05

10.00%

2 / 20

       init($callable)

0.00%

0 / 1

      2

0.00%

0 / 2

       autoload($class)

0.00%

0 / 1

      27.81

15.38%

2 / 13

       registerAutoload($callable = null)

0.00%

0 / 1

      6

0.00%

0 / 5

1
	<?php

2

3

10

11
	/**

12
	 * General utility class in Swift Mailer, not to be instantiated.

13
	 *

14
	 * @package Swift

15
	 *

16
	 * @author Chris Corbyn

17
	 */

18
	abstract class Swift

19
	{

20
	    public static $initialized = false;

21
	    public static $inits = array();

22

23
	    /** Swift Mailer Version number generated during dist release process */

24
	    const VERSION = '@SWIFT_VERSION_NUMBER@';

25

26
	    /**

27
	     * Registers an initializer callable that will be called the first time

28
	     * a SwiftMailer class is autoloaded.

29
	     *

30
	     * This enables you to tweak the default configuration in a lazy way.

31
	     *

32
	     * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class

33
	     */

34
	    public static function init($callable)

35
	    {

36
	        self::$inits[] = $callable;

37
	    }

38

39
	    /**

40
	     * Internal autoloader for spl_autoload_register().

41
	     *

42
	     * @param string $class

43
	     */

44
	    public static function autoload($class)

45
	    {

46
	        // Don't interfere with other autoloaders

47
	        if (0 !== strpos($class, 'Swift_')) {

48
	            return;

49
	        }

50

51
	        $path = dirname(__FILE__).'/'.str_replace('_', '/', $class).'.php';

52

53
	        if (!file_exists($path)) {

54
	            return;

55
	        }

56

57
	        require $path;

58

59
	        if (self::$inits && !self::$initialized) {

60
	            self::$initialized = true;

61
	            foreach (self::$inits as $init) {

62
	                call_user_func($init);

63
	            }

64
	        }

65
	    }

66

67
	    /**

68
	     * Configure autoloading using Swift Mailer.

69
	     *

70
	     * This is designed to play nicely with other autoloaders.

71
	     *

72
	     * @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class

73
	     */

74
	    public static function registerAutoload($callable = null)

75
	    {

76
	        if (null !== $callable) {

77
	            self::$inits[] = $callable;

78
	        }

79
	        spl_autoload_register(array('Swift', 'autoload'));

80
	    }

81
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.17 using PHP 5.5.6 and PHPUnit 3.7.34 at Sat Apr 5 13:10:46 CEST 2014.


text:
//	Copyright © 2013 - 2014, Alain Metge. All rights reserved.
//
//		This file is part of Hyperstore (http://www.hyperstore.org)
//
// 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.

#region Imports

using System.Diagnostics;

#endregion

namespace Hyperstore.Modeling.HyperGraph
{
    ///-------------------------------------------------------------------------------------------------
    /// <summary>
    ///  Stockage des informations d'un edge au niveau d'un vertex.
    /// </summary>
    ///-------------------------------------------------------------------------------------------------
    [DebuggerDisplay("Id={Id}, SchemaId={SchemaId}")]
    public class EdgeInfo : Hyperstore.Modeling.HyperGraph.NodeInfo
    {
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Constructor.
        /// </summary>
        /// <param name="id">
        ///  The identifier.
        /// </param>
        /// <param name="schemaId">
        ///  The identifier of the meta class.
        /// </param>
        /// <param name="endId">
        ///  The end identifier.
        /// </param>
        ///-------------------------------------------------------------------------------------------------
        public EdgeInfo(Identity id, Identity schemaId, Identity endId) : base(id, schemaId)
        {
            Contract.Requires(id, "id");
            Contract.Requires(schemaId, "schemaId");

            EndId = endId;
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Gets or sets the identifier of the end.
        /// </summary>
        /// <value>
        ///  The identifier of the end.
        /// </value>
        ///-------------------------------------------------------------------------------------------------
        public Identity EndId { get; private set; }
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_search"
        android:showAsAction="always"
        android:title="@string/action_search"
        android:actionViewClass="android.widget.SearchView" />
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:icon="@drawable/ic_menu_item_secure"
        android:title="@string/action_settings"
        android:showAsAction="ifRoom|withText" />
  <item android:id="@+id/menu_item_refresh"
        android:icon="@drawable/ic_menu_item_refresh"
        android:title="@string/refresh"
        android:showAsAction="ifRoom|withText" />
</menu>


text:
export async function ipfsPut(content) {
    const obj = {
        content: Buffer.from(content),
        path: '/'
    }
    const response = await window.ipfs.files.add(obj)
    return response[0].hash
}

export async function readText(multihash) {
    const buffer = await window.ipfs.object.get(multihash)
    return buffer.toString('utf-8')
}

export async function getStats() {
    const ipfs = window.ipfs;
    const orbitDb = window.orbitDb
    const dbs = {}
    const stats = {}
    if (ipfs && ipfs.isOnline()) {
        stats.ipfsLoaded = true
        const peers = await ipfs.swarm.peers()
        const id = await ipfs.id()
        stats.peers = peers.map(p => p.peer.id._idB58String)
        stats.id = id.id
    } else {
        stats.ipfsLoaded = false
    }
    if (stats.ipfsLoaded && orbitDb) {
        stats.orbitDbLoaded = true
        stats.pubKey = await orbitDb.key.getPublic('hex')
        Object.values(window.dbs || {}).forEach(db => {
            let writeable = db.access.write.indexOf('*') >= 0 || db.access.write.indexOf(stats.pubKey) >= 0
            const dbInfo = {
                opLogLength: db._oplog.length,
                access: {
                    admin: db.access.admin,
                    read: db.access.read,
                    write: db.access.write,
                    writeable
                },
                peers: []
            }
            const subscription = orbitDb._pubsub._subscriptions[db.address]
            if (subscription && subscription.room) {
                dbInfo.peers = [...(subscription.room._peers || [])]
            }
            dbs[db.address] = dbInfo
        })
    } else {
        stats.orbitDbLoaded = false
    }
    stats.dbs = dbs
    return stats
}


text:
'use strict';

var mongoose = require('mongoose');

var shoppingListProductSchema = mongoose.Schema({
    name: { type: String, required: true, unique: true},
    categoryName: { type: String, required: true},
    categoryImage: { type: String },
    unit: {type: String},
    quantity: {type: Number},
    lifetime: {type: Number},
    image: {type: String}
});

var ShoppingListProduct = mongoose.model('ShoppingListProduct', shoppingListProductSchema);


text:
//@ts-check

'use strict';

const withDefaults = require('../shared.webpack.config');

module.exports = withDefaults({
	context: __dirname,
	entry: {
		extension: './src/ipynbMain.ts',
	},
	output: {
		filename: 'ipynbMain.js'
	}
});


text:
using AutoMapper;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Streamus_Web_API.App_Start;
using Streamus_Web_API.Domain;
using Streamus_Web_API.Dto;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;

namespace Streamus_Web_API
{
    public class StreamusWebApi : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            InitializeApplication();
        }

        public static void InitializeApplication()
        {
            //NHibernateProfiler.Initialize();

            //  I don't want $id, no need to support circular references: http://stackoverflow.com/questions/18355312/map-id-in-web-api-to-custom-id
            JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            jsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;

            //  Convert sentence casing to camel casing when serializing to JSON.
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            CreateAutoMapperMaps();
        }

        /// <summary>
        ///     Initialize the AutoMapper mappings for the solution.
        ///     Do not reverse the mappings between domain and DTO: http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/
        ///     http://automapper.codeplex.com/
        /// </summary>
        public static void CreateAutoMapperMaps()
        {
            Mapper.CreateMap<ClientError, ClientErrorDto>();

            Mapper.CreateMap<Playlist, PlaylistDto>();
            Mapper.CreateMap<PlaylistItem, PlaylistItemDto>()
                  .ForMember(dest => dest.Song, opt => opt.ResolveUsing(src => new SongDto
                      {
                          Author = src.Author,
                          Duration = src.Duration,
                          Id = src.SongId,
                          Title = src.SongTitle,
                          Type = src.SongType
                      }));

            Mapper.CreateMap<ShareCode, ShareCodeDto>();

            Mapper.CreateMap<User, UserDto>();

            Mapper.AssertConfigurationIsValid();
        }
    }
}


text:
var Cache, Hash, NOT_EXISTING, SimpleCache, hasOwnProperty, util;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
util = require('util');
Hash = require('hash');
Cache = require('../cache');
NOT_EXISTING = Cache.NOT_EXISTING;
hasOwnProperty = Object.prototype.hasOwnProperty;
module.exports = SimpleCache = function(options) {
  Cache.call(this, options);
  this.data = new Hash(this.data);
  this.maxLength = this.maxLength || 0;
  this.maxAge = this.maxAge || 0;
  this.debug = this.debug || false;
  this.intervals = [];
  if (this.maxLength) {
    setTimeout(__bind(function() {
      return this.intervals.push(setInterval(__bind(function() {
        return this.reduce();
      }, this), 500));
    }, this), 100);
  }
  if (this.maxAge) {
    this.millis = (new Date).getMilliseconds();
    this.timeslots = {};
    this.intervals.push(setInterval(__bind(function() {
      var secs, _results;
      secs = this.seconds(this.maxAge);
      _results = [];
      while (this.removeTimeslot(secs)) {
        _results.push(secs--);
      }
      return _results;
    }, this), 1000));
  }
  return this;
};
util.inherits(SimpleCache, Cache);
SimpleCache.prototype.seconds = function(minus) {
  if (minus == null) {
    minus = 0;
  }
  return Math.floor((Date.now() - this.millis) / 1000) - minus;
};
SimpleCache.prototype.timeslot = function(minus) {
  var secs;
  if (minus == null) {
    minus = 0;
  }
  secs = this.seconds();
  if (this.timeslots[secs]) {
    return this.timeslots[secs];
  } else {
    return this.timeslots[secs] = [];
  }
};
SimpleCache.prototype.get = function(key, __) {
  var data;
  data = this.data.get(key);
  if (data) {
    data[1]++;
    return __(null, data[0]);
  }
  return __(null, NOT_EXISTING);
};
SimpleCache.prototype.set = function(key, data, __) {
  this.data.set(key, [data, 1]);
  if (this.maxAge) {
    this.timeslot().push(key);
  }
  return __(null);
};
SimpleCache.prototype.del = function(key) {
  return this.data.del(key);
};
SimpleCache.prototype.destruct = function() {
  var i, _i, _len, _ref, _results;
  _ref = this.intervals;
  _results = [];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    i = _ref[_i];
    _results.push(clearInterval(i));
  }
  return _results;
};
SimpleCache.prototype.reduce = function() {
  var accesses, le, reducedLength, t, _this;
  if (this.debug) {
    console.log("node_memo simple cache: Current length: " + (this.length()));
  }
  if (this.length() < this.maxLength) {
    return false;
  }
  if (this.debug) {
    t = Date.now();
  }
  reducedLength = Math.floor(this.maxLength / 2);
  accesses = [];
  this.data.forEach(function(v, k) {
    return accesses.push(v[1]);
  });
  le = accesses.sort(function(a, b) {
    return b - a;
  })[reducedLength];
  _this = this;
  this.data.forEach(function(v, k) {
    if (v[1] <= le) {
      return _this.del(k);
    }
  });
  if (this.debug) {
    console.log("node_memo simple cache: Reduced to " + reducedLength + " in " + (Date.now() - t) + " ms");
  }
  return true;
};
SimpleCache.prototype.length = function() {
  return Object.keys(this.data.getData()).length;
};
SimpleCache.prototype.removeTimeslot = function(slot) {
  var key, list, num, t, _i, _len;
  list = this.timeslots[slot];
  if (!(list != null)) {
    return false;
  }
  if (this.debug) {
    t = Date.now();
  }
  num = list.length;
  for (_i = 0, _len = list.length; _i < _len; _i++) {
    key = list[_i];
    this.del(key);
  }
  delete this.timeslots[slot];
  if (this.debug) {
    console.log("node_memo simple cache: Removed " + num + " objects in timeslot " + slot + " in " + (Date.now() - t) + " ms");
  }
  return true;
};