text:
"""Setup."""

from distutils import core
import os

from setuptools import find_packages

here = os.path.abspath(os.path.dirname(__file__))
try:
  README = open(os.path.join(here, 'README.md'), encoding='utf-8').read()
except IOError:
  README = ''

install_requires = [
    'absl-py>=0.7.0',
    'gym>=0.17.3',
    'numpy>=1.18.5',
    'pybullet>=3.0.4',
    'matplotlib>=3.1.1',
    'opencv-python>=4.1.2.30',
    'meshcat>=0.0.18',
    'scipy>=1.4.1',
    'scikit-image>=0.17.2',
    'tensorflow>=2.3.0',
    'tensorflow-addons>=0.11.2',
    'tensorflow_hub>=0.9.0',
    'transforms3d>=0.3.1',
]

core.setup(
    name='ravens',
    version='0.1',
    description='Ravens is a collection of simulated tasks in PyBullet for learning vision-based robotic manipulation.',
    long_description='\n\n'.join([README]),
    long_description_content_type='text/markdown',
    author='Andy Zeng, Pete Florence, Daniel Seita, Jonathan Tompson, Ayzaan Wahid',
    author_email='ravens-team@google.com',
    url='https://github.com/google-research/ravens',
    packages=find_packages(),
    install_requires=install_requires,
)


text:
pplog_mechanize
===============
[![Code Climate](https://codeclimate.com/github/gouf/pplog_mechanize_module/badges/gpa.svg)](https://codeclimate.com/github/gouf/pplog_mechanize_module)

redpajama_set_name: RedPajamaGithub


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-101.js
 * @description Object.defineProperties - 'P' is accessor property, both properties.[[Get]] and P.[[Get]] are two different values (8.12.9 step 12)
 */

function testcase() {

        var obj = {};

        function get_func() {
            return 10;
        }
        function set_func(value) {
            obj.setVerifyHelpProp = value;
        }

        Object.defineProperty(obj, "foo", {
            get: get_func,
            set: set_func,
            enumerable: true,
            configurable: true
        });

        function get_func2() {
            return 20;
        }

        Object.defineProperties(obj, {
            foo: {
                get: get_func2
            }
        });
        return accessorPropertyAttributesAreCorrect(obj, "foo", get_func2, set_func, "setVerifyHelpProp", true, true);
    }
runTestCase(testcase);


text:
  title: Override permalink
  layout: slide
  permalink: /slide/3/
---


text:
require 'rails_helper'

describe "organisations/_form.html.erb", :type => :view do
  before :each do
    @categories_start_with = {what_they_do: 'alligator', who_they_help: 'crocodile', how_they_help: 'iguana'}
    @organisation = Organisation.new(name: 'Sarah Plain and Tall Foundation')
    @category1 = FactoryGirl.create(:category, name: "alligator",  charity_commission_id: 100)
    @category2 = FactoryGirl.create(:category, name: "crocodile", charity_commission_id: 210)
    @category3 = FactoryGirl.create(:category, name: "iguana", charity_commission_id: 310)
    @category4 = FactoryGirl.create(:category, name: "capybara",  charity_commission_id: 101)
    @category5 = FactoryGirl.create(:category, name: "guinea pig", charity_commission_id: 201)
    @category6 = FactoryGirl.create(:category, name: "rabbit", charity_commission_id: 304)
    @organisation.categories << [@category1, @category3]
    @organisation.save!
    render partial: 'form', locals: {org: @organisation}
  end
  it "renders form partial even for empty Organisation" do
    expect(rendered).not_to be_nil
  end

  it "renders the form with placeholders" do

    hash = {
            'organisation_name' => 'Enter organisation name',
            'organisation_address'  => 'Enter organisation address',
            'organisation_postcode' => 'Enter organisation post code',
            'organisation_email' => 'Enter organisation email address',
            'organisation_description' => 'Enter organisation description',
            'organisation_website' => 'Enter organisation website url',
            'organisation_telephone' => 'Enter organisation phone number',
            'organisation_superadmin_email_to_add' => "You may add an organisation administrator email here",
            'organisation_donation_info' => 'Enter organisation donation url'
    }
    hash.each do |label,placeholder|
      expect(rendered).to have_xpath("(//td/input|//td/textarea)[@id='#{label}'][@placeholder='#{placeholder}']")
    end
  end

  it 'should have categories in scroll box ordered by type and name' do
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'What you do')]/following-sibling::div[1]/label[text()[contains(.,'alligator')]]")
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'What you do')]/following-sibling::div[2]/label[text()[contains(.,'capybara')]]")
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'Who you help')]/following-sibling::div[1]/label[text()[contains(.,'crocodile')]]")
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'Who you help')]/following-sibling::div[2]/label[text()[contains(.,'guinea pig')]]")
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'How you help')]/following-sibling::div[1]/label[text()[contains(.,'iguana')]]")
    expect(rendered).to have_xpath("//div[contains(@class, 'category_type')]/child::*[1][contains(., 'How you help')]/following-sibling::div[2]/label[text()[contains(.,'rabbit')]]")
  end

  it 'should have categories associated with organisation checked' do
    [@category1.name, @category3.name].each do |category|
      expect(rendered).to have_xpath("//div/label[text()[contains(.,'#{category}')]]/input[2][@checked='checked']")
    end
    [@category2.name, @category4.name,@category5.name,@category6.name].each do |category|
      expect(rendered).not_to have_xpath("//div/label[text()[contains(.,'#{category}')]]/input[2][@checked='checked']")
    end
  end
end


text:
from rest_framework.filters import BaseFilterBackend
from users.models import MemberInfo

class UserFilter(BaseFilterBackend):

    def filter_queryset(self, request, queryset, view):
        q = request.query_params.get
        user = request.user
        query = queryset

        if q('listened'):
            query = query.filter(
                    listened_to__artist__name__iexact=q('listened')).distinct()
        return query


text:
package life.http;

import life.Account;
import life.Asset;
import life.LifeException;
import life.Trade;
import life.db.DbIterator;
import life.db.DbUtils;
import life.util.Convert;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;

import javax.servlet.http.HttpServletRequest;

public final class GetTrades extends APIServlet.APIRequestHandler {

    static final GetTrades instance = new GetTrades();

    private GetTrades() {
        super(new APITag[] {APITag.AE}, "asset", "account", "firstIndex", "lastIndex", "includeAssetInfo");
    }

    @Override
    JSONStreamAware processRequest(HttpServletRequest req) throws LifeException {

        String assetId = Convert.emptyToNull(req.getParameter("asset"));
        String accountId = Convert.emptyToNull(req.getParameter("account"));

        int firstIndex = ParameterParser.getFirstIndex(req);
        int lastIndex = ParameterParser.getLastIndex(req);
        boolean includeAssetInfo = !"false".equalsIgnoreCase(req.getParameter("includeAssetInfo"));

        JSONObject response = new JSONObject();
        JSONArray tradesData = new JSONArray();
        DbIterator<Trade> trades = null;
        try {
            if (accountId == null) {
                Asset asset = ParameterParser.getAsset(req);
                trades = asset.getTrades(firstIndex, lastIndex);
            } else if (assetId == null) {
                Account account = ParameterParser.getAccount(req);
                trades = account.getTrades(firstIndex, lastIndex);
            } else {
                Asset asset = ParameterParser.getAsset(req);
                Account account = ParameterParser.getAccount(req);
                trades = Trade.getAccountAssetTrades(account.getId(), asset.getId(), firstIndex, lastIndex);
            }
            while (trades.hasNext()) {
                tradesData.add(JSONData.trade(trades.next(), includeAssetInfo));
            }
        } finally {
            DbUtils.close(trades);
        }
        response.put("trades", tradesData);

        return response;
    }

    @Override
    boolean startDbTransaction() {
        return true;
    }

}


text:
export default class AppCtrl {
  constructor() {
    self.currentFilters = {}

    // Open Sidebar by default on bigger screens
    if (window.innerWidth > 900) this.toggleSidebar()

    // Apply default sorting
    const defaultOrder = window.config.sorting.default_order
    this.sortBy(defaultOrder, false)
  }

  toggleSidebar() {
    toggleClass('#sidebar', 'hidden')
  }

  toggleSorting() {
    toggleClass('.sorting-options', 'hidden')
  }

  filterBy(type) {
    const el = currentElement()
    self.currentFilters[el.name] = {
      element: el,
      type: type
    }

    addClass('article', 'hidden')
    if (type == 'tags') toggleClass(el, 'active')

    window.collection.forEach(item => {
      let show = true

      Object.values(self.currentFilters).forEach((filter) => {
        show = show && applyFilter(item, filter)
        if (!show) return
      })

      if (show) showItem(item)
    })

    insertHTML('#counter', findAll('article:not(.hidden)').length)
  }

  applyFilter(item, filter) {
    const el = filter.element
    const attribute = el.name
    let filterValue = el.value
    let itemValue = item[attribute]

    switch(filter.type) {
      case 'global_text':
        const itemContent = Object.values(item).filter(isString).join(' ')

        if (contains(stripTags(itemContent), filterValue))
          return true

        break;
      case 'text':
        if (contains(itemValue, filterValue))
          return true

        break;
      case 'select':
      case 'radio_buttons':
        if (filterValue == 'All' || filterValue == itemValue)
          return true

        break;
      case 'numeric_range':
        itemValue = item[attribute.replace(/_min$|_max$/, '')]
        filterValue = parseFloat(filterValue) || 0

        if (contains(attribute, '_min$') && itemValue >= filterValue)
          return true

        if (contains(attribute, '_max$') && itemValue <= filterValue)
          return true

        break;
      case 'date_range':
        itemValue = Date.parse(item[attribute.replace(/_min$|_max$/, '')])
        const filterDate = Date.parse(filterValue)

        if (contains(attribute, '_min$') && itemValue >= filterDate)
          return true

        if (contains(attribute, '_max$') && itemValue <= filterDate)
          return true

        break;
      case 'tags':
        let activeTags = Array.from(findAll('.tag.active')).map(tag => tag.value)

        if (itemValue && activeTags.every(tag => itemValue.includes(tag)))
          return true

        break;
      case 'boolean':
        if (filterValue == 'All')
          return true

        if (filterValue == 'true' && itemValue)
          return true

        if (filterValue == 'false' && !itemValue)
          return true

        break;
      default:
        return false
    }
  }

  sortBy(sorting, interactive = true) {
    const [attribute, direction] = sorting.split(' ')
    const container = find('.collection-container')
    const items = []

    findAll('article:not(.hidden)').forEach(itemDom => {
      let item = window.collection.find(item => item.dom_id == itemDom.id)
      items.push(item)
    })

    items.sort((a, b) => {
      if (direction == 'asc') {
        if (a[attribute] < b[attribute]) return -1
        if (a[attribute] > b[attribute]) return 1
        return 0
      } else {
        if (a[attribute] < b[attribute]) return 1
        if (a[attribute] > b[attribute]) return -1
        return 0
      }
    }).forEach(item => {
      container.appendChild(find(`#${item.dom_id}`))
    })

    removeClass('.sorting-options a', 'active')
    findAll('.sorting-options a').forEach(option => {
      if (option.innerText.toLowerCase() == sorting)
        addClass(option, 'active')
    })

    if (interactive) this.toggleSorting()
  }

  showItem(item) {
    removeClass(`#${item.dom_id}`, 'hidden')
  }

  isString(string) {
    if (typeof string === 'string' || string instanceof String)
      return true
  }

  contains(content, search) {
    const regexp = new RegExp(search, 'i')
    return regexp.test(content)
  }

  stripTags(string) {
    const parseHTML = new DOMParser().parseFromString(string, 'text/html')
    return parseHTML.body.textContent || ''
  }
}


text:
  </body>
  {% comment %}
    {% stylesheet pure/pure-min.css %}
    <!--[if lte IE 8]>
        {% stylesheet pure/grids-responsive-old-ie-min.css %}
    <![endif]-->
    <!--[if gt IE 8]><!-->
        {% stylesheet pure/grids-responsive-min.css %}
    <!--<![endif]-->
  {% endcomment %}

  <!-- Les scripts from third parties  -->
  {% javascript vendor %}
  <!-- Les scripts for my app -->
  {% javascript application %}

  {% if site.env == 'development' %}
    <!-- Only in development mode -->
    <script src="//localhost:35729/livereload.js"></script>
  {% else %}
    <!-- Les google analytics -->
    <script>
          (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
          function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
          e=o.createElement(i);r=o.getElementsByTagName(i)[0];
          e.src='//{{ site.ga_site }}/analytics.js';
          r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
          ga('create','{{ site.ga_analytics }}', 'auto');ga('send','pageview');
    </script>
  {% endif %}

</html>


text:
<?php

namespace Gifty;

/**
 * http://gifty.lt/ api service
 * @package Gifty
 * @author Tadas Juozapaitis <kasp3rito@gmail.com>
 */
class GiftyService
{
    private $apiEndpoint = 'http://gifty.lt/api/1.0/';
    private $customerKey;
    private $customerSecret;
    private $userId;
    private $testing = false;

    public function __construct($customerKey, $customerSecret, $userId)
    {
        $this
            ->setCustomerKey($customerKey)
            ->setCustomerSecret($customerSecret)
            ->setUserId($userId);
    }

    /**
     * @return string
     */
    public function getApiEndpoint()
    {
        return $this->apiEndpoint;
    }

    /**
     * @param string $apiEndpoint
     * @return $this
     */
    public function setApiEndpoint($apiEndpoint)
    {
        $this->apiEndpoint = $apiEndpoint;

        return $this;
    }

    /**
     * @return string
     */
    public function getCustomerKey()
    {
        return $this->customerKey;
    }

    /**
     * @param string $customerKey
     * @return $this
     */
    public function setCustomerKey($customerKey)
    {
        $this->customerKey = $customerKey;

        return $this;
    }

    /**
     * @return string
     */
    public function getCustomerSecret()
    {
        return $this->customerSecret;
    }

    /**
     * @param string $customerSecret
     * @return $this
     */
    public function setCustomerSecret($customerSecret)
    {
        $this->customerSecret = $customerSecret;

        return $this;
    }

    /**
     * @return string
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * @param string $userId
     * @return $this
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;

        return $this;
    }

    /**
     * @return boolean
     */
    public function isTesting()
    {
        return $this->testing;
    }

    /**
     * @param boolean $testing
     * @return $this
     */
    public function setTesting($testing)
    {
        $this->testing = $testing;

        return $this;
    }

    /**
     * @param int $productId
     * @return string
     */
    protected function generateSignature($productId)
    {
        return md5($this->getCustomerSecret() . $this->getCustomerKey() . $productId);
    }

    /**
     * @param string $method
     * @param array $parameters
     * @throws \Exception
     * @return Response
     */
    protected function callApi($method, array $parameters)
    {
        $parameters['user_id'] = $this->getUserId();
        $parameters['customer_key'] = $this->getCustomerKey();
        $parameters['signature'] = $this->generateSignature($parameters['product_id']);
        if ($this->isTesting()) {
            $parameters['testing'] = 1;
        }

        $response = file_get_contents($this->getApiEndpoint() . $method . '?' . http_build_query($parameters));
        if (false === $response) {
            throw new \Exception("Can't read from api endpoint");
        }

        return new Response($response);
    }

    /**
     * @param string $productId
     * @param string $templateId
     * @param string $recipient phone number (+370...) or email
     * @return Response
     */
    public function createGift($productId, $templateId, $recipient = null)
    {
        $parameters = [
            'product_id' => $productId,
            'template_id' => $templateId
        ];

        if (null !== $recipient) {
            $parameters['recipient'] = $recipient;
        }

        return $this->callApi('customers.create_gift', $parameters);
    }
}


text:
<?php
/**
 * The basic frontend class for the GA plugin, extendable for the children
 */

if ( ! class_exists( 'Yoast_GA_Frontend' ) ) {

	class Yoast_GA_Frontend extends Yoast_GA_Options {

		/**
		 * Class constructor
		 */
		public function __construct() {
			parent::__construct();

			if ( isset( $this->options['tag_links_in_rss'] ) && $this->options['tag_links_in_rss'] == 1 ) {
				add_filter( 'the_permalink_rss', array( $this, 'rsslinktagger' ), 99 );
			}

			// Check if the customer is running Universal or not (Enable in GA Settings -> Universal)
			if ( isset( $this->options['enable_universal'] ) && $this->options['enable_universal'] == 1 ) {
				require_once 'class-universal.php';
			} else {
				require_once 'class-ga-js.php';
			}
		}

		/**
		 * Check if we need to show an actual tracking code
		 *
		 * @return bool
		 */
		public function do_tracking() {
			global $current_user;

			get_currentuserinfo();

			if ( 0 == $current_user->ID ) {
				return true;
			}

			if ( isset( $this->options['ignore_users'] ) ) {
				if ( in_array( $current_user->roles[0], $this->options['ignore_users'] ) ) {
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		}

		/**
		 * Parse the domain
		 *
		 * @param $uri
		 *
		 * @return array|bool
		 */
		public function yoast_ga_get_domain( $uri ) {
			$hostPattern     = '/^(https?:\/\/)?([^\/]+)/i';
			$domainPatternUS = '/[^\.\/]+\.[^\.\/]+$/';
			$domainPatternUK = '/[^\.\/]+\.[^\.\/]+\.[^\.\/]+$/';

			$matching = preg_match( $hostPattern, $uri, $matches );
			if ( $matching ) {
				$host = $matches[2];
				if ( preg_match( '/.*\..*\..*\..*$/', $host ) ) {
					preg_match( $domainPatternUK, $host, $matches );
				} else {
					preg_match( $domainPatternUS, $host, $matches );
				}

				if ( isset( $matches[0] ) ) {
					return array( 'domain' => $matches[0], 'host' => $host );
				} else {
					return false;
				}
			} else {
				return false;
			}
		}

		/**
		 * Add the UTM source parameters in the RSS feeds to track traffic
		 *
		 * @param string $guid
		 *
		 * @return string
		 */
		public function rsslinktagger( $guid ) {
			global $post;
			if ( is_feed() ) {
				if ( $this->options['allow_anchor'] ) {
					$delimiter = '#';
				} else {
					$delimiter = '?';
					if ( strpos( $guid, $delimiter ) > 0 ) {
						$delimiter = '&';
					}
				}

				return $guid . $delimiter . 'utm_source=rss&utm_medium=rss&utm_campaign=' . urlencode( $post->post_name );
			}

			return $guid;
		}

		/**
		 * Return the target with a lot of parameters
		 *
		 * @param string $category
		 * @param array  $matches
		 *
		 * @return array
		 */
		public function get_target( $category, $matches ) {
			$protocol            = $matches[2];
			$original_url        = $matches[3];
			$domain              = $this->yoast_ga_get_domain( $matches[3] );
			$origin              = $this->yoast_ga_get_domain( $_SERVER['HTTP_HOST'] );
			$download_extensions = explode( ',', str_replace( '.', '', $this->options['extensions_of_files'] ) );
			$extension           = substr( strrchr( $original_url, '.' ), 1 );

			// Break out immediately if the link is not an http or https link.
			$type = null;
			if ( $protocol !== 'http' && $protocol !== 'https' && $protocol !== 'mailto' ) {
				$type = null;
			} else {
				if ( ( $protocol == 'mailto' ) ) {
					$type = 'email';
				} elseif ( in_array( $extension, $download_extensions ) ) {
					$type = 'download';
				} else {
					if ( $domain['domain'] == $origin['domain'] ) {
						$out_links = explode( ',', $this->options['track_internal_as_outbound'] );

						if ( count( $out_links ) >= 1 ) {
							foreach ( $out_links as $out ) {
								if ( ! empty( $original_url ) && ! empty( $domain['domain'] ) ) {
									if ( strpos( $original_url, $domain['domain'] . $out ) !== false ) {
										$type = 'internal-as-outbound';
									}
								}
							}
						}

						if ( ! isset( $type ) ) {
							$type = 'internal';
						}
					} elseif ( $domain['domain'] != $origin['domain'] ) {
						$type = 'outbound';
					}
				}
			}

			return array(
				'category'        => $category,
				'type'            => $type,
				'protocol'        => $protocol,
				'domain'          => $domain['domain'],
				'host'            => $domain['host'],
				'origin_domain'   => $origin['domain'],
				'origin_host'     => $origin['host'],
				'extension'       => $extension,
				'link_attributes' => rtrim( $matches[1] . ' ' . $matches[4] ),
				'link_text'       => $matches[5],
				'original_url'    => $original_url,
			);
		}

		/**
		 * Merge the existing onclick with a new one and append it
		 *
		 * @param string $link_attribute
		 * @param string $onclick
		 *
		 * @return string
		 */
		public function output_add_onclick( $link_attribute, $onclick ) {
			if ( preg_match( '/onclick=[\'\"](.*?;)[\'\"]/i', $link_attribute, $matches ) > 0 ) {
				$js_snippet_single = 'onclick=\'' . $matches[1] . ' ' . $onclick . '\'';
				$js_snippet_double = 'onclick="' . $matches[1] . ' ' . $onclick . '"';

				$link_attribute = str_replace( 'onclick="' . $matches[1] . '"', $js_snippet_double, $link_attribute );
				$link_attribute = str_replace( "onclick='" . $matches[1] . "'", $js_snippet_single, $link_attribute );

				return $link_attribute;
			} else {
				if ( ! is_null( $onclick ) ) {
					return 'onclick="' . $onclick . '" ' . $link_attribute;
				} else {
					return $link_attribute;
				}
			}
		}

		/**
		 * Generate the full URL
		 *
		 * @param string $link
		 *
		 * @return string
		 */
		public function make_full_url( $link ) {
			switch ( $link['type'] ) {
				case 'download':
				case 'internal':
				case 'internal-as-outbound':
				case 'outbound':
					return $link['protocol'] . '://' . $link['original_url'];
					break;
				case 'email':
					return 'mailto:' . $link['original_url'];
					break;
			}
		}
	}

	global $yoast_ga_frontend;
	$yoast_ga_frontend = new Yoast_GA_Frontend;
}


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala
package collection
package mutable

import generic._
import scala.collection.immutable.{List, Nil}
import scala.collection.Iterator
import scala.annotation.migration

/** Factory object for the `mutable.Stack` class.
 *
 *  $factoryInfo
 *  @define coll mutable stack
 *  @define Coll `mutable.Stack`
 */
object Stack extends SeqFactory[Stack] {
  class StackBuilder[A] extends Builder[A, Stack[A]] {
    val lbuff = new ListBuffer[A]
    def +=(elem: A) = { lbuff += elem; this }
    def clear() = lbuff.clear()
    def result = new Stack(lbuff.result)
  }

  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Stack[A]] = ReusableCBF.asInstanceOf[GenericCanBuildFrom[A]]
  def newBuilder[A]: Builder[A, Stack[A]] = new StackBuilder[A]
  val empty: Stack[Nothing] = new Stack(Nil)
}

/** A stack implements a data structure which allows to store and retrieve
 *  objects in a last-in-first-out (LIFO) fashion.
 *
 *  @tparam A    type of the elements contained in this stack.
 *
 *  @author  Matthias Zenger
 *  @author  Martin Odersky
 *  @version 2.8
 *  @since   1
 *  @see [[http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html#stacks "Scala's Collection Library overview"]]
 *  section on `Stacks` for more information.
 *  @define Coll `Stack`
 *  @define coll stack
 *  @define orderDependent
 *  @define orderDependentFold
 *  @define mayNotTerminateInf
 *  @define willNotTerminateInf
 */
@deprecated("Stack is an inelegant and potentially poorly-performing wrapper around List. Use a List assigned to a var instead.", "2.12.0")
class Stack[A] private (var elems: List[A])
extends AbstractSeq[A]
   with Seq[A]
   with SeqLike[A, Stack[A]]
   with GenericTraversableTemplate[A, Stack]
   with Cloneable[Stack[A]]
   with Serializable
{
  def this() = this(Nil)

  override def companion = Stack

  /** Checks if the stack is empty.
   *
   *  @return true, iff there is no element on the stack
   */
  override def isEmpty: Boolean = elems.isEmpty

  /** The number of elements in the stack */
  override def length = elems.length

  /** Retrieve `n`-th element from stack, where top of stack has index `0`.
   *
   *  This is a linear time operation.
   *
   *  @param index     the index of the element to return
   *  @return          the element at the specified index
   *  @throws IndexOutOfBoundsException if the index is out of bounds
   */
  override def apply(index: Int) = elems(index)

  /** Replace element at index `n` with the new element `newelem`.
   *
   *  This is a linear time operation.
   *
   *  @param n       the index of the element to replace.
   *  @param newelem the new element.
   *  @throws   IndexOutOfBoundsException if the index is not valid
   */
  def update(n: Int, newelem: A) =
    if(n < 0 || n >= length) throw new IndexOutOfBoundsException(n.toString)
    else elems = elems.take(n) ++ (newelem :: elems.drop(n+1))

  /** Push an element on the stack.
   *
   *  @param   elem       the element to push on the stack.
   *  @return the stack with the new element on top.
   */
  def push(elem: A): this.type = { elems = elem :: elems; this }

  /** Push two or more elements onto the stack. The last element
   *  of the sequence will be on top of the new stack.
   *
   *  @param   elems      the element sequence.
   *  @return the stack with the new elements on top.
   */
  def push(elem1: A, elem2: A, elems: A*): this.type =
    this.push(elem1).push(elem2).pushAll(elems)

  /** Push all elements in the given traversable object onto the stack. The
   *  last element in the traversable object will be on top of the new stack.
   *
   *  @param xs the traversable object.
   *  @return the stack with the new elements on top.
   */
  def pushAll(xs: TraversableOnce[A]): this.type = { xs foreach push ; this }

  /** Returns the top element of the stack. This method will not remove
   *  the element from the stack. An error is signaled if there is no
   *  element on the stack.
   *
   *  @throws java.util.NoSuchElementException
   *  @return the top element
   */
  def top: A =
    elems.head

  /** Removes the top element from the stack.
   *
   *  @throws java.util.NoSuchElementException
   *  @return the top element
   */
  def pop(): A = {
    val res = elems.head
    elems = elems.tail
    res
  }

  /**
   * Removes all elements from the stack. After this operation completed,
   * the stack will be empty.
   */
  def clear(): Unit = elems = Nil

  /** Returns an iterator over all elements on the stack. This iterator
   *  is stable with respect to state changes in the stack object; i.e.
   *  such changes will not be reflected in the iterator. The iterator
   *  issues elements in the reversed order they were inserted into the
   *  stack (LIFO order).
   *
   *  @return an iterator over all stack elements.
   */
  @migration("`iterator` traverses in FIFO order.", "2.8.0")
  override def iterator: Iterator[A] = elems.iterator

  /** Creates a list of all stack elements in LIFO order.
   *
   *  @return the created list.
   */
  @migration("`toList` traverses in FIFO order.", "2.8.0")
  override def toList: List[A] = elems

  @migration("`foreach` traverses in FIFO order.", "2.8.0")
  override def foreach[U](f: A => U): Unit = super.foreach(f)

  /** This method clones the stack.
   *
   *  @return  a stack with the same elements.
   */
  override def clone(): Stack[A] = new Stack[A](elems)
}


text:
using System;

namespace LudumDare24.Views.Tweens.Easings
{
    public class DiscreteEasing : IEasing
    {
        public float Ease(
            float startingValue,
            float targetValue,
            TimeSpan targetRunTime,
            TimeSpan elapsedTime)
        {
            return elapsedTime < targetRunTime ? startingValue : targetValue;
        }
    }
}


text:
package org.apache.flink.core.fs;

import org.junit.Test;

import java.io.IOException;
import java.net.URI;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/** Tests for the {@link Path} class. */
public class PathTest {

    @Test
    public void testPathFromString() {

        Path p = new Path("/my/path");
        assertEquals("/my/path", p.toUri().getPath());
        assertNull(p.toUri().getScheme());

        p = new Path("/my/path/");
        assertEquals("/my/path", p.toUri().getPath());
        assertNull(p.toUri().getScheme());

        p = new Path("/my//path/");
        assertEquals("/my/path", p.toUri().getPath());
        assertNull(p.toUri().getScheme());

        p = new Path("/my//path//a///");
        assertEquals("/my/path/a", p.toUri().getPath());
        assertNull(p.toUri().getScheme());

        p = new Path("\\my\\path\\\\a\\\\\\");
        assertEquals("/my/path/a", p.toUri().getPath());
        assertNull(p.toUri().getScheme());

        p = new Path("hdfs:///my/path");
        assertEquals("/my/path", p.toUri().getPath());
        assertEquals("hdfs", p.toUri().getScheme());

        p = new Path("hdfs:///my/path/");
        assertEquals("/my/path", p.toUri().getPath());
        assertEquals("hdfs", p.toUri().getScheme());

        p = new Path("file:///my/path");
        assertEquals("/my/path", p.toUri().getPath());
        assertEquals("file", p.toUri().getScheme());

        p = new Path("C:/my/windows/path");
        assertEquals("/C:/my/windows/path", p.toUri().getPath());

        p = new Path("file:/C:/my/windows/path");
        assertEquals("/C:/my/windows/path", p.toUri().getPath());

        try {
            new Path((String) null);
            fail();
        } catch (Exception e) {
            // exception expected
        }

        try {
            new Path("");
            fail();
        } catch (Exception e) {
            // exception expected
        }
    }

    @Test
    public void testIsAbsolute() {

        // UNIX

        Path p = new Path("/my/abs/path");
        assertTrue(p.isAbsolute());

        p = new Path("/");
        assertTrue(p.isAbsolute());

        p = new Path("./my/rel/path");
        assertFalse(p.isAbsolute());

        p = new Path("my/rel/path");
        assertFalse(p.isAbsolute());

        // WINDOWS

        p = new Path("C:/my/abs/windows/path");
        assertTrue(p.isAbsolute());

        p = new Path("y:/my/abs/windows/path");
        assertTrue(p.isAbsolute());

        p = new Path("/y:/my/abs/windows/path");
        assertTrue(p.isAbsolute());

        p = new Path("b:\\my\\abs\\windows\\path");
        assertTrue(p.isAbsolute());

        p = new Path("/c:/my/dir");
        assertTrue(p.isAbsolute());

        p = new Path("/C:/");
        assertTrue(p.isAbsolute());

        p = new Path("C:");
        assertFalse(p.isAbsolute());

        p = new Path("C:/");
        assertTrue(p.isAbsolute());

        p = new Path("C:my\\relative\\path");
        assertFalse(p.isAbsolute());

        p = new Path("\\my\\dir");
        assertTrue(p.isAbsolute());

        p = new Path("\\");
        assertTrue(p.isAbsolute());

        p = new Path(".\\my\\relative\\path");
        assertFalse(p.isAbsolute());

        p = new Path("my\\relative\\path");
        assertFalse(p.isAbsolute());

        p = new Path("\\\\myServer\\myDir");
        assertTrue(p.isAbsolute());
    }

    @Test
    public void testGetName() {

        Path p = new Path("/my/fancy/path");
        assertEquals("path", p.getName());

        p = new Path("/my/fancy/path/");
        assertEquals("path", p.getName());

        p = new Path("hdfs:///my/path");
        assertEquals("path", p.getName());

        p = new Path("hdfs:///myPath/");
        assertEquals("myPath", p.getName());

        p = new Path("/");
        assertEquals("", p.getName());

        p = new Path("C:/my/windows/path");
        assertEquals("path", p.getName());

        p = new Path("file:/C:/my/windows/path");
        assertEquals("path", p.getName());
    }

    @Test
    public void testGetParent() {

        Path p = new Path("/my/fancy/path");
        assertEquals("/my/fancy", p.getParent().toUri().getPath());

        p = new Path("/my/other/fancy/path/");
        assertEquals("/my/other/fancy", p.getParent().toUri().getPath());

        p = new Path("hdfs:///my/path");
        assertEquals("/my", p.getParent().toUri().getPath());

        p = new Path("hdfs:///myPath/");
        assertEquals("/", p.getParent().toUri().getPath());

        p = new Path("/");
        assertNull(p.getParent());

        p = new Path("C:/my/windows/path");
        assertEquals("/C:/my/windows", p.getParent().toUri().getPath());
    }

    @Test
    public void testSuffix() {

        Path p = new Path("/my/path");
        p = p.suffix("_123");
        assertEquals("/my/path_123", p.toUri().getPath());

        p = new Path("/my/path/");
        p = p.suffix("/abc");
        assertEquals("/my/path/abc", p.toUri().getPath());

        p = new Path("C:/my/windows/path");
        p = p.suffix("/abc");
        assertEquals("/C:/my/windows/path/abc", p.toUri().getPath());
    }

    @Test
    public void testDepth() {

        Path p = new Path("/my/path");
        assertEquals(2, p.depth());

        p = new Path("/my/fancy/path/");
        assertEquals(3, p.depth());

        p = new Path("/my/fancy/fancy/fancy/fancy/fancy/fancy/fancy/fancy/fancy/fancy/path");
        assertEquals(12, p.depth());

        p = new Path("/");
        assertEquals(0, p.depth());

        p = new Path("C:/my/windows/path");
        assertEquals(4, p.depth());
    }

    @Test
    public void testParsing() {
        URI u;
        String scheme = "hdfs";
        String authority = "localhost:8000";
        String path = "/test/test";

        // correct usage
        // hdfs://localhost:8000/test/test
        u = new Path(scheme + "://" + authority + path).toUri();
        assertEquals(scheme, u.getScheme());
        assertEquals(authority, u.getAuthority());
        assertEquals(path, u.getPath());
        // hdfs:///test/test
        u = new Path(scheme + "://" + path).toUri();
        assertEquals(scheme, u.getScheme());
        assertEquals(null, u.getAuthority());
        assertEquals(path, u.getPath());
        // hdfs:/test/test
        u = new Path(scheme + ":" + path).toUri();
        assertEquals(scheme, u.getScheme());
        assertEquals(null, u.getAuthority());
        assertEquals(path, u.getPath());

        // incorrect usage
        // hdfs://test/test
        u = new Path(scheme + ":/" + path).toUri();
        assertEquals(scheme, u.getScheme());
        assertEquals("test", u.getAuthority());
        assertEquals("/test", u.getPath());
        // hdfs:////test/test
        u = new Path(scheme + ":///" + path).toUri();
        assertEquals("hdfs", u.getScheme());
        assertEquals(null, u.getAuthority());
        assertEquals(path, u.getPath());
    }

    @Test
    public void testMakeQualified() throws IOException {
        // make relative path qualified
        String path = "test/test";
        Path p = new Path(path).makeQualified(FileSystem.getLocalFileSystem());
        URI u = p.toUri();

        assertEquals("file", u.getScheme());
        assertEquals(null, u.getAuthority());

        String q =
                new Path(FileSystem.getLocalFileSystem().getWorkingDirectory().getPath(), path)
                        .getPath();
        assertEquals(q, u.getPath());

        // make absolute path qualified
        path = "/test/test";
        p = new Path(path).makeQualified(FileSystem.getLocalFileSystem());
        u = p.toUri();
        assertEquals("file", u.getScheme());
        assertEquals(null, u.getAuthority());
        assertEquals(path, u.getPath());
    }
}


text:
from rest_framework.serializers import ModelSerializer, StringRelatedField, PrimaryKeyRelatedField,\
    SlugRelatedField, HyperlinkedIdentityField
from rest_framework import serializers

from api.models.student_models import Student, StudentSubjectGrade

class StudentSerializer(ModelSerializer):

    class Meta:
        model = Student
        fields = ('identifier', 'gender', 'aggregate_score', 'graduation_year', 'division', 'school')

class StudentSubjectGradeSerializer(ModelSerializer):
    student = StringRelatedField()
    subject = StringRelatedField()
    grade = StringRelatedField()

    class Meta:
        model = StudentSubjectGrade
        fields = ('student', 'subject', 'grade')

class SchoolStudentSerializer(ModelSerializer):
    school = StringRelatedField()

    class Meta:
        model = Student
        fields = ('school', 'graduation_year', 'gender', 'division', 'aggregate_score')


text:
layout: page
title: Forest Networks Trade Fair
date: 2016-05-24
author: Jeremy Lara
tags: weekly links, java
status: published
summary: Praesent fringilla, leo sed ullamcorper cursus, est arcu consequat.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 08/29/2018
  endDate: 08/31/2018
  ctyhocn: MIASTHX
  groupCode: FNTF
published: true
---
Nulla quis scelerisque nunc. Donec iaculis ut lorem eu hendrerit. Phasellus ac consectetur mauris. Fusce dictum nisl venenatis massa tempor ullamcorper. Nulla facilisi. Curabitur posuere eleifend lacus, in porttitor turpis fringilla eget. Mauris vel eros erat. In consectetur commodo facilisis. In hac habitasse platea dictumst. Duis ut dolor ipsum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tincidunt congue ex, sed molestie velit cursus non. Duis volutpat, augue sagittis venenatis imperdiet, orci mi egestas magna, scelerisque tempor elit eros quis felis. Morbi congue nisl a eros suscipit, vitae convallis urna aliquet. Sed ut lectus dictum, sodales eros quis, feugiat metus. Phasellus eu dictum augue. Nam vulputate risus metus, quis aliquam arcu congue vel. Donec nec iaculis risus, sit amet cursus velit. Curabitur eleifend sapien purus, ut tristique diam blandit in. In sit amet erat eget arcu laoreet iaculis a in velit. Proin ac cursus orci. Sed sodales augue id arcu lobortis elementum.

* Cras egestas massa porttitor, facilisis nunc ac, luctus odio
* Mauris dignissim est vel dignissim accumsan
* Maecenas id enim vel nisl laoreet sollicitudin ut vitae arcu
* Nullam eu arcu dignissim, dapibus turpis consectetur, ultrices nisl
* Ut rutrum justo quis accumsan vulputate
* Duis vulputate urna nec diam tincidunt, in porttitor risus accumsan.

Quisque gravida sed quam volutpat pharetra. Donec orci orci, feugiat nec pretium non, laoreet a est. Donec facilisis condimentum leo, vitae maximus ipsum aliquam a. Nullam euismod, eros et efficitur ullamcorper, ante lorem egestas nunc, vestibulum posuere dui erat vitae neque. Phasellus id ultrices odio. Aenean lacinia pharetra ultrices. Donec ultricies, lacus non viverra tempus, eros lectus rutrum erat, id pulvinar diam leo nec tellus. Donec lacinia, sem nec pharetra tempor, quam neque tempor mauris, sed bibendum eros nisi et felis. Maecenas orci dui, congue vel velit non, maximus efficitur nulla. Nunc tempus ullamcorper condimentum. Praesent leo arcu, mattis at cursus ut, sagittis pretium metus. Fusce placerat odio dolor, at tincidunt nisi egestas in.


text:
layout: page
title: Peak Basic Llc. Conference
date: 2016-05-24
author: Dylan Fischer
tags: weekly links, java
status: published
summary: Vivamus non egestas felis. Suspendisse sed tincidunt enim. Suspendisse vitae.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/02/2019
  endDate: 01/06/2019
  ctyhocn: BGNOHHX
  groupCode: PBLC
published: true
---
Integer eget venenatis sem, vitae eleifend orci. Quisque non porta leo. Donec non mi semper arcu imperdiet maximus vitae sit amet lectus. Donec quis nibh sed lacus euismod tempus eu in arcu. Maecenas aliquam varius feugiat. Donec varius mauris at ex rhoncus accumsan. Nunc sed quam quis turpis facilisis facilisis at ut arcu. Aliquam nec maximus ligula. Donec purus sem, dapibus vel lacus non, fringilla sagittis lorem. Integer dictum nec enim eu convallis.

1 Cras imperdiet nunc vitae sollicitudin cursus
1 Nullam fringilla ipsum ac lorem euismod, gravida iaculis mauris auctor
1 Duis ornare odio vestibulum nunc luctus blandit
1 Donec commodo felis ac est vehicula, quis rutrum mi pellentesque
1 Nam ut mi et ante commodo tempus ut eget lectus.

Sed at metus orci. Maecenas eleifend finibus blandit. Duis sed odio a purus molestie tempus et non dui. Aliquam posuere ante nunc, eget dictum ex mollis convallis. Nulla porttitor imperdiet quam ac congue. Donec vitae elit quis urna placerat feugiat. Morbi cursus tincidunt velit. Pellentesque blandit posuere ipsum. Praesent commodo mi sed ante porta, non sagittis nisi ultrices. Praesent bibendum lorem non porta rutrum. Cras elementum enim aliquam, varius massa quis, tincidunt nunc.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean sit amet mi sapien. Nulla vehicula vehicula tellus, eget lobortis nisl. Nulla pretium vel felis id finibus. Suspendisse vestibulum efficitur pulvinar. Duis eu luctus velit. Pellentesque imperdiet lacus lorem, ut viverra mauris mollis at. Suspendisse facilisis in nisi ac lacinia. Vivamus vel ornare eros, quis aliquet arcu. Curabitur rhoncus est a vestibulum fermentum. Quisque tristique mi quis eleifend imperdiet. Sed bibendum pretium mauris, eu interdum nisi rhoncus facilisis.


text:
import json

from nose.tools import eq_, ok_

from django.core.files import File
from django.conf import settings

from funfactory.urlresolvers import reverse

from airmozilla.main.models import Event, Picture
from .base import ManageTestCase

class TestPictureGallery(ManageTestCase):

    other_image = 'airmozilla/manage/tests/other_logo.png'

    def test_load_gallery(self):
        url = reverse('manage:picturegallery')
        response = self.client.get(url)
        eq_(response.status_code, 200)

    def test_load_gallery_with_event(self):
        url = reverse('manage:picturegallery')
        event = Event.objects.get(title='Test event')
        response = self.client.get(url, {'event': event.id})
        eq_(response.status_code, 200)
        ok_(event.title in response.content)
        # the link to the upload should carry the event ID
        url = reverse('manage:picture_add') + '?event=%d' % event.id
        ok_(url in response.content)

    def test_picturegallery_data(self):
        url = reverse('manage:picturegallery_data')
        response = self.client.get(url)
        eq_(response.status_code, 200)
        eq_(response['Content-Type'], 'application/json')

        # it's no fun until you add some pictures
        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )
            picture2 = Picture.objects.create(
                file=File(fp),
                notes=""
            )
        response = self.client.get(url)
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        ok_(struct['urls'])
        p1, p2 = struct['pictures']
        # because it's sorted by 'created'
        ok_(p1['width'])
        ok_(p1['height'])
        ok_(p1['size'])
        eq_(p1['events'], [])
        eq_(p2['events'], [])
        assert p1['id'] == picture2.id
        assert p2['id'] == picture.id
        eq_(p2['notes'], 'Some notes')

        picture.notes = 'Other notes'
        picture.save()
        response = self.client.get(url)
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        eq_(struct['pictures'][1]['notes'], 'Other notes')
        eq_(struct['stats']['total_pictures'], 2)
        eq_(struct['stats']['event_pictures'], 0)

    def test_picturegallery_data_event_filtering(self):
        url = reverse('manage:picturegallery_data')
        event = Event.objects.get(title='Test event')
        with open(self.main_image) as fp:
            Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )
            Picture.objects.create(
                file=File(fp),
                notes="Other notes",
                event=event
            )
        response = self.client.get(url)
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        eq_(len(struct['pictures']), 1)
        p, = struct['pictures']
        eq_(p['notes'], 'Some notes')

        response = self.client.get(url, {'event': event.id})
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        eq_(len(struct['pictures']), 2)

        eq_(struct['stats']['total_pictures'], 2)
        eq_(struct['stats']['event_pictures'], 1)

    def test_picture_edit(self):
        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )

        url = reverse('manage:picture_edit', args=(picture.id,))
        response = self.client.get(url)
        eq_(response.status_code, 200)
        ok_('Some notes' in response.content)

        with open(self.other_image) as fp:
            response = self.client.post(url, {
                'file': fp,
                'notes': 'Other notes'
            })
            eq_(response.status_code, 302)

        picture = Picture.objects.get(id=picture.id)
        eq_(picture.notes, 'Other notes')

    def test_picture_edit_set_new_default_placeholder(self):
        with open(self.main_image) as fp:
            Picture.objects.create(
                file=File(fp),
                notes="Initial one",
                default_placeholder=True
            )

        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )

        url = reverse('manage:picture_edit', args=(picture.id,))
        with open(self.other_image) as fp:
            response = self.client.post(url, {
                'file': fp,
                'notes': 'Other notes',
                'default_placeholder': True,
            })
            eq_(response.status_code, 302)

        picture = Picture.objects.get(id=picture.id)
        eq_(picture.notes, 'Other notes')
        ok_(picture.default_placeholder)
        eq_(Picture.objects.filter(default_placeholder=True).count(), 1)

    def test_picture_delete(self):
        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )

        url = reverse('manage:picture_delete', args=(picture.id,))
        response = self.client.post(url)
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        eq_(struct, True)

    def test_picture_delete_all(self):
        event1 = Event.objects.get(title='Test event')
        with open(self.main_image) as fp:
            event2 = Event.objects.create(
                title='Second test',
                description='Anything goes',
                start_time=event1.start_time,
                archive_time=event1.archive_time,
                privacy=Event.PRIVACY_PUBLIC,
                status=event1.status,
                placeholder_img=event1.placeholder_img,
            )
            Picture.objects.create(
                file=File(fp),
                notes="Some notes",
                event=event2
            )
            picture2 = Picture.objects.create(
                file=File(fp),
                notes="Some other notes"
            )

        event2.picture = picture2

        # check button is present for placeholder + picture case
        url = reverse('manage:picturegallery')

        response = self.client.get(url, {'event': event2.id})
        eq_(response.status_code, 200)
        ok_("Remove all pictures" in response.content)

        # check delete works properly
        delete_url = reverse("manage:picture_delete_all", args=(event2.id,))

        response = self.client.post(delete_url, data={"event": event2.id})
        eq_(response.status_code, 200)
        eq_(Picture.objects.filter(event=event2).count(), 0)
        eq_(Picture.objects.all().count(), 1)

        # do not set a picture not associated with the event to None
        eq_(not event2.picture, False)

        # check correct response if no place holder
        event2.placeholder_img = None
        event2.save()
        response = self.client.get(url, {'event': event2.id})
        eq_(response.status_code, 200)
        ok_("Unable to delete all pictures" in response.content)

    def test_picture_delete_blocked(self):
        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )
        event = Event.objects.get(title='Test event')
        event.placeholder_img = None
        event.picture = picture
        event.save()

        url = reverse('manage:picture_delete', args=(picture.id,))
        response = self.client.post(url)
        eq_(response.status_code, 400)

    def test_picture_add(self):
        url = reverse('manage:picture_add')
        response = self.client.get(url)
        eq_(response.status_code, 200)

        with open(self.other_image) as fp:
            response = self.client.post(url, {
                'file': fp
            })

        picture, = Picture.objects.all()
        assert picture.width
        assert picture.height
        assert picture.size
        eq_(picture.modified_user, self.user)

    def test_picture_add_with_event(self):
        event = Event.objects.get(title='Test event')
        url = reverse('manage:event_edit', args=(event.id,))
        response = self.client.get(url, {'event': event.id})
        eq_(response.status_code, 200)
        ok_(event.title in response.content)

        url = reverse('manage:picture_add')
        response = self.client.get(url, {'event': event.id})
        eq_(response.status_code, 200)
        ok_('?event=%d' % event.id in response.content)

    def test_redirect_picture_thumbnail(self):
        with open(self.main_image) as fp:
            picture = Picture.objects.create(
                file=File(fp),
                notes="Some notes"
            )

        url = reverse('manage:redirect_picture_thumbnail', args=(picture.id,))
        response = self.client.get(url)
        eq_(response.status_code, 302)
        ok_(settings.MEDIA_URL in response['Location'])

    def test_picture_event_associate(self):
        with open(self.main_image) as fp:
            picture = Picture.objects.create(file=File(fp))

        url = reverse('manage:picture_event_associate', args=(picture.id,))
        response = self.client.post(url)
        eq_(response.status_code, 400)
        response = self.client.post(url, {'event': 9999})
        eq_(response.status_code, 404)

        event = Event.objects.get(title='Test event')
        response = self.client.post(url, {'event': event.id})
        eq_(response.status_code, 200)
        struct = json.loads(response.content)
        eq_(struct, True)


text:
package ca.waterloo.dsg.graphflow.query.operator.filter;

import ca.waterloo.dsg.graphflow.graph.TypeAndPropertyKeyStore;
import ca.waterloo.dsg.graphflow.query.operator.descriptor.EdgeOrVertexPropertyDescriptor;
import ca.waterloo.dsg.graphflow.query.result.MatchQueryOutput;
import ca.waterloo.dsg.graphflow.query.structuredquery.ComparisonPredicate;
import ca.waterloo.dsg.graphflow.query.structuredquery.InClausePredicate;
import ca.waterloo.dsg.graphflow.query.structuredquery.QueryPredicate;
import ca.waterloo.dsg.graphflow.util.datatype.DataType;
import ca.waterloo.dsg.graphflow.util.datatype.RuntimeComparator;
import ca.waterloo.dsg.graphflow.util.datatype.RuntimeComparator.ComparisonOperator;
import org.antlr.v4.runtime.misc.Pair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * Contains static methods for creating {@link Predicate} objects that are used by {@link Filter}.
 */
public class PredicateFactory {

    /**
     * Returns a {@link Predicate<String[]>} which combines a list of {@link QueryPredicate}s
     *
     * @param queryPredicates a list of  {@link QueryPredicate}s which are to be converted to a
     * {@link Predicate<String[]>}
     * @param descriptorIndexMap a map of variables to their index in the
     * property result set created by the {@link Filter} operator. {@link Filter} uses its {@link
     * EdgeOrVertexPropertyDescriptor} list to create the property result set from the {@link
     * MatchQueryOutput}.
     * @return a {@link Predicate<String[]>} instance that will perform the comparisons specified
     * in the {@code queryPredicates}.
     */
    public static Predicate<String[]> getFilterPredicate(List<QueryPredicate> queryPredicates,
        Map<String, Integer> descriptorIndexMap) {
        Predicate<String[]> result = null;
        for (QueryPredicate queryPredicate : queryPredicates) {
            Predicate<String[]> predicate;
            switch (queryPredicate.getPredicateType()) {
                case IN_CLAUSE_ONLY_LITERALS:
                case IN_CLAUSE_VARIABLES_AND_LITERALS:
                    predicate = getInClausePredicate((InClausePredicate) queryPredicate,
                    descriptorIndexMap);
                    break;
                case COMPARATIVE_CLAUSE_TWO_PROPERTY_KEY_OPERANDS:
                case COMPARATIVE_CLAUSE_PROPERTY_KEY_AND_LITERAL_OPERANDS:
                     predicate = getComparativeClausePredicate((ComparisonPredicate) queryPredicate,
                        descriptorIndexMap);
                     break;
                default:
                    // Should never execute. Every predicate type introduced should be supported.
                    throw new IllegalArgumentException("The predicate type " + queryPredicate.
                        getPredicateType().name() + " is not supported.");
            }
            if (null == result) {
                result = predicate;
            } else {
                result = result.and(predicate);
            }
        }
        return result;
    }

    private static Predicate<String[]> getInClausePredicate(InClausePredicate inClause,
        Map<String, Integer> descriptorIndexMap) {
        Pair<String, String> leftOperand = inClause.getLeftOperand();
        DataType dataType = TypeAndPropertyKeyStore.getInstance().
            getPropertyDataType(leftOperand.b);

        int leftOperandIndexInPropertyResults = descriptorIndexMap.get(leftOperand.a + '.' +
            leftOperand.b);

        List<Integer> rightOperandsIndexInPropertyResults = new ArrayList<>();
        for (Pair<String, String> variable : inClause.getVariablesWithProperty()) {
            rightOperandsIndexInPropertyResults.add(descriptorIndexMap.get(variable.a + '.' +
                variable.b));
        }
        return (String[] predicate) -> {
            for (String literal : inClause.getLiterals()) {
                if (RuntimeComparator.resolveTypesAndCompare(DataType.parseDataType(dataType,
                    predicate[leftOperandIndexInPropertyResults]), DataType.parseDataType(dataType,
                    literal), ComparisonOperator.EQUALS)) {
                    return true;
                }
            }
            for (int indexInPropertyResults : rightOperandsIndexInPropertyResults) {
                if (RuntimeComparator.resolveTypesAndCompare(DataType.parseDataType(dataType,
                    predicate[leftOperandIndexInPropertyResults]), DataType.parseDataType(dataType,
                    predicate[indexInPropertyResults]), ComparisonOperator.EQUALS)) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Predicate<String[]> getComparativeClausePredicate(
        ComparisonPredicate comparisonPredicate, Map<String, Integer> descriptorIndexMap) {
        DataType dataType = getDataTypeToCastOperandsTo(comparisonPredicate);
        ComparisonOperator operator = comparisonPredicate.getComparisonOperator();
        Pair<String, String> leftOperand = comparisonPredicate.getLeftOperand();
        Pair<String, String> rightOperand = comparisonPredicate.getRightOperand();
        String literal = comparisonPredicate.getLiteral();

        int variable1IndexInPropertyResults = descriptorIndexMap.get(leftOperand.a + '.' +
            leftOperand.b);
        int variable2IndexInPropertyResults = (null != rightOperand) ? descriptorIndexMap.get(
            rightOperand.a + '.' + rightOperand.b) : -1;

        return (String[] predicate) -> {
            String rvalue = (variable2IndexInPropertyResults == -1) ? literal : predicate[
                variable2IndexInPropertyResults];
            return RuntimeComparator.resolveTypesAndCompare(DataType.parseDataType(dataType,
                predicate[variable1IndexInPropertyResults]), DataType.parseDataType(dataType,
                rvalue), operator);
        };
    }

    private static DataType getDataTypeToCastOperandsTo(ComparisonPredicate predicate) {
        DataType leftOperandDataType = TypeAndPropertyKeyStore.getInstance().getPropertyDataType(
            predicate.getLeftOperand().b);
        if (DataType.BOOLEAN == leftOperandDataType || DataType.STRING == leftOperandDataType ||
            DataType.DOUBLE == leftOperandDataType) {
            return leftOperandDataType;
        }

        DataType rightOperandDataType = DataType.INT;
        if (null != predicate.getRightOperand()) {
            rightOperandDataType = TypeAndPropertyKeyStore.getInstance().getPropertyDataType(
                predicate.getRightOperand().b);
        } else if (predicate.getLiteral().contains(".")) {
            // The numerical literal was written as a floating-point.
            rightOperandDataType = DataType.DOUBLE;
        }
        return rightOperandDataType;
    }
}


text:
package jsonconfig

import (
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

// Parser must implement ParseJSON
type Parser interface {
	ParseJSON([]byte) error
}

// Load the JSON config file
func Load(configFile string, p Parser) {
	var err error
	var absPath string
	var input = io.ReadCloser(os.Stdin)
	if absPath, err = filepath.Abs(configFile); err != nil {
		log.Fatalln(err)
	}

	if input, err = os.Open(absPath); err != nil {
		log.Fatalln(err)
	}

	// Read the config file
	jsonBytes, err := ioutil.ReadAll(input)
	input.Close()
	if err != nil {
		log.Fatalln(err)
	}

	// Parse the config
	if err := p.ParseJSON(jsonBytes); err != nil {
		log.Fatalln("Could not parse %q: %v", configFile, err)
	}
}


text:
package it.bob.apps.android.cultactive.beans.operas;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;
import it.bob.apps.android.cultactive.utils.CAConstants;

import java.util.Collection;

/**
 * Created by roberto on 16/06/15.
 */
@DatabaseTable( tableName = CAConstants.DB_TABLE_NAME_OPERA_MUSIC_ALBUMS)
public class BeanOperaMusicAlbum extends BeanOpera
{

    @DatabaseField(columnName = CAConstants.DB_TABLE_COL_OPERA_MUSIC_ALBUM_TIME)
    private int time = CAConstants.DEFAULT_INT_VALUE;

    @DatabaseField(columnName = CAConstants.DB_TABLE_COL_OPERA_MUSIC_ALBUM_YEAR)
    private int year = CAConstants.DEFAULT_INT_VALUE;

    @DatabaseField(columnName = CAConstants.DB_TABLE_COL_OPERA_MUSIC_ALBUM_CATEGORY)
    private String category = CAConstants.DEFAULT_STRING_VALUE;

    @ForeignCollectionField
    private Collection<BeanOperaMusicSong> songs;

    /* ********************************************************************* */
    /*                             CONSTRUCTORS                              */
    /* ********************************************************************* */

    public BeanOperaMusicAlbum(String title, int rate, int time, int year, String category, Collection<BeanOperaMusicSong> songs)
    {
        super(title, CAConstants.OPERA_TYPES.OPERA_MUSIC_ALBUM, rate);
        this.setTime(time);
        this.setYear(year);
        this.setCategory(category);
        this.setSongs(songs);
    }

    /* ********************************************************************* */
    /*                       GETTER AND SETTER METHODS                       */
    /* ********************************************************************* */

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Collection<BeanOperaMusicSong> getSongs() {
        return songs;
    }

    public void setSongs(Collection<BeanOperaMusicSong> songs) {
        this.songs = songs;
    }

}


text:
do 'webalizer-lib.pl';

# is_installed(mode)
# For mode 1, returns 2 if the server is installed and configured for use by
# Webmin, 1 if installed but not configured, or 0 otherwise.
# For mode 0, returns 1 if installed, 0 if not
sub is_installed
{
return 0 if (!&has_command($config{'webalizer'}));
local $ver = &get_webalizer_version(\$dummy);
return 0 if (!$ver || $ver < 2);
return $_[0] ? 2 : 1;
}


text:
<Record>
<Term>Dibenzothiophene</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Miscellaneous Adjuvant</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Miscellaneous Adjuvant/Dibenzothiophene</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Dibenzothiophene</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Miscellaneous Adjuvant</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>2,2'-Biphenylylene Sulfide</Synonym>
<Synonym>DIBENZOTHIOPHENE</Synonym>
<Synonym>Dibenzo(b,d)thiophene</Synonym>
<Synonym>Dibenzothiophene</Synonym>
<Synonym>Diphenylene Sulfide</Synonym>
<Description>A sulfur-containing polycyclic aromatic hydrocarbon (PAH) derivate consisting of 3 fused rings with keratolytic activity. Dibenzothiophene is a component of petroleum oils.</Description>
<Source>NCI Thesaurus</Source>
</Record>


text:
package net.stargraph.core.impl.lucene;

import net.stargraph.core.search.SearchQueryHolder;
import net.stargraph.rank.ModifiableSearchParams;
import org.apache.lucene.search.Query;

import java.util.Objects;

public class LuceneQueryHolder implements SearchQueryHolder<Query> {
    private ModifiableSearchParams searchParams;
    private Query query;

    public LuceneQueryHolder(Query query, ModifiableSearchParams searchParams) {
        this.query = Objects.requireNonNull(query);
        this.searchParams = Objects.requireNonNull(searchParams);
    }

    @Override
    public Query getQuery() {
        return query;
    }

    public ModifiableSearchParams getSearchParams() {
        return searchParams;
    }
}


text:
/**
 * A resource which can later be freed by calling `dispose()`.
 */
export interface Disposable {
  dispose(): void;
}

/**
 * Function which represents a specific event which you can subscribe to.
 */
export interface Event<T> {
  (listener: (e: T) => any): Disposable;
}

/**
 * An event emitter which can be subscribe to to hear when this event is fired.
 */
export class EventEmitter<T> implements Disposable {

  private _listeners: ((t: T) => void)[] = [];

  /**
   * Dispose of and disconnect all listeners.
   */
  dispose(): void {
    this._listeners = [];
  }

  /**
   * Attach a listener to this event.
   *
   * @param listener the function to call when this event is triggered.
   * @return a `Disposable` which when used disconnects this listener from the event.
   */
  event: Event<T> = (listener: (t: T) => void): Disposable => {
    this._listeners.push(listener);
    return {
      dispose: () => {
        this._listeners = this._listeners.filter(item => item !== listener);
      }
    };
  };

  /**
   * Fire the event to all listeners.
   *
   * @param t the payload of the event.
   */
  fire(t: T): void {
    this._listeners.forEach(listener => listener(t));
  }

  /**
   * Returns true if this event emitter has at least on listener subscribed to it.
   *
   * @return true if this event emitter has at least on listener subscribed to it.
   */

  hasListeners(): boolean {
    return this._listeners.length !== 0;
  }
}


text:
package org.eulerdb.kernel;

import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.eulerdb.kernel.storage.EdbManager;
import org.eulerdb.kernel.storage.EdbStorage;
import org.eulerdb.kernel.storage.EdbStorage.storeType;

import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.ExceptionFactory;

public class EdbEdge implements Edge, Serializable {

	/**
	 *
	 */
	protected transient Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
	private static final long serialVersionUID = 1034618974276848252L;
	protected transient static List<String> sBlackList = Arrays.asList(new String[] { "id",
			"label" });
	protected String mFromVertex; // head/in
	protected String mToVertex; // tail/out
	protected String mRelation;
	protected String mId;
	protected String mOwner;
	protected transient EdbStorage mStorage = null;

	/**
	 * The EdbEdge constructor is invisible outside of the package. The only way to add Edge is via graph's addEdge function.
	 * @param owner
	 * @param id
	 */
	EdbEdge(String owner, Vertex n1, Vertex n2, Object id, String relation) {
		logger.debug("EdbEdge consturctor: from "+ n1.getId()+" to "+n2.getId()+" relation of "+ relation);
		mOwner = owner;
		mFromVertex = (String) n1.getId();
		mToVertex = (String) n2.getId();
		mRelation = relation;
		mId = n1.getId() + "_" + relation + "_" + n2.getId();// FIXME id is not
																// used here
		if (mStorage == null)
			mStorage = EdbManager.getDbInstance(mOwner);
		initSaving();
	}

	/**
	 * Re-Initialize transient variable after deserialization
	 * @param in
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private void readObject(java.io.ObjectInputStream in)
		    throws IOException, ClassNotFoundException {
		    in.defaultReadObject();

		    if(logger==null)
		    	logger = Logger.getLogger(this.getClass().getCanonicalName());

		    logger.debug("deserializing");

		    if(sBlackList==null)
		    	sBlackList = Arrays.asList(new String[] { "id","label" });

		    if (mStorage == null)
				mStorage = EdbManager.getDbInstance(mOwner);
		}

	@Override
	public Object getId() {
		return mId;
	}

	@Override
	public Object getProperty(String arg0) {
		logger.debug("getProperty of "+ arg0);
		@SuppressWarnings("unchecked")
		Map<String, Object> props = (Hashtable<String, Object>) mStorage
				.getObj(storeType.EDGEPROPERTY,
						mStorage.getTransaction(), mId);

		return props.get(arg0);
	}

	@Override
	public Set<String> getPropertyKeys() {
		@SuppressWarnings("unchecked")
		Map<String, Object> props = (Hashtable<String, Object>) mStorage
				.getObj(storeType.EDGEPROPERTY,
						mStorage.getTransaction(), mId);

		return props.keySet();
	}

	@Override
	public Object removeProperty(String arg0) {
		logger.debug("remove property "+ arg0);
		@SuppressWarnings("unchecked")
		Map<String, Object> props = (Hashtable<String, Object>) mStorage
				.getObj(storeType.EDGEPROPERTY,
						mStorage.getTransaction(), mId);
		Object o = props.remove(arg0);
		mStorage.store(storeType.EDGEPROPERTY, mStorage.getTransaction(),
				mId, props);
		return o;
	}

	@Override
	public void setProperty(String arg0, Object arg1) {
		logger.debug("setProperty key: "+ arg0+" value: "+ arg1);

		if(arg0==null||arg0.equals(""))
			throw ExceptionFactory.elementKeyCanNotBeEmpty();

		if (sBlackList.contains(arg0))
			throw new IllegalArgumentException(arg0
					+ " is not allowed to be used as property name");
		//mStorage.createSecondaryIfNeed(storeType.EDGEPROPERTY,EdbTransactionalGraph.txs.get(), arg0);
		@SuppressWarnings("unchecked")
		Map<String, Object> props = (Hashtable<String, Object>) mStorage
				.getObj(storeType.EDGEPROPERTY,
						mStorage.getTransaction(), mId);
		props.put(arg0, arg1);
		mStorage.store(storeType.EDGEPROPERTY, mStorage.getTransaction(),
				mId, props);

	}

	@Override
	public String getLabel() {
		return mRelation;
	}

	/**
	 * see the model for detail
	 */
	@Override
	public Vertex getVertex(Direction arg0) {
		logger.debug("getVertex of direction " +arg0);
		if (arg0 == Direction.IN)
			return (Vertex) mStorage.getObj(storeType.VERTEX,
					mStorage.getTransaction(), mToVertex);
		else if (arg0 == Direction.OUT)
			return (Vertex) mStorage.getObj(storeType.VERTEX,
					mStorage.getTransaction(), mFromVertex);
		else{

			logger.error("direction should not be "+ arg0);
			throw ExceptionFactory.bothIsNotSupported();//   IllegalArgumentException("direction should not be "+ arg0);
		}
	}

	private void initSaving() {
		logger.debug("initialize property for edge "+ mId);
		Map<String, Object> props = new Hashtable<String, Object>();
		mStorage.store(storeType.EDGEPROPERTY, mStorage.getTransaction(),
				mId, props);

	}

	public String getVertexId(Direction arg0) {
		logger.debug("getVertex of direction " +arg0);
		if (arg0 == Direction.IN)
			return mToVertex;
		else if (arg0 == Direction.OUT)
			return mFromVertex;
		else {
			logger.error("direction should not be "+ arg0);
			throw ExceptionFactory.bothIsNotSupported();
		}
	}

	public Vertex getToVertex() {
		logger.debug("getToVertex ");
		return (Vertex) mStorage.getObj(storeType.VERTEX,
				mStorage.getTransaction(), mFromVertex);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (mId == null ? 0 : mId.hashCode());
		logger.debug("hashCode for edge "+mId+" is "+result);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (mId == null)
			return false;
		if (!(obj.getClass() == getClass()))
			return false;
		EdbEdge other = (EdbEdge) obj;
		if (!mId.equals(other.getId()))
			return false;
		return true;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class CameraReverbControl : MonoBehaviour
{
    public AudioReverbPreset DefaultState;
    private AudioReverbFilter Filter;
    private float timer;

    public void Update()
    {
        if (Filter == null)
            Filter = GetComponent<AudioReverbFilter>();

        timer += Time.unscaledDeltaTime;

        if(timer > 0.1f)
            Filter.reverbPreset = DefaultState;
    }

    public void SetReverb(AudioReverbPreset preset)
    {
        timer = 0f;
        Filter.reverbPreset = preset;
    }
}


text:
define(function (require) {

    var React = require('react');
    var NormalRenderer = require('../components/tree/NormalRenderer.jsx');

    return {

        leafFactory: function leafFactory(me) {
            if (!(me.props.datasource instanceof Array) || !me.props.datasource.length) return null;
            var value = me.___getValue___();
            try {
                value = JSON.parse(value);
            } catch (e) {
                value = {};
            }
            var expand = value.expand || {};
            var result = [];
            addLeaves(me.props.datasource, '');
            return result;
            function addLeaves(arr, level) {
                for (var i = 0; i < arr.length; i++) {
                    var item = JSON.parse(JSON.stringify(arr[i]));
                    var key = level.length ? level + ',' + i : i + '';
                    var props = {
                        key: key, // 层次
                        index: key, // react会吃掉key这个属性,呵呵
                        item: item, // 数据源
                        value: value, // tree的值
                        treeComponent: me, // tree实例
                        disabled: me.props.disabled || item.disabled, // 禁用
                        onAction: me.props.onAction
                    };
                    if (item.hr) {
                        result.push(React.createElement('hr', props));
                        continue;
                    }
                    var Renderer = typeof me.props.leafRenderer === 'function' ? me.props.leafRenderer : NormalRenderer;
                    result.push(React.createElement(Renderer, props));
                    if (item.children instanceof Array && expand[item.value]) {
                        addLeaves(item.children, props.index);
                    }
                }
            }
        }
    };
});


text:
package com.learnium.RNDeviceInfo.resolver;

import android.content.Context;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.lang.reflect.InvocationTargetException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

class DeviceIdResolverTest {

  @Mock
  Context context;

  private DeviceIdResolver deviceIdResolver;

  @BeforeEach
  void setUp() {
    MockitoAnnotations.initMocks(this);
    deviceIdResolver = spy(new DeviceIdResolver(context));
  }

  /**
   * By default, if no library is setup to get a deviceId then return "unknown"
   */
  @Test
  void getInstanceIdSync() {
    assertEquals("unknown", deviceIdResolver.getInstanceIdSync());
  }

  /**
   * If FirebaseId library is available, then return it
   */
  @Test
  void getInstanceIdSyncFirebase() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    doReturn("Firebase123").when(deviceIdResolver).getFirebaseInstanceId();
    assertEquals("Firebase123", deviceIdResolver.getInstanceIdSync());
  }

  /**
   * If GMS library available then return its generated id
   */
  @Test
  void getInstanceIdSyncGMS() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    doReturn("GMS123").when(deviceIdResolver).getGmsInstanceId();
    assertEquals("GMS123", deviceIdResolver.getInstanceIdSync());
  }

}


text:
NSString *const kZHGTokenResponseBaseClassRefreshToken = @"refresh_token";
NSString *const kZHGTokenResponseBaseClassExpiresIn = @"expires_in";
NSString *const kZHGTokenResponseBaseClassAccessToken = @"access_token";
NSString *const kZHGTokenResponseBaseClassTokenType = @"token_type";

@interface ZHGTokenResponseBaseClass ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation ZHGTokenResponseBaseClass

@synthesize refreshToken = _refreshToken;
@synthesize expiresIn = _expiresIn;
@synthesize accessToken = _accessToken;
@synthesize tokenType = _tokenType;

+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict
{
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];

    // This check serves to make sure that a non-NSDictionary object
    // passed into the model class doesn't break the parsing.
    if(self && [dict isKindOfClass:[NSDictionary class]]) {
            self.refreshToken = [self objectOrNilForKey:kZHGTokenResponseBaseClassRefreshToken fromDictionary:dict];
            self.expiresIn = [[self objectOrNilForKey:kZHGTokenResponseBaseClassExpiresIn fromDictionary:dict] doubleValue];
            self.accessToken = [self objectOrNilForKey:kZHGTokenResponseBaseClassAccessToken fromDictionary:dict];
            self.tokenType = [self objectOrNilForKey:kZHGTokenResponseBaseClassTokenType fromDictionary:dict];

    }

    return self;

}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:self.refreshToken forKey:kZHGTokenResponseBaseClassRefreshToken];
    [mutableDict setValue:[NSNumber numberWithDouble:self.expiresIn] forKey:kZHGTokenResponseBaseClassExpiresIn];
    [mutableDict setValue:self.accessToken forKey:kZHGTokenResponseBaseClassAccessToken];
    [mutableDict setValue:self.tokenType forKey:kZHGTokenResponseBaseClassTokenType];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict
{
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    self.refreshToken = [aDecoder decodeObjectForKey:kZHGTokenResponseBaseClassRefreshToken];
    self.expiresIn = [aDecoder decodeDoubleForKey:kZHGTokenResponseBaseClassExpiresIn];
    self.accessToken = [aDecoder decodeObjectForKey:kZHGTokenResponseBaseClassAccessToken];
    self.tokenType = [aDecoder decodeObjectForKey:kZHGTokenResponseBaseClassTokenType];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeObject:_refreshToken forKey:kZHGTokenResponseBaseClassRefreshToken];
    [aCoder encodeDouble:_expiresIn forKey:kZHGTokenResponseBaseClassExpiresIn];
    [aCoder encodeObject:_accessToken forKey:kZHGTokenResponseBaseClassAccessToken];
    [aCoder encodeObject:_tokenType forKey:kZHGTokenResponseBaseClassTokenType];
}

- (id)copyWithZone:(NSZone *)zone
{
    ZHGTokenResponseBaseClass *copy = [[ZHGTokenResponseBaseClass alloc] init];

    if (copy) {

        copy.refreshToken = [self.refreshToken copyWithZone:zone];
        copy.expiresIn = self.expiresIn;
        copy.accessToken = [self.accessToken copyWithZone:zone];
        copy.tokenType = [self.tokenType copyWithZone:zone];
    }

    return copy;
}

@end


text:
A [route](/docs/Glossary.md#route) has three attributes that determine whether or not it "matches" the URL:

1. [nesting](#nesting) and
2. its [`path`](#path-syntax)
3. its [precedence](#precedence)

### Nesting
React Router uses the concept of nested routes to let you declare nested sets of views that should be rendered when a given URL is invoked. Nested routes are arranged in a tree-like structure. To find a match, React Router traverses the [route config](/docs/Glossary.md#routeconfig) depth-first searching for a route that matches the URL.

### Path Syntax
A route path is [a string pattern](/docs/Glossary.md#routepattern) that is used to match a URL (or a portion of one). Route paths are interpreted literally, except for the following special symbols:

  - `:paramName` – matches a URL segment up to the next `/`, `?`, or `#`. The matched string is called a [param](/docs/Glossary.md#params)
  - `()` – Wraps a portion of the URL that is optional
  - `*` – Matches all characters (non-greedy) up to the next character in the pattern, or to the end of the URL if there is none, and creates a `splat` [param](/docs/Glossary.md#params)

```js
<Route path="/hello/:name">         // matches /hello/michael and /hello/ryan
<Route path="/hello(/:name)">       // matches /hello, /hello/michael, and /hello/ryan
<Route path="/files/*.*">           // matches /files/hello.jpg and /files/path/to/hello.jpg
```

If a route uses a relative `path`, it builds upon the accumulated `path` of its ancestors. Nested routes may opt-out of this behavior by [using an absolute `path`](RouteConfiguration.md#decoupling-the-ui-from-the-url).

### Precedence
Finally, the routing algorithm attempts to match routes in the order they are defined, top to bottom. So, when you have two sibling routes you should be sure the first doesn't match all possible `path`s that can be matched by the later sibling. For example, **don't** do this:

```js
<Route path="/comments" ... />
<Redirect from="/comments" ... />
```


text:
package org.rioproject.tools.ui.servicenotification;

import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.lease.Lease;
import net.jini.core.lease.LeaseDeniedException;
import net.jini.discovery.DiscoveryManagement;
import org.rioproject.event.DynamicEventConsumer;
import org.rioproject.event.RemoteServiceEvent;
import org.rioproject.event.RemoteServiceEventListener;
import org.rioproject.eventcollector.api.EventCollector;
import org.rioproject.eventcollector.api.EventCollectorAdmin;
import org.rioproject.eventcollector.api.EventCollectorRegistration;
import org.rioproject.eventcollector.api.UnknownEventCollectorRegistration;
import org.rioproject.log.ServiceLogEvent;
import org.rioproject.monitor.ProvisionFailureEvent;
import org.rioproject.monitor.ProvisionMonitorEvent;
import org.rioproject.resources.util.ThrowableUtil;
import org.rioproject.sla.SLAThresholdEvent;
import org.rioproject.tools.ui.ChainedRemoteEventListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Handles the creation of event consumers, based on whether an {@link org.rioproject.eventcollector.api.EventCollector}
 * is being used, or whether we register for notifications to all discovered services.
 *
 * @author Dennis Reedy
 */
public class RemoteEventConsumerManager {
    private EventCollectorRegistration eventCollectorRegistration;
    private ChainedRemoteEventListener remoteEventListener;
    private DynamicEventConsumer provisionFailureEventConsumer;
    private DynamicEventConsumer provisionMonitorEventConsumer;
    private DynamicEventConsumer serviceLogEventConsumer;
    private DynamicEventConsumer slaThresholdEventConsumer;
    private AtomicBoolean useEventCollector = new AtomicBoolean(true);
    private final List<EventCollector> eventCollectors = new LinkedList<EventCollector>();
    private PendingEventCollectorRegistration pendingEventCollectionRegistration;

    public void registerForEventCollectorNotification(RemoteEventListener eventListener,
                                                      Configuration config) throws IOException,
                                                                                ConfigurationException,
                                                                                UnknownEventCollectorRegistration,
                                                                                LeaseDeniedException {
        if(eventCollectors.isEmpty()) {
            pendingEventCollectionRegistration = new PendingEventCollectorRegistration(eventListener, config);
            return;
        }

        /* Create the event consumer for EventCollector notification */
        if(remoteEventListener==null) {
            remoteEventListener = new ChainedRemoteEventListener(eventListener, config);
        }
        if(eventCollectorRegistration==null && useEventCollector.get()) {
            List<EventCollector> removals = new ArrayList<EventCollector>();
            for(EventCollector eventCollector : eventCollectors) {
                try {
                    eventCollectorRegistration = eventCollector.register(Lease.ANY);
                    eventCollectorRegistration.enableDelivery(remoteEventListener.getRemoteEventListener());
                } catch (IOException e) {
                    if(!ThrowableUtil.isRetryable(e)) {
                        removals.add(eventCollector);
                    } else {
                        throw e;
                    }
                }
            }
            if(!removals.isEmpty()) {
                for(EventCollector eventCollector : removals) {
                    synchronized (eventCollectors) {
                        eventCollectors.remove(eventCollector);
                    }
                }
            }
        }
    }

    public int getEventControllerCount() {
        return eventCollectors.size();
    }

    public void registerForAllServiceNotification(RemoteServiceEventListener remoteEventListener,
                                                  DiscoveryManagement dMgr) throws Exception {
        /* Create the event consumer for ProvisionFailureEvent utilities */

        provisionFailureEventConsumer = new DynamicEventConsumer(ProvisionFailureEvent.getEventDescriptor(),
                                                                 remoteEventListener,
                                                                 dMgr);
        provisionMonitorEventConsumer = new DynamicEventConsumer(ProvisionMonitorEvent.getEventDescriptor(),
                                                                 remoteEventListener,
                                                                 dMgr);
        serviceLogEventConsumer = new DynamicEventConsumer(ServiceLogEvent.getEventDescriptor(),
                                                           remoteEventListener,
                                                           dMgr);
        slaThresholdEventConsumer = new DynamicEventConsumer(SLAThresholdEvent.getEventDescriptor(),
                                                             remoteEventListener,
                                                             dMgr);

    }

    public void setUseEventCollector(boolean useEventCollector) {
        this.useEventCollector.set(useEventCollector);
    }

    public void delete(Collection<RemoteServiceEvent> events) {
        if(events!=null && !events.isEmpty() && useEventCollector.get()) {
            for(EventCollector eventCollector : eventCollectors) {
                try {
                    EventCollectorAdmin admin = (EventCollectorAdmin)eventCollector.getAdmin();
                    admin.delete(events);
                } catch(IOException e) {

                }
            }
        }
    }

    public void addEventCollector(EventCollector eventCollector) throws LeaseDeniedException,
                                                                        IOException,
                                                                        UnknownEventCollectorRegistration {
        eventCollectors.add(eventCollector);
        if(pendingEventCollectionRegistration!=null) {
            try {
                registerForEventCollectorNotification(pendingEventCollectionRegistration.getEventListener(),
                                                      pendingEventCollectionRegistration.getConfig());
                pendingEventCollectionRegistration = null;
            } catch (ConfigurationException e) {
                e.printStackTrace();
            }
        }
    }

    public void removeEventCollector(EventCollector eventCollector) {
        eventCollectors.remove(eventCollector);
    }

    public void refresh() throws UnknownEventCollectorRegistration, IOException {
        if(eventCollectorRegistration!=null) {
            eventCollectorRegistration.enableDelivery(remoteEventListener.getRemoteEventListener());
        }
    }

    public void terminate() {
        if(eventCollectorRegistration!=null) {
            try {
                eventCollectorRegistration.disableDelivery();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                eventCollectorRegistration.getLease().cancel();
            } catch (Exception e) {
                e.printStackTrace();
            }
            eventCollectorRegistration = null;
        }
        if(remoteEventListener!=null) {
            remoteEventListener.terminate();
            remoteEventListener = null;
        }
        if(provisionFailureEventConsumer!=null) {
            provisionFailureEventConsumer.terminate();
            provisionFailureEventConsumer = null;
        }
        if(provisionMonitorEventConsumer!=null) {
            provisionMonitorEventConsumer.terminate();
            provisionMonitorEventConsumer = null;
        }
        if(serviceLogEventConsumer!=null) {
            serviceLogEventConsumer.terminate();
            serviceLogEventConsumer = null;
        }
        if(slaThresholdEventConsumer!=null) {
            slaThresholdEventConsumer.terminate();
            slaThresholdEventConsumer = null;
        }
    }

    private class PendingEventCollectorRegistration {
        private RemoteEventListener eventListener;
        private Configuration config;

        private PendingEventCollectorRegistration(RemoteEventListener eventListener, Configuration config) {
            this.eventListener = eventListener;
            this.config = config;
        }

        public RemoteEventListener getEventListener() {
            return eventListener;
        }

        public Configuration getConfig() {
            return config;
        }
    }
}


text:
package sun.awt.X11;

import java.awt.Component;
import java.awt.Rectangle;
import java.awt.Insets;

import java.awt.event.ComponentEvent;

import sun.util.logging.PlatformLogger;

import sun.awt.AWTAccessor;

/**
 * This class implements window which serves as content window for decorated frames.
 * Its purpose to provide correct events dispatching for the complex
 * constructs such as decorated frames.
 *
 * It should always be located at (- left inset, - top inset) in the associated
 * decorated window.  So coordinates in it would be the same as java coordinates.
 */
public final class XContentWindow extends XWindow {
    private static PlatformLogger insLog = PlatformLogger.getLogger("sun.awt.X11.insets.XContentWindow");

    static XContentWindow createContent(XDecoratedPeer parentFrame) {
        final WindowDimensions dims = parentFrame.getDimensions();
        Rectangle rec = dims.getBounds();
        // Fix for  - set the location of the content window to the (-left inset, -top inset)
        Insets ins = dims.getInsets();
        if (ins != null) {
            rec.x = -ins.left;
            rec.y = -ins.top;
        } else {
            rec.x = 0;
            rec.y = 0;
        }
        final XContentWindow cw = new XContentWindow(parentFrame, rec);
        cw.xSetVisible(true);
        return cw;
    }

    private final XDecoratedPeer parentFrame;

    // A list of expose events that come when the parentFrame is iconified
    private final java.util.List<SavedExposeEvent> iconifiedExposeEvents =
            new java.util.ArrayList<SavedExposeEvent>();

    private XContentWindow(XDecoratedPeer parentFrame, Rectangle bounds) {
        super((Component)parentFrame.getTarget(), parentFrame.getShell(), bounds);
        this.parentFrame = parentFrame;
    }

    void preInit(XCreateWindowParams params) {
        super.preInit(params);
        params.putIfNull(BIT_GRAVITY, Integer.valueOf(XConstants.NorthWestGravity));
        Long eventMask = (Long)params.get(EVENT_MASK);
        if (eventMask != null) {
            eventMask = eventMask & ~(XConstants.StructureNotifyMask);
            params.put(EVENT_MASK, eventMask);
        }
    }

    protected String getWMName() {
        return "Content window";
    }
    protected boolean isEventDisabled(XEvent e) {
        switch (e.get_type()) {
          // Override parentFrame to receive MouseEnter/Exit
          case XConstants.EnterNotify:
          case XConstants.LeaveNotify:
              return false;
          // We handle ConfigureNotify specifically in XDecoratedPeer
          case XConstants.ConfigureNotify:
              return true;
          // We don't want SHOWN/HIDDEN on content window since it will duplicate XDecoratedPeer
          case XConstants.MapNotify:
          case XConstants.UnmapNotify:
              return true;
          default:
              return super.isEventDisabled(e) || parentFrame.isEventDisabled(e);
        }
    }

    // Coordinates are that of the shell
    void setContentBounds(WindowDimensions dims) {
        XToolkit.awtLock();
        try {
            // Bounds of content window are of the same size as bounds of Java window and with
            // location as -(insets)
            Rectangle newBounds = dims.getBounds();
            Insets in = dims.getInsets();
            if (in != null) {
                newBounds.setLocation(-in.left, -in.top);
            }
            if (insLog.isLoggable(PlatformLogger.FINE)) insLog.fine("Setting content bounds {0}, old bounds {1}",
                                                                    newBounds, getBounds());
            // Fix for 5023533:
            // Change in the size of the content window means, well, change of the size
            // Change in the location of the content window means change in insets
            boolean needHandleResize = !(newBounds.equals(getBounds()));
            reshape(newBounds);
            if (needHandleResize) {
                insLog.fine("Sending RESIZED");
                handleResize(newBounds);
            }
        } finally {
            XToolkit.awtUnlock();
        }
        validateSurface();
    }

    // NOTE: This method may be called by privileged threads.
    //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
    public void handleResize(Rectangle bounds) {
        AWTAccessor.getComponentAccessor().setSize((Component)target, bounds.width, bounds.height);
        postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED));
    }

    public void handleExposeEvent(Component target, int x, int y, int w, int h) {
        // TODO: ?
        // get rid of 'istanceof' by subclassing:
        // XContentWindow -> XFrameContentWindow

        // Expose event(s) that result from deiconification
        // come before a deicinofication notification.
        // We reorder these events by saving all expose events
        // that come when the frame is iconified. Then we
        // actually handle saved expose events on deiconification.

        if (parentFrame instanceof XFramePeer &&
                (((XFramePeer)parentFrame).getState() & java.awt.Frame.ICONIFIED) != 0) {
            // Save expose events if the frame is iconified
            // in order to handle them on deiconification.
            iconifiedExposeEvents.add(new SavedExposeEvent(target, x, y, w, h));
        } else {
            // Normal case: [it is not a frame or] the frame is not iconified.
            super.handleExposeEvent(target, x, y, w, h);
        }
    }

    void purgeIconifiedExposeEvents() {
        for (SavedExposeEvent evt : iconifiedExposeEvents) {
            super.handleExposeEvent(evt.target, evt.x, evt.y, evt.w, evt.h);
        }
        iconifiedExposeEvents.clear();
    }

    private static class SavedExposeEvent {
        Component target;
        int x, y, w, h;
        SavedExposeEvent(Component target, int x, int y, int w, int h) {
            this.target = target;
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
        }
    }

    public String toString() {
        return getClass().getName() + "[" + getBounds() + "]";
    }
}


text:
       <meta http-equiv="refresh" content="1" />

 Test for simple Webcam Live streaming


text:
@interface TestLikeUtils : SZIntegrationTestCase

@end


text:
using UnityEngine;
using System.Collections;

public class rotateMe : MonoBehaviour {

    public Vector3 angleRotation;

	// Use this for initialization
	void Start ()
    {

	}

	// Update is called once per frame
	void Update ()
    {
        if (Time.timeScale != 0.0f)
            transform.Rotate(angleRotation);
	}
}


text:
function World(width, height, floor, surfer, rocks) {
  this.width = width || 600;
  this.height = height || 200;
  this.surfer = surfer;
  this.rocks = rocks;
  this.floor = floor;
}

module.exports = World;


text:
class FeedAnalysisReportsLongDates < ActiveRecord::Migration

  def self.up
    execute_java_migration('org.sonar.db.version.v51.FeedAnalysisReportsLongDates')
  end

end