= MetaSearch

MetaSearch is extensible searching for your form_for enjoyment. It “wraps” one of your ActiveRecord models, providing methods that allow you to build up search conditions against that model, and has a few extra form helpers to simplify sorting and supplying multiple parameters to your condition methods as well.

== NOTE

The successor to MetaSearch is {Ransack}[http://github.com/ernie/ransack]. It's got features
that MetaSearch doesn't, along with some API changes. I haven't had the time to dedicate to
making it bulletproof yet, so I'm releasing a 1.1.x branch of MetaSearch to help with migrations
to Rails 3.1.

This is intended to be a stopgap measure.

t's important to note that the long-term migration path for your apps should be toward
Ransack, which is written in a more sane manner that will make supporting new versions
of Rails much easier going forward.

== Getting Started

In your Gemfile:

  gem "meta_search"  # Last officially released gem
  # gem "meta_search", :git => "git://github.com/ernie/meta_search.git" # Track git repo

or, to install as a plugin:

  rails plugin install git://github.com/ernie/meta_search.git

In your controller:

  def index
    @search = Article.search(params[:search])
    @articles = @search.all   # load all matching records
    # @articles = @search.relation # Retrieve the relation, to lazy-load in view
    # @articles = @search.paginate(:page => params[:page]) # Who doesn't love will_paginate?
  end

In your view:

  <%= form_for @search, :url => articles_path, :html => {:method => :get} do |f| %>
    <%= f.label :title_contains %>
    <%= f.text_field :title_contains %>

    <%= f.label :comments_created_at_greater_than, 'With comments after' %>
    <%= f.datetime_select :comments_created_at_greater_than, :include_blank => true %>

    <%= f.submit %>
  <% end %>

Options for the search method are documented at MetaSearch::Searches::ActiveRecord.

== "Wheres", and what they're good for

Wheres are how MetaSearch does its magic. Wheres have a name (and possible aliases) which are
appended to your model and association attributes. When you instantiate a MetaSearch::Builder
against a model (manually or by calling your model's +search+ method) the builder responds to
methods named for your model's attributes and associations, suffixed by the name of the Where.

These are the default Wheres, broken down by the types of ActiveRecord columns they can search
against:

=== All data types

* _equals_ (alias: _eq_) - Just as it sounds.
* _does_not_equal_ (aliases: _ne_, _noteq_) - The opposite of equals, oddly enough.
* _in_ - Takes an array, matches on equality with any of the items in the array.
* _not_in_ (aliases: _ni_, _notin_) - Like above, but negated.
* _is_null_ - The column has an SQL NULL value.
* _is_not_null_ - The column contains anything but NULL.

=== Strings

* _contains_ (aliases: _like_, _matches_) - Substring match.
* _does_not_contain_ (aliases: _nlike_, _nmatches_) - Negative substring match.
* _starts_with_ (alias: _sw_) - Match strings beginning with the entered term.
* _does_not_start_with_ (alias: _dnsw_) - The opposite of above.
* _ends_with_ (alias: _ew_) - Match strings ending with the entered term.
* _does_not_end_with_ (alias: _dnew_) - Negative of above.

=== Numbers, dates, and times

* _greater_than_ (alias: _gt_) - Greater than.
* _greater_than_or_equal_to_ (aliases: _gte_, _gteq_) - Greater than or equal to.
* _less_than_ (alias: _lt_) - Less than.
* _less_than_or_equal_to_ (aliases: _lte_, _lteq_) - Less than or equal to.

=== Booleans

* _is_true_ - Is true. Useful for a checkbox like "only show admin users".
* _is_false_ - The complement of _is_true_.

=== Non-boolean data types

* _is_present_ - As with _is_true_, useful with a checkbox. Not NULL or the empty string.
* _is_blank_ - Returns records with a value of NULL or the empty string in the column.

So, given a model like this...

  class Article < ActiveRecord::Base
    belongs_to :author
    has_many :comments
    has_many :moderations, :through => :comments
  end

...you might end up with attributes like <tt>title_contains</tt>,
<tt>comments_title_starts_with</tt>, <tt>moderations_value_less_than</tt>,
<tt>author_name_equals</tt>, and so on.

Additionally, all of the above predicate types also have an _any and _all version, which
expects an array of the corresponding parameter type, and requires any or all of the
parameters to be a match, respectively. So:

  Article.search :author_name_starts_with_any => ['Jim', 'Bob', 'Fred']

will match articles authored by Jimmy, Bobby, or Freddy, but not Winifred.

== Advanced usage

=== Narrowing the scope of a search

While the most common use case is to simply call Model.search(params[:search]), there
may be times where you want to scope your search more tightly. For instance, only allowing
users to search their own projects (assuming a current_user method returning the current user):

  @search = current_user.projects.search(params[:search])

Or, you can build up any relation you like and call the search method on that object:

  @projects_with_awesome_users_search =
    Project.joins(:user).where(:users => {:awesome => true}).search(params[:search])

=== ORed conditions

If you'd like to match on one of several possible columns, you can do this:

  <%= f.text_field :title_or_description_contains %>
  <%= f.text_field :title_or_author_name_starts_with %>

Caveats:

* Only one match type is supported. You can't do
  <tt>title_matches_or_description_starts_with</tt> for instance.
* If you're matching across associations, remember that the associated table will be
  INNER JOINed, therefore limiting results to those that at least have a corresponding
  record in the associated table.

=== Compound conditions (any/all)

All Where types automatically get an "any" and "all" variant. This has the same name and
aliases as the original, but is suffixed with _any and _all, for an "OR" or "AND" search,
respectively. So, if you want to provide the user with 5 different search boxes to enter
possible article titles:

  <%= f.multiparameter_field :title_contains_any,
        *5.times.inject([]) {|a, b| a << {:field_type => :text_field}} +
        [:size => 10] %>

=== Multi-level associations

MetaSearch will allow you to traverse your associations in one form, generating the
necessary joins along the way. If you have the following models...

  class Company < ActiveRecord::Base
    has_many :developers
  end

  class Developer < ActiveRecord::Base
    belongs_to :company
    has_many :notes
  end

...you can do this in your form to search your companies by developers with certain notes:

  <%= f.text_field :developers_notes_note_contains %>

You can travel forward and back through the associations, so this would also work (though
be entirely pointless in this case):

  <%= f.text_field :developers_notes_developer_company_name_contains %>

However, to prevent abuse, this is limited to associations of a total "depth" of 5 levels.
This means that while starting from a Company model, as above, you could do
Company -> :developers -> :notes -> :developer -> :company, which has gotten you right
back where you started, but "travels" through 5 models total.

In the case of polymorphic belongs_to associations, things work a bit differently. Let's say
you have the following models:

  class Article < ActiveRecord::Base
    has_many :comments, :as => :commentable
  end

  class Post < ActiveRecord::Base
    has_many :comments, :as => :commentable
  end

  class Comment < ActiveRecord::Base
    belongs_to :commentable, :polymorphic => true
    validates_presence_of :body
  end

Your first instinct might be to set up a text field for :commentable_body_contains, but
you can't do this. MetaSearch would have no way to know which class lies on the other side
of the polymorphic association, so it wouldn't be able to join the correct tables.

Instead, you'll follow a convention Searchlogic users are already familiar with, using the
name of the polymorphic association, then the underscored class name (AwesomeClass becomes
awesome_class), then the delimiter "type", to tell MetaSearch anything that follows is an
attribute name. For example:

  <%= f.text_field :commentable_article_type_body_contains %>

If you'd like to match on multiple types of polymorphic associations, you can join them
with \_or_, just like any other conditions:

  <%= f.text_field :commentable_article_type_body_or_commentable_post_type_body_contains %>

It's not pretty, but it works. Alternately, consider creating a custom search method as
described below to save yourself some typing if you're creating a lot of these types of
search fields.

=== Adding a new Where

If none of the built-in search criteria work for you, you can add new Wheres. To do so,
create an initializer (<tt>/config/initializers/meta_search.rb</tt>, for instance) and add lines
like:

  MetaSearch::Where.add :between, :btw,
    :predicate => :in,
    :types => [:integer, :float, :decimal, :date, :datetime, :timestamp, :time],
    :formatter => Proc.new {|param| Range.new(param.first, param.last)},
    :validator => Proc.new {|param|
      param.is_a?(Array) && !(param[0].blank? || param[1].blank?)
    }

See MetaSearch::Where for info on the supported options.

=== Accessing custom search methods (and named scopes!)

MetaSearch can be given access to any class method on your model to extend its search capabilities.
The only rule is that the method must return an ActiveRecord::Relation so that MetaSearch can
continue to extend the search with other attributes. Conveniently, scopes (formerly "named scopes")
do this already.

Consider the following model:

  class Company < ActiveRecord::Base
    has_many :slackers, :class_name => "Developer", :conditions => {:slacker => true}
    scope :backwards_name, lambda {|name| where(:name => name.reverse)}
    scope :with_slackers_by_name_and_salary_range,
      lambda {|name, low, high|
        joins(:slackers).where(:developers => {:name => name, :salary => low..high})
      }
  end

To allow MetaSearch access to a model method, including a named scope, just use
<tt>search_methods</tt> in the model:

  search_methods :backwards_name

This will allow you to add a text field named :backwards_name to your search form, and
it will behave as you might expect.

In the case of the second scope, we have multiple parameters to pass in, of different
types. We can pass the following to <tt>search_methods</tt>:

  search_methods :with_slackers_by_name_and_salary_range,
    :splat_param => true, :type => [:string, :integer, :integer]

MetaSearch needs us to tell it that we don't want to keep the array supplied to it as-is, but
"splat" it when passing it to the model method. Regarding <tt>:types</tt>: In this case,
ActiveRecord would have been smart enough to handle the typecasting for us, but I wanted to
demonstrate how we can tell MetaSearch that a given parameter is of a specific database "column type." This is just a hint MetaSearch uses in the same way it does when casting "Where" params based
on the DB column being searched. It's also important so that things like dates get handled
properly by FormBuilder.

=== multiparameter_field

The example Where above adds support for a "between" search, which requires an array with
two parameters. These can be passed using Rails multiparameter attributes. To make life easier,
MetaSearch adds a helper for this:

  <%= f.multiparameter_field :moderations_value_between,
      {:field_type => :text_field}, {:field_type => :text_field}, :size => 5 %>

<tt>multiparameter_field</tt> works pretty much like the other FormBuilder helpers, but it
lets you sandwich a list of fields, each in hash format, between the attribute and the usual
options hash. See MetaSearch::Helpers::FormBuilder for more info.

=== checks and collection_checks

If you need to get an array into your where, and you don't care about parameter order,
you might choose to use a select or collection_select with multiple selection enabled,
but everyone hates multiple selection boxes. MetaSearch adds a couple of additional
helpers, +checks+ and +collection_checks+ to handle multiple selections in a
more visually appealing manner. They can be called with or without a block. Without a
block, you get an array of MetaSearch::Check objects to do with as you please.

With a block, each check is yielded to your template, like so:

How many heads?

    <% f.checks :number_of_heads_in,
      [['One', 1], ['Two', 2], ['Three', 3]], :class => 'checkboxy' do |check| %>

        <%= check.box %>
        <%= check.label %>

    <% end %>

Again, full documentation is in MetaSearch::Helpers::FormBuilder.

=== Sorting columns

If you'd like to sort by a specific column in your results (the attributes of the base model)
or an association column then supply the <tt>meta_sort</tt> parameter in your form.
The parameter takes the form <tt>column.direction</tt> where +column+ is the column name or
underscore-separated association_column combination, and +direction+ is one of "asc" or "desc"
for ascending or descending, respectively.

Normally, you won't supply this parameter yourself, but instead will use the helper method
<tt>sort_link</tt> in your views, like so:

  <%= sort_link @search, :title %>

Or, if in the context of a form_for against a MetaSearch::Builder:

  <%= f.sort_link :title %>

The <tt>@search</tt> object is the instance of MetaSearch::Builder you got back earlier from
your controller. The other required parameter is the attribute name itself. Optionally,
you can provide a string as a 3rd parameter to override the default link name, and then
additional hashed for the +options+ and +html_options+ hashes for link_to.

By default, the link that is created will sort by the given column in ascending order when first clicked. If you'd like to reverse this (so the first click sorts the results in descending order), you can pass +:default_order => :desc+ in the options hash, like so:

  <%= sort_link @search, :ratings, "Highest Rated", :default_order => :desc %>

You can sort by more than one column as well, by creating a link like:

  <%= sort_link :name_and_salary %>

If you'd like to do a custom sort, you can do so by setting up two scopes in your model:

  scope :sort_by_custom_name_asc, order('custom_name ASC')
  scope :sort_by_custom_name_desc, order('custom_name DESC')

You can then do <tt>sort_link @search, :custom_name</tt> and it will work as you expect.

All <tt>sort_link</tt>-generated links will have the CSS class sort_link, as well as a
directional class (ascending or descending) if the link is for a currently sorted column,
for your styling enjoyment.

This feature should hopefully help out those of you migrating from Searchlogic, and a thanks
goes out to Ben Johnson for the HTML entities used for the up and down arrows, which provide
a nice default look.

=== Including/excluding attributes and associations

If you'd like to allow only certain associations or attributes to be searched, you can do
so inside your models

  class Article < ActiveRecord::Base
    attr_searchable :some_public_data, :some_more_searchable_stuff
    assoc_searchable :search_this_association_why_dontcha
  end

If you'd rather blacklist attributes and associations rather than whitelist, use the
<tt>attr_unsearchable</tt> and <tt>assoc_unsearchable</tt> method instead. If a
whitelist is supplied, it takes precedence.

Excluded attributes on a model will be honored across associations, so if an Article
<tt>has_many :comments</tt> and the Comment model looks something like this:

  class Comment < ActiveRecord::Base
    validates_presence_of :user_id, :body
    attr_unsearchable :user_id
  end

Then your call to <tt>Article.search</tt> will allow <tt>:comments_body_contains</tt>
but not <tt>:comments_user_id_equals</tt> to be passed.

=== Conditional access to searches

<tt>search_methods</tt>, <tt>attr_searchable</tt>, <tt>attr_unsearchable</tt>,
<tt>assoc_searchable</tt>, and <tt>assoc_unsearchable</tt> all accept an <tt>:if</tt>
option. If present, it should specify a Proc (or other object responding to <tt>call</tt>)
that accepts a single parameter. This parameter will be the instance of the MetaSearch::Builder
that gets created by a call to Model.search. Any unused search options (the second hash param)
that get passed to Model.search will be available via the Builder object's <tt>options</tt>
reader, and can be used for access control via this proc/object.

Example:

  assoc_unsearchable :notes,
                     :if => proc {|s| s.options[:access] == 'blocked' || !s.options[:access]}

=== Localization

MetaSearch supports i18n localization in a few different ways. Consider this abbreviated
example "flanders" locale:

  flanders:
    activerecord:
      attributes:
        company:
          name: "Company name-diddly"
        developer:
          name: "Developer name-diddly"
          salary: "Developer salary-doodly"
    meta_search:
      or: 'or-diddly'
      predicates:
        contains: "%{attribute} contains-diddly"
        equals: "%{attribute} equals-diddly"
      attributes:
        company:
          reverse_name: "Company reverse name-diddly"
        developer:
          name_contains: "Developer name-diddly contains-aroonie"

First, MetaSearch will use a key found under meta_search.attributes.model_name.attribute_name,
if it exists. As a fallback, it will use a localization based on the predicate type, along with
the usual ActiveRecord attribute localization (the activerecord.attributes.model_name keys above).
Additionally, a localized "or" can be specified for multi-column searches.

== Contributions

There are several ways you can help MetaSearch continue to improve.

* Use MetaSearch in your real-world projects and {submit bug reports or feature suggestions}[http://metautonomous.lighthouseapp.com/projects/53012-metasearch/].
* Better yet, if you’re so inclined, fix the issue yourself and submit a patch! Or you can {fork the project on GitHub}[http://github.com/ernie/meta_search] and send me a pull request (please include tests!)
* If you like MetaSearch, spread the word. More users == more eyes on code == more bugs getting found == more bugs getting fixed (hopefully!)
* Lastly, if MetaSearch has saved you hours of development time on your latest Rails gig, and you’re feeling magnanimous, please consider {making a donation}[http://pledgie.com/campaigns/9647] to the project. I have spent hours of my personal time coding and supporting MetaSearch, and your donation would go a great way toward justifying that time spent to my loving wife. :)

== Copyright

Copyright (c) 2010 {Ernie Miller}[http://metautonomo.us]. See LICENSE for details.


package ecs

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetInstanceConsoleOutput invokes the ecs.GetInstanceConsoleOutput API synchronously
// api document: https://help.aliyun.com/api/ecs/getinstanceconsoleoutput.html
func (client *Client) GetInstanceConsoleOutput(request *GetInstanceConsoleOutputRequest) (response *GetInstanceConsoleOutputResponse, err error) {
	response = CreateGetInstanceConsoleOutputResponse()
	err = client.DoAction(request, response)
	return
}

// GetInstanceConsoleOutputWithChan invokes the ecs.GetInstanceConsoleOutput API asynchronously
// api document: https://help.aliyun.com/api/ecs/getinstanceconsoleoutput.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetInstanceConsoleOutputWithChan(request *GetInstanceConsoleOutputRequest) (<-chan *GetInstanceConsoleOutputResponse, <-chan error) {
	responseChan := make(chan *GetInstanceConsoleOutputResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetInstanceConsoleOutput(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetInstanceConsoleOutputWithCallback invokes the ecs.GetInstanceConsoleOutput API asynchronously
// api document: https://help.aliyun.com/api/ecs/getinstanceconsoleoutput.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetInstanceConsoleOutputWithCallback(request *GetInstanceConsoleOutputRequest, callback func(response *GetInstanceConsoleOutputResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetInstanceConsoleOutputResponse
		var err error
		defer close(result)
		response, err = client.GetInstanceConsoleOutput(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetInstanceConsoleOutputRequest is the request struct for api GetInstanceConsoleOutput
type GetInstanceConsoleOutputRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
	InstanceId           string           `position:"Query" name:"InstanceId"`
}

// GetInstanceConsoleOutputResponse is the response struct for api GetInstanceConsoleOutput
type GetInstanceConsoleOutputResponse struct {
	*responses.BaseResponse
	RequestId      string `json:"RequestId" xml:"RequestId"`
	InstanceId     string `json:"InstanceId" xml:"InstanceId"`
	ConsoleOutput  string `json:"ConsoleOutput" xml:"ConsoleOutput"`
	LastUpdateTime string `json:"LastUpdateTime" xml:"LastUpdateTime"`
}

// CreateGetInstanceConsoleOutputRequest creates a request to invoke GetInstanceConsoleOutput API
func CreateGetInstanceConsoleOutputRequest() (request *GetInstanceConsoleOutputRequest) {
	request = &GetInstanceConsoleOutputRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Ecs", "2014-05-26", "GetInstanceConsoleOutput", "ecs", "openAPI")
	return
}

// CreateGetInstanceConsoleOutputResponse creates a response to parse from GetInstanceConsoleOutput response
func CreateGetInstanceConsoleOutputResponse() (response *GetInstanceConsoleOutputResponse) {
	response = &GetInstanceConsoleOutputResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.ui.animation

import androidx.animation.AnimatedFloat
import androidx.animation.AnimatedValue
import androidx.compose.Model
import androidx.animation.ValueHolder
import androidx.annotation.CheckResult
import androidx.compose.Effect
import androidx.compose.memo
import androidx.ui.graphics.Color
import androidx.ui.graphics.lerp
import androidx.ui.lerp

/**
 * The animatedValue effect creates an [AnimatedValue] and positionally memoizes it. When the
 * [AnimatedValue] object gets its value updated, components that rely on that value will be
 * automatically recomposed.
 *
 * @param initVal Initial value to set [AnimatedValue] to.
 * @param interpolator A value interpolator for interpolating two values of type [T]
 */
@CheckResult(suggest = "+")
fun <T> animatedValue(initVal: T, interpolator: (T, T, Float) -> T): Effect<AnimatedValue<T>> =
    memo { AnimatedValue(AnimValueHolder(initVal, interpolator)) }

/**
 * The animatedValue effect creates an [AnimatedFloat] and positionally memoizes it. When the
 * [AnimatedFloat] object gets its value updated, components that rely on that value will be
 * automatically recomposed.
 *
 * @param initVal Initial value to set [AnimatedFloat] to.
 */
@CheckResult(suggest = "+")
fun animatedFloat(initVal: Float): Effect<AnimatedFloat> =
    memo { AnimatedFloat(AnimValueHolder(initVal, ::lerp)) }

/**
 * The animatedValue effect creates an [AnimatedValue] of [Color] and positionally memoizes it. When
 * the [AnimatedValue] object gets its value updated, components that rely on that value will be
 * automatically recomposed.
 *
 * @param initVal Initial value to set [AnimatedValue] to.
 */
@CheckResult(suggest = "+")
fun animatedColor(initVal: Color): Effect<AnimatedValue<Color>> =
    memo { AnimatedValue(AnimValueHolder(initVal, ::lerp)) }

@Model
private class AnimValueHolder<T>(
    override var value: T,
    override val interpolator: (T, T, Float) -> T
) : ValueHolder<T>


/*
 * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.security.cert;

import java.util.Iterator;
import java.util.Set;

/**
 * An immutable valid policy tree node as defined by the PKIX certification
 * path validation algorithm.
 *
 *
One of the outputs of the PKIX certification path validation
 * algorithm is a valid policy tree, which includes the policies that
 * were determined to be valid, how this determination was reached,
 * and any policy qualifiers encountered. This tree is of depth
 * n, where n is the length of the certification
 * path that has been validated.
 *
 *
Most applications will not need to examine the valid policy tree.
 * They can achieve their policy processing goals by setting the
 * policy-related parameters in PKIXParameters. However,
 * the valid policy tree is available for more sophisticated applications,
 * especially those that process policy qualifiers.
 *
 *
{@link PKIXCertPathValidatorResult#getPolicyTree()
 * PKIXCertPathValidatorResult.getPolicyTree} returns the root node of the
 * valid policy tree. The tree can be traversed using the
 * {@link #getChildren getChildren} and {@link #getParent getParent} methods.
 * Data about a particular node can be retrieved using other methods of
 * PolicyNode.
 *
 *
Concurrent Access
 *
All PolicyNode objects must be immutable and
 * thread-safe. Multiple threads may concurrently invoke the methods defined
 * in this class on a single PolicyNode object (or more than one)
 * with no ill effects. This stipulation applies to all public fields and
 * methods of this class and any added or overridden by subclasses.
 *
 * @since       1.4
 * @author      Sean Mullan
 */
public interface PolicyNode {

    /**
     * Returns the parent of this node, or null if this is the
     * root node.
     *
     * @return the parent of this node, or null if this is the
     * root node
     */
    PolicyNode getParent();

    /**
     * Returns an iterator over the children of this node. Any attempts to
     * modify the children of this node through the
     * Iterator's remove method must throw an
     * UnsupportedOperationException.
     *
     * @return an iterator over the children of this node
     */
    Iterator<? extends PolicyNode> getChildren();

    /**
     * Returns the depth of this node in the valid policy tree.
     *
     * @return the depth of this node (0 for the root node, 1 for its
     * children, and so on)
     */
    int getDepth();

    /**
     * Returns the valid policy represented by this node.
     *
     * @return the String OID of the valid policy
     * represented by this node. For the root node, this method always returns
     * the special anyPolicy OID: "2.5.29.32.0".
     */
    String getValidPolicy();

    /**
     * Returns the set of policy qualifiers associated with the
     * valid policy represented by this node.
     *
     * @return an immutable Set of
     * PolicyQualifierInfos. For the root node, this
     * is always an empty Set.
     */
    Set<? extends PolicyQualifierInfo> getPolicyQualifiers();

    /**
     * Returns the set of expected policies that would satisfy this
     * node's valid policy in the next certificate to be processed.
     *
     * @return an immutable Set of expected policy
     * String OIDs. For the root node, this method
     * always returns a Set with one element, the
     * special anyPolicy OID: "2.5.29.32.0".
     */
    Set<String> getExpectedPolicies();

    /**
     * Returns the criticality indicator of the certificate policy extension
     * in the most recently processed certificate.
     *
     * @return true if extension marked critical,
     * false otherwise. For the root node, false
     * is always returned.
     */
    boolean isCritical();
}


import java.util.Arrays;
import org.checkerframework.checker.fenum.qual.FenumTop;

/*
 * This test case violates an assertion in the compiler.
 * It does not depend on the Fenum Checker, it breaks for any checker.
 */
public class IdentityArrayList {
    // The type of the third argument to Arrays.copyOf should be:
    // Class<? extends T @FenumTop []>
    // But the annotated JDK does not have annotations for the Fenum Checker.
    @SuppressWarnings("argument.type.incompatible")
    public <T> T[] toArray(T[] a) {
        // Warnings only with -Alint=cast:strict.
        // TODO:: warning: (cast.unsafe)
        // :: warning: [unchecked] unchecked cast
        return (T[]) Arrays.copyOf(null, 0, a.getClass());
    }

    public <T> T[] toArray2(T[] a) {
        wc(null, 0, new java.util.LinkedList<T[]>());
        // TODO:: warning: (cast.unsafe)
        // :: warning: [unchecked] unchecked cast
        return (T[]) myCopyOf(null, 0, a.getClass());
    }

    public static <T, U> T[] myCopyOf(
            U[] original, int newLength, Class<? extends T @FenumTop []> newType) {
        return null;
    }

    public static <T, U> T[] wc(
            U[] original, int newLength, java.util.List<? extends T @FenumTop []> arr) {
        return null;
    }
}


// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.binnavi.Gui.HotkeyDialog;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

/**
 * Renderer class for rendering the right half of hotkey section titles.
 */
public final class CRightTitleRenderer extends JComponent implements TableCellRenderer {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = 616276581744640519L;

  @Override
  public Component getTableCellRendererComponent(final JTable table,
      final Object value,
      final boolean isSelected,
      final boolean hasFocus,
      final int row,
      final int column) {
    return new CRightTitleComponent(value.toString());
  }
}


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2005 Sun Microsystems Inc. All Rights Reserved
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * https://opensso.dev.java.net/public/CDDLv1.0.html or
 * opensso/legal/CDDLv1.0.txt
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at opensso/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * $Id: Guid.java,v 1.4 2009/01/28 05:34:50 ww203982 Exp $
 *
 * Portions Copyright 2015 ForgeRock AS.
 */

package com.iplanet.ums;

import org.forgerock.opendj.ldap.DN;

/**
 * This class represents an LDAP entry and it provides
 * access to the ID (dn) and GUID of the given name. Every persistent object
 * (that is, entry in the Directory server) has a GUID (Globally Unique
 * Identifier) associated with it. Upon doing a getGuid() (getGuid() is a method
 * in the PersistentObject class) on an LDAP entry, this GUID object would be
 * returned (not a DN string or a guid in the LDAP sense). Methods of the Guid
 * object could then be used to get the actual DN, etc.
 *
 * @supported.all.api
 */
public class Guid {

    // holds the LDAP dn for the LDAP entry associated with this Guid object
    private DN _dn;

    // holds the unique ID for the LDAP entry associated with this Guid object
    private long _uniqueId;

    /**
     * Constructs a Guid object from the specified distinguished name.
     *
     * @param dn
     *            string representation of the distinguished name
     */
    public Guid(String dn) {
        _dn = DN.valueOf(dn);
        _uniqueId = -1;
    }

    /**
     * Constructs a Guid object from the specified unique ID.
     *
     * @param id
     *            unique ID
     */
    public Guid(long id) {
        _dn = DN.valueOf("");
        _uniqueId = id;
    }

    /**
     * Constructs a Guid object from the specified distinguished name and unique
     * ID.
     *
     * @param dn
     *            string representation of the distinguished name
     * @param id
     *            unique ID
     */
    public Guid(String dn, long id) {
        _dn = DN.valueOf(dn);
        _uniqueId = id;
    }

    /**
     * Returns the string representation of the distinguished name.
     *
     * @return the string representation of the distinguished name
     */
    public String getDn() {
        return _dn.toString();
    }

    /**
     * Sets the dn for this object. Note that the value is not persisted in
     * LDAP.
     *
     * @param dn
     *            string representation of the distinguished name
     */
    protected void setDn(String dn) {
        _dn = DN.valueOf(dn);
    }

    /**
     * Returns the nsuniqueID name in the Guid object associated with an LDAP
     * entry.
     *
     * @return the nsuniqueID name in the Guid object associated with an LDAP
     *         entry
     */
    public long getId() {
        return _uniqueId;
    }

    /**
     * Sets the nsuniqueID name in the Guid object associated with an LDAP entry
     * Note that the value is not persisted in LDAP.
     *
     * @param id
     *            the nsuniqueID name
     */
    protected void setId(long id) {
        _uniqueId = id;
    }

    /**
     * Determines if the current Guid is equal to the specified Guid.
     *
     * @param guid
     *            Guid to compare against the current Guid
     * @return true if the two Guids are the same
     */
    public boolean equals(Guid guid) {
        return _dn.equals(DN.valueOf(guid.getDn()));
    }

    /**
     * Compares two dn's for equality.
     *
     * @param dn1
     *            the first dn to compare
     * @param dn2
     *            the second dn to compare
     * @return true if the two dn's are equal
     */
    static boolean equals(String dn1, String dn2) {
        return DN.valueOf(dn1).equals(DN.valueOf(dn2));
    }

    /**
     * Returns the String form of this Guid object.
     *
     * @return the string representation of the Guid
     */
    public String toString() {
        return _dn.toString();
        // For future use
        // StringBuffer buff = new StringBuffer();
        // buff.append("DN : " + _dn + "\n");
        // buff.append("ID : " + _uniqueId + "\n");
        // return buff.toString();
    }
}


/**
 * angular-swx-local-storage - $localStorage service for use in your AngularJS applications.
 * @author Paul Massey, paul.massey@scriptwerx.io
 * @version v1.0.2
 * @build 35 - Mon Feb 29 2016 12:06:30 GMT+0000 (GMT)
 * @link http://www.scriptwerx.io
 * @license MIT
 */
(function(angular) {

    'use strict';

    /**
     * @ngdoc service
     * @name $localStorage
     *
     * @requires $window
     * @requires $location
     * @requires $cacheFactory
     *
     * @description Provides a key-value (string-object) storage, that is backed by localStorage with support for expiry (in days).
     * Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.
     *
     * @param {service} $window The $window service.
     * @param {service} $location The $location service.
     * @param {service} $cacheFactory The $cacheFactory service.
     *
     * @example
     * ```js
     * myApp.$inject = ['$localStorage'];
     * function myApp($localStorage) {
   *   // Your app code...
   * }
     *
     * angular
     *   .module('myApp', ['swxLocalStorage']);
     * ```
     *
     * @ngInject
     */
    $localStorage.$inject = ['$window', '$location', '$cacheFactory'];
    function $localStorage($window, $location, $cacheFactory) {

        /**
         * @private
         * @description
         * Create a prefix to be used by $window.localStorage
         */
        var prefix = $location.host().substring(0, $location.host().indexOf('.')) + '_',
            webStorage,
            oneDay = 24 * 60 * 60 * 1000,
            cache = $cacheFactory(prefix + 'cache'),
            service = this,
            isLocalStorageAvailable = true;

        /**
         * @ngdoc method
         * @name $localStorage.prefix
         * @methodOf $localStorage
         *
         * @description
         * Overrides the default domain prefix.
         *
         * N.B. Destroys the existing cache.
         *
         * @param {string} val The string to add to the persistent data prefix.
         *
         * @example
         * ```js
         * $localStorage.prefix('myPrefix');
         * ```
         */
        service.prefix = function(val) {
            prefix = val + '_';
            cache.destroy();
            cache = $cacheFactory(prefix + 'cache');
        };

        /**
         * @ngdoc method
         * @name $localStorage.put
         * @methodOf $localStorage
         *
         * @description Add data to storage
         *
         * @param {string} key The key to store the data with.
         * @param {*} value The data to store.
         * [@param {number} expires] (expiry in days)
         *
         * @example
         * ```js
         * $localStorage.put('myKey', { data: 'my_data' });
         * ```
         */
        service.put = function(key, value) {

            var dataToStore = { data: value };

            if (arguments.length > 2 && angular.isNumber(arguments[2])) {
                dataToStore.expires = new Date().getTime() + (arguments[2] * oneDay);
            }

            cache.put(key, dataToStore);

            if (isLocalStorageAvailable) {
                webStorage.setItem(prefix + key, angular.toJson(dataToStore, false));
            }

            return value;
        };

        /**
         * @ngdoc method
         * @name $localStorage.get
         * @methodOf $localStorage
         *
         * @description Get data from localStorage, will return from session cache if possible for greater performance.
         *
         * @param {String} key The key of the stored data to retrieve.
         * @returns {*} The value of the stored data or undefined.
         *
         * @example
         * ```js
         * $localStorage.get('myKey');
         * ```
         */
        service.get = function(key) {

            var item;

            if (cache.get(key)) {
                item = cache.get(key);
            }
            else if (isLocalStorageAvailable) {
                item = angular.fromJson(webStorage.getItem(prefix + key));
            }

            if (!item) {
                return void 0;
            }

            if (item.expires && item.expires < new Date().getTime()) {
                service.remove(key);
                return void 0;
            }

            cache.put(key, item);

            return item.data;
        };

        /**
         * @ngdoc method
         * @name $localStorage.remove
         * @methodOf $localStorage
         *
         * @descriotion Remove data from storage.
         *
         * @param {String} key The key of the stored data to remove.
         *
         * @example
         * ```js
         * $localStorage.remove('myKey');
         * ```
         */
        service.remove = function(key) {
            service.put(key, void 0);
            if (isLocalStorageAvailable) {
                webStorage.removeItem(prefix + key);
            }
            cache.remove(key);
        };

        /**
         * @ngdoc method
         * @name $localStorage.empty
         * @methodOf $localStorage
         *
         * @description Delete all data from session storage and localStorage.
         *
         * @example
         * ```js
         * $localStorage.empty();
         * ```
         */
        service.empty = function() {
            if (isLocalStorageAvailable) {
                webStorage.clear();
            }
            cache.removeAll();
        };

        /**
         * @private
         * @description
         * Check for $window.localStorage availability and functionality
         */
        (function() {

            // Some browsers will return true when in private browsing mode so test to make sure it's functional.
            try {
                webStorage = $window.localStorage;
                var key = 'swxTest_' + Math.round(Math.random() * 1e7);
                webStorage.setItem(key, 'test');
                webStorage.removeItem(key);
            }
            catch (e) {
                isLocalStorageAvailable = false;
            }

        })();
    }

    /**
     * @ngdoc overview
     * @name swxLocalStorage
     * @description
     * $localStorage service for use in your AngularJS applications.
     *
     * Provides a key-value (string-object) storage, that is backed by localStorage with support for expiry (in days).
     * Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.
     */
    angular
        .module('swxLocalStorage', [])
        .service('$localStorage', $localStorage);

})(window.angular);


#mpromise
==========

[![Build Status](https://travis-ci.org/aheckmann/mpromise.png)](https://travis-ci.org/aheckmann/mpromise)

A [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com).

## installation

```
$ npm install mpromise
```

## docs

An `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed.

The exports object is the Promise constructor.

```js
var Promise = require('mpromise');
```

The constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected).

```js
var promise = new Promise(fn);
```

This is the same as passing the `fn` to `onResolve` directly.

```js
var promise = new Promise;
promise.onResolve(function (err, args..) {
  ...
});
```

### Methods

####fulfill

Fulfilling a promise with values:

```js
var promise = new Promise;
promise.fulfill(args...);
```

If the promise has already been fulfilled or rejected, no action is taken.

####reject

Rejecting a promise with a reason:

```js
var promise = new Promise;
promise.reject(reason);
```

If the promise has already been fulfilled or rejected, no action is taken.

####resolve

Node.js callback style promise resolution `(err, args...)`:

```js
var promise = new Promise;
promise.resolve([reason], [arg1, arg2, ...]);
```

If the promise has already been fulfilled or rejected, no action is taken.

####onFulfill

To register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`.

```js
var promise = new Promise;
promise.onFulfill(function (a, b) {
  assert.equal(3, a + b);
});
promise.fulfill(1, 2);
```

The function will only be called once when the promise is fulfilled, never when rejected.

Registering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise.

```js
var promise = new Promise;
promise.fulfill(" :D ");
promise.onFulfill(function (arg) {
  console.log(arg); // logs " :D "
})
```

####onReject

To register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`.

```js
var promise = new Promise;
promise.onReject(function (reason) {
  assert.equal('sad', reason);
});
promise.reject('sad');
```

The function will only be called once when the promise is rejected, never when fulfilled.

Registering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise.

```js
var promise = new Promise;
promise.reject(" :( ");
promise.onReject(function (reason) {
  console.log(reason); // logs " :( "
})
```

####onResolve

Allows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject).

```js
// fulfillment
var promise = new Promise;
promise.onResolve(function (err, a, b) {
  console.log(a + b); // logs 3
});
promise.fulfill(1, 2);

// rejection
var promise = new Promise;
promise.onResolve(function (err) {
  if (err) {
    console.log(err.message); // logs "failed"
  }
});
promise.reject(new Error('failed'));
```

####then

Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.

Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests).

```js
// promise.then(onFulfill, onReject);

var p = new Promise;

p.then(function (arg) {
  return arg + 1;
}).then(function (arg) {
  throw new Error(arg + ' is an error!');
}).then(null, function (err) {
  assert.ok(err instanceof Error);
  assert.equal('2 is an error', err.message);
});
p.fullfill(1);
```

####end

Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception be rethrown.
You can pass an OnReject handler to `end` so that exceptions will be handled (like a final catch clause);
This method returns it's promise for easy use with `return`.

```js
var p = new Promise;
p.then(function(){ throw new Error('shucks') });
setTimeout(function () {
  p.fulfill();
  // error was caught and swallowed by the promise returned from
  // p.then(). we either have to always register handlers on
  // the returned promises or we can do the following...
}, 10);

// this time we use .end() which prevents catching thrown errors
var p = new Promise;
setTimeout(function () {
  p.fulfill(); // throws "shucks"
}, 10);
return p.then(function(){ throw new Error('shucks') }).end(); // <--
```

### chain

Allows direct promise to promise chaining (especially useful by a outside aggregating function). It doesn't use the asynchronous `resolve` algorithm and so excepts only another Promise as it's argument.

```js
function makeMeAPromise(i) {
  var p = new Promise;
  p.fulfill(i);
  return p;
}

var returnPromise = initialPromise = new Promise;
for (i=0; i<10; ++i)
    returnPromise = returnPromise.chain(makeMeAPromise(i));

initialPromise.fulfill();
return returnPromise;
```

###Event names

If you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively.

```js
Promise.SUCCESS = 'complete';
Promise.FAILURE = 'err';
```

###Luke, use the Source
For more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js).

## license

[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE)


# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

include(CMakeLanguageInformation)

# This file sets the basic flags for the Fortran language in CMake.
# It also loads the available platform file for the system-compiler
# if it exists.

set(_INCLUDED_FILE 0)

# Load compiler-specific information.
if(CMAKE_Fortran_COMPILER_ID)
  include(Compiler/${CMAKE_Fortran_COMPILER_ID}-Fortran OPTIONAL)
endif()

set(CMAKE_BASE_NAME)
get_filename_component(CMAKE_BASE_NAME "${CMAKE_Fortran_COMPILER}" NAME_WE)
# since the gnu compiler has several names force g++
if(CMAKE_COMPILER_IS_GNUG77)
  set(CMAKE_BASE_NAME g77)
endif()
if(CMAKE_Fortran_COMPILER_ID)
  include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_Fortran_COMPILER_ID}-Fortran OPTIONAL RESULT_VARIABLE _INCLUDED_FILE)
endif()
if (NOT _INCLUDED_FILE)
  include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL
          RESULT_VARIABLE _INCLUDED_FILE)
endif ()

# load any compiler-wrapper specific information
if (CMAKE_Fortran_COMPILER_WRAPPER)
  __cmake_include_compiler_wrapper(Fortran)
endif ()

# We specify the compiler information in the system file for some
# platforms, but this language may not have been enabled when the file
# was first included.  Include it again to get the language info.
# Remove this when all compiler info is removed from system files.
if (NOT _INCLUDED_FILE)
  include(Platform/${CMAKE_SYSTEM_NAME} OPTIONAL)
endif ()

if(CMAKE_Fortran_SIZEOF_DATA_PTR)
  foreach(f ${CMAKE_Fortran_ABI_FILES})
    include(${f})
  endforeach()
  unset(CMAKE_Fortran_ABI_FILES)
endif()

# This should be included before the _INIT variables are
# used to initialize the cache.  Since the rule variables
# have if blocks on them, users can still define them here.
# But, it should still be after the platform file so changes can
# be made to those values.

if(CMAKE_USER_MAKE_RULES_OVERRIDE)
  # Save the full path of the file so try_compile can use it.
  include(${CMAKE_USER_MAKE_RULES_OVERRIDE} RESULT_VARIABLE _override)
  set(CMAKE_USER_MAKE_RULES_OVERRIDE "${_override}")
endif()

if(CMAKE_USER_MAKE_RULES_OVERRIDE_Fortran)
  # Save the full path of the file so try_compile can use it.
  include(${CMAKE_USER_MAKE_RULES_OVERRIDE_Fortran} RESULT_VARIABLE _override)
  set(CMAKE_USER_MAKE_RULES_OVERRIDE_Fortran "${_override}")
endif()

if(NOT CMAKE_Fortran_COMPILE_OPTIONS_PIC)
  set(CMAKE_Fortran_COMPILE_OPTIONS_PIC ${CMAKE_C_COMPILE_OPTIONS_PIC})
endif()

if(NOT CMAKE_Fortran_COMPILE_OPTIONS_PIE)
  set(CMAKE_Fortran_COMPILE_OPTIONS_PIE ${CMAKE_C_COMPILE_OPTIONS_PIE})
endif()
if(NOT CMAKE_Fortran_LINK_OPTIONS_PIE)
  set(CMAKE_Fortran_LINK_OPTIONS_PIE ${CMAKE_C_LINK_OPTIONS_PIE})
endif()
if(NOT CMAKE_Fortran_LINK_OPTIONS_NO_PIE)
  set(CMAKE_Fortran_LINK_OPTIONS_NO_PIE ${CMAKE_C_LINK_OPTIONS_NO_PIE})
endif()

if(NOT CMAKE_Fortran_COMPILE_OPTIONS_DLL)
  set(CMAKE_Fortran_COMPILE_OPTIONS_DLL ${CMAKE_C_COMPILE_OPTIONS_DLL})
endif()

# Create a set of shared library variable specific to Fortran
# For 90% of the systems, these are the same flags as the C versions
# so if these are not set just copy the flags from the c version
if(NOT DEFINED CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS)
  set(CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_Fortran_FLAGS)
  set(CMAKE_SHARED_LIBRARY_Fortran_FLAGS ${CMAKE_SHARED_LIBRARY_C_FLAGS})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_Fortran_FLAGS)
  set(CMAKE_SHARED_LIBRARY_LINK_Fortran_FLAGS ${CMAKE_SHARED_LIBRARY_LINK_C_FLAGS})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG)
  set(CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG_SEP)
  set(CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_RPATH_LINK_Fortran_FLAG)
  set(CMAKE_SHARED_LIBRARY_RPATH_LINK_Fortran_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG})
endif()

if(NOT DEFINED CMAKE_EXE_EXPORTS_Fortran_FLAG)
  set(CMAKE_EXE_EXPORTS_Fortran_FLAG ${CMAKE_EXE_EXPORTS_C_FLAG})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_SONAME_Fortran_FLAG)
  set(CMAKE_SHARED_LIBRARY_SONAME_Fortran_FLAG ${CMAKE_SHARED_LIBRARY_SONAME_C_FLAG})
endif()

# for most systems a module is the same as a shared library
# so unless the variable CMAKE_MODULE_EXISTS is set just
# copy the values from the LIBRARY variables
if(NOT CMAKE_MODULE_EXISTS)
  set(CMAKE_SHARED_MODULE_Fortran_FLAGS ${CMAKE_SHARED_LIBRARY_Fortran_FLAGS})
  set(CMAKE_SHARED_MODULE_CREATE_Fortran_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS})
endif()

# repeat for modules
if(NOT DEFINED CMAKE_SHARED_MODULE_CREATE_Fortran_FLAGS)
  set(CMAKE_SHARED_MODULE_CREATE_Fortran_FLAGS ${CMAKE_SHARED_MODULE_CREATE_C_FLAGS})
endif()

if(NOT DEFINED CMAKE_SHARED_MODULE_Fortran_FLAGS)
  set(CMAKE_SHARED_MODULE_Fortran_FLAGS ${CMAKE_SHARED_MODULE_C_FLAGS})
endif()

if(NOT DEFINED CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG)
  set(CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG})
endif()

if(NOT DEFINED CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG_SEP)
  set(CMAKE_EXECUTABLE_RUNTIME_Fortran_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_Fortran_FLAG_SEP})
endif()

if(NOT DEFINED CMAKE_EXECUTABLE_RPATH_LINK_Fortran_FLAG)
  set(CMAKE_EXECUTABLE_RPATH_LINK_Fortran_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_Fortran_FLAG})
endif()

if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_Fortran_WITH_RUNTIME_PATH)
  set(CMAKE_SHARED_LIBRARY_LINK_Fortran_WITH_RUNTIME_PATH ${CMAKE_SHARED_LIBRARY_LINK_C_WITH_RUNTIME_PATH})
endif()

if(NOT CMAKE_INCLUDE_FLAG_Fortran)
  set(CMAKE_INCLUDE_FLAG_Fortran ${CMAKE_INCLUDE_FLAG_C})
endif()

set(CMAKE_VERBOSE_MAKEFILE FALSE CACHE BOOL "If this value is on, makefiles will be generated without the .SILENT directive, and all commands will be echoed to the console during the make.  This is useful for debugging only. With Visual Studio IDE projects all commands are done without /nologo.")

set(CMAKE_Fortran_FLAGS_INIT "$ENV{FFLAGS} ${CMAKE_Fortran_FLAGS_INIT}")

cmake_initialize_per_config_variable(CMAKE_Fortran_FLAGS "Flags used by the Fortran compiler")

if(NOT CMAKE_Fortran_COMPILER_LAUNCHER AND DEFINED ENV{CMAKE_Fortran_COMPILER_LAUNCHER})
  set(CMAKE_Fortran_COMPILER_LAUNCHER "$ENV{CMAKE_Fortran_COMPILER_LAUNCHER}"
    CACHE STRING "Compiler launcher for Fortran.")
endif()

include(CMakeCommonLanguageInclude)

# now define the following rule variables
# CMAKE_Fortran_CREATE_SHARED_LIBRARY
# CMAKE_Fortran_CREATE_SHARED_MODULE
# CMAKE_Fortran_COMPILE_OBJECT
# CMAKE_Fortran_LINK_EXECUTABLE

# create a Fortran shared library
if(NOT CMAKE_Fortran_CREATE_SHARED_LIBRARY)
  set(CMAKE_Fortran_CREATE_SHARED_LIBRARY
      "<CMAKE_Fortran_COMPILER> <CMAKE_SHARED_LIBRARY_Fortran_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>")
endif()

# create a Fortran shared module just copy the shared library rule
if(NOT CMAKE_Fortran_CREATE_SHARED_MODULE)
  set(CMAKE_Fortran_CREATE_SHARED_MODULE ${CMAKE_Fortran_CREATE_SHARED_LIBRARY})
endif()

# Create a static archive incrementally for large object file counts.
# If CMAKE_Fortran_CREATE_STATIC_LIBRARY is set it will override these.
if(NOT DEFINED CMAKE_Fortran_ARCHIVE_CREATE)
  set(CMAKE_Fortran_ARCHIVE_CREATE "<CMAKE_AR> qc <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
if(NOT DEFINED CMAKE_Fortran_ARCHIVE_APPEND)
  set(CMAKE_Fortran_ARCHIVE_APPEND "<CMAKE_AR> q <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
if(NOT DEFINED CMAKE_Fortran_ARCHIVE_FINISH)
  set(CMAKE_Fortran_ARCHIVE_FINISH "<CMAKE_RANLIB> <TARGET>")
endif()

# compile a Fortran file into an object file
# (put -o after -c to workaround bug in at least one mpif77 wrapper)
if(NOT CMAKE_Fortran_COMPILE_OBJECT)
  set(CMAKE_Fortran_COMPILE_OBJECT
    "<CMAKE_Fortran_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -c <SOURCE> -o <OBJECT>")
endif()

# link a fortran program
if(NOT CMAKE_Fortran_LINK_EXECUTABLE)
  set(CMAKE_Fortran_LINK_EXECUTABLE
    "<CMAKE_Fortran_COMPILER> <CMAKE_Fortran_LINK_FLAGS> <LINK_FLAGS> <FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
endif()

if(CMAKE_Fortran_STANDARD_LIBRARIES_INIT)
  set(CMAKE_Fortran_STANDARD_LIBRARIES "${CMAKE_Fortran_STANDARD_LIBRARIES_INIT}"
    CACHE STRING "Libraries linked by default with all Fortran applications.")
  mark_as_advanced(CMAKE_Fortran_STANDARD_LIBRARIES)
endif()

# set this variable so we can avoid loading this more than once.
set(CMAKE_Fortran_INFORMATION_LOADED 1)


# -*- coding: utf-8 -*-
#
#  SelfTest/Hash/common.py: Common code for Crypto.SelfTest.Hash
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain.  To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================

"""Self-testing for PyCrypto hash modules"""

import unittest
from binascii import a2b_hex, b2a_hex, hexlify

from Crypto.Util.py3compat import b, _memoryview
from Crypto.Util.strxor import strxor_c

class _NoDefault: pass        # sentinel object
def _extract(d, k, default=_NoDefault):
    """Get an item from a dictionary, and remove it from the dictionary."""
    try:
        retval = d[k]
    except KeyError:
        if default is _NoDefault:
            raise
        return default
    del d[k]
    return retval

# Generic cipher test case
class CipherSelfTest(unittest.TestCase):

    def __init__(self, module, params):
        unittest.TestCase.__init__(self)
        self.module = module

        # Extract the parameters
        params = params.copy()
        self.description = _extract(params, 'description')
        self.key = b(_extract(params, 'key'))
        self.plaintext = b(_extract(params, 'plaintext'))
        self.ciphertext = b(_extract(params, 'ciphertext'))
        self.module_name = _extract(params, 'module_name', None)
        self.assoc_data = _extract(params, 'assoc_data', None)
        self.mac = _extract(params, 'mac', None)
        if self.assoc_data:
            self.mac = b(self.mac)

        mode = _extract(params, 'mode', None)
        self.mode_name = str(mode)

        if mode is not None:
            # Block cipher
            self.mode = getattr(self.module, "MODE_" + mode)

            self.iv = _extract(params, 'iv', None)
            if self.iv is None:
                self.iv = _extract(params, 'nonce', None)
            if self.iv is not None:
                self.iv = b(self.iv)

        else:
            # Stream cipher
            self.mode = None
            self.iv = _extract(params, 'iv', None)
            if self.iv is not None:
                self.iv = b(self.iv)

        self.extra_params = params

    def shortDescription(self):
        return self.description

    def _new(self):
        params = self.extra_params.copy()
        key = a2b_hex(self.key)

        old_style = []
        if self.mode is not None:
            old_style = [ self.mode ]
        if self.iv is not None:
            old_style += [ a2b_hex(self.iv) ]

        return self.module.new(key, *old_style, **params)

    def isMode(self, name):
        if not hasattr(self.module, "MODE_"+name):
            return False
        return self.mode == getattr(self.module, "MODE_"+name)

    def runTest(self):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)
        assoc_data = []
        if self.assoc_data:
            assoc_data = [ a2b_hex(b(x)) for x in self.assoc_data]

        ct = None
        pt = None

        #
        # Repeat the same encryption or decryption twice and verify
        # that the result is always the same
        #
        for i in range(2):
            cipher = self._new()
            decipher = self._new()

            # Only AEAD modes
            for comp in assoc_data:
                cipher.update(comp)
                decipher.update(comp)

            ctX = b2a_hex(cipher.encrypt(plaintext))
            ptX = b2a_hex(decipher.decrypt(ciphertext))

            if ct:
                self.assertEqual(ct, ctX)
                self.assertEqual(pt, ptX)
            ct, pt = ctX, ptX

        self.assertEqual(self.ciphertext, ct)  # encrypt
        self.assertEqual(self.plaintext, pt)   # decrypt

        if self.mac:
            mac = b2a_hex(cipher.digest())
            self.assertEqual(self.mac, mac)
            decipher.verify(a2b_hex(self.mac))

class CipherStreamingSelfTest(CipherSelfTest):

    def shortDescription(self):
        desc = self.module_name
        if self.mode is not None:
            desc += " in %s mode" % (self.mode_name,)
        return "%s should behave like a stream cipher" % (desc,)

    def runTest(self):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # The cipher should work like a stream cipher

        # Test counter mode encryption, 3 bytes at a time
        ct3 = []
        cipher = self._new()
        for i in range(0, len(plaintext), 3):
            ct3.append(cipher.encrypt(plaintext[i:i+3]))
        ct3 = b2a_hex(b("").join(ct3))
        self.assertEqual(self.ciphertext, ct3)  # encryption (3 bytes at a time)

        # Test counter mode decryption, 3 bytes at a time
        pt3 = []
        cipher = self._new()
        for i in range(0, len(ciphertext), 3):
            pt3.append(cipher.encrypt(ciphertext[i:i+3]))
        # PY3K: This is meant to be text, do not change to bytes (data)
        pt3 = b2a_hex(b("").join(pt3))
        self.assertEqual(self.plaintext, pt3)  # decryption (3 bytes at a time)

class RoundtripTest(unittest.TestCase):
    def __init__(self, module, params):
        from Crypto import Random
        unittest.TestCase.__init__(self)
        self.module = module
        self.iv = Random.get_random_bytes(module.block_size)
        self.key = b(params['key'])
        self.plaintext = 100 * b(params['plaintext'])
        self.module_name = params.get('module_name', None)

    def shortDescription(self):
        return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)

    def runTest(self):

        ## ECB mode
        mode = self.module.MODE_ECB
        encryption_cipher = self.module.new(a2b_hex(self.key), mode)
        ciphertext = encryption_cipher.encrypt(self.plaintext)
        decryption_cipher = self.module.new(a2b_hex(self.key), mode)
        decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
        self.assertEqual(self.plaintext, decrypted_plaintext)

class IVLengthTest(unittest.TestCase):
    def __init__(self, module, params):
        unittest.TestCase.__init__(self)
        self.module = module
        self.key = b(params['key'])

    def shortDescription(self):
        return "Check that all modes except MODE_ECB and MODE_CTR require an IV of the proper length"

    def runTest(self):
        self.assertRaises(TypeError, self.module.new, a2b_hex(self.key),
                self.module.MODE_ECB, b(""))

    def _dummy_counter(self):
        return "\0" * self.module.block_size

class NoDefaultECBTest(unittest.TestCase):
    def __init__(self, module, params):
        unittest.TestCase.__init__(self)
        self.module = module
        self.key = b(params['key'])

    def runTest(self):
        self.assertRaises(TypeError, self.module.new, a2b_hex(self.key))

class ByteArrayTest(unittest.TestCase):
    """Verify we can use bytearray's for encrypting and decrypting"""

    def __init__(self, module, params):
        unittest.TestCase.__init__(self)
        self.module = module

        # Extract the parameters
        params = params.copy()
        self.description = _extract(params, 'description')
        self.key = b(_extract(params, 'key'))
        self.plaintext = b(_extract(params, 'plaintext'))
        self.ciphertext = b(_extract(params, 'ciphertext'))
        self.module_name = _extract(params, 'module_name', None)
        self.assoc_data = _extract(params, 'assoc_data', None)
        self.mac = _extract(params, 'mac', None)
        if self.assoc_data:
            self.mac = b(self.mac)

        mode = _extract(params, 'mode', None)
        self.mode_name = str(mode)

        if mode is not None:
            # Block cipher
            self.mode = getattr(self.module, "MODE_" + mode)

            self.iv = _extract(params, 'iv', None)
            if self.iv is None:
                self.iv = _extract(params, 'nonce', None)
            if self.iv is not None:
                self.iv = b(self.iv)
        else:
            # Stream cipher
            self.mode = None
            self.iv = _extract(params, 'iv', None)
            if self.iv is not None:
                self.iv = b(self.iv)

        self.extra_params = params

    def _new(self):
        params = self.extra_params.copy()
        key = a2b_hex(self.key)

        old_style = []
        if self.mode is not None:
            old_style = [ self.mode ]
        if self.iv is not None:
            old_style += [ a2b_hex(self.iv) ]

        return self.module.new(key, *old_style, **params)

    def runTest(self):

        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)
        assoc_data = []
        if self.assoc_data:
            assoc_data = [ bytearray(a2b_hex(b(x))) for x in self.assoc_data]

        cipher = self._new()
        decipher = self._new()

        # Only AEAD modes
        for comp in assoc_data:
            cipher.update(comp)
            decipher.update(comp)

        ct = b2a_hex(cipher.encrypt(bytearray(plaintext)))
        pt = b2a_hex(decipher.decrypt(bytearray(ciphertext)))

        self.assertEqual(self.ciphertext, ct)  # encrypt
        self.assertEqual(self.plaintext, pt)   # decrypt

        if self.mac:
            mac = b2a_hex(cipher.digest())
            self.assertEqual(self.mac, mac)
            decipher.verify(bytearray(a2b_hex(self.mac)))

class MemoryviewTest(unittest.TestCase):
    """Verify we can use memoryviews for encrypting and decrypting"""

    def __init__(self, module, params):
        unittest.TestCase.__init__(self)
        self.module = module

        # Extract the parameters
        params = params.copy()
        self.description = _extract(params, 'description')
        self.key = b(_extract(params, 'key'))
        self.plaintext = b(_extract(params, 'plaintext'))
        self.ciphertext = b(_extract(params, 'ciphertext'))
        self.module_name = _extract(params, 'module_name', None)
        self.assoc_data = _extract(params, 'assoc_data', None)
        self.mac = _extract(params, 'mac', None)
        if self.assoc_data:
            self.mac = b(self.mac)

        mode = _extract(params, 'mode', None)
        self.mode_name = str(mode)

        if mode is not None:
            # Block cipher
            self.mode = getattr(self.module, "MODE_" + mode)

            self.iv = _extract(params, 'iv', None)
            if self.iv is None:
                self.iv = _extract(params, 'nonce', None)
            if self.iv is not None:
                self.iv = b(self.iv)
        else:
            # Stream cipher
            self.mode = None
            self.iv = _extract(params, 'iv', None)
            if self.iv is not None:
                self.iv = b(self.iv)

        self.extra_params = params

    def _new(self):
        params = self.extra_params.copy()
        key = a2b_hex(self.key)

        old_style = []
        if self.mode is not None:
            old_style = [ self.mode ]
        if self.iv is not None:
            old_style += [ a2b_hex(self.iv) ]

        return self.module.new(key, *old_style, **params)

    def runTest(self):

        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)
        assoc_data = []
        if self.assoc_data:
            assoc_data = [ memoryview(a2b_hex(b(x))) for x in self.assoc_data]

        cipher = self._new()
        decipher = self._new()

        # Only AEAD modes
        for comp in assoc_data:
            cipher.update(comp)
            decipher.update(comp)

        ct = b2a_hex(cipher.encrypt(memoryview(plaintext)))
        pt = b2a_hex(decipher.decrypt(memoryview(ciphertext)))

        self.assertEqual(self.ciphertext, ct)  # encrypt
        self.assertEqual(self.plaintext, pt)   # decrypt

        if self.mac:
            mac = b2a_hex(cipher.digest())
            self.assertEqual(self.mac, mac)
            decipher.verify(memoryview(a2b_hex(self.mac)))

def make_block_tests(module, module_name, test_data, additional_params=dict()):
    tests = []
    extra_tests_added = False
    for i in range(len(test_data)):
        row = test_data[i]

        # Build the "params" dictionary with
        # - plaintext
        # - ciphertext
        # - key
        # - mode (default is ECB)
        # - (optionally) description
        # - (optionally) any other parameter that this cipher mode requires
        params = {}
        if len(row) == 3:
            (params['plaintext'], params['ciphertext'], params['key']) = row
        elif len(row) == 4:
            (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
        elif len(row) == 5:
            (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
            params.update(extra_params)
        else:
            raise AssertionError("Unsupported tuple size %d" % (len(row),))

        if not "mode" in params:
            params["mode"] = "ECB"

        # Build the display-name for the test
        p2 = params.copy()
        p_key = _extract(p2, 'key')
        p_plaintext = _extract(p2, 'plaintext')
        p_ciphertext = _extract(p2, 'ciphertext')
        p_mode = _extract(p2, 'mode')
        p_description = _extract(p2, 'description', None)

        if p_description is not None:
            description = p_description
        elif p_mode == 'ECB' and not p2:
            description = "p=%s, k=%s" % (p_plaintext, p_key)
        else:
            description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
        name = "%s #%d: %s" % (module_name, i+1, description)
        params['description'] = name
        params['module_name'] = module_name
        params.update(additional_params)

        # Add extra test(s) to the test suite before the current test
        if not extra_tests_added:
            tests += [
                RoundtripTest(module, params),
                IVLengthTest(module, params),
                NoDefaultECBTest(module, params),
                ByteArrayTest(module, params),
            ]
            extra_tests_added = True

        # Add the current test to the test suite
        tests.append(CipherSelfTest(module, params))

    return tests

def make_stream_tests(module, module_name, test_data):
    tests = []
    extra_tests_added = False
    for i in range(len(test_data)):
        row = test_data[i]

        # Build the "params" dictionary
        params = {}
        if len(row) == 3:
            (params['plaintext'], params['ciphertext'], params['key']) = row
        elif len(row) == 4:
            (params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
        elif len(row) == 5:
            (params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
            params.update(extra_params)
        else:
            raise AssertionError("Unsupported tuple size %d" % (len(row),))

        # Build the display-name for the test
        p2 = params.copy()
        p_key = _extract(p2, 'key')
        p_plaintext = _extract(p2, 'plaintext')
        p_ciphertext = _extract(p2, 'ciphertext')
        p_description = _extract(p2, 'description', None)

        if p_description is not None:
            description = p_description
        elif not p2:
            description = "p=%s, k=%s" % (p_plaintext, p_key)
        else:
            description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
        name = "%s #%d: %s" % (module_name, i+1, description)
        params['description'] = name
        params['module_name'] = module_name

        # Add extra test(s) to the test suite before the current test
        if not extra_tests_added:
            tests += [
                ByteArrayTest(module, params),
            ]

            import sys
            if sys.version[:3] != '2.6':
                tests.append(MemoryviewTest(module, params))
            extra_tests_added = True

        # Add the test to the test suite
        tests.append(CipherSelfTest(module, params))
        tests.append(CipherStreamingSelfTest(module, params))
    return tests

# vim:set ts=4 sw=4 sts=4 expandtab:


/*
copyright 2004 Alexander Malmberg <alexander@malmberg.org>

Test -base's cluster of NSString classes. This tests the optimized
implementations of many NSString methods in GSString and its subclasses.
*/

#import "NSString_tests.h"

#import <Foundation/NSString.h>

int main(int argc,char **argv)
{
  TestNSStringClass([NSString class]);
  return 0;
}


SRC_DIR = client/js
BUILD_DIR = build

PREFIX = .
DIST_DIR = client/js

BASE_FILES = ${SRC_DIR}/md5.js\
	${SRC_DIR}/store.js\
	${SRC_DIR}/cookies.js\
	${SRC_DIR}/dateformat.js\
	${SRC_DIR}/json.js\
	${SRC_DIR}/im.js

MODULES = ${SRC_DIR}/intro.js\
	${BASE_FILES}\
	${SRC_DIR}/outro.js

IMJS = ${DIST_DIR}/im.compiled.js
IMJS_MIN = ${DIST_DIR}/im.min.js

COMPILER = java -jar ${BUILD_DIR}/google-compiler-20100616.jar

all: imjs min
	@@echo "Ajax IM build complete."

imjs: ${IMJS}

${IMJS}: ${MODULES}
	@@echo "Building" ${IMJS}
	@@cat ${MODULES} | sed 's/debug = true/debug = false/' > ${IMJS}

min: ${IMJS_MIN}

${IMJS_MIN}: ${IMJS}
	@@echo "Building" ${IMJS_MIN}

	@@head -21 ${IMJS} > ${IMJS_MIN}
	@@${COMPILER} --js ${IMJS} --warning_level QUIET >> ${IMJS_MIN}
	@@rm -f ${IMJS}

clean:
	@@echo "Removing built files"
	@@rm -f ${IMJS}
	@@rm -f ${IMJS_MIN}


import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';

export default createSvgIcon(
  <path d="M22 8l-4-4v3H3v2h15v3l4-4zM2 16l4 4v-3h15v-2H6v-3l-4 4z" />
, 'SyncAlt');


<?php

namespace spec\Prophecy\Argument\Token;

use PhpSpec\ObjectBehavior;

class CallbackTokenSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('get_class');
    }

    function it_implements_TokenInterface()
    {
        $this->shouldBeAnInstanceOf('Prophecy\Argument\Token\TokenInterface');
    }

    function it_is_not_last()
    {
        $this->shouldNotBeLast();
    }

    function it_scores_7_if_argument_matches_callback()
    {
        $this->beConstructedWith(function ($argument) { return 2 === $argument; });

        $this->scoreArgument(2)->shouldReturn(7);
    }

    function it_does_not_scores_if_argument_does_not_match_callback()
    {
        $this->beConstructedWith(function ($argument) { return 2 === $argument; });

        $this->scoreArgument(5)->shouldReturn(false);
    }

    function its_string_representation_should_tell_that_its_callback()
    {
        $this->__toString()->shouldReturn('callback()');
    }
}


# This source code refers to The Go Authors for copyright purposes.
# The master list of authors is in the main Go distribution,
# visible at http://tip.golang.org/AUTHORS.


<!doctype html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="./../../assets/css/combined.css">
	<link rel="shortcut icon" href="./../../favicon.ico" />

	<title>Theme Introduction - Classes - FuelPHP Documentation</title>

					FuelPHP, a PHP 5.3 Framework
					Documentation

				<form id="google_search">

						<input type="submit" name="search_submit" id="search_submit" value="search" />
						<input type="text" value="" id="search_input" name="search_input" />

				</form>

			table of contents

Theme class

Introduction

				The Theme class provides theming to your application.

				A theme will group theme templates (views) and assets, and allows you to change the look and feel of your application by
				switching the active theme.

				Like modules and packages, themes can be stored in multiple locations. You can define the paths to these locations in the
				configuration file,	or add them to the theme instance at runtime. A theme is identified by its name, which must be equal
				to the name of the theme folder	used in one of the theme locations. If the theme is defined in multiple locations,
				the first one found will be used.

Theme information

				You can provide setup information for your theme through the theme information file.
				This file has a fixed name for all your themes, which can be configured through the global configuration file. It also has an
				option to make this file required.

				The format of an information file follows the same rules as normal configuration files, and supports the same file types.
				An information file can contain a special section called 'options'. Options can be get or set from your code, and can be used
				to control certain characteristics of your theme, for example a color used, or a custom css filename to select a color scheme.

At this moment, information files are read-only. You can alter the options at runtime, but you can not write them back.

Theme assets

				You theme is likely to have assets (images, javascript or css files). Assets have to be installed inside the DOCROOT
				so that the browser can load them. You can elect to install the assets inside the theme directory, which implies this has to be inside
				the DOCROOT, or have the theme files outside the DOCROOT, and the theme assets in a separate folder
				inside the DOCROOT. Alternatively, you can specify a base URL for your assets, for example if you use a CDN.

				The following logic is used to determine the location of the theme asset files:

						If your asset folder is a URL, it is suffixed by the theme name, and used are the base URL for your assets.

						If the theme folder is inside the DOCROOT, and it contains a folder with the name of the configured
						assets_folder, this will be the URL for all your theme assets.

						If the theme folder is inside the DOCROOT, and it does NOT contains a folder with the name of the configured
						assets_folder, the assets_folder will be assumed to be the root of all your theme assets,
						to which the name of the theme will be appended.

						If the theme folder is outside the DOCROOT, the assets_folder will be assumed to be the
						root of all your theme assets, to which the name of the theme will be appended.

					If you want to use the built-in Asset class support, your asset folder must have a compatible folder structure, with /css, /img and /js subfolders.

Theme templates or layouts

				The Theme works with theme templates or layouts, which are view files that define the layout of your page.

Theme template partials

				The variable sections of the template can be defined using template partials, which are separate views build to provide a
				section of the page. In larger application designs, partials are often generated by separate code, accessed via HMVC calls.

				The contents of a partials section can be accessed through a view variable $partial, an array with an entry for each of the partial
				sections defined. You access a section using it's name. So for a partial section called 'sidebar', you would use echo $partial['sidebar']; in your page template.

Partial chrome

				'Chrome' is a term used in UI interface design, and describes the design and styling of a window border. In the context of the Theme
				class, it is a view that can be used to encapsulate a template partial section, which allows you to style that section independent
				of the template itself and of the partial output. Chrome will only be generated if there were partials to render.

				For example, if you have a UI with windows, some of which can be opened and closed, some of which can be moved, and some are static,
				you can use different chrome templates assigned to each of the template sections representing such a window. Each chrome template
				will contain the HTML and javascript code to achieve the desired functionality. From your application code, you can control this
				by simply assigning the correct chrome template.

Example:

<?php
class Homepage extends \Controller
{
	/**
	 * load the theme template, set the page title and the menu's
	 */
	public function before()
	{
		// load the theme template
		$this->theme = \Theme::instance();

		// set the page template
		$this->theme->set_template('layouts/homepage');

		// set the page title (can be chained to set_template() too)
		$this->theme->get_template()->set('title', 'My homepage');

		// set the homepage navigation menu
		$this->theme->set_partial('navbar', 'homepage/navbar');

		// define chrome with rounded window borders for the sidebar section
		$this->theme->set_chrome('sidebar', 'chrome/borders/rounded', 'partial');

		// set the partials for the homepage sidebar content
		$this->theme->set_partial('sidebar', 'homepage/widgets/login');
		$this->theme->set_partial('sidebar', 'homepage/widgets/news')->set('users', Model_News::latest(5));

		// call the user model to get the list of logged in users, pass that to the users sidebar partial
		$this->theme->set_partial('sidebar', 'homepage/widgets/users')->set('users', Model_User::logged_in_users());
	}

	/**
	 * A simple example. A normal action method would probably have code to
	 * retrieve data from models and pass this to a partial view...
	 */
	public function action_index()
	{
		// the homepage has a flash image banner
		$this->theme->set_partial('banner', 'homepage/banner');

		// a block of static content
		$this->theme->set_partial('banner', 'homepage/content');

		// and two link lists and a copyright block
		$this->theme->set_partial('footerleft', 'homepage/shortcuts');
		$this->theme->set_partial('footercenter', 'homepage/links');
		$this->theme->set_partial('footerright', 'homepage/copyright');
	}

	/**
	 * keep the after() as standard as possible to allow custom responses from actions
	 */
	public function after($response)
	{
		// If no response object was returned by the action,
		if (empty($response) or  ! $response instanceof Response)
		{
			// render the defined template
			$response = \Response::forge(\Theme::instance()->render());
		}

		return parent::after($response);
	}
}

Configuration

				The Theme class is configured through the app/config/theme.php configuration file.
				A configuration file with the defaults mentioned below is already present in fuel/core/config.
				You can override this configuration by copying this config file to your application config directory, and modify that file as needed.

						Param
						Type
						Default
						Description

						active
						string

'default'

						The active theme to use. You can select one later using the active() method.

						fallback
						string

'default'

						The fallback theme to use. If a view is not found in the active theme, this theme is used as a fallback. You can select one later using the fallback() method.

						paths
						array

array()

						The theme search paths. They are searched in the order given. You can add them later using the add_path() or add_paths() methods.

						assets_folder
						string

'assets'

						The folder inside the theme to be used to store assets.  This is relative to the theme's path.

						view_ext
						string

'.html'

						The extension for theme view files.

						info_file_name
						string

'theme.info'

						The theme info file name.

						require_info_file
						boolean

false

						Whether to require a theme info file.

						info_file_type
						string

'php'

						File type of the theme info file.  Possible values: php, ini, json and yaml.

						use_modules
						boolean

false

						Whether to automatically prefix the view filename with the current module name.

Example config:

// Inside app/config/theme.php

return array(
	'active' => 'default',
	'fallback' => 'default',
	'paths' => array(			// theme files are outside the DOCROOT here
		APPPATH.'themes',
	),
	'assets_folder' => 'themes',	// so this implies <localpath>/public/themes/<themename>...
	'view_ext' => '.html',
	'info_file_name' => 'theme.info',
	'require_info_file' => false,
	'info_file_type' => 'php',
);

Once you have your settings in place you can start using the Theme class.

				© FuelPHP Development Team 2010-2013 - FuelPHP is released under the MIT license.


/*
 *  Copyright 2016 Adobe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

window.CQ.CoreComponentsIT.Breadcrumb.v1 = window.CQ.CoreComponentsIT.Breadcrumb.v1 || {}

/**
 * Test for the breadcrumb component
 */
;(function(h, $) {
    "use strict";

    // shortcuts
    var c = window.CQ.CoreComponentsIT.commons;
    var breadcrumb = window.CQ.CoreComponentsIT.Breadcrumb.v1;

    /**
     * Before Test Case
     */
    breadcrumb.tcExecuteBeforeTest = function(breadcrumbRT, pageRT) {
        return new h.TestCase("Create Sample Content")
            // common set up
            .execTestCase(c.tcExecuteBeforeTest)

            // TODO : turn this into a loop or recursive

            // create level 1
            .execFct(function(opts, done) {
                c.createPage(c.template, c.rootPage, "level_1", "level_1", done, pageRT);
            })
            // create level 2
            .execFct(function(opts, done) {
                c.createPage(c.template, h.param("level_1")(), "level_2", "level_2", done, pageRT);
            })
            // create level 3
            .execFct(function(opts, done) {
                c.createPage(c.template, h.param("level_2")(), "level_3", "level_3", done, pageRT);
            })
            // create level 4
            .execFct(function(opts, done) {
                c.createPage(c.template, h.param("level_3")(), "level_4", "level_4", done, pageRT);
            })
            // create level 5
            .execFct(function(opts, done) {
                c.createPage(c.template, h.param("level_4")(), "level_5", "level_5", done, pageRT);
            })

            // create a proxy component
            .execFct(function(opts, done) {
                c.createProxyComponent(breadcrumbRT, c.proxyPath, "compPath", done);
            })

            // add the component to the deepest level
            .execFct(function(opts, done) {
                c.addComponent(h.param("compPath")(opts), h.param("level_5")(opts) + c.relParentCompPath, "cmpPath", done);
            })

            // open the deepest level in the editor
            .navigateTo("/editor.html%level_5%.html");
    };

    /**
     * After Test Case
     */
    breadcrumb.tcExecuteAfterTest = function() {
        return new h.TestCase("Clean up after Test")
            // common clean up
            .execTestCase(c.tcExecuteAfterTest)
            // delete the test page we created
            .execFct(function(opts, done) {
                c.deletePage(h.param("level_1")(opts), done);
            })

            // delete the test page we created
            .execFct(function(opts, done) {
                c.deleteProxyComponent(h.param("compPath")(opts), done);
            });

    };

    /**
     * Test: Set the Hide Current flag
     */
    breadcrumb.testHideCurrent = function(itemSelector, tcExecuteBeforeTest, tcExecuteAfterTest) {
        return new h.TestCase("Check Hide Current Flag", {
            execBefore: tcExecuteBeforeTest,
            execAfter: tcExecuteAfterTest })

            // check first if current page is shown
            .config.changeContext(c.getContentFrame)
            // the li entry for current page
            .assert.exist(itemSelector.active + ":contains('level_5')", true)
            .config.resetContext()

            // Open the configuration dialog
            .execTestCase(c.tcOpenConfigureDialog("cmpPath"))
            // check the checkbox th make the current page hidden
            .click("input[name='./hideCurrent']")
            // Close the configuration dialog
            .execTestCase(c.tcSaveConfigureDialog)
            // got to the content frame
            .config.changeContext(c.getContentFrame)

            // the li entry for current page should not be found
            .assert.exist(itemSelector.active + ":contains('level_5')", false);
    };

    /**
     * Test: Set the Show Hidden flag
     */
    breadcrumb.testShowHidden = function(itemSelector, tcExecuteBeforeTest, tcExecuteAfterTest) {
        return new h.TestCase("Check Show Hidden Flag", {
            execBefore: tcExecuteBeforeTest,
            execAfter: tcExecuteAfterTest })

            // TODO : should be moved to its own execBefore function
            // set one of the pages has hidden first
            .execFct(function(opts, done) {
                $.ajax({
                    url: h.param("level_3")(),
                    method: "POST",
                    complete: done,
                    // POST data to be send in the request
                    data: {
                        "_charset_": "utf-8",
                        "./jcr:content/hideInNav": "true"
                    }
                });
            })
            // reload the page to make the change visible
            .reload()

            // go to content frame
            .config.changeContext(c.getContentFrame)
            // verify level 3 is no longer available
            .assert.exist(itemSelector.normal + " > a:contains('level_3')", false)
            // go back to edit frame
            .config.resetContext()

            // Open the configuration dialog
            .execTestCase(c.tcOpenConfigureDialog("cmpPath"))
            // check the checkbox to show hidden pages
            .click("input[name='./showHidden']")
            // Close the configuration dialog
            .execTestCase(c.tcSaveConfigureDialog)
            // got to the content frame
            .config.changeContext(c.getContentFrame)

            // the level 3 should be visible again
            .assert.exist(itemSelector.normal + " > a:contains('level_3')", true);
    };

    /**
     * Test: Change the start level
     */
    breadcrumb.changeStartLevel = function(itemSelector, tcExecuteBeforeTest, tcExecuteAfterTest) {
        return new h.TestCase("Change Start Level", {
            execBefore: tcExecuteBeforeTest,
            execAfter: tcExecuteAfterTest })

            // check the current number of parent levels
            .assert.isTrue(function() {
                return h.find(itemSelector.normal, "iframe#ContentFrame").size() === 6;
            })

            // Open the configuration dialog
            .execTestCase(c.tcOpenConfigureDialog("cmpPath"))
            // check the current config setting
            .assert.isTrue(function() {
                return h.find("input[name='./startLevel']").val() === "2";
            })
            // increase start level by 2
            .fillInput("input[name='./startLevel']", 4)
            // Close the configuration dialog
            .execTestCase(c.tcSaveConfigureDialog)

            // check the current number
            .assert.isTrue(function() {
                return h.find(itemSelector.normal, "iframe#ContentFrame").size() === 4;
            });
    };

    /**
     * Test: Set the start level to lowest allowed value of 0.
     * This shouldn't render anything since level 0 is not a valid page.
     */
    breadcrumb.setZeroStartLevel = function(itemSelector, tcExecuteBeforeTest, tcExecuteAfterTest) {
        return new h.TestCase("Set Start Level to 0", {
            execBefore: tcExecuteBeforeTest,
            execAfter: tcExecuteAfterTest })

            // check the current number of items
            .assert.isTrue(function() {
                return h.find(itemSelector.normal, "iframe#ContentFrame").size() === 6;
            })

            // Open the configuration dialog
            .execTestCase(c.tcOpenConfigureDialog("cmpPath"))
            // set it to 0
            .fillInput("input[name='./startLevel']", 0)
            // Close the configuration dialog
            .asserts.visible(c.selConfigDialog)
            // check if element name is marked as invalid
            .asserts.isTrue(function() {
                return h.find("input[name='./startLevel'].is-invalid").size() === 1;
            });
    };

    /**
     * Test: Set the start level to the highest possible value 100.
     * This shouldn't render anything since level 100 is higher the the current's page level.
     */
    breadcrumb.set100StartLevel = function(itemSelector, tcExecuteBeforeTest, tcExecuteAfterTest) {
        return new h.TestCase("Set Start Level to 100", {
            execBefore: tcExecuteBeforeTest,
            execAfter: tcExecuteAfterTest })

            // check the current number of items
            .assert.isTrue(function() {
                return h.find(itemSelector.normal, "iframe#ContentFrame").size() === 6;
            })
            // Open the configuration dialog
            .execTestCase(c.tcOpenConfigureDialog("cmpPath"))
            // set it to 100
            .fillInput("input[name='./startLevel']", 100)
            // Close the configuration dialog
            .execTestCase(c.tcSaveConfigureDialog)

            // 100 is higher then current level so nothing should get rendered
            .assert.isTrue(function() {
                return h.find(itemSelector.normal, "iframe#ContentFrame").size() === 0 &&
                    h.find(itemSelector.active, "iframe#ContentFrame").size() === 0;
            });
    };

}(hobs, jQuery));