code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const ChartRadar32: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default ChartRadar32;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/chart--radar/32.d.ts | TypeScript | mit | 222 |
package net.nemerosa.ontrack.model.form;
import net.nemerosa.ontrack.common.BaseException;
public class FormFieldNotFoundException extends BaseException {
public FormFieldNotFoundException(String name) {
super("Field %s not found in form.", name);
}
}
| nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/form/FormFieldNotFoundException.java | Java | mit | 270 |
package ios.ac.cn;
import java.util.Arrays;
public class ThreeSumClosest {
/*
* 以 i 为起点, j, k 在 [i+1:) 上游走,使得 num[i] + num[j] + num[k] 尽力逼近 target
*/
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int closestVal = num[0] + num[1] + num[2];
int closestGap = Math.abs(closestVal - target);
for (int i = 0; i < num.length - 2; i++) {
int j = i + 1, k = num.length - 1;
while (j < k) {
int curVal = num[i] + num[j] + num[k];
int curGap = Math.abs(curVal - target);
if (curGap < closestGap) {
closestGap = curGap;
closestVal = curVal;
}
// 使得 curVal 不断逼近 target
if (curVal > target) {
--k;
} else {
++j;
}
}
}
return closestVal;
}
public static void main(String[] args) {
int[] num = { 1, 2, 4, 8, 16, 32, 64, 128 };
System.out.print(new ThreeSumClosest().threeSumClosest(num, 82));
}
}
| wh-acmer/minixalpha-acm | LeetCode/Java/Solution/src/ios/ac/cn/ThreeSumClosest.java | Java | mit | 946 |
using System;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using Umbraco.Core;
namespace Umbraco.Web.Editors
{
/// <summary>
/// This is used to auto-select specific actions on controllers that would otherwise be ambiguous based on a single parameter type
/// </summary>
/// <remarks>
/// As an example, lets say we have 2 methods: GetChildren(int id) and GetChildren(Guid id), by default Web Api won't allow this since
/// it won't know what to select, but if this Tuple is passed in new Tuple{string, string}("GetChildren", "id")
/// </remarks>
internal class ParameterSwapControllerActionSelector : ApiControllerActionSelector
{
private readonly ParameterSwapInfo[] _actions;
/// <summary>
/// Constructor accepting a list of action name + parameter name
/// </summary>
/// <param name="actions"></param>
public ParameterSwapControllerActionSelector(params ParameterSwapInfo[] actions)
{
_actions = actions;
}
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
var found = _actions.FirstOrDefault(x => controllerContext.Request.RequestUri.GetLeftPart(UriPartial.Path).InvariantEndsWith(x.ActionName));
if (found != null)
{
var id = HttpUtility.ParseQueryString(controllerContext.Request.RequestUri.Query).Get(found.ParamName);
if (id != null)
{
var idTypes = found.SupportedTypes;
foreach (var idType in idTypes)
{
var converted = id.TryConvertTo(idType);
if (converted)
{
var method = MatchByType(idType, controllerContext, found);
if (method != null)
return method;
}
}
}
}
return base.SelectAction(controllerContext);
}
private static ReflectedHttpActionDescriptor MatchByType(Type idType, HttpControllerContext controllerContext, ParameterSwapInfo found)
{
var controllerType = controllerContext.Controller.GetType();
var methods = controllerType.GetMethods().Where(info => info.Name == found.ActionName).ToArray();
if (methods.Length > 1)
{
//choose the one that has the parameter with the T type
var method = methods.FirstOrDefault(x => x.GetParameters().FirstOrDefault(p => p.Name == found.ParamName && p.ParameterType == idType) != null);
return new ReflectedHttpActionDescriptor(controllerContext.ControllerDescriptor, method);
}
return null;
}
internal class ParameterSwapInfo
{
public string ActionName { get; private set; }
public string ParamName { get; private set; }
public Type[] SupportedTypes { get; private set; }
public ParameterSwapInfo(string actionName, string paramName, params Type[] supportedTypes)
{
ActionName = actionName;
ParamName = paramName;
SupportedTypes = supportedTypes;
}
}
}
} | gavinfaux/Umbraco-CMS | src/Umbraco.Web/Editors/ParameterSwapControllerActionSelector.cs | C# | mit | 3,432 |
<?php
namespace Kahlan\Block;
use Closure;
use Throwable;
use Exception;
use Kahlan\Expectation;
use Kahlan\ExternalExpectation;
use Kahlan\Log;
use Kahlan\Scope\Specification as Scope;
use Kahlan\Suite;
class Specification extends \Kahlan\Block
{
/**
* List of expectations.
* @var Expectation[]
*/
protected $_expectations = [];
/**
* Constructor.
*
* @param array $config The Suite config array. Options are:
* -`'closure'` _Closure_ : the closure of the test.
* -`'message'` _string_ : the spec message.
* -`'scope'` _string_ : supported scope are `'normal'` & `'focus'`.
*/
public function __construct($config = [])
{
$defaults = [
'message' => 'passes'
];
$config += $defaults;
$config['message'] = 'it ' . $config['message'];
parent::__construct($config);
$this->_scope = new Scope(['block' => $this]);
$this->_closure = $this->_bindScope($this->_closure);
}
/**
* Reset the specification.
*
* @return Expectation
*/
public function reset()
{
$this->_passed = null;
$this->_expectations = [];
$this->_log = new Log([
'block' => $this,
'backtrace' => $this->_backtrace
]);
return $this;
}
/**
* The assert statement.
*
* @param array $config The config array. Options are:
* -`'actual'` _mixed_ : the actual value.
* -`'timeout'` _integer_ : the timeout value.
* Or:
* -`'handler'` _Closure_ : a delegated handler to execute.
* -`'type'` _string_ : delegated handler supported exception type.
*
* @return Expectation
*/
public function assert($config = [])
{
return $this->_expectations[] = new Expectation($config);
}
/**
* The expect statement (assert shortcut).
*
* @param mixed $actual The expression to check
*
* @return Expectation
*/
public function expect($actual, $timeout = 0)
{
return $this->_expectations[] = new Expectation(compact('actual', 'timeout'));
}
/**
* The waitsFor statement.
*
* @param mixed $actual The expression to check
*
* @return mixed
*/
public function waitsFor($actual, $timeout = 0)
{
$timeout = $timeout ?: $this->timeout();
$closure = $actual instanceof Closure ? $actual : function () use ($actual) {
return $actual;
};
$spec = new static(['closure' => $closure]);
return $this->expect($spec, $timeout);
}
/**
* Spec execution helper.
*/
protected function _execute()
{
$result = null;
$spec = function () {
$this->_expectations = [];
$closure = $this->_closure;
$result = $this->_suite->runBlock($this, $closure, 'specification');
foreach ($this->_expectations as $expectation) {
$this->_passed = $expectation->process() && $this->_passed;
}
return $result;
};
$suite = $this->suite();
return $spec();
}
/**
* Start spec execution helper.
*/
protected function _blockStart()
{
$this->report('specStart', $this);
if ($this->_parent) {
$this->_parent->runCallbacks('beforeEach');
}
}
/**
* End spec execution helper.
*/
protected function _blockEnd($runAfterEach = true)
{
$type = $this->log()->type();
foreach ($this->_expectations as $expectation) {
if (!($logs = $expectation->logs()) && $type !== 'errored') {
$this->log()->type('pending');
}
foreach ($logs as $log) {
$this->log($log['type'], $log);
}
}
if ($type === 'passed' && empty($this->_expectations)) {
$this->log()->type('pending');
}
$type = $this->log()->type();
if ($type === 'failed' || $type === 'errored') {
$this->_passed = false;
$this->suite()->failure();
}
if ($this->_parent && $runAfterEach) {
try {
$this->_parent->runCallbacks('afterEach');
} catch (Exception $exception) {
$this->_exception($exception, true);
}
}
$this->summary()->log($this->log());
$this->report('specEnd', $this->log());
Suite::current()->scope()->clear();
$this->suite()->autoclear();
}
/**
* Returns execution log.
*
* @return array
*/
public function logs()
{
$logs = [];
foreach ($this->_expectations as $expectation) {
foreach ($expectation->logs() as $log) {
$logs[] = $log;
}
}
return $logs;
}
}
| crysalead/kahlan | src/Block/Specification.php | PHP | mit | 5,127 |
<?php
namespace Concrete\Core\Page\Search\ColumnSet\Column;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Column\ColumnInterface;
use Concrete\Core\Search\Column\PagerColumnInterface;
use Concrete\Core\Search\ItemList\Pager\PagerProviderInterface;
class DateLastModified extends Column implements PagerColumnInterface
{
public function getColumnKey()
{
return 'c.cDateModified';
}
public function getColumnName()
{
return t('Last Modified');
}
public function getColumnCallback()
{
return array('\Concrete\Core\Page\Search\ColumnSet\DefaultSet', 'getCollectionDateModified');
}
public function filterListAtOffset(PagerProviderInterface $itemList, $mixed)
{
$query = $itemList->getQueryObject();
$sort = $this->getColumnSortDirection() == 'desc' ? '<' : '>';
$where = sprintf('(c.cDateModified, p.cID) %s (:sortDate, :sortID)', $sort);
$query->setParameter('sortDate', $mixed->getCollectionDateLastModified());
$query->setParameter('sortID', $mixed->getCollectionID());
$query->andWhere($where);
}
}
| acliss19xx/concrete5 | concrete/src/Page/Search/ColumnSet/Column/DateLastModified.php | PHP | mit | 1,145 |
require "active_record/relation/from_clause"
require "active_record/relation/query_attribute"
require "active_record/relation/where_clause"
require "active_record/relation/where_clause_factory"
require 'active_model/forbidden_attributes_protection'
require 'active_support/core_ext/string/filters'
module ActiveRecord
module QueryMethods
extend ActiveSupport::Concern
include ActiveModel::ForbiddenAttributesProtection
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
# In this case, #where must be chained with #not to return a new relation.
class WhereChain
include ActiveModel::ForbiddenAttributesProtection
def initialize(scope)
@scope = scope
end
# Returns a new relation expressing WHERE + NOT condition according to
# the conditions in the arguments.
#
# #not accepts conditions as a string, array, or hash. See QueryMethods#where for
# more details on each format.
#
# User.where.not("name = 'Jon'")
# # SELECT * FROM users WHERE NOT (name = 'Jon')
#
# User.where.not(["name = ?", "Jon"])
# # SELECT * FROM users WHERE NOT (name = 'Jon')
#
# User.where.not(name: "Jon")
# # SELECT * FROM users WHERE name != 'Jon'
#
# User.where.not(name: nil)
# # SELECT * FROM users WHERE name IS NOT NULL
#
# User.where.not(name: %w(Ko1 Nobu))
# # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
#
# User.where.not(name: "Jon", role: "admin")
# # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
def not(opts, *rest)
opts = sanitize_forbidden_attributes(opts)
where_clause = @scope.send(:where_clause_factory).build(opts, rest)
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
@scope.where_clause += where_clause.invert
@scope
end
end
FROZEN_EMPTY_ARRAY = [].freeze
Relation::MULTI_VALUE_METHODS.each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_values
@values[:#{name}] || FROZEN_EMPTY_ARRAY
end
def #{name}_values=(values)
assert_mutability!
@values[:#{name}] = values
end
CODE
end
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_value # def readonly_value
@values[:#{name}] # @values[:readonly]
end # end
CODE
end
Relation::SINGLE_VALUE_METHODS.each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_value=(value) # def readonly_value=(value)
assert_mutability! # assert_mutability!
@values[:#{name}] = value # @values[:readonly] = value
end # end
CODE
end
Relation::CLAUSE_METHODS.each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_clause # def where_clause
@values[:#{name}] || new_#{name}_clause # @values[:where] || new_where_clause
end # end
#
def #{name}_clause=(value) # def where_clause=(value)
assert_mutability! # assert_mutability!
@values[:#{name}] = value # @values[:where] = value
end # end
CODE
end
def bound_attributes
if limit_value && !string_containing_comma?(limit_value)
limit_bind = Attribute.with_cast_value(
"LIMIT".freeze,
connection.sanitize_limit(limit_value),
Type::Value.new,
)
end
if offset_value
offset_bind = Attribute.with_cast_value(
"OFFSET".freeze,
offset_value.to_i,
Type::Value.new,
)
end
connection.combine_bind_parameters(
from_clause: from_clause.binds,
join_clause: arel.bind_values,
where_clause: where_clause.binds,
having_clause: having_clause.binds,
limit: limit_bind,
offset: offset_bind,
)
end
FROZEN_EMPTY_HASH = {}.freeze
def create_with_value # :nodoc:
@values[:create_with] || FROZEN_EMPTY_HASH
end
alias extensions extending_values
# Specify relationships to be included in the result set. For
# example:
#
# users = User.includes(:address)
# users.each do |user|
# user.address.city
# end
#
# allows you to access the +address+ attribute of the +User+ model without
# firing an additional query. This will often result in a
# performance improvement over a simple join.
#
# You can also specify multiple relationships, like this:
#
# users = User.includes(:address, :friends)
#
# Loading nested relationships is possible using a Hash:
#
# users = User.includes(:address, friends: [:address, :followers])
#
# === conditions
#
# If you want to add conditions to your included models you'll have
# to explicitly reference them. For example:
#
# User.includes(:posts).where('posts.name = ?', 'example')
#
# Will throw an error, but this will work:
#
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
#
# Note that #includes works with association names while #references needs
# the actual table name.
def includes(*args)
check_if_method_has_arguments!(:includes, args)
spawn.includes!(*args)
end
def includes!(*args) # :nodoc:
args.reject!(&:blank?)
args.flatten!
self.includes_values |= args
self
end
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
#
# User.eager_load(:posts)
# # SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
# # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
# # "users"."id"
def eager_load(*args)
check_if_method_has_arguments!(:eager_load, args)
spawn.eager_load!(*args)
end
def eager_load!(*args) # :nodoc:
self.eager_load_values += args
self
end
# Allows preloading of +args+, in the same way that #includes does:
#
# User.preload(:posts)
# # SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
def preload(*args)
check_if_method_has_arguments!(:preload, args)
spawn.preload!(*args)
end
def preload!(*args) # :nodoc:
self.preload_values += args
self
end
# Use to indicate that the given +table_names+ are referenced by an SQL string,
# and should therefore be JOINed in any query rather than loaded separately.
# This method only works in conjunction with #includes.
# See #includes for more details.
#
# User.includes(:posts).where("posts.name = 'foo'")
# # Doesn't JOIN the posts table, resulting in an error.
#
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
# # Query now knows the string references posts, so adds a JOIN
def references(*table_names)
check_if_method_has_arguments!(:references, table_names)
spawn.references!(*table_names)
end
def references!(*table_names) # :nodoc:
table_names.flatten!
table_names.map!(&:to_s)
self.references_values |= table_names
self
end
# Works in two unique ways.
#
# First: takes a block so it can be used just like +Array#select+.
#
# Model.all.select { |m| m.field == value }
#
# This will build an array of objects from the database for the scope,
# converting them into an array and iterating through them using +Array#select+.
#
# Second: Modifies the SELECT statement for the query so that only certain
# fields are retrieved:
#
# Model.select(:field)
# # => [#<Model id: nil, field: "value">]
#
# Although in the above example it looks as though this method returns an
# array, it actually returns a relation object and can have other query
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
#
# The argument to the method can also be an array of fields.
#
# Model.select(:field, :other_field, :and_one_more)
# # => [#<Model id: nil, field: "value", other_field: "value", and_one_more: "value">]
#
# You can also use one or more strings, which will be used unchanged as SELECT fields.
#
# Model.select('field AS field_one', 'other_field AS field_two')
# # => [#<Model id: nil, field: "value", other_field: "value">]
#
# If an alias was specified, it will be accessible from the resulting objects:
#
# Model.select('field AS field_one').first.field_one
# # => "value"
#
# Accessing attributes of an object that do not have fields retrieved by a select
# except +id+ will throw ActiveModel::MissingAttributeError:
#
# Model.select(:field).first.other_field
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
def select(*fields)
return super if block_given?
raise ArgumentError, 'Call this with at least one field' if fields.empty?
spawn._select!(*fields)
end
def _select!(*fields) # :nodoc:
fields.flatten!
fields.map! do |field|
klass.attribute_alias?(field) ? klass.attribute_alias(field).to_sym : field
end
self.select_values += fields
self
end
# Allows to specify a group attribute:
#
# User.group(:name)
# # SELECT "users".* FROM "users" GROUP BY name
#
# Returns an array with distinct records based on the +group+ attribute:
#
# User.select([:id, :name])
# # => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">]
#
# User.group(:name)
# # => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
#
# User.group('name AS grouped_name, age')
# # => [#<User id: 3, name: "Foo", age: 21, ...>, #<User id: 2, name: "Oscar", age: 21, ...>, #<User id: 5, name: "Foo", age: 23, ...>]
#
# Passing in an array of attributes to group by is also supported.
#
# User.select([:id, :first_name]).group(:id, :first_name).first(3)
# # => [#<User id: 1, first_name: "Bill">, #<User id: 2, first_name: "Earl">, #<User id: 3, first_name: "Beto">]
def group(*args)
check_if_method_has_arguments!(:group, args)
spawn.group!(*args)
end
def group!(*args) # :nodoc:
args.flatten!
self.group_values += args
self
end
# Allows to specify an order attribute:
#
# User.order(:name)
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
#
# User.order(email: :desc)
# # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
#
# User.order(:name, email: :desc)
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
#
# User.order('name')
# # SELECT "users".* FROM "users" ORDER BY name
#
# User.order('name DESC')
# # SELECT "users".* FROM "users" ORDER BY name DESC
#
# User.order('name DESC, email')
# # SELECT "users".* FROM "users" ORDER BY name DESC, email
def order(*args)
check_if_method_has_arguments!(:order, args)
spawn.order!(*args)
end
def order!(*args) # :nodoc:
preprocess_order_args(args)
self.order_values += args
self
end
# Replaces any existing order defined on the relation with the specified order.
#
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
#
# Subsequent calls to order on the same relation will be appended. For example:
#
# User.order('email DESC').reorder('id ASC').order('name ASC')
#
# generates a query with 'ORDER BY id ASC, name ASC'.
def reorder(*args)
check_if_method_has_arguments!(:reorder, args)
spawn.reorder!(*args)
end
def reorder!(*args) # :nodoc:
preprocess_order_args(args)
self.reordering_value = true
self.order_values = args
self
end
VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock,
:limit, :offset, :joins, :includes, :from,
:readonly, :having])
# Removes an unwanted relation that is already defined on a chain of relations.
# This is useful when passing around chains of relations and would like to
# modify the relations without reconstructing the entire chain.
#
# User.order('email DESC').unscope(:order) == User.all
#
# The method arguments are symbols which correspond to the names of the methods
# which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES.
# The method can also be called with multiple arguments. For example:
#
# User.order('email DESC').select('id').where(name: "John")
# .unscope(:order, :select, :where) == User.all
#
# One can additionally pass a hash as an argument to unscope specific +:where+ values.
# This is done by passing a hash with a single key-value pair. The key should be
# +:where+ and the value should be the where value to unscope. For example:
#
# User.where(name: "John", active: true).unscope(where: :name)
# == User.where(active: true)
#
# This method is similar to #except, but unlike
# #except, it persists across merges:
#
# User.order('email').merge(User.except(:order))
# == User.order('email')
#
# User.order('email').merge(User.unscope(:order))
# == User.all
#
# This means it can be used in association definitions:
#
# has_many :comments, -> { unscope(where: :trashed) }
#
def unscope(*args)
check_if_method_has_arguments!(:unscope, args)
spawn.unscope!(*args)
end
def unscope!(*args) # :nodoc:
args.flatten!
self.unscope_values += args
args.each do |scope|
case scope
when Symbol
symbol_unscoping(scope)
when Hash
scope.each do |key, target_value|
if key != :where
raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key."
end
target_values = Array(target_value).map(&:to_s)
self.where_clause = where_clause.except(*target_values)
end
else
raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example."
end
end
self
end
# Performs a joins on +args+. The given symbol(s) should match the name of
# the association(s).
#
# User.joins(:posts)
# # SELECT "users".*
# # FROM "users"
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
#
# Multiple joins:
#
# User.joins(:posts, :account)
# # SELECT "users".*
# # FROM "users"
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# # INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"
#
# Nested joins:
#
# User.joins(posts: [:comments])
# # SELECT "users".*
# # FROM "users"
# # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# # INNER JOIN "comments" "comments_posts"
# # ON "comments_posts"."post_id" = "posts"."id"
#
# You can use strings in order to customize your joins:
#
# User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
# # SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
def joins(*args)
check_if_method_has_arguments!(:joins, args)
spawn.joins!(*args)
end
def joins!(*args) # :nodoc:
args.compact!
args.flatten!
self.joins_values += args
self
end
# Performs a left outer joins on +args+:
#
# User.left_outer_joins(:posts)
# => SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"
#
def left_outer_joins(*args)
check_if_method_has_arguments!(:left_outer_joins, args)
args.compact!
args.flatten!
spawn.left_outer_joins!(*args)
end
alias :left_joins :left_outer_joins
def left_outer_joins!(*args) # :nodoc:
self.left_outer_joins_values += args
self
end
alias :left_joins! :left_outer_joins!
# Returns a new relation, which is the result of filtering the current relation
# according to the conditions in the arguments.
#
# #where accepts conditions in one of several formats. In the examples below, the resulting
# SQL is given as an illustration; the actual query generated may be different depending
# on the database adapter.
#
# === string
#
# A single string, without additional arguments, is passed to the query
# constructor as an SQL fragment, and used in the where clause of the query.
#
# Client.where("orders_count = '2'")
# # SELECT * from clients where orders_count = '2';
#
# Note that building your own string from user input may expose your application
# to injection attacks if not done properly. As an alternative, it is recommended
# to use one of the following methods.
#
# === array
#
# If an array is passed, then the first element of the array is treated as a template, and
# the remaining elements are inserted into the template to generate the condition.
# Active Record takes care of building the query to avoid injection attacks, and will
# convert from the ruby type to the database type where needed. Elements are inserted
# into the string in the order in which they appear.
#
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
#
# Alternatively, you can use named placeholders in the template, and pass a hash as the
# second element of the array. The names in the template are replaced with the corresponding
# values from the hash.
#
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
#
# This can make for more readable code in complex queries.
#
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
# than the previous methods; you are responsible for ensuring that the values in the template
# are properly quoted. The values are passed to the connector for quoting, but the caller
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
# the values are inserted using the same escapes as the Ruby core method +Kernel::sprintf+.
#
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
#
# If #where is called with multiple arguments, these are treated as if they were passed as
# the elements of a single array.
#
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
#
# When using strings to specify conditions, you can use any operator available from
# the database. While this provides the most flexibility, you can also unintentionally introduce
# dependencies on the underlying database. If your code is intended for general consumption,
# test with multiple database backends.
#
# === hash
#
# #where will also accept a hash condition, in which the keys are fields and the values
# are values to be searched for.
#
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
#
# User.where({ name: "Joe", email: "joe@example.com" })
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
#
# User.where({ name: ["Alice", "Bob"]})
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
#
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
#
# In the case of a belongs_to relationship, an association key can be used
# to specify the model if an ActiveRecord object is used as the value.
#
# author = Author.find(1)
#
# # The following queries will be equivalent:
# Post.where(author: author)
# Post.where(author_id: author)
#
# This also works with polymorphic belongs_to relationships:
#
# treasure = Treasure.create(name: 'gold coins')
# treasure.price_estimates << PriceEstimate.create(price: 125)
#
# # The following queries will be equivalent:
# PriceEstimate.where(estimate_of: treasure)
# PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
#
# === Joins
#
# If the relation is the result of a join, you may create a condition which uses any of the
# tables in the join. For string and array conditions, use the table name in the condition.
#
# User.joins(:posts).where("posts.created_at < ?", Time.now)
#
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
#
# User.joins(:posts).where({ "posts.published" => true })
# User.joins(:posts).where({ posts: { published: true } })
#
# === no argument
#
# If no argument is passed, #where returns a new instance of WhereChain, that
# can be chained with #not to return a new relation that negates the where clause.
#
# User.where.not(name: "Jon")
# # SELECT * FROM users WHERE name != 'Jon'
#
# See WhereChain for more details on #not.
#
# === blank condition
#
# If the condition is any blank-ish object, then #where is a no-op and returns
# the current relation.
def where(opts = :chain, *rest)
if :chain == opts
WhereChain.new(spawn)
elsif opts.blank?
self
else
spawn.where!(opts, *rest)
end
end
def where!(opts, *rest) # :nodoc:
opts = sanitize_forbidden_attributes(opts)
references!(PredicateBuilder.references(opts)) if Hash === opts
self.where_clause += where_clause_factory.build(opts, rest)
self
end
# Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.
#
# Post.where(trashed: true).where(trashed: false)
# # WHERE `trashed` = 1 AND `trashed` = 0
#
# Post.where(trashed: true).rewhere(trashed: false)
# # WHERE `trashed` = 0
#
# Post.where(active: true).where(trashed: true).rewhere(trashed: false)
# # WHERE `active` = 1 AND `trashed` = 0
#
# This is short-hand for <tt>unscope(where: conditions.keys).where(conditions)</tt>.
# Note that unlike reorder, we're only unscoping the named conditions -- not the entire where statement.
def rewhere(conditions)
unscope(where: conditions.keys).where(conditions)
end
# Returns a new relation, which is the logical union of this relation and the one passed as an
# argument.
#
# The two relations must be structurally compatible: they must be scoping the same model, and
# they must differ only by #where (if no #group has been defined) or #having (if a #group is
# present). Neither relation may have a #limit, #offset, or #distinct set.
#
# Post.where("id = 1").or(Post.where("author_id = 3"))
# # SELECT `posts`.* FROM `posts` WHERE (('id = 1' OR 'author_id = 3'))
#
def or(other)
unless other.is_a? Relation
raise ArgumentError, "You have passed #{other.class.name} object to #or. Pass an ActiveRecord::Relation object instead."
end
spawn.or!(other)
end
def or!(other) # :nodoc:
incompatible_values = structurally_incompatible_values_for_or(other)
unless incompatible_values.empty?
raise ArgumentError, "Relation passed to #or must be structurally compatible. Incompatible values: #{incompatible_values}"
end
self.where_clause = self.where_clause.or(other.where_clause)
self.having_clause = self.having_clause.or(other.having_clause)
self
end
# Allows to specify a HAVING clause. Note that you can't use HAVING
# without also specifying a GROUP clause.
#
# Order.having('SUM(price) > 30').group('user_id')
def having(opts, *rest)
opts.blank? ? self : spawn.having!(opts, *rest)
end
def having!(opts, *rest) # :nodoc:
opts = sanitize_forbidden_attributes(opts)
references!(PredicateBuilder.references(opts)) if Hash === opts
self.having_clause += having_clause_factory.build(opts, rest)
self
end
# Specifies a limit for the number of records to retrieve.
#
# User.limit(10) # generated SQL has 'LIMIT 10'
#
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
def limit(value)
spawn.limit!(value)
end
def limit!(value) # :nodoc:
if string_containing_comma?(value)
# Remove `string_containing_comma?` when removing this deprecation
ActiveSupport::Deprecation.warn(<<-WARNING.squish)
Passing a string to limit in the form "1,2" is deprecated and will be
removed in Rails 5.1. Please call `offset` explicitly instead.
WARNING
end
self.limit_value = value
self
end
# Specifies the number of rows to skip before returning rows.
#
# User.offset(10) # generated SQL has "OFFSET 10"
#
# Should be used with order.
#
# User.offset(10).order("name ASC")
def offset(value)
spawn.offset!(value)
end
def offset!(value) # :nodoc:
self.offset_value = value
self
end
# Specifies locking settings (default to +true+). For more information
# on locking, please see ActiveRecord::Locking.
def lock(locks = true)
spawn.lock!(locks)
end
def lock!(locks = true) # :nodoc:
case locks
when String, TrueClass, NilClass
self.lock_value = locks || true
else
self.lock_value = false
end
self
end
# Returns a chainable relation with zero records.
#
# The returned relation implements the Null Object pattern. It is an
# object with defined null behavior and always returns an empty array of
# records without querying the database.
#
# Any subsequent condition chained to the returned relation will continue
# generating an empty relation and will not fire any query to the database.
#
# Used in cases where a method or scope could return zero records but the
# result needs to be chainable.
#
# For example:
#
# @posts = current_user.visible_posts.where(name: params[:name])
# # the visible_posts method is expected to return a chainable Relation
#
# def visible_posts
# case role
# when 'Country Manager'
# Post.where(country: country)
# when 'Reviewer'
# Post.published
# when 'Bad User'
# Post.none # It can't be chained if [] is returned.
# end
# end
#
def none
where("1=0").extending!(NullRelation)
end
def none! # :nodoc:
where!("1=0").extending!(NullRelation)
end
# Sets readonly attributes for the returned relation. If value is
# true (default), attempting to update a record will result in an error.
#
# users = User.readonly
# users.first.save
# => ActiveRecord::ReadOnlyRecord: User is marked as readonly
def readonly(value = true)
spawn.readonly!(value)
end
def readonly!(value = true) # :nodoc:
self.readonly_value = value
self
end
# Sets attributes to be used when creating new records from a
# relation object.
#
# users = User.where(name: 'Oscar')
# users.new.name # => 'Oscar'
#
# users = users.create_with(name: 'DHH')
# users.new.name # => 'DHH'
#
# You can pass +nil+ to #create_with to reset attributes:
#
# users = users.create_with(nil)
# users.new.name # => 'Oscar'
def create_with(value)
spawn.create_with!(value)
end
def create_with!(value) # :nodoc:
if value
value = sanitize_forbidden_attributes(value)
self.create_with_value = create_with_value.merge(value)
else
self.create_with_value = {}
end
self
end
# Specifies table from which the records will be fetched. For example:
#
# Topic.select('title').from('posts')
# # SELECT title FROM posts
#
# Can accept other relation objects. For example:
#
# Topic.select('title').from(Topic.approved)
# # SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
#
# Topic.select('a.title').from(Topic.approved, :a)
# # SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
#
def from(value, subquery_name = nil)
spawn.from!(value, subquery_name)
end
def from!(value, subquery_name = nil) # :nodoc:
self.from_clause = Relation::FromClause.new(value, subquery_name)
self
end
# Specifies whether the records should be unique or not. For example:
#
# User.select(:name)
# # Might return two records with the same name
#
# User.select(:name).distinct
# # Returns 1 record per distinct name
#
# User.select(:name).distinct.distinct(false)
# # You can also remove the uniqueness
def distinct(value = true)
spawn.distinct!(value)
end
alias uniq distinct
deprecate uniq: :distinct
# Like #distinct, but modifies relation in place.
def distinct!(value = true) # :nodoc:
self.distinct_value = value
self
end
alias uniq! distinct!
deprecate uniq!: :distinct!
# Used to extend a scope with additional methods, either through
# a module or through a block provided.
#
# The object returned is a relation, which can be further extended.
#
# === Using a module
#
# module Pagination
# def page(number)
# # pagination code goes here
# end
# end
#
# scope = Model.all.extending(Pagination)
# scope.page(params[:page])
#
# You can also pass a list of modules:
#
# scope = Model.all.extending(Pagination, SomethingElse)
#
# === Using a block
#
# scope = Model.all.extending do
# def page(number)
# # pagination code goes here
# end
# end
# scope.page(params[:page])
#
# You can also use a block and a module list:
#
# scope = Model.all.extending(Pagination) do
# def per_page(number)
# # pagination code goes here
# end
# end
def extending(*modules, &block)
if modules.any? || block
spawn.extending!(*modules, &block)
else
self
end
end
def extending!(*modules, &block) # :nodoc:
modules << Module.new(&block) if block
modules.flatten!
self.extending_values += modules
extend(*extending_values) if extending_values.any?
self
end
# Reverse the existing order clause on the relation.
#
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
def reverse_order
spawn.reverse_order!
end
def reverse_order! # :nodoc:
orders = order_values.uniq
orders.reject!(&:blank?)
self.order_values = reverse_sql_order(orders)
self
end
# Returns the Arel object associated with the relation.
def arel # :nodoc:
@arel ||= build_arel
end
private
def assert_mutability!
raise ImmutableRelation if @loaded
raise ImmutableRelation if defined?(@arel) && @arel
end
def build_arel
arel = Arel::SelectManager.new(table)
build_joins(arel, joins_values.flatten) unless joins_values.empty?
build_left_outer_joins(arel, left_outer_joins_values.flatten) unless left_outer_joins_values.empty?
arel.where(where_clause.ast) unless where_clause.empty?
arel.having(having_clause.ast) unless having_clause.empty?
if limit_value
if string_containing_comma?(limit_value)
arel.take(connection.sanitize_limit(limit_value))
else
arel.take(Arel::Nodes::BindParam.new)
end
end
arel.skip(Arel::Nodes::BindParam.new) if offset_value
arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
build_order(arel)
build_select(arel)
arel.distinct(distinct_value)
arel.from(build_from) unless from_clause.empty?
arel.lock(lock_value) if lock_value
arel
end
def symbol_unscoping(scope)
if !VALID_UNSCOPING_VALUES.include?(scope)
raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
end
clause_method = Relation::CLAUSE_METHODS.include?(scope)
multi_val_method = Relation::MULTI_VALUE_METHODS.include?(scope)
if clause_method
unscope_code = "#{scope}_clause="
else
unscope_code = "#{scope}_value#{'s' if multi_val_method}="
end
case scope
when :order
result = []
else
result = [] if multi_val_method
end
self.send(unscope_code, result)
end
def association_for_table(table_name)
table_name = table_name.to_s
@klass._reflect_on_association(table_name) ||
@klass._reflect_on_association(table_name.singularize)
end
def build_from
opts = from_clause.value
name = from_clause.name
case opts
when Relation
name ||= 'subquery'
opts.arel.as(name.to_s)
else
opts
end
end
def build_left_outer_joins(manager, outer_joins)
buckets = outer_joins.group_by do |join|
case join
when Hash, Symbol, Array
:association_join
else
raise ArgumentError, 'only Hash, Symbol and Array are allowed'
end
end
build_join_query(manager, buckets, Arel::Nodes::OuterJoin)
end
def build_joins(manager, joins)
buckets = joins.group_by do |join|
case join
when String
:string_join
when Hash, Symbol, Array
:association_join
when ActiveRecord::Associations::JoinDependency
:stashed_join
when Arel::Nodes::Join
:join_node
else
raise 'unknown class: %s' % join.class.name
end
end
build_join_query(manager, buckets, Arel::Nodes::InnerJoin)
end
def build_join_query(manager, buckets, join_type)
buckets.default = []
association_joins = buckets[:association_join]
stashed_association_joins = buckets[:stashed_join]
join_nodes = buckets[:join_node].uniq
string_joins = buckets[:string_join].map(&:strip).uniq
join_list = join_nodes + convert_join_strings_to_ast(manager, string_joins)
join_dependency = ActiveRecord::Associations::JoinDependency.new(
@klass,
association_joins,
join_list
)
join_infos = join_dependency.join_constraints stashed_association_joins, join_type
join_infos.each do |info|
info.joins.each { |join| manager.from(join) }
manager.bind_values.concat info.binds
end
manager.join_sources.concat(join_list)
manager
end
def convert_join_strings_to_ast(table, joins)
joins
.flatten
.reject(&:blank?)
.map { |join| table.create_string_join(Arel.sql(join)) }
end
def build_select(arel)
if select_values.any?
arel.project(*arel_columns(select_values.uniq))
else
arel.project(@klass.arel_table[Arel.star])
end
end
def arel_columns(columns)
columns.map do |field|
if (Symbol === field || String === field) && (klass.has_attribute?(field) || klass.attribute_alias?(field)) && !from_clause.value
arel_attribute(field)
elsif Symbol === field
connection.quote_table_name(field.to_s)
else
field
end
end
end
def reverse_sql_order(order_query)
if order_query.empty?
return [arel_attribute(primary_key).desc] if primary_key
raise IrreversibleOrderError,
"Relation has no current order and table has no primary key to be used as default order"
end
order_query.flat_map do |o|
case o
when Arel::Attribute
o.desc
when Arel::Nodes::Ordering
o.reverse
when String
if does_not_support_reverse?(o)
raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically"
end
o.split(',').map! do |s|
s.strip!
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
end
else
o
end
end
end
def does_not_support_reverse?(order)
#uses sql function with multiple arguments
order =~ /\([^()]*,[^()]*\)/ ||
# uses "nulls first" like construction
order =~ /nulls (first|last)\Z/i
end
def build_order(arel)
orders = order_values.uniq
orders.reject!(&:blank?)
arel.order(*orders) unless orders.empty?
end
VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC,
'asc', 'desc', 'ASC', 'DESC'] # :nodoc:
def validate_order_args(args)
args.each do |arg|
next unless arg.is_a?(Hash)
arg.each do |_key, value|
raise ArgumentError, "Direction \"#{value}\" is invalid. Valid " \
"directions are: #{VALID_DIRECTIONS.inspect}" unless VALID_DIRECTIONS.include?(value)
end
end
end
def preprocess_order_args(order_args)
order_args.map! do |arg|
klass.send(:sanitize_sql_for_order, arg)
end
order_args.flatten!
validate_order_args(order_args)
references = order_args.grep(String)
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
references!(references) if references.any?
# if a symbol is given we prepend the quoted table name
order_args.map! do |arg|
case arg
when Symbol
arel_attribute(arg).asc
when Hash
arg.map { |field, dir|
arel_attribute(field).send(dir.downcase)
}
else
arg
end
end.flatten!
end
# Checks to make sure that the arguments are not blank. Note that if some
# blank-like object were initially passed into the query method, then this
# method will not raise an error.
#
# Example:
#
# Post.references() # raises an error
# Post.references([]) # does not raise an error
#
# This particular method should be called with a method_name and the args
# passed into that method as an input. For example:
#
# def references(*args)
# check_if_method_has_arguments!("references", args)
# ...
# end
def check_if_method_has_arguments!(method_name, args)
if args.blank?
raise ArgumentError, "The method .#{method_name}() must contain arguments."
end
end
def structurally_incompatible_values_for_or(other)
Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } +
(Relation::MULTI_VALUE_METHODS - [:extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } +
(Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") }
end
def new_where_clause
Relation::WhereClause.empty
end
alias new_having_clause new_where_clause
def where_clause_factory
@where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder)
end
alias having_clause_factory where_clause_factory
def new_from_clause
Relation::FromClause.empty
end
def string_containing_comma?(value)
::String === value && value.include?(",")
end
end
end
| susancal/Waitr | vendor/cache/ruby/2.3.0/gems/activerecord-5.0.0/lib/active_record/relation/query_methods.rb | Ruby | mit | 41,496 |
package subpage
import (
. "github.com/ungerik/go-start/view"
"github.com/ungerik/go-start/examples/ViewPaths/views"
"github.com/ungerik/go-start/examples/ViewPaths/views/root"
)
func init() {
views.Admin_User0 = &Page{
Title: RenderView(
func(ctx *Context) error {
// The username is in ctx.URLArgs[0]
ctx.Response.WriteString("Manage " + ctx.URLArgs[0])
return nil
},
),
Content: Views{
DynamicViewBindURLArgs(
// The URL argument 0 can also be bound dynamically
// to a function argument:
func(ctx *Context, username string) (View, error) {
return H1("Manage user ", username), nil
},
),
root.Navigation(),
DynamicViewBindURLArgs(
func(ctx *Context, username string) (View, error) {
return Views{
H4(Printf("This view uses the URL argument '%s':", username)),
HTML(views.Admin_User0.URL(ctx)),
}, nil
},
),
},
}
}
| prinsmike/go-start | examples/ViewPaths/views/admin/user_0/user_0.go | GO | mit | 917 |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2016
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// 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.
#endregion
#region Usings
using System.Collections.Generic;
#endregion
namespace DotNetNuke.Collections
{
// Taken from Rob Conery's Blog post on the ASP.Net MVC PagedList Helper
// http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/
/// <summary>
/// Provides an interface to a paged list, which contains a snapshot
/// of a single page of data from the data store
/// </summary>
/// <typeparam name = "T">The type of objects stored in the list</typeparam>
public interface IPagedList<T> : IList<T>
{
/// <summary>
/// Gets a boolean indicating if there is a next page available
/// </summary>
bool HasNextPage { get; }
/// <summary>
/// Gets a boolean indicating if there is a previous page available
/// </summary>
bool HasPreviousPage { get; }
/// <summary>
/// Gets a boolean indicating if this is the first page
/// </summary>
bool IsFirstPage { get; }
/// <summary>
/// Gets a boolean indicating if this is the last page
/// </summary>
bool IsLastPage { get; }
/// <summary>
/// The no of pages in this list
/// </summary>
int PageCount { get; set; }
/// <summary>
/// The index of the page contained in this list
/// </summary>
int PageIndex { get; set; }
/// <summary>
/// The size of the page in this list
/// </summary>
int PageSize { get; set; }
/// <summary>
/// The total number of objects in the data store
/// </summary>
int TotalCount { get; set; }
}
} | moshefi/Dnn.Platform | DNN Platform/Library/Collections/IPagedList.cs | C# | mit | 2,905 |
#include "DHT.h"
#define DHT11 11
#define DHT22 22
#define DHT21 21
#define AM2301 21
DHT::DHT(uint8_t pin, uint8_t type){
_pin = pin;
_type = type;
}
void DHT::init(){
pinMode(_pin, INPUT_PULLUP);
digitalWrite(_pin, HIGH);
place=0;
}
#define MIN_PERIOD 1970
#define US_DELAY 5
#define WHILE_NOBLOCK(value) \
for(_noblock=0; (value); _noblock++){ \
delayMicroseconds(US_DELAY); \
if(_noblock == 255) { \
Serial.println("Error Block"); \
goto error; \
} \
}
#define PPl() Serial.print("Pl:"), Serial.println(place)
int8_t DHT::read(){
int8_t out = 0;
uint8_t _noblock;
uint8_t data[5] = {0, 0, 0, 0, 0};
switch(place){
case 0:
PPl();
start = millis();
Serial.println("starting DHT");
place = 1;
case 1:
if((uint16_t)(millis() - start) < MIN_PERIOD){
return false; // will return true only once
}
digitalWrite(_pin, LOW);
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
start = millis();
place = 2;
case 2:
PPl();
if((uint16_t)(millis() - start) < 20){
return false;
}
Serial.println("taking data");
noInterrupts();
pinMode(_pin, INPUT_PULLUP);
digitalWrite(_pin, HIGH);
WHILE_NOBLOCK(digitalRead(_pin) == HIGH);
WHILE_NOBLOCK(digitalRead(_pin) == LOW);
WHILE_NOBLOCK(digitalRead(_pin) == HIGH);
for (uint8_t i = 0; i < 40; i++) {
uint8_t counter = 0;
WHILE_NOBLOCK(digitalRead(_pin) == LOW);
for(_noblock=0; digitalRead(_pin) == HIGH; _noblock++){
delayMicroseconds(US_DELAY);
counter++;
if(_noblock == 255) {
goto error;
Serial.println("error counter");
}
}
data[i/8] <<= 1;
if (counter > 4) {
data[i/8] |= 1;
}
}
interrupts();
if (data[4] != ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
Serial.println("Error End");
goto error;
}
switch(_type){
case DHT11:
humidity = data[0];
temperature = data[2];
break;
case DHT21:
case DHT22:
humidity = ((data[0] << 8) + data[1]);
humidity /= 10;
temperature = (((data[2] bitand 0x7F) << 8) + data[3]);
temperature /= 10;
if(data[2] bitand 0x80){
temperature *= -1;
}
break;
default:
Serial.println("Error Type");
goto error;
}
valid = true;
place = 0;
return true;
error:
interrupts();
Serial.print("B:"); Serial.println(_noblock);
valid = false;
place = 0;
return -1;
}
}
| cloudformdesign/DHT | DHT.cpp | C++ | mit | 3,037 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddRoleToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', getAvailableRoles())->default('user');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role');
});
}
}
| brunocascio/unlp-parciales | database/migrations/2016_03_05_203132_add_role_to_users_table.php | PHP | mit | 555 |
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class Originator extends AbstractTag
{
protected $Id = '2100,0070';
protected $Name = 'Originator';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Originator';
}
| bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/Originator.php | PHP | mit | 781 |
var Method = require('aeolus').Method;
var redirecter = new Method();
redirecter.handle(function (request, response) {
response.redirect("../#/person/" + request.getParameter("id"));
});
module.exports = redirecter;
| awesomesourcecode/MoviesBackendServer | api/get/person.(id).js | JavaScript | mit | 220 |
'use strict';
var bitcore = require('bitcore');
angular.module('copayApp.services')
.factory('balanceService', function($rootScope, $filter, $timeout, rateService) {
var root = {};
var _balanceCache = {};
root.clearBalanceCache = function(w) {
w.clearUnspentCache();
delete _balanceCache[w.getId()];
};
root._fetchBalance = function(w, cb) {
cb = cb || function() {};
var satToUnit = 1 / w.settings.unitToSatoshi;
var COIN = bitcore.util.COIN;
w.getBalance(function(err, balanceSat, balanceByAddrSat, safeBalanceSat, safeUnspentCount) {
if (err) return cb(err);
var r = {};
r.totalBalance = $filter('noFractionNumber')(balanceSat * satToUnit);
r.totalBalanceBTC = (balanceSat / COIN);
var availableBalanceNr = safeBalanceSat * satToUnit;
r.availableBalance = $filter('noFractionNumber')(safeBalanceSat * satToUnit);
r.availableBalanceBTC = (safeBalanceSat / COIN);
r.safeUnspentCount = safeUnspentCount;
var lockedBalance = (balanceSat - safeBalanceSat) * satToUnit;
r.lockedBalance = lockedBalance ? $filter('noFractionNumber')(lockedBalance) : null;
r.lockedBalanceBTC = (balanceSat - safeBalanceSat) / COIN;
if (r.safeUnspentCount) {
var estimatedFee = copay.Wallet.estimatedFee(r.safeUnspentCount);
r.topAmount = (((availableBalanceNr * w.settings.unitToSatoshi).toFixed(0) - estimatedFee) / w.settings.unitToSatoshi);
}
var balanceByAddr = {};
for (var ii in balanceByAddrSat) {
balanceByAddr[ii] = balanceByAddrSat[ii] * satToUnit;
}
r.balanceByAddr = balanceByAddr;
if (rateService.isAvailable()) {
var totalBalanceAlternative = rateService.toFiat(balanceSat, w.settings.alternativeIsoCode);
var lockedBalanceAlternative = rateService.toFiat(balanceSat - safeBalanceSat, w.settings.alternativeIsoCode);
var alternativeConversionRate = rateService.toFiat(100000000, w.settings.alternativeIsoCode);
r.totalBalanceAlternative = $filter('noFractionNumber')(totalBalanceAlternative, 2);
r.lockedBalanceAlternative = $filter('noFractionNumber')(lockedBalanceAlternative, 2);
r.alternativeConversionRate = $filter('noFractionNumber')(alternativeConversionRate, 2);
r.alternativeBalanceAvailable = true;
r.alternativeIsoCode = w.settings.alternativeIsoCode;
};
r.updatingBalance = false;
return cb(null, r)
});
};
root.update = function(w, cb, isFocused) {
w = w || $rootScope.wallet;
if (!w || !w.isComplete()) return;
copay.logger.debug('Updating balance of:', w.getName(), isFocused);
var wid = w.getId();
// cache available? Set the cached values until we updated them
if (_balanceCache[wid]) {
w.balanceInfo = _balanceCache[wid];
} else {
if (isFocused)
$rootScope.updatingBalance = true;
}
w.balanceInfo = w.balanceInfo || {};
w.balanceInfo.updating = true;
root._fetchBalance(w, function(err, res) {
if (err) throw err;
w.balanceInfo = _balanceCache[wid] = res;
w.balanceInfo.updating = false;
if (isFocused) {
$rootScope.updatingBalance = false;
}
// we alwalys calltimeout because if balance is cached, we are still on the same
// execution path
if (cb) $timeout(function() {
return cb();
}, 1);
});
};
return root;
});
| Tetpay/copay | js/services/balanceService.js | JavaScript | mit | 3,598 |
require_relative 'neural_test'
module ItsAlive
class OutputNeuronTest < NeuralTest
def test_that_it_can_add_outputs
neuron = OutputNeuron.new(3)
assert { neuron.outputs.length == 3 }
end
def test_that_it_correctly_calculates_delta
neuron = OutputNeuron.new(1)
neuron.dendrites << Synapse.input_to(neuron, 0.5)
neuron.signal([1]).activate
neuron.learn(1)
assert { neuron.delta == -0.03876033167077969 }
end
end
end
| vyorkin-archive/itsalive | test/itsalive/output_neuron_test.rb | Ruby | mit | 480 |
define(['square/filters/filters'], function (filters) {
'use strict';
filters.filter('cpf', function () {
return function (value) {
if (!value) {
return value;
}
var lpad = function (value, padding) {
var zeroes = '0';
for (var i = 0; i < padding; i++) {
zeroes += '0';
}
return (zeroes + value).slice(padding * -1);
};
var newValue = angular.isNumber(value) ? lpad(value.toString(), 11) : lpad(value, 11);
return jQuery.mask.string(newValue, '999.999.999-99');
};
});
filters.filter('cpfValidator', function () {
return function (value) {
value = value.replace(/[^\d]+/g, '');
if (value.length !== 11 || value === '') {
return false;
}
// Elimina cpfs invalidos conhecidos
if (value === '00000000000' ||
value === '11111111111' ||
value === '22222222222' ||
value === '33333333333' ||
value === '44444444444' ||
value === '55555555555' ||
value === '66666666666' ||
value === '77777777777' ||
value === '88888888888' ||
value === '99999999999') {
return false;
}
// Valida 1o digito
var add = 0;
for (var i = 0; i < 9; i++) {
add += parseInt(value.charAt(i), 10) * (10 - i);
}
var rev = 11 - (add % 11);
if (rev === 10 || rev === 11) {
rev = 0;
}
if (rev !== parseInt(value.charAt(9), 10)) {
return false;
}
// Valida 2o digito
add = 0;
for (i = 0; i < 10; i++) {
add += parseInt(value.charAt(i), 10) * (11 - i);
}
rev = 11 - (add % 11);
if (rev === 10 || rev === 11) {
rev = 0;
}
if (rev !== parseInt(value.charAt(10), 10)) {
return false;
}
return true;
};
});
}); | leonardosalles/squarespa | squareframework-ui/target/classes/js/filters/cpf.js | JavaScript | mit | 1,808 |
namespace _12.StackImplementation
{
using System;
public class StackTesting
{
public static void Main()
{
var Testing = new JStack<int>();
Testing.Push(1);
Testing.Push(2);
Console.WriteLine(Testing.Peek());
Console.WriteLine(Testing.Pop());
Console.WriteLine(Testing.Count);
Console.WriteLine(Testing.Peek());
Console.WriteLine(Testing.Count);
Testing.Push(1);
Testing.Push(2);
Testing.Push(1);
Testing.Push(2);
Testing.Push(1);
Testing.Push(2);
Console.WriteLine(Testing.Count);
}
}
} | dzhenko/TelerikAcademy | DSA/DSA-Preparation/DSA-2-LinearDataStructures/12. StackImplementation/Testing.cs | C# | mit | 713 |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.boilit.asm;
/**
* A reference to a field or a method.
*
* @author Remi Forax
* @author Eric Bruneton
*/
public final class Handle {
/**
* The kind of field or method designated by this Handle. Should be
* {@link org.boilit.asm.Opcodes#H_GETFIELD}, {@link org.boilit.asm.Opcodes#H_GETSTATIC},
* {@link org.boilit.asm.Opcodes#H_PUTFIELD}, {@link org.boilit.asm.Opcodes#H_PUTSTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKEVIRTUAL}, {@link org.boilit.asm.Opcodes#H_INVOKESTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKESPECIAL}, {@link org.boilit.asm.Opcodes#H_NEWINVOKESPECIAL} or
* {@link org.boilit.asm.Opcodes#H_INVOKEINTERFACE}.
*/
final int tag;
/**
* The internal name of the field or method designed by this handle.
*/
final String owner;
/**
* The name of the field or method designated by this handle.
*/
final String name;
/**
* The descriptor of the field or method designated by this handle.
*/
final String desc;
/**
* Constructs a new field or method handle.
*
* @param tag
* the kind of field or method designated by this Handle. Must be
* {@link org.boilit.asm.Opcodes#H_GETFIELD}, {@link org.boilit.asm.Opcodes#H_GETSTATIC},
* {@link org.boilit.asm.Opcodes#H_PUTFIELD}, {@link org.boilit.asm.Opcodes#H_PUTSTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKEVIRTUAL},
* {@link org.boilit.asm.Opcodes#H_INVOKESTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKESPECIAL},
* {@link org.boilit.asm.Opcodes#H_NEWINVOKESPECIAL} or
* {@link org.boilit.asm.Opcodes#H_INVOKEINTERFACE}.
* @param owner
* the internal name of the field or method designed by this
* handle.
* @param name
* the name of the field or method designated by this handle.
* @param desc
* the descriptor of the field or method designated by this
* handle.
*/
public Handle(int tag, String owner, String name, String desc) {
this.tag = tag;
this.owner = owner;
this.name = name;
this.desc = desc;
}
/**
* Returns the kind of field or method designated by this handle.
*
* @return {@link org.boilit.asm.Opcodes#H_GETFIELD}, {@link org.boilit.asm.Opcodes#H_GETSTATIC},
* {@link org.boilit.asm.Opcodes#H_PUTFIELD}, {@link org.boilit.asm.Opcodes#H_PUTSTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKEVIRTUAL}, {@link org.boilit.asm.Opcodes#H_INVOKESTATIC},
* {@link org.boilit.asm.Opcodes#H_INVOKESPECIAL},
* {@link org.boilit.asm.Opcodes#H_NEWINVOKESPECIAL} or
* {@link org.boilit.asm.Opcodes#H_INVOKEINTERFACE}.
*/
public int getTag() {
return tag;
}
/**
* Returns the internal name of the field or method designed by this handle.
*
* @return the internal name of the field or method designed by this handle.
*/
public String getOwner() {
return owner;
}
/**
* Returns the name of the field or method designated by this handle.
*
* @return the name of the field or method designated by this handle.
*/
public String getName() {
return name;
}
/**
* Returns the descriptor of the field or method designated by this handle.
*
* @return the descriptor of the field or method designated by this handle.
*/
public String getDesc() {
return desc;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Handle)) {
return false;
}
Handle h = (Handle) obj;
return tag == h.tag && owner.equals(h.owner) && name.equals(h.name)
&& desc.equals(h.desc);
}
@Override
public int hashCode() {
return tag + owner.hashCode() * name.hashCode() * desc.hashCode();
}
/**
* Returns the textual representation of this handle. The textual
* representation is:
*
* <pre>
* owner '.' name desc ' ' '(' tag ')'
* </pre>
*
* . As this format is unambiguous, it can be parsed if necessary.
*/
@Override
public String toString() {
return owner + '.' + name + desc + " (" + tag + ')';
}
}
| xinggg22/bsl | src/main/java/org/boilit/asm/Handle.java | Java | mit | 6,173 |
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from ipaddress import ip_network
from operator import itemgetter
from indico.util.i18n import _
from indico.web.forms.fields import MultiStringField
class MultiIPNetworkField(MultiStringField):
"""A field to enter multiple IPv4 or IPv6 networks.
The field data is a set of ``IPNetwork``s not bound to a DB session.
The ``unique`` and ``sortable`` parameters of the parent class cannot be used with this class.
"""
def __init__(self, *args, **kwargs):
super(MultiIPNetworkField, self).__init__(*args, field=('subnet', _("subnet")), **kwargs)
self._data_converted = False
self.data = None
def _value(self):
if self.data is None:
return []
elif self._data_converted:
data = [{self.field_name: unicode(network)} for network in self.data or []]
return sorted(data, key=itemgetter(self.field_name))
else:
return self.data
def process_data(self, value):
if value is not None:
self._data_converted = True
self.data = value
def _fix_network(self, network):
network = network.encode('ascii', 'ignore')
if network.startswith('::ffff:'):
# convert ipv6-style ipv4 to regular ipv4
# the ipaddress library doesn't deal with such IPs properly!
network = network[7:]
return unicode(network)
def process_formdata(self, valuelist):
self._data_converted = False
super(MultiIPNetworkField, self).process_formdata(valuelist)
self.data = {ip_network(self._fix_network(entry[self.field_name])) for entry in self.data}
self._data_converted = True
def pre_validate(self, form):
pass # nothing to do
| mvidalgarcia/indico | indico/modules/networks/fields.py | Python | mit | 2,008 |
import { FilterService } from './filterservice';
describe('FilterService Suite', () => {
let data: any = [
{brand: "VW", year: 2012, color: {name:"Orange"}, vin: "dsad231ff"},
{brand: "Audi", year: 2011, color: {name:"Black"}, vin: "gwregre345"},
{brand: "Renault", year: 2005, color: {name:"Black"}, vin: "h354htr"},
{brand: "BMW", year: 2003, color: {name:"Blue"}, vin: "j6w54qgh"},
{brand: "Mercedes", year: 1995, color: {name:"Red"}, vin: "hrtwy34"},
{brand: "Volvo", year: 2005, color: {name:"Orange"}, vin: "jejtyj"},
{brand: "Honda", year: 2012, color: {name:"Blue"}, vin: "g43gr"},
{brand: "Jaguar", year: 2013,color: {name:"Black"}, vin: "greg34"},
{brand: "Ford", year: 2000, color: {name:"White"}, vin: "h54hw5"},
{brand: "Fiat", year: 2013, color: {name:"Yellow"}, vin: "245t2s"}
];
let timeData = [
{date:'Tue Aug 04 2019 00:00:00 GMT+0300 (GMT+03:00)'},
{date:'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)'},
{date:'Tue Aug 07 2019 00:00:00 GMT+0300 (GMT+03:00)'}
];
let filterService = new FilterService();
it('Should filter by startsWith', () => {
let filteredValue = filterService.filter(data,['brand'],'f','startsWith');
expect(filteredValue.length).toEqual(2);
filteredValue = filterService.filter(data,['brand'],'','startsWith');
expect(filteredValue.length).toEqual(10);
filteredValue = filterService.filter(data,[''],'f','startsWith');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by contains', () => {
let filteredValue = filterService.filter(data,['brand'],'f','contains');
expect(filteredValue.length).toEqual(2);
filteredValue = filterService.filter(data,['brand'],'','contains');
expect(filteredValue.length).toEqual(10);
filteredValue = filterService.filter(data,[''],'f','contains');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by endsWith', () => {
let filteredValue = filterService.filter(data,['brand'],'t','endsWith');
expect(filteredValue.length).toEqual(2);
filteredValue = filterService.filter(data,['brand'],'','endsWith');
expect(filteredValue.length).toEqual(10);
filteredValue = filterService.filter(data,[''],'t','endsWith');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by equals', () => {
let filteredValue = filterService.filter(data,['brand'],'BMW','equals');
expect(filteredValue.length).toEqual(1);
filteredValue = filterService.filter(data,['brand'],'','equals');
expect(filteredValue.length).toEqual(10);
filteredValue = filterService.filter(data,[''],'BMW','equals');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by notEquals', () => {
let filteredValue = filterService.filter(data,['brand'],'BMW','notEquals');
expect(filteredValue.length).toEqual(9);
filteredValue = filterService.filter(data,['brand'],'','notEquals');
expect(filteredValue.length).toEqual(0);
filteredValue = filterService.filter(data,[''],'BMW','notEquals');
expect(filteredValue.length).toEqual(10);
});
it('Should filter by lt', () => {
let filteredValue = filterService.filter(timeData,['date'],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','lt');
expect(filteredValue.length).toEqual(1);
filteredValue = filterService.filter(timeData,['date'],'','lt');
expect(filteredValue.length).toEqual(0);
filteredValue = filterService.filter(timeData,[''],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','lt');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by lte', () => {
let filteredValue = filterService.filter(timeData,['date'],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','lte');
expect(filteredValue.length).toEqual(2);
filteredValue = filterService.filter(timeData,['date'],'','lte');
expect(filteredValue.length).toEqual(0);
filteredValue = filterService.filter(timeData,[''],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','lte');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by gt', () => {
let filteredValue = filterService.filter(timeData,['date'],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','gt');
expect(filteredValue.length).toEqual(1);
filteredValue = filterService.filter(timeData,['date'],'','gt');
expect(filteredValue.length).toEqual(3);
filteredValue = filterService.filter(timeData,[''],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','gt');
expect(filteredValue.length).toEqual(0);
});
it('Should filter by gte', () => {
let filteredValue = filterService.filter(timeData,['date'],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','gte');
expect(filteredValue.length).toEqual(2);
filteredValue = filterService.filter(timeData,['date'],'','gte');
expect(filteredValue.length).toEqual(3);
filteredValue = filterService.filter(timeData,[''],'Tue Aug 05 2019 00:00:00 GMT+0300 (GMT+03:00)','gte');
expect(filteredValue.length).toEqual(0);
});
});
| WebRota/primeng | src/app/components/api/filterservice.spec.ts | TypeScript | mit | 5,381 |
/*
* filename EventDispatcher.cpp
* fileinfo À̺¥Æ® ºÐ¹è ¹× ó¸® Ŭ·¡½º ±¸Çö ÆÄÀÏ
* author ÁÖÇå¾ç (Heonyang Ju)
*/
#include "EventDispatcher.h"
COMA_USING_NS
EventDispatcher::EventDispatcher()
{}
EventDispatcher::~EventDispatcher()
{
listenerList_.clear();
}
void EventDispatcher::SetEventListener(const std::string& type, EventCallback function, void* target)
{
for (const auto& iter : listenerList_)
{
if (iter.type == type && &iter.function == &function)
{
return;
}
}
listenerList_.push_back(Listener{ type, function, target });
}
void EventDispatcher::RemoveEventListener(const std::string& type, void* target)
{
for (auto iter = listenerList_.begin(); iter != listenerList_.end(); )
{
if ((*iter).type == type && (*iter).target == target)
{
iter = listenerList_.erase(iter);
}
else
{
++iter;
}
}
}
bool EventDispatcher::HasEventListener(const std::string& type)
{
for (const auto& iter : listenerList_)
{
if (iter.type == type)
{
return true;
}
}
return false;
}
void EventDispatcher::DispatchEvent(const Event* event)
{
for (const auto& iter : listenerList_)
{
if (iter.type == event->GetType())
{
if (iter.target)
{
iter.function(event);
}
}
}
delete event;
} | letepyu/Coma2D | Coma2D/Coma2D/EventDispatcher.cpp | C++ | mit | 1,245 |
/*
File generated by NetTiers templates [www.nettiers.com]
Important: Do not modify this file. Edit the file Cart.cs instead.
*/
#region Using Directives
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Security;
using System.Data;
using PetShop.Business;
using PetShop.Business.Validation;
//using Entities = PetShop.Business;
using PetShop.Data;
using PetShop.Data.Bases;
using Microsoft.Practices.EnterpriseLibrary.Logging;
#endregion
namespace PetShop.Services
{
///<summary>
/// An object representation of the 'Cart' table.
///</summary>
/// <remarks>
/// IMPORTANT!!! You should not modify this partial class, modify the Cart.cs file instead.
/// All custom implementations should be done in the <see cref="Cart"/> class.
/// </remarks>
[DataObject]
[CLSCompliant(true)]
public partial class CartServiceBase : ServiceBase<Cart, CartKey>
{
#region Constructors
///<summary>
/// Creates a new <see cref="Cart"/> instance .
///</summary>
public CartServiceBase() : base()
{
}
///<summary>
/// A simple factory method to create a new <see cref="Cart"/> instance.
///</summary>
///<param name="_uniqueId"></param>
///<param name="_itemId"></param>
///<param name="_name"></param>
///<param name="_type"></param>
///<param name="_price"></param>
///<param name="_categoryId"></param>
///<param name="_productId"></param>
///<param name="_isShoppingCart"></param>
///<param name="_quantity"></param>
public static Cart CreateCart(int _uniqueId, string _itemId, string _name, string _type, decimal _price, string _categoryId, string _productId, bool _isShoppingCart, int _quantity)
{
Cart newEntityCart = new Cart();
newEntityCart.UniqueId = _uniqueId;
newEntityCart.ItemId = _itemId;
newEntityCart.Name = _name;
newEntityCart.Type = _type;
newEntityCart.Price = _price;
newEntityCart.CategoryId = _categoryId;
newEntityCart.ProductId = _productId;
newEntityCart.IsShoppingCart = _isShoppingCart;
newEntityCart.Quantity = _quantity;
return newEntityCart;
}
#endregion Constructors
#region Fields
private static SecurityContext<Cart> securityContext = new SecurityContext<Cart>();
private static readonly string layerExceptionPolicy = "ServiceLayerExceptionPolicy";
private static readonly bool noTranByDefault = false;
#endregion
#region SecurityContext
///<summary>
/// Contains all necessary information to validate and authorize the
/// call of the method with the Principal and Roles of the current user.
///</summary>
public static SecurityContext<Cart> SecurityContext
{
get
{
return securityContext;
}
}
#endregion
#region Data Access Methods
#region GetByForeignKey Methods
#endregion GetByForeignKey Methods
#region GetByIndexes
/// <summary>
/// Gets a row from the DataSource based on its primary key.
/// </summary>
/// <param name="key">The unique identifier of the row to retrieve.</param>
/// <returns>Returns an instance of the Entity class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public override Cart Get(CartKey key)
{
return GetByCartId(key.CartId);
}
/// <summary>
/// method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key FK_Cart_UniqueID index.
/// </summary>
/// <param name="_uniqueId"></param>
/// <returns>Returns an instance of the <see cref="TList{Cart}"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> GetByUniqueId(int _uniqueId)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByUniqueId");
#endregion Security check
#region Initialisation
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetByUniqueId(transactionManager, _uniqueId) ;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key FK_Cart_UniqueID index.
/// </summary>
/// <param name="_uniqueId"></param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Page length of records you would like to retrieve</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>Returns an instance of the <see cref="TList{Cart}"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> GetByUniqueId(int _uniqueId, int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByUniqueId");
#endregion Security check
#region Initialisation
totalCount = -1;
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetByUniqueId(transactionManager, _uniqueId, start, pageLength, out totalCount) ;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key IX_SHOPPINGCART index.
/// </summary>
/// <param name="_isShoppingCart"></param>
/// <returns>Returns an instance of the <see cref="TList{Cart}"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> GetByIsShoppingCart(bool _isShoppingCart)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByIsShoppingCart");
#endregion Security check
#region Initialisation
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetByIsShoppingCart(transactionManager, _isShoppingCart) ;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key IX_SHOPPINGCART index.
/// </summary>
/// <param name="_isShoppingCart"></param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Page length of records you would like to retrieve</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>Returns an instance of the <see cref="TList{Cart}"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> GetByIsShoppingCart(bool _isShoppingCart, int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByIsShoppingCart");
#endregion Security check
#region Initialisation
totalCount = -1;
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetByIsShoppingCart(transactionManager, _isShoppingCart, start, pageLength, out totalCount) ;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key PK_Cart index.
/// </summary>
/// <param name="_cartId"></param>
/// <returns>Returns an instance of the <see cref="Cart"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual Cart GetByCartId(int _cartId)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByCartId");
#endregion Security check
#region Initialisation
Cart entity = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
entity = dataProvider.CartProvider.GetByCartId(transactionManager, _cartId) as Cart;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entity;
}
/// <summary>
/// Method that Gets rows in a <see cref="TList{Cart}" /> from the datasource based on the primary key PK_Cart index.
/// </summary>
/// <param name="_cartId"></param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Page length of records you would like to retrieve</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>Returns an instance of the <see cref="Cart"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual Cart GetByCartId(int _cartId, int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetByCartId");
#endregion Security check
#region Initialisation
totalCount = -1;
Cart entity = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
entity = dataProvider.CartProvider.GetByCartId(transactionManager, _cartId, start, pageLength, out totalCount) as Cart;
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entity;
}
#endregion GetByIndexes
#region GetAll
/// <summary>
/// Get a complete collection of <see cref="Cart" /> entities.
/// </summary>
/// <returns></returns>
public override TList<Cart> GetAll()
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetAll");
#endregion Security check
#region Initialisation
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetAll(transactionManager);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Get a set portion of a complete list of <see cref="Cart" /> entities
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>a <see cref="TList{Cart}"/> </returns>
public virtual TList<Cart> GetAll(int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetAll");
#endregion Security check
#region Initialisation
totalCount = -1;
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetAll(transactionManager, start, pageLength, out totalCount);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
#endregion GetAll
#region GetPaged
/// <summary>
/// Gets a page of <see cref="TList{Cart}" /> rows from the DataSource.
/// </summary>
/// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> GetPaged(out int totalCount)
{
return GetPaged(null, null, 0, int.MaxValue, out totalCount);
}
/// <summary>
/// Gets a page of <see cref="TList{Cart}" /> rows from the DataSource.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> GetPaged(int start, int pageLength, out int totalCount)
{
return GetPaged(null, null, start, pageLength, out totalCount);
}
/// <summary>
/// Gets a page of entity rows with a <see cref="TList{Cart}" /> from the DataSource with a where clause and order by clause.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC).</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public override TList<Cart> GetPaged(string whereClause,string orderBy, int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("GetPaged");
#endregion Security check
#region Initialisation
totalCount = -1;
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.GetPaged(transactionManager, whereClause, orderBy, start, pageLength, out totalCount);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Gets the number of rows in the DataSource that match the specified whereClause.
/// This method is only provided as a workaround for the ObjectDataSource's need to
/// execute another method to discover the total count instead of using another param, like our out param.
/// This method should be avoided if using the ObjectDataSource or another method.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="totalCount">Number of rows in the DataSource.</param>
/// <returns>Returns the number of rows.</returns>
public int GetTotalItems(string whereClause, out int totalCount)
{
GetPaged(whereClause, null, 0, int.MaxValue, out totalCount);
return totalCount;
}
#endregion GetPaged
#region Find
#region Parsed Find Methods
/// <summary>
/// Attempts to do a parameterized version of a simple whereclause.
/// Returns rows meeting the whereClause condition from the DataSource.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks>
/// <returns>Returns a typed collection of Entity objects.</returns>
public virtual TList<Cart> Find(string whereClause)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Find");
#endregion Security check
#region Initialisation
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.Find(transactionManager, whereClause);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Returns rows meeting the whereClause condition from the DataSource.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">out parameter to get total records for query</param>
/// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks>
/// <returns>Returns a typed collection TList{Cart} of <c>Cart</c> objects.</returns>
public override TList<Cart> Find(string whereClause, int start, int pageLength, out int totalCount)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Find");
#endregion Security check
#region Initialisation
totalCount = -1;
TList<Cart> list = null;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.Find(transactionManager, whereClause, start, pageLength, out totalCount);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
#endregion Parsed Find Methods
#region Parameterized Find Methods
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> Find(IFilterParameterCollection parameters)
{
return Find(parameters, (string) null);
}
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="sortColumns">A collection of <see cref="SqlSortColumn"/> objects.</param>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> Find(IFilterParameterCollection parameters, ISortColumnCollection sortColumns)
{
return Find(parameters, sortColumns.ToString());
}
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> Find(IFilterParameterCollection parameters, string orderBy)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Find");
#endregion Security check
#region Initialisation
TransactionManager transactionManager = null;
TList<Cart> list = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.Find(transactionManager, parameters, orderBy);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="sortColumns">A collection of <see cref="SqlSortColumn"/> objects.</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> Find(IFilterParameterCollection parameters, ISortColumnCollection sortColumns, int start, int pageLength, out int count)
{
return Find(parameters, sortColumns.ToString(), start, pageLength, out count);
}
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <returns>Returns a typed collection of <c>Cart</c> objects.</returns>
public virtual TList<Cart> Find(IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Find");
#endregion Security check
#region Initialisation
count = -1;
TransactionManager transactionManager = null;
TList<Cart> list = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
list = dataProvider.CartProvider.Find(transactionManager, parameters, orderBy, start, pageLength, out count);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return list;
}
#endregion Parameterized Find Methods
#endregion
#region Insert
#region Insert Entity
/// <summary>
/// public virtual method that Inserts a Cart object into the datasource using a transaction.
/// </summary>
/// <param name="entity">Cart object to Insert.</param>
/// <remarks>After Inserting into the datasource, the Cart object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Insert Method with an already open transaction.
/// <code>
/// Cart entity = new Cart();
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Insert Child entity, Then Parent Entity
/// ChildObjectTypeService.Insert(entity.ChildObjectSource);
/// CartService.Insert(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Insert)]
public override bool Insert(Cart entity)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Insert");
if (!entity.IsValid)
throw new EntityNotValidException(entity, "Insert", entity.Error);
#endregion Security and validation check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.Insert(transactionManager, entity);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion Insert Entity
#region Insert Collection
/// <summary>
/// public virtual method that Inserts rows in <see cref="TList{Cart}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>Cart</c> objects in a <see cref="TList{Cart}" /> object to Insert.</param>
/// <remarks>
/// This function will only Insert entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Inserting the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Inserting into the datasource, the <c>Cart</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Insert.</returns>
/// <example>
/// The following code shows the usage of the Insert Method with a collection of Cart.
/// <code><![CDATA[
/// TList<Cart> list = new TList<Cart>();
/// Cart entity = new Cart();
/// entity.StringProperty = "foo";
/// Cart entity2 = new Cart();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// CartService.Insert(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Insert)]
public virtual TList<Cart> Insert(TList<Cart> entityCollection)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Insert");
if (!entityCollection.IsValid)
{
throw new EntityNotValidException(entityCollection, "Insert", DomainUtil.GetErrorsFromList<Cart>(entityCollection));
}
#endregion Security and validation check
#region Initialisation
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.Insert(transactionManager, entityCollection);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entityCollection;
}
#endregion Insert Collection
#endregion Insert
#region Update
#region Update Entity
/// <summary>
/// public virtual method that Updates a Cart object into the datasource using a transaction.
/// </summary>
/// <param name="entity">Cart object to Update.</param>
/// <remarks>After Updateing into the datasource, the Cart object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Update Method with an already open transaction.
/// <code>
/// Cart entity = CartService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Update Child entity, Then Parent Entity
/// ChildObjectTypeService.Update(entity.ChildObjectSource);
/// CartService.Update(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
public override bool Update(Cart entity)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Update");
if (!entity.IsValid)
throw new EntityNotValidException(entity, "Update", entity.Error);
#endregion Security and validation check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.Update(transactionManager, entity);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion Update Entity
#region Update Collection
/// <summary>
/// public virtual method that Updates rows in <see cref="TList{Cart}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>Cart</c> objects in a <see cref="TList{Cart}" /> object to Update.</param>
/// <remarks>
/// This function will only Update entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Updateing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Updateing into the datasource, the <c>Cart</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Update.</returns>
/// <example>
/// The following code shows the usage of the Update Method with a collection of Cart.
/// <code><![CDATA[
/// TList<Cart> list = new TList<Cart>();
/// Cart entity = new Cart();
/// entity.StringProperty = "foo";
/// Cart entity2 = new Cart();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// CartService.Update(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
public virtual TList<Cart> Update(TList<Cart> entityCollection)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Update");
if (!entityCollection.IsValid)
{
throw new EntityNotValidException(entityCollection, "Update", DomainUtil.GetErrorsFromList<Cart>(entityCollection));
}
#endregion Security and validation check
#region Initialisation
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.Update(transactionManager, entityCollection);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entityCollection;
}
#endregion Update Collection
#endregion Update
#region Save
#region Save Entity
/// <summary>
/// public virtual method that Saves a Cart object into the datasource using a transaction.
/// </summary>
/// <param name="entity">Cart object to Save.</param>
/// <remarks>After Saveing into the datasource, the Cart object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Save Method with an already open transaction.
/// <code>
/// Cart entity = CartService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Save Child entity, Then Parent Entity
/// ChildObjectTypeService.Save(entity.ChildObjectSource);
/// CartService.Save(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
public override Cart Save(Cart entity)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Save");
if (!entity.IsValid)
throw new EntityNotValidException(entity, "Save", entity.Error);
#endregion Security and validation check
#region Initialisation
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.Save(transactionManager, entity);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entity;
}
#endregion Save Entity
#region Save Collection
/// <summary>
/// public virtual method that Saves rows in <see cref="TList{Cart}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>Cart</c> objects in a <see cref="TList{Cart}" /> object to Save.</param>
/// <remarks>
/// This function will only Save entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Saveing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Saveing into the datasource, the <c>Cart</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Save.</returns>
/// <example>
/// The following code shows the usage of the Save Method with a collection of Cart.
/// <code><![CDATA[
/// TList<Cart> list = new TList<Cart>();
/// Cart entity = new Cart();
/// entity.StringProperty = "foo";
/// Cart entity2 = new Cart();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// CartService.Save(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
public virtual TList<Cart> Save(TList<Cart> entityCollection)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Save");
if (!entityCollection.IsValid)
{
throw new EntityNotValidException(entityCollection, "Save", DomainUtil.GetErrorsFromList<Cart>(entityCollection));
}
#endregion Security and validation check
#region Initialisation
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.Save(transactionManager, entityCollection);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entityCollection;
}
#endregion Save Collection
#endregion Save
#region Delete
#region Delete Entity
/// <summary>
/// public virtual method that Deletes a Cart object into the datasource using a transaction.
/// </summary>
/// <param name="entity">Cart object to Delete.</param>
/// <remarks>After Deleteing into the datasource, the Cart object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Delete Method with an already open transaction.
/// <code>
/// Cart entity = CartService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Delete Child entity, Then Parent Entity
/// ChildObjectTypeService.Delete(entity.ChildObjectSource);
/// CartService.Delete(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Delete)]
public override bool Delete(Cart entity)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Delete");
if (!entity.IsValid)
throw new EntityNotValidException(entity, "Delete", entity.Error);
#endregion Security and validation check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.Delete(transactionManager, entity);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion Delete Entity
#region Delete Collection
/// <summary>
/// public virtual method that Deletes rows in <see cref="TList{Cart}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>Cart</c> objects in a <see cref="TList{Cart}" /> object to Delete.</param>
/// <remarks>
/// This function will only Delete entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Deleteing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Deleteing into the datasource, the <c>Cart</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Delete.</returns>
/// <example>
/// The following code shows the usage of the Delete Method with a collection of Cart.
/// <code><![CDATA[
/// TList<Cart> list = new TList<Cart>();
/// Cart entity = new Cart();
/// entity.StringProperty = "foo";
/// Cart entity2 = new Cart();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// CartService.Delete(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Delete)]
public virtual TList<Cart> Delete(TList<Cart> entityCollection)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Delete");
if (!entityCollection.IsValid)
{
throw new EntityNotValidException(entityCollection, "Delete", DomainUtil.GetErrorsFromList<Cart>(entityCollection));
}
#endregion Security and validation check
#region Initialisation
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.Delete(transactionManager, entityCollection);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return entityCollection;
}
#endregion Delete Collection
#endregion Delete
#region Delete
/// <summary>
/// Deletes a row from the DataSource.
/// </summary>
/// <param name="key">The unique identifier of the row to delete.</param>
/// <returns>Returns true if operation suceeded.</returns>
public bool Delete(CartKey key)
{
return Delete(key.CartId );
}
/// <summary>
/// Deletes a row from the DataSource based on the PK'S int _cartId
/// </summary>
/// <param name="_cartId">Cart pk id.</param>
/// <remarks>Deletes based on primary key(s).</remarks>
/// <returns>Returns true if operation suceeded.</returns>
[DataObjectMethod(DataObjectMethodType.Delete)]
public virtual bool Delete(int _cartId)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("Delete");
#endregion Security check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
//since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
transactionManager = ConnectionScope.ValidateOrCreateTransaction();
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.Delete(transactionManager, _cartId);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion
#region GetBy m:m Aggregate Relationships
#endregion N2N Relationships
#region Custom Methods
#endregion
#region DeepLoad
#region Deep Load By Entity Keys
/// <summary>
/// public virtualDeep Loads the requested <see cref="TList<Cart>"/> by the entity keys. The criteria of the child
/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
/// </summary>
/// <param name="_uniqueId"></param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
/// <param name="childTypes">Cart Property Collection Type Array To Include or Exclude from Load</param>
/// <returns>Returns an instance of the <see cref="TList<Cart>"/> class and DeepLoaded.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> DeepLoadByUniqueId(int _uniqueId, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes)
{
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepLoadByUniqueId");
bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
TList<Cart> list = GetByUniqueId(_uniqueId);
//Check to see if list is not null, before attempting to Deep Load
if (list != null)
DeepLoad(list, deep, deepLoadType, childTypes);
return list;
}
/// <summary>
/// public virtualDeep Loads the requested <see cref="TList<Cart>"/> by the entity keys. The criteria of the child
/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
/// </summary>
/// <param name="_isShoppingCart"></param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
/// <param name="childTypes">Cart Property Collection Type Array To Include or Exclude from Load</param>
/// <returns>Returns an instance of the <see cref="TList<Cart>"/> class and DeepLoaded.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual TList<Cart> DeepLoadByIsShoppingCart(bool _isShoppingCart, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes)
{
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepLoadByIsShoppingCart");
bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
TList<Cart> list = GetByIsShoppingCart(_isShoppingCart);
//Check to see if list is not null, before attempting to Deep Load
if (list != null)
DeepLoad(list, deep, deepLoadType, childTypes);
return list;
}
/// <summary>
/// public virtualDeep Loads the requested <see cref="Cart"/> by the entity keys. The criteria of the child
/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
/// </summary>
/// <param name="_cartId"></param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
/// <param name="childTypes">Cart Property Collection Type Array To Include or Exclude from Load</param>
/// <returns>Returns an instance of the <see cref="Cart"/> class and DeepLoaded.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual Cart DeepLoadByCartId(int _cartId, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes)
{
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepLoadByCartId");
bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
Cart entity = GetByCartId(_cartId);
//Check to see if entity is not null, before attempting to Deep Load
if (entity != null)
DeepLoad(entity, deep, deepLoadType, childTypes);
return entity;
}
#endregion
#region DeepLoad By Entity
/// <summary>
/// public virtualDeep Load the IEntity object with all of the child
/// property collections only 1 Level Deep.
/// </summary>
/// <param name="entity">Cart Object</param>
/// <remarks>
/// <seealso cref="DeepLoad(Cart)"/> overloaded methods for a recursive N Level deep loading method.
/// </remarks>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual void DeepLoad(Cart entity)
{
DeepLoad(entity, false, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// public virtualDeep Load the IEntity object with all of the child
/// property collections only 1 Level Deep.
/// </summary>
/// <remarks>
/// <seealso cref="DeepLoad(Cart)"/> overloaded methods for a recursive N Level deep loading method.
/// </remarks>
/// <param name="entity">Cart Object</param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual void DeepLoad(Cart entity, bool deep)
{
DeepLoad(entity, deep, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// public virtualDeep Loads the <see cref="IEntity"/> object with criteria based of the child
/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
/// </summary>
/// <remarks>
/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
/// </remarks>
/// <param name="entity">The <see cref="Cart"/> object to load.</param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively load all Property Collections that are descendants of this instance.
/// If True, saves the complete object graph below this object. If False, saves this object only. </param>
/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
/// <param name="childTypes">Cart Property Collection Type Array To Include or Exclude from Load</param>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual void DeepLoad(Cart entity, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepLoad");
#endregion Security check
#region Initialisation
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.DeepLoad(transactionManager, entity, deep, deepLoadType, childTypes);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return;
}
#endregion
#region DeepLoad By Entity Collection
/// <summary>
/// Deep Loads the <see cref="TList{Cart}" /> object with all of the child
/// property collections only 1 Level Deep.
/// </summary>
/// <remarks>
/// <seealso cref="DeepLoad(Cart)"/> overloaded methods for a recursive N Level deep loading method.
/// </remarks>
/// <param name="entityCollection">the <see cref="TList{Cart}" /> Object to deep loads.</param>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual void DeepLoad(TList<Cart> entityCollection)
{
DeepLoad(entityCollection, false, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// Deep Loads the <see cref="TList{Cart}" /> object.
/// </summary>
/// <remarks>
/// <seealso cref="DeepLoad(Cart)"/> overloaded methods for a recursive N Level deep loading method.
/// </remarks>
/// <param name="entityCollection">the <see cref="TList{Cart}" /> Object to deep loads.</param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
[DataObjectMethod(DataObjectMethodType.Select)]
public virtual void DeepLoad(TList<Cart> entityCollection, bool deep)
{
DeepLoad(entityCollection, deep, DeepLoadType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// Deep Loads the entire <see cref="TList{Cart}" /> object with criteria based of the child
/// property collections only N Levels Deep based on the DeepLoadType.
/// </summary>
/// <remarks>
/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire collection's object graph.
/// </remarks>
/// <param name="entityCollection">The <see cref="TList{Cart}" /> instance to load.</param>
/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
/// <param name="deepLoadType"><see cref="DeepLoadType"/> Enumeration to Include/Exclude object property collections from Load.
/// Use DeepLoadType.IncludeChildren, ExcludeChildren to traverse the entire object graph.
/// </param>
/// <param name="childTypes"><see cref="Cart"/> Property Collection Type Array To Include or Exclude from Load</param>
[DataObjectMethod(DataObjectMethodType.Select, false)]
public override void DeepLoad(TList<Cart> entityCollection, bool deep, DeepLoadType deepLoadType, params System.Type[] childTypes)
{
#region Security check
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepLoad");
#endregion Security check
#region Initialisation
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
transactionManager = ConnectionScope.ValidateOrCreateTransaction(noTranByDefault);
dataProvider = ConnectionScope.Current.DataProvider;
dataProvider.CartProvider.DeepLoad(transactionManager, entityCollection, deep, deepLoadType, childTypes);
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return;
}
#endregion
#endregion
#region DeepSave
#region DeepSave By Entity
/// <summary>
/// public virtualDeep Saves the <see cref="Cart"/> object with all of the child
/// property collections N Levels Deep.
/// </summary>
/// <param name="entity">Cart Object</param>
[DataObjectMethod(DataObjectMethodType.Update)]
public override bool DeepSave(Cart entity)
{
return DeepSave(entity, DeepSaveType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// public virtualDeep Saves the entire object graph of the Cart object with criteria based of the child
/// Type property array and DeepSaveType.
/// </summary>
/// <param name="entity">Cart Object</param>
/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
/// <param name="childTypes"><c>Cart</c> property Type Array To Include or Exclude from Save</param>
[DataObjectMethod(DataObjectMethodType.Update)]
public override bool DeepSave(Cart entity, DeepSaveType deepSaveType, params System.Type[] childTypes)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepSave");
if (!entity.IsValid)
{
throw new EntityNotValidException(entity, "DeepSave");
}
#endregion Security and validation check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
//since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
transactionManager = ConnectionScope.ValidateOrCreateTransaction();
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.DeepSave(transactionManager, entity, deepSaveType, childTypes);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion
#region DeepSave By Entity Collection
/// <summary>
/// Deep Save the entire <see cref="TList{Cart}" /> object with all of the child
/// property collections.
/// </summary>
/// <param name="entityCollection">TList{Cart} Object</param>
[DataObjectMethod(DataObjectMethodType.Update)]
public virtual bool DeepSave(TList<Cart> entityCollection)
{
return DeepSave(entityCollection, DeepSaveType.ExcludeChildren, System.Type.EmptyTypes);
}
/// <summary>
/// Deep Save the entire object graph of the <see cref="TList{Cart}" /> object with criteria based of the child
/// property collections.
/// </summary>
/// <param name="entityCollection"><see cref="TList{Cart}" /> Object</param>
/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
/// <param name="childTypes">Cart Property Collection Type Array To Include or Exclude from Save</param>
[DataObjectMethod(DataObjectMethodType.Update)]
public override bool DeepSave(TList<Cart> entityCollection, DeepSaveType deepSaveType, params System.Type[] childTypes)
{
#region Security and validation check
// throws security exception if not authorized
SecurityContext.IsAuthorized("DeepSave");
if (!entityCollection.IsValid)
{
throw new EntityNotValidException(entityCollection, "DeepSave");
}
#endregion Security and validation check
#region Initialisation
bool result = false;
bool isBorrowedTransaction = false;
TransactionManager transactionManager = null;
NetTiersProvider dataProvider = null;
#endregion Initialisation
try
{
isBorrowedTransaction = ConnectionScope.Current.HasTransaction;
//since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
transactionManager = ConnectionScope.ValidateOrCreateTransaction();
dataProvider = ConnectionScope.Current.DataProvider;
result = dataProvider.CartProvider.DeepSave(transactionManager, entityCollection, deepSaveType, childTypes);
if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
transactionManager.Commit();
}
catch (Exception exc)
{
#region Handle transaction rollback and exception
if (transactionManager != null && transactionManager.IsOpen)
transactionManager.Rollback();
//Handle exception based on policy
if (DomainUtil.HandleException(exc, layerExceptionPolicy))
throw;
#endregion Handle transaction rollback and exception
}
return result;
}
#endregion
#endregion
#endregion Data Access Methods
}//End Class
} // end namespace
| netTiers/netTiers | Samples/Petshop/Source/PetShop.Services/CartServiceBase.generated.cs | C# | mit | 72,915 |
/*
Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.*/
using System;
using System.Data;
using System.Linq;
using Utilities.DataTypes;
using Utilities.ORM.Interfaces;
using Utilities.ORM.Manager.Schema.Default.Database;
using Utilities.ORM.Manager.Schema.Interfaces;
using Utilities.ORM.Manager.SourceProvider.Interfaces;
using Xunit;
namespace UnitTests.ORM.Manager
{
public class ORMManager : DatabaseBaseClass
{
[Fact]
public void Create()
{
var Temp = new Utilities.ORM.Manager.ORMManager(Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Mapper.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.QueryProvider.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.Schema.Manager>(),
Utilities.IoC.Manager.Bootstrapper.Resolve<Utilities.ORM.Manager.SourceProvider.Manager>(),
Utilities.IoC.Manager.Bootstrapper.ResolveAll<IDatabase>());
Assert.NotNull(Temp);
Assert.Equal("ORM Manager\r\n", Temp.ToString());
}
}
} | JaCraig/Craig-s-Utility-Library | UnitTests/ORM/Manager/ORMManager.cs | C# | mit | 2,173 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Image_Graph - PEAR PHP OO Graph Rendering Utility.
*
* PHP versions 4 and 5
*
* LICENSE: This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version. This library 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 Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this library; if not, write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* @category Images
* @package Image_Graph
* @subpackage Plot
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version CVS: $Id: Band.php,v 1.3 2009/10/14 06:53:49 mhoegh Exp $
* @link http://pear.php.net/package/Image_Graph
* @since File available since Release 0.3.0dev2
*/
/**
* Include file Image/Graph/Plot.php
*/
require_once 'Image/Graph/Plot.php';
/**
* "Band" (area chart with min AND max) chart.
*
* @category Images
* @package Image_Graph
* @subpackage Plot
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Graph
* @since Class available since Release 0.3.0dev2
*/
class Image_Graph_Plot_Band extends Image_Graph_Plot
{
/**
* Perform the actual drawing on the legend.
*
* @param int $x0 The top-left x-coordinate
* @param int $y0 The top-left y-coordinate
* @param int $x1 The bottom-right x-coordinate
* @param int $y1 The bottom-right y-coordinate
* @access private
*/
function _drawLegendSample($x0, $y0, $x1, $y1)
{
$h = abs($y1 - $y0) / 6;
$w = round(abs($x1 - $x0) / 5);
$y = ($y0 + $y1) / 2;
$this->_canvas->addVertex(array('x' => $x0, 'y' => $y - $h * 3));
$this->_canvas->addVertex(array('x' => $x0 + $w, 'y' => $y - 4 * $h));
$this->_canvas->addVertex(array('x' => $x0 + 2 * $w, 'y' => $y - $h * 2));
$this->_canvas->addVertex(array('x' => $x0 + 3 * $w, 'y' => $y - $h * 4));
$this->_canvas->addVertex(array('x' => $x0 + 4 * $w, 'y' => $y - $h * 3));
$this->_canvas->addVertex(array('x' => $x1, 'y' => $y - $h * 2));
$this->_canvas->addVertex(array('x' => $x1, 'y' => $y + $h * 3));
$this->_canvas->addVertex(array('x' => $x0 + 4 * $w, 'y' => $y + $h));
$this->_canvas->addVertex(array('x' => $x0 + 3 * $w, 'y' => $y + 2 * $h));
$this->_canvas->addVertex(array('x' => $x0 + 2 * $w, 'y' => $y + 1 * $h));
$this->_canvas->addVertex(array('x' => $x0 + 1 * $w, 'y' => $y));
$this->_canvas->addVertex(array('x' => $x0, 'y' => $y + $h));
$this->_getLineStyle();
$this->_getFillStyle();
$this->_canvas->polygon(array('connect' => true));
}
/**
* Output the plot
*
* @return bool Was the output 'good' (true) or 'bad' (false).
* @access private
*/
function _done()
{
if (parent::_done() === false) {
return false;
}
if (!is_array($this->_dataset)) {
return false;
}
$current = array();
$this->_canvas->startGroup(get_class($this) . '_' . $this->_title);
$this->_clip(true);
$keys = array_keys($this->_dataset);
foreach ($keys as $key) {
$dataset =& $this->_dataset[$key];
$dataset->_reset();
$upperBand = array();
$lowerBand = array();
while ($data = $dataset->_next()) {
if ($this->_parent->_horizontal) {
$point['X'] = $data['X'];
$point['Y'] = $data['Y']['high'];
$y = $this->_pointY($point);
$x_high = $this->_pointX($point);
$point['Y'] = $data['Y']['low'];
$x_low = $this->_pointX($point);
$data = array('X' => $x_high, 'Y' => $y);
if (isset($point['data'])) {
$data['data'] = $point['data'];
} else {
$data['data'] = array();
}
$upperBand[] = $data;
$data = array('X' => $x_low, 'Y' => $y);
if (isset($point['data'])) {
$data['data'] = $point['data'];
} else {
$data['data'] = array();
}
$lowerBand[] = $data;
}
else {
$point['X'] = $data['X'];
$y = $data['Y'];
$point['Y'] = $data['Y']['high'];
$x = $this->_pointX($point);
$y_high = $this->_pointY($point);
$point['Y'] = $data['Y']['low'];
$y_low = $this->_pointY($point);
$data = array('X' => $x, 'Y' => $y_high);
if (isset($point['data'])) {
$data['data'] = $point['data'];
} else {
$data['data'] = array();
}
$upperBand[] = $data;
$data = array('X' => $x, 'Y' => $y_low);
if (isset($point['data'])) {
$data['data'] = $point['data'];
} else {
$data['data'] = array();
}
$lowerBand[] = $data;
}
}
$lowerBand = array_reverse($lowerBand);
foreach ($lowerBand as $point) {
$this->_canvas->addVertex(
$this->_mergeData(
$point['data'],
array('x' => $point['X'], 'y' => $point['Y'])
)
);
}
foreach ($upperBand as $point) {
$this->_canvas->addVertex(
$this->_mergeData(
$point['data'],
array('x' => $point['X'], 'y' => $point['Y'])
)
);
}
unset($upperBand);
unset($lowerBand);
$this->_getLineStyle($key);
$this->_getFillStyle($key);
$this->_canvas->polygon(array('connect' => true, 'map_vertices' => true));
}
unset($keys);
$this->_drawMarker();
$this->_clip(false);
$this->_canvas->endGroup();
return true;
}
}
?> | pcucurullo/groot | app/libs/PEAR/Image/Graph/Plot/Band.php | PHP | mit | 7,414 |
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for duplicated instance (or singleton) method
# definitions.
#
# @example
#
# # bad
#
# def foo
# 1
# end
#
# def foo
# 2
# end
#
# @example
#
# # bad
#
# def foo
# 1
# end
#
# alias foo bar
#
# @example
#
# # good
#
# def foo
# 1
# end
#
# def bar
# 2
# end
#
# @example
#
# # good
#
# def foo
# 1
# end
#
# alias bar foo
class DuplicateMethods < Cop
MSG = 'Method `%<method>s` is defined at both %<defined>s and ' \
'%<current>s.'
def initialize(config = nil, options = nil)
super
@definitions = {}
end
def on_def(node)
# if a method definition is inside an if, it is very likely
# that a different definition is used depending on platform, etc.
return if node.ancestors.any?(&:if_type?)
return if possible_dsl?(node)
found_instance_method(node, node.method_name)
end
def on_defs(node)
return if node.ancestors.any?(&:if_type?)
return if possible_dsl?(node)
if node.receiver.const_type?
_, const_name = *node.receiver
check_const_receiver(node, node.method_name, const_name)
elsif node.receiver.self_type?
check_self_receiver(node, node.method_name)
end
end
def_node_matcher :method_alias?, <<-PATTERN
(alias (sym $_name) sym)
PATTERN
def on_alias(node)
return unless (name = method_alias?(node))
return if node.ancestors.any?(&:if_type?)
return if possible_dsl?(node)
found_instance_method(node, name)
end
def_node_matcher :alias_method?, <<-PATTERN
(send nil? :alias_method (sym $_name) _)
PATTERN
def_node_matcher :attr?, <<-PATTERN
(send nil? ${:attr_reader :attr_writer :attr_accessor :attr} $...)
PATTERN
def_node_matcher :sym_name, '(sym $_name)'
def on_send(node)
if (name = alias_method?(node))
return unless name
return if node.ancestors.any?(&:if_type?)
return if possible_dsl?(node)
found_instance_method(node, name)
elsif (attr = attr?(node))
on_attr(node, *attr)
end
end
private
def check_const_receiver(node, name, const_name)
qualified = lookup_constant(node, const_name)
return unless qualified
found_method(node, "#{qualified}.#{name}")
end
def check_self_receiver(node, name)
enclosing = node.parent_module_name
return unless enclosing
found_method(node, "#{enclosing}.#{name}")
end
def message_for_dup(node, method_name)
format(MSG, method: method_name, defined: @definitions[method_name],
current: source_location(node))
end
def found_instance_method(node, name)
return unless (scope = node.parent_module_name)
if scope =~ /\A#<Class:(.*)>\Z/
found_method(node, "#{Regexp.last_match(1)}.#{name}")
else
found_method(node, "#{scope}##{name}")
end
end
def found_method(node, method_name)
if @definitions.key?(method_name)
loc = case node.type
when :def, :defs
node.loc.keyword.join(node.loc.name)
else
node.loc.expression
end
message = message_for_dup(node, method_name)
add_offense(node, location: loc, message: message)
else
@definitions[method_name] = source_location(node)
end
end
def on_attr(node, attr_name, args)
case attr_name
when :attr
writable = args.size == 2 && args.last.true_type?
found_attr(node, [args.first], readable: true, writable: writable)
when :attr_reader
found_attr(node, args, readable: true)
when :attr_writer
found_attr(node, args, writable: true)
when :attr_accessor
found_attr(node, args, readable: true, writable: true)
end
end
def found_attr(node, args, readable: false, writable: false)
args.each do |arg|
name = sym_name(arg)
next unless name
found_instance_method(node, name) if readable
found_instance_method(node, "#{name}=") if writable
end
end
def lookup_constant(node, const_name)
# this method is quite imperfect and can be fooled
# to do much better, we would need to do global analysis of the whole
# codebase
node.each_ancestor(:class, :module, :casgn) do |ancestor|
namespace, mod_name = *ancestor.defined_module
loop do
if mod_name == const_name
return qualified_name(ancestor.parent_module_name,
namespace,
mod_name)
end
break if namespace.nil?
namespace, mod_name = *namespace
end
end
end
def qualified_name(enclosing, namespace, mod_name)
if enclosing != 'Object'
if namespace
"#{enclosing}::#{namespace.const_name}::#{mod_name}"
else
"#{enclosing}::#{mod_name}"
end
elsif namespace
"#{namespace.const_name}::#{mod_name}"
else
mod_name
end
end
def possible_dsl?(node)
# DSL methods may evaluate a block in the context of a newly created
# class or module
# Assume that if a method definition is inside any block call which
# we can't identify, it could be a DSL
node.each_ancestor(:block).any? do |ancestor|
ancestor.method_name != :class_eval && !ancestor.class_constructor?
end
end
def source_location(node)
range = node.location.expression
path = smart_path(range.source_buffer.name)
"#{path}:#{range.line}"
end
end
end
end
end
| vergenzt/rubocop | lib/rubocop/cop/lint/duplicate_methods.rb | Ruby | mit | 6,718 |
package com.microsoft.bingads.v10.api.test.entities.ad_extension.call.read;
import com.microsoft.bingads.v10.api.test.entities.ad_extension.call.BulkCallAdExtensionTest;
import com.microsoft.bingads.v10.bulk.entities.BulkCallAdExtension;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class BulkCallAdExtensionReadFromRowValuesVersionTest extends BulkCallAdExtensionTest {
@Parameter(value = 1)
public Integer expectedResult;
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"123", 123},
{"2147483647", 2147483647},
{"", null},
{null, null}
});
}
@Test
public void testRead() {
this.<Integer>testReadProperty("Version", this.datum, this.expectedResult, new Function<BulkCallAdExtension, Integer>() {
@Override
public Integer apply(BulkCallAdExtension c) {
return c.getCallAdExtension().getVersion();
}
});
}
}
| JeffRisberg/BING01 | src/test/java/com/microsoft/bingads/v10/api/test/entities/ad_extension/call/read/BulkCallAdExtensionReadFromRowValuesVersionTest.java | Java | mit | 1,334 |
#include <boost/config.hpp>
//
// bind_fwd_test.cpp - forwarding test
//
// Copyright (c) 2015 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/bind/bind.hpp>
#include <boost/core/lightweight_test.hpp>
using namespace boost::placeholders;
//
void fv1( int & a )
{
a = 1;
}
void fv2( int & a, int & b )
{
a = 1;
b = 2;
}
void fv3( int & a, int & b, int & c )
{
a = 1;
b = 2;
c = 3;
}
void fv4( int & a, int & b, int & c, int & d )
{
a = 1;
b = 2;
c = 3;
d = 4;
}
void fv5( int & a, int & b, int & c, int & d, int & e )
{
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
}
void fv6( int & a, int & b, int & c, int & d, int & e, int & f )
{
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = 6;
}
void fv7( int & a, int & b, int & c, int & d, int & e, int & f, int & g )
{
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = 6;
g = 7;
}
void fv8( int & a, int & b, int & c, int & d, int & e, int & f, int & g, int & h )
{
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = 6;
g = 7;
h = 8;
}
void fv9( int & a, int & b, int & c, int & d, int & e, int & f, int & g, int & h, int & i )
{
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = 6;
g = 7;
h = 8;
i = 9;
}
void test()
{
{
int a = 0;
boost::bind( fv1, _1 )( a );
BOOST_TEST( a == 1 );
}
{
int a = 0;
int b = 0;
boost::bind( fv2, _1, _2 )( a, b );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
}
{
int a = 0;
int b = 0;
int c = 0;
boost::bind( fv3, _1, _2, _3 )( a, b, c );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
boost::bind( fv4, _1, _2, _3, _4 )( a, b, c, d );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
boost::bind( fv5, _1, _2, _3, _4, _5 )( a, b, c, d, e );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
BOOST_TEST( e == 5 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
boost::bind( fv6, _1, _2, _3, _4, _5, _6 )( a, b, c, d, e, f );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
BOOST_TEST( e == 5 );
BOOST_TEST( f == 6 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
boost::bind( fv7, _1, _2, _3, _4, _5, _6, _7 )( a, b, c, d, e, f, g );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
BOOST_TEST( e == 5 );
BOOST_TEST( f == 6 );
BOOST_TEST( g == 7 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
boost::bind( fv8, _1, _2, _3, _4, _5, _6, _7, _8 )( a, b, c, d, e, f, g, h );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
BOOST_TEST( e == 5 );
BOOST_TEST( f == 6 );
BOOST_TEST( g == 7 );
BOOST_TEST( h == 8 );
}
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
int i = 0;
boost::bind( fv9, _1, _2, _3, _4, _5, _6, _7, _8, _9 )( a, b, c, d, e, f, g, h, i );
BOOST_TEST( a == 1 );
BOOST_TEST( b == 2 );
BOOST_TEST( c == 3 );
BOOST_TEST( d == 4 );
BOOST_TEST( e == 5 );
BOOST_TEST( f == 6 );
BOOST_TEST( g == 7 );
BOOST_TEST( h == 8 );
BOOST_TEST( i == 9 );
}
}
int main()
{
test();
return boost::report_errors();
}
| davehorton/drachtio-server | deps/boost_1_77_0/libs/bind/test/bind_fwd_test.cpp | C++ | mit | 4,438 |
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
package com.iluwatar.factory.method;
/**
* WeaponType enumeration.
*/
public enum WeaponType {
SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
private final String title;
WeaponType(String title) {
this.title = title;
}
@Override
public String toString() {
return title;
}
}
| mookkiah/java-design-patterns | factory-method/src/main/java/com/iluwatar/factory/method/WeaponType.java | Java | mit | 1,471 |
<?php
namespace Neos\Flow\Validation\Validator;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Validation\Exception\InvalidValidationOptionsException;
/**
* Validator for checking Date and Time boundaries
*
* @api
*/
class DateTimeRangeValidator extends AbstractValidator
{
/**
* @var array
*/
protected $supportedOptions = [
'latestDate' => [null, 'The latest date to accept', 'string'],
'earliestDate' => [null, 'The earliest date to accept', 'string']
];
/**
* Adds errors if the given DateTime does not match the set boundaries.
*
* latestDate and earliestDate may be each <time>, <start>/<duration> or <duration>/<end>, where <duration> is an
* ISO 8601 duration and <start> or <end> or <time> may be 'now' or a PHP supported format. (1)
*
* In general, you are able to provide a timestamp or a timestamp with additional calculation. Calculations are done
* as described in ISO 8601 (2), with an introducing "P". P7MT2H30M for example mean a period of 7 months, 2 hours
* and 30 minutes (P introduces a period at all, while a following T introduces the time-section of a period. This
* is not at least in order not to confuse months and minutes, both represented as M).
* A period is separated from the timestamp with a forward slash "/". If the period follows the timestamp, that
* period is added to the timestamp; if the period precedes the timestamp, it's subtracted.
* The timestamp can be one of PHP's supported date formats (1), so also "now" is supported.
*
* Use cases:
*
* If you offer something that has to be manufactured and you ask for a delivery date, you might assure that this
* date is at least two weeks in advance; this could be done with the expression "now/P2W".
* If you have a library of ancient goods and want to track a production date that is at least 5 years ago, you can
* express it with "P5Y/now".
*
* Examples:
*
* If you want to test if a given date is at least five minutes ahead, use
* earliestDate: now/PT5M
* If you want to test if a given date was at least 10 days ago, use
* latestDate: P10D/now
* If you want to test if a given date is between two fix boundaries, just combine the latestDate and earliestDate-options:
* earliestDate: 2007-03-01T13:00:00Z
* latestDate: 2007-03-30T13:00:00Z
*
* Footnotes:
*
* http://de.php.net/manual/en/datetime.formats.compound.php (1)
* http://en.wikipedia.org/wiki/ISO_8601#Durations (2)
* http://en.wikipedia.org/wiki/ISO_8601#Time_intervals (3)
*
* @param mixed $dateTime The DateTime value that should be validated
* @return void
* @api
*/
protected function isValid($dateTime)
{
if (!$dateTime instanceof \DateTimeInterface) {
$this->addError('The given value was not a valid date', 1324314378);
return;
}
$earliestDate = isset($this->options['earliestDate']) ? $this->parseReferenceDate($this->options['earliestDate']) : null;
$latestDate = isset($this->options['latestDate']) ? $this->parseReferenceDate($this->options['latestDate']) : null;
if (isset($earliestDate) && isset($latestDate)) {
if ($dateTime < $earliestDate || $dateTime > $latestDate) {
$this->addError('The given date must be between %s and %s', 1325615630, [$earliestDate->format('Y-m-d H:i:s'), $latestDate->format('Y-m-d H:i:s')]);
}
} elseif (isset($earliestDate)) {
if ($dateTime < $earliestDate) {
$this->addError('The given date must be after %s', 1324315107, [$earliestDate->format('Y-m-d H:i:s')]);
}
} elseif (isset($latestDate)) {
if ($dateTime > $latestDate) {
$this->addError('The given date must be before %s', 1324315115, [$latestDate->format('Y-m-d H:i:s')]);
}
}
}
/**
* Calculates a DateTime object from a given Time interval
*
* @param string $referenceDateString being one of <time>, <start>/<offset> or <offset>/<end>
* @return \DateTime
* @throws InvalidValidationOptionsException
* @see isValid()
*/
protected function parseReferenceDate($referenceDateString)
{
$referenceDateParts = explode('/', $referenceDateString, 2);
if (count($referenceDateParts) === 1) {
// assume a valid Date/Time string
return new \DateTime($referenceDateParts[0]);
}
// check if the period (the interval) is the first or second item:
if (strpos($referenceDateParts[0], 'P') === 0) {
$interval = new \DateInterval($referenceDateParts[0]);
$date = new \DateTime($referenceDateParts[1]);
return $date->sub($interval);
} elseif (strpos($referenceDateParts[1], 'P') === 0) {
$interval = new \DateInterval($referenceDateParts[1]);
$date = new \DateTime($referenceDateParts[0]);
return $date->add($interval);
} else {
throw new InvalidValidationOptionsException(sprintf('There is no valid interval declaration in "%s". Exactly one part must begin with "P".', $referenceDateString), 1324314462);
}
}
}
| gerhard-boden/flow-development-collection | Neos.Flow/Classes/Validation/Validator/DateTimeRangeValidator.php | PHP | mit | 5,604 |
var layer = require('../index')
, should = require('should');
var prettyNum = function(i) {
var a = i.toString().split('')
, alen = a.length
, howMany = Math.floor(alen / 3);
for (var idx = alen - 3; howMany > 0; howMany--) {
a.splice(idx, 0, ',');
idx = idx - 3;
}
return a.join('');
}
module.exports = function(testMode) {
// don't require workbench when just wanting to run tests
if (testMode) {
var bench = {};
bench.cycles = function(fn, time) {
var cycles = 0
, startTime = Date.now()
, time = time * 1000;
while (true) {
fn();
if ((Date.now() - startTime) > time) break;
cycles++;
}
return cycles;
}
} else {
var bench = require('../../workbench/index');
}
/*
should return arguments.length and check the return instead
*/
var actual = {
args0: function() {
if (testMode)
(arguments.length).should.be.equal(0);
},
args1: function(x) {
if (testMode)
(arguments.length).should.be.equal(1);
},
args2: function(x,y) {
if (testMode)
(arguments.length).should.be.equal(2);
},
args3: function(x,y,z) {
if (testMode)
(arguments.length).should.be.equal(3);
},
args4: function(a,b,c,d) {
if (testMode)
(arguments.length).should.be.equal(4);
},
args5: function(a,b,c,d,e) {
if (testMode)
(arguments.length).should.be.equal(5);
}
}
var args0 = function() {}
, args1 = function(x, next) { next(x); }
, args2 = function(x,y, next) { next(x,y); }
, args3 = function(x,y,z, next) { next(x,y,z); }
, args4 = function(a,b,c,d, next) { next(a,b,c,d); }
, args5 = function(a,b,c,d,e, next) { next(a,b,c,d,e); };
layer.set(actual, actual.args0, args0);
layer.set(actual, actual.args1, args1);
layer.set(actual, actual.args2, args2);
layer.set(actual, actual.args3, args3);
layer.set(actual, actual.args4, args4);
layer.set(actual, actual.args5, args5);
function runner(fn, name) {
var time;
(testMode) ? time = 0.01 : time = 7;
var cycles = prettyNum(bench.cycles(fn, time));
if (!testMode) console.log(name, cycles);
}
runner(function() { actual.args0(); }, 'args0');
runner(function() { actual.args1(1); }, 'args1');
runner(function() { actual.args2(1, 2); }, 'args2');
runner(function() { actual.args3(1, 2, 3); }, 'args3');
runner(function() { actual.args4(1, 2, 3, 4); }, 'args4');
runner(function() { actual.args5(1, 2, 3, 4, 5); }, 'args5');
} | lovebear/layer | benchmark/setup.js | JavaScript | mit | 2,574 |
var util = require('util')
var Transform = require('stream').Transform
util.inherits(Concat, Transform)
function Concat(cb) {
Transform.call(this)
this.cb = cb
this.buffers = []
}
Concat.prototype._transform = function(chunk, encoding, done) {
this.buffers.push(chunk)
this.push(chunk)
done()
}
Concat.prototype._flush = function(done) {
this.cb(this.buffers)
done()
}
process.stdin.pipe(new Concat(log))
function log(buffs) {
console.log(Buffer.concat(buffs))
}
| nmarley/node-playground | bytewiser/buffer-concat-official.js | JavaScript | mit | 486 |
using UnityEditor;
using UnityEngine;
[CanEditMultipleObjects, CustomEditor(typeof(MegaShapeArc))]
public class MegaShapeArcEditor : MegaShapeEditor
{
public override bool Params()
{
MegaShapeArc shape = (MegaShapeArc)target;
bool rebuild = false;
float v = EditorGUILayout.FloatField("Radius", shape.radius);
if ( v != shape.radius )
{
shape.radius = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("From", shape.from);
if ( v != shape.from )
{
shape.from = v;
rebuild = true;
}
v = EditorGUILayout.FloatField("To", shape.to);
if ( v != shape.to )
{
shape.to = v;
rebuild = true;
}
bool bv = EditorGUILayout.Toggle("Pie", shape.pie);
if ( bv != shape.pie )
{
shape.pie = bv;
rebuild = true;
}
return rebuild;
}
} | lejeanf/VisualExperiments | Visual_Experiments/Assets/Plugins/Mega-Fiers/Editor/MegaFiers/MegaShape/MegaShapeArcEditor.cs | C# | mit | 793 |
class TestMJruby < MTest::Unit::TestCase
def test_jruby_opts_env
ENV['JRUBY_OPTS'] = "--dev -J-cp foo.jar --2.0 -J-Xms1g"
assert_equal jruby_opts_env, ["--dev", "-J-cp", "foo.jar", "--2.0", "-J-Xms1g"]
end
end
MTest::Unit.new.run
| enebo/mjruby | test/test_mjruby.rb | Ruby | mit | 248 |
'use strict';
function calcCacheSize() {
var size = 0;
for(var key in jqLite.cache) { size++; }
return size;
}
describe('$compile', function() {
var element, directive, $compile, $rootScope;
beforeEach(module(provideLog, function($provide, $compileProvider){
element = null;
directive = $compileProvider.directive;
directive('log', function(log) {
return {
restrict: 'CAM',
priority:0,
compile: valueFn(function(scope, element, attrs) {
log(attrs.log || 'LOG');
})
};
});
directive('highLog', function(log) {
return { restrict: 'CAM', priority:3, compile: valueFn(function(scope, element, attrs) {
log(attrs.highLog || 'HIGH');
})};
});
directive('mediumLog', function(log) {
return { restrict: 'CAM', priority:2, compile: valueFn(function(scope, element, attrs) {
log(attrs.mediumLog || 'MEDIUM');
})};
});
directive('greet', function() {
return { restrict: 'CAM', priority:10, compile: valueFn(function(scope, element, attrs) {
element.text("Hello " + attrs.greet);
})};
});
directive('set', function() {
return function(scope, element, attrs) {
element.text(attrs.set);
};
});
directive('mediumStop', valueFn({
priority: 2,
terminal: true
}));
directive('stop', valueFn({
terminal: true
}));
directive('negativeStop', valueFn({
priority: -100, // even with negative priority we still should be able to stop descend
terminal: true
}));
return function(_$compile_, _$rootScope_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
};
}));
function compile(html) {
element = angular.element(html);
$compile(element)($rootScope);
}
afterEach(function(){
dealoc(element);
});
describe('configuration', function() {
it('should register a directive', function() {
module(function() {
directive('div', function(log) {
return {
restrict: 'ECA',
link: function(scope, element) {
log('OK');
element.text('SUCCESS');
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div></div>')($rootScope);
expect(element.text()).toEqual('SUCCESS');
expect(log).toEqual('OK');
});
});
it('should allow registration of multiple directives with same name', function() {
module(function() {
directive('div', function(log) {
return {
restrict: 'ECA',
link: {
pre: log.fn('pre1'),
post: log.fn('post1')
}
};
});
directive('div', function(log) {
return {
restrict: 'ECA',
link: {
pre: log.fn('pre2'),
post: log.fn('post2')
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div></div>')($rootScope);
expect(log).toEqual('pre1; pre2; post2; post1');
});
});
it('should throw an exception if a directive is called "hasOwnProperty"', function() {
module(function() {
expect(function() {
directive('hasOwnProperty', function() { });
}).toThrowMinErr('ng','badname', "hasOwnProperty is not a valid directive name");
});
inject(function($compile) {});
});
});
describe('compile phase', function() {
it('should attach scope to the document node when it is compiled explicitly', inject(function($document){
$compile($document)($rootScope);
expect($document.scope()).toBe($rootScope);
}));
it('should wrap root text nodes in spans', inject(function($compile, $rootScope) {
element = jqLite('<div>A<a>B</a>C</div>');
var text = element.contents();
expect(text[0].nodeName).toEqual('#text');
text = $compile(text)($rootScope);
expect(text[0].nodeName).toEqual('SPAN');
expect(element.find('span').text()).toEqual('A<a>B</a>C');
}));
it('should not wrap root whitespace text nodes in spans', function() {
element = jqLite(
'<div> <div>A</div>\n '+ // The spaces and newlines here should not get wrapped
'<div>B</div>C\t\n '+ // The "C", tabs and spaces here will be wrapped
'</div>');
$compile(element.contents())($rootScope);
var spans = element.find('span');
expect(spans.length).toEqual(1);
expect(spans.text().indexOf('C')).toEqual(0);
});
it('should not leak memory when there are top level empty text nodes', function() {
// We compile the contents of element (i.e. not element itself)
// Then delete these contents and check the cache has been reset to zero
// First with only elements at the top level
element = jqLite('<div><div></div></div>');
$compile(element.contents())($rootScope);
element.empty();
expect(calcCacheSize()).toEqual(0);
// Next with non-empty text nodes at the top level
// (in this case the compiler will wrap them in a <span>)
element = jqLite('<div>xxx</div>');
$compile(element.contents())($rootScope);
element.empty();
expect(calcCacheSize()).toEqual(0);
// Next with comment nodes at the top level
element = jqLite('<div><!-- comment --></div>');
$compile(element.contents())($rootScope);
element.empty();
expect(calcCacheSize()).toEqual(0);
// Finally with empty text nodes at the top level
element = jqLite('<div> \n<div></div> </div>');
$compile(element.contents())($rootScope);
element.empty();
expect(calcCacheSize()).toEqual(0);
});
it('should not blow up when elements with no childNodes property are compiled', inject(
function($compile, $rootScope) {
// it turns out that when a browser plugin is bound to an DOM element (typically <object>),
// the plugin's context rather than the usual DOM apis are exposed on this element, so
// childNodes might not exist.
if (msie < 9) return;
element = jqLite('<div>{{1+2}}</div>');
try {
element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'};
} catch(e) {
} finally {
if (!element[0].childNodes[1]) return; //browser doesn't support this kind of mocking
}
expect(element[0].childNodes[1].textContent).toBe('fake node');
$compile(element)($rootScope);
$rootScope.$apply();
// object's children can't be compiled in this case, so we expect them to be raw
expect(element.html()).toBe("3");
}));
describe('multiple directives per element', function() {
it('should allow multiple directives per element', inject(function($compile, $rootScope, log){
element = $compile(
'<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>')
($rootScope);
expect(element.text()).toEqual('Hello angular');
expect(log).toEqual('L; M; H');
}));
it('should recurse to children', inject(function($compile, $rootScope){
element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope);
expect(element.text()).toEqual('0hello2angular4');
}));
it('should allow directives in classes', inject(function($compile, $rootScope, log) {
element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope);
expect(element.html()).toEqual('Hello angular');
expect(log).toEqual('123');
}));
it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) {
if (!window.SVGElement) return;
// According to spec SVG element className property is readonly, but only FF
// implements it this way which causes compile exceptions.
element = $compile('<svg><text>{{1}}</text></svg>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1');
}));
it('should receive scope, element, and attributes', function() {
var injector;
module(function() {
directive('log', function($injector, $rootScope) {
injector = $injector;
return {
restrict: 'CA',
compile: function(element, templateAttr) {
expect(typeof templateAttr.$normalize).toBe('function');
expect(typeof templateAttr.$set).toBe('function');
expect(isElement(templateAttr.$$element)).toBeTruthy();
expect(element.text()).toEqual('unlinked');
expect(templateAttr.exp).toEqual('abc');
expect(templateAttr.aa).toEqual('A');
expect(templateAttr.bb).toEqual('B');
expect(templateAttr.cc).toEqual('C');
return function(scope, element, attr) {
expect(element.text()).toEqual('unlinked');
expect(attr).toBe(templateAttr);
expect(scope).toEqual($rootScope);
element.text('worked');
};
}
};
});
});
inject(function($rootScope, $compile, $injector) {
element = $compile(
'<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope);
expect(element.text()).toEqual('worked');
expect(injector).toBe($injector); // verify that directive is injectable
});
});
});
describe('error handling', function() {
it('should handle exceptions', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
directive('factoryError', function() { throw 'FactoryError'; });
directive('templateError',
valueFn({ compile: function() { throw 'TemplateError'; } }));
directive('linkingError',
valueFn(function() { throw 'LinkingError'; }));
});
inject(function($rootScope, $compile, $exceptionHandler) {
element = $compile('<div factory-error template-error linking-error></div>')($rootScope);
expect($exceptionHandler.errors[0]).toEqual('FactoryError');
expect($exceptionHandler.errors[1][0]).toEqual('TemplateError');
expect(ie($exceptionHandler.errors[1][1])).
toEqual('<div factory-error linking-error template-error>');
expect($exceptionHandler.errors[2][0]).toEqual('LinkingError');
expect(ie($exceptionHandler.errors[2][1])).
toEqual('<div class="ng-scope" factory-error linking-error template-error>');
// crazy stuff to make IE happy
function ie(text) {
var list = [],
parts, elementName;
parts = lowercase(text).
replace('<', '').
replace('>', '').
split(' ');
elementName = parts.shift();
parts.sort();
parts.unshift(elementName);
forEach(parts, function(value){
if (value.substring(0,2) !== 'ng') {
value = value.replace('=""', '');
var match = value.match(/=(.*)/);
if (match && match[1].charAt(0) != '"') {
value = value.replace(/=(.*)/, '="$1"');
}
list.push(value);
}
});
return '<' + list.join(' ') + '>';
}
});
});
it('should allow changing the template structure after the current node', function() {
module(function(){
directive('after', valueFn({
compile: function(element) {
element.after('<span log>B</span>');
}
}));
});
inject(function($compile, $rootScope, log){
element = jqLite("<div><div after>A</div></div>");
$compile(element)($rootScope);
expect(element.text()).toBe('AB');
expect(log).toEqual('LOG');
});
});
it('should allow changing the template structure after the current node inside ngRepeat', function() {
module(function(){
directive('after', valueFn({
compile: function(element) {
element.after('<span log>B</span>');
}
}));
});
inject(function($compile, $rootScope, log){
element = jqLite('<div><div ng-repeat="i in [1,2]"><div after>A</div></div></div>');
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('ABAB');
expect(log).toEqual('LOG; LOG');
});
});
it('should allow modifying the DOM structure in post link fn', function() {
module(function() {
directive('removeNode', valueFn({
link: function($scope, $element) {
$element.remove();
}
}));
});
inject(function($compile, $rootScope) {
element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>');
$rootScope.test = 'Hello';
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.children().length).toBe(1);
expect(element.text()).toBe('Hello');
});
});
});
describe('compiler control', function() {
describe('priority', function() {
it('should honor priority', inject(function($compile, $rootScope, log){
element = $compile(
'<span log="L" x-high-log="H" data-medium-log="M"></span>')
($rootScope);
expect(log).toEqual('L; M; H');
}));
});
describe('terminal', function() {
it('should prevent further directives from running', inject(function($rootScope, $compile) {
element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope);
expect(element.text()).toEqual('OK');
}
));
it('should prevent further directives from running, but finish current priority level',
inject(function($rootScope, $compile, log) {
// class is processed after attrs, so putting log in class will put it after
// the stop in the current level. This proves that the log runs after stop
element = $compile(
'<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope);
expect(element.text()).toEqual('OK');
expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']);
})
);
});
describe('restrict', function() {
it('should allow restriction of availability', function () {
module(function () {
forEach({div: 'E', attr: 'A', clazz: 'C', comment: 'M', all: 'EACM'},
function (restrict, name) {
directive(name, function (log) {
return {
restrict: restrict,
compile: valueFn(function (scope, element, attr) {
log(name);
})
};
});
});
});
inject(function ($rootScope, $compile, log) {
dealoc($compile('<span div class="div"></span>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<div></div>')($rootScope));
expect(log).toEqual('div');
log.reset();
dealoc($compile('<attr class="attr"></attr>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<span attr></span>')($rootScope));
expect(log).toEqual('attr');
log.reset();
dealoc($compile('<clazz clazz></clazz>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<span class="clazz"></span>')($rootScope));
expect(log).toEqual('clazz');
log.reset();
dealoc($compile('<!-- directive: comment -->')($rootScope));
expect(log).toEqual('comment');
log.reset();
dealoc($compile('<all class="all" all><!-- directive: all --></all>')($rootScope));
expect(log).toEqual('all; all; all; all');
});
});
it('should use EA rule as the default', function () {
module(function () {
directive('defaultDir', function (log) {
return {
compile: function () {
log('defaultDir');
}
};
});
});
inject(function ($rootScope, $compile, log) {
dealoc($compile('<span default-dir ></span>')($rootScope));
expect(log).toEqual('defaultDir');
log.reset();
dealoc($compile('<default-dir></default-dir>')($rootScope));
expect(log).toEqual('defaultDir');
log.reset();
dealoc($compile('<span class="default-dir"></span>')($rootScope));
expect(log).toEqual('');
log.reset();
});
});
});
describe('template', function() {
beforeEach(module(function() {
directive('replace', valueFn({
restrict: 'CAM',
replace: true,
template: '<div class="log" style="width: 10px" high-log>Replace!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('nomerge', valueFn({
restrict: 'CAM',
replace: true,
template: '<div class="log" id="myid" high-log>No Merge!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('append', valueFn({
restrict: 'CAM',
template: '<div class="log" style="width: 10px" high-log>Append!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithInterpolatedClass', valueFn({
replace: true,
template: '<div class="class_{{1+1}}">Replace with interpolated class!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithInterpolatedStyle', valueFn({
replace: true,
template: '<div style="width:{{1+1}}px">Replace with interpolated style!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithTr', valueFn({
replace: true,
template: '<tr><td>TR</td></tr>'
}));
directive('replaceWithTd', valueFn({
replace: true,
template: '<td>TD</td>'
}));
directive('replaceWithTh', valueFn({
replace: true,
template: '<th>TH</th>'
}));
directive('replaceWithThead', valueFn({
replace: true,
template: '<thead><tr><td>TD</td></tr></thead>'
}));
directive('replaceWithTbody', valueFn({
replace: true,
template: '<tbody><tr><td>TD</td></tr></tbody>'
}));
directive('replaceWithTfoot', valueFn({
replace: true,
template: '<tfoot><tr><td>TD</td></tr></tfoot>'
}));
directive('replaceWithOption', valueFn({
replace: true,
template: '<option>OPTION</option>'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
template: '<optgroup>OPTGROUP</optgroup>'
}));
}));
it('should replace element with template', inject(function($compile, $rootScope) {
element = $compile('<div><div replace>ignore</div><div>')($rootScope);
expect(element.text()).toEqual('Replace!');
expect(element.find('div').attr('compiled')).toEqual('COMPILED');
}));
it('should append element with template', inject(function($compile, $rootScope) {
element = $compile('<div><div append>ignore</div><div>')($rootScope);
expect(element.text()).toEqual('Append!');
expect(element.find('div').attr('compiled')).toEqual('COMPILED');
}));
it('should compile template when replacing', inject(function($compile, $rootScope, log) {
element = $compile('<div><div replace medium-log>ignore</div><div>')
($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Replace!');
expect(log).toEqual('LOG; HIGH; MEDIUM');
}));
it('should compile template when appending', inject(function($compile, $rootScope, log) {
element = $compile('<div><div append medium-log>ignore</div><div>')
($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Append!');
expect(log).toEqual('LOG; HIGH; MEDIUM');
}));
it('should merge attributes including style attr', inject(function($compile, $rootScope) {
element = $compile(
'<div><div replace class="medium-log" style="height: 20px" ></div><div>')
($rootScope);
var div = element.find('div');
expect(div.hasClass('medium-log')).toBe(true);
expect(div.hasClass('log')).toBe(true);
expect(div.css('width')).toBe('10px');
expect(div.css('height')).toBe('20px');
expect(div.attr('replace')).toEqual('');
expect(div.attr('high-log')).toEqual('');
}));
it('should not merge attributes if they are the same', inject(function($compile, $rootScope) {
element = $compile(
'<div><div nomerge class="medium-log" id="myid"></div><div>')
($rootScope);
var div = element.find('div');
expect(div.hasClass('medium-log')).toBe(true);
expect(div.hasClass('log')).toBe(true);
expect(div.attr('id')).toEqual('myid');
}));
it('should prevent multiple templates per element', inject(function($compile) {
try {
$compile('<div><span replace class="replace"></span></div>');
this.fail(new Error('should have thrown Multiple directives error'));
} catch(e) {
expect(e.message).toMatch(/Multiple directives .* asking for template/);
}
}));
it('should play nice with repeater when replacing', inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1,2]" replace></div>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Replace!Replace!');
}));
it('should play nice with repeater when appending', inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1,2]" append></div>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Append!Append!');
}));
it('should handle interpolated css class from replacing directive', inject(
function($compile, $rootScope) {
element = $compile('<div replace-with-interpolated-class></div>')($rootScope);
$rootScope.$digest();
expect(element).toHaveClass('class_2');
}));
if (!msie || msie > 11) {
// style interpolation not working on IE (including IE11).
it('should handle interpolated css style from replacing directive', inject(
function($compile, $rootScope) {
element = $compile('<div replace-with-interpolated-style></div>')($rootScope);
$rootScope.$digest();
expect(element.css('width')).toBe('2px');
}
));
}
it('should merge interpolated css class', inject(function($compile, $rootScope) {
element = $compile('<div class="one {{cls}} three" replace></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.cls = 'two';
});
expect(element).toHaveClass('one');
expect(element).toHaveClass('two'); // interpolated
expect(element).toHaveClass('three');
expect(element).toHaveClass('log'); // merged from replace directive template
}));
it('should merge interpolated css class with ngRepeat',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1]" class="one {{cls}} three" replace></div>' +
'</div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.cls = 'two';
});
var child = element.find('div').eq(0);
expect(child).toHaveClass('one');
expect(child).toHaveClass('two'); // interpolated
expect(child).toHaveClass('three');
expect(child).toHaveClass('log'); // merged from replace directive template
}));
it("should fail if replacing and template doesn't have a single root element", function() {
module(function() {
directive('noRootElem', function() {
return {
replace: true,
template: 'dada'
};
});
directive('multiRootElem', function() {
return {
replace: true,
template: '<div></div><div></div>'
};
});
directive('singleRootWithWhiteSpace', function() {
return {
replace: true,
template: ' <div></div> \n'
};
});
});
inject(function($compile) {
expect(function() {
$compile('<p no-root-elem></p>');
}).toThrowMinErr("$compile", "tplrt", "Template for directive 'noRootElem' must have exactly one root element. ");
expect(function() {
$compile('<p multi-root-elem></p>');
}).toThrowMinErr("$compile", "tplrt", "Template for directive 'multiRootElem' must have exactly one root element. ");
// ws is ok
expect(function() {
$compile('<p single-root-with-white-space></p>');
}).not.toThrow();
});
});
it('should support templates with root <tr> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tr></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tr/i);
}));
it('should support templates with root <td> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-td></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/td/i);
}));
it('should support templates with root <th> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-th></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/th/i);
}));
it('should support templates with root <thead> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-thead></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/thead/i);
}));
it('should support templates with root <tbody> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tbody></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tbody/i);
}));
it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tfoot></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));
it('should support templates with root <option> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/option/i);
}));
it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
if (window.SVGAElement) {
it('should support SVG templates using directive.type=svg', function() {
module(function() {
directive('svgAnchor', valueFn({
replace: true,
template: '<a xlink:href="{{linkurl}}">{{text}}</a>',
type: 'SVG',
scope: {
linkurl: '@svgAnchor',
text: '@?'
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
var child = element.children().eq(0);
$rootScope.$digest();
expect(nodeName_(child)).toMatch(/a/i);
expect(child[0].constructor).toBe(window.SVGAElement);
expect(child[0].href.baseVal).toBe("/foo/bar");
});
});
}
// MathML is only natively supported in Firefox at the time of this test's writing,
// and even there, the browser does not export MathML element constructors globally.
// So the test is slightly limited in what it does. But as browsers begin to
// implement MathML natively, this can be tightened up to be more meaningful.
it('should support MathML templates using directive.type=math', function() {
module(function() {
directive('pow', valueFn({
replace: true,
transclude: true,
template: '<msup><mn>{{pow}}</mn></msup>',
type: 'MATH',
scope: {
pow: '@pow',
},
link: function(scope, elm, attr, ctrl, transclude) {
transclude(function(node) {
elm.prepend(node[0]);
});
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/msup/i);
});
});
});
describe('template as function', function() {
beforeEach(module(function() {
directive('myDirective', valueFn({
replace: true,
template: function($element, $attrs) {
expect($element.text()).toBe('original content');
expect($attrs.myDirective).toBe('some value');
return '<div id="templateContent">template content</div>';
},
compile: function($element, $attrs) {
expect($element.text()).toBe('template content');
expect($attrs.id).toBe('templateContent');
}
}));
}));
it('should evaluate `template` when defined as fn and use returned string as template', inject(
function($compile, $rootScope) {
element = $compile('<div my-directive="some value">original content<div>')($rootScope);
expect(element.text()).toEqual('template content');
}));
});
describe('templateUrl', function() {
beforeEach(module(
function() {
directive('hello', valueFn({
restrict: 'CAM',
templateUrl: 'hello.html',
transclude: true
}));
directive('cau', valueFn({
restrict: 'CAM',
templateUrl: 'cau.html'
}));
directive('crossDomainTemplate', valueFn({
restrict: 'CAM',
templateUrl: 'http://example.com/should-not-load.html'
}));
directive('trustedTemplate', function($sce) {
return {
restrict: 'CAM',
templateUrl: function() {
return $sce.trustAsResourceUrl('http://example.com/trusted-template.html');
}
};
});
directive('cError', valueFn({
restrict: 'CAM',
templateUrl:'error.html',
compile: function() {
throw new Error('cError');
}
}));
directive('lError', valueFn({
restrict: 'CAM',
templateUrl: 'error.html',
compile: function() {
throw new Error('lError');
}
}));
directive('iHello', valueFn({
restrict: 'CAM',
replace: true,
templateUrl: 'hello.html'
}));
directive('iCau', valueFn({
restrict: 'CAM',
replace: true,
templateUrl:'cau.html'
}));
directive('iCError', valueFn({
restrict: 'CAM',
replace: true,
templateUrl:'error.html',
compile: function() {
throw new Error('cError');
}
}));
directive('iLError', valueFn({
restrict: 'CAM',
replace: true,
templateUrl: 'error.html',
compile: function() {
throw new Error('lError');
}
}));
directive('replace', valueFn({
replace: true,
template: '<span>Hello, {{name}}!</span>'
}));
directive('replaceWithTr', valueFn({
replace: true,
templateUrl: 'tr.html'
}));
directive('replaceWithTd', valueFn({
replace: true,
templateUrl: 'td.html'
}));
directive('replaceWithTh', valueFn({
replace: true,
templateUrl: 'th.html'
}));
directive('replaceWithThead', valueFn({
replace: true,
templateUrl: 'thead.html'
}));
directive('replaceWithTbody', valueFn({
replace: true,
templateUrl: 'tbody.html'
}));
directive('replaceWithTfoot', valueFn({
replace: true,
templateUrl: 'tfoot.html'
}));
directive('replaceWithOption', valueFn({
replace: true,
templateUrl: 'option.html'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
templateUrl: 'optgroup.html'
}));
}
));
it('should not load cross domain templates by default', inject(
function($compile, $rootScope, $templateCache, $sce) {
expect(function() {
$templateCache.put('http://example.com/should-not-load.html', 'Should not load even if in cache.');
$compile('<div class="crossDomainTemplate"></div>')($rootScope);
}).toThrowMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: http://example.com/should-not-load.html');
}
));
it('should load cross domain templates when trusted', inject(
function($compile, $httpBackend, $rootScope, $sce) {
$httpBackend.expect('GET', 'http://example.com/trusted-template.html').respond('<span>example.com/trusted_template_contents</span>');
element = $compile('<div class="trustedTemplate"></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div class="trustedTemplate"></div>');
$httpBackend.flush();
expect(sortedHtml(element)).
toEqual('<div class="trustedTemplate"><span>example.com/trusted_template_contents</span></div>');
}
));
it('should append template via $http and cache it in $templateCache', inject(
function($compile, $httpBackend, $templateCache, $rootScope, $browser) {
$httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!');
$templateCache.put('cau.html', '<span>Cau!</span>');
element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div><b class="hello"></b><b class="cau"></b></div>');
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>');
$httpBackend.flush();
expect(sortedHtml(element)).toEqual(
'<div>' +
'<b class="hello"><span>Hello!</span> World!</b>' +
'<b class="cau"><span>Cau!</span></b>' +
'</div>');
}
));
it('should inline template via $http and cache it in $templateCache', inject(
function($compile, $httpBackend, $templateCache, $rootScope) {
$httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>');
$templateCache.put('cau.html', '<span>Cau!</span>');
element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>');
$rootScope.$digest();
expect(sortedHtml(element)).toBeOneOf(
'<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>',
'<div><b class="i-hello"></b><span class="i-cau" i-cau="">Cau!</span></div>' //ie8
);
$httpBackend.flush();
expect(sortedHtml(element)).toBeOneOf(
'<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>',
'<div><span class="i-hello" i-hello="">Hello!</span><span class="i-cau" i-cau="">Cau!</span></div>' //ie8
);
}
));
it('should compile, link and flush the template append', inject(
function($compile, $templateCache, $rootScope, $browser) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class="hello"></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
}
));
it('should compile, link and flush the template inline', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class=i-hello></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).toBeOneOf(
'<div><span class="i-hello">Hello, Elvis!</span></div>',
'<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8
);
}
));
it('should compile, flush and link the template append', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div><b class="hello"></b></div>');
element = template($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
}
));
it('should compile, flush and link the template inline', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div><b class=i-hello></b></div>');
element = template($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).toBeOneOf(
'<div><span class="i-hello">Hello, Elvis!</span></div>',
'<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8
);
}
));
it('should compile template when replacing element in another template',
inject(function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<div replace></div>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class="hello"></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span replace="">Hello, Elvis!</span></b></div>');
}));
it('should compile template when replacing root element',
inject(function($compile, $templateCache, $rootScope) {
$rootScope.name = 'Elvis';
element = $compile('<div replace></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<span replace="">Hello, Elvis!</span>');
}));
it('should resolve widgets after cloning in append mode', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
$httpBackend.expect('GET', 'error.html').respond('<div></div>');
$templateCache.put('cau.html', '<span>{{name}}</span>');
$rootScope.greeting = 'Hello';
$rootScope.name = 'Elvis';
var template = $compile(
'<div>' +
'<b class="hello"></b>' +
'<b class="cau"></b>' +
'<b class=c-error></b>' +
'<b class=l-error></b>' +
'</div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Hello Elvis');
expect(e2.text()).toEqual('Hello Elvis');
expect($exceptionHandler.errors.length).toEqual(2);
expect($exceptionHandler.errors[0][0].message).toEqual('cError');
expect($exceptionHandler.errors[1][0].message).toEqual('lError');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in append mode without $templateCache', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div class="cau"></div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Elvis');
expect(e2.text()).toEqual('Elvis');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in inline mode', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
$httpBackend.expect('GET', 'error.html').respond('<div></div>');
$templateCache.put('cau.html', '<span>{{name}}</span>');
$rootScope.greeting = 'Hello';
$rootScope.name = 'Elvis';
var template = $compile(
'<div>' +
'<b class=i-hello></b>' +
'<b class=i-cau></b>' +
'<b class=i-c-error></b>' +
'<b class=i-l-error></b>' +
'</div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Hello Elvis');
expect(e2.text()).toEqual('Hello Elvis');
expect($exceptionHandler.errors.length).toEqual(2);
expect($exceptionHandler.errors[0][0].message).toEqual('cError');
expect($exceptionHandler.errors[1][0].message).toEqual('lError');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in inline mode without $templateCache', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div class="i-cau"></div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Elvis');
expect(e2.text()).toEqual('Elvis');
dealoc(e1);
dealoc(e2);
});
});
it('should be implicitly terminal and not compile placeholder content in append', inject(
function($compile, $templateCache, $rootScope, log) {
// we can't compile the contents because that would result in a memory leak
$templateCache.put('hello.html', 'Hello!');
element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope);
expect(log).toEqual('');
}
));
it('should be implicitly terminal and not compile placeholder content in inline', inject(
function($compile, $templateCache, $rootScope, log) {
// we can't compile the contents because that would result in a memory leak
$templateCache.put('hello.html', 'Hello!');
element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope);
expect(log).toEqual('');
}
));
it('should throw an error and clear element content if the template fails to load', inject(
function($compile, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!');
element = $compile('<div><b class="hello">content</b></div>')($rootScope);
expect(function() {
$httpBackend.flush();
}).toThrowMinErr('$compile', 'tpload', 'Failed to load template: hello.html');
expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>');
}
));
it('should prevent multiple templates per element', function() {
module(function() {
directive('sync', valueFn({
restrict: 'C',
template: '<span></span>'
}));
directive('async', valueFn({
restrict: 'C',
templateUrl: 'template.html'
}));
});
inject(function($compile, $httpBackend){
$httpBackend.whenGET('template.html').respond('<p>template.html</p>');
expect(function() {
$compile('<div><div class="sync async"></div></div>');
$httpBackend.flush();
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [async, sync] asking for template on: '+
'<div class="sync async">');
});
});
it('should copy classes from pre-template node into linked element', function() {
module(function() {
directive('test', valueFn({
templateUrl: 'test.html',
replace: true
}));
});
inject(function($compile, $templateCache, $rootScope) {
var child;
$templateCache.put('test.html', '<p class="template-class">Hello</p>');
element = $compile('<div test></div>')($rootScope, function(node) {
node.addClass('clonefn-class');
});
$rootScope.$digest();
expect(element).toHaveClass('template-class');
expect(element).toHaveClass('clonefn-class');
});
});
describe('delay compile / linking functions until after template is resolved', function(){
var template;
beforeEach(module(function() {
function logDirective (name, priority, options) {
directive(name, function(log) {
return (extend({
priority: priority,
compile: function() {
log(name + '-C');
return {
pre: function() { log(name + '-PreL'); },
post: function() { log(name + '-PostL'); }
};
}
}, options || {}));
});
}
logDirective('first', 10);
logDirective('second', 5, { templateUrl: 'second.html' });
logDirective('third', 3);
logDirective('last', 0);
logDirective('iFirst', 10, {replace: true});
logDirective('iSecond', 5, {replace: true, templateUrl: 'second.html' });
logDirective('iThird', 3, {replace: true});
logDirective('iLast', 0, {replace: true});
}));
it('should flush after link append', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
template = $compile('<div><span first second last></span></div>');
element = template($rootScope);
expect(log).toEqual('first-C');
log('FLUSH');
$httpBackend.flush();
$rootScope.$digest();
expect(log).toEqual(
'first-C; FLUSH; second-C; last-C; third-C; ' +
'first-PreL; second-PreL; last-PreL; third-PreL; ' +
'third-PostL; last-PostL; second-PostL; first-PostL');
var span = element.find('span');
expect(span.attr('first')).toEqual('');
expect(span.attr('second')).toEqual('');
expect(span.find('div').attr('third')).toEqual('');
expect(span.attr('last')).toEqual('');
expect(span.text()).toEqual('3');
}));
it('should flush after link inline', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
template = $compile('<div><span i-first i-second i-last></span></div>');
element = template($rootScope);
expect(log).toEqual('iFirst-C');
log('FLUSH');
$httpBackend.flush();
$rootScope.$digest();
expect(log).toEqual(
'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
var div = element.find('div');
expect(div.attr('i-first')).toEqual('');
expect(div.attr('i-second')).toEqual('');
expect(div.attr('i-third')).toEqual('');
expect(div.attr('i-last')).toEqual('');
expect(div.text()).toEqual('3');
}));
it('should flush before link append', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
template = $compile('<div><span first second last></span></div>');
expect(log).toEqual('first-C');
log('FLUSH');
$httpBackend.flush();
expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C');
element = template($rootScope);
$rootScope.$digest();
expect(log).toEqual(
'first-C; FLUSH; second-C; last-C; third-C; ' +
'first-PreL; second-PreL; last-PreL; third-PreL; ' +
'third-PostL; last-PostL; second-PostL; first-PostL');
var span = element.find('span');
expect(span.attr('first')).toEqual('');
expect(span.attr('second')).toEqual('');
expect(span.find('div').attr('third')).toEqual('');
expect(span.attr('last')).toEqual('');
expect(span.text()).toEqual('3');
}));
it('should flush before link inline', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
template = $compile('<div><span i-first i-second i-last></span></div>');
expect(log).toEqual('iFirst-C');
log('FLUSH');
$httpBackend.flush();
expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C');
element = template($rootScope);
$rootScope.$digest();
expect(log).toEqual(
'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
var div = element.find('div');
expect(div.attr('i-first')).toEqual('');
expect(div.attr('i-second')).toEqual('');
expect(div.attr('i-third')).toEqual('');
expect(div.attr('i-last')).toEqual('');
expect(div.text()).toEqual('3');
}));
});
it('should allow multiple elements in template', inject(function($compile, $httpBackend) {
$httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after');
element = jqLite('<div hello></div>');
$compile(element);
$httpBackend.flush();
expect(element.text()).toEqual('before mid after');
}));
it('should work when directive is on the root element', inject(
function($compile, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').
respond('<span>3==<span ng-transclude></span></span>');
element = jqLite('<b class="hello">{{1+2}}</b>');
$compile(element)($rootScope);
$httpBackend.flush();
expect(element.text()).toEqual('3==3');
}
));
it('should work when directive is in a repeater', inject(
function($compile, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').
respond('<span>i=<span ng-transclude></span>;</span>');
element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>');
$compile(element)($rootScope);
$httpBackend.flush();
expect(element.text()).toEqual('i=1;i=2;');
}
));
it("should fail if replacing and template doesn't have a single root element", function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
directive('template', function() {
return {
replace: true,
templateUrl: 'template.html'
};
});
});
inject(function($compile, $templateCache, $rootScope, $exceptionHandler) {
// no root element
$templateCache.put('template.html', 'dada');
$compile('<p template></p>');
$rootScope.$digest();
expect($exceptionHandler.errors.pop().message).
toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/);
// multi root
$templateCache.put('template.html', '<div></div><div></div>');
$compile('<p template></p>');
$rootScope.$digest();
expect($exceptionHandler.errors.pop().message).
toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/);
// ws is ok
$templateCache.put('template.html', ' <div></div> \n');
$compile('<p template></p>');
$rootScope.$apply();
expect($exceptionHandler.errors).toEqual([]);
});
});
it('should resume delayed compilation without duplicates when in a repeater', function() {
// this is a test for a regression
// scope creation, isolate watcher setup, controller instantiation, etc should happen
// only once even if we are dealing with delayed compilation of a node due to templateUrl
// and the template node is in a repeater
var controllerSpy = jasmine.createSpy('controller');
module(function($compileProvider) {
$compileProvider.directive('delayed', valueFn({
controller: controllerSpy,
templateUrl: 'delayed.html',
scope: {
title: '@'
}
}));
});
inject(function($templateCache, $compile, $rootScope) {
$rootScope.coolTitle = 'boom!';
$templateCache.put('delayed.html', '<div>{{title}}</div>');
element = $compile(
'<div><div ng-repeat="i in [1,2]"><div delayed title="{{coolTitle + i}}"></div>|</div></div>'
)($rootScope);
$rootScope.$apply();
expect(controllerSpy.callCount).toBe(2);
expect(element.text()).toBe('boom!1|boom!2|');
});
});
it('should support templateUrl with replace', function() {
// a regression https://github.com/angular/angular.js/issues/3792
module(function($compileProvider) {
$compileProvider.directive('simple', function() {
return {
templateUrl: '/some.html',
replace: true
};
});
});
inject(function($templateCache, $rootScope, $compile) {
$templateCache.put('/some.html',
'<div ng-switch="i">' +
'<div ng-switch-when="1">i = 1</div>' +
'<div ng-switch-default>I dont know what `i` is.</div>' +
'</div>');
element = $compile('<div simple></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.i = 1;
});
expect(element.html()).toContain('i = 1');
});
});
it('should support templates with root <tr> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tr.html', '<tr><td>TR</td></tr>');
expect(function() {
element = $compile('<div replace-with-tr></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tr/i);
}));
it('should support templates with root <td> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('td.html', '<td>TD</td>');
expect(function() {
element = $compile('<div replace-with-td></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/td/i);
}));
it('should support templates with root <th> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('th.html', '<th>TH</th>');
expect(function() {
element = $compile('<div replace-with-th></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/th/i);
}));
it('should support templates with root <thead> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('thead.html', '<thead><tr><td>TD</td></tr></thead>');
expect(function() {
element = $compile('<div replace-with-thead></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/thead/i);
}));
it('should support templates with root <tbody> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tbody.html', '<tbody><tr><td>TD</td></tr></tbody>');
expect(function() {
element = $compile('<div replace-with-tbody></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tbody/i);
}));
it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tfoot.html', '<tfoot><tr><td>TD</td></tr></tfoot>');
expect(function() {
element = $compile('<div replace-with-tfoot></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));
it('should support templates with root <option> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('option.html', '<option>OPTION</option>');
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/option/i);
}));
it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('optgroup.html', '<optgroup>OPTGROUP</optgroup>');
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
if (window.SVGAElement) {
it('should support SVG templates using directive.type=svg', function() {
module(function() {
directive('svgAnchor', valueFn({
replace: true,
templateUrl: 'template.html',
type: 'SVG',
scope: {
linkurl: '@svgAnchor',
text: '@?'
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('template.html', '<a xlink:href="{{linkurl}}">{{text}}</a>');
element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/a/i);
expect(child[0].constructor).toBe(window.SVGAElement);
expect(child[0].href.baseVal).toBe("/foo/bar");
});
});
}
// MathML is only natively supported in Firefox at the time of this test's writing,
// and even there, the browser does not export MathML element constructors globally.
// So the test is slightly limited in what it does. But as browsers begin to
// implement MathML natively, this can be tightened up to be more meaningful.
it('should support MathML templates using directive.type=math', function() {
module(function() {
directive('pow', valueFn({
replace: true,
transclude: true,
templateUrl: 'template.html',
type: 'MATH',
scope: {
pow: '@pow',
},
link: function(scope, elm, attr, ctrl, transclude) {
transclude(function(node) {
elm.prepend(node[0]);
});
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('template.html', '<msup><mn>{{pow}}</mn></msup>');
element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/msup/i);
});
});
});
describe('templateUrl as function', function() {
beforeEach(module(function() {
directive('myDirective', valueFn({
replace: true,
templateUrl: function($element, $attrs) {
expect($element.text()).toBe('original content');
expect($attrs.myDirective).toBe('some value');
return 'my-directive.html';
},
compile: function($element, $attrs) {
expect($element.text()).toBe('template content');
expect($attrs.id).toBe('templateContent');
}
}));
}));
it('should evaluate `templateUrl` when defined as fn and use returned value as url', inject(
function($compile, $rootScope, $templateCache) {
$templateCache.put('my-directive.html', '<div id="templateContent">template content</span>');
element = $compile('<div my-directive="some value">original content<div>')($rootScope);
expect(element.text()).toEqual('');
$rootScope.$digest();
expect(element.text()).toEqual('template content');
}));
});
describe('scope', function() {
var iscope;
beforeEach(module(function() {
forEach(['', 'a', 'b'], function(name) {
directive('scope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
compile: function() {
return {pre: function (scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
}};
}
};
});
directive('iscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
compile: function() {
return function (scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
};
}
};
});
directive('tscope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
templateUrl: 'tscope.html',
compile: function() {
return function (scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('stscope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
template: '<span></span>',
compile: function() {
return function (scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('trscope' + uppercase(name), function(log) {
return {
scope: true,
replace: true,
restrict: 'CA',
templateUrl: 'trscope.html',
compile: function() {
return function (scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('tiscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
templateUrl: 'tiscope.html',
compile: function() {
return function (scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScope')).toBe(scope);
};
}
};
});
directive('stiscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
template: '<span></span>',
compile: function() {
return function (scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScope')).toBe(scope);
};
}
};
});
});
directive('log', function(log) {
return {
restrict: 'CA',
link: {pre: function(scope) {
log('log-' + scope.$id + '-' + (scope.$parent && scope.$parent.$id || 'no-parent'));
}}
};
});
}));
it('should allow creation of new scopes', inject(function($rootScope, $compile, log) {
element = $compile('<div><span scope><a log></a></span></div>')($rootScope);
expect(log).toEqual('2; log-2-1; LOG');
expect(element.find('span').hasClass('ng-scope')).toBe(true);
}));
it('should allow creation of new isolated scopes for directives', inject(
function($rootScope, $compile, log) {
element = $compile('<div><span iscope><a log></a></span></div>')($rootScope);
expect(log).toEqual('log-1-no-parent; LOG; 2');
$rootScope.name = 'abc';
expect(iscope.$parent).toBe($rootScope);
expect(iscope.name).toBeUndefined();
}));
it('should allow creation of new scopes for directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'tscope.html').respond('<a log>{{name}}; scopeId: {{$id}}</a>');
element = $compile('<div><span tscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 2');
expect(element.find('span').scope().$id).toBe(2);
}));
it('should allow creation of new scopes for replace directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'trscope.html').
respond('<p><a log>{{name}}; scopeId: {{$id}}</a></p>');
element = $compile('<div><span trscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 2');
expect(element.find('a').scope().$id).toBe(2);
}));
it('should allow creation of new scopes for replace directives with templates in a repeater',
inject(function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'trscope.html').
respond('<p><a log>{{name}}; scopeId: {{$id}} |</a></p>');
element = $compile('<div><span ng-repeat="i in [1,2,3]" trscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-3-2; LOG; 3; log-5-4; LOG; 5; log-7-6; LOG; 7');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 3 |Jozo; scopeId: 5 |Jozo; scopeId: 7 |');
expect(element.find('p').scope().$id).toBe(3);
expect(element.find('a').scope().$id).toBe(3);
}));
it('should allow creation of new isolated scopes for directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>');
element = $compile('<div><span tiscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'abc';
expect(iscope.$parent).toBe($rootScope);
expect(iscope.name).toBeUndefined();
}));
it('should correctly create the scope hierachy', inject(
function($rootScope, $compile, log) {
element = $compile(
'<div>' + //1
'<b class=scope>' + //2
'<b class=scope><b class=log></b></b>' + //3
'<b class=log></b>' +
'</b>' +
'<b class=scope>' + //4
'<b class=log></b>' +
'</b>' +
'</div>'
)($rootScope);
expect(log).toEqual('2; 3; log-3-2; LOG; log-2-1; LOG; 4; log-4-1; LOG');
})
);
it('should allow more than one new scope directives per element, but directives should share' +
'the scope', inject(
function($rootScope, $compile, log) {
element = $compile('<div class="scope-a; scope-b"></div>')($rootScope);
expect(log).toEqual('2; 2');
})
);
it('should not allow more then one isolate scope creation per element', inject(
function($rootScope, $compile) {
expect(function(){
$compile('<div class="iscope-a; scope-b"></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [iscopeA, scopeB] asking for new/isolated scope on: ' +
'<div class="iscope-a; scope-b">');
})
);
it('should not allow more than one isolate scope creation per element regardless of directive priority', function() {
module(function($compileProvider) {
$compileProvider.directive('highPriorityScope', function() {
return {
restrict: 'C',
priority: 1,
scope: true,
link: function() {}
};
});
});
inject(function($compile) {
expect(function(){
$compile('<div class="iscope-a; high-priority-scope"></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [highPriorityScope, iscopeA] asking for new/isolated scope on: ' +
'<div class="iscope-a; high-priority-scope">');
});
});
it('should create new scope even at the root of the template', inject(
function($rootScope, $compile, log) {
element = $compile('<div scope-a></div>')($rootScope);
expect(log).toEqual('2');
})
);
it('should create isolate scope even at the root of the template', inject(
function($rootScope, $compile, log) {
element = $compile('<div iscope></div>')($rootScope);
expect(log).toEqual('2');
})
);
describe('scope()/isolate() scope getters', function() {
describe('with no directives', function() {
it('should return the scope of the parent node', inject(
function($rootScope, $compile) {
element = $compile('<div></div>')($rootScope);
expect(element.scope()).toBe($rootScope);
})
);
});
describe('with new scope directives', function() {
it('should return the new scope at the directive element', inject(
function($rootScope, $compile) {
element = $compile('<div scope></div>')($rootScope);
expect(element.scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the original template', inject(
function($rootScope, $compile) {
element = $compile('<div scope><a></a></div>')($rootScope);
expect(element.find('a').scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the directive template', inject(
function($rootScope, $compile, $httpBackend) {
$httpBackend.expect('GET', 'tscope.html').respond('<a></a>');
element = $compile('<div tscope></div>')($rootScope);
$httpBackend.flush();
expect(element.find('a').scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the directive sync template', inject(
function($rootScope, $compile) {
element = $compile('<div stscope></div>')($rootScope);
expect(element.find('span').scope().$parent).toBe($rootScope);
})
);
});
describe('with isolate scope directives', function() {
it('should return the root scope for directives at the root element', inject(
function($rootScope, $compile) {
element = $compile('<div iscope></div>')($rootScope);
expect(element.scope()).toBe($rootScope);
})
);
it('should return the non-isolate scope at the directive element', inject(
function($rootScope, $compile) {
var directiveElement;
element = $compile('<div><div iscope></div></div>')($rootScope);
directiveElement = element.children();
expect(directiveElement.scope()).toBe($rootScope);
expect(directiveElement.isolateScope().$parent).toBe($rootScope);
})
);
it('should return the isolate scope for children in the original template', inject(
function($rootScope, $compile) {
element = $compile('<div iscope><a></a></div>')($rootScope);
expect(element.find('a').scope()).toBe($rootScope); //xx
})
);
it('should return the isolate scope for children in directive template', inject(
function($rootScope, $compile, $httpBackend) {
$httpBackend.expect('GET', 'tiscope.html').respond('<a></a>');
element = $compile('<div tiscope></div>')($rootScope);
expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature
$httpBackend.flush();
expect(element.find('a').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
})
);
it('should return the isolate scope for children in directive sync template', inject(
function($rootScope, $compile) {
element = $compile('<div stiscope></div>')($rootScope);
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
})
);
});
describe('with isolate scope directives and directives that manually create a new scope', function() {
it('should return the new scope at the directive element', inject(
function($rootScope, $compile) {
var directiveElement;
element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope);
$rootScope.$apply();
directiveElement = element.find('a');
expect(directiveElement.scope().$parent).toBe($rootScope);
expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope());
})
);
it('should return the isolate scope for child elements', inject(
function($rootScope, $compile, $httpBackend) {
var directiveElement, child;
$httpBackend.expect('GET', 'tiscope.html').respond('<span></span>');
element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope);
$rootScope.$apply();
$httpBackend.flush();
directiveElement = element.find('a');
child = directiveElement.find('span');
expect(child.scope()).toBe(directiveElement.isolateScope());
})
);
it('should return the isolate scope for child elements in directive sync template', inject(
function($rootScope, $compile) {
var directiveElement, child;
element = $compile('<div><a ng-if="true" stiscope></a></div>')($rootScope);
$rootScope.$apply();
directiveElement = element.find('a');
child = directiveElement.find('span');
expect(child.scope()).toBe(directiveElement.isolateScope());
})
);
});
});
});
});
});
describe('interpolation', function() {
var observeSpy, directiveAttrs, deregisterObserver;
beforeEach(module(function() {
directive('observer', function() {
return function(scope, elm, attr) {
directiveAttrs = attr;
observeSpy = jasmine.createSpy('$observe attr');
deregisterObserver = attr.$observe('someAttr', observeSpy);
};
});
directive('replaceSomeAttr', valueFn({
compile: function(element, attr) {
attr.$set('someAttr', 'bar-{{1+1}}');
expect(element).toBe(attr.$$element);
}
}));
}));
it('should compile and link both attribute and text bindings', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should one-time bind if the expression starts with two colons', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{::name}}">text: {{::name}}</div>')($rootScope);
expect($rootScope.$$watchers.length).toBe(2);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
expect($rootScope.$$watchers.length).toBe(0);
$rootScope.name = 'not-angular';
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should one-time bind if the expression starts with a space and two colons', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{::name}}">text: {{ ::name }}</div>')($rootScope);
expect($rootScope.$$watchers.length).toBe(2);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
expect($rootScope.$$watchers.length).toBe(0);
$rootScope.name = 'not-angular';
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should process attribute interpolation in pre-linking phase at priority 100', function() {
module(function() {
directive('attrLog', function(log) {
return {
compile: function($element, $attrs) {
log('compile=' + $attrs.myName);
return {
pre: function($scope, $element, $attrs) {
log('preLinkP0=' + $attrs.myName);
},
post: function($scope, $element, $attrs) {
log('postLink=' + $attrs.myName);
}
};
}
};
});
});
module(function() {
directive('attrLogHighPriority', function(log) {
return {
priority: 101,
compile: function() {
return {
pre: function($scope, $element, $attrs) {
log('preLinkP101=' + $attrs.myName);
}
};
}
};
});
});
inject(function($rootScope, $compile, log) {
element = $compile('<div attr-log-high-priority attr-log my-name="{{name}}"></div>')($rootScope);
$rootScope.name = 'angular';
$rootScope.$apply();
log('digest=' + element.attr('my-name'));
expect(log).toEqual('compile={{name}}; preLinkP101={{name}}; preLinkP0=; postLink=; digest=angular');
});
});
describe('SCE values', function() {
it('should resolve compile and link both attribute and text bindings', inject(
function($rootScope, $compile, $sce) {
$rootScope.name = $sce.trustAsHtml('angular');
element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
}));
});
it('should decorate the binding with ng-binding and interpolation function', inject(
function($compile, $rootScope) {
element = $compile('<div>{{1+2}}</div>')($rootScope);
expect(element.hasClass('ng-binding')).toBe(true);
expect(element.data('$binding')[0].exp).toEqual('{{1+2}}');
}));
it('should observe interpolated attrs', inject(function($rootScope, $compile) {
$compile('<div some-attr="{{value}}" observer></div>')($rootScope);
// should be async
expect(observeSpy).not.toHaveBeenCalled();
$rootScope.$apply(function() {
$rootScope.value = 'bound-value';
});
expect(observeSpy).toHaveBeenCalledOnceWith('bound-value');
}));
it('should return a deregistration function while observing an attribute', inject(function($rootScope, $compile) {
$compile('<div some-attr="{{value}}" observer></div>')($rootScope);
$rootScope.$apply('value = "first-value"');
expect(observeSpy).toHaveBeenCalledWith('first-value');
deregisterObserver();
$rootScope.$apply('value = "new-value"');
expect(observeSpy).not.toHaveBeenCalledWith('new-value');
}));
it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) {
// we need the interpolated attributes to be initialized so that linking fn in a component
// can access the value during link
$rootScope.whatever = 'test value';
$compile('<div some-attr="{{whatever}}" observer></div>')($rootScope);
expect(directiveAttrs.someAttr).toBe($rootScope.whatever);
}));
it('should allow directive to replace interpolated attributes before attr interpolation compilation', inject(
function($compile, $rootScope) {
element = $compile('<div some-attr="foo-{{1+1}}" replace-some-attr></div>')($rootScope);
$rootScope.$digest();
expect(element.attr('some-attr')).toEqual('bar-2');
}));
it('should call observer of non-interpolated attr through $evalAsync',
inject(function($rootScope, $compile) {
$compile('<div some-attr="nonBound" observer></div>')($rootScope);
expect(directiveAttrs.someAttr).toBe('nonBound');
expect(observeSpy).not.toHaveBeenCalled();
$rootScope.$digest();
expect(observeSpy).toHaveBeenCalled();
})
);
it('should delegate exceptions to $exceptionHandler', function() {
observeSpy = jasmine.createSpy('$observe attr').andThrow('ERROR');
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
directive('error', function() {
return function(scope, elm, attr) {
attr.$observe('someAttr', observeSpy);
attr.$observe('someAttr', observeSpy);
};
});
});
inject(function($compile, $rootScope, $exceptionHandler) {
$compile('<div some-attr="{{value}}" error></div>')($rootScope);
$rootScope.$digest();
expect(observeSpy).toHaveBeenCalled();
expect(observeSpy.callCount).toBe(2);
expect($exceptionHandler.errors).toEqual(['ERROR', 'ERROR']);
});
});
it('should translate {{}} in terminal nodes', inject(function($rootScope, $compile) {
element = $compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element).replace(' selected="true"', '')).
toEqual('<select ng:model="x">' +
'<option value="">Greet !</option>' +
'</select>');
$rootScope.name = 'Misko';
$rootScope.$digest();
expect(sortedHtml(element).replace(' selected="true"', '')).
toEqual('<select ng:model="x">' +
'<option value="">Greet Misko!</option>' +
'</select>');
}));
it('should support custom start/end interpolation symbols in template and directive template',
function() {
module(function($interpolateProvider, $compileProvider) {
$interpolateProvider.startSymbol('##').endSymbol(']]');
$compileProvider.directive('myDirective', function() {
return {
template: '<span>{{hello}}|{{hello|uppercase}}</span>'
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
});
it('should support custom start/end interpolation symbols in async directive template',
function() {
module(function($interpolateProvider, $compileProvider) {
$interpolateProvider.startSymbol('##').endSymbol(']]');
$compileProvider.directive('myDirective', function() {
return {
templateUrl: 'myDirective.html'
};
});
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('myDirective.html', '<span>{{hello}}|{{hello|uppercase}}</span>');
element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
});
it('should make attributes observable for terminal directives', function() {
module(function() {
directive('myAttr', function(log) {
return {
terminal: true,
link: function(scope, element, attrs) {
attrs.$observe('myAttr', function(val) {
log(val);
});
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div my-attr="{{myVal}}"></div>')($rootScope);
expect(log).toEqual([]);
$rootScope.myVal = 'carrot';
$rootScope.$digest();
expect(log).toEqual(['carrot']);
});
});
});
describe('link phase', function() {
beforeEach(module(function() {
forEach(['a', 'b', 'c'], function(name) {
directive(name, function(log) {
return {
restrict: 'ECA',
compile: function() {
log('t' + uppercase(name));
return {
pre: function() {
log('pre' + uppercase(name));
},
post: function linkFn() {
log('post' + uppercase(name));
}
};
}
};
});
});
}));
it('should not store linkingFns for noop branches', inject(function ($rootScope, $compile) {
element = jqLite('<div name="{{a}}"><span>ignore</span></div>');
var linkingFn = $compile(element);
// Now prune the branches with no directives
element.find('span').remove();
expect(element.find('span').length).toBe(0);
// and we should still be able to compile without errors
linkingFn($rootScope);
}));
it('should compile from top to bottom but link from bottom up', inject(
function($compile, $rootScope, log) {
element = $compile('<a b><c></c></a>')($rootScope);
expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postB; postA');
}
));
it('should support link function on directive object', function() {
module(function() {
directive('abc', valueFn({
link: function(scope, element, attrs) {
element.text(attrs.abc);
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div abc="WORKS">FAIL</div>')($rootScope);
expect(element.text()).toEqual('WORKS');
});
});
it('should support $observe inside link function on directive object', function() {
module(function() {
directive('testLink', valueFn({
templateUrl: 'test-link.html',
link: function(scope, element, attrs) {
attrs.$observe( 'testLink', function ( val ) {
scope.testAttr = val;
});
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test-link.html', '{{testAttr}}' );
element = $compile('<div test-link="{{1+2}}"></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('3');
});
});
});
describe('attrs', function() {
it('should allow setting of attributes', function() {
module(function() {
directive({
setter: valueFn(function(scope, element, attr) {
attr.$set('name', 'abc');
attr.$set('disabled', true);
expect(attr.name).toBe('abc');
expect(attr.disabled).toBe(true);
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<div setter></div>')($rootScope);
expect(element.attr('name')).toEqual('abc');
expect(element.attr('disabled')).toEqual('disabled');
});
});
it('should read boolean attributes as boolean only on control elements', function() {
var value;
module(function() {
directive({
input: valueFn({
restrict: 'ECA',
link:function(scope, element, attr) {
value = attr.required;
}
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<input required></input>')($rootScope);
expect(value).toEqual(true);
});
});
it('should read boolean attributes as text on non-controll elements', function() {
var value;
module(function() {
directive({
div: valueFn({
restrict: 'ECA',
link:function(scope, element, attr) {
value = attr.required;
}
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<div required="some text"></div>')($rootScope);
expect(value).toEqual('some text');
});
});
it('should create new instance of attr for each template stamping', function() {
module(function($provide) {
var state = { first: [], second: [] };
$provide.value('state', state);
directive({
first: valueFn({
priority: 1,
compile: function(templateElement, templateAttr) {
return function(scope, element, attr) {
state.first.push({
template: {element: templateElement, attr:templateAttr},
link: {element: element, attr: attr}
});
};
}
}),
second: valueFn({
priority: 2,
compile: function(templateElement, templateAttr) {
return function(scope, element, attr) {
state.second.push({
template: {element: templateElement, attr:templateAttr},
link: {element: element, attr: attr}
});
};
}
})
});
});
inject(function($rootScope, $compile, state) {
var template = $compile('<div first second>');
dealoc(template($rootScope.$new(), noop));
dealoc(template($rootScope.$new(), noop));
// instance between directives should be shared
expect(state.first[0].template.element).toBe(state.second[0].template.element);
expect(state.first[0].template.attr).toBe(state.second[0].template.attr);
// the template and the link can not be the same instance
expect(state.first[0].template.element).not.toBe(state.first[0].link.element);
expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr);
// each new template needs to be new instance
expect(state.first[0].link.element).not.toBe(state.first[1].link.element);
expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr);
expect(state.second[0].link.element).not.toBe(state.second[1].link.element);
expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr);
});
});
it('should properly $observe inside ng-repeat', function() {
var spies = [];
module(function() {
directive('observer', function() {
return function(scope, elm, attr) {
spies.push(jasmine.createSpy('observer ' + spies.length));
attr.$observe('some', spies[spies.length - 1]);
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div><div ng-repeat="i in items">'+
'<span some="id_{{i.id}}" observer></span>'+
'</div></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.items = [{id: 1}, {id: 2}];
});
expect(spies[0]).toHaveBeenCalledOnceWith('id_1');
expect(spies[1]).toHaveBeenCalledOnceWith('id_2');
spies[0].reset();
spies[1].reset();
$rootScope.$apply(function() {
$rootScope.items[0].id = 5;
});
expect(spies[0]).toHaveBeenCalledOnceWith('id_5');
});
});
describe('$set', function() {
var attr;
beforeEach(function(){
module(function() {
directive('input', valueFn({
restrict: 'ECA',
link: function(scope, element, attr) {
scope.attr = attr;
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<input></input>')($rootScope);
attr = $rootScope.attr;
expect(attr).toBeDefined();
});
});
it('should set attributes', function() {
attr.$set('ngMyAttr', 'value');
expect(element.attr('ng-my-attr')).toEqual('value');
expect(attr.ngMyAttr).toEqual('value');
});
it('should allow overriding of attribute name and remember the name', function() {
attr.$set('ngOther', '123', true, 'other');
expect(element.attr('other')).toEqual('123');
expect(attr.ngOther).toEqual('123');
attr.$set('ngOther', '246');
expect(element.attr('other')).toEqual('246');
expect(attr.ngOther).toEqual('246');
});
it('should remove attribute', function() {
attr.$set('ngMyAttr', 'value');
expect(element.attr('ng-my-attr')).toEqual('value');
attr.$set('ngMyAttr', undefined);
expect(element.attr('ng-my-attr')).toBe(undefined);
attr.$set('ngMyAttr', 'value');
attr.$set('ngMyAttr', null);
expect(element.attr('ng-my-attr')).toBe(undefined);
});
it('should not set DOM element attr if writeAttr false', function() {
attr.$set('test', 'value', false);
expect(element.attr('test')).toBeUndefined();
expect(attr.test).toBe('value');
});
});
});
describe('isolated locals', function() {
var componentScope, regularScope;
beforeEach(module(function() {
directive('myComponent', function() {
return {
scope: {
attr: '@',
attrAlias: '@attr',
ref: '=',
refAlias: '= ref',
reference: '=',
optref: '=?',
optrefAlias: '=? optref',
optreference: '=?',
expr: '&',
exprAlias: '&expr'
},
link: function(scope) {
componentScope = scope;
}
};
});
directive('badDeclaration', function() {
return {
scope: { attr: 'xxx' }
};
});
directive('storeScope', function() {
return {
link: function(scope) {
regularScope = scope;
}
};
});
}));
it('should give other directives the parent scope', inject(function($rootScope) {
compile('<div><input type="text" my-component store-scope ng-model="value"></div>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.find('input').val()).toBe('from-parent');
expect(componentScope).not.toBe(regularScope);
expect(componentScope.$parent).toBe(regularScope);
}));
it('should not give the isolate scope to other directive template', function() {
module(function() {
directive('otherTplDir', function() {
return {
template: 'value: {{value}}'
};
});
});
inject(function($rootScope) {
compile('<div my-component other-tpl-dir>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
it('should not give the isolate scope to other directive template (with templateUrl)', function() {
module(function() {
directive('otherTplDir', function() {
return {
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', 'value: {{value}}');
compile('<div my-component other-tpl-dir>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
it('should not give the isolate scope to regular child elements', function() {
inject(function($rootScope) {
compile('<div my-component>value: {{value}}</div>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
describe('bind-once', function () {
function countWatches(scope) {
var result = 0;
while (scope !== null) {
result += (scope.$$watchers && scope.$$watchers.length) || 0;
result += countWatches(scope.$$childHead);
scope = scope.$$nextSibling;
}
return result;
}
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '=', param2: '='},
template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
};
});
});
inject(function($rootScope) {
compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> '='
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(7);
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:foo;4:');
expect(countWatches($rootScope)).toEqual(5);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '@', param2: '@'},
template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
};
});
});
inject(function($rootScope) {
compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> {{ }}
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(5); // (- 2) -> bind-once in template
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:;4:');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '=', param2: '='},
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(7); // 5 -> template watch group, 2 -> '='
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:foo;4:');
expect(countWatches($rootScope)).toEqual(5);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '@', param2: '@'},
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(5); // (5 - 2) -> template watch group, 2 -> {{ }}
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:;4:');
});
});
});
describe('attribute', function() {
it('should copy simple attribute', inject(function() {
compile('<div><span my-component attr="some text">');
expect(componentScope.attr).toEqual('some text');
expect(componentScope.attrAlias).toEqual('some text');
expect(componentScope.attrAlias).toEqual(componentScope.attr);
}));
it('should set up the interpolation before it reaches the link function', inject(function() {
$rootScope.name = 'misko';
compile('<div><span my-component attr="hello {{name}}">');
expect(componentScope.attr).toEqual('hello misko');
expect(componentScope.attrAlias).toEqual('hello misko');
}));
it('should update when interpolated attribute updates', inject(function() {
compile('<div><span my-component attr="hello {{name}}">');
$rootScope.name = 'igor';
$rootScope.$apply();
expect(componentScope.attr).toEqual('hello igor');
expect(componentScope.attrAlias).toEqual('hello igor');
}));
});
describe('object reference', function() {
it('should update local when origin changes', inject(function() {
compile('<div><span my-component ref="name">');
expect(componentScope.ref).toBe(undefined);
expect(componentScope.refAlias).toBe(componentScope.ref);
$rootScope.name = 'misko';
$rootScope.$apply();
expect($rootScope.name).toBe('misko');
expect(componentScope.ref).toBe('misko');
expect(componentScope.refAlias).toBe('misko');
$rootScope.name = {};
$rootScope.$apply();
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
}));
it('should update local when both change', inject(function() {
compile('<div><span my-component ref="name">');
$rootScope.name = {mark:123};
componentScope.ref = 'misko';
$rootScope.$apply();
expect($rootScope.name).toEqual({mark:123});
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
$rootScope.name = 'igor';
componentScope.ref = {};
$rootScope.$apply();
expect($rootScope.name).toEqual('igor');
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
}));
it('should not break if local and origin both change to the same value', inject(function() {
$rootScope.name = 'aaa';
compile('<div><span my-component ref="name">');
//change both sides to the same item withing the same digest cycle
componentScope.ref = 'same';
$rootScope.name = 'same';
$rootScope.$apply();
//change origin back to its previous value
$rootScope.name = 'aaa';
$rootScope.$apply();
expect($rootScope.name).toBe('aaa');
expect(componentScope.ref).toBe('aaa');
}));
it('should complain on non assignable changes', inject(function() {
compile('<div><span my-component ref="\'hello \' + name">');
$rootScope.name = 'world';
$rootScope.$apply();
expect(componentScope.ref).toBe('hello world');
componentScope.ref = 'ignore me';
expect($rootScope.$apply).
toThrowMinErr("$compile", "nonassign", "Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!");
expect(componentScope.ref).toBe('hello world');
// reset since the exception was rethrown which prevented phase clearing
$rootScope.$$phase = null;
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.ref).toBe('hello misko');
}));
// regression
it('should stabilize model', inject(function() {
compile('<div><span my-component reference="name">');
var lastRefValueInParent;
$rootScope.$watch('name', function(ref) {
lastRefValueInParent = ref;
});
$rootScope.name = 'aaa';
$rootScope.$apply();
componentScope.reference = 'new';
$rootScope.$apply();
expect(lastRefValueInParent).toBe('new');
}));
describe('literal objects', function() {
it('should copy parent changes', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
expect(componentScope.reference).toEqual({name: 'a'});
$rootScope.name = 'b';
$rootScope.$apply();
expect(componentScope.reference).toEqual({name: 'b'});
}));
it('should not change the component when parent does not change', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
var lastComponentValue = componentScope.reference;
$rootScope.$apply();
expect(componentScope.reference).toBe(lastComponentValue);
}));
it('should complain when the component changes', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
componentScope.reference = {name: 'b'};
expect(function() {
$rootScope.$apply();
}).toThrowMinErr("$compile", "nonassign", "Expression '{name: name}' used with directive 'myComponent' is non-assignable!");
}));
it('should work for primitive literals', inject(function() {
test('1', 1);
test('null', null);
test('undefined', undefined);
test("'someString'", 'someString');
function test(literalString, literalValue) {
compile('<div><span my-component reference="'+literalString+'">');
$rootScope.$apply();
expect(componentScope.reference).toBe(literalValue);
dealoc(element);
}
}));
});
});
describe('optional object reference', function() {
it('should update local when origin changes', inject(function() {
compile('<div><span my-component optref="name">');
expect(componentScope.optRef).toBe(undefined);
expect(componentScope.optRefAlias).toBe(componentScope.optRef);
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.optref).toBe($rootScope.name);
expect(componentScope.optrefAlias).toBe($rootScope.name);
$rootScope.name = {};
$rootScope.$apply();
expect(componentScope.optref).toBe($rootScope.name);
expect(componentScope.optrefAlias).toBe($rootScope.name);
}));
it('should not throw exception when reference does not exist', inject(function() {
compile('<div><span my-component>');
expect(componentScope.optref).toBe(undefined);
expect(componentScope.optrefAlias).toBe(undefined);
expect(componentScope.optreference).toBe(undefined);
}));
});
describe('executable expression', function() {
it('should allow expression execution with locals', inject(function() {
compile('<div><span my-component expr="count = count + offset">');
$rootScope.count = 2;
expect(typeof componentScope.expr).toBe('function');
expect(typeof componentScope.exprAlias).toBe('function');
expect(componentScope.expr({offset: 1})).toEqual(3);
expect($rootScope.count).toEqual(3);
expect(componentScope.exprAlias({offset: 10})).toEqual(13);
expect($rootScope.count).toEqual(13);
}));
});
it('should throw on unknown definition', inject(function() {
expect(function() {
compile('<div><span bad-declaration>');
}).toThrowMinErr("$compile", "iscp", "Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}");
}));
it('should expose a $$isolateBindings property onto the scope', inject(function() {
compile('<div><span my-component>');
expect(typeof componentScope.$$isolateBindings).toBe('object');
expect(componentScope.$$isolateBindings.attr).toBe('@attr');
expect(componentScope.$$isolateBindings.attrAlias).toBe('@attr');
expect(componentScope.$$isolateBindings.ref).toBe('=ref');
expect(componentScope.$$isolateBindings.refAlias).toBe('=ref');
expect(componentScope.$$isolateBindings.reference).toBe('=reference');
expect(componentScope.$$isolateBindings.expr).toBe('&expr');
expect(componentScope.$$isolateBindings.exprAlias).toBe('&expr');
}));
});
describe('controller', function() {
it('should get required controller', function() {
module(function() {
directive('main', function(log) {
return {
priority: 2,
controller: function() {
this.name = 'main';
},
link: function(scope, element, attrs, controller) {
log(controller.name);
}
};
});
directive('dep', function(log) {
return {
priority: 1,
require: 'main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
directive('other', function(log) {
return {
link: function(scope, element, attrs, controller) {
log(!!controller); // should be false
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main dep other></div>')($rootScope);
expect(log).toEqual('false; dep:main; main');
});
});
it('should get required controller via linkingFn (template)', function() {
module(function() {
directive('dirA', function() {
return {
controller: function() {
this.name = 'dirA';
}
};
});
directive('dirB', function(log) {
return {
require: 'dirA',
template: '<p>dirB</p>',
link: function(scope, element, attrs, dirAController) {
log('dirAController.name: ' + dirAController.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div dir-a dir-b></div>')($rootScope);
expect(log).toEqual('dirAController.name: dirA');
});
});
it('should get required controller via linkingFn (templateUrl)', function() {
module(function() {
directive('dirA', function() {
return {
controller: function() {
this.name = 'dirA';
}
};
});
directive('dirB', function(log) {
return {
require: 'dirA',
templateUrl: 'dirB.html',
link: function(scope, element, attrs, dirAController) {
log('dirAController.name: ' + dirAController.name);
}
};
});
});
inject(function(log, $compile, $rootScope, $templateCache) {
$templateCache.put('dirB.html', '<p>dirB</p>');
element = $compile('<div dir-a dir-b></div>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('dirAController.name: dirA');
});
});
it('should require controller of an isolate directive from a non-isolate directive on the ' +
'same element', function() {
var IsolateController = function() {};
var isolateDirControllerInNonIsolateDirective;
module(function() {
directive('isolate', function() {
return {
scope: {},
controller: IsolateController
};
});
directive('nonIsolate', function() {
return {
require: 'isolate',
link: function(_, __, ___, isolateDirController) {
isolateDirControllerInNonIsolateDirective = isolateDirController;
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(isolateDirControllerInNonIsolateDirective).toBeDefined();
expect(isolateDirControllerInNonIsolateDirective instanceof IsolateController).toBe(true);
});
});
it('should give the isolate scope to the controller of another replaced directives in the template', function() {
module(function() {
directive('testDirective', function() {
return {
replace: true,
restrict: 'E',
scope: {},
template: '<input type="checkbox" ng-model="model">'
};
});
});
inject(function($rootScope) {
compile('<div><test-directive></test-directive></div>');
element = element.children().eq(0);
expect(element[0].checked).toBe(false);
element.isolateScope().model = true;
$rootScope.$digest();
expect(element[0].checked).toBe(true);
});
});
it('should share isolate scope with replaced directives (template)', function() {
var normalScope;
var isolateScope;
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
template: '<span ng-init="name=\'WORKS\'">{{name}}</span>',
link: function(s) {
isolateScope = s;
}
};
});
directive('nonIsolate', function() {
return {
link: function(s) {
normalScope = s;
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(normalScope).toBe($rootScope);
expect(normalScope.name).toEqual(undefined);
expect(isolateScope.name).toEqual('WORKS');
$rootScope.$digest();
expect(element.text()).toEqual('WORKS');
});
});
it('should share isolate scope with replaced directives (templateUrl)', function() {
var normalScope;
var isolateScope;
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
templateUrl: 'main.html',
link: function(s) {
isolateScope = s;
}
};
});
directive('nonIsolate', function() {
return {
link: function(s) {
normalScope = s;
}
};
});
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('main.html', '<span ng-init="name=\'WORKS\'">{{name}}</span>');
element = $compile('<div isolate non-isolate></div>')($rootScope);
$rootScope.$apply();
expect(normalScope).toBe($rootScope);
expect(normalScope.name).toEqual(undefined);
expect(isolateScope.name).toEqual('WORKS');
expect(element.text()).toEqual('WORKS');
});
});
it('should not get confused about where to use isolate scope when a replaced directive is used multiple times',
function() {
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
template: '<span scope-tester="replaced"><span scope-tester="inside"></span></span>'
};
});
directive('scopeTester', function(log) {
return {
link: function($scope, $element) {
log($element.attr('scope-tester') + '=' + ($scope.$root === $scope ? 'non-isolate' : 'isolate'));
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div>' +
'<div isolate scope-tester="outside"></div>' +
'<span scope-tester="sibling"></span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('inside=isolate; ' +
'outside replaced=non-isolate; ' + // outside
'outside replaced=isolate; ' + // replaced
'sibling=non-isolate');
});
});
it('should require controller of a non-isolate directive from an isolate directive on the ' +
'same element', function() {
var NonIsolateController = function() {};
var nonIsolateDirControllerInIsolateDirective;
module(function() {
directive('isolate', function() {
return {
scope: {},
require: 'nonIsolate',
link: function(_, __, ___, nonIsolateDirController) {
nonIsolateDirControllerInIsolateDirective = nonIsolateDirController;
}
};
});
directive('nonIsolate', function() {
return {
controller: NonIsolateController
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(nonIsolateDirControllerInIsolateDirective).toBeDefined();
expect(nonIsolateDirControllerInIsolateDirective instanceof NonIsolateController).toBe(true);
});
});
it('should support controllerAs', function() {
module(function() {
directive('main', function() {
return {
templateUrl: 'main.html',
transclude: true,
scope: {},
controller: function() {
this.name = 'lucas';
},
controllerAs: 'mainCtrl'
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('main.html', '<span>template:{{mainCtrl.name}} <div ng-transclude></div></span>');
element = $compile('<div main>transclude:{{mainCtrl.name}}</div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('template:lucas transclude:');
});
});
it('should support controller alias', function() {
module(function($controllerProvider) {
$controllerProvider.register('MainCtrl', function() {
this.name = 'lucas';
});
directive('main', function() {
return {
templateUrl: 'main.html',
scope: {},
controller: 'MainCtrl as mainCtrl'
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('main.html', '<span>{{mainCtrl.name}}</span>');
element = $compile('<div main></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('lucas');
});
});
it('should require controller on parent element',function() {
module(function() {
directive('main', function(log) {
return {
controller: function() {
this.name = 'main';
}
};
});
directive('dep', function(log) {
return {
require: '^main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:main');
});
});
it("should throw an error if required controller can't be found",function() {
module(function() {
directive('dep', function(log) {
return {
require: '^main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
expect(function() {
$compile('<div main><div dep></div></div>')($rootScope);
}).toThrowMinErr("$compile", "ctreq", "Controller 'main', required by directive 'dep', can't be found!");
});
});
it('should have optional controller on current element', function() {
module(function() {
directive('dep', function(log) {
return {
require: '?main',
link: function(scope, element, attrs, controller) {
log('dep:' + !!controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:false');
});
});
it('should support multiple controllers', function() {
module(function() {
directive('c1', valueFn({
controller: function() { this.name = 'c1'; }
}));
directive('c2', valueFn({
controller: function() { this.name = 'c2'; }
}));
directive('dep', function(log) {
return {
require: ['^c1', '^c2'],
link: function(scope, element, attrs, controller) {
log('dep:' + controller[0].name + '-' + controller[1].name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div c1 c2><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:c1-c2');
});
});
it('should instantiate the controller just once when template/templateUrl', function() {
var syncCtrlSpy = jasmine.createSpy('sync controller'),
asyncCtrlSpy = jasmine.createSpy('async controller');
module(function() {
directive('myDirectiveSync', valueFn({
template: '<div>Hello!</div>',
controller: syncCtrlSpy
}));
directive('myDirectiveAsync', valueFn({
templateUrl: 'myDirectiveAsync.html',
controller: asyncCtrlSpy,
compile: function() {
return function() {
};
}
}));
});
inject(function($templateCache, $compile, $rootScope) {
expect(syncCtrlSpy).not.toHaveBeenCalled();
expect(asyncCtrlSpy).not.toHaveBeenCalled();
$templateCache.put('myDirectiveAsync.html', '<div>Hello!</div>');
element = $compile('<div>'+
'<span xmy-directive-sync></span>' +
'<span my-directive-async></span>' +
'</div>')($rootScope);
expect(syncCtrlSpy).not.toHaveBeenCalled();
expect(asyncCtrlSpy).not.toHaveBeenCalled();
$rootScope.$apply();
//expect(syncCtrlSpy).toHaveBeenCalledOnce();
expect(asyncCtrlSpy).toHaveBeenCalledOnce();
});
});
it('should instantiate controllers in the parent->child order when transluction, templateUrl and replacement ' +
'are in the mix', function() {
// When a child controller is in the transclusion that replaces the parent element that has a directive with
// a controller, we should ensure that we first instantiate the parent and only then stuff that comes from the
// transclusion.
//
// The transclusion moves the child controller onto the same element as parent controller so both controllers are
// on the same level.
module(function() {
directive('parentDirective', function() {
return {
transclude: true,
replace: true,
templateUrl: 'parentDirective.html',
controller: function (log) { log('parentController'); }
};
});
directive('childDirective', function() {
return {
require: '^parentDirective',
templateUrl: 'childDirective.html',
controller : function(log) { log('childController'); }
};
});
});
inject(function($templateCache, log, $compile, $rootScope) {
$templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
$templateCache.put('childDirective.html', '<span>childTemplateText;</span>');
element = $compile('<div parent-directive><div child-directive></div>childContentText;</div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('parentController; childController');
expect(element.text()).toBe('childTemplateText;childContentText;');
});
});
it('should instantiate the controller after the isolate scope bindings are initialized (with template)', function () {
module(function () {
var Ctrl = function ($scope, log) {
log('myFoo=' + $scope.myFoo);
};
directive('myDirective', function () {
return {
scope: {
myFoo: "="
},
template: '<p>Hello</p>',
controller: Ctrl
};
});
});
inject(function ($templateCache, $compile, $rootScope, log) {
$rootScope.foo = "bar";
element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('myFoo=bar');
});
});
it('should instantiate the controller after the isolate scope bindings are initialized (with templateUrl)', function () {
module(function () {
var Ctrl = function ($scope, log) {
log('myFoo=' + $scope.myFoo);
};
directive('myDirective', function () {
return {
scope: {
myFoo: "="
},
templateUrl: 'hello.html',
controller: Ctrl
};
});
});
inject(function ($templateCache, $compile, $rootScope, log) {
$templateCache.put('hello.html', '<p>Hello</p>');
$rootScope.foo = "bar";
element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('myFoo=bar');
});
});
it('should instantiate controllers in the parent->child->baby order when nested transluction, templateUrl and ' +
'replacement are in the mix', function() {
// similar to the test above, except that we have one more layer of nesting and nested transclusion
module(function() {
directive('parentDirective', function() {
return {
transclude: true,
replace: true,
templateUrl: 'parentDirective.html',
controller: function (log) { log('parentController'); }
};
});
directive('childDirective', function() {
return {
require: '^parentDirective',
transclude: true,
replace: true,
templateUrl: 'childDirective.html',
controller : function(log) { log('childController'); }
};
});
directive('babyDirective', function() {
return {
require: '^childDirective',
templateUrl: 'babyDirective.html',
controller : function(log) { log('babyController'); }
};
});
});
inject(function($templateCache, log, $compile, $rootScope) {
$templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
$templateCache.put('childDirective.html', '<span ng-transclude>childTemplateText;</span>');
$templateCache.put('babyDirective.html', '<span>babyTemplateText;</span>');
element = $compile('<div parent-directive>' +
'<div child-directive>' +
'childContentText;' +
'<div baby-directive>babyContent;</div>' +
'</div>' +
'</div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('parentController; childController; babyController');
expect(element.text()).toBe('childContentText;babyTemplateText;');
});
});
it('should allow controller usage in pre-link directive functions with templateUrl', function () {
module(function () {
var Ctrl = function (log) {
log('instance');
};
directive('myDirective', function () {
return {
scope: true,
templateUrl: 'hello.html',
controller: Ctrl,
compile: function () {
return {
pre: function (scope, template, attr, ctrl) {},
post: function () {}
};
}
};
});
});
inject(function ($templateCache, $compile, $rootScope, log) {
$templateCache.put('hello.html', '<p>Hello</p>');
element = $compile('<div my-directive></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('instance');
expect(element.text()).toBe('Hello');
});
});
it('should allow controller usage in pre-link directive functions with a template', function () {
module(function () {
var Ctrl = function (log) {
log('instance');
};
directive('myDirective', function () {
return {
scope: true,
template: '<p>Hello</p>',
controller: Ctrl,
compile: function () {
return {
pre: function (scope, template, attr, ctrl) {},
post: function () {}
};
}
};
});
});
inject(function ($templateCache, $compile, $rootScope, log) {
element = $compile('<div my-directive></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('instance');
expect(element.text()).toBe('Hello');
});
});
it('should throw ctreq with correct directive name, regardless of order', function() {
module(function($compileProvider) {
$compileProvider.directive('aDir', valueFn({
restrict: "E",
require: "ngModel",
link: noop
}));
});
inject(function($compile, $rootScope) {
expect(function() {
// a-dir will cause a ctreq error to be thrown. Previously, the error would reference
// the last directive in the chain (which in this case would be ngClick), based on
// priority and alphabetical ordering. This test verifies that the ordering does not
// affect which directive is referenced in the minErr message.
element = $compile('<a-dir ng-click="foo=bar"></a-dir>')($rootScope);
}).toThrowMinErr('$compile', 'ctreq',
"Controller 'ngModel', required by directive 'aDir', can't be found!");
});
});
});
describe('transclude', function() {
describe('content transclusion', function() {
it('should support transclude directive', function() {
module(function() {
directive('trans', function() {
return {
transclude: 'content',
replace: true,
scope: true,
template: '<ul><li>W:{{$parent.$id}}-{{$id}};</li><li ng-transclude></li></ul>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div trans>T:{{$parent.$id}}-{{$id}}<span>;</span></div></div>')
($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('W:1-2;T:1-3;');
expect(jqLite(element.find('span')[0]).text()).toEqual('T:1-3');
expect(jqLite(element.find('span')[1]).text()).toEqual(';');
});
});
it('should transclude transcluded content', function() {
module(function() {
directive('book', valueFn({
transclude: 'content',
template: '<div>book-<div chapter>(<div ng-transclude></div>)</div></div>'
}));
directive('chapter', valueFn({
transclude: 'content',
templateUrl: 'chapter.html'
}));
directive('section', valueFn({
transclude: 'content',
template: '<div>section-!<div ng-transclude></div>!</div></div>'
}));
return function($httpBackend) {
$httpBackend.
expect('GET', 'chapter.html').
respond('<div>chapter-<div section>[<div ng-transclude></div>]</div></div>');
};
});
inject(function(log, $rootScope, $compile, $httpBackend) {
element = $compile('<div><div book>paragraph</div></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('book-');
$httpBackend.flush();
$rootScope.$apply();
expect(element.text()).toEqual('book-chapter-section-![(paragraph)]!');
});
});
it('should only allow one content transclusion per element', function() {
module(function() {
directive('first', valueFn({
transclude: true
}));
directive('second', valueFn({
transclude: true
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first="" second=""></div>');
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
});
});
it('should not leak if two "element" transclusions are on the same element', function() {
var calcCacheSize = function() {
var size = 0;
forEach(jqLite.cache, function(item, key) { size++; });
return size;
};
inject(function($compile, $rootScope) {
expect(calcCacheSize()).toEqual(0);
element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope);
expect(calcCacheSize()).toEqual(1);
$rootScope.$apply('xs = [0,1]');
expect(calcCacheSize()).toEqual(2);
$rootScope.$apply('xs = [0]');
expect(calcCacheSize()).toEqual(1);
$rootScope.$apply('xs = []');
expect(calcCacheSize()).toEqual(1);
element.remove();
expect(calcCacheSize()).toEqual(0);
});
});
it('should not leak if two "element" transclusions are on the same element', function() {
var calcCacheSize = function() {
var size = 0;
forEach(jqLite.cache, function(item, key) { size++; });
return size;
};
inject(function($compile, $rootScope) {
expect(calcCacheSize()).toEqual(0);
element = $compile('<div><div ng-repeat="x in xs" ng-if="val">{{x}}</div></div>')($rootScope);
$rootScope.$apply('xs = [0,1]');
// At this point we have a bunch of comment placeholders but no real transcluded elements
// So the cache only contains the root element's data
expect(calcCacheSize()).toEqual(1);
$rootScope.$apply('val = true');
// Now we have two concrete transcluded elements plus some comments so two more cache items
expect(calcCacheSize()).toEqual(3);
$rootScope.$apply('val = false');
// Once again we only have comments so no transcluded elements and the cache is back to just
// the root element
expect(calcCacheSize()).toEqual(1);
element.remove();
// Now we've even removed the root element along with its cache
expect(calcCacheSize()).toEqual(0);
});
});
it('should remove transclusion scope, when the DOM is destroyed', function() {
module(function() {
directive('box', valueFn({
transclude: true,
scope: { name: '=', show: '=' },
template: '<div><h1>Hello: {{name}}!</h1><div ng-transclude></div></div>',
link: function(scope, element) {
scope.$watch(
'show',
function(show) {
if (!show) {
element.find('div').find('div').remove();
}
}
);
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.username = 'Misko';
$rootScope.select = true;
element = $compile(
'<div><div box name="username" show="select">user: {{username}}</div></div>')
($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('Hello: Misko!user: Misko');
var widgetScope = $rootScope.$$childHead;
var transcludeScope = widgetScope.$$nextSibling;
expect(widgetScope.name).toEqual('Misko');
expect(widgetScope.$parent).toEqual($rootScope);
expect(transcludeScope.$parent).toEqual($rootScope);
$rootScope.select = false;
$rootScope.$apply();
expect(element.text()).toEqual('Hello: Misko!');
expect(widgetScope.$$nextSibling).toEqual(null);
});
});
it('should add a $$transcluded property onto the transcluded scope', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
replace: true,
scope: true,
template: '<div><span>I:{{$$transcluded}}</span><div ng-transclude></div></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div trans>T:{{$$transcluded}}</div></div>')
($rootScope);
$rootScope.$apply();
expect(jqLite(element.find('span')[0]).text()).toEqual('I:');
expect(jqLite(element.find('span')[1]).text()).toEqual('T:true');
});
});
it('should clear contents of the ng-translude element before appending transcluded content', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude>old stuff! </div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans>unicorn!</div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><span>unicorn!</span></div>');
});
});
it('should throw on an ng-transclude element inside no transclusion directive', function() {
inject(function ($rootScope, $compile) {
// we need to do this because different browsers print empty attributes differently
try {
$compile('<div><div ng-transclude></div></div>')($rootScope);
} catch(e) {
expect(e.message).toMatch(new RegExp(
'^\\[ngTransclude:orphan\\] ' +
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found\\. ' +
'Element: <div ng-transclude.+'));
}
});
});
it('should not pass transclusion into a template directive when the directive didn\'t request transclusion', function() {
module(function($compileProvider) {
$compileProvider.directive('transFoo', valueFn({
template: '<div>' +
'<div no-trans-bar></div>' +
'<div ng-transclude>this one should get replaced with content</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
$compileProvider.directive('noTransBar', valueFn({
template: '<div>' +
// This ng-transclude is invalid. It should throw an error.
'<div class="bar" ng-transclude></div>' +
'</div>',
transclude: false
}));
});
inject(function($compile, $rootScope) {
expect(function() {
$compile('<div trans-foo>content</div>')($rootScope);
}).toThrowMinErr('ngTransclude', 'orphan',
'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">');
});
});
it('should not pass transclusion into a templateUrl directive', function() {
module(function($compileProvider) {
$compileProvider.directive('transFoo', valueFn({
template: '<div>' +
'<div no-trans-bar></div>' +
'<div ng-transclude>this one should get replaced with content</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
$compileProvider.directive('noTransBar', valueFn({
templateUrl: 'noTransBar.html',
transclude: false
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('noTransBar.html',
'<div>' +
// This ng-transclude is invalid. It should throw an error.
'<div class="bar" ng-transclude></div>' +
'</div>');
expect(function() {
element = $compile('<div trans-foo>content</div>')($rootScope);
$rootScope.$apply();
}).toThrowMinErr('ngTransclude', 'orphan',
'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">');
});
});
it('should expose transcludeFn in compile fn even for templateUrl', function() {
module(function() {
directive('transInCompile', valueFn({
transclude: true,
// template: '<div class="foo">whatever</div>',
templateUrl: 'foo.html',
compile: function(_, __, transclude) {
return function(scope, element) {
transclude(scope, function(clone, scope) {
element.html('');
element.append(clone);
});
};
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('foo.html', '<div class="foo">whatever</div>');
compile('<div trans-in-compile>transcluded content</div>');
$rootScope.$apply();
expect(trim(element.text())).toBe('transcluded content');
});
});
it('should make the result of a transclusion available to the parent directive in post-linking phase' +
'(template)', function() {
module(function() {
directive('trans', function(log) {
return {
transclude: true,
template: '<div ng-transclude></div>',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent directive in post-linking phase' +
'(templateUrl)', function() {
// when compiling an async directive the transclusion is always processed before the directive
// this is different compared to sync directive. delaying the transclusion makes little sense.
module(function() {
directive('trans', function(log) {
return {
transclude: true,
templateUrl: 'trans.html',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile, $templateCache) {
$templateCache.put('trans.html', '<div ng-transclude></div>');
element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
'(template)', function() {
module(function() {
directive('replacedTrans', function(log) {
return {
transclude: true,
replace: true,
template: '<div ng-transclude></div>',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
' (templateUrl)', function() {
module(function() {
directive('replacedTrans', function(log) {
return {
transclude: true,
replace: true,
templateUrl: 'trans.html',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile, $templateCache) {
$templateCache.put('trans.html', '<div ng-transclude></div>');
element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should copy the directive controller to all clones', function() {
var transcludeCtrl, cloneCount = 2;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
transcludeCtrl = this;
},
link: function(scope, el, attr, ctrl, $transclude) {
var i;
for (i=0; i<cloneCount; i++) {
$transclude(cloneAttach);
}
function cloneAttach(clone) {
el.append(clone);
}
}
}));
});
inject(function($compile) {
element = $compile('<div transclude><span></span></div>')($rootScope);
var children = element.children(), i;
expect(transcludeCtrl).toBeDefined();
expect(element.data('$transcludeController')).toBe(transcludeCtrl);
for (i=0; i<cloneCount; i++) {
expect(children.eq(i).data('$transcludeController')).toBeUndefined();
}
});
});
it('should provide the $transclude controller local as 5th argument to the pre and post-link function', function() {
var ctrlTransclude, preLinkTransclude, postLinkTransclude;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
ctrlTransclude = $transclude;
},
compile: function() {
return {
pre: function(scope, el, attr, ctrl, $transclude) {
preLinkTransclude = $transclude;
},
post: function(scope, el, attr, ctrl, $transclude) {
postLinkTransclude = $transclude;
}
};
}
}));
});
inject(function($compile) {
element = $compile('<div transclude></div>')($rootScope);
expect(ctrlTransclude).toBeDefined();
expect(ctrlTransclude).toBe(preLinkTransclude);
expect(ctrlTransclude).toBe(postLinkTransclude);
});
});
it('should allow an optional scope argument in $transclude', function() {
var capturedChildCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(scope, function(clone) {
element.append(clone);
});
}
}));
});
inject(function($compile) {
element = $compile('<div transclude>{{$id}}</div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('' + $rootScope.$id);
});
});
it('should expose the directive controller to transcluded children', function() {
var capturedChildCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function() {
},
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(function(clone) {
element.append(clone);
});
}
}));
directive('child', valueFn({
require: '^transclude',
link: function(scope, element, attr, ctrl) {
capturedChildCtrl = ctrl;
}
}));
});
inject(function($compile) {
element = $compile('<div transclude><div child></div></div>')($rootScope);
expect(capturedChildCtrl).toBeTruthy();
});
});
describe('nested transcludes', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.directive('noop', valueFn({}));
$compileProvider.directive('sync', valueFn({
template: '<div ng-transclude></div>',
transclude: true
}));
$compileProvider.directive('async', valueFn({
templateUrl: 'async',
transclude: true
}));
$compileProvider.directive('syncSync', valueFn({
template: '<div noop><div sync><div ng-transclude></div></div></div>',
transclude: true
}));
$compileProvider.directive('syncAsync', valueFn({
template: '<div noop><div async><div ng-transclude></div></div></div>',
transclude: true
}));
$compileProvider.directive('asyncSync', valueFn({
templateUrl: 'asyncSync',
transclude: true
}));
$compileProvider.directive('asyncAsync', valueFn({
templateUrl: 'asyncAsync',
transclude: true
}));
}));
beforeEach(inject(function($templateCache) {
$templateCache.put('async', '<div ng-transclude></div>');
$templateCache.put('asyncSync', '<div noop><div sync><div ng-transclude></div></div></div>');
$templateCache.put('asyncAsync', '<div noop><div async><div ng-transclude></div></div></div>');
}));
it('should allow nested transclude directives with sync template containing sync template', inject(function($compile, $rootScope) {
element = $compile('<div sync-sync>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with sync template containing async template', inject(function($compile, $rootScope) {
element = $compile('<div sync-async>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with async template containing sync template', inject(function($compile, $rootScope) {
element = $compile('<div async-sync>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with async template containing asynch template', inject(function($compile, $rootScope) {
element = $compile('<div async-async>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should not leak memory with nested transclusion', function() {
var calcCacheSize = function() {
var count = 0;
for (var k in jqLite.cache) { ++count; }
return count;
};
inject(function($compile, $rootScope) {
var size;
expect(calcCacheSize()).toEqual(0);
element = jqLite('<div><ul><li ng-repeat="n in nums">{{n}} => <i ng-if="0 === n%2">Even</i><i ng-if="1 === n%2">Odd</i></li></ul></div>');
$compile(element)($rootScope.$new());
$rootScope.nums = [0,1,2];
$rootScope.$apply();
size = calcCacheSize();
$rootScope.nums = [3,4,5];
$rootScope.$apply();
expect(calcCacheSize()).toEqual(size);
element.remove();
expect(calcCacheSize()).toEqual(0);
});
});
});
describe('nested isolated scope transcludes', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.directive('trans', valueFn({
restrict: 'E',
template: '<div ng-transclude></div>',
transclude: true
}));
$compileProvider.directive('transAsync', valueFn({
restrict: 'E',
templateUrl: 'transAsync',
transclude: true
}));
$compileProvider.directive('iso', valueFn({
restrict: 'E',
transclude: true,
template: '<trans><span ng-transclude></span></trans>',
scope: {}
}));
$compileProvider.directive('isoAsync1', valueFn({
restrict: 'E',
transclude: true,
template: '<trans-async><span ng-transclude></span></trans-async>',
scope: {}
}));
$compileProvider.directive('isoAsync2', valueFn({
restrict: 'E',
transclude: true,
templateUrl: 'isoAsync',
scope: {}
}));
}));
beforeEach(inject(function($templateCache) {
$templateCache.put('transAsync', '<div ng-transclude></div>');
$templateCache.put('isoAsync', '<trans-async><span ng-transclude></span></trans-async>');
}));
it('should pass the outer scope to the transclude on the isolated template sync-sync', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso><span ng-bind="val"></span></iso>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should pass the outer scope to the transclude on the isolated template async-sync', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso-async1><span ng-bind="val"></span></iso-async1>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should pass the outer scope to the transclude on the isolated template async-async', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso-async2><span ng-bind="val"></span></iso-async2>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
});
describe('multiple siblings receiving transclusion', function() {
it("should only receive transclude from parent", function() {
module(function($compileProvider) {
$compileProvider.directive('myExample', valueFn({
scope: {},
link: function link(scope, element, attrs) {
var foo = element[0].querySelector('.foo');
scope.children = angular.element(foo).children().length;
},
template: '<div>' +
'<div>myExample {{children}}!</div>' +
'<div ng-if="children">has children</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
});
inject(function($compile, $rootScope) {
var element = $compile('<div my-example></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('myExample 0!');
dealoc(element);
element = $compile('<div my-example><p></p></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('myExample 1!has children');
dealoc(element);
});
});
});
});
describe('element transclusion', function() {
it('should support basic element transclusion', function() {
module(function() {
directive('trans', function(log) {
return {
transclude: 'element',
priority: 2,
controller: function($transclude) { this.$transclude = $transclude; },
compile: function(element, attrs, template) {
log('compile: ' + angular.mock.dump(element));
return function(scope, element, attrs, ctrl) {
log('link');
var cursor = element;
template(scope.$new(), function(clone) {cursor.after(cursor = clone);});
ctrl.$transclude(function(clone) {cursor.after(clone);});
};
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>')
($rootScope);
$rootScope.$apply();
expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH');
expect(element.text()).toEqual('1-2;1-3;');
});
});
it('should only allow one element transclusion per element', function() {
module(function() {
directive('first', valueFn({
transclude: 'element'
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first second></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [first, second] asking for transclusion on: ' +
'<!-- first: -->');
});
});
it('should only allow one element transclusion per element when directives have different priorities', function() {
// we restart compilation in this case and we need to remember the duplicates during the second compile
// regression #3893
module(function() {
directive('first', valueFn({
transclude: 'element',
priority: 100
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first second></div>');
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
});
});
it('should only allow one element transclusion per element when async replace directive is in the mix', function() {
module(function() {
directive('template', valueFn({
templateUrl: 'template.html',
replace: true
}));
directive('first', valueFn({
transclude: 'element',
priority: 100
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile, $httpBackend) {
$httpBackend.expectGET('template.html').respond('<p second>template.html</p>');
$compile('<div template first></div>');
expect(function() {
$httpBackend.flush();
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/);
});
});
it('should support transcluded element on root content', function() {
var comment;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
compile: function(element, attr, linker) {
return function(scope, element, attr) {
comment = element;
};
}
}));
});
inject(function($compile, $rootScope) {
var element = jqLite('<div>before<div transclude></div>after</div>').contents();
expect(element.length).toEqual(3);
expect(nodeName_(element[1])).toBe('div');
$compile(element)($rootScope);
expect(nodeName_(element[1])).toBe('#comment');
expect(nodeName_(comment)).toBe('#comment');
});
});
it('should terminate compilation only for element trasclusion', function() {
module(function() {
directive('elementTrans', function(log) {
return {
transclude: 'element',
priority: 50,
compile: log.fn('compile:elementTrans')
};
});
directive('regularTrans', function(log) {
return {
transclude: true,
priority: 50,
compile: log.fn('compile:regularTrans')
};
});
});
inject(function(log, $compile, $rootScope) {
$compile('<div><div element-trans log="elem"></div><div regular-trans log="regular"></div></div>')($rootScope);
expect(log).toEqual('compile:elementTrans; compile:regularTrans; regular');
});
});
it('should instantiate high priority controllers only once, but low priority ones each time we transclude',
function() {
module(function() {
directive('elementTrans', function(log) {
return {
transclude: 'element',
priority: 50,
controller: function($transclude, $element) {
log('controller:elementTrans');
$transclude(function(clone) {
$element.after(clone);
});
$transclude(function(clone) {
$element.after(clone);
});
$transclude(function(clone) {
$element.after(clone);
});
}
};
});
directive('normalDir', function(log) {
return {
controller: function() {
log('controller:normalDir');
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div><div element-trans normal-dir></div></div>')($rootScope);
expect(log).toEqual([
'controller:elementTrans',
'controller:normalDir',
'controller:normalDir',
'controller:normalDir'
]);
});
});
it('should allow to access $transclude in the same directive', function() {
var _$transclude;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function($transclude) {
_$transclude = $transclude;
}
}));
});
inject(function($compile) {
element = $compile('<div transclude></div>')($rootScope);
expect(_$transclude).toBeDefined();
});
});
it('should copy the directive controller to all clones', function() {
var transcludeCtrl, cloneCount = 2;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function() {
transcludeCtrl = this;
},
link: function(scope, el, attr, ctrl, $transclude) {
var i;
for (i=0; i<cloneCount; i++) {
$transclude(cloneAttach);
}
function cloneAttach(clone) {
el.after(clone);
}
}
}));
});
inject(function($compile) {
element = $compile('<div><div transclude></div></div>')($rootScope);
var children = element.children(), i;
for (i=0; i<cloneCount; i++) {
expect(children.eq(i).data('$transcludeController')).toBe(transcludeCtrl);
}
});
});
it('should expose the directive controller to transcluded children', function() {
var capturedTranscludeCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function() {
},
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(scope, function(clone) {
element.after(clone);
});
}
}));
directive('child', valueFn({
require: '^transclude',
link: function(scope, element, attr, ctrl) {
capturedTranscludeCtrl = ctrl;
}
}));
});
inject(function($compile) {
element = $compile('<div transclude><div child></div></div>')($rootScope);
expect(capturedTranscludeCtrl).toBeTruthy();
});
});
it('should allow access to $transclude in a templateUrl directive', function() {
var transclude;
module(function() {
directive('template', valueFn({
templateUrl: 'template.html',
replace: true
}));
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
transclude = $transclude;
}
}));
});
inject(function($compile, $httpBackend) {
$httpBackend.expectGET('template.html').respond('<div transclude></div>');
element = $compile('<div template></div>')($rootScope);
$httpBackend.flush();
expect(transclude).toBeDefined();
});
});
// issue #6006
it('should link directive with $element as a comment node', function() {
module(function($provide) {
directive('innerAgain', function(log) {
return {
transclude: 'element',
link: function(scope, element, attr, controllers, transclude) {
log('innerAgain:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
transclude(scope, function(clone) {
element.parent().append(clone);
});
}
};
});
directive('inner', function(log) {
return {
replace: true,
templateUrl: 'inner.html',
link: function(scope, element) {
log('inner:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
}
};
});
directive('outer', function(log) {
return {
transclude: 'element',
link: function(scope, element, attrs, controllers, transclude) {
log('outer:'+lowercase(nodeName_(element))+':'+trim(element[0].data));
transclude(scope, function(clone) {
element.parent().append(clone);
});
}
};
});
});
inject(function(log, $compile, $rootScope, $templateCache) {
$templateCache.put('inner.html', '<div inner-again><p>Content</p></div>');
element = $compile('<div><div outer><div inner></div></div></div>')($rootScope);
$rootScope.$digest();
var child = element.children();
expect(log.toArray()).toEqual([
"outer:#comment:outer:",
"innerAgain:#comment:innerAgain:",
"inner:#comment:innerAgain:"
]);
expect(child.length).toBe(1);
expect(child.contents().length).toBe(2);
expect(lowercase(nodeName_(child.contents().eq(0)))).toBe('#comment');
expect(lowercase(nodeName_(child.contents().eq(1)))).toBe('div');
});
});
});
it('should safely create transclude comment node and not break with "-->"',
inject(function($rootScope) {
// see: https://github.com/angular/angular.js/issues/1740
element = $compile('<ul><li ng-repeat="item in [\'-->\', \'x\']">{{item}}|</li></ul>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('-->|x|');
}));
// See https://github.com/angular/angular.js/issues/7183
it("should pass transclusion through to template of a 'replace' directive", function() {
module(function() {
directive('transSync', function() {
return {
transclude: true,
link: function(scope, element, attr, ctrl, transclude) {
expect(transclude).toEqual(jasmine.any(Function));
transclude(function(child) { element.append(child); });
}
};
});
directive('trans', function($timeout) {
return {
transclude: true,
link: function(scope, element, attrs, ctrl, transclude) {
// We use timeout here to simulate how ng-if works
$timeout(function() {
transclude(function(child) { element.append(child); });
});
}
};
});
directive('replaceWithTemplate', function() {
return {
templateUrl: "template.html",
replace: true
};
});
});
inject(function($compile, $rootScope, $templateCache, $timeout) {
$templateCache.put('template.html', '<div trans-sync>Content To Be Transcluded</div>');
expect(function() {
element = $compile('<div><div trans><div replace-with-template></div></div></div>')($rootScope);
$timeout.flush();
}).not.toThrow();
expect(element.text()).toEqual('Content To Be Transcluded');
});
});
});
describe('img[src] sanitization', function() {
it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) {
element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'http://example.com/image.png';
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image.png');
// But it should accept trusted values anyway.
$rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png');
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image2.png');
}));
it('should not sanitize attributes other than src', inject(function($compile, $rootScope) {
/* jshint scripturl:true */
element = $compile('<img title="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = "javascript:doEvilStuff()";
$rootScope.$apply();
expect(element.attr('title')).toBe('javascript:doEvilStuff()');
}));
it('should use $$sanitizeUriProvider for reconfiguration of the src whitelist', function() {
module(function($compileProvider, $$sanitizeUriProvider) {
var newRe = /javascript:/,
returnVal;
expect($compileProvider.imgSrcSanitizationWhitelist()).toBe($$sanitizeUriProvider.imgSrcSanitizationWhitelist());
returnVal = $compileProvider.imgSrcSanitizationWhitelist(newRe);
expect(returnVal).toBe($compileProvider);
expect($$sanitizeUriProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
expect($compileProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
});
inject(function() {
// needed to the module definition above is run...
});
});
it('should use $$sanitizeUri', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = "someUrl";
$$sanitizeUri.andReturn('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('src')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true);
});
});
});
describe('a[href] sanitization', function() {
it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) {
/* jshint scripturl:true */
element = $compile('<div href="{{testUrl}}"></div>')($rootScope);
$rootScope.testUrl = "javascript:doEvilStuff()";
$rootScope.$apply();
expect(element.attr('href')).toBe('javascript:doEvilStuff()');
}));
it('should not sanitize attributes other than href', inject(function($compile, $rootScope) {
/* jshint scripturl:true */
element = $compile('<a title="{{testUrl}}"></a>')($rootScope);
$rootScope.testUrl = "javascript:doEvilStuff()";
$rootScope.$apply();
expect(element.attr('title')).toBe('javascript:doEvilStuff()');
}));
it('should use $$sanitizeUriProvider for reconfiguration of the href whitelist', function() {
module(function($compileProvider, $$sanitizeUriProvider) {
var newRe = /javascript:/,
returnVal;
expect($compileProvider.aHrefSanitizationWhitelist()).toBe($$sanitizeUriProvider.aHrefSanitizationWhitelist());
returnVal = $compileProvider.aHrefSanitizationWhitelist(newRe);
expect(returnVal).toBe($compileProvider);
expect($$sanitizeUriProvider.aHrefSanitizationWhitelist()).toBe(newRe);
expect($compileProvider.aHrefSanitizationWhitelist()).toBe(newRe);
});
inject(function() {
// needed to the module definition above is run...
});
});
it('should use $$sanitizeUri', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
$rootScope.testUrl = "someUrl";
$$sanitizeUri.andReturn('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('href')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
});
});
});
describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() {
it('should disallow interpolation on onclick', inject(function($compile, $rootScope) {
// All interpolations are disallowed.
$rootScope.onClickJs = "";
expect(function() {
$compile('<button onclick="{{onClickJs}}"></script>')($rootScope);
}).toThrowMinErr(
"$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " +
"Please use the ng- versions (such as ng-click instead of onclick) instead.");
expect(function() {
$compile('<button ONCLICK="{{onClickJs}}"></script>')($rootScope);
}).toThrowMinErr(
"$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " +
"Please use the ng- versions (such as ng-click instead of onclick) instead.");
expect(function() {
$compile('<button ng-attr-onclick="{{onClickJs}}"></script>')($rootScope);
}).toThrowMinErr(
"$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " +
"Please use the ng- versions (such as ng-click instead of onclick) instead.");
}));
it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) {
/* jshint scripturl:true */
element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope);
$rootScope.onClickJs = 'javascript:doSomething()';
$rootScope.$apply();
expect(element.attr('on-click')).toEqual('javascript:doSomething()');
}));
it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) {
element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope);
$rootScope.dataOnVar = 'data-on text';
$rootScope.$apply();
expect(element.attr('data-on')).toEqual('data-on text');
element = $compile('<button on="{{onVar}}"></script>')($rootScope);
$rootScope.onVar = 'on text';
$rootScope.$apply();
expect(element.attr('on')).toEqual('on text');
}));
});
describe('iframe[src]', function() {
it('should pass through src attributes for the same domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = "different_page";
$rootScope.$apply();
expect(element.attr('src')).toEqual('different_page');
}));
it('should clear out src attributes for a different domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = "http://a.different.domain.example.com";
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: " +
"http://a.different.domain.example.com");
}));
it('should clear out JS src attributes', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = "javascript:alert(1);";
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: " +
"javascript:alert(1);");
}));
it('should clear out non-resource_url src attributes', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()");
expect($rootScope.$apply).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()");
}));
it('should pass through $sce.trustAs() values in src attributes', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()");
$rootScope.$apply();
expect(element.attr('src')).toEqual('javascript:doTrustedStuff()');
}));
});
describe('form[action]', function() {
it('should pass through action attribute for the same domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = "different_page";
$rootScope.$apply();
expect(element.attr('action')).toEqual('different_page');
}));
it('should clear out action attribute for a different domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = "http://a.different.domain.example.com";
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: " +
"http://a.different.domain.example.com");
}));
it('should clear out JS action attribute', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = "javascript:alert(1);";
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: " +
"javascript:alert(1);");
}));
it('should clear out non-resource_url action attribute', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()");
expect($rootScope.$apply).toThrowMinErr(
"$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " +
"loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()");
}));
it('should pass through $sce.trustAs() values in action attribute', inject(function($compile, $rootScope, $sce) {
/* jshint scripturl:true */
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()");
$rootScope.$apply();
expect(element.attr('action')).toEqual('javascript:doTrustedStuff()');
}));
});
if (!msie || msie >= 11) {
describe('iframe[srcdoc]', function() {
it('should NOT set iframe contents for untrusted values', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = '<div onclick="">hello</div>';
expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
/Can't interpolate: {{html}}\n/.source +
/[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
}));
it('should NOT set html for wrongly typed values', inject(function($rootScope, $compile, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = $sce.trustAsCss('<div onclick="">hello</div>');
expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
/Can't interpolate: {{html}}\n/.source +
/[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
}));
it('should set html for trusted values', inject(function($rootScope, $compile, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = $sce.trustAsHtml('<div onclick="">hello</div>');
$rootScope.$digest();
expect(angular.lowercase(element.attr('srcdoc'))).toEqual('<div onclick="">hello</div>');
}));
});
}
describe('ngAttr* attribute binding', function() {
it('should bind after digest but not before', inject(function($compile, $rootScope) {
$rootScope.name = "Misko";
element = $compile('<span ng-attr-test="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
it('should bind after digest but not before when after overridden attribute', inject(function($compile, $rootScope) {
$rootScope.name = "Misko";
element = $compile('<span test="123" ng-attr-test="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
it('should bind after digest but not before when before overridden attribute', inject(function($compile, $rootScope) {
$rootScope.name = "Misko";
element = $compile('<span ng-attr-test="{{name}}" test="123"></span>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
describe('in directive', function() {
beforeEach(module(function() {
directive('syncTest', function(log) {
return {
link: {
pre: function(s, e, attr) { log(attr.test); },
post: function(s, e, attr) { log(attr.test); }
}
};
});
directive('asyncTest', function(log) {
return {
templateUrl: 'async.html',
link: {
pre: function(s, e, attr) { log(attr.test); },
post: function(s, e, attr) { log(attr.test); }
}
};
});
}));
beforeEach(inject(function($templateCache) {
$templateCache.put('async.html', '<h1>Test</h1>');
}));
it('should provide post-digest value in synchronous directive link functions when after overridden attribute',
inject(function(log, $rootScope, $compile) {
$rootScope.test = "TEST";
element = $compile('<div sync-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}));
it('should provide post-digest value in synchronous directive link functions when before overridden attribute',
inject(function(log, $rootScope, $compile) {
$rootScope.test = "TEST";
element = $compile('<div sync-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}));
it('should provide post-digest value in asynchronous directive link functions when after overridden attribute',
inject(function(log, $rootScope, $compile) {
$rootScope.test = "TEST";
element = $compile('<div async-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}));
it('should provide post-digest value in asynchronous directive link functions when before overridden attribute',
inject(function(log, $rootScope, $compile) {
$rootScope.test = "TEST";
element = $compile('<div async-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}));
});
it('should work with different prefixes', inject(function($compile, $rootScope) {
$rootScope.name = "Misko";
element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBeUndefined();
expect(element.attr('test2')).toBeUndefined();
expect(element.attr('test3')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
expect(element.attr('test2')).toBe('Misko');
expect(element.attr('test3')).toBe('Misko');
}));
it('should work with the "href" attribute', inject(function($compile, $rootScope) {
$rootScope.value = 'test';
element = $compile('<a ng-attr-href="test/{{value}}"></a>')($rootScope);
$rootScope.$digest();
expect(element.attr('href')).toBe('test/test');
}));
it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) {
$rootScope.name = "Misko";
element = $compile('<span data-ng-attr-test2="{{name}}" x-ng-attr-test3="{{name}}" data-ng:attr-test4="{{name}}"></span>')($rootScope);
expect(element.attr('test2')).toBeUndefined();
expect(element.attr('test3')).toBeUndefined();
expect(element.attr('test4')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test2')).toBe('Misko');
expect(element.attr('test3')).toBe('Misko');
expect(element.attr('test4')).toBe('Misko');
}));
describe('when an attribute has a dash-separated name', function () {
it('should work with different prefixes', inject(function($compile, $rootScope) {
$rootScope.name = "JamieMason";
element = $compile('<span ng:attr:dash-test="{{name}}" ng-Attr-dash-test2="{{name}}" ng_Attr_dash-test3="{{name}}"></span>')($rootScope);
expect(element.attr('dash-test')).toBeUndefined();
expect(element.attr('dash-test2')).toBeUndefined();
expect(element.attr('dash-test3')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('dash-test')).toBe('JamieMason');
expect(element.attr('dash-test2')).toBe('JamieMason');
expect(element.attr('dash-test3')).toBe('JamieMason');
}));
it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) {
$rootScope.name = "JamieMason";
element = $compile('<span data-ng-attr-dash-test2="{{name}}" x-ng-attr-dash-test3="{{name}}" data-ng:attr-dash-test4="{{name}}"></span>')($rootScope);
expect(element.attr('dash-test2')).toBeUndefined();
expect(element.attr('dash-test3')).toBeUndefined();
expect(element.attr('dash-test4')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('dash-test2')).toBe('JamieMason');
expect(element.attr('dash-test3')).toBe('JamieMason');
expect(element.attr('dash-test4')).toBe('JamieMason');
}));
it('should keep attributes ending with -start single-element directives', function() {
module(function($compileProvider) {
$compileProvider.directive('dashStarter', function(log) {
return {
link: function(scope, element, attrs) {
log(attrs.onDashStart);
}
};
});
});
inject(function($compile, $rootScope, log) {
$compile('<span data-dash-starter data-on-dash-start="starter"></span>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('starter');
});
});
it('should keep attributes ending with -end single-element directives', function() {
module(function($compileProvider) {
$compileProvider.directive('dashEnder', function(log) {
return {
link: function(scope, element, attrs) {
log(attrs.onDashEnd);
}
};
});
});
inject(function($compile, $rootScope, log) {
$compile('<span data-dash-ender data-on-dash-end="ender"></span>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('ender');
});
});
});
});
describe('multi-element directive', function() {
it('should group on link function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-show-start="show"></span>' +
'<span ng-show-end></span>' +
'</div>')($rootScope);
$rootScope.$digest();
var spans = element.find('span');
expect(spans.eq(0)).toBeHidden();
expect(spans.eq(1)).toBeHidden();
}));
it('should group on compile function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
'<span ng-repeat-end>{{i}}B;</span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1A1B;2A2B;');
}));
it('should support grouping over text nodes', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
':' + // Important: proves that we can iterate over non-elements
'<span ng-repeat-end>{{i}}B;</span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1A:1B;2A:2B;');
}));
it('should group on $root compile function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
'<span ng-repeat-end>{{i}}B;</span>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1A1B;2A2B;');
}));
it('should group on nested groups', function() {
module(function($compileProvider) {
$compileProvider.directive("ngMultiBind", valueFn({
multiElement: true,
link: function(scope, element, attr) {
element.text(scope.$eval(attr.ngMultiBind));
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<div ng-repeat-start="i in [1,2]">{{i}}A</div>' +
'<span ng-multi-bind-start="\'.\'"></span>' +
'<span ng-multi-bind-end></span>' +
'<div ng-repeat-end>{{i}}B;</div>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1A..1B;2A..2B;');
});
});
it('should group on nested groups of same directive', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<div ng-repeat-start="i in [1,2]">{{i}}(</div>' +
'<span ng-repeat-start="j in [2,3]">{{j}}-</span>' +
'<span ng-repeat-end>{{j}}</span>' +
'<div ng-repeat-end>){{i}};</div>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;');
}));
it('should set up and destroy the transclusion scopes correctly',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-if-start="val0"><span ng-if="val1"></span></div>' +
'<div ng-if-end><span ng-if="val2"></span></div>' +
'</div>'
)($rootScope);
$rootScope.$apply('val0 = true; val1 = true; val2 = true');
// At this point we should have something like:
//
// <div class="ng-scope">
//
// <!-- ngIf: val0 -->
//
// <div ng-if-start="val0" class="ng-scope">
// <!-- ngIf: val1 -->
// <span ng-if="val1" class="ng-scope"></span>
// <!-- end ngIf: val1 -->
// </div>
//
// <div ng-if-end="" class="ng-scope">
// <!-- ngIf: val2 -->
// <span ng-if="val2" class="ng-scope"></span>
// <!-- end ngIf: val2 -->
// </div>
//
// <!-- end ngIf: val0 -->
// </div>
var ngIfStartScope = element.find('div').eq(0).scope();
var ngIfEndScope = element.find('div').eq(1).scope();
expect(ngIfStartScope.$id).toEqual(ngIfEndScope.$id);
var ngIf1Scope = element.find('span').eq(0).scope();
var ngIf2Scope = element.find('span').eq(1).scope();
expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
expect(ngIf1Scope.$parent.$id).toEqual(ngIf2Scope.$parent.$id);
$rootScope.$apply('val1 = false');
// Now we should have something like:
//
// <div class="ng-scope">
// <!-- ngIf: val0 -->
// <div ng-if-start="val0" class="ng-scope">
// <!-- ngIf: val1 -->
// </div>
// <div ng-if-end="" class="ng-scope">
// <!-- ngIf: val2 -->
// <span ng-if="val2" class="ng-scope"></span>
// <!-- end ngIf: val2 -->
// </div>
// <!-- end ngIf: val0 -->
// </div>
expect(ngIfStartScope.$$destroyed).not.toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).not.toEqual(true);
$rootScope.$apply('val0 = false');
// Now we should have something like:
//
// <div class="ng-scope">
// <!-- ngIf: val0 -->
// </div>
expect(ngIfStartScope.$$destroyed).toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
}));
it('should set up and destroy the transclusion scopes correctly',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat-start="val in val0" ng-if="val1"></div>' +
'<div ng-repeat-end ng-if="val2"></div>' +
'</div>'
)($rootScope);
// To begin with there is (almost) nothing:
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
// </div>
expect(element.scope().$id).toEqual($rootScope.$id);
// Now we create all the elements
$rootScope.$apply('val0 = [1]; val1 = true; val2 = true');
// At this point we have:
//
// <div class="ng-scope">
//
// <!-- ngRepeat: val in val0 -->
// <!-- ngIf: val1 -->
// <div ng-repeat-start="val in val0" class="ng-scope">
// </div>
// <!-- end ngIf: val1 -->
//
// <!-- ngIf: val2 -->
// <div ng-repeat-end="" class="ng-scope">
// </div>
// <!-- end ngIf: val2 -->
// <!-- end ngRepeat: val in val0 -->
// </div>
var ngIf1Scope = element.find('div').eq(0).scope();
var ngIf2Scope = element.find('div').eq(1).scope();
var ngRepeatScope = ngIf1Scope.$parent;
expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
expect(ngIf1Scope.$parent.$id).toEqual(ngRepeatScope.$id);
expect(ngIf2Scope.$parent.$id).toEqual(ngRepeatScope.$id);
// What is happening here??
// We seem to have a repeater scope which doesn't actually match to any element
expect(ngRepeatScope.$parent.$id).toEqual($rootScope.$id);
// Now remove the first ngIf element from the first item in the repeater
$rootScope.$apply('val1 = false');
// At this point we should have:
//
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
//
// <!-- ngIf: val1 -->
//
// <!-- ngIf: val2 -->
// <div ng-repeat-end="" ng-if="val2" class="ng-scope"></div>
// <!-- end ngIf: val2 -->
//
// <!-- end ngRepeat: val in val0 -->
// </div>
//
expect(ngRepeatScope.$$destroyed).toEqual(false);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(false);
// Now remove the second ngIf element from the first item in the repeater
$rootScope.$apply('val2 = false');
// We are mostly back to where we started
//
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
// <!-- ngIf: val1 -->
// <!-- ngIf: val2 -->
// <!-- end ngRepeat: val in val0 -->
// </div>
expect(ngRepeatScope.$$destroyed).toEqual(false);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
// Finally remove the repeat items
$rootScope.$apply('val0 = []');
// Somehow this ngRepeat scope knows how to destroy itself...
expect(ngRepeatScope.$$destroyed).toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
}));
it('should throw error if unterminated', function () {
module(function($compileProvider) {
$compileProvider.directive('foo', function() {
return {
multiElement: true
};
});
});
inject(function($compile, $rootScope) {
expect(function() {
element = $compile(
'<div>' +
'<span foo-start></span>' +
'</div>');
}).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
});
});
it('should correctly collect ranges on multiple directives on a single element', function () {
module(function($compileProvider) {
$compileProvider.directive('emptyDirective', function() {
return {
multiElement: true,
link: function (scope, element) {
element.data('x', 'abc');
}
};
});
$compileProvider.directive('rangeDirective', function() {
return {
multiElement: true,
link: function (scope) {
scope.x = 'X';
scope.y = 'Y';
}
};
});
});
inject(function ($compile, $rootScope) {
element = $compile(
'<div>' +
'<div range-directive-start empty-directive>{{x}}</div>' +
'<div range-directive-end>{{y}}</div>' +
'</div>'
)($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('XY');
expect(angular.element(element[0].firstChild).data('x')).toBe('abc');
});
});
it('should throw error if unterminated (containing termination as a child)', function () {
module(function($compileProvider) {
$compileProvider.directive('foo', function() {
return {
multiElement: true
};
});
});
inject(function($compile) {
expect(function() {
element = $compile(
'<div>' +
'<span foo-start><span foo-end></span></span>' +
'</div>');
}).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found.");
});
});
it('should support data- and x- prefix', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span data-ng-show-start="show"></span>' +
'<span data-ng-show-end></span>' +
'<span x-ng-show-start="show"></span>' +
'<span x-ng-show-end></span>' +
'</div>')($rootScope);
$rootScope.$digest();
var spans = element.find('span');
expect(spans.eq(0)).toBeHidden();
expect(spans.eq(1)).toBeHidden();
expect(spans.eq(2)).toBeHidden();
expect(spans.eq(3)).toBeHidden();
}));
});
describe('$animate animation hooks', function() {
beforeEach(module('ngAnimateMock'));
it('should automatically fire the addClass and removeClass animation hooks',
inject(function($compile, $animate, $rootScope) {
var data, element = jqLite('<div class="{{val1}} {{val2}} fire"></div>');
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.hasClass('fire')).toBe(true);
$rootScope.val1 = 'ice';
$rootScope.val2 = 'rice';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('addClass');
expect(data.args[1]).toBe('ice rice');
expect(element.hasClass('ice')).toBe(true);
expect(element.hasClass('rice')).toBe(true);
expect(element.hasClass('fire')).toBe(true);
$rootScope.val2 = 'dice';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('setClass');
expect(data.args[1]).toBe('dice');
expect(data.args[2]).toBe('rice');
expect(element.hasClass('ice')).toBe(true);
expect(element.hasClass('dice')).toBe(true);
expect(element.hasClass('fire')).toBe(true);
$rootScope.val1 = '';
$rootScope.val2 = '';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('removeClass');
expect(data.args[1]).toBe('ice dice');
expect(element.hasClass('ice')).toBe(false);
expect(element.hasClass('dice')).toBe(false);
expect(element.hasClass('fire')).toBe(true);
}));
});
});
| shaozhengxing/angular.js | test/ng/compileSpec.js | JavaScript | mit | 219,821 |
//
//
//
const express = require('express');
const router = express.Router();
const randomstring = require('randomstring');
const Player = require('core/player');
router.get('/player/init', function(req, res, next) {
let random_name = "player_"
random_name += randomstring.generate({
length: 4,
charset: 'numeric'
});
let user = {
username: req.body.username || random_name
};
Player.add(user, function(err, player, exists) {
if (err) {
return next(err);
}
if (player) {
return res.json({
username: player.username,
uuid: player.uuid
});
}
res.status(409).json(exists);
})
});
module.exports = router;
| geeks-fight-club/geeks-games-core | server/http/json-ui/player_init.js | JavaScript | mit | 692 |
var searchData=
[
['vector3',['vector3',['../namespacerobotis__manipulator_1_1math.html#a057ca65131575b85aec169f3a50ed796',1,'robotis_manipulator::math']]],
['velocity',['velocity',['../structrobotis__manipulator_1_1_dynamicvector.html#a6bbccf8316887a8da3cd6aa065f3beac',1,'robotis_manipulator::Dynamicvector::velocity()'],['../structrobotis__manipulator_1_1_point.html#a4eaec95fac0c755eb0aa704b36ebe97b',1,'robotis_manipulator::Point::velocity()']]]
];
| ROBOTIS-GIT/emanual | docs/en/software/robotis_manipulator_libs/doxygen/html/search/all_12.js | JavaScript | mit | 458 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Answer Schema
*/
var AnswerSchema = new Schema({
content: {
type: String,
default: '',
required: 'Please fill Answer content',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
article_id: {
type: String,
default: '',
trim: true
}
});
mongoose.model('Answer', AnswerSchema);
| leonarther16th/eslhunter | app/models/answer.server.model.js | JavaScript | mit | 481 |
using System;
using System.Linq;
using System.Linq.Expressions;
using Marten.Linq;
namespace Marten.Testing.OtherAssembly.Bug1851
{
public class GenericOuter<TInOtherAssembly> where TInOtherAssembly : StoredObjectInOtherAssembly
{
public class FindByNameQuery: ICompiledQuery<TInOtherAssembly, string>
{
public string Name { get; set; } = string.Empty;
public Expression<Func<IMartenQueryable<TInOtherAssembly>, string>> QueryIs()
{
return q => q.Where(x => x.Name == Name).Select(x => x.Name).FirstOrDefault();
}
}
}
}
| mysticmind/marten | src/Marten.Testing.OtherAssembly/Bug1851/GenericOuter.cs | C# | mit | 625 |
import mongoose from 'mongoose';
const { Schema } = mongoose;
const typeSchema = new Schema({
name: String,
image: String,
date: {
type: Date,
default: Date.now(),
},
places: [
{
type: Schema.Types.ObjectId,
ref: 'Place',
},
],
});
const Type = mongoose.model('Type', typeSchema);
export default Type;
| AlexeyKorkoza/TestProjectAndNodeJS | backend/src/models/type.js | JavaScript | mit | 386 |
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
OnInit,
Output
} from '@angular/core';
@Component({
selector: 'playlist-cover',
styleUrls: ['./playlist-cover.scss'],
template: `
<div class="playlist-cover is-flex-row is-flex-valign">
<div class="cover-bg" [ngStyle]="{ 'background-image': 'url(' + thumbUrl + ')' }"></div>
<div class="btn btn-transparent playlist-thumbnail">
<img [src]="thumbUrl">
</div>
<div class="actions is-flex-2">
<button class="btn btn-lg ux-maker play-media bg-primary"
(click)="play.emit(playlist)" title="play playlist">
<icon name="play"></icon>
</button>
<button class="btn btn-lg ux-maker play-media bg-primary"
(click)="queue.emit(playlist)" title="queue playlist">
<icon name="share"></icon>
</button>
</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PlaylistCoverComponent implements OnInit {
@Input() playlist: GoogleApiYouTubePlaylistResource;
@Output() play = new EventEmitter<GoogleApiYouTubePlaylistResource>();
@Output() queue = new EventEmitter<GoogleApiYouTubePlaylistResource>();
constructor() {}
ngOnInit() {}
get title() {
return this.playlist && this.playlist.snippet
? this.playlist.snippet.title
: '...';
}
get total() {
return this.playlist && this.playlist.contentDetails
? this.playlist.contentDetails.itemCount
: '...';
}
get thumbUrl() {
const thumbnails = this.playlist && this.playlist.snippet.thumbnails;
const sizes = ['default', 'medium'];
return sizes.reduce(
(acc, size) => thumbnails.hasOwnProperty(size) && thumbnails[size].url,
''
);
}
}
| orizens/echoes-ng2 | src/app/shared/components/playlist-viewer/playlist-cover.component.ts | TypeScript | mit | 1,747 |
'use strict';
/**
* @ngdoc function
* @name tbsApp.controller:EidolonListCtrl
* @description
* # EidolonListCtrl
* Controller of the tbsApp
*/
angular.module('tbsApp').controller('EidolonListCtrl', function ($scope, $routeParams, $modal, REidolon, UserData) {
$scope.have_eidolon = UserData.get('have_eidolon', {});
$scope.job_level = UserData.get('eidolon_level', {});
$scope.characters = [];
REidolon.all(function(data){
var _char = null;
for(var i = 0; i < data.length; ++i){
_char = angular.copy(data[i]);
_char.max_job = parseInt(data[i].max_job);
$scope.characters.push(_char);
}
});
$scope.toggle = function(ref){
UserData.set('have_eidolon', $scope.have_eidolon);
};
$scope.job_change = function(ref){
UserData.set('eidolon_level', $scope.job_level);
};
});
| m-atthieu/tbs.desile.fr | front/scripts/controllers/eidolon-list.js | JavaScript | mit | 902 |
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('DeliveryOrders', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
number: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('DeliveryOrders');
}
}; | PinguinJantan/openPackTrack-backend | migrations/20171017155907-create-delivery-order.js | JavaScript | mit | 610 |
package yushijinhun.authlibagent.javaagent.tweaker;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import yushijinhun.authlibagent.javaagent.AuthlibAgent;
/**
* @author ustc_zzzz
*/
public class AuthlibClassTransformer implements IClassTransformer {
private final LaunchClassLoader classLoader = Launch.classLoader;
private final ClassFileTransformer transformer = AuthlibAgent.createTransformer();
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
if (name == null || bytes == null) return bytes;
try {
byte[] result = this.transformer.transform(this.classLoader, name.replace('.', '/'), null, null, bytes);
return result == null ? bytes : result;
} catch (IllegalClassFormatException e) {
throw new RuntimeException(e);
}
}
}
| to2mbn/authlib-agent | authlib-javaagent/src/main/java/yushijinhun/authlibagent/javaagent/tweaker/AuthlibClassTransformer.java | Java | mit | 1,062 |
class TimeZoneInput < Formtastic::Inputs::SelectInput
TIME_ZONES = [
["(GMT -12:00) Marshall Is.", "Marshall Is.", { class: "time-zone--12" }],
["(GMT -11:00) Midway Island", "Midway Island", { class: "time-zone-11" }],
["(GMT -10:00) Hawaii", "Hawaii", { class: "time-zone-10" }],
["(GMT -9:00) Alaska", "Alaska", { class: "time-zone-9" }],
["(GMT -8:00) Pacific Time (US & Canada)", "Pacific Time (US & Canada)", { class: "time-zone-8" }],
["(GMT -7:00) Mountain Time (US & Canada)", "Mountain Time (US & Canada)", { class: "time-zone-7" }],
["(GMT -6:00) Central Time (US & Canada)", "Central Time (US & Canada)", { class: "time-zone-6" }],
["(GMT -5:00) Eastern Time (US & Canada)", "Eastern Time (US & Canada)", { class: "time-zone-5" }],
["(GMT -4:00) Atlantic Time (Canada)", "Atlantic Time (Canada)", { class: "time-zone-4" }],
["(GMT -3:30) Newfoundland", "Newfoundland", { class: "time-zone-3.5" }],
["(GMT -3:00) Buenos Aires", "Buenos Aires", { class: "time-zone-3" }],
["(GMT -2:00) Mid-Atlantic", "Mid-Atlantic", { class: "time-zone-2" }],
["(GMT -9:00) Azores", "Azores", { class: "time-zone-1" }],
["(GMT) London", "London", { class: "time-zone0" }],
["(GMT +1:00) Brussels", "Brussels", { class: "time-zone1" }],
["(GMT +2:00) South Africa", "South Africa", { class: "time-zone2" }],
["(GMT +3:00) Baghdad", "Baghdad", { class: "time-zone3" }],
["(GMT +3:30) Tehran", "Tehran", { class: "time-zone3.5" }],
["(GMT +4:00) Abu Dhabi", "Abu Dhabi", { class: "time-zone4" }],
["(GMT +4:30) Kabul", "Kabul", { class: "time-zone4.5" }],
["(GMT +5:00) Ekaterinburg", "Ekaterinburg", { class: "time-zone5" }],
["(GMT +5:30) New Delhi", "New Delhi", { class: "time-zone5.5" }],
["(GMT +5:45) Kathmandu", "Kathmandu", { class: "time-zone5.75" }],
["(GMT +6:00) Almaty", "Almaty", { class: "time-zone6" }],
["(GMT +7:00) Bangkok", "Bangkok", { class: "time-zone7" }],
["(GMT +8:00) Beijing", "Beijing", { class: "time-zone8" }],
["(GMT +9:00) Tokyo", "Tokyo", { class: "time-zone9" }],
["(GMT +9:30) Adelaide", "Adelaide", { class: "time-zone9.5" }],
["(GMT +10:00) Guam", "Guam", { class: "time-zone10" }],
["(GMT +11:00) Magadan", "Magadan", { class: "time-zone11" }],
["(GMT +12:00) Auckland", "Auckland", { class: "time-zone12" }]
]
def collection
TIME_ZONES
end
def wrapper_html_options
super.merge(class: "select input time_zone")
end
end
| codelation/activeadmin_pro | app/inputs/time_zone_input.rb | Ruby | mit | 2,496 |
(function (window) {
var tooltips = {
autoscale: "Show all data (autoscale)",
selection: "Select data for export"
};
var axis = {
numberWidthUsingFormatter: function(elem, cx, cy, fontSizeInPixels, numberStr) {
var testSVG,
testText,
bbox,
width,
height,
node;
testSVG = elem.append("svg")
.attr("width", cx)
.attr("height", cy)
.attr("class", "graph");
testText = testSVG.append('g')
.append("text")
.attr("class", "axis")
.attr("x", -fontSizeInPixels/4 + "px")
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(numberStr);
node = testText.node();
// This code is sometimes called by tests that use d3's jsdom-based mock SVG DOm, which
// doesn't implement getBBox.
if (node.getBBox) {
bbox = testText.node().getBBox();
width = bbox.width;
height = bbox.height;
} else {
width = 0;
height = 0;
}
testSVG.remove();
return [width, height];
},
axisProcessDrag: function(dragstart, currentdrag, domain) {
var originExtent, maxDragIn,
newdomain = domain,
origin = 0,
axis1 = domain[0],
axis2 = domain[1],
extent = axis2 - axis1;
if (currentdrag !== 0) {
if ((axis1 >= 0) && (axis2 > axis1)) { // example: (20, 10, [0, 40]) => [0, 80]
origin = axis1;
originExtent = dragstart-origin;
maxDragIn = originExtent * 0.4 + origin;
if (currentdrag > maxDragIn) {
change = originExtent / (currentdrag-origin);
extent = axis2 - origin;
newdomain = [axis1, axis1 + (extent * change)];
}
} else if ((axis1 < 0) && (axis2 > 0)) { // example: (20, 10, [-40, 40]) => [-80, 80]
origin = 0; // (-0.4, -0.2, [-1.0, 0.4]) => [-1.0, 0.4]
originExtent = dragstart-origin;
maxDragIn = originExtent * 0.4 + origin;
if ((dragstart >= 0 && currentdrag > maxDragIn) || (dragstart < 0 && currentdrag < maxDragIn)) {
change = originExtent / (currentdrag-origin);
newdomain = [axis1 * change, axis2 * change];
}
} else if ((axis1 < 0) && (axis2 < 0)) { // example: (-60, -50, [-80, -40]) => [-120, -40]
origin = axis2;
originExtent = dragstart-origin;
maxDragIn = originExtent * 0.4 + origin;
if (currentdrag < maxDragIn) {
change = originExtent / (currentdrag-origin);
extent = axis1 - origin;
newdomain = [axis2 + (extent * change), axis2];
}
}
}
newdomain[0] = +newdomain[0].toPrecision(5);
newdomain[1] = +newdomain[1].toPrecision(5);
return newdomain;
}
};
function Graph(idOrElement, options, message, tabindex) {
var api = {}, // Public API object to be returned.
// D3 selection of the containing DOM element the graph is placed in
elem,
// Regular representation of containing DOM element the graph is placed in
node,
// JQuerified version of DOM element
$node,
// Size of containing DOM element
cx, cy,
// Calculated padding between edges of DOM container and interior plot area of graph.
padding,
// Object containing width and height in pixels of interior plot area of graph
size,
// D3 objects representing SVG elements/containers in graph
svg,
vis,
plot,
viewbox,
title,
xlabel,
ylabel,
selectedRulerX,
selectedRulerY,
// Strings used as tooltips when labels are visible but are truncated because
// they are too big to be rendered into the space the graph allocates
titleTooltip,
xlabelTooltip,
ylabelTooltip,
// Instantiated D3 scale functions
// currently either d3.scale.linear, d3.scale.log, or d3.scale.pow
xScale,
yScale,
// The approximate number of gridlines in the plot, passed to d3.scale.ticks() function
xTickCount,
yTickCount,
// Instantiated D3 line function: d3.svg.line()
line,
// numeric format functions wrapping the d3.format() functions
fx,
fy,
// Instantiated D3 numeric format functions: d3.format()
fx_d3,
fy_d3,
// Function for stroke styling of major and minor grid lines
gridStroke = function(d) { return d ? "#ccc" : "#666"; },
// Functions for translation of grid lines and associated numeric labels
tx = function(d) { return "translate(" + xScale(d) + ",0)"; },
ty = function(d) { return "translate(0," + yScale(d) + ")"; },
// Div created and placed with z-index above all other graph layers that holds
// graph action/mode buttons.
buttonLayer,
selectionButton,
// Div created and placed with z-index under all other graph layers
background,
// Optional string which can be displayed in background of interior plot area of graph.
notification,
// An array of strings holding 0 or more lines for the title of the graph
titles = [],
// D3 selection containing canvas
graphCanvas,
// HTML5 Canvas object containing just plotted lines
gcanvas,
gctx,
canvasFillStyle = "rgba(255,255,255, 0.0)",
// Function dynamically created when X axis domain shift is in progress
domainShift,
// Boolean indicating X axis domain shif is in progress
shiftingX = false,
// Easing function used during X axis domain shift
cubicEase = d3.ease('cubic'),
// These are used to implement fluid X axis domain shifting.
// This is used when plotting samples/points and extent of plotted
// data approach extent of X axis.
// Domain shifting can also occur when the current sample point is moved.
// This most often occurs when using a graph to examine data from a model
// and movingthe current sample point backwards and forwards in data that
// have already been collected.
// The style of the cursor when hovering over a sample.point marker.
// The cursor changes depending on the operations that can be performed.
markerCursorStyle,
// Metrics calculated to support layout of titles, axes as
// well as text and numeric labels for axes.
fontSizeInPixels,
halfFontSizeInPixels,
quarterFontSizeInPixels,
titleFontSizeInPixels,
axisFontSizeInPixels,
xlabelFontSizeInPixels,
ylabelFontSizeInPixels,
// Array objects containing width and height of X and Y axis labels
xlabelMetrics,
ylabelMetrics,
// Width of widest numeric labels on X and Y axes
xAxisNumberWidth,
yAxisNumberWidth,
// Height of numeric labels on X and Y axes
xAxisNumberHeight,
yAxisNumberHeight,
// Padding necessary for X and Y axis labels to leave enough room for numeric labels
xAxisVerticalPadding,
yAxisHorizontalPadding,
// Padding necessary between right side of interior plot and edge of graph so
// make room for numeric lanel on right edge of X axis.
xAxisLabelHorizontalPadding,
// Baselines calculated for positioning of X and Y axis labels.
xAxisLabelBaseline,
yAxisLabelBaseline,
// Thickness of draggable areas for rescaling axes, these surround numeric labels
xAxisDraggableHeight,
yAxisDraggableWidth,
// D3 SVG rects used to implement axis dragging
xAxisDraggable,
yAxisDraggable,
// Strings used as tooltips when numeric axis draggables are visible but responsive
// layout system has removed the axis labels because of small size of graph.
xAxisDraggableTooltip,
yAxisDraggableTooltip,
// Used to calculate styles for markers appearing on samples/points (normally circles)
markerRadius,
markerStrokeWidth,
// Stroke width used for lines in graph
lineWidth,
// Used to categorize size of graphs in responsive layout mode where
// certain graph chrome is removed when graph is rendered smaller.
sizeType = {
category: "medium",
value: 3,
icon: 120,
tiny: 240,
small: 480,
medium: 960,
large: 1920
},
// State variables indicating whether an axis drag operation is in place.
// NaN values are used to indicate operation not in progress and
// checked like this: if (!isNaN(downx)) { resacle operation in progress }
//
// When drag/rescale operation is occuring values contain plot
// coordinates of start of drag (0 is a valid value).
downx = NaN,
downy = NaN,
// State variable indicating whether a data point is being dragged.
// When data point drag operation is occuring value contain two element
// array wiith plot coordinates of drag position.
draggedPoint = null,
// When a data point is selected contains two element array wiith plot coordinates
// of selected data point.
selected = null,
// An array of data points in the plot which are near the cursor.
// Normally used to temporarily display data point markers when cursor
// is nearby when markAllDataPoints is disabled.
selectable = [],
// An array containing two-element arrays consisting of X and Y values for samples/points
points = [],
// An array containing 1 or more points arrays to be plotted.
pointArray,
// When additional dataseries are added to the graph via addPoints(datapoints)
// newDataSeries contains the number of series in dataPoints
// Each series is a separate stream of data consisting of [x, y] pairs.
// Additional static dataseries can be graphed along with the new series that
// are streaming in as samples by pushing extra series into the array of data
// setup with resetPoints().
newDataSeries,
// Index into points array for current sample/point.
// Normally references data point last added.
// Current sample can refer to earlier points. This is
// represented in the view by using a desaturated styling for
// plotted data after te currentSample.
currentSample,
// When graphing data samples as opposed to [x, y] data pairs contains
// the fixed time interval between subsequent samples.
sampleInterval,
// Normally data sent to graph as samples starts at an X value of 0
// A different starting x value can be set
dataSampleStart,
// The default options for a graph
default_options = {
// Enables the button layer with: AutoScale ...
showButtons: true,
// Responsive Layout provides pregressive removal of
// graph elements when size gets smaller
responsiveLayout: false,
// Font sizes for graphs are normally specified using ems.
// When fontScaleRelativeToParent to true the font-size of the
// containing element is set based on the size of the containing
// element. hs means whn the containing element is smaller the
// foint-size of the labels in thegraph will be smaller.
fontScaleRelativeToParent: true,
enableAutoScaleButton: true,
enableAxisScaling: true,
enableSelectionButton: false,
clearSelectionOnLeavingSelectMode: false,
//
// dataType can be either 'points or 'samples'
//
dataType: 'points',
//
// dataType: 'points'
//
// Arrays of two-element arrays of x, y data pairs, this is the internal
// format the graphers uses to represent data.
dataPoints: [],
//
// dataType: 'samples'
//
// An array of samples (or an array or arrays of samples)
dataSamples: [],
// The constant time interval between sample values
sampleInterval: 1,
// Normally data sent to graph as samples starts at an X value of 0
// A different starting x value can be set
dataSampleStart: 0,
// title can be a string or an array of strings, if an
// array of strings each element is on a separate line.
title: "graph",
// The labels for the axes, these are separate from the numeric labels.
xlabel: "x-axis",
ylabel: "y-axis",
// Initial extent of the X and Y axes.
xmax: 10,
xmin: 0,
ymax: 10,
ymin: 0,
// Approximate values for how many gridlines should appear on the axes.
xTickCount: 10,
yTickCount: 10,
// The formatter strings used to convert numbers into strings.
// see: https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format
xFormatter: ".3s",
yFormatter: ".3s",
// Scale type: options are:
// linear: https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-linear
// log: https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-log
// pow: https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-pow
xscale: 'linear',
yscale: 'linear',
// Used when scale type is set to "pow"
xscaleExponent: 0.5,
yscaleExponent: 0.5,
// How many samples/points over which a graph shift should take place
// when the data being plotted gets close to the edge of the X axis.
axisShift: 10,
// selectablePoints: false,
// true if data points should be marked ... currently marked with a circle.
markAllDataPoints: false,
// only show circles when hovering near them with the mouse or
// tapping near then on a tablet
markNearbyDataPoints: false,
// number of circles to show on each side of the central point
extraCirclesVisibleOnHover: 2,
// true to show dashed horizontal and vertical rulers when a circle is selected
showRulersOnSelection: false,
// width of the line used for plotting
lineWidth: 2.0,
// Enable values of data points to be changed by selecting and dragging.
dataChange: false,
// Enables adding of data to a graph by option/alt clicking in the graph.
addData: false,
// Set value to a string and it will be rendered in background of graph.
notification: false,
// Render lines between samples/points
lines: true,
// Render vertical bars extending up to samples/points
bars: false
},
// brush selection variables
selection_region = {
xmin: null,
xmax: null,
ymin: null,
ymax: null
},
has_selection = false,
selection_visible = false,
selection_enabled = true,
selection_listener,
brush_element,
brush_control;
// ------------------------------------------------------------
//
// Initialization
//
// ------------------------------------------------------------
function initialize(idOrElement, opts, mesg) {
if (opts || !options) {
options = setupOptions(opts);
}
initializeLayout(idOrElement, mesg);
options.xrange = options.xmax - options.xmin;
options.yrange = options.ymax - options.ymin;
if (Object.prototype.toString.call(options.title) === "[object Array]") {
titles = options.title;
} else {
titles = [options.title];
}
titles.reverse();
// use local variables for both access speed and for responsive over-riding
sampleInterval = options.sampleInterval;
dataSampleStart = options.dataSampleStart;
lineWidth = options.lineWidth;
size = {
"width": 120,
"height": 120
};
setupScales();
fx_d3 = d3.format(options.xFormatter);
fy_d3 = d3.format(options.yFormatter);
// Wrappers around certain d3 formatters to prevent problems like this:
// scale = d3.scale.linear().domain([-.7164, .7164])
// scale.ticks(10).map(d3.format('.3r'))
// => ["-0.600", "-0.400", "-0.200", "-0.0000000000000000888", "0.200", "0.400", "0.600"]
fx = function(num) {
var domain = xScale.domain(),
onePercent = Math.abs((domain[1] - domain[0])*0.01);
if (Math.abs(0+num) < onePercent) {
num = 0;
}
return fx_d3(num);
};
fy = function(num) {
var domain = yScale.domain(),
onePercent = Math.abs((domain[1] - domain[0])*0.01);
if (Math.abs(0+num) < onePercent) {
num = 0;
}
return fy_d3(num);
};
xTickCount = options.xTickCount;
yTickCount = options.yTickCount;
pointArray = [];
switch(options.dataType) {
case "fake":
points = fakeDataPoints();
pointArray = [points];
break;
case 'points':
resetDataPoints(options.dataPoints);
break;
case 'samples':
resetDataSamples(options.dataSamples, sampleInterval, dataSampleStart);
break;
}
selectable = [];
selected = null;
setCurrentSample(points.length);
}
function initializeLayout(idOrElement, mesg) {
if (idOrElement) {
// d3.select works both for element ID (e.g. "#grapher")
// and for DOM element.
elem = d3.select(idOrElement);
node = elem.node();
$node = $(node);
// cx = $node.width();
// cy = $node.height();
cx = elem.property("clientWidth");
cy = elem.property("clientHeight");
}
if (mesg) {
message = mesg;
}
if (svg !== undefined) {
svg.remove();
svg = undefined;
}
if (background !== undefined) {
background.remove();
background = undefined;
}
if (graphCanvas !== undefined) {
graphCanvas.remove();
graphCanvas = undefined;
}
if (options.dataChange) {
markerCursorStyle = "ns-resize";
} else {
markerCursorStyle = "crosshair";
}
scale();
// drag axis logic
downx = NaN;
downy = NaN;
draggedPoint = null;
}
function scale(w, h) {
if (!w && !h) {
cx = Math.max(elem.property("clientWidth"), 60);
cy = Math.max(elem.property("clientHeight"),60);
} else {
cx = w;
node.style.width = cx +"px";
if (!h) {
node.style.height = "100%";
h = elem.property("clientHeight");
cy = h;
node.style.height = cy +"px";
} else {
cy = h;
node.style.height = cy +"px";
}
}
calculateSizeType();
}
function calculateLayout(forceUpdate) {
scale();
fontSizeInPixels = parseFloat($node.css("font-size"));
if (!options.fontScaleRelativeToParent) {
$node.css("font-size", 0.5 + sizeType.value/6 + 'em');
}
fontSizeInPixels = parseFloat($node.css("font-size"));
halfFontSizeInPixels = fontSizeInPixels/2;
quarterFontSizeInPixels = fontSizeInPixels/4;
if (svg === undefined) {
titleFontSizeInPixels = fontSizeInPixels;
axisFontSizeInPixels = fontSizeInPixels;
xlabelFontSizeInPixels = fontSizeInPixels;
ylabelFontSizeInPixels = fontSizeInPixels;
} else {
titleFontSizeInPixels = parseFloat($("svg.graph text.title").css("font-size"));
axisFontSizeInPixels = parseFloat($("svg.graph text.axis").css("font-size"));
xlabelFontSizeInPixels = parseFloat($("svg.graph text.xlabel").css("font-size"));
ylabelFontSizeInPixels = parseFloat($("svg.graph text.ylabel").css("font-size"));
}
updateAxesAndSize();
updateScales();
line = d3.svg.line()
.x(function(d, i) { return xScale(points[i][0]); })
.y(function(d, i) { return yScale(points[i][1]); });
}
function setupOptions(options) {
if (options) {
for(var p in default_options) {
if (options[p] === undefined) {
options[p] = default_options[p];
}
}
} else {
options = default_options;
}
if (options.axisShift < 1) options.axisShift = 1;
return options;
}
function updateAxesAndSize() {
if (xScale === undefined) {
xlabelMetrics = [fontSizeInPixels, fontSizeInPixels];
ylabelMetrics = [fontSizeInPixels*2, fontSizeInPixels];
} else {
xlabelMetrics = axis.numberWidthUsingFormatter(elem, cx, cy, axisFontSizeInPixels,
longestNumber(xScale.ticks(xTickCount), fx));
ylabelMetrics = axis.numberWidthUsingFormatter(elem, cx, cy, axisFontSizeInPixels,
longestNumber(yScale.ticks(yTickCount), fy));
}
xAxisNumberWidth = xlabelMetrics[0];
xAxisNumberHeight = xlabelMetrics[1];
xAxisLabelHorizontalPadding = xAxisNumberWidth * 0.6;
xAxisDraggableHeight = xAxisNumberHeight * 1.1;
xAxisVerticalPadding = xAxisDraggableHeight + xAxisNumberHeight*1.3;
xAxisLabelBaseline = xAxisVerticalPadding-xAxisNumberHeight/3;
yAxisNumberWidth = ylabelMetrics[0];
yAxisNumberHeight = ylabelMetrics[1];
yAxisDraggableWidth = yAxisNumberWidth + xAxisNumberHeight/4;
yAxisHorizontalPadding = yAxisDraggableWidth + yAxisNumberHeight;
yAxisLabelBaseline = -(yAxisDraggableWidth+yAxisNumberHeight/4);
switch(sizeType.value) {
case 0: // icon
padding = {
"top": halfFontSizeInPixels,
"right": halfFontSizeInPixels,
"bottom": fontSizeInPixels,
"left": fontSizeInPixels
};
break;
case 1: // tiny
padding = {
"top": options.title ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
"right": halfFontSizeInPixels,
"bottom": fontSizeInPixels,
"left": fontSizeInPixels
};
break;
case 2: // small
padding = {
"top": options.title ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
"right": xAxisLabelHorizontalPadding,
"bottom": axisFontSizeInPixels*1.25,
"left": yAxisNumberWidth*1.25
};
xTickCount = Math.max(6, options.xTickCount/2);
yTickCount = Math.max(6, options.yTickCount/2);
break;
case 3: // medium
padding = {
"top": options.title ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
"right": xAxisLabelHorizontalPadding,
"bottom": options.xlabel ? xAxisVerticalPadding : axisFontSizeInPixels*1.25,
"left": options.ylabel ? yAxisHorizontalPadding : yAxisNumberWidth
};
break;
default: // large
padding = {
"top": options.title ? titleFontSizeInPixels*1.8 : fontSizeInPixels,
"right": xAxisLabelHorizontalPadding,
"bottom": options.xlabel ? xAxisVerticalPadding : axisFontSizeInPixels*1.25,
"left": options.ylabel ? yAxisHorizontalPadding : yAxisNumberWidth
};
break;
}
if (sizeType.value > 2 ) {
padding.top += (titles.length-1) * sizeType.value/3 * sizeType.value/3 * fontSizeInPixels;
} else {
titles = [titles[0]];
}
size.width = Math.max(cx - padding.left - padding.right, 60);
size.height = Math.max(cy - padding.top - padding.bottom, 60);
}
function calculateSizeType() {
if (options.responsiveLayout) {
if (cx <= sizeType.icon) {
sizeType.category = 'icon';
sizeType.value = 0;
} else if (cx <= sizeType.tiny) {
sizeType.category = 'tiny';
sizeType.value = 1;
} else if (cx <= sizeType.small) {
sizeType.category = 'small';
sizeType.value = 2;
} else if (cx <= sizeType.medium) {
sizeType.category = 'medium';
sizeType.value = 3;
} else {
sizeType.category = 'large';
sizeType.value = 4;
}
} else {
sizeType.category = 'large';
sizeType.value = 4;
}
}
function longestNumber(array, formatter, precision) {
var longest = 0,
index = 0,
str,
len,
i;
precision = precision || 5;
for (i = 0; i < array.length; i++) {
str = formatter(+array[i].toPrecision(precision));
str = str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
len = str.length;
if (len > longest) {
longest = len;
index = i;
}
}
return formatter(array[index]);
}
// Setup xScale, yScale, making sure that options.xmax/xmin/ymax/ymin always reflect changes to
// the relevant domains.
function setupScales() {
function domainObservingScale(scale, callback) {
var domain = scale.domain;
scale.domain = function(_) {
if (arguments.length) {
callback(_);
}
return domain.apply(scale, arguments);
};
return scale;
}
xScale = domainObservingScale(d3.scale[options.xscale](), function(_) {
options.xmin = _[0];
options.xmax = _[1];
});
yScale = domainObservingScale(d3.scale[options.yscale](), function(_) {
options.ymin = _[0];
options.ymax = _[1];
});
updateScales();
}
function updateScales() {
updateXScale();
updateYScale();
}
// Update the x-scale.
function updateXScale() {
xScale.domain([options.xmin, options.xmax])
.range([0, size.width]);
cancelDomainShift();
}
// Update the y-scale.
function updateYScale() {
yScale.domain([options.ymin, options.ymax])
.range([size.height, 0]);
}
function fakeDataPoints() {
var yrange2 = options.yrange / 2,
yrange4 = yrange2 / 2,
pnts;
options.datacount = size.width/30;
options.xtic = options.xrange / options.datacount;
options.ytic = options.yrange / options.datacount;
pnts = d3.range(options.datacount).map(function(i) {
return [i * options.xtic + options.xmin, options.ymin + yrange4 + Math.random() * yrange2 ];
});
return pnts;
}
function setCurrentSample(samplePoint) {
if (typeof samplePoint === "number") {
currentSample = samplePoint;
}
if (typeof currentSample !== "number") {
currentSample = points.length-1;
}
return currentSample;
}
// converts data samples into an array of points
function indexedData(samples, interval, start) {
var i = 0,
pnts = [];
interval = interval || 1;
start = start || 0;
for (i = 0; i < samples.length; i++) {
pnts.push([i * interval + start, samples[i]]);
}
return pnts;
}
//
// Update notification message
//
function notify(mesg) {
message = mesg;
if (mesg) {
notification.text(mesg);
} else {
notification.text('');
}
}
function createButtonLayer() {
buttonLayer = elem.append("div");
buttonLayer
.attr("class", "button-layer")
.style("z-index", 3);
if (options.enableAutoScaleButton) {
buttonLayer.append('a')
.attr({
"class": "autoscale-button",
"title": tooltips.autoscale
})
.on("click", function() {
autoscale();
})
.append("i")
.attr("class", "icon-picture");
}
if (options.enableSelectionButton) {
selectionButton = buttonLayer.append('a');
selectionButton.attr({
"class": "selection-button",
"title": tooltips.selection
})
.on("click", function() {
toggleSelection();
})
.append("i")
.attr("class", "icon-cut");
}
resizeButtonLayer();
}
function resizeButtonLayer() {
buttonLayer
.style({
"width": fontSizeInPixels*1.75 + "px",
"height": fontSizeInPixels*1.25 + "px",
"top": padding.top + halfFontSizeInPixels + "px",
"left": padding.left + (size.width - fontSizeInPixels*2.0) + "px"
});
}
// ------------------------------------------------------------
//
// Rendering
//
// ------------------------------------------------------------
//
// Render a new graph by creating the SVG and Canvas elements
//
function renderNewGraph() {
svg = elem.append("svg")
.attr("width", cx)
.attr("height", cy)
.attr("class", "graph")
.style('z-index', 2);
// .attr("tabindex", tabindex || 0);
vis = svg.append("g")
.attr("transform", "translate(" + padding.left + "," + padding.top + ")");
plot = vis.append("rect")
.attr("class", "plot")
.attr("width", size.width)
.attr("height", size.height)
.attr("pointer-events", "all")
.attr("fill", "rgba(255,255,255,0)")
.on("mousemove", plotMousemove)
.on("mousedown", plotDrag)
.on("touchstart", plotDrag);
plot.call(d3.behavior.zoom().x(xScale).y(yScale).on("zoom", redraw));
background = elem.append("div")
.attr("class", "background")
.style({
"width": size.width + "px",
"height": size.height + "px",
"top": padding.top + "px",
"left": padding.left + "px",
"z-index": 0
});
createGraphCanvas();
viewbox = vis.append("svg")
.attr("class", "viewbox")
.attr("top", 0)
.attr("left", 0)
.attr("width", size.width)
.attr("height", size.height)
.attr("viewBox", "0 0 "+size.width+" "+size.height);
selectedRulerX = viewbox.append("line")
.attr("stroke", gridStroke)
.attr("stroke-dasharray", "2,2")
.attr("y1", 0)
.attr("y2", size.height)
.attr("x1", function(d) { return selected === null ? 0 : selected[0]; } )
.attr("x2", function(d) { return selected === null ? 0 : selected[0]; } )
.attr("class", "ruler hidden");
selectedRulerY = viewbox.append("line")
.attr("stroke", gridStroke)
.attr("stroke-dasharray", "2,2")
.attr("x1", 0)
.attr("x2", size.width)
.attr("y1", function(d) { return selected === null ? 0 : selected[1]; } )
.attr("y2", function(d) { return selected === null ? 0 : selected[1]; } )
.attr("class", "ruler hidden");
yAxisDraggable = svg.append("rect")
.attr("class", "draggable-axis")
.attr("x", padding.left-yAxisDraggableWidth)
.attr("y", padding.top)
.attr("rx", yAxisNumberHeight/6)
.attr("width", yAxisDraggableWidth)
.attr("height", size.height)
.attr("pointer-events", "all")
.style("cursor", "row-resize")
.on("mousedown", yAxisDrag)
.on("touchstart", yAxisDrag);
yAxisDraggableTooltip = yAxisDraggable.append("title");
xAxisDraggable = svg.append("rect")
.attr("class", "draggable-axis")
.attr("x", padding.left)
.attr("y", size.height+padding.top)
.attr("rx", yAxisNumberHeight/6)
.attr("width", size.width)
.attr("height", xAxisDraggableHeight)
.attr("pointer-events", "all")
.style("cursor", "col-resize")
.on("mousedown", xAxisDrag)
.on("touchstart", xAxisDrag);
xAxisDraggableTooltip = xAxisDraggable.append("title");
if (sizeType.value <= 2 && options.ylabel) {
xAxisDraggableTooltip.text(options.xlabel);
}
if (sizeType.catefory && options.ylabel) {
yAxisDraggableTooltip.text(options.ylabel);
}
adjustAxisDraggableFill();
brush_element = viewbox.append("g")
.attr("class", "brush");
// add Chart Title
if (options.title && sizeType.value > 0) {
title = vis.selectAll("text")
.data(titles, function(d) { return d; });
title.enter().append("text")
.attr("class", "title")
.text(function(d) { return d; })
.attr("x", function(d) { return size.width/2 - Math.min(size.width, getComputedTextLength(this))/2; })
.attr("dy", function(d, i) { return -i * titleFontSizeInPixels - halfFontSizeInPixels + "px"; });
titleTooltip = title.append("title")
.text("");
} else if (options.title) {
titleTooltip = plot.append("title")
.text(options.title);
}
// Add the x-axis label
if (sizeType.value > 2) {
xlabel = vis.append("text")
.attr("class", "axis")
.attr("class", "xlabel")
.text(options.xlabel)
.attr("x", size.width/2)
.attr("y", size.height)
.attr("dy", xAxisLabelBaseline + "px")
.style("text-anchor","middle");
}
// add y-axis label
if (sizeType.value > 2) {
ylabel = vis.append("g").append("text")
.attr("class", "axis")
.attr("class", "ylabel")
.text( options.ylabel)
.style("text-anchor","middle")
.attr("transform","translate(" + yAxisLabelBaseline + " " + size.height/2+") rotate(-90)");
if (sizeType.category === "small") {
yAxisDraggable.append("title")
.text(options.ylabel);
}
}
d3.select(node)
.on("mousemove.drag", mousemove)
.on("touchmove.drag", mousemove)
.on("mouseup.drag", mouseup)
.on("touchend.drag", mouseup);
notification = vis.append("text")
.attr("class", "graph-notification")
.text(message)
.attr("x", size.width/2)
.attr("y", size.height/2)
.style("text-anchor","middle");
updateMarkers();
updateRulers();
}
//
// Repaint an existing graph by rescaling/updating the SVG and Canvas elements
//
function repaintExistingGraph() {
vis
.attr("width", cx)
.attr("height", cy)
.attr("transform", "translate(" + padding.left + "," + padding.top + ")");
plot
.attr("width", size.width)
.attr("height", size.height);
background
.style({
"width": size.width + "px",
"height": size.height + "px",
"top": padding.top + "px",
"left": padding.left + "px",
"z-index": 0
});
viewbox
.attr("top", 0)
.attr("left", 0)
.attr("width", size.width)
.attr("height", size.height)
.attr("viewBox", "0 0 "+size.width+" "+size.height);
yAxisDraggable
.attr("x", padding.left-yAxisDraggableWidth)
.attr("y", padding.top-yAxisNumberHeight/2)
.attr("width", yAxisDraggableWidth)
.attr("height", size.height+yAxisNumberHeight);
xAxisDraggable
.attr("x", padding.left)
.attr("y", size.height+padding.top)
.attr("width", size.width)
.attr("height", xAxisDraggableHeight);
adjustAxisDraggableFill();
if (options.title && sizeType.value > 0) {
title
.attr("x", function(d) { return size.width/2 - Math.min(size.width, getComputedTextLength(this))/2; })
.attr("dy", function(d, i) { return -i * titleFontSizeInPixels - halfFontSizeInPixels + "px"; });
titleTooltip
.text("");
} else if (options.title) {
titleTooltip
.text(options.title);
}
if (options.xlabel && sizeType.value > 2) {
xlabel
.attr("x", size.width/2)
.attr("y", size.height)
.attr("dy", xAxisLabelBaseline + "px");
xAxisDraggableTooltip
.text("");
} else {
xAxisDraggableTooltip
.text(options.xlabel);
}
if (options.ylabel && sizeType.value > 2) {
ylabel
.attr("transform","translate(" + yAxisLabelBaseline + " " + size.height/2+") rotate(-90)");
yAxisDraggableTooltip
.text("");
} else {
yAxisDraggableTooltip
.text(options.ylabel);
}
notification
.attr("x", size.width/2)
.attr("y", size.height/2);
vis.selectAll("g.x").remove();
vis.selectAll("g.y").remove();
if (has_selection && selection_visible) {
updateBrushElement();
}
updateMarkers();
updateRulers();
resizeCanvas();
}
function getComputedTextLength(el) {
if (el.getComputedTextLength) {
return el.getComputedTextLength();
} else {
return 100;
}
}
function adjustAxisDraggableFill() {
if (sizeType.value <= 1) {
xAxisDraggable
.style({
"fill": "rgba(196, 196, 196, 0.2)"
});
yAxisDraggable
.style({
"fill": "rgba(196, 196, 196, 0.2)"
});
} else {
xAxisDraggable
.style({
"fill": null
});
yAxisDraggable
.style({
"fill": null
});
}
}
//
// Redraw the plot and axes when plot is translated or axes are re-scaled
//
function redraw() {
updateAxesAndSize();
repaintExistingGraph();
// Regenerate x-ticks
var gx = vis.selectAll("g.x")
.data(xScale.ticks(xTickCount), String)
.attr("transform", tx);
var gxe = gx.enter().insert("g", "a")
.attr("class", "x")
.attr("transform", tx);
gxe.append("line")
.attr("stroke", gridStroke)
.attr("y1", 0)
.attr("y2", size.height);
if (sizeType.value > 1) {
gxe.append("text")
.attr("class", "axis")
.attr("y", size.height)
.attr("dy", axisFontSizeInPixels + "px")
.attr("text-anchor", "middle")
.text(fx)
.on("mouseover", function() { d3.select(this).style("font-weight", "bold");})
.on("mouseout", function() { d3.select(this).style("font-weight", "normal");});
}
gx.exit().remove();
// Regenerate y-ticks
var gy = vis.selectAll("g.y")
.data(yScale.ticks(yTickCount), String)
.attr("transform", ty);
var gye = gy.enter().insert("g", "a")
.attr("class", "y")
.attr("transform", ty)
.attr("background-fill", "#FFEEB6");
gye.append("line")
.attr("stroke", gridStroke)
.attr("x1", 0)
.attr("x2", size.width);
if (sizeType.value > 1) {
if (options.yscale === "log") {
var gye_length = gye[0].length;
if (gye_length > 100) {
gye = gye.filter(function(d) { return !!d.toString().match(/(\.[0]*|^)[1]/);});
} else if (gye_length > 50) {
gye = gye.filter(function(d) { return !!d.toString().match(/(\.[0]*|^)[12]/);});
} else {
gye = gye.filter(function(d) {
return !!d.toString().match(/(\.[0]*|^)[125]/);});
}
}
gye.append("text")
.attr("class", "axis")
.attr("x", -axisFontSizeInPixels/4 + "px")
.attr("dy", ".35em")
.attr("text-anchor", "end")
.style("cursor", "ns-resize")
.text(fy)
.on("mouseover", function() { d3.select(this).style("font-weight", "bold");})
.on("mouseout", function() { d3.select(this).style("font-weight", "normal");});
}
gy.exit().remove();
plot.call(d3.behavior.zoom().x(xScale).y(yScale).on("zoom", redraw));
update();
}
// ------------------------------------------------------------
//
// Rendering: Updating samples/data points in the plot
//
// ------------------------------------------------------------
//
// Update plotted data, optionally pass in new samplePoint
//
function update(samplePoint) {
setCurrentSample(samplePoint);
updateCanvasFromPoints(currentSample);
updateMarkers();
if (d3.event && d3.event.keyCode) {
d3.event.preventDefault();
d3.event.stopPropagation();
}
}
// samplePoint is optional argument
function updateOrRescale(samplePoint) {
setCurrentSample(samplePoint);
updateOrRescalePoints();
}
// samplePoint is optional argument
function updateOrRescalePoints(samplePoint) {
var domain = xScale.domain(),
xAxisStart = Math.round(domain[0]),
xAxisEnd = Math.round(domain[1]),
start = Math.max(0, xAxisStart),
xextent = domain[1] - domain[0],
shiftPoint = xextent * 0.95,
currentExtent;
setCurrentSample(samplePoint);
if (currentSample > 0) {
currentExtent = points[currentSample-1][0];
} else {
currentExtent = points[currentSample][0];
}
if (shiftingX) {
shiftingX = domainShift();
if (shiftingX) {
cancelAxisRescale();
redraw();
} else {
update(currentSample);
}
} else {
if (currentExtent > domain[0] + shiftPoint) {
domainShift = shiftXDomainRealTime(shiftPoint*0.9, options.axisShift);
shiftingX = domainShift();
redraw();
} else if ( currentExtent < domain[1] - shiftPoint && currentSample < points.length && xAxisStart > 0) {
domainShift = shiftXDomainRealTime(shiftPoint*0.9, options.axisShift, -1);
shiftingX = domainShift();
redraw();
} else if (currentExtent < domain[0]) {
domainShift = shiftXDomainRealTime(shiftPoint*0.1, 1, -1);
shiftingX = domainShift();
redraw();
} else {
update(currentSample);
}
}
}
function shiftXDomainRealTime(shift, steps, direction) {
var d0 = xScale.domain()[0],
d1 = xScale.domain()[1],
increment = 1/steps,
index = 0;
return function() {
var factor;
direction = direction || 1;
index += increment;
factor = shift * cubicEase(index);
if (direction > 0) {
xScale.domain([d0 + factor, d1 + factor]);
return xScale.domain()[0] < (d0 + shift);
} else {
xScale.domain([d0 - factor, d1 - factor]);
return xScale.domain()[0] > (d0 - shift);
}
};
}
function cancelDomainShift() {
shiftingX = false;
// effectively asserts that we don't call domainShift until a new domain shift is required
domainShift = null;
}
function cancelAxisRescale() {
if (!isNaN(downx)) {
downx = NaN;
}
if (!isNaN(downy)) {
downy = NaN;
}
}
function circleClasses(d) {
var cs = [];
if (d === selected) {
cs.push("selected");
}
if (cs.length === 0) {
return null;
} else {
return cs.join(" ");
}
}
function updateMarkerRadius() {
var d = xScale.domain(),
r = xScale.range();
markerRadius = (r[1] - r[0]) / ((d[1] - d[0]));
markerRadius = Math.min(Math.max(markerRadius, 4), 8);
markerStrokeWidth = markerRadius/3;
}
function updateMarkers() {
var marker,
markedPoints = null;
if (options.markAllDataPoints && sizeType.value > 1) {
markedPoints = points;
} else if (options.markNearbyDataPoints && sizeType.value > 1) {
markedPoints = selectable.slice(0);
if (selected !== null && markedPoints.indexOf(selected) === -1) {
markedPoints.push(selected);
}
}
if (markedPoints !== null) {
updateMarkerRadius();
marker = vis.select("svg").selectAll("circle").data(markedPoints);
marker.enter().append("circle")
.attr("class", circleClasses)
.attr("cx", function(d) { return xScale(d[0]); })
.attr("cy", function(d) { return yScale(d[1]); })
.attr("r", markerRadius)
.style("stroke-width", markerStrokeWidth)
.style("cursor", markerCursorStyle)
.on("mousedown.drag", dataPointDrag)
.on("touchstart.drag", dataPointDrag)
.append("title")
.text(function(d) { return "( " + fx(d[0]) + ", " + fy(d[1]) + " )"; });
marker
.attr("class", circleClasses)
.attr("cx", function(d) { return xScale(d[0]); })
.attr("cy", function(d) { return yScale(d[1]); })
.select("title")
.text(function(d) { return "( " + fx(d[0]) + ", " + fy(d[1]) + " )"; });
marker.exit().remove();
}
updateRulers();
}
function updateRulers() {
if (options.showRulersOnSelection && selected !== null) {
selectedRulerX
.attr("y1", 0)
.attr("y2", size.height)
.attr("x1", function(d) { return selected === null ? 0 : xScale(selected[0]); } )
.attr("x2", function(d) { return selected === null ? 0 : xScale(selected[0]); } )
.attr("class", function(d) { return "ruler" + (selected === null ? " hidden" : ""); } );
selectedRulerY
.attr("x1", 0)
.attr("x2", size.width)
.attr("y1", function(d) { return selected === null ? 0 : yScale(selected[1]); } )
.attr("y2", function(d) { return selected === null ? 0 : yScale(selected[1]); } )
.attr("class", function(d) { return "ruler" + (selected === null ? " hidden" : ""); } );
} else {
selectedRulerX.attr("class", "ruler hidden");
selectedRulerY.attr("class", "ruler hidden");
}
}
// ------------------------------------------------------------
//
// UI Interaction: Plot dragging and translation; Axis re-scaling
//
// ------------------------------------------------------------
function plotMousemove() {
if (options.markNearbyDataPoints) {
var mousePoint = d3.mouse(vis.node()),
translatedMousePointX = xScale.invert(Math.max(0, Math.min(size.width, mousePoint[0]))),
p,
idx, pMin, pMax,
i;
// highlight the central point, and also points to the left and right
// TODO Handle multiple data sets/lines
selectable = [];
for (i = 0; i < pointArray.length; i++) {
points = pointArray[i];
p = findClosestPointByX(translatedMousePointX, i);
if (p !== null) {
idx = points.indexOf(p);
pMin = idx - (options.extraCirclesVisibleOnHover);
pMax = idx + (options.extraCirclesVisibleOnHover + 1);
if (pMin < 0) { pMin = 0; }
if (pMax > points.length - 1) { pMax = points.length; }
selectable = selectable.concat(points.slice(pMin, pMax));
}
}
update();
}
}
function findClosestPointByX(x, line) {
if (typeof(line) === "undefined" || line === null) { line = 0; }
// binary search through points.
// This assumes points is sorted ascending by x value, which for realTime graphs is true.
points = pointArray[line];
if (points.length === 0) { return null; }
var min = 0,
max = points.length - 1,
mid, diff, p1, p2, p3;
while (min < max) {
mid = Math.floor((min + max)/2.0);
if (points[mid][0] < x) {
min = mid + 1;
} else {
max = mid;
}
}
// figure out which point is actually closest.
// we have to compare 3 points, to account for floating point rounding errors.
// if the mouse moves off the left edge of the graph, p1 may not exist.
// if the mouse moves off the right edge of the graph, p3 may not exist.
p1 = points[mid - 1];
p2 = points[mid];
p3 = points[mid + 1];
if (typeof(p1) !== "undefined" && Math.abs(p1[0] - x) <= Math.abs(p2[0] - x)) {
return p1;
} else if (typeof(p3) === "undefined" || Math.abs(p2[0] - x) <= Math.abs(p3[0] - x)) {
return p2;
} else {
return p3;
}
}
function plotDrag() {
if(options.enableAxisScaling) {
var p;
d3.event.preventDefault();
d3.select('body').style("cursor", "move");
if (d3.event.altKey) {
plot.style("cursor", "nesw-resize");
if (d3.event.shiftKey && options.addData) {
p = d3.mouse(vis.node());
var newpoint = [];
newpoint[0] = xScale.invert(Math.max(0, Math.min(size.width, p[0])));
newpoint[1] = yScale.invert(Math.max(0, Math.min(size.height, p[1])));
points.push(newpoint);
points.sort(function(a, b) {
if (a[0] < b[0]) { return -1; }
if (a[0] > b[0]) { return 1; }
return 0;
});
selected = newpoint;
update();
} else {
p = d3.mouse(vis.node());
downx = xScale.invert(p[0]);
downy = yScale.invert(p[1]);
draggedPoint = false;
d3.event.stopPropagation();
}
// d3.event.stopPropagation();
}
}
}
function falseFunction() {
return false;
}
function xAxisDrag() {
if(options.enableAxisScaling) {
node.focus();
document.onselectstart = falseFunction;
d3.event.preventDefault();
var p = d3.mouse(vis.node());
downx = xScale.invert(p[0]);
}
}
function yAxisDrag() {
if(options.enableAxisScaling) {
node.focus();
d3.event.preventDefault();
document.onselectstart = falseFunction;
var p = d3.mouse(vis.node());
downy = yScale.invert(p[1]);
}
}
function dataPointDrag(d) {
node.focus();
d3.event.preventDefault();
document.onselectstart = falseFunction;
if (selected === d) {
selected = draggedPoint = null;
} else {
selected = draggedPoint = d;
}
update();
}
function mousemove() {
var p = d3.mouse(vis.node()),
index,
px,
x,
nextPoint,
prevPoint,
minusHalf,
plusHalf;
// t = d3.event.changedTouches;
document.onselectstart = function() { return true; };
d3.event.preventDefault();
if (draggedPoint) {
if (options.dataChange) {
draggedPoint[1] = yScale.invert(Math.max(0, Math.min(size.height, p[1])));
} else {
index = points.indexOf(draggedPoint);
if (index && index < (points.length-1)) {
px = xScale.invert(p[0]);
x = draggedPoint[0];
nextPoint = points[index+1];
prevPoint = points[index-1];
minusHalf = x - (x - prevPoint[0])/2;
plusHalf = x + (nextPoint[0] - x)/2;
if (px < minusHalf) {
draggedPoint = prevPoint;
selected = draggedPoint;
} else if (px > plusHalf) {
draggedPoint = nextPoint;
selected = draggedPoint;
}
}
}
update();
}
if (!isNaN(downx)) {
d3.select('body').style("cursor", "col-resize");
plot.style("cursor", "col-resize");
if (shiftingX) {
xScale.domain(axis.axisProcessDrag(downx, xScale.invert(p[0]), xScale.domain()));
} else {
xScale.domain(axis.axisProcessDrag(downx, xScale.invert(p[0]), xScale.domain()));
}
updateMarkerRadius();
redraw();
d3.event.stopPropagation();
}
if (!isNaN(downy)) {
d3.select('body').style("cursor", "row-resize");
plot.style("cursor", "row-resize");
yScale.domain(axis.axisProcessDrag(downy, yScale.invert(p[1]), yScale.domain()));
redraw();
d3.event.stopPropagation();
}
}
function mouseup() {
d3.select('body').style("cursor", "auto");
plot.style("cursor", "auto");
document.onselectstart = function() { return true; };
if (!isNaN(downx)) {
redraw();
downx = NaN;
}
if (!isNaN(downy)) {
redraw();
downy = NaN;
}
draggedPoint = null;
}
//------------------------------------------------------
//
// Autoscale
//
// ------------------------------------------------------------
/**
If there are more than 1 data points, scale the x axis to contain all x values,
and scale the y axis so that the y values lie in the middle 80% of the visible y range.
Then nice() the x and y scales (which means that the x and y domains will likely expand
somewhat).
*/
function autoscale() {
var i,
j,
len,
point,
x,
y,
xmin = Infinity,
xmax = -Infinity,
ymin = Infinity,
ymax = -Infinity,
transform,
pow;
if (points.length < 2) return;
for (i = 0; i < pointArray.length; i++) {
points = pointArray[i];
for (j = 0, len = points.length; j < len; j++){
point = points[j];
x = point[0];
y = point[1];
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
if (y < ymin) ymin = y;
if (y > ymax) ymax = y;
}
}
// Like Math.pow but returns a value with the same sign as x: pow(-1, 0.5) -> -1
pow = function(x, exponent) {
return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
};
// convert ymin, ymax to a linear scale, and set 'transform' to the function that
// converts the new min, max to the relevant scale.
switch (options.yscale) {
case 'linear':
transform = function(x) { return x; };
break;
case 'log':
ymin = Math.log(ymin) / Math.log(10);
ymax = Math.log(ymax) / Math.log(10);
transform = function(x) { return Math.pow(10, x); };
break;
case 'pow':
ymin = pow(ymin, options.yscaleExponent);
ymax = pow(ymax, options.yscaleExponent);
transform = function(x) { return pow(x, 1/options.yscaleExponent); };
break;
}
xScale.domain([xmin, xmax]).nice();
yScale.domain([transform(ymin - 0.15*(ymax-ymin)), transform(ymax + 0.15*(ymax-ymin))]).nice();
redraw();
}
// ------------------------------------------------------------
//
// Brush Selection
//
// ------------------------------------------------------------
function toggleSelection() {
if (!selectionVisible()) {
// The graph model defaults to visible=false and enabled=true.
// Reset these so that this first click turns on selection correctly.
selectionEnabled(false);
selectionVisible(true);
}
if (!!selectionEnabled()) {
if (options.clearSelectionOnLeavingSelectMode || selectionDomain() === []) {
selectionDomain(null);
}
selectionEnabled(false);
} else {
if (selectionDomain() == null) {
selectionDomain([]);
}
selectionEnabled(true);
}
}
/**
Set or get the selection domain (i.e., the range of x values that are selected).
Valid domain specifiers:
null no current selection (selection is turned off)
[] a current selection exists but is empty (has_selection is true)
[x1, x2] the region between x1 and x2 is selected. Any data points between
x1 and x2 (inclusive) would be considered to be selected.
Default value is null.
*/
function selectionDomain(a) {
if (!arguments.length) {
if (!has_selection) {
return null;
}
if (selection_region.xmax === Infinity && selection_region.xmin === Infinity ) {
return [];
}
return [selection_region.xmin, selection_region.xmax];
}
// setter
if (a === null) {
has_selection = false;
}
else if (a.length === 0) {
has_selection = true;
selection_region.xmin = Infinity;
selection_region.xmax = Infinity;
}
else {
has_selection = true;
selection_region.xmin = a[0];
selection_region.xmax = a[1];
}
updateBrushElement();
if (selection_listener) {
selection_listener(selectionDomain());
}
return api;
}
/**
Get whether the graph currently has a selection region. Default value is false.
If true, it would be valid to filter the data points to return a subset within the selection
region, although this region may be empty!
If false the graph is not considered to have a selection region.
Note that even if has_selection is true, the selection region may not be currently shown,
and if shown, it may be empty.
*/
function hasSelection() {
return has_selection;
}
/**
Set or get the visibility of the selection region. Default value is false.
Has no effect if the graph does not currently have a selection region
(selection_domain is null).
If the selection_enabled property is true, the user will also be able to interact
with the selection region.
*/
function selectionVisible(val) {
if (!arguments.length) {
return selection_visible;
}
// setter
val = !!val;
if (selection_visible !== val) {
selection_visible = val;
updateBrushElement();
}
return api;
}
/**
Set or get whether user manipulation of the selection region should be enabled
when a selection region exists and is visible. Default value is true.
Setting the value to true has no effect unless the graph has a selection region
(selection_domain is non-null) and the region is visible (selection_visible is true).
However, the selection_enabled setting is honored whenever those properties are
subsequently updated.
Setting the value to false does not affect the visibility of the selection region,
and does not affect the ability to change the region by calling selectionDomain().
Note that graph panning and zooming are disabled while selection manipulation is enabled.
*/
function selectionEnabled(val) {
if (!arguments.length) {
return selection_enabled;
}
// setter
val = !!val;
if (selection_enabled !== val) {
selection_enabled = val;
if (selectionButton) {
if (val) {
selectionButton.attr("style", "color: #aa0000;");
} else {
selectionButton.attr("style", "");
}
}
updateBrushElement();
}
return api;
}
/**
Set or get the listener to be called when the selection_domain changes.
Both programatic and interactive updates of the selection region result in
notification of the listener.
The listener is called with the new selection_domain value in the first argument.
*/
function selectionListener(cb) {
if (!arguments.length) {
return selection_listener;
}
// setter
selection_listener = cb;
return api;
}
function brushListener() {
var extent;
if (selection_enabled) {
// Note there is a brush.empty() method, but it still reports true after the
// brush extent has been programatically updated.
extent = brush_control.extent();
selectionDomain( extent[0] !== extent[1] ? extent : [] );
}
}
function updateBrushElement() {
if (has_selection && selection_visible) {
brush_control = brush_control || d3.svg.brush()
.x(xScale)
.extent([selection_region.xmin || 0, selection_region.xmax || 0])
.on("brush", brushListener);
brush_element
.call(brush_control.extent([selection_region.xmin || 0, selection_region.xmax || 0]))
.style('display', 'inline')
.style('pointer-events', selection_enabled ? 'all' : 'none')
.selectAll("rect")
.attr("height", size.height);
} else {
brush_element.style('display', 'none');
}
}
// ------------------------------------------------------------
//
// Canvas-based plotting
//
// ------------------------------------------------------------
function createGraphCanvas() {
graphCanvas = elem.append("canvas");
gcanvas = graphCanvas.node();
resizeCanvas();
}
function resizeCanvas() {
graphCanvas
.attr("class", "overlay")
.style({
"position": "absolute",
"width": size.width + "px",
"height": size.height + "px",
"top": padding.top + "px",
"left": padding.left + "px",
"z-index": 1
});
gcanvas = graphCanvas.node();
gcanvas.width = size.width;
gcanvas.height = size.height;
gcanvas.top = padding.top;
gcanvas.left = padding.left;
setupCanvasContext();
updateCanvasFromPoints(currentSample);
}
function clearCanvas() {
if (gcanvas.getContext) {
gcanvas.width = gcanvas.width;
gctx.lineWidth = lineWidth;
gctx.fillStyle = canvasFillStyle;
gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
gctx.strokeStyle = "rgba(255,65,0, 1.0)";
}
}
function setupCanvasContext() {
if (gcanvas.getContext) {
gctx = gcanvas.getContext( '2d' );
gctx.globalCompositeOperation = "source-over";
gctx.lineWidth = lineWidth;
gctx.fillStyle = canvasFillStyle;
gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
gctx.strokeStyle = "rgba(255,65,0, 1.0)";
}
}
//
// Update Canvas plotted data from [x, y] data points
//
function updateCanvasFromPoints(samplePoint) {
var i, j, k,
dx,
px, py,
index,
yOrigin = yScale(0.00001),
lines = options.lines,
bars = options.bars,
twopi = 2 * Math.PI,
pointsLength,
numberOfLines = pointArray.length,
xAxisStart,
xAxisEnd,
pointStop,
start,
lengthX;
// hack for lack of canvas support in jsdom tests
if (typeof gcanvas.getContext === "undefined" ) { return; }
setCurrentSample(samplePoint);
clearCanvas();
gctx.fillRect(0, 0, gcanvas.width, gcanvas.height);
gctx.lineWidth = lineWidth;
xAxisStart = xScale.domain()[0];
xAxisEnd = xScale.domain()[1];
start = Math.max(0, xAxisStart);
if (lines) {
for (i = 0; i < numberOfLines; i++) {
points = pointArray[i];
pointsLength = points.length;
if (pointsLength === 0) { break; }
index = 0;
// find first point >= xAxisStart
for (j = 0; j < pointsLength; j++) {
if (points[j][0] >= xAxisStart) { break; }
index++;
}
if (index > 0) { --index; }
if (index >= pointsLength) { break; }
px = xScale(points[index][0]);
py = yScale(points[index][1]);
setStrokeColor(i);
gctx.beginPath();
gctx.moveTo(px, py);
dx = points[index][0];
index++;
if (i < newDataSeries) {
// plot all ... or until one point past xAxisEnd
// or until we reach currentSample
for (; index < samplePoint; index++) {
dx = points[index][0];
px = xScale(dx);
py = yScale(points[index][1]);
gctx.lineTo(px, py);
if (dx >= xAxisEnd) { break; }
}
gctx.stroke();
// now plot in a desaturated style all the rest of the points
// ... or until one point past xAxisEnd
if (index < pointsLength && dx < xAxisEnd) {
setStrokeColor(i, true);
gctx.lineWidth = lineWidth/2;
for (;index < pointsLength; index++) {
dx = points[index][0];
px = xScale(dx);
py = yScale(points[index][1]);
gctx.lineTo(px, py);
if (dx >= xAxisEnd) { break; }
}
gctx.stroke();
}
} else {
// else we are plotting older complete datasets
// plot all ... or until one point past xAxisEnd
setStrokeColor(0, true);
gctx.lineWidth = lineWidth/2;
// temporary hack ...
var previousPx = 0;
for (; index < pointsLength-1; index++) {
dx = points[index][0];
px = xScale(dx);
if (px < previousPx) { break; }
previousPx = px;
py = yScale(points[index][1]);
gctx.lineTo(px, py);
if (dx >= xAxisEnd) { break; }
}
gctx.stroke();
}
}
} else if (bars) {
for (i = 0; i < numberOfLines; i++) {
points = pointArray[i];
pointsLength = points.length;
setStrokeColor(i);
pointStop = samplePoint - 1;
for (index=start; index < pointStop; index++) {
px = xScale(points[index][0]);
py = yScale(points[index][1]);
if (py === 0) {
continue;
}
gctx.beginPath();
gctx.moveTo(px, yOrigin);
gctx.lineTo(px, py);
gctx.stroke();
}
pointStop = points.length-1;
if (index < pointStop) {
setStrokeColor(i, true);
for (;index < pointStop; index++) {
px = xScale(points[index][0]);
py = yScale(points[index][1]);
gctx.beginPath();
gctx.moveTo(px, yOrigin);
gctx.lineTo(px, py);
gctx.stroke();
}
}
}
} else {
for (i = 0; i < numberOfLines; i++) {
points = pointArray[i];
pointsLength = points.length;
index = 0;
// find first point >= xAxisStart
for (j = 0; j < pointsLength; j++) {
if (points[j][0] >= xAxisStart) { break; }
index++;
}
if (index > 0) { --index; }
if (index >= pointsLength) { break; }
px = xScale(points[index][0]);
py = yScale(points[index][1]);
setFillColor(i);
dx = points[index][0];
index++;
// plot all ... or until one point past xAxisEnd
// or until we reach currentSample
for (; index < samplePoint; index++) {
dx = points[index][0];
px = xScale(dx);
py = yScale(points[index][1]);
gctx.fillRect(px, py, lineWidth, lineWidth);
if (dx >= xAxisEnd) { break; }
}
// now plot in a desaturated style all the rest of the points
// ... or until one point past xAxisEnd
if (index < pointsLength && dx < xAxisEnd) {
setFillColor(i, true);
for (;index < pointsLength; index++) {
dx = points[index][0];
px = xScale(dx);
py = yScale(points[index][1]);
gctx.fillRect(px, py, lineWidth, lineWidth);
if (dx >= xAxisEnd) { break; }
}
}
}
}
}
function setStrokeColor(i, afterSamplePoint) {
var opacity = afterSamplePoint ? 0.5 : 1.0;
switch(i) {
case 0:
gctx.strokeStyle = "rgba(160,00,0," + opacity + ")";
break;
case 1:
gctx.strokeStyle = "rgba(44,160,0," + opacity + ")";
break;
case 2:
gctx.strokeStyle = "rgba(44,0,160," + opacity + ")";
break;
default:
gctx.strokeStyle = "rgba(44,0,160," + opacity + ")";
break;
}
}
function setFillColor(i, afterSamplePoint) {
var opacity = afterSamplePoint ? 0.4 : 1.0;
switch(i) {
case 0:
gctx.fillStyle = "rgba(160,00,0," + opacity + ")";
break;
case 1:
gctx.fillStyle = "rgba(44,160,0," + opacity + ")";
break;
case 2:
gctx.fillStyle = "rgba(44,0,160," + opacity + ")";
break;
default:
gctx.fillStyle = "rgba(44,0,160," + opacity + ")";
break;
}
}
// ------------------------------------------------------------
//
// Adding samples/data points
//
// ------------------------------------------------------------
// Add an array of points then update the graph.
function addPoints(datapoints) {
newDataSeries = datapoints.length;
addDataPoints(datapoints);
setCurrentSample(points.length);
updateOrRescale();
}
// Add an array of samples then update the graph.
function addSamples(datasamples) {
addDataSamples(datasamples);
setCurrentSample(points.length);
updateOrRescale();
}
// Add a point [x, y] by processing sample (Y value) synthesizing
// X value from sampleInterval and number of points
function addSample(sample) {
var index = points.length,
xvalue = (index + dataSampleStart) * sampleInterval,
point = [ xvalue, sample ];
points.push(point);
setCurrentSample(points.length);
updateOrRescale();
}
// Add a point [x, y] to points array
function addPoint(pnt) {
points.push(pnt);
setCurrentSample(points.length);
updateOrRescale();
}
// Add an array (or arrays) of points.
function addDataPoints(datapoints) {
if (Object.prototype.toString.call(datapoints[0]) === "[object Array]") {
for (var i = 0; i < datapoints.length; i++) {
points = pointArray[i];
points.push.apply(points, [datapoints[i]]);
pointArray[i] = points;
}
points = pointArray[0];
} else {
points.push.apply(points, datapoints);
pointArray = [points];
}
}
// Add an array of points by processing an array of samples (Y values)
// synthesizing the X value from sampleInterval interval and number of points.
function addDataSamples(datasamples) {
var start,
i;
if (Object.prototype.toString.call(datasamples[0]) === "[object Array]") {
for (i = 0; i < datasamples.length; i++) {
if (!pointArray[i]) { pointArray.push([]); }
points = pointArray[i];
start = points.length * sampleInterval;
points.push.apply(points, indexedData(datasamples[i], sampleInterval, start));
pointArray[i] = points;
}
points = pointArray[0];
} else {
for (i = 0; i < datasamples.length; i++) {
if (!pointArray[i]) { pointArray.push([]); }
start = pointArray[i].length * sampleInterval;
pointArray[i].push([start, datasamples[i]]);
}
}
}
function resetDataPoints(datapoints) {
function copy(array) {
var ret = [];
array.forEach(function(element) {
ret.push(element);
});
return ret;
}
pointArray = [];
if (!datapoints || datapoints.length === 0) {
points = [];
pointArray = [points];
} else if (Object.prototype.toString.call(datapoints[0]) === "[object Array]") {
for (var i = 0; i < datapoints.length; i++) {
pointArray.push(copy(datapoints[i]));
}
points = pointArray[0];
} else {
points = datapoints;
pointArray = [copy(points)];
}
setCurrentSample(points.length - 1);
cancelDomainShift();
}
function resetDataSamples(datasamples, interval, start) {
pointArray = [];
if (Object.prototype.toString.call(datasamples[0]) === "[object Array]") {
for (var i = 0; i < datasamples.length; i++) {
pointArray.push(indexedData(datasamples[i], interval, start));
}
points = pointArray[0];
} else {
points = indexedData(datasamples, interval, start);
pointArray = [points];
}
sampleInterval = interval;
dataSampleStart = start;
}
function resetSamples(datasamples) {
resetDataSamples(datasamples, sampleInterval, dataSampleStart);
}
function deletePoint(i) {
if (points.length) {
points.splice(i, 1);
if (currentSample >= points.length) {
currentSample = points.length-1;
}
}
}
// ------------------------------------------------------------
//
// Keyboard Handling
//
// ------------------------------------------------------------
function registerKeyboardHandler() {
svg.node().addEventListener("keydown", function (evt) {
if (!selected) return false;
if (evt.type === "keydown") {
switch (evt.keyCode) {
case 8: // backspace
case 46: // delete
if (options.dataChange) {
var i = points.indexOf(selected);
deletePoint(i);
selected = points.length ? points[i > 0 ? i - 1 : 0] : null;
update();
}
evt.preventDefault();
evt.stopPropagation();
break;
}
evt.preventDefault();
}
});
}
// ------------------------------------------------------------
//
// Graph attribute updaters
//
// ------------------------------------------------------------
// update the title
function updateTitle() {
if (options.title && title) {
title.text(options.title);
}
renderGraph();
}
// update the x-axis label
function updateXlabel() {
if (options.xlabel && xlabel) {
xlabel.text(options.xlabel);
}
renderGraph();
}
// update the y-axis label
function updateYlabel() {
if (options.ylabel && ylabel) {
ylabel.text(options.ylabel);
} else {
ylabel.style("display", "none");
}
renderGraph();
}
// ------------------------------------------------------------
//
// Main API functions ...
//
// ------------------------------------------------------------
function renderGraph() {
calculateLayout();
if (svg === undefined) {
renderNewGraph();
} else {
repaintExistingGraph();
}
if (options.showButtons) {
if (!buttonLayer) createButtonLayer();
resizeButtonLayer();
}
redraw();
}
function reset(idOrElement, options, message) {
if (arguments.length) {
initialize(idOrElement, options, message);
} else {
initialize();
}
renderGraph();
// and then render again using actual size of SVG text elements are
renderGraph();
redraw();
registerKeyboardHandler();
return api;
}
function resize(w, h) {
scale(w, h);
initializeLayout();
renderGraph();
redraw();
return api;
}
//
// Public API to instantiated Graph
//
api = {
update: update,
repaint: renderGraph,
reset: reset,
redraw: redraw,
resize: resize,
notify: notify,
// selection brush api
selectionDomain: selectionDomain,
selectionVisible: selectionVisible,
selectionListener: selectionListener,
selectionEnabled: selectionEnabled,
hasSelection: hasSelection,
/**
Read only getter for the d3 selection referencing the DOM elements containing the d3
brush used to implement selection region manipulation.
*/
brushElement: function() {
return brush_element;
},
/**
Read-only getter for the d3 brush control (d3.svg.brush() function) used to implement
selection region manipulation.
*/
brushControl: function() {
return brush_control;
},
/**
Read-only getter for the internal listener to the d3 'brush' event.
*/
brushListener: function() {
return brushListener;
},
// specific update functions ???
scale: scale,
updateOrRescale: updateOrRescale,
xDomain: function(_) {
if (!arguments.length) return [options.xmin, options.xmax];
options.xmin = _[0];
options.xmax = _[1];
if (updateXScale) {
updateXScale();
redraw();
}
return api;
},
yDomain: function(_) {
if (!arguments.length) return [options.ymin, options.ymax];
options.ymin = _[0];
options.ymax = _[1];
if (updateYScale) {
updateYScale();
redraw();
}
return api;
},
xmin: function(_) {
if (!arguments.length) return options.xmin;
options.xmin = _;
options.xrange = options.xmax - options.xmin;
if (updateXScale) {
updateXScale();
redraw();
}
return api;
},
xmax: function(_) {
if (!arguments.length) return options.xmax;
options.xmax = _;
options.xrange = options.xmax - options.xmin;
if (updateXScale) {
updateXScale();
redraw();
}
return api;
},
ymin: function(_) {
if (!arguments.length) return options.ymin;
options.ymin = _;
options.yrange = options.ymax - options.ymin;
if (updateYScale) {
updateYScale();
redraw();
}
return api;
},
ymax: function(_) {
if (!arguments.length) return options.ymax;
options.ymax = _;
options.yrange = options.ymax - options.ymin;
if (updateYScale) {
updateYScale();
redraw();
}
return api;
},
xLabel: function(_) {
if (!arguments.length) return options.xlabel;
options.xlabel = _;
updateXlabel();
return api;
},
yLabel: function(_) {
if (!arguments.length) return options.ylabel;
options.ylabel = _;
updateYlabel();
return api;
},
title: function(_) {
if (!arguments.length) return options.title;
options.title = _;
updateTitle();
return api;
},
width: function(_) {
if (!arguments.length) return size.width;
size.width = _;
return api;
},
height: function(_) {
if (!arguments.length) return size.height;
size.height = _;
return api;
},
elem: function(_) {
if (!arguments.length) return elem;
elem = d3.select(_);
graph(elem);
return api;
},
numberOfPoints: function() {
if (points) {
return points.length;
} else {
return false;
}
},
// Point data consist of an array (or arrays) of [x,y] arrays.
addPoints: addPoints,
addPoint: addPoint,
resetPoints: resetDataPoints,
// Sample data consists of an array (or an array or arrays) of samples.
// The interval between samples is assumed to have already been set
// by specifying options.sampleInterval when creating the graph.
addSamples: addSamples,
addSample: addSample,
resetSamples: resetSamples
};
// Initialization.
initialize(idOrElement, options, message);
if (node) {
renderGraph();
// Render again using actual size of SVG text elements.
renderGraph();
}
return api;
}
// Support node-style modules and AMD.
if (typeof module === "object" && module && typeof module.exports === "object") {
module.exports = Graph;
} else if (typeof define === "function" && define.amd) {
define(function () { return Graph; });
}
// If there is a window object, that at least has a document property,
// define Lab.grapher.Graph.
if (typeof window === "object" && typeof window.document === "object") {
window.Lab = window.Lab || {};
window.Lab.grapher = window.Lab.grapher || {};
window.Lab.grapher.Graph = Graph;
}
})(window);
| pjanik/lab-grapher | lab.grapher.js | JavaScript | mit | 82,458 |
#include <cstdio>
using namespace std;
bool adj[1001][1001];
int n, x, y, q[1001], f, b, cur, vis[1001];
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d%d", &x, &y);
adj[x][y]=1;
}
scanf("%d%d", &x, &y);
f=b=0;
q[++b]=x;
cur = x;
vis[x]=1;
while(f!=b){
cur=q[++f];
for(int i = 1; i<=1000; i++){
if(adj[cur][i]&&!vis[i]){
vis[i]=1;
q[++b]=i;
}
}
}
if(vis[y]) printf("Tangled\n");
else printf("Not Tangled\n");
return 0;
} | ruar18/competitive-programming | dmoj/mwc/15c4p4-dealing-with-knots.cpp | C++ | mit | 588 |
'use strict';
var mockGlobalAnalytics = {};
global.analytics = mockGlobalAnalytics;
module.exports = mockGlobalAnalytics;
| nice-fungal/analytics.js-core | test/support/global.ts | TypeScript | mit | 123 |
module Timetrap
module Config
extend self
PATH = ENV['TIMETRAP_CONFIG_FILE'] || File.join(ENV['HOME'], '.timetrap.yml')
# Application defaults.
#
# These are written to a config file by invoking:
# <code>
# t configure
# </code>
def defaults
{
# Path to the sqlite db
'database_file' => "#{ENV['HOME']}/.timetrap.db",
# Unit of time for rounding (-r) in seconds
'round_in_seconds' => 900,
# delimiter used when appending notes with `t edit --append`
'append_notes_delimiter' => ' ',
# an array of directories to search for user defined fomatter classes
'formatter_search_paths' => [
"#{ENV['HOME']}/.timetrap/formatters"
],
# formatter to use when display is invoked without a --format option
'default_formatter' => 'text',
# the auto_sheet to use
'auto_sheet' => 'dotfiles',
# an array of directories to search for user defined auto_sheet classes
'auto_sheet_search_paths' => [
"#{ENV['HOME']}/.timetrap/auto_sheets"
],
# the default command to when you run `t`. default to printing usage.
'default_command' => nil,
# only allow one running entry at a time.
# automatically check out of any running tasks when checking in.
'auto_checkout' => false,
# interactively prompt for a note if one isn't passed when checking in.
'require_note' => false,
# command to launch external editor (false if no external editor used)
'note_editor' => false,
# set day of the week when determining start of the week.
'week_start' => "Monday",
}
end
def [](key)
overrides = File.exist?(PATH) ? YAML.load(erb_render(File.read(PATH))) : {}
defaults.merge(overrides)[key]
rescue => e
warn "invalid config file"
warn e.message
defaults[key]
end
def erb_render(content)
ERB.new(content).result
end
def configure!
configs = if File.exist?(PATH)
defaults.merge(YAML.load_file(PATH))
else
defaults
end
File.open(PATH, 'w') do |fh|
fh.puts(configs.to_yaml)
end
end
end
end
| apeschar/timetrap | lib/timetrap/config.rb | Ruby | mit | 2,261 |
package cn.edu.gdut.zaoying.Option.series.funnel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MaxNumber {
double value() default 0;
} | zaoying/EChartsAnnotation | src/cn/edu/gdut/zaoying/Option/series/funnel/MaxNumber.java | Java | mit | 336 |
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
package com.iluwatar.facade;
import org.junit.jupiter.api.Test;
/**
* Application test
*/
public class AppTest {
@Test
public void test() {
App.main(new String[]{});
}
}
| zik43/java-design-patterns | facade/src/test/java/com/iluwatar/facade/AppTest.java | Java | mit | 1,329 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* GetMobileStatusRequestDetailsType
*
* @package PayPal
*/
class GetMobileStatusRequestDetailsType extends XSDSimpleType
{
/**
* Phone number for status inquiry
*/
var $Phone;
function GetMobileStatusRequestDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'Phone' =>
array (
'required' => true,
'type' => 'PhoneNumberType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getPhone()
{
return $this->Phone;
}
function setPhone($Phone, $charset = 'iso-8859-1')
{
$this->Phone = $Phone;
$this->_elements['Phone']['charset'] = $charset;
}
}
| AMSGWeblinks/prestaPaypalPlugin | sdk/lib/PayPal/Type/GetMobileStatusRequestDetailsType.php | PHP | mit | 1,019 |
package soko
import (
"fmt"
"net/url"
)
type Backend interface {
// Saves current configuration to a specific file
Save() error
// APIs to control backend metadata
// Gets value from key
Get(serverID string, key string) (string, error)
// Put value on the key
Put(serverID string, key string, value string) error
// Delete value on the key
Delete(serverID string, key string) error
// TODO: implement
// List(serverID string, prefix string) , returns all of values with serverID
// Search(key string) , retruns serverID
// Watch(serverID string, key string) , this blocks until change
// ...
}
func FindBackend(config *Config) (Backend, error) {
switch config.Backend {
case "":
// Defaults to return consul default backend
return NewConsulBackend("", false)
case "consul", "consuls":
c := config.SectionConfig
u, err := url.Parse(c["url"])
if err != nil {
return nil, err
}
ssl := (u.Scheme == "https") || (config.Backend == "consuls")
return NewConsulBackend(u.Host, ssl)
case "openstack":
return NewOpenStackBackend(config.SectionConfig)
case "aws":
return NewAWSBackend(config.SectionConfig)
default:
return nil, fmt.Errorf("Unsupported backend: %s", config.Backend)
}
}
| udzura/metama | backend.go | GO | mit | 1,231 |
namespace Wexflow.Core.Db.Oracle
{
public class Notification : Core.Db.Notification
{
public static readonly string ColumnName_Id = "ID";
public static readonly string ColumnName_AssignedBy = "ASSIGNED_BY";
public static readonly string ColumnName_AssignedOn = "ASSIGNED_ON";
public static readonly string ColumnName_AssignedTo = "ASSIGNED_TO";
public static readonly string ColumnName_Message = "MESSAGE";
public static readonly string ColumnName_IsRead = "IS_READ";
public static readonly string TableStruct = "(" + ColumnName_Id + " NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "
+ ColumnName_AssignedBy + " INTEGER, "
+ ColumnName_AssignedOn + " TIMESTAMP, "
+ ColumnName_AssignedTo + " INTEGER, "
+ ColumnName_Message + " VARCHAR2(4000), "
+ ColumnName_IsRead + " NUMBER(1))";
public long Id { get; set; }
public override string GetDbId()
{
return Id.ToString();
}
}
}
| aelassas/Wexflow | src/netcore/Wexflow.Core.Db.Oracle/Notification.cs | C# | mit | 1,280 |
#--
# Copyright (c) 2005-2013, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
#
# Made in Japan.
#++
module Ruote::Exp
#
# A few helper methods for evaluating :if and :unless expression
# attributes in process definitions.
#
module Condition
#
# A runtime error for unusable comparison strings.
#
class ConditionError < RuntimeError
def initialize(code)
super(
"couldn't interpret >#{code}<, " +
"if it comes from a ${xx} construct, please use ${\"xx} or ${'yy}")
end
end
REGEXES = {
'evl_set' => /^(.+?)( +is)?( +not)?( +set)$/,
'evl_null' => /^(.+?)( +is)?( +not)?( +null)$/,
'evl_empty' => /^(.+[\]}"'])( +is)?( +not)?( +empty)$/,
'evl_in' => /^(.+?)( +is)?( +not)?( +in +)(\[.*\]|\{.*\})$/
}
def self.apply?(sif, sunless)
return (true?(sif)) if sif != nil
return ( ! true?(sunless)) if sunless != nil
true
end
# Returns true if the given conditional string evaluates to true.
#
def self.true?(conditional)
conditional = unescape(conditional.to_s)
REGEXES.each do |method, regex|
m = regex.match(conditional)
return self.send(method, m) if m
end
evl(conditional) ? true : false
rescue ArgumentError => ae
raise ConditionError.new(conditional)
end
# Returns true if the given conditional string evaluates to false.
#
def self.false?(conditional)
( ! true?(conditional))
end
# Evaluates the given [conditional] code string and returns the
# result.
#
# Note : this is not a full Ruby evaluation !
#
def self.eval(code)
evl(code)
rescue ArgumentError => ae
raise ConditionError.new(code)
end
protected # somehow
def self.parse(conditional)
Ruote.parse_ruby(conditional)
rescue SyntaxError => se
split_comparison(conditional)
rescue => e
[ :false ]
end
COMPREGEXES = %w[ == != ].collect { |c| /^ *(.+?) *(#{c}) *(.+) *$/ }
# try harder if it's comparison (== or !=)
#
def self.split_comparison(conditional)
COMPREGEXES.each do |r|
m = r.match(conditional)
next unless m
return [
:call, [ :str, m[1] ], m[2].to_sym, [ :arglist, [ :str, m[3] ] ] ]
end
[ :str, conditional ]
end
def self.unescape(s)
s.gsub('&', '&').gsub('>', '>').gsub('<', '<')
end
COMPARATORS = %w[ == > < != >= <= ].collect { |c| c.to_sym }
def self.evl(tree)
return evl(parse(tree)) if tree.is_a?(String)
return nil if tree == []
return tree.last if tree.first == :str
return tree.last if tree.first == :lit
return tree.last.to_s if tree.first == :const
return nil if tree == [ :nil ]
return true if tree == [ :true ]
return false if tree == [ :false ]
return ( ! evl(tree.last)) if tree.first == :not
return evl(tree[1]) && evl(tree[2]) if tree[0] == :and
return evl(tree[1]) || evl(tree[2]) if tree[0] == :or
return tree[1..-1].collect { |e| evl(e) } if tree[0] == :array
return Hash.[](*tree[1..-1].collect { |e| evl(e) }) if tree[0] == :hash
if tree[0] == :match3
return evl(tree[2]) =~ evl(tree[1])
end
if tree[0] == :call && tree[2] == :=~
return evl(tree[1]) =~ Regexp.new(evl(tree.last.last).to_s)
end
if tree[0] == :call && COMPARATORS.include?(tree[2])
return evl(tree[1]).send(tree[2], evl(tree.last.last))
end
if (c = flatten_and_compare(tree)) != nil
return c
end
if tree[0] == :call
return flatten(tree)
end
raise ArgumentError
# TODO : consider returning false
#require 'ruby2ruby'
#Ruby2Ruby.new.process(Sexp.from_array(tree))
# returns the raw Ruby as a String
# it's nice but "Loan/Grant" becomes "(Loan / Grant)"
end
def self.flatten_and_compare(tree)
ftree = tree.flatten
comparator = (ftree & COMPARATORS).first
return nil unless comparator
icomparator = ftree.index(comparator)
left = ftree[0..icomparator - 1]
right = ftree[icomparator + 1..-1]
evl("#{flatten(left).inspect} #{comparator} #{flatten(right).inspect}")
end
KEYWORDS = %w[ call const arglist str ].collect { |w| w.to_sym }
def self.flatten(tree)
(tree.flatten - KEYWORDS).collect { |e| e.nil? ? ' ' : e.to_s }.join.strip
end
def self.evl_set(match)
set = evl(match[1])
set = set != nil && set != ''
set = false if match[1].match(/is$/) && match[2].nil?
match[3].nil? ? set : ( ! set)
end
def self.evl_empty(match)
object = evl(match[1])
empty = if object.respond_to?(:empty?)
object.empty?
elsif object.nil?
true
else
false
end
( ! match[3].nil? ^ empty)
end
def self.evl_null(match)
( ! match[3].nil? ^ evl(match[1]).nil?)
end
def self.evl_in(match)
( ! match[3].nil? ^ evl(match[5]).include?(evl(match[1]))) rescue false
end
end
end
| ConsultingMD/ruote | lib/ruote/exp/condition.rb | Ruby | mit | 6,229 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using MultipartFormDataSample.Server.Models;
namespace MultipartFormDataSample.Server.Controllers
{
public class SendApiController : ApiController
{
[Route("api/send")]
public string UploadImageSet(ImageSet model)
{
var sb = new StringBuilder();
sb.AppendFormat("Received image set {0}: ", model.Name);
model.Images.ForEach(i =>
sb.AppendFormat("Got image {0} of type {1} and size {2} bytes,", i.FileName, i.MimeType,
i.ImageData.Length)
);
var result = sb.ToString();
Trace.Write(result);
return result;
}
}
}
| marcinbudny/MultipartFormDataSample | Server/MultipartFormDataSample.Server/MultipartFormDataSample.Server/Controllers/SendApiController.cs | C# | mit | 923 |
package org.devgateway.ocds.web.rest.controller;
import org.devgateway.ocds.persistence.mongo.Address;
import org.devgateway.ocds.persistence.mongo.ContactPoint;
import org.devgateway.ocds.persistence.mongo.Identifier;
import org.devgateway.ocds.persistence.mongo.Organization;
import org.devgateway.ocds.persistence.mongo.repository.main.OrganizationRepository;
import org.devgateway.ocds.web.rest.controller.request.OrganizationSearchRequest;
import org.devgateway.ocds.web.rest.controller.selector.BuyerSearchController;
import org.devgateway.ocds.web.rest.controller.selector.OrganizationSearchController;
import org.devgateway.ocds.web.rest.controller.selector.ProcuringEntitySearchController;
import org.devgateway.ocds.web.rest.controller.selector.SupplierSearchController;
import org.devgateway.toolkit.web.AbstractWebTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
public class OrganizationEndpointsTest extends AbstractWebTest {
@Autowired
private OrganizationSearchController organizationSearchController;
@Autowired
private ProcuringEntitySearchController procuringEntitySearchController;
@Autowired
private BuyerSearchController buyerSearchController;
@Autowired
private SupplierSearchController supplierSearchController;
@Autowired
private OrganizationRepository organizationRepository;
private static final String ORG_ID = "1234";
@Before
public void importTestData() throws IOException, InterruptedException {
organizationRepository.deleteAll();
final Organization organization = new Organization();
organization.setName("Development Gateway");
organization.setId(ORG_ID);
final Address address = new Address();
address.setCountryName("Romania");
address.setLocality("Bucuresti");
address.setPostalCode("022671");
address.setRegion("Bucuresti");
address.setStreetAddress("7 Sos. Iancului");
organization.setAddress(address);
final ContactPoint contactPoint = new ContactPoint();
contactPoint.setEmail("mpostelnicu@developmentgateway.org");
contactPoint.setFaxNumber("01234567");
contactPoint.setTelephone("01234567");
try {
contactPoint.setUrl(new URI("http://developmentgateway.org"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
organization.setContactPoint(contactPoint);
final Identifier identifier = new Identifier();
identifier.setId(ORG_ID);
organization.getAdditionalIdentifiers().add(identifier);
organization.getRoles().add(Organization.OrganizationType.procuringEntity.toString());
organization.getRoles().add(Organization.OrganizationType.buyer.toString());
final Organization savedOrganization = organizationRepository.save(organization);
Assert.assertNotNull(savedOrganization);
Assert.assertEquals(ORG_ID, savedOrganization.getId());
}
@Test
public void testOrganizationIdEndpoint() {
final Organization organizationId = organizationSearchController.byId(ORG_ID);
Assert.assertNotNull(organizationId);
}
@Test
public void testOrganizationSearchText() {
final OrganizationSearchRequest osr = new OrganizationSearchRequest();
osr.setText("Development");
final List<Organization> organizations = organizationSearchController.searchText(osr);
Assert.assertEquals(1, organizations.size(), 0);
}
@Test
public void testProcuringEntityIdEndpoint() {
final Organization organizationId = procuringEntitySearchController.byId(ORG_ID);
Assert.assertNotNull(organizationId);
}
@Test
public void testProcuringEntitySearchText() {
final OrganizationSearchRequest osr = new OrganizationSearchRequest();
osr.setText("Development");
final List<Organization> organizations = procuringEntitySearchController.searchText(osr);
Assert.assertEquals(1, organizations.size(), 0);
}
@Test
public void testBuyerIdEndpoint() {
final Organization organizationId = buyerSearchController.byId(ORG_ID);
Assert.assertNotNull(organizationId);
}
@Test
public void testBuyerSearchText() {
final OrganizationSearchRequest osr = new OrganizationSearchRequest();
osr.setText("Development");
final List<Organization> organizations = buyerSearchController.searchText(osr);
Assert.assertEquals(1, organizations.size(), 0);
}
@Test
public void testSupplierIdEndpoint() {
final Organization organizationId = supplierSearchController.byId(ORG_ID);
Assert.assertNull(organizationId);
}
@Test
public void testSupplierSaerchText() {
final OrganizationSearchRequest osr = new OrganizationSearchRequest();
osr.setText("Development");
final List<Organization> organizations = supplierSearchController.searchText(osr);
Assert.assertEquals(0, organizations.size(), 0);
}
} | devgateway/ocua | web/src/test/java/org/devgateway/ocds/web/rest/controller/OrganizationEndpointsTest.java | Java | mit | 5,272 |
/*
This file was generated by Dashcode.
You may edit this file to customize your widget or web page
according to the license.txt file included in the project.
*/
//
// Function: load()
// Called by HTML body element's onload event when the widget is ready to start
//
function load()
{
dashcode.setupParts();
}
//
// Function: remove()
// Called when the widget has been removed from the Dashboard
//
function remove()
{
// Stop any timers to prevent CPU usage
// Remove any preferences as needed
// widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey("your-key"));
}
//
// Function: hide()
// Called when the widget has been hidden
//
function hide()
{
// Stop any timers to prevent CPU usage
}
//
// Function: show()
// Called when the widget has been shown
//
function show()
{
// Restart any timers that were stopped on hide
}
//
// Function: sync()
// Called when the widget has been synchronized with .Mac
//
function sync()
{
// Retrieve any preference values that you need to be synchronized here
// Use this for an instance key's value:
// instancePreferenceValue = widget.preferenceForKey(null, dashcode.createInstancePreferenceKey("your-key"));
//
// Or this for global key's value:
// globalPreferenceValue = widget.preferenceForKey(null, "your-key");
}
//
// Function: showBack(event)
// Called when the info button is clicked to show the back of the widget
//
// event: onClick event from the info button
//
function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
//
// Function: showFront(event)
// Called when the done button is clicked from the back of the widget
//
// event: onClick event from the done button
//
function showFront(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToFront");
}
front.style.display="block";
back.style.display="none";
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
if (window.widget) {
widget.onremove = remove;
widget.onhide = hide;
widget.onshow = show;
widget.onsync = sync;
}
| sandalsoft/Bitcoin.dcproj | project/widget.wdgt/main.js | JavaScript | mit | 2,509 |
<?php
/**
* Spoon Library
*
* This source file is part of the Spoon Library. More information,
* documentation and tutorials can be found @ http://www.spoon-library.com
*
* @package spoon
* @subpackage datagrid
*
*
* @author Davy Hellemans <davy@spoon-library.com>
* @since 1.0.0
*/
/**
* This class is the base class used to generate datagrids from a range of sources.
*
* @package spoon
* @subpackage datagrid
*
*
* @author Davy Hellemans <davy@spoon-library.com>
* @since 1.0.0
*/
class SpoonDataGrid
{
/**
* List of columns that may be sorted in, based on the query results
*
* @var array
*/
private $allowedSortingColumns = array();
/**
* Html attributes
*
* @var array
*/
private $attributes = array('datagrid' => array(),
'row' => array(),
'row_even' => array(),
'row_odd' => array(),
'footer' => array());
/**
* Table caption/description
*
* @var string
*/
private $caption;
/**
* Array of column functions
*
* @var array
*/
private $columnFunctions = array();
/**
* Array of column objects
*
* @var array
*/
protected $columns = array();
/**
* Default compile directory
*
* @var string
*/
private $compileDirectory;
/**
* Final output
*
* @var string
*/
private $content;
/**
* Debug status
*
* @var bool
*/
private $debug = false;
/**
* Offset start value
*
* @var int
*/
private $offsetParameter;
/**
* Order start value
*
* @var string
*/
private $orderParameter;
/**
* Separate results with pages
*
* @var bool
*/
private $paging = true;
/**
* Default number of results per page
*
* @var int
*/
private $pagingLimit = 30;
/**
* Class used to define paging
*
* @var SpoonDataGridPaging
*/
private $pagingClass = 'SpoonDataGridPaging';
/**
* Parse status
*
* @var bool
*/
private $parsed = false;
/**
* List of row functions
*
* @var array
*/
private $rowFunctions = array();
/**
* Temporary output of the parsed row functions
*
* @var string
*/
private $rowFunctionsParsed = array();
/**
* Default sorting column
*
* @var string
*/
private $sortingColumn;
/**
* Sorting columns (cached when requested)
*
* @var array
*/
private $sortingColumns = array();
/**
* Sorting icons
*
* @var array
*/
private $sortingIcons = array( 'asc' => null,
'ascSelected' => null,
'desc' => null,
'descSelected' => null);
/**
* Sorting Labels
*
* @var array
*/
private $sortingLabels = array( 'asc' => 'Sort ascending',
'ascSelected' => 'Sorted ascending',
'desc' => 'Sort descending',
'descSelected' => 'Sorted descending');
/**
* Default sorting method
*
* @var string
*/
private $sortParameter;
/**
* Source of the datagrid
*
* @var SpoonDataGridSource
*/
protected $source;
/**
* DataGrid summary
*
* @var string
*/
private $summary;
/**
* Default or custom template
*
* @var string
*/
private $template;
/**
* Template instance
*
* @var SpoonTemplate
*/
protected $tpl;
/**
* Basic URL
*
* @var string
*/
private $URL;
/**
* Class constructor.
*
* @param SpoonDatagridSource $source The data-source, which needs to extend from SpoonDatagridSource.
* @param string[optional] $template The template that will be used to parse the datagrid.
*/
public function __construct(SpoonDatagridSource $source, $template = null)
{
// set source
$this->setSource($source);
// set template
if($template !== null) $this->setTemplate($template);
// load template
$this->tpl = new SpoonTemplate();
// create default columns
$this->createColumns();
}
/**
* Adds a new column with a couple of options such as title, URL, image, ...
*
* @param string $name The name for this column, later used to refer to this column.
* @param string[optional] $label The label that will be displayed in the header cell.
* @param string[optional] $value The value you wish to display.
* @param string[optional] $URL The URL to refer to.
* @param string[optional] $title The title tag, in case you've provided a URL.
* @param string[optional] $image The location to an image, used to fill the column.
* @param int[optional] $sequence The sequence for this column, by default it will be added at the back.
*/
public function addColumn($name, $label = null, $value = null, $URL = null, $title = null, $image = null, $sequence = null)
{
// redefine name
$name = (string) $name;
// column already exists
if(isset($this->columns[$name])) throw new SpoonDatagridException('A column with the name "' . $name . '" already exists.');
// redefine sequence
if($sequence === null) $sequence = count($this->columns) + 1;
// new column
$this->columns[$name] = new SpoonDatagridColumn($name, $label, $value, $URL, $title, $image, $sequence);
// add the class as an attribute to this column
$this->columns[$name]->setAttributes(array('class' => $name));
}
/**
* Builds the requested URL.
*
* @return string
* @param int $offset The offset.
* @param string $order The order-column.
* @param string $sort The sorting-method.
*/
private function buildURL($offset, $order, $sort)
{
return str_replace(array('[offset]', '[order]', '[sort]'), array($offset, $order, $sort), $this->URL);
}
/**
* Clears the attributes.
*/
public function clearAttributes()
{
$this->attributes['datagrid'] = array();
}
/**
* Clears the attributes for a specific column.
*
* @param string $column The name of the column you want to clear the column attributes from.
*/
public function clearColumnAttributes($column)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesn't exist
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist and therefor no attributes can be removed.');
// exists
$this->columns[(string) $column]->clearAttributes();
}
}
/**
* Clears the even row attributes.
*/
public function clearEvenRowAttributes()
{
$this->attributes['row_even'] = array();
}
/**
* clears the odd row attributes.
*/
public function clearOddRowAttributes()
{
$this->attributes['row_odd'] = array();
}
/**
* Clears the row attributes.
*/
public function clearRowAttributes()
{
$this->attributes['row'] = array();
}
/**
* Creates the default columns, based on the initially provided source.
*/
private function createColumns()
{
// has results
if($this->source->getNumResults() != 0)
{
// fetch the column names
foreach($this->source->getColumns() as $column)
{
// add column
$this->addColumn($column, $column, '[' . $column . ']', null, null, null, (count($this->columns) +1));
// by default the column name will be added as a class
$this->columns[$column]->setAttributes(array('class' => $column));
// may be sorted on
$this->allowedSortingColumns[] = $column;
}
}
}
/**
* Shows the output & stops script execution.
*/
public function display()
{
echo $this->getContent();
exit;
}
/**
* Generates the array with the order columns.
*/
private function generateOrder()
{
// delete current cache of sortable columns
$this->sortingColumns = array();
// columns present
if(count($this->columns) != 0)
{
// loop columns
foreach($this->columns as $column)
{
// allowed sorting, sorting enabled specifically
if(in_array($column->getName(), $this->allowedSortingColumns) && $column->getSorting())
{
// add to the list
$this->sortingColumns[] = $column->getName();
// default
$default = $column->getName();
}
}
// no default defined
if($this->sortingColumn === null && isset($default)) $this->sortingColumn = $default;
}
}
/**
* Retrieve all the datagrid attributes.
*
* @return array
*/
public function getAttributes()
{
return $this->attributes['datagrid'];
}
/**
* Fetch the column object for a specific column.
*
* @return SpoonDatagridColumn
* @param string $column The name of the column.
*/
public function getColumn($column)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesnt exist
if(!isset($this->columns[$column])) throw new SpoonDatagridException('The column "' . $column . '" doesn\'t exist.');
// exists
return $this->columns[$column];
}
// fallback
return new SpoonDatagridColumn($column);
}
/**
* Fetch the list of columns in this datagrid.
*
* @return array
*/
public function getColumns()
{
return $this->getColumnsSequence();
}
/**
* Retrieve the columns sequence.
*
* @return array
*/
private function getColumnsSequence()
{
// init var
$columns = array();
// loop all the columns
foreach($this->columns as $column) $columns[$column->getSequence()] = $column->getName();
// reindex
return (!empty($columns)) ? SpoonFilter::arraySortKeys($columns) : $columns;
}
/**
* Retrieve the parsed output.
*
* @return string
*/
public function getContent()
{
// parse if needed
if(!$this->parsed) $this->parse();
// fetch content
return $this->content;
}
/**
* Fetch the debug status.
*
* @return bool
*/
public function getDebug()
{
return $this->debug;
}
/**
* Returns the html attributes based on an array.
*
* @return string
* @param array[optional] $array The attributes to be converted into HTML-attributes.
*/
private function getHTMLAttributes(array $array = array())
{
// output
$html = '';
// loop elements
foreach($array as $label => $value) $html .= ' ' . $label . '="' . $value . '"';
return $html;
}
/**
* Retrieve the number of results for this datagrids' source.
*
* @return int
*/
public function getNumResults()
{
return $this->source->getNumResults();
}
/**
* Retrieve the offset value.
*
* @return int
*/
public function getOffset()
{
// default offset
$offset = null;
// paging enabled
if($this->paging)
{
// has results
if($this->source->getNumResults() != 0)
{
// offset parameter defined
if($this->offsetParameter !== null) $offset = $this->offsetParameter;
// use default
else $offset = (isset($_GET['offset'])) ? (int) $_GET['offset'] : 0;
// offset cant be bigger than the number of results
if($offset >= $this->source->getNumResults()) $offset = (int) $this->source->getNumResults() - $this->pagingLimit;
// offset divided by the per page limit should have no rest
if(($offset % $this->pagingLimit) != 0) $offset = 0;
// offset minus the pagina limit may not go below zero
if(($offset - $this->pagingLimit) < 0) $offset = 0;
}
// no results
else $offset = 0;
}
return $offset;
}
/**
* Retrieves the column that's currently being sorted on.
*
* @return string
*/
public function getOrder()
{
// default value
$order = null;
// sorting enabled
if($this->getSorting())
{
/**
* First the list of columns that can be ordered on,
* must be re-generated
*/
$this->generateOrder();
// order parameter defined
if($this->orderParameter !== null) $order = $this->orderParameter;
// defaut order
else $order = (isset($_GET['order'])) ? (string) $_GET['order'] : null;
// retrieve order
$order = SpoonFilter::getValue($order, $this->sortingColumns, $this->sortingColumn);
}
return $order;
}
/**
* Is paging enabled?
*
* @return bool
*/
public function getPaging()
{
return $this->paging;
}
/**
* Fetch name of the class that will be used to parse the paging.
*
* @return string
*/
public function getPagingClass()
{
return $this->pagingClass;
}
/**
* Fetch the number of items that will be shown on each page.
*
* @return int
*/
public function getPagingLimit()
{
return ($this->paging) ? $this->pagingLimit : null;
}
/**
* Retrieve the sorting method.
*
* @return string The sorting method, either asc or desc.
*/
public function getSort()
{
// default sort
$sort = ($this->sortParameter !== null) ? $this->sortParameter : null;
// redefine
$sort = (isset($_GET['sort'])) ? (string) $_GET['sort'] : $sort;
// retrieve sort
return SpoonFilter::getValue($sort, array('asc', 'desc'), 'asc');
}
/**
* Retrieve the sorting status.
*
* @return bool
*/
public function getSorting()
{
// generate order
$this->generateOrder();
// sorting columns exist?
return (count($this->sortingColumns) != 0) ? true : false;
}
/**
* Retrieve the datagrid source object.
*
* @return SpoonDatagridSource
*/
public function getSource()
{
return $this->source;
}
/**
* Fetch the template instance
*
* @return SpoonTemplate
*/
public function getTemplate()
{
return $this->tpl;
}
/**
* Retrieve the location of the template that will be used.
*
* @return string
*/
private function getTemplatePath()
{
return ($this->template != null) ? $this->template : dirname(__FILE__) . '/datagrid.tpl';
}
/**
* Retrieve the URL.
*
* @return string The URL that will be used, may contain variables with square brackets.
*/
public function getURL()
{
return $this->URL;
}
/**
* Parse the datagrid.
*/
private function parse()
{
// has results
if($this->source->getNumResults() > 0)
{
// fetch records
$aRecords = $this->source->getData($this->getOffset(), $this->getPagingLimit(), $this->getOrder(), $this->getSort());
// has results
if(count($aRecords) != 0)
{
// compile directory
$compileDirectory = ($this->compileDirectory !== null) ? $this->compileDirectory : dirname(realpath(__FILE__));
$this->tpl->setCompileDirectory($compileDirectory);
// only force compiling when debug is enabled
if($this->debug) $this->tpl->setForceCompile(true);
// table attributes
$this->parseAttributes();
// table summary
$this->parseSummary();
// caption/description
$this->parseCaption();
// header row
$this->parseHeader();
// actual rows
$this->parseBody($aRecords);
// pagination
$this->parseFooter();
// parse to buffer
ob_start();
$this->tpl->display($this->getTemplatePath());
$this->content = ob_get_clean();
}
}
// update parsed status
$this->parsed = true;
}
/**
* Parses the datagrid attributes.
*/
private function parseAttributes()
{
$this->tpl->assign('attributes', $this->getHtmlAttributes($this->attributes['datagrid']));
}
/**
* Parses the body.
*
* @param array $records The rows.
*/
private function parseBody(array $records)
{
// init var
$rows = array();
// columns sequence
$sequence = $this->getColumnsSequence();
// loop records
foreach($records as $i => &$record)
{
// replace possible variables
$record = $this->parseRecord($record);
// parse column functions
$record = $this->parseColumnFunctions($record);
// parse custom row functions
$this->parseRowFunctions($record, $this->attributes['row']);
// reset row
$row = array('attributes' => '', 'columns' => array());
// row attributes
$row['attributes'] = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($this->attributes['row']));
// add custom row functions
if(!empty($this->rowFunctionsParsed))
{
// reset attributes
$row['attributes'] = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($this->rowFunctionsParsed));
// clear for the next row
$this->rowFunctionsParsed = array();
}
// default row behaviour
else $row['attributes'] = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($this->attributes['row']));
// odd row attributes (reversed since the first $i = 0)
if(!SpoonFilter::isOdd($i)) $cycleAttributes = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($this->attributes['row_odd']));
// even row attributes
else $cycleAttributes = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($this->attributes['row_even']));
// no longer overwrite default attributes with odd/even attributes.
if(!empty($row['attributes']))
{
$cycleData = array();
$rowData = array();
preg_match_all('/( (.*?)=\"(.*?)\")/', $row['attributes'], $rowData);
preg_match_all('/( (.*?)=\"(.*?)\")/', $cycleAttributes, $cycleData);
// go trough the attribute data to see if anything matches
foreach($cycleData[2] as $cycleAttribute => $cycleValue)
{
if(in_array($cycleValue, $rowData[2]))
{
$rowData[3][$cycleAttribute] .= ' ' . $cycleData[3][$cycleAttribute];
// remove the data so we can use the others to merge the arrays
unset($cycleData[2][$cycleAttribute], $cycleData[3][$cycleAttribute]);
}
}
// merge all the values, so we get everything we need
$rowData[2] = array_merge($rowData[2], $cycleData[2]);
$rowData[3] = array_merge($rowData[3], $cycleData[3]);
// rebuild the data
$row['attributes'] = $this->getHTMLAttributes(array_combine($rowData[2], $rowData[3]));
}
// no match, just assign the cycle attributes as the row attributes
else $row['attributes'] = $cycleAttributes;
// define the columns
$columns = array();
// loop columns
foreach($sequence as $name)
{
// column
$column = $this->columns[$name];
// has overwrite enabled
if($column->getOverwrite())
{
// fetch key
$iKey = array_search('[' . $column->getName() . ']', $record['labels']);
// parse the actual value
$columnValue = $record['values'][$iKey];
}
// no overwrite status
else
{
// default value
$columnValue = '';
// has an url
if($column->getURL() !== null)
{
// open url tag
$columnValue .= '<a href="' . str_replace($record['labels'], $record['values'], $column->getURL()) . '"';
// add title
$columnValue .= ' title="' . str_replace($record['labels'], $record['values'], $column->getURLTitle()) . '"';
// confirm
if($column->getConfirm() && $column->getConfirmMessage() !== null)
{
// default confirm
if($column->getConfirmCustom() == '') $columnValue .= ' onclick="return confirm(\'' . str_replace($record['labels'], $record['values'], $column->getConfirmMessage()) . '\');"';
// custom confirm
else
{
// replace the message
$tmpValue = str_replace('%message%', $column->getConfirmMessage(), $column->getConfirmCustom());
// make vars available
$tmpValue = str_replace($record['labels'], $record['values'], $tmpValue);
// add id
$columnValue .= ' ' . $tmpValue;
}
}
// close start tag
$columnValue .= '>';
}
// has an image
if($column->getImage() !== null)
{
// open img tag
$columnValue .= '<img src="' . str_replace($record['labels'], $record['values'], $column->getImage()) . '"';
// add title & alt
$columnValue .= ' alt="' . str_replace($record['labels'], $record['values'], $column->getImageTitle()) . '"';
$columnValue .= ' title="' . str_replace($record['labels'], $record['values'], $column->getImageTitle()) . '"';
// close img tag
$columnValue .= ' />';
}
// regular value
else
{
// fetch key
$iKey = array_search('[' . $column->getName() . ']', $record['labels']);
// parse value
$columnValue .= $record['values'][$iKey];
}
// has an url (close the tag)
if($column->getURL() !== null) $columnValue .= '</a>';
}
// fetch column attributes
$columnAttributes = str_replace($record['labels'], $record['values'], $this->getHtmlAttributes($column->getAttributes()));
// visible & iteration
if(!$column->getHidden())
{
// add this column
$columns[] = array('attributes' => $columnAttributes, 'value' => $columnValue);
// add to custom list
$row['column'][$name] = $columnValue;
}
}
// add the columns to the rows
$row['columns'] = $columns;
// add the row
$rows[] = $row;
}
// assign body
$this->tpl->assign('rows', $rows);
// assign the number of columns
$this->tpl->assign('numColumns', count($rows[0]['columns']));
}
/**
* Parses the caption tag.
*/
private function parseCaption()
{
if($this->caption !== null) $this->tpl->assign('caption', $this->caption);
}
/**
* Parses the column functions.
*
* @return array
* @param array $record The column-data.
*/
private function parseColumnFunctions($record)
{
// store old error reporting settings
$currentErrorReporting = ini_get('error_reporting');
// ignore warnings and notices
error_reporting(E_WARNING | E_NOTICE);
// loop functions
foreach($this->columnFunctions as $function)
{
// no arguments given
if($function['arguments'] == null) $value = call_user_func($function['function']);
// array
elseif(is_array($function['arguments']))
{
// replace arguments
$function['arguments'] = str_replace($record['labels'], $record['values'], $function['arguments']);
// execute function
$value = call_user_func_array($function['function'], $function['arguments']);
}
// no null/array
else $value = call_user_func($function['function'], str_replace($record['labels'], $record['values'], $function['arguments']));
/**
* Now that we have the return value of this method, we can
* do the actual writeback to the column(s). If overwrite was
* true, we're going to enable the overwrite of the writeback column(s)
*/
// one column, that exists
if(is_string($function['columns']) && isset($this->columns[$function['columns']]))
{
// fetch key
$iKey = array_search('[' . $function['columns'] . ']', $record['labels']);
// value was set
if($iKey !== false)
{
// update value
$record['values'][$iKey] = $value;
// update overwrite
if($function['overwrite']) $this->columns[$function['columns']]->setOverwrite(true);
}
}
// write to multiple columns
elseif(is_array($function['columns']) && count($function['columns']) != 0)
{
// loop target columns
foreach($function['columns'] as $column)
{
// fetch key
$iKey = array_search('[' . $column . ']', $record['labels']);
// value was set
if($iKey !== false)
{
// update value
$record['values'][$iKey] = $value;
// update overwrite
if($function['overwrite']) $this->columns[$column]->setOverwrite(true);
}
}
}
}
// restore error reporting
error_reporting($currentErrorReporting);
return $record;
}
/**
* Parses the footer.
*/
private function parseFooter()
{
// attributes
$this->tpl->assign('footerAttributes', $this->getHtmlAttributes($this->attributes['footer']));
// parse paging
$this->parsePaging();
}
/**
* Parses the header row.
*/
private function parseHeader()
{
// init vars
$header = array();
// sequence
$sequence = $this->getColumnsSequence();
// sorting enabled?
$sorting = $this->getSorting();
// sortable columns
$sortingColumns = array();
foreach($sequence as $oColumn) if($this->columns[$oColumn]->getSorting()) $sortingColumns[] = $oColumn;
// loop columns
foreach($sequence as $name)
{
// define column
$column = array();
// column
$oColumn = $this->columns[$name];
// visible
if(!$oColumn->getHidden())
{
// sorting globally enabled AND for this column
if($sorting && in_array($name, $sortingColumns))
{
// init var
$column['sorting'] = true;
$column['noSorting'] = false;
// sorted on this column?
if($this->getOrder() == $name)
{
// sorted
$column['sorted'] = true;
$column['notSorted'] = false;
// asc
if($this->getSort() == 'asc')
{
$column['sortedAsc'] = true;
$column['sortedDesc'] = false;
}
// desc
else
{
$column['sortedAsc'] = false;
$column['sortedDesc'] = true;
}
}
/**
* This column is sortable, but there's currently not being
* sorted on this column.
*/
elseif(in_array($name, $sortingColumns))
{
$column['sorted'] = false;
$column['notSorted'] = true;
}
/**
* URL's are parsed for the opposite column, as for the asc & desc version
* for this column. If the sorting is currently not on this column
* the default sorting method (mostly asc) will be used to define the opposite/default
* sorting method.
*/
// currently not sorting on this column
if($this->getOrder() != $name) $sortingMethod = $this->columns[$name]->getSortingMethod();
// sorted on this column ascending
elseif($this->getSort() == 'asc') $sortingMethod = 'desc';
// sorting on this column descending
else $sortingMethod = 'asc';
// build actual urls
$column['sortingURL'] = $this->buildURL($this->getOffset(), $name, $sortingMethod);
$column['sortingURLAsc'] = $this->buildURL($this->getOffset(), $name, 'asc');
$column['sortingURLDesc'] = $this->buildURL($this->getOffset(), $name, 'desc');
/**
* There's no point in parsing the icon for this column if there's
* not being sorted on this column.
*/
/**
* To define the default icon for sorting, we need to apply
* the same rules as with the default url. See those comments for
* the necessary details.
*/
if($this->getOrder() != $name) $sortingIcon = $this->sortingIcons[$this->columns[$name]->getSortingMethod()];
// sorted on this column asc/desc
elseif($this->getSort() == 'asc') $sortingIcon = $this->sortingIcons['ascSelected'];
else $sortingIcon = $this->sortingIcons['descSelected'];
// asc & desc icons
$column['sortingIcon'] = $sortingIcon;
$column['sortingIconAsc'] = ($this->getSort() == 'asc') ? $this->sortingIcons['ascSelected'] : $this->sortingIcons['asc'];
$column['sortingIconDesc'] = ($this->getSort() == 'desc') ? $this->sortingIcons['descSelected'] : $this->sortingIcons['desc'];
// not sorted on this column
if($this->getOrder() != $name) $sortingLabel = $this->sortingLabels[$this->columns[$name]->getSortingMethod()];
// sorted on this column asc/desc
elseif($this->getSort() == 'asc') $sortingLabel = $this->sortingLabels['ascSelected'];
else $sortingLabel = $this->sortingLabels['descSelected'];
// add sorting labels
$column['sortingLabel'] = $sortingLabel;
$column['sortingLabelAsc'] = $this->sortingLabels['asc'];
$column['sortingLabelDesc'] = $this->sortingLabels['desc'];
}
// no sorting enabled for this column
else
{
$column['sorting'] = false;
$column['noSorting'] = true;
}
// parse vars
$column['label'] = $oColumn->getLabel();
// add attributes
$column['attributes'] = $this->getHTMLAttributes($oColumn->getHeaderAttributes());
// add to array
$header[] = $column;
}
}
// default headers
$this->tpl->assign('headers', $header);
}
/**
* Parses the paging.
*/
private function parsePaging()
{
// enabled
if($this->paging)
{
// offset, order & sort
$this->tpl->assign(array('offset', 'order', 'sort'), array($this->getOffset(), $this->getOrder(), $this->getSort()));
// number of results
$this->tpl->assign('iResults', $this->source->getNumResults());
// number of pages
$this->tpl->assign('iPages', ceil($this->source->getNumResults() / $this->pagingLimit));
// current page
$this->tpl->assign('iCurrentPage', ceil($this->getOffset() / $this->pagingLimit) + 1);
// number of items per page
$this->tpl->assign('iPerPage', $this->pagingLimit);
// parse paging
$content = call_user_func(array($this->pagingClass, 'getContent'), $this->URL, $this->getOffset(), $this->getOrder(), $this->getSort(), $this->source->getNumResults(), $this->pagingLimit, $this->debug, $this->compileDirectory);
// asign content
$this->tpl->assign('paging', $content);
}
}
/**
* Parses the record.
*
* @return array
* @param array $record The row-data.
*/
private function parseRecord(array $record)
{
// init var
$array = array('labels' => array(), 'values' => array());
// create labels/values array
foreach($record as $label => $value)
{
$array['labels'][] = '[' . $label . ']';
$array['values'][] = $value;
}
// add offset?
if($this->paging)
{
$array['labels'][] = '[offset]';
$array['values'][] = $this->getOffset();
}
// sorting
if(count($this->sortingColumns) != 0)
{
$array['labels'][] = '[order]';
$array['labels'][] = '[sort]';
// --
$array['values'][] = $this->getOrder();
$array['values'][] = $this->getSort();
}
// loop the record fields
foreach($this->columns as $column)
{
// this column is an extra field, added in the datagrid
if(!in_array('[' . $column->getName() . ']', $array['labels']))
{
$array['values'][] = str_replace($array['labels'], $array['values'], $column->getValue());
$array['labels'][] = '[' . $column->getName() . ']';
}
}
return $array;
}
/**
* Parses the column functions.
*
* @param array $record The row-data.
* @param array[optional] $rowAttributes The attributes on the row.
*/
private function parseRowFunctions($record, array $rowAttributes = null)
{
// store old error reporting settings
$currentErrorReporting = ini_get('error_reporting');
// ignore warnings and notices
error_reporting(E_WARNING | E_NOTICE);
// loop functions
foreach($this->rowFunctions as $function)
{
// no arguments given
if($function['arguments'] == null) $value = call_user_func($function['function'], $rowAttributes);
// array
elseif(is_array($function['arguments']))
{
// replace arguments
$function['arguments'] = str_replace($record['labels'], $record['values'], $function['arguments']);
$function['arguments'][] = $rowAttributes;
// execute function
$value = call_user_func_array($function['function'], $function['arguments']);
}
// no null/array
else $value = call_user_func($function['function'], str_replace($record['labels'], $record['values'], $function['arguments']), $rowAttributes);
/**
* Now that we have the return value we have to write the the
* custom row function cache. If overwrite was enabled, we're
* overwriting this, else we're adding to it!
*/
if($function['overwrite']) $this->rowFunctionsParsed = $value;
else
{
// loop return values
foreach((array) $value as $key => $value)
{
if(isset($this->rowFunctionsParsed[$key])) $this->rowFunctionsParsed[$key] .= ' ' . $value;
else $this->rowFunctionsParsed[$key] = $value;
}
}
}
// restore error reporting
error_reporting($currentErrorReporting);
// cough it up
return $record;
}
/**
* Parses the summary.
*/
private function parseSummary()
{
if($this->summary !== null) $this->tpl->assign('summary', $this->summary);
}
/**
* Set main datagrid attributes.
*
* @param array $attributes The attributes to set on the datagrid.
*/
public function setAttributes(array $attributes)
{
foreach($attributes as $key => $value) $this->attributes['datagrid'][(string) $key] = (string) $value;
}
/**
* Sets the table caption or main description.
*
* @param string $value The value for the caption-element.
*/
public function setCaption($value)
{
$this->caption = (string) $value;
}
/**
* Set one or more attributes for a specific column.
*
* @param string $column The column to apply the attributes on.
* @param array $attributes The attributes for a column.
*/
public function setColumnAttributes($column, array $attributes)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesnt exist
if(!isset($this->columns[$column])) throw new SpoonDatagridException('The column "' . $column . '" doesn\'t exist, therefor no attributes can be added.');
// exists
else $this->columns[$column]->setAttributes($attributes);
}
}
/**
* Set a custom column confirm message.
*
* @param string $column The column to apply the confirmation on.
* @param string $message The message to use.
* @param string[optional] $custom Custom code you wish to use to confirm.
*/
public function setColumnConfirm($column, $message, $custom = null)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesnt exist
if(!isset($this->columns[$column])) throw new SpoonDatagridException('The column "' . $column . '" doesn\'t exist, therefor no confirm message/script can be added.');
// exists
else $this->columns[$column]->setConfirm($message, $custom);
}
}
/**
* Sets the column function to be executed for every row.
*
* @param mixed $function The function to apply.
* @param mixed[optional] $arguments The arguments for the function.
* @param mixed $columns The columns wherein the result will appear.
* @param bool[optional] $overwrite Should the result overwrite the current value?
*/
public function setColumnFunction($function, $arguments = null, $columns, $overwrite = false)
{
// has results
if($this->source->getNumResults() > 0)
{
// regular function
if(!is_array($function))
{
// function checks
if(!function_exists((string) $function)) throw new SpoonDatagridException('The function "' . (string) $function . '" doesn\'t exist.');
}
// class method
else
{
// method checks
if(count($function) != 2) throw new SpoonDatagridException('When providing a method for a column function it must be like array(\'class\', \'method\')');
// method doesn't exist
elseif(!is_callable(array($function[0], $function[1]))) throw new SpoonDatagridException('The method ' . (string) $function[0] . '::' . (string) $function[1] . ' does not exist.');
}
// add to function stack
$this->columnFunctions[] = array('function' => $function, 'arguments' => $arguments, 'columns' => $columns, 'overwrite' => (bool) $overwrite);
}
}
/**
* Set one or more attributes for a columns' header.
*
* @param string $column The column whereon the atrributes will be set.
* @param array $attributes The attributes for a column.
*/
public function setColumnHeaderAttributes($column, array $attributes)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesnt exist
if(!isset($this->columns[$column])) throw new SpoonDatagridException('The column "' . $column . '" doesn\'t exist, therefor no attributes can be added to its header.');
// exists
else $this->columns[$column]->setHeaderAttributes($attributes);
}
}
/**
* Sets a single column hidden.
*
* @param string $column The column to hide/show.
* @param bool[optional] $on Should the column be hidden?
*/
public function setColumnHidden($column, $on = true)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesn't exist
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist and therefor can\'t be set hidden.');
// exists
$this->columns[(string) $column]->setHidden($on);
}
}
/**
* Sets one or more columns hidden.
*
* @param array $columns An array with the columns to hide.
*/
public function setColumnsHidden($columns)
{
// has results
if($this->source->getNumResults() > 0)
{
// array
if(is_array($columns)) foreach($columns as $column) $this->setColumnHidden((string) $column);
// multiple arguments
else
{
// set columns hidden
foreach(func_get_args() as $column) $this->setColumnHidden($column);
}
}
}
/**
* Set the default sorting method for a column.
*
* @param string $column The column to set the method for.
* @param string[optional] $sort The sorting method, possible values are: asc, desc.
*/
public function setColumnSortingMethod($column, $sort = 'asc')
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesn't exist
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist and therefor no default sorting method can be applied to it.');
// exists
$this->columns[(string) $column]->setSortingMethod($sort);
}
}
/**
* Sets the columns sequence.
*
* @param array $columns The columns in the correct sequence.
*/
public function setColumnsSequence($columns)
{
// has results
if($this->source->getNumResults() > 0)
{
// array
if(is_array($columns)) call_user_func_array(array($this, 'setColumnsSequence'), $columns);
// multiple arguments
else
{
// current sequence
$sequences = $this->getColumnsSequence();
// fetch arguments
$arguments = func_get_args();
// build columns
$columns = (is_array($arguments[0])) ? $arguments[0] : $arguments;
// counter
$i = 1;
// loop colums
foreach($columns as $column)
{
// column exists
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist. Therefor its sequence can\'t be altered.');
// update sequence
$this->columns[(string) $column]->setSequence($i);
// remove from the original list
$iKey = (int) array_search((string) $column, $sequences);
unset($sequences[$iKey]);
// update counter
$i++;
}
// reset counter
$i = 1;
// add remaining columns
foreach($sequences as $sequence)
{
// update sequence
$this->columns[$sequence]->setSequence(count($columns) + $i);
// update counter
$i++;
}
}
}
}
/**
* Set the URL for a column.
*
* @param string $column The column wheron the URL will be applied.
* @param string $URL The URL.
* @param string[optional] $title The title for the URL.
*/
public function setColumnURL($column, $URL, $title = null)
{
// has results
if($this->source->getNumResults() > 0)
{
// column doesn't exist
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist and therefore no URL can be applied.');
// exists
$this->columns[(string) $column]->setURL($URL, $title);
}
}
/**
* Sets the compile directory.
*
* @param string $path The path to the compile directory.
*/
public function setCompileDirectory($path)
{
$this->compileDirectory = (string) $path;
}
/**
* Adjust the debug setting.
*
* @param bool[optional] $on Should we enable debug-mode.
*/
public function setDebug($on = true)
{
$this->debug = (bool) $on;
}
/**
* Set the even row attributes.
*
* @param array $attributes The attributes for an even row.
*/
public function setEvenRowAttributes(array $attributes)
{
if($this->source->getNumResults() > 0)
{
foreach($attributes as $key => $value)
{
$this->attributes['row_even'][(string) $key] = (string) $value;
}
}
}
/**
* Set the header labels.
*
* @param array $labels An array whith the labels where the key is the name of the column.
*/
public function setHeaderLabels(array $labels)
{
// has results
if($this->source->getNumResults() > 0)
{
// loop the keys
foreach($labels as $column => $label)
{
// column doesn't exist
if(!isset($this->columns[$column])) throw new SpoonDatagridException('The column "' . $column . '" doesn\'t exist, therefor no label can be assigned to it.');
// exists
else $this->columns[$column]->setLabel($label);
}
}
}
/**
* Set the odd row attributes.
*
* @param array $attributes The attributes for an odd-row.
*/
public function setOddRowAttributes(array $attributes)
{
if($this->source->getNumResults() > 0)
{
foreach($attributes as $key => $value)
{
$this->attributes['row_odd'][(string) $key] = (string) $value;
}
}
}
/**
* Sets the value for offset. eg from the URL.
*
* @param int[optional] $value The value from the offset-parameter.
*/
public function setOffsetParameter($value = null)
{
$this->offsetParameter = (int) $value;
}
/**
* Sets the value for the order. eg from the URL.
*
* @param string[optional] $value The value from the order-parameter.
*/
public function setOrderParameter($value = null)
{
$this->orderParameter = (string) $value;
}
/**
* Allow/disallow showing the results on multiple pages.
*
* @param bool[optional] $on Is paging enabled?
*/
public function setPaging($on = false)
{
$this->paging = (bool) $on;
}
/**
* Sets an alternative paging class.
*
* @param string $class The class that should be used for paging.
*/
public function setPagingClass($class)
{
// class cant be found
if(!class_exists((string) $class)) throw new SpoonDatagridException('The class "' . (string) $class . '" you provided for the alternative paging can not be found.');
// class exists
else
{
// does not impmlement the interface
if(!in_array('iSpoonDatagridPaging', class_implements($class))) throw new SpoonDatagridException('The paging class you provided does not implement the "iSpoonDatagridPaging" interface');
// all is fine
else $this->pagingClass = $class;
}
}
/**
* Sets the number of results per page.
*
* @param int[optional] $limit The maximum number of rows when paging is enabled.
*/
public function setPagingLimit($limit = 30)
{
$this->pagingLimit = abs((int) $limit);
}
/**
* Sets the row attributes.
*
* @param array $attributes The attributes for a row.
*/
public function setRowAttributes(array $attributes)
{
foreach($attributes as $key => $value) $this->attributes['row'][(string) $key] = (string) $value;
}
/**
* Sets the row function to be executed for every row.
*
* @param mixed $function The function to apply.
* @param mixed[optional] $arguments The arguments to pass to the function.
* @param bool[optional] $overwrite Should the result overwrite the current value?
*/
public function setRowFunction($function, $arguments = null, $overwrite = false)
{
// has results
if($this->source->getNumResults() > 0)
{
// regular function
if(!is_array($function))
{
// function checks
if(!function_exists((string) $function)) throw new SpoonDatagridException('The function "' . (string) $function . '" doesn\'t exist.');
}
// class method
else
{
// method checks
if(count($function) != 2) throw new SpoonDatagridException('When providing a method for a column function it must be like array(\'class\', \'method\')');
// method doesn't exist
elseif(!is_callable(array($function[0], $function[1]))) throw new SpoonDatagridException('The method ' . (string) $function[0] . '::' . (string) $function[1] . ' does not exist.');
}
// add to function stack
$this->rowFunctions[] = array('function' => $function, 'arguments' => $arguments, 'overwrite' => (bool) $overwrite);
}
}
/**
* Sets the columns that may be sorted on.
*
* @param array $columns The columns whereon sorting is enabled.
* @param string[optional] $default The column whereon will be sorted by default.
*/
public function setSortingColumns(array $columns, $default = null)
{
// has results
if($this->source->getNumResults() > 0)
{
// loop columns
foreach($columns as $column)
{
// column doesn't exist
if(!isset($this->columns[(string) $column])) throw new SpoonDatagridException('The column "' . (string) $column . '" doesn\'t exist and therefor can\'t be sorted on.');
// column exists
else
{
// not sortable
if(!in_array((string) $column, $this->allowedSortingColumns)) throw new SpoonDatagridException('The column "' . (string) $column . '" can\'t be sorted on.');
// sortable
else
{
// enable sorting
$this->columns[(string) $column]->setSorting(true);
// set default sorting
if(!isset($defaultColumn)) $defaultColumn = (string) $column;
}
}
}
// default column set
if($default !== null && in_array($defaultColumn, $columns)) $defaultColumn = (string) $default;
// default column is not good
if(!in_array($defaultColumn, $this->allowedSortingColumns)) throw new SpoonDatagridException('The column "' . $defaultColumn . '" can\'t be set as the default sorting column, because it doesn\'t exist or may not be sorted on.');
// set default column
$this->sortingColumn = $defaultColumn;
}
}
/**
* Sets the sorting icons.
*
* @param string[optional] $asc The icon for ascending.
* @param string[optional] $ascSelected The icon when ascending sort is applied.
* @param string[optional] $desc The icon for descending.
* @param string[optional] $descSelected The icon when descending sort is applied.
*/
public function setSortingIcons($asc = null, $ascSelected = null, $desc = null, $descSelected)
{
if($asc !== null) $this->sortingIcons['asc'] = (string) $asc;
if($ascSelected !== null) $this->sortingIcons['ascSelected'] = (string) $ascSelected;
if($desc !== null) $this->sortingIcons['desc'] = (string) $desc;
if($descSelected !== null) $this->sortingIcons['descSelected'] = (string) $descSelected;
}
/**
* Sets the sorting labels.
*
* @param string[optional] $asc The value for ascending.
* @param string[optional] $ascSelected The value when ascending sort is applied.
* @param string[optional] $desc The value for descending.
* @param string[optional] $descSelected The value when descending sort is applied.
*/
public function setSortingLabels($asc = null, $ascSelected = null, $desc = null, $descSelected = null)
{
if($asc !== null) $this->sortingLabels['asc'] = (string) $asc;
if($ascSelected !== null) $this->sortingLabels['ascSelected'] = (string) $ascSelected;
if($desc !== null) $this->sortingLabels['desc'] = (string) $desc;
if($descSelected !== null) $this->sortingLabels['descSelected'] = (string) $descSelected;
}
/**
* Sets the value to sort.
*
* @param string[optional] $value The sorting-method.
*/
public function setSortParameter($value = 'desc')
{
$this->sortParameter = SpoonFilter::getValue($value, array('asc', 'desc'), 'asc');
}
/**
* Sets the source for this datagrid.
*
* @param SpoonDatagridSource $source The source for the datagrid, it should implement SpoonDatagridSource.
*/
private function setSource(SpoonDatagridSource $source)
{
$this->source = $source;
}
/**
* Sets the table summary.
*
* @param string $value The summary value.
*/
public function setSummary($value)
{
$this->summary = (string) $value;
}
/**
* Sets the path to the template file.
*
* @param string $template The path to the template.
*/
public function setTemplate($template)
{
$this->template = (string) $template;
}
/**
* Defines the default URL.
*
* @param string $URL The URL to use.
*/
public function setURL($URL)
{
$this->URL = (string) $URL;
}
}
/**
* This exception is used to handle datagrid related exceptions.
*
* @package spoon
* @subpackage datagrid
*
*
* @author Davy Hellemans <davy@spoon-library.com>
* @since 0.1.1
*/
class SpoonDatagridException extends SpoonException {}
| 24thStreet/JH-De-Wauwel | vendor/spoon/library/spoon/datagrid/datagrid.php | PHP | mit | 47,971 |
<?php
class WebUser extends CWebUser
{
/**
* @var string
*/
protected $lang;
/**
* @var array
*/
private $availableLanguages = ['ru', 'en'];
/**
* @return string
*/
function getRole()
{
return $this->getState('role', 'guest');
}
/**
* @return boolean
*/
public function isAdmin()
{
return $this->getRole() === 'admin';
}
/**
* @return boolean
*/
public function isModerator()
{
return $this->getRole() === 'moderator';
}
/**
* @return string
*/
public function getLang() {
if ($this->lang === null) {
$langCookie = Yii::app()->request->cookies['lang'];
if (is_object($langCookie)) {
$this->lang = $langCookie->value;
}
if (empty($this->lang)) {
$this->lang = 'ru';
}
if (!in_array($this->lang, $this->availableLanguages)) {
$this->lang = 'ru';
}
}
return $this->lang;
}
/**
* @param string $lang
* @return \WebUser
*/
public function setLang($lang) {
if (!in_array($this->lang, $this->availableLanguages)) {
$lang = 'ru';
}
$cookie = new CHttpCookie('lang', $lang);
$cookie->path = '/';
$cookie->expire = time() + 3600 * 30;
Yii::app()->request->cookies['lang'] = $cookie;
return $this;
}
} | wowtransfer/wowtransfer-php-client | public_html/protected/components/WebUser.php | PHP | mit | 1,212 |
<?php
namespace Vipa\UserBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class VipaUserExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
| okulbilisim/ojs | src/Vipa/UserBundle/DependencyInjection/VipaUserExtension.php | PHP | mit | 755 |
# frozen_string_literal: true
# Provides an intuitive way to build has_many associated records in the same form.
module Formtastic
module Inputs
module Base
def input_wrapping(&block)
html = super
template.concat(html) if template.output_buffer && template.assigns[:has_many_block]
html
end
end
end
end
module ActiveAdmin
class FormBuilder < ::Formtastic::FormBuilder
self.input_namespaces = [::Object, ::ActiveAdmin::Inputs, ::Formtastic::Inputs]
# TODO: remove both class finders after formtastic 4 (where it will be default)
self.input_class_finder = ::Formtastic::InputClassFinder
self.action_class_finder = ::Formtastic::ActionClassFinder
def cancel_link(url = { action: "index" }, html_options = {}, li_attrs = {})
li_attrs[:class] ||= "cancel"
li_content = template.link_to I18n.t("active_admin.cancel"), url, html_options
template.content_tag(:li, li_content, li_attrs)
end
attr_accessor :already_in_an_inputs_block
def has_many(assoc, options = {}, &block)
HasManyBuilder.new(self, assoc, options).render(&block)
end
end
# Decorates a FormBuilder with the additional attributes and methods
# to build a has_many block. Nested has_many blocks are handled by
# nested decorators.
class HasManyBuilder < SimpleDelegator
attr_reader :assoc
attr_reader :options
attr_reader :heading, :sortable_column, :sortable_start
attr_reader :new_record, :destroy_option, :remove_record
def initialize(has_many_form, assoc, options)
super has_many_form
@assoc = assoc
@options = extract_custom_settings!(options.dup)
@options.reverse_merge!(for: assoc)
@options[:class] = [options[:class], "inputs has_many_fields"].compact.join(" ")
if sortable_column
@options[:for] = [assoc, sorted_children(sortable_column)]
end
end
def render(&block)
html = "".html_safe
html << template.content_tag(:h3) { heading } if heading.present?
html << template.capture { content_has_many(&block) }
html = wrap_div_or_li(html)
template.concat(html) if template.output_buffer
html
end
protected
# remove options that should not render as attributes
def extract_custom_settings!(options)
@heading = options.key?(:heading) ? options.delete(:heading) : default_heading
@sortable_column = options.delete(:sortable)
@sortable_start = options.delete(:sortable_start) || 0
@new_record = options.key?(:new_record) ? options.delete(:new_record) : true
@destroy_option = options.delete(:allow_destroy)
@remove_record = options.delete(:remove_record)
options
end
def default_heading
assoc_klass.model_name.
human(count: ::ActiveAdmin::Helpers::I18n::PLURAL_MANY_COUNT)
end
def assoc_klass
@assoc_klass ||= __getobj__.object.class.reflect_on_association(assoc).klass
end
def content_has_many(&block)
form_block = proc do |form_builder|
render_has_many_form(form_builder, options[:parent], &block)
end
template.assigns[:has_many_block] = true
contents = without_wrapper { inputs(options, &form_block) }
contents ||= "".html_safe
js = new_record ? js_for_has_many(options[:class], &form_block) : ""
contents << js
end
# Renders the Formtastic inputs then appends ActiveAdmin delete and sort actions.
def render_has_many_form(form_builder, parent, &block)
index = parent && form_builder.send(:parent_child_index, parent)
template.concat template.capture { yield(form_builder, index) }
template.concat has_many_actions(form_builder, "".html_safe)
end
def has_many_actions(form_builder, contents)
if form_builder.object.new_record?
contents << template.content_tag(:li) do
remove_text = remove_record.is_a?(String) ? remove_record : I18n.t("active_admin.has_many_remove")
template.link_to remove_text, "#", class: "button has_many_remove"
end
elsif allow_destroy?(form_builder.object)
form_builder.input(
:_destroy, as: :boolean,
wrapper_html: { class: "has_many_delete" },
label: I18n.t("active_admin.has_many_delete"))
end
if sortable_column
form_builder.input sortable_column, as: :hidden
contents << template.content_tag(:li, class: "handle") do
I18n.t("active_admin.move")
end
end
contents
end
def allow_destroy?(form_object)
!! case destroy_option
when Symbol, String
form_object.public_send destroy_option
when Proc
destroy_option.call form_object
else
destroy_option
end
end
def sorted_children(column)
__getobj__.object.public_send(assoc).sort_by do |o|
attribute = o.public_send column
[attribute.nil? ? Float::INFINITY : attribute, o.id || Float::INFINITY]
end
end
def without_wrapper
is_being_wrapped = already_in_an_inputs_block
self.already_in_an_inputs_block = false
html = yield
self.already_in_an_inputs_block = is_being_wrapped
html
end
# Capture the ADD JS
def js_for_has_many(class_string, &form_block)
assoc_name = assoc_klass.model_name
placeholder = "NEW_#{assoc_name.to_s.underscore.upcase.gsub(/\//, '_')}_RECORD"
opts = {
for: [assoc, assoc_klass.new],
class: class_string,
for_options: { child_index: placeholder }
}
html = template.capture { __getobj__.send(:inputs_for_nested_attributes, opts, &form_block) }
text = new_record.is_a?(String) ? new_record : I18n.t("active_admin.has_many_new", model: assoc_name.human)
template.link_to text, "#", class: "button has_many_add", data: {
html: CGI.escapeHTML(html).html_safe, placeholder: placeholder
}
end
def wrap_div_or_li(html)
template.content_tag(
already_in_an_inputs_block ? :li : :div,
html,
class: "has_many_container #{assoc}",
"data-sortable" => sortable_column,
"data-sortable-start" => sortable_start)
end
end
end
| javierjulio/activeadmin | lib/active_admin/form_builder.rb | Ruby | mit | 6,286 |
/*
* gauge.js
* Copyright(c) 2015 Vladimir Rodkin <mail@vovanr.com>
* MIT Licensed
*/
/* global define */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
root.Gauge = factory(root.jQuery);
}
})(this, function ($) {
'use strict';
var template = '<svg version="1.1" width="100%" height="100%" ' +
'preserveAspectRatio="xMidYMid meet" viewBox="-50 -50 100 100">' +
'<defs>' +
'<g id="gauge-mark" class="gauge-mark">' +
'<line x1="0" y1="-40.5" x2="0" y2="-40.75" />' +
'</g>' +
'<g id="gauge-tick" class="gauge-tick">' +
'<line x1="0" y1="-40.5" x2="0" y2="-41.5" />' +
'</g>' +
'</defs>' +
'<g class="gauge-marks"></g>' +
'<g class="gauge-ticks"></g>' +
'<g class="gauge-labels"></g>' +
'<g class="gauge-scale-arc"></g>' +
'<g class="gauge-scale-arc-warning"></g>' +
'<g class="gauge-scale-arc-danger"></g>' +
'<g class="gauge-hand">' +
'<polygon points="-1,0 0,-41 1,0" />' +
'<circle cx="0" cy="0" r="2" />' +
'</g>' +
'</svg>';
var Gauge;
/**
* @param {Object} o Options
* @param {HTMLElement} o.block
* @param {Number} o.actualValue
* @param {Array} o.labels
* @param {Number} [o.maxValue]
* @param {Number} [o.warningValue] in percents
* @param {Number} [o.dangerValue] in percentes
* @constructor
* @module Gauge
*/
Gauge = function (o) {
this._block = o.block;
this._actualValue = o.actualValue;
this._labels = o.labels;
this._maxValue = o.maxValue || this._labels[this._labels.length - 1];
this._warningValue = o.warningValue;
this._dangerValue = o.dangerValue;
this._delta = 100 / this._maxValue;
this._render();
};
Gauge.prototype = {
/**
* @private
*/
_render: function () {
this._block.innerHTML = template;
this._renderHand();
this._renderTicks();
this._renderMarks();
this._renderTicksLabels();
this._renderArcScale();
if (this._warningValue !== undefined) {
this._renderArcWarning();
}
if (this._dangerValue !== undefined) {
this._renderArcDanger();
}
},
/**
* @param {Number} value
* @return {Number} degree
* @private
*/
_valueToDegree: function (value) {
// -120 deg - excluded part
// -210 deg - rotate start to simmetrical view
return (value / this._maxValue * (360 - 120)) - 210;
},
/**
* @param {Number} value
* @param {Number} radius
* @return {Object} position
* @private
*/
_valueToPosition: function (value, radius) {
var a = this._valueToDegree(value) * Math.PI / 180;
var x = radius * Math.cos(a);
var y = radius * Math.sin(a);
return {
x: x,
y: y
};
},
/**
* @param {Number} percent
* @return {Number} value
* @private
*/
_percentToValue: function (percent) {
return percent / this._delta;
},
/**
* @private
*/
_renderHand: function () {
this._hand = $('.gauge-hand', this._block)[0];
this._setValue(this._actualValue);
},
/**
* @private
*/
_setValue: function () {
this._hand.style.transform = 'rotate(' + (this._valueToDegree(this._actualValue) + 90) + 'deg)';
},
/**
* @param {Number} value
* @public
*/
setValue: function (value) {
this._actualValue = value;
this._setValue();
},
/**
* @private
*/
_renderTicks: function () {
var ticksCache = '';
var ticks = $('.gauge-ticks', this._block)[0];
var total = this._labels.length - 1;
for (var value = 0; value <= total; value++) {
ticksCache += this._buildTick(value);
}
ticks.innerHTML = ticksCache;
},
/**
* @return {String}
* @private
*/
_buildTick: function (value) {
return '<use xlink:href="#gauge-tick" transform="rotate(' + (this._valueToDegree(value) + 90) + ')" />';
},
/**
* @private
*/
_renderTicksLabels: function () {
var labelsCache = '';
var labels = $('.gauge-labels', this._block)[0];
var total = this._labels.length - 1;
for (var value = 0; value <= total; value++) {
labelsCache += this._buildTickLabel(value);
}
labels.innerHTML = labelsCache;
},
/**
* @param {Number} value
* @return {String}
* @private
*/
_buildTickLabel: function (value) {
var position = this._valueToPosition(value, 43);
return '<text x="' + position.x + '" y="' + position.y + '" text-anchor="middle">' +
this._labels[value] + '</text>';
},
/**
* @private
*/
_renderMarks: function () {
var marksCache = '';
var marks = $('.gauge-marks', this._block)[0];
var total = (this._labels.length - 1) * 10;
for (var value = 0; value <= total; value++) {
// Skip marks on ticks
if (value % 10 === 0) {
continue;
}
marksCache += this._buildMark(value / 10);
}
marks.innerHTML = marksCache;
},
/**
* @return {String}
* @private
*/
_buildMark: function (value) {
return '<use xlink:href="#gauge-mark" transform="rotate(' + (this._valueToDegree(value) + 90) + ')" />';
},
/**
* @private
*/
_renderArcScale: function () {
var max = 100;
if (this._dangerValue) {
max = this._dangerValue;
}
if (this._warningValue) {
max = this._warningValue;
}
var group = $('.gauge-scale-arc', this._block)[0];
var arc = this._buildArc(0, max, 39);
group.innerHTML = arc;
},
/**
* @private
*/
_renderArcWarning: function () {
var max = 100;
if (this._dangerValue) {
max = this._dangerValue;
}
var group = $('.gauge-scale-arc-warning', this._block)[0];
var arc = this._buildArc(this._warningValue, max, 39);
group.innerHTML = arc;
},
/**
* @private
*/
_renderArcDanger: function () {
var group = $('.gauge-scale-arc-danger', this._block)[0];
var arc = this._buildArc(this._dangerValue, 100, 39);
group.innerHTML = arc;
},
/**
* @param {Number} min in percents
* @param {Number} max in percents
* @param {Number} radius
* @return {String}
* @private
*/
_buildArc: function (min, max, radius) {
min = this._percentToValue(min);
max = this._percentToValue(max);
var positionStart = this._valueToPosition(min, radius);
var positionEnd = this._valueToPosition(max, radius);
var alpha = (360 - 120) / this._maxValue * (max - min);
var arc = '<path d="M' + positionStart.x + ',' + positionStart.y +
' A' + radius + ',' + radius + ' 0 ' +
((alpha > 180) ? 1 : 0) + ',1 ' +
positionEnd.x + ',' + positionEnd.y +
'" style="fill: none;" />';
return arc;
}
};
return Gauge;
});
| VovanR/gauge.js | src/index.js | JavaScript | mit | 6,504 |
<!DOCTYPE html>
<html>
<head>
<title>Escuela Salesiana María Mazzarello</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../css/bootstrap-theme.css">
<link rel="stylesheet" type="text/css" href="../css/bootstrap-theme.min.css">
</head>
<body style="background-color:#FB65E4;">
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-12 col-lg-12">
<br/>
<br/>
<br/>
<div class="jumbotron">
<h1>BIENVENIDAS/OS</h1>
<p class="text-xs-justify">Usted esta alojado en el panel de inicio de sesión del sistema de notas de la
Escuela María Mazzarello.<br/> Para hacer uso del sistema solo debe ingresar sus datos
correctamente, no importa si usted es docente de la institución o Alumna.</p>
<form>
<div class="form-group">
<label>Ingrese su usuario</label>
<input id="usuario" class="form-control">
</div>
<div class="form-group">
<label>Ingrese su contraseña</label>
<input type="password" id="password" class="form-control">
</div>
<input type="submit" class="btn btn-info btn-block" value="Ingresar">
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript" src ="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</body>
</html>
| FicLel/MMSN | pages/Login.php | PHP | mit | 1,598 |
# Modules in this file are included in both specs and cucumber steps.
module TestHelpers
def create_listing(listing_type, category, share_type)
share_types = share_type ? share_type.split(",").collect { |st| Factory(:share_type, :name => st) } : [Factory(:share_type, :name => (listing_type.eql?("offer") ? "sell" : "buy"))]
if category
case category
when "favor"
listing = Factory(:listing, :category => category, :share_types => [], :listing_type => listing_type)
when "rideshare"
listing = Factory(:listing, :category => category, :share_types => [], :origin => "test", :destination => "test2", :listing_type => listing_type)
else
listing = Factory(:listing, :category => category, :share_types => share_types, :listing_type => listing_type)
end
else
listing = Factory(:listing, :category => "item")
end
end
def get_test_person_and_session(username="kassi_testperson1")
session = nil
test_person = nil
#frist try loggin in to cos
begin
session = Session.create({:username => username, :password => "testi" })
#try to find in kassi database
test_person = Person.find(session.person_id)
rescue RestClient::Request::Unauthorized => e
#if not found, create completely new
session = Session.create
test_person = Person.create({ :username => username,
:password => "testi",
:email => "#{username}@example.com",
:given_name => "Test",
:family_name => "Person"},
session.cookie)
rescue ActiveRecord::RecordNotFound => e
test_person = Person.add_to_kassi_db(session.person_id)
end
return [test_person, session]
end
def generate_random_username(length = 12)
chars = ("a".."z").to_a + ("0".."9").to_a
random_username = "aa_kassitest"
1.upto(length - 7) { |i| random_username << chars[rand(chars.size-1)] }
return random_username
end
def set_subdomain(subdomain = "test")
subdomain += "." unless subdomain.blank?
@request.host = "#{subdomain}.lvh.me"
end
end
| comet/Kassi_Desktop | test/helper_modules.rb | Ruby | mit | 2,175 |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.Xbox.Services
{
public partial class XboxLive
{
public static bool UseMockServices
{
get { return false; }
}
public static bool UseMockHttp
{
get { return true; }
}
}
} | MSFT-Heba/xbox-live-api-csharp | Source/Microsoft.Xbox.Services.Test.CSharp/XboxLive.cs | C# | mit | 419 |
package May2021GoogLeetcode;
import java.util.Arrays;
import java.util.Comparator;
public class _1024VideoStitching {
// https://www.youtube.com/watch?v=Gg64QXc9K0s
public static void main(String[] args) {
System.out.println(videoStitching(new int[][] { new int[] { 0, 2 }, new int[] { 4, 6 }, new int[] { 8, 10 },
new int[] { 1, 9 }, new int[] { 1, 5 }, new int[] { 5, 9 } }, 10));
System.out.println(videoStitching(new int[][] { new int[] { 0, 1 }, new int[] { 1, 2 } }, 5));
System.out.println(videoStitching(new int[][] { new int[] { 0, 1 }, new int[] { 6, 8 }, new int[] { 0, 2 },
new int[] { 5, 6 }, new int[] { 0, 4 }, new int[] { 0, 3 }, new int[] { 6, 7 }, new int[] { 1, 3 },
new int[] { 4, 7 }, new int[] { 1, 4 }, new int[] { 2, 5 }, new int[] { 2, 6 }, new int[] { 3, 4 },
new int[] { 4, 5 }, new int[] { 5, 7 }, new int[] { 6, 9 } }, 9));
System.out.println(videoStitching(new int[][] { new int[] { 0, 4 }, new int[] { 2, 8 } }, 5));
}
public static int videoStitching(int[][] clips, int T) {
Arrays.sort(clips, new Comparator<int[]>() {
});
}
}
| darshanhs90/Java-InterviewPrep | src/May2021GoogLeetcode/_1024VideoStitching.java | Java | mit | 1,101 |
(function() {
'use strict';
angular
.module('siteApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('finishReset', {
parent: 'account',
url: '/reset/finish?key',
data: {
authorities: []
},
views: {
'content@': {
templateUrl: 'app/account/reset/finish/reset.finish.html',
controller: 'ResetFinishController',
controllerAs: 'vm'
}
}
});
}
})();
| egrohs/Politicos | site/src/main/webapp/app/account/reset/finish/reset.finish.state.js | JavaScript | mit | 657 |
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
public static CameraShake instance;
public float xShake, yShake, shakeSpeed, shakeCoolRate = 1f;
private Vector3 initialPosition;
private Vector3 goalPosition;
private float initialXShake, initialYShake;
void Awake()
{
instance = this;
initialPosition = transform.localPosition;
initialXShake = xShake;
initialYShake = yShake;
goalPosition = initialPosition;
}
void Update ()
{
updateScreenshake();
}
/// <summary>
/// Set the amplitude for the screen to shake
/// </summary>
/// <param name="shake"></param>
public void setScreenShake(float shake)
{
xShake = yShake = shake;
}
/// <summary>
/// Adds to the screenshake amplitude instead of overriding it
/// </summary>
/// <param name="shake"></param>
public void addScreenShake(float shake)
{
xShake += shake;
yShake += shake;
}
/// <summary>
/// Resets shake x and y values to initial values;
/// </summary>
public void resetShake()
{
xShake = initialXShake;
yShake = initialYShake;
}
/// <summary>
/// Centers camera and stops shake
/// </summary>
public void reset()
{
xShake = yShake = shakeSpeed = 0f;
shakeCoolRate = 1f;
transform.localPosition = initialPosition;
goalPosition = initialPosition;
}
void resetGoal()
{
goalPosition = new Vector3(Random.Range(-1f * xShake, xShake), Random.Range(-1f * yShake, yShake), initialPosition.z);
}
void updateScreenshake()
{
if (xShake == 0f && yShake == 0f && transform.localPosition == goalPosition)
return;
if (shakeSpeed <= 0f)
{
resetGoal();
transform.localPosition = goalPosition;
}
else if ((xShake + yShake > 0f) && transform.moveTowardsLocal((Vector2)goalPosition, shakeSpeed))
{
resetGoal();
}
if (xShake > 0f)
{
xShake -= shakeCoolRate * Time.deltaTime;
xShake = Mathf.Max(xShake, 0f);
}
if (yShake > 0f)
{
yShake -= shakeCoolRate * Time.deltaTime;
yShake = Mathf.Max(yShake, 0f);
}
if (xShake + yShake == 0f)
{
goalPosition = initialPosition;
transform.moveTowardsLocal((Vector2)goalPosition, shakeSpeed);
}
}
}
| uulltt/NitoriWare | Assets/Scripts/Generic Microgame Behaviors/Camera/CameraShake.cs | C# | mit | 2,216 |
package com.sentenial.ws.client.dd;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for RequestCancelDirectDebit complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RequestCancelDirectDebit">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Creditor" type="{urn:com:sentenial:origix:ws:common:commontypes}Creditor"/>
* <element name="MandateInfo" type="{urn:com:sentenial:origix:ws:common:commontypes}MandateInfo" minOccurs="0"/>
* <element name="PmtEndToEndId" type="{urn:com:sentenial:origix:ws:common:types}Max35Text"/>
* <element name="OperationRsn" type="{urn:com:sentenial:origix:ws:common:types}CancelDirectDebitReasonCode"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RequestCancelDirectDebit", propOrder = {
"creditor",
"mandateInfo",
"pmtEndToEndId",
"operationRsn"
})
@XmlSeeAlso({
CancelDirectDebitRequest.class
})
public class RequestCancelDirectDebit {
@XmlElement(name = "Creditor", required = true)
protected Creditor creditor;
@XmlElement(name = "MandateInfo")
protected MandateInfo mandateInfo;
@XmlElement(name = "PmtEndToEndId", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String pmtEndToEndId;
@XmlElement(name = "OperationRsn", required = true)
protected CancelDirectDebitReasonCode operationRsn;
/**
* Gets the value of the creditor property.
*
* @return
* possible object is
* {@link Creditor }
*
*/
public Creditor getCreditor() {
return creditor;
}
/**
* Sets the value of the creditor property.
*
* @param value
* allowed object is
* {@link Creditor }
*
*/
public void setCreditor(Creditor value) {
this.creditor = value;
}
/**
* Gets the value of the mandateInfo property.
*
* @return
* possible object is
* {@link MandateInfo }
*
*/
public MandateInfo getMandateInfo() {
return mandateInfo;
}
/**
* Sets the value of the mandateInfo property.
*
* @param value
* allowed object is
* {@link MandateInfo }
*
*/
public void setMandateInfo(MandateInfo value) {
this.mandateInfo = value;
}
/**
* Gets the value of the pmtEndToEndId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPmtEndToEndId() {
return pmtEndToEndId;
}
/**
* Sets the value of the pmtEndToEndId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPmtEndToEndId(String value) {
this.pmtEndToEndId = value;
}
/**
* Gets the value of the operationRsn property.
*
* @return
* possible object is
* {@link CancelDirectDebitReasonCode }
*
*/
public CancelDirectDebitReasonCode getOperationRsn() {
return operationRsn;
}
/**
* Sets the value of the operationRsn property.
*
* @param value
* allowed object is
* {@link CancelDirectDebitReasonCode }
*
*/
public void setOperationRsn(CancelDirectDebitReasonCode value) {
this.operationRsn = value;
}
}
| whelanp/sentenial-ws-client | src/main/java/com/sentenial/ws/client/dd/RequestCancelDirectDebit.java | Java | mit | 3,860 |
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun\Api;
use Mailgun\Api\Suppression\Bounce;
use Mailgun\Api\Suppression\Complaint;
use Mailgun\Api\Suppression\Unsubscribe;
use Mailgun\Api\Suppression\Whitelist;
use Mailgun\HttpClient\RequestBuilder;
use Mailgun\Hydrator\Hydrator;
use Psr\Http\Client\ClientInterface;
/**
* @see https://documentation.mailgun.com/api-suppressions.html
*
* @author Sean Johnson <sean@mailgun.com>
*/
class Suppression
{
/**
* @var ClientInterface
*/
private $httpClient;
/**
* @var RequestBuilder
*/
private $requestBuilder;
/**
* @var Hydrator
*/
private $hydrator;
public function __construct(ClientInterface $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
$this->requestBuilder = $requestBuilder;
$this->hydrator = $hydrator;
}
public function bounces(): Bounce
{
return new Bounce($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function complaints(): Complaint
{
return new Complaint($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function unsubscribes(): Unsubscribe
{
return new Unsubscribe($this->httpClient, $this->requestBuilder, $this->hydrator);
}
public function whitelists(): Whitelist
{
return new Whitelist($this->httpClient, $this->requestBuilder, $this->hydrator);
}
}
| michabbb-backup/mailgun-php | src/Api/Suppression.php | PHP | mit | 1,660 |
/**
* Copyright 2016-2017 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
'use strict';
import { expect } from 'chai';
import * as expressionInterpolator from '../src/expression_interpolator';
describe( 'expressionInterpolator', () => {
///////////////////////////////////////////////////////////////////////////////////////////////////////////
describe( '.create( options )', () => {
it( 'returns an interpolator', () => {
const interpolator = expressionInterpolator.create();
expect( interpolator ).to.be.an( 'object' );
} );
describe( 'the returned object', () => {
const interpolator = expressionInterpolator.create();
it( 'has an interpolate method', () => {
expect( interpolator ).to.respondTo( 'interpolate' );
} );
} );
} );
///////////////////////////////////////////////////////////////////////////////////////////////////////////
describe( '.interpolate( context, data )', () => {
const context = {
id: 'my-id0',
features: {
test: {
enabled: true,
resource: 'my-resource'
}
}
};
const interpolator = expressionInterpolator.create();
describe( 'when interpolating plain strings', () => {
it( 'returns non-matching strings unchanged', () => {
expect( interpolator.interpolate( context, '$test' ) )
.to.eql( '$test' );
} );
it( 'replaces feature references', () => {
expect( interpolator.interpolate( context, '${features.test.resource}' ) )
.to.eql( 'my-resource' );
} );
it( 'replaces topic references', () => {
expect( interpolator.interpolate( context, '${topic:my-topic}' ) )
.to.eql( 'my+id0+my-topic' );
} );
it( 'replaces exact matches without converting to strings', () => {
expect( interpolator.interpolate( context, '${features.test.enabled}' ) )
.to.eql( true );
} );
it( 'replaces substring matches with the stringified value', () => {
expect( interpolator.interpolate( context, '!${features.test.enabled}' ) )
.to.eql( '!true' );
} );
/* Undocumented/hidden feature */
/*
it( 'supports multiple matches per string', () => {
expect( interpolator.interpolate( context,
'${topic:my-topic} => ( ${features.test.resource}, ${features.test.enabled} )' )
).to.eql( 'my+id0+my-topic => ( my-resource, true )' );
} );
*/
} );
describe( 'when interpolating arrays', () => {
it( 'returns non-matching items unchanged', () => {
expect( interpolator.interpolate( context, [ '$test' ] ) )
.to.eql( [ '$test' ] );
} );
it( 'replaces feature references in array items', () => {
expect( interpolator.interpolate( context, [ '${features.test.resource}' ] ) )
.to.eql( [ 'my-resource' ] );
} );
it( 'replaces topic references in array items', () => {
expect( interpolator.interpolate( context, [ '${topic:my-topic}' ] ) )
.to.eql( [ 'my+id0+my-topic' ] );
} );
it( 'drops items where the expression evaluates to undefined', () => {
expect( interpolator.interpolate( context, [ '1', '${features.empty}', '2' ] ) )
.to.eql( [ '1', '2' ] );
} );
} );
describe( 'when interpolating objects', () => {
it( 'replaces feature references in object properties', () => {
expect( interpolator.interpolate( context, { test: '${features.test.resource}' } ) )
.to.eql( { test: 'my-resource' } );
} );
it( 'replaces topic references in object properties', () => {
expect( interpolator.interpolate( context, { test: '${topic:my-topic}' } ) )
.to.eql( { test: 'my+id0+my-topic' } );
} );
it( 'replaces feature references in object keys', () => {
expect( interpolator.interpolate( context, { '${features.test.resource}': 'test' } ) )
.to.eql( { 'my-resource': 'test' } );
} );
it( 'drops properties where the expression evaluates to undefined', () => {
expect( interpolator.interpolate( context, { test: '${features.empty}', ok: true } ) )
.to.eql( { ok: true } );
} );
it( 'drops keys where the expression evaluates to undefined', () => {
expect( interpolator.interpolate( context, { '${features.empty}': 'test', ok: true } ) )
.to.eql( { ok: true } );
} );
} );
describe( 'when interpolating anything else', () => {
it( 'returns numbers unchanged', () => {
expect( interpolator.interpolate( context, 123 ) ).to.eql( 123 );
} );
it( 'returns booleans unchanged', () => {
expect( interpolator.interpolate( context, true ) ).to.eql( true );
expect( interpolator.interpolate( context, false ) ).to.eql( false );
} );
} );
} );
} );
| LaxarJS/laxar-tooling | test/expression_interpolator.js | JavaScript | mit | 5,308 |
<?php
declare(strict_types=1);
$metadata->mapField(
[
'type' => 'integer',
'name' => 'fixPrice',
'fieldName' => 'fixPrice',
]
);
| bigfoot90/doctrine2 | tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php | PHP | mit | 173 |
require 'erubis'
module Skeleton
def self.common_playbook
input = File.read 'templates/playbook.eruby'
template_file = Erubis::Eruby.new input
File.write "playbook-#{$project_name}/playbook.yml", template_file.result
end
def self.required_system_playbook
input = File.read 'templates/playbook.eruby'
template_file = Erubis::Eruby.new input
required_system = $required_systems
required_system.each do |required_system|
context = {
required_system: required_system
}
File.write "playbook-#{$project_name}/#{required_system}/playbook.yml", template_file.result
end
end
end
| noqcks/playbook-skeleton | lib/skeleton/playbook.rb | Ruby | mit | 637 |
module.exports = {
development: {
session: {
key: '${randomstring.generate(30)}',
path: '/tmp/session.nedb'
},
view_engine: 'jade',
smtp: {
secure: true,
user: 'user',
password: 'password',
server: 'smtp.example.com'
},
database: {
driver: 'sqlite',
host: './',
database: '${controllerName.toLowerCase()}_development.sqlite'
}
},
test: {
session: {
key: '${randomstring.generate(30)}',
path: '/tmp/session.nedb'
},
view_engine: 'jade',
smtp: {
secure: true,
user: 'user',
password: 'password',
server: 'smtp.example.com'
},
database: {
driver: 'sqlite',
host: './',
database: '${controllerName.toLowerCase()}_test.sqlite'
}
},
production: {
session: {
key: '${randomstring.generate(30)}',
path: '/tmp/session.nedb'
},
view_engine: 'jade',
smtp: {
secure: true,
user: 'user',
password: 'password',
server: 'smtp.example.com'
},
database: {
driver: 'sqlite',
host: './',
database: '${controllerName.toLowerCase()}_test.sqlite'
}
}
} | moongift/airline | skeleton/config.js | JavaScript | mit | 1,188 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using SharpDX.Mathematics.Interop;
using D3D = SharpDX.Direct3D;
using D3D11 = SharpDX.Direct3D11;
using D2D1 = SharpDX.Direct2D1;
using DXGI = SharpDX.DXGI;
using WIC = SharpDX.WIC;
using DW = SharpDX.DirectWrite;
using Windows.UI.Xaml.Media.Imaging;
using NGraphics.UWP;
namespace NGraphics
{
public class WICBitmapCanvas : RenderTargetCanvas, IImageCanvas
{
protected readonly WIC.Bitmap Bmp;
readonly Size size;
readonly double scale;
public WICBitmapCanvas (Size size, double scale = 1.0, bool transparency = true, Direct2DFactories factories = null)
: this (
// DIPs = pixels / (DPI/96.0)
new WIC.Bitmap ((factories ?? Direct2DFactories.Shared).WICFactory, (int)(Math.Ceiling (size.Width * scale)), (int)(Math.Ceiling (size.Height * scale)), transparency ? WIC.PixelFormat.Format32bppPBGRA : WIC.PixelFormat.Format32bppBGR, WIC.BitmapCreateCacheOption.CacheOnLoad),
new D2D1.RenderTargetProperties (D2D1.RenderTargetType.Default, new D2D1.PixelFormat (DXGI.Format.Unknown, D2D1.AlphaMode.Unknown), (float)(96.0 * scale), (float)(96.0 * scale), D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT))
{
}
public WICBitmapCanvas (WIC.Bitmap bmp, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null)
: base (new D2D1.WicRenderTarget ((factories ?? Direct2DFactories.Shared).D2DFactory, bmp, properties), factories)
{
this.Bmp = bmp;
this.scale = properties.DpiX / 96.0;
var bmpSize = bmp.Size;
this.size = new Size (bmpSize.Width / scale, bmpSize.Height / scale);
}
public IImage GetImage ()
{
renderTarget.EndDraw ();
return new WICBitmapSourceImage (Bmp, scale, factories);
}
public Size Size
{
get { return size; }
}
public double Scale
{
get { return scale; }
}
}
public class WICBitmapSourceImage : IImage
{
readonly WIC.BitmapSource bmp;
readonly Direct2DFactories factories;
readonly double scale;
public WIC.BitmapSource Bitmap { get { return bmp; } }
public Size Size { get { return Conversions.ToSize (bmp.Size); } }
public double Scale { get { return scale; } }
public WICBitmapSourceImage (WIC.BitmapSource bmp, double scale, Direct2DFactories factories = null)
{
if (bmp == null)
throw new ArgumentNullException ("bmp");
this.bmp = bmp;
this.scale = scale;
this.factories = factories ?? Direct2DFactories.Shared;
}
public void SaveAsPng (string path)
{
throw new NotSupportedException ("WinUniversal does not support saving to files. Please use the Stream override instead.");
}
public void SaveAsPng (System.IO.Stream stream)
{
using (var encoder = new WIC.PngBitmapEncoder (factories.WICFactory, stream)) {
using (var bitmapFrameEncode = new WIC.BitmapFrameEncode (encoder)) {
bitmapFrameEncode.Initialize ();
var size = bmp.Size;
bitmapFrameEncode.SetSize (size.Width, size.Height);
var pf = bmp.PixelFormat;
bitmapFrameEncode.SetPixelFormat (ref pf);
bitmapFrameEncode.WriteSource (bmp);
bitmapFrameEncode.Commit ();
encoder.Commit ();
}
}
}
}
public class SurfaceImageSourceCanvas : RenderTargetCanvas
{
DXGI.ISurfaceImageSourceNative sisn;
public SurfaceImageSourceCanvas (SurfaceImageSource surfaceImageSource, Rect updateRect, Direct2DFactories factories = null)
: base (factories)
{
sisn = ComObject.As<DXGI.ISurfaceImageSourceNative> (surfaceImageSource);
RawPoint offset;
var surface = sisn.BeginDraw (updateRect.ToRectangle (), out offset);
var dpi = 96.0;
var properties = new D2D1.RenderTargetProperties (D2D1.RenderTargetType.Default, new D2D1.PixelFormat (DXGI.Format.Unknown, D2D1.AlphaMode.Unknown), (float)(dpi), (float)(dpi), D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT);
Initialize (new D2D1.RenderTarget (this.factories.D2DFactory, surface, properties));
}
}
/// <summary>
/// ICanvas wrapper over a Direct2D RenderTarget.
/// </summary>
public class RenderTargetCanvas : ICanvas
{
protected D2D1.RenderTarget renderTarget;
protected readonly Direct2DFactories factories;
readonly Stack<D2D1.DrawingStateBlock> stateStack = new Stack<D2D1.DrawingStateBlock> ();
protected RenderTargetCanvas (Direct2DFactories factories = null)
{
this.factories = factories ?? Direct2DFactories.Shared;
}
public RenderTargetCanvas (DXGI.Surface surface, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null)
{
if (surface == null)
throw new ArgumentNullException ("surface");
this.factories = factories ?? Direct2DFactories.Shared;
Initialize (new D2D1.RenderTarget (this.factories.D2DFactory, surface, properties));
}
public RenderTargetCanvas (D2D1.RenderTarget renderTarget, Direct2DFactories factories = null)
{
if (renderTarget == null)
throw new ArgumentNullException ("renderTarget");
this.factories = factories ?? Direct2DFactories.Shared;
Initialize (renderTarget);
}
protected void Initialize (D2D1.RenderTarget renderTarget)
{
this.renderTarget = renderTarget;
renderTarget.BeginDraw ();
}
public void SaveState ()
{
var s = new D2D1.DrawingStateBlock (factories.D2DFactory);
renderTarget.SaveDrawingState (s);
stateStack.Push (s);
}
public void Transform (Transform transform)
{
var currentTx = renderTarget.Transform;
var tx = new Matrix3x2 ();
tx.M11 = (float)transform.A;
tx.M12 = (float)transform.B;
tx.M21 = (float)transform.C;
tx.M22 = (float)transform.D;
tx.M31 = (float)transform.E;
tx.M32 = (float)transform.F;
renderTarget.Transform = tx * currentTx;
}
public void RestoreState ()
{
if (stateStack.Count > 0) {
var s = stateStack.Pop ();
renderTarget.RestoreDrawingState (s);
}
}
public TextMetrics MeasureText (string text, Font font)
{
return WinUniversalPlatform.GlobalMeasureText(factories, text, font);
}
public void DrawText (string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
{
var layout = new DW.TextLayout (factories.DWFactory, text, WinUniversalPlatform.GetTextFormat (factories, font), (float)frame.Width, (float)frame.Height);
var h = layout.Metrics.Height + layout.OverhangMetrics.Top;
renderTarget.DrawTextLayout ((frame.TopLeft - h*Point.OneY).ToVector2 (), layout, GetBrush (frame, brush));
}
public void DrawPath (IEnumerable<PathOp> ops, Pen pen = null, Brush brush = null)
{
var bb = new BoundingBoxBuilder ();
var s = new D2D1.PathGeometry (factories.D2DFactory);
var figureDepth = 0;
using (var sink = s.Open ()) {
foreach (var op in ops) {
if (op is MoveTo) {
while (figureDepth > 0) {
sink.EndFigure (D2D1.FigureEnd.Open);
figureDepth--;
}
var mt = ((MoveTo)op);
sink.BeginFigure (Conversions.ToVector2 (mt.Point), D2D1.FigureBegin.Filled);
figureDepth++;
bb.Add (mt.Point);
}
else if (op is LineTo) {
var lt = ((LineTo)op);
sink.AddLine (Conversions.ToVector2 (lt.Point));
bb.Add (lt.Point);
}
else if (op is ArcTo) {
var ar = ((ArcTo)op);
// TODO: Direct2D Arcs
//sink.AddArc (new D2D1.ArcSegment {
// Size = Conversions.ToSize2F (ar.Radius),
// Point = Conversions.ToVector2 (ar.Point),
// SweepDirection = ar.SweepClockwise ? D2D1.SweepDirection.Clockwise : D2D1.SweepDirection.CounterClockwise,
//});
sink.AddLine (Conversions.ToVector2 (ar.Point));
bb.Add (ar.Point);
}
else if (op is CurveTo) {
var ct = ((CurveTo)op);
sink.AddBezier (new D2D1.BezierSegment {
Point1 = Conversions.ToVector2 (ct.Control1),
Point2 = Conversions.ToVector2 (ct.Control2),
Point3 = Conversions.ToVector2 (ct.Point),
});
bb.Add (ct.Point);
bb.Add (ct.Control1);
bb.Add (ct.Control2);
}
else if (op is ClosePath) {
sink.EndFigure (D2D1.FigureEnd.Closed);
figureDepth--;
}
else {
// TODO: More path operations
}
}
while (figureDepth > 0) {
sink.EndFigure (D2D1.FigureEnd.Open);
figureDepth--;
}
sink.Close ();
}
var p = GetBrush (pen);
var b = GetBrush (bb.BoundingBox, brush);
if (b != null) {
renderTarget.FillGeometry (s, b);
}
if (p != null) {
renderTarget.DrawGeometry (s, p, (float)pen.Width, GetStrokeStyle (pen));
}
}
public void DrawRectangle (Rect frame, Size corner, Pen pen = null, Brush brush = null)
{
var p = GetBrush (pen);
var b = GetBrush (frame, brush);
if (b != null) {
if (corner.Width > 0 || corner.Height > 0) {
var rr = new D2D1.RoundedRectangle ();
rr.Rect = frame.ToRectangleF ();
rr.RadiusX = (float)corner.Width;
rr.RadiusY = (float)corner.Height;
renderTarget.FillRoundedRectangle (ref rr, b);
}
else {
renderTarget.FillRectangle (frame.ToRectangleF (), b);
}
}
if (p != null) {
if (corner.Width > 0 || corner.Height > 0) {
var rr = new D2D1.RoundedRectangle ();
rr.Rect = frame.ToRectangleF ();
rr.RadiusX = (float)corner.Width;
rr.RadiusY = (float)corner.Height;
renderTarget.DrawRoundedRectangle (ref rr, p, (float)pen.Width, GetStrokeStyle (pen));
}
else {
renderTarget.DrawRectangle (frame.ToRectangleF (), p, (float)pen.Width, GetStrokeStyle (pen));
}
}
}
public void DrawEllipse (Rect frame, Pen pen = null, Brush brush = null)
{
var p = GetBrush (pen);
var b = GetBrush (frame, brush);
var c = frame.Center;
var s = new D2D1.Ellipse (new RawVector2 { X = (float)c.X, Y = (float)c.Y }, (float)(frame.Width / 2.0), (float)(frame.Height / 2.0));
if (b != null) {
renderTarget.FillEllipse (s, b);
}
if (p != null) {
renderTarget.DrawEllipse (s, p, (float)pen.Width, GetStrokeStyle (pen));
}
}
public void DrawImage (IImage image, Rect frame, double alpha = 1.0)
{
var i = GetImage (image);
renderTarget.DrawBitmap (i, frame.ToRectangleF (), (float)alpha, D2D1.BitmapInterpolationMode.Linear);
}
D2D1.Bitmap GetImage (IImage image)
{
if (image == null)
return null;
var wbi = image as WICBitmapSourceImage;
if (wbi != null) {
Guid renderFormat = WIC.PixelFormat.Format32bppPBGRA;
if (wbi.Bitmap.PixelFormat != renderFormat) {
//System.Diagnostics.Debug.WriteLine ("RT FORMAT: " + renderTarget.PixelFormat.Format);
//System.Diagnostics.Debug.WriteLine ("BMP FORMAT: " + wbi.Bitmap.PixelFormat);
var c = new WIC.FormatConverter (factories.WICFactory);
c.Initialize (wbi.Bitmap, renderFormat);
//System.Diagnostics.Debug.WriteLine ("CO FORMAT: " + c.PixelFormat);
return D2D1.Bitmap.FromWicBitmap (renderTarget, c);
}
else {
return D2D1.Bitmap.FromWicBitmap (renderTarget, wbi.Bitmap);
}
}
throw new NotSupportedException ("Image type " + image.GetType () + " not supported");
}
D2D1.StrokeStyle GetStrokeStyle (Pen pen)
{
return null;
}
D2D1.Brush GetBrush (Pen pen)
{
if (pen == null) return null;
return new D2D1.SolidColorBrush (renderTarget, pen.Color.ToColor4 ());
}
D2D1.Brush GetBrush (Rect frame, Brush brush)
{
if (brush == null) return null;
var sb = brush as SolidBrush;
if (sb != null) {
return new D2D1.SolidColorBrush (renderTarget, sb.Color.ToColor4 ());
}
var lgb = brush as LinearGradientBrush;
if (lgb != null) {
if (lgb.Stops.Count < 2) return null;
var props = new D2D1.LinearGradientBrushProperties {
StartPoint = lgb.GetAbsoluteStart (frame).ToVector2 (),
EndPoint = lgb.GetAbsoluteEnd (frame).ToVector2 (),
};
return new D2D1.LinearGradientBrush (renderTarget, props, GetStops (lgb.Stops));
}
var rgb = brush as RadialGradientBrush;
if (rgb != null) {
if (rgb.Stops.Count < 2) return null;
var rad = rgb.GetAbsoluteRadius (frame);
var center = rgb.GetAbsoluteCenter (frame);
var focus = rgb.GetAbsoluteFocus (frame);
var props = new D2D1.RadialGradientBrushProperties {
Center = center.ToVector2 (),
RadiusX = (float)rad.Width,
RadiusY = (float)rad.Height,
GradientOriginOffset = (focus - center).ToVector2 (),
};
return new D2D1.RadialGradientBrush (renderTarget, props, GetStops (rgb.Stops));
}
// TODO: Radial gradient brushes
return new D2D1.SolidColorBrush (renderTarget, Colors.Black.ToColor4 ());
}
D2D1.GradientStopCollection GetStops (List<GradientStop> stops)
{
var q =
stops.
Select (s => new D2D1.GradientStop {
Color = s.Color.ToColor4 (),
Position = (float)s.Offset,
});
return new D2D1.GradientStopCollection (renderTarget, q.ToArray ());
}
}
public class Direct2DFactories
{
public readonly WIC.ImagingFactory WICFactory;
public readonly D2D1.Factory D2DFactory;
public readonly DW.Factory DWFactory;
//public readonly D2D1.DeviceContext _d2DDeviceContext;
public static readonly Direct2DFactories Shared = new Direct2DFactories ();
public Direct2DFactories ()
{
WICFactory = new WIC.ImagingFactory ();
DWFactory = new DW.Factory ();
var d3DDevice = new D3D11.Device (
D3D.DriverType.Hardware,
D3D11.DeviceCreationFlags.BgraSupport,
D3D.FeatureLevel.Level_11_1,
D3D.FeatureLevel.Level_11_0,
D3D.FeatureLevel.Level_10_1,
D3D.FeatureLevel.Level_10_0,
D3D.FeatureLevel.Level_9_3,
D3D.FeatureLevel.Level_9_2,
D3D.FeatureLevel.Level_9_1
);
var dxgiDevice = ComObject.As<SharpDX.DXGI.Device> (d3DDevice.NativePointer);
var d2DDevice = new D2D1.Device (dxgiDevice);
D2DFactory = d2DDevice.Factory;
//_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
//var dpi = DisplayDpi;
//_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
}
/*static float DisplayDpi
{
get
{
return Windows.Graphics.Display.DisplayInformation.GetForCurrentView ().LogicalDpi;
}
}*/
}
public static partial class Conversions
{
public static RawColor4 ToColor4 (this Color color)
{
return new RawColor4 ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
}
public static RawVector2 ToVector2 (this Point point)
{
return new RawVector2 { X = (float)point.X, Y = (float)point.Y };
}
public static Size2F ToSize2F (this Size size)
{
return new Size2F ((float)size.Width, (float)size.Height);
}
public static Size ToSize (this Size2F size)
{
return new Size (size.Width, size.Height);
}
public static Size ToSize (this Size2 size)
{
return new Size (size.Width, size.Height);
}
public static RawRectangleF ToRectangleF (this Rect rect)
{
return new RawRectangleF ((float)rect.X, (float)rect.Y, (float)rect.Right, (float)rect.Bottom);
}
public static RawRectangle ToRectangle (this Rect rect)
{
return new RawRectangle ((int)rect.X, (int)rect.Y, (int)rect.Right, (int)rect.Bottom);
}
}
}
| jomar/NGraphics | Platforms/NGraphics.UWP/Direct2DCanvas.cs | C# | mit | 15,250 |
import { CrossFade } from "../component/channel/CrossFade";
import { Gain } from "../core/context/Gain";
import { ToneAudioNode, ToneAudioNodeOptions } from "../core/context/ToneAudioNode";
import { NormalRange } from "../core/type/Units";
import { readOnly } from "../core/util/Interface";
import { Signal } from "../signal/Signal";
export interface EffectOptions extends ToneAudioNodeOptions {
wet: NormalRange;
}
/**
* Effect is the base class for effects. Connect the effect between
* the effectSend and effectReturn GainNodes, then control the amount of
* effect which goes to the output using the wet control.
*/
export abstract class Effect<Options extends EffectOptions>
extends ToneAudioNode<Options> {
readonly name: string = "Effect";
/**
* the drywet knob to control the amount of effect
*/
private _dryWet: CrossFade = new CrossFade({ context: this.context });
/**
* The wet control is how much of the effected
* will pass through to the output. 1 = 100% effected
* signal, 0 = 100% dry signal.
*/
wet: Signal<"normalRange"> = this._dryWet.fade;
/**
* connect the effectSend to the input of hte effect
*/
protected effectSend: Gain = new Gain({ context: this.context });
/**
* connect the output of the effect to the effectReturn
*/
protected effectReturn: Gain = new Gain({ context: this.context });
/**
* The effect input node
*/
input: Gain = new Gain({ context: this.context });
/**
* The effect output
*/
output = this._dryWet;
constructor(options: EffectOptions) {
super(options);
// connections
this.input.fan(this._dryWet.a, this.effectSend);
this.effectReturn.connect(this._dryWet.b);
this.wet.setValueAtTime(options.wet, 0);
this._internalChannels = [this.effectReturn, this.effectSend];
readOnly(this, "wet");
}
static getDefaults(): EffectOptions {
return Object.assign(ToneAudioNode.getDefaults(), {
wet: 1,
});
}
/**
* chains the effect in between the effectSend and effectReturn
*/
protected connectEffect(effect: ToneAudioNode | AudioNode): this {
// add it to the internal channels
this._internalChannels.push(effect);
this.effectSend.chain(effect, this.effectReturn);
return this;
}
dispose(): this {
super.dispose();
this._dryWet.dispose();
this.effectSend.dispose();
this.effectReturn.dispose();
this.wet.dispose();
return this;
}
}
| TONEnoTONE/Tone.js | Tone/effect/Effect.ts | TypeScript | mit | 2,380 |
<?php
// MyCompanyMyProjectAppBundle:PamAnnee:pam_annee.html.twig
return array (
'57785d6' =>
array (
0 =>
array (
0 => '@MyCompanyMyProjectAppBundle/Resources/public/css/*',
),
1 =>
array (
),
2 =>
array (
'output' => '_controller/css/57785d6.css',
'name' => '57785d6',
'debug' => NULL,
'combine' => NULL,
),
),
);
| ithone/pam | app/cache/test/assetic/config/8/893ed526d3434cba6346aea7f89bd4c1.php | PHP | mit | 393 |
require 'shellwords'
require 'travis/build/script/shared/bundler'
require 'travis/build/script/shared/chruby'
require 'travis/build/script/shared/rvm'
module Travis
module Build
class Script
class ObjectiveC < Script
DEFAULTS = {
rvm: 'default',
gemfile: 'Gemfile',
podfile: 'Podfile',
}
include RVM
include Bundler
def announce
super
sh.fold 'announce' do
sh.cmd 'xcodebuild -version -sdk'
sh.cmd 'xctool -version'
sh.cmd 'xcrun simctl list'
end
sh.if use_ruby_motion do
sh.cmd 'motion --version'
end
sh.if podfile? do
sh.cmd 'pod --version'
end
end
def export
super
[:sdk, :scheme, :project, :workspace].each do |key|
sh.export "TRAVIS_XCODE_#{key.upcase}", config[:"xcode_#{key}"].to_s.shellescape, echo: false
end
end
def setup_cache
return unless use_directory_cache?
super
sh.if podfile? do
sh.echo ''
if data.cache?(:cocoapods)
sh.fold 'cache.cocoapods' do
sh.echo ''
directory_cache.add("#{pod_dir}/Pods")
end
end
end
end
def install
super
sh.if podfile? do
sh.if "! ([[ -f #{pod_dir}/Podfile.lock && -f #{pod_dir}/Pods/Manifest.lock ]] && cmp --silent #{pod_dir}/Podfile.lock #{pod_dir}/Pods/Manifest.lock)", raw: true do
sh.fold('install.cocoapods') do
sh.echo "Installing Pods with 'pod install'", ansi: :yellow
sh.cmd "pushd #{pod_dir}"
sh.cmd 'pod install', retry: true
sh.cmd 'popd'
end
end
end
end
def script
sh.if use_ruby_motion(with_bundler: true) do
sh.cmd 'bundle exec rake spec'
end
sh.elif use_ruby_motion do
sh.cmd 'rake spec'
end
sh.else do
if config[:xcode_scheme] && (config[:xcode_project] || config[:xcode_workspace])
sh.cmd "xctool #{xctool_args} build test"
else
# deprecate DEPRECATED_MISSING_WORKSPACE_OR_PROJECT
sh.cmd "echo -e \"\\033[33;1mWARNING:\\033[33m Using Objective-C testing without specifying a scheme and either a workspace or a project is deprecated.\"", echo: false, timing: true
sh.cmd "echo \" Check out our documentation for more information: http://about.travis-ci.org/docs/user/languages/objective-c/\"", echo: false, timing: true
end
end
end
def use_directory_cache?
super || data.cache?(:cocoapods)
end
private
def podfile?
"-f #{config[:podfile].to_s.shellescape}"
end
def pod_dir
File.dirname(config[:podfile]).shellescape
end
def use_ruby_motion(options = {})
condition = '-f Rakefile && "$(cat Rakefile)" =~ require\ [\\"\\\']motion/project'
condition << ' && -f Gemfile' if options.delete(:with_bundler)
condition
end
def xctool_args
config[:xctool_args].to_s.tap do |xctool_args|
%w[project workspace scheme sdk].each do |var|
xctool_args << " -#{var} #{config[:"xcode_#{var}"].to_s.shellescape}" if config[:"xcode_#{var}"]
end
end.strip
end
# DEPRECATED_MISSING_WORKSPACE_OR_PROJECT = <<-msg
# Using Objective-C testing without specifying a scheme and either a workspace or a project is deprecated.
# Check out our documentation for more information: http://about.travis-ci.org/docs/user/languages/objective-c/
# msg
end
end
end
end
| jhass/travis-build | lib/travis/build/script/objective_c.rb | Ruby | mit | 3,999 |
import React, { Component } from 'react';
import NavLink from './NavLink';
import './Menu.css';
class Menu extends Component {
componentDidMount() {
this.hideMenu = this.hideMenu.bind(this);
this.menuIcon = document.querySelector('.menu__icon');
this.menu = document.querySelector('.menu');
this.menuOverlay = document.querySelector('.menu__overlay');
this.bindNavigation();
}
componentWillReceiveProps(nextProps) {
if (nextProps.isMenuOpen) {
this.showMenu();
}
}
toggleMenu() {
if (!this.isMenuOpen()) {
this.showMenu();
}
else {
this.hideMenu();
}
}
isMenuOpen() {
return this.menu.classList.contains('menu--show');
}
hideMenu() {
this.menu.classList.remove('menu--show');
this.menuOverlay.classList.remove('menu__overlay--show');
}
showMenu() {
this.menu.classList.add('menu--show');
this.menuOverlay.classList.add('menu__overlay--show');
}
bindNavigation() {
document.body.addEventListener('keyup', (event) => {
let menuListElement = document.querySelector('.menu__list a.active').parentElement;
if (event.key === 'ArrowLeft') {
let activeSiblingElement = menuListElement.previousElementSibling;
if (activeSiblingElement && activeSiblingElement.children) {
menuListElement.previousElementSibling.children[0].click();
}
}
else if (event.key === 'ArrowRight') {
let activeSiblingElement = menuListElement.nextElementSibling;
if (activeSiblingElement && activeSiblingElement.children) {
activeSiblingElement.children[0].click();
}
}
});
}
render() {
return (
<div className="menu-container">
<div className="menu">
<div className="menu__header">
<h2>Workshop 1</h2>
</div>
<ul className="menu__list">
<li>
<NavLink to="/prerequisites">
<span className="menu__steps">0</span>
Prerequisites
</NavLink>
</li>
<li>
<NavLink to="/introduction" onlyActiveOnIndex={true}>
<span className="menu__steps">1</span>
Introduction
</NavLink>
</li>
<li>
<NavLink to="/setup">
<span className="menu__steps">2</span>
Setup
</NavLink>
</li>
<li>
<NavLink to="/up-and-running">
<span className="menu__steps">3</span>
Up & Running
</NavLink>
</li>
<li>
<NavLink to="/components">
<span className="menu__steps">4</span>
Components
</NavLink>
</li>
<li>
<NavLink to="/routing">
<span className="menu__steps">5</span>
Routing
</NavLink>
</li>
<li>
<NavLink to="/fetching-data">
<span className="menu__steps">6</span>
Fetching Data
</NavLink>
</li>
<li>
<NavLink to="/styles">
<span className="menu__steps">7</span>
Styles
</NavLink>
</li>
<li>
<NavLink to="/homework">
<span className="menu__steps">8</span>
Homework
</NavLink>
</li>
</ul>
<div className="menu__header">
<h2>Workshop 2</h2>
</div>
<ul className="menu__list">
<li>
<NavLink to="/recap">
<span className="menu__steps">9</span>
Recap
</NavLink>
</li>
<li>
<NavLink to="/architecture">
<span className="menu__steps">10</span>
The App, Architecture
</NavLink>
</li>
<li>
<NavLink to="/back-to-fundamentals">
<span className="menu__steps">11</span>
Back to fundamentals
</NavLink>
</li>
<li>
<NavLink to="/component-design">
<span className="menu__steps">12</span>
Component Design
</NavLink>
</li>
<li>
<NavLink to="/airbnb-map-view">
<span className="menu__steps">13</span>
Airbnb Map View
</NavLink>
</li>
<li>
<NavLink to="/on-your-own">
<span className="menu__steps">14</span>
On your own
</NavLink>
</li>
</ul>
<div className="menu__header">
<h2>Workshop 3</h2>
</div>
<ul className="menu__list">
<li>
<NavLink to="/recap-two">
<span className="menu__steps">15</span>
Recap
</NavLink>
</li>
<li>
<NavLink to="/search-ui">
<span className="menu__steps">16</span>
Search UI
</NavLink>
</li>
<li>
<NavLink to="/map-ui">
<span className="menu__steps">17</span>
Map UI
</NavLink>
</li>
<li>
<NavLink to="/list-item-detail">
<span className="menu__steps">18</span>
List Item Detail View
</NavLink>
</li>
<li>
<NavLink to="/on-your-own-two">
<span className="menu__steps">19</span>
On Your Own
</NavLink>
</li>
<div className="menu__header">
<h2>Workshop 4</h2>
</div>
<li>
<NavLink to="/recap-three">
<span className="menu__steps">20</span>
Recap
</NavLink>
</li>
<li>
<NavLink to="/state-management">
<span className="menu__steps">21</span>
State Management
</NavLink>
</li>
<li>
<NavLink to="/the-api">
<span className="menu__steps">22</span>
The Bar Finder API
</NavLink>
</li>
<li>
<NavLink to="/reorganize">
<span className="menu__steps">23</span>
Let's Get Started
</NavLink>
</li>
<li>
<NavLink to="/store-setup">
<span className="menu__steps">24</span>
Store Setup
</NavLink>
</li>
<li>
<NavLink to="/home-screen">
<span className="menu__steps">25</span>
Home Screen
</NavLink>
</li>
<li>
<NavLink to="/map-screen">
<span className="menu__steps">26</span>
Map Screen
</NavLink>
</li>
<li>
<NavLink to="/congrats">
<span className="menu__steps">27</span>
Congratulations!
</NavLink>
</li>
</ul>
</div>
<div className="menu__overlay" onClick={this.hideMenu}></div>
</div>
);
}
}
export default Menu;
Menu.defaultProps = {
isMenuOpen: false
};
| gufsky/react-native-workshop | src/Menu.js | JavaScript | mit | 7,711 |
var HelloComponent = React.createClass(
{
render: function()
{
var el = (
<div>
Hello
<ChildrenComponent/>
</div>
);
return el;
}
});
var ChildrenComponent = React.createClass(
{
render: function()
{
var elArray = [<ChildComponent/>,<ChildComponent/>,<ChildComponent/>];
var el = (<div>{elArray}</div>);
return el;
}
});
var ChildComponent = React.createClass(
{
render: function()
{
var el = (<div>child</div>);
return el;
}
});
var mount = React.render(<HelloComponent/>, document.body);
| kenokabe/react-abc | www/react01-2.js | JavaScript | mit | 607 |
module Fudge
module Tasks
# Allow use of Flay complexity analyser
#
# task :flay
#
# runs flay with max score of 0
#
# task :flay, :exclude => 'subpath/'
#
# excludes files matching :exclude from run
#
# task :flay, :max => 20
#
# sets max score to 20
#
# Any and all options can be defined
#
class Flay < Shell
include Helpers::BundleAware
private
def cmd(options={})
bundle_cmd(flay_ruby_files, options)
end
def flay_ruby_files
finder = FileFinder.new(options)
finder.generate_command("flay", tty_options)
end
def check_for
[check_regex, method(:flay_checker)]
end
def check_regex
/Total score \(lower is better\) = (?<score>\d+)/
end
def flay_checker(matches)
score = matches[:score].to_i
if score > max_score
"Duplication Score Higher Than #{max_score}"
else
true
end
end
def max_score
options.fetch(:max, 0)
end
def tty_options
opts = []
opts << "--diff"
opts
end
end
register Flay
end
end
| Sage/fudge | lib/fudge/tasks/flay.rb | Ruby | mit | 1,214 |
{
matrix_id: '1665',
name: 'fome11',
group: 'Mittelmann',
description: 'Linear programming problem (H. Mittelmann test set)',
author: '',
editor: 'H. Mittelmann',
date: '2005',
kind: 'linear programming problem',
problem_2D_or_3D: '0',
num_rows: '12142',
num_cols: '24460',
nonzeros: '71264',
num_explicit_zeros: '0',
num_strongly_connected_components: '2',
num_dmperm_blocks: '1',
structural_full_rank: 'true',
structural_rank: '12142',
pattern_symmetry: '0.000',
numeric_symmetry: '0.000',
rb_type: 'real',
structure: 'rectangular',
cholesky_candidate: 'no',
positive_definite: 'no',
notes: 'Hans Mittelmann test set, http://plato.asu.edu/ftp/lptestset
minimize c\'*x, subject to A*x=b and lo <= x <= hi
',
b_field: 'full 12142-by-1
',
aux_fields: 'c: full 24460-by-1
lo: full 24460-by-1
hi: full 24460-by-1
z0: full 1-by-1
', norm: '1.591695e+01',
min_singular_value: '4.598797e-16',
condition_number: '34611119861164224',
svd_rank: '12116',
sprank_minus_rank: '26',
null_space_dimension: '26',
full_numerical_rank: 'no',
svd_gap: '28859823003685.242188',
image_files: 'fome11.png,fome11_scc.png,fome11_svd.png,fome11_graph.gif,',
}
| ScottKolo/suitesparse-matrix-collection-website | db/collection_data/matrices/Mittelmann/fome11.rb | Ruby | mit | 1,286 |
/**
* EmailController
* @namespace kalendr.email.controllers
*/
(function () {
'use strict';
angular
.module('kalendr.email.controllers')
.controller('EmailController', EmailController);
EmailController.$inject = ['$rootScope', '$scope', 'Authentication', 'Snackbar', 'Email'];
/**
* @namespace EnmasseController
*/
function EmailController($rootScope, $scope, Authentication, Snackbar, Email) {
var vm = this;
vm.submit = submit;
function submit() {
var format;
if (vm.email_type == 'PDF') {
format = 1;
} else {
format = 0;
}
Email.create(vm.start_date, vm.end_date, format).then(emailSuccess, emailError);
$scope.closeThisDialog();
function emailSuccess(data, status, headers, config) {
Snackbar.show('Success! Email sent');
}
function emailError(data, status, headers, config) {
Snackbar.error(data.error);
}
}
}
})
();
| bewallyt/Kalendr | static/javascripts/email/controllers/new-email.controller.js | JavaScript | mit | 1,102 |
// @flow
import URLSearchParams from 'url-search-params'; // a polyfill for IE
type LocationType = {
hash: string,
pathname: string,
search: Object
};
export function getLocationParts(loc: LocationType) {
return {
hash: loc.hash.substring(1),
path: loc.pathname,
query: new URLSearchParams(loc.search),
};
}
| mvolkmann/starter | src/util/hash-route.js | JavaScript | mit | 333 |
<?
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Model_AttributeKeyCategory extends Object {
const ASET_ALLOW_NONE = 0;
const ASET_ALLOW_SINGLE = 1;
const ASET_ALLOW_MULTIPLE = 2;
public static function getByID($akCategoryID) {
$db = Loader::db();
$row = $db->GetRow('select akCategoryID, akCategoryHandle, akCategoryAllowSets, pkgID from AttributeKeyCategories where akCategoryID = ?', array($akCategoryID));
if (isset($row['akCategoryID'])) {
$akc = new AttributeKeyCategory();
$akc->setPropertiesFromArray($row);
return $akc;
}
}
public static function getByHandle($akCategoryHandle) {
$db = Loader::db();
$row = $db->GetRow('select akCategoryID, akCategoryHandle, akCategoryAllowSets, pkgID from AttributeKeyCategories where akCategoryHandle = ?', array($akCategoryHandle));
if (isset($row['akCategoryID'])) {
$akc = new AttributeKeyCategory();
$akc->setPropertiesFromArray($row);
return $akc;
}
}
public function handleExists($akHandle) {
$db = Loader::db();
$r = $db->GetOne("select count(akID) from AttributeKeys where akHandle = ? and akCategoryID = ?", array($akHandle, $this->akCategoryID));
return $r > 0;
}
public static function exportList($xml) {
$attribs = self::getList();
$axml = $xml->addChild('attributecategories');
foreach($attribs as $akc) {
$acat = $axml->addChild('category');
$acat->addAttribute('handle', $akc->getAttributeKeyCategoryHandle());
$acat->addAttribute('allow-sets', $akc->allowAttributeSets());
$acat->addAttribute('package', $akc->getPackageHandle());
}
}
public function getAttributeKeyByHandle($akHandle) {
if ($this->pkgID > 0) {
Loader::model('attribute/categories/' . $this->akCategoryHandle, $this->getPackageHandle());
} else {
Loader::model('attribute/categories/' . $this->akCategoryHandle);
}
$txt = Loader::helper('text');
$className = $txt->camelcase($this->akCategoryHandle);
$c1 = $className . 'AttributeKey';
$ak = call_user_func(array($c1, 'getByHandle'), $akHandle);
return $ak;
}
public function getAttributeKeyByID($akID) {
if ($this->pkgID > 0) {
Loader::model('attribute/categories/' . $this->akCategoryHandle, $this->getPackageHandle());
} else {
Loader::model('attribute/categories/' . $this->akCategoryHandle);
}
$txt = Loader::helper('text');
$className = $txt->camelcase($this->akCategoryHandle);
$c1 = $className . 'AttributeKey';
$ak = call_user_func(array($c1, 'getByID'), $akID);
return $ak;
}
public function getUnassignedAttributeKeys() {
$db = Loader::db();
$r = $db->Execute('select AttributeKeys.akID from AttributeKeys left join AttributeSetKeys on AttributeKeys.akID = AttributeSetKeys.akID where asID is null and akIsInternal = 0 and akCategoryID = ?', $this->akCategoryID);
$keys = array();
$cat = AttributeKeyCategory::getByID($this->akCategoryID);
while ($row = $r->FetchRow()) {
$keys[] = $cat->getAttributeKeyByID($row['akID']);
}
return $keys;
}
public static function getListByPackage($pkg) {
$db = Loader::db();
$list = array();
$r = $db->Execute('select akCategoryID from AttributeKeyCategories where pkgID = ? order by akCategoryID asc', array($pkg->getPackageID()));
while ($row = $r->FetchRow()) {
$list[] = AttributeKeyCategory::getByID($row['akCategoryID']);
}
$r->Close();
return $list;
}
public function getAttributeKeyCategoryID() {return $this->akCategoryID;}
public function getAttributeKeyCategoryHandle() {return $this->akCategoryHandle;}
public function getPackageID() {return $this->pkgID;}
public function getPackageHandle() {return PackageList::getHandle($this->pkgID);}
public function allowAttributeSets() {return $this->akCategoryAllowSets;}
public function setAllowAttributeSets($val) {
$db = Loader::db();
$db->Execute('update AttributeKeyCategories set akCategoryAllowSets = ? where akCategoryID = ?', array($val, $this->akCategoryID));
$this->akCategoryAllowSets = $val;
}
public function getAttributeSets() {
$db = Loader::db();
$r = $db->Execute('select asID from AttributeSets where akCategoryID = ? order by asDisplayOrder asc, asID asc', $this->akCategoryID);
$sets = array();
while ($row = $r->FetchRow()) {
$sets[] = AttributeSet::getByID($row['asID']);
}
return $sets;
}
public function clearAttributeKeyCategoryColumnHeaders() {
$db = Loader::db();
$db->Execute('update AttributeKeys set akIsColumnHeader = 0 where akCategoryID = ?', $this->akCategoryID);
}
public function associateAttributeKeyType($at) {
if (!$this->hasAttributeKeyTypeAssociated($at)) {
$db = Loader::db();
$db->Execute('insert into AttributeTypeCategories (atID, akCategoryID) values (?, ?)', array($at->getAttributeTypeID(), $this->akCategoryID));
}
}
public function hasAttributeKeyTypeAssociated($at) {
$db = Loader::db();
$r = $db->getOne('select atID from AttributeTypeCategories where atID = ? and akCategoryID = ?', array($at->getAttributeTypeID(), $this->akCategoryID));
return (boolean) $r;
}
public function clearAttributeKeyCategoryTypes() {
$db = Loader::db();
$db->Execute('delete from AttributeTypeCategories where akCategoryID = ?', $this->akCategoryID);
}
/**
* note, this does not remove anything but the direct data associated with the category
*/
public function delete() {
$db = Loader::db();
$this->clearAttributeKeyCategoryTypes();
$this->clearAttributeKeyCategoryColumnHeaders();
$this->rescanSetDisplayOrder();
$db->Execute('delete from AttributeKeyCategories where akCategoryID = ?', $this->akCategoryID);
}
public static function getList() {
$db = Loader::db();
$cats = array();
$r = $db->Execute('select akCategoryID from AttributeKeyCategories order by akCategoryID asc');
while ($row = $r->FetchRow()) {
$cats[] = AttributeKeyCategory::getByID($row['akCategoryID']);
}
return $cats;
}
public static function add($akCategoryHandle, $akCategoryAllowSets = AttributeKeyCategory::ASET_ALLOW_NONE, $pkg = false) {
$db = Loader::db();
if (is_object($pkg)) {
$pkgID = $pkg->getPackageID();
}
$db->Execute('insert into AttributeKeyCategories (akCategoryHandle, akCategoryAllowSets, pkgID) values (?, ?, ?)', array($akCategoryHandle, $akCategoryAllowSets, $pkgID));
$id = $db->Insert_ID();
if ($pkgID > 0) {
Loader::model('attribute/categories/' . $akCategoryHandle, $pkg->getPackageHandle());
} else {
Loader::model('attribute/categories/' . $akCategoryHandle);
}
$txt = Loader::helper("text");
$class = $txt->camelcase($akCategoryHandle) . 'AttributeKey';
$obj = new $class;
$obj->createIndexedSearchTable();
return AttributeKeyCategory::getByID($id);
}
public function addSet($asHandle, $asName, $pkg = false, $asIsLocked = 1) {
if ($this->akCategoryAllowSets > AttributeKeyCategory::ASET_ALLOW_NONE) {
$db = Loader::db();
$pkgID = 0;
if (is_object($pkg)) {
$pkgID = $pkg->getPackageID();
}
$sets = $db->GetOne('select count(asID) from AttributeSets where akCategoryID = ?', array($this->akCategoryID));
$asDisplayOrder = 0;
if ($sets > 0) {
$asDisplayOrder = $db->GetOne('select max(asDisplayOrder) from AttributeSets where akCategoryID = ?', array($this->akCategoryID));
$asDisplayOrder++;
}
$db->Execute('insert into AttributeSets (asHandle, asName, akCategoryID, asIsLocked, asDisplayOrder, pkgID) values (?, ?, ?, ?, ?,?)', array($asHandle, $asName, $this->akCategoryID, $asIsLocked, $asDisplayOrder, $pkgID));
$id = $db->Insert_ID();
$as = AttributeSet::getByID($id);
return $as;
}
}
protected function rescanSetDisplayOrder() {
$db = Loader::db();
$do = 1;
$r = $db->Execute('select asID from AttributeSets where akCategoryID = ? order by asDisplayOrder asc, asID asc', $this->getAttributeKeyCategoryID());
while ($row = $r->FetchRow()) {
$db->Execute('update AttributeSetKeys set displayOrder = ? where asID = ?', array($do, $row['asID']));
$do++;
}
}
public function updateAttributeSetDisplayOrder($uats) {
$db = Loader::db();
for ($i = 0; $i < count($uats); $i++) {
$v = array($this->getAttributeKeyCategoryID(), $uats[$i]);
$db->query("update AttributeSets set asDisplayOrder = {$i} where akCategoryID = ? and asID = ?", $v);
}
}
}
| RogerKok/concrete5.6.3 | concrete/core/models/attribute/category.php | PHP | mit | 8,316 |
using System;
using MongoDB.Driver;
using NetDevPL.Infrastructure.MongoDB;
namespace NetDevPL.Features.NetGroups
{
public class Repository
{
readonly MongoDBProvider<NetGroupDataSnapshot> provider = new MongoDBProvider<NetGroupDataSnapshot>("netdevpl", "netGroupsSnapshot");
public NetGroupDataSnapshot GetGroups()
{
return provider.Collection.Find(d => true).SortByDescending(d => d.SnapshotDate).Limit(1).FirstOrDefault() ?? NetGroupDataSnapshot.Create();
}
public void Add(NetGroupDataSnapshot snapshot)
{
provider.Collection.InsertOne(snapshot);
}
}
} | soltys/NetDevPLWebsite | src/Features/NetDevPL.Features.NetGroups/Repository.cs | C# | mit | 653 |
package net.fortytwo.smsn.brain.rdf.classes;
import net.fortytwo.smsn.brain.rdf.SimpleAtomClass;
import java.util.regex.Pattern;
public class AKAReference extends SimpleAtomClass {
public AKAReference() {
super(
"aka",
// TODO: the foaf:nick mapping is not quite appropriate to the "brand/trade name" and "formerly" usage
Pattern.compile("(aka|brand name|trade name|formerly) \\\"[^\\\"]+\\\"(, \\\"[^\\\"]+\\\")*"),
null,
null
);
}
public static String extractAlias(final String value) {
int i = value.indexOf('\"');
int j = value.lastIndexOf('\"');
return value.substring(i + 1, j);
}
}
| joshsh/extendo | brain/src/main/java/net/fortytwo/smsn/brain/rdf/classes/AKAReference.java | Java | mit | 738 |
FCKLang.InsertCodeBtn = 'Insert Code' ;
| poppastring/dasblog | source/newtelligence.DasBlog.Contrib.FCKeditor/FCKeditor/editor/plugins/insertcode/lang/en.js | JavaScript | mit | 45 |
'use strict';
var grunt = require('grunt');
var jshint = require('../tasks/lib/jshint').init(grunt);
// In case the grunt being used to test is different than the grunt being
// tested, initialize the task and config subsystems.
if (grunt.task.searchDirs.length === 0) {
grunt.task.init([]);
grunt.config.init({});
}
exports['jshint'] = function(test) {
test.expect(1);
grunt.log.muted = true;
test.doesNotThrow(function() {
jshint.lint(grunt.file.read('test/fixtures/lint.txt'));
}, 'It should not blow up if an error occurs on character 0.');
test.done();
};
| jadedsurfer/genx | node_modules/grunt/node_modules/grunt-contrib-jshint/test/jshint_test.js | JavaScript | mit | 584 |
from ..output import outputfile, outputstr
from ..utils import multiple_index, limit_text
from ..utils import _index_function_gen, asciireplace, generate_func, generate_func_any, ROW_OBJ
from ..exceptions.messages import ApiObjectMsg as msg
from types import FunctionType
from tabulate import tabulate
from threading import RLock
SelectionLock = RLock()
NonHashMergeLock = RLock()
class Selection(object):
__slots__ = ["__rows__", "__apimother__"]
def __init__(self, selection, api_mother):
self.__rows__ = (selection)
self.__apimother__ = api_mother
def __add__(self, sel):
return Selection((
tuple(self.rows) + tuple(sel.rows)), self.__apimother__)
def __len__(self):
return len(self.rows)
def __getitem__(self, v):
if isinstance(v, slice):
return Selection(self.rows[v], self.__apimother__)
if isinstance(v, int):
return (self.rows[v])
elif isinstance(v, str):
return (x.getcolumn(v) for x in self.rows)
elif isinstance(v, tuple):
return (multiple_index(x, v) for x in self.rows)
elif isinstance(v, FunctionType):
return Selection(_index_function_gen(self, v), self.__apimother__)
else:
raise TypeError(msg.getitemmsg.format(type(v)))
@property
def rows(self):
if not isinstance(self.__rows__, tuple):
self.process()
return self.__rows__
else:
return self.__rows__
def process(self):
"""Processes the Selection, then returns it
Use this if chaining selections but you still need the parent
for later usage. Or if their are mulitple chains from the
same parent selection
"""
if not isinstance(self.__rows__, tuple):
with SelectionLock:
self.__rows__ = tuple(self.__rows__)
return self
@property
def columns(self):
return self.__apimother__.columns
@property
def __columnsmap__(self):
return self.__apimother__.__columnsmap__
@property
def columns_mapping(self):
return {v:k for k,v in self.__columnsmap__.items()}
@property
def columns_attributes(self):
return list(self.__columnsmap__.keys())
@property
def addcolumn(self):
"""Adds a column
:param columnname: Name of the column to add.
:param columndata: The default value of the new column.
:param add_to_columns: Determines whether this column should
be added to the internal tracker.
:type columnname: :class:`str`
:type add_to_columns: :class:`bool`
Note: Rows that are being accessed by another thread will error out
if accessed during the brief time addcolumn is updating.
Note: This will affect the entire MainSelection, not just this
selection
"""
return self.__apimother__.addcolumn
@property
def delcolumn(self):
return self.__apimother__.delcolumn
@property
def rename_column(self):
return self.__apimother__.rename_column
def transform(self, column, func):
for row in self.rows:
row.setcolumn(column, func(row.getcolumn(column)))
return self
def _merge(self, args):
maps = []
for con in (self,) + args:
maps.append({(x.__hashvalue__()):x for x in con.rows})
master = {}
for d in maps:
master.update(d)
keys = set(master.keys())
for key in keys:
yield master[key]
def merge(self, *args, force_safety=True):
"""Merges selections
Note: This merge's algorithm relies on the uniqueness of the rows.
duplicate rows will be only represented by 1 row.
Note: This Merge relies on all data in a row being hashable, use non_hash_merge if you
can't guarantee this.
"""
try:
if force_safety:
if (not all(self.__apimother__ is x.__apimother__ for x in args)):
raise ValueError("Merge by default only accepts rows from same origin")
return Selection(tuple(self._merge(args)), self.__apimother__)
except TypeError as exc:
raise TypeError(
"{} - Use the non_hash_merge to merge rows with non-hashable datatypes.".format(exc))
def safe_merge(self, *args):
"""This is much slower but is hashes rows as processed instead of preprocessing them"""
out = self
for x in args:
out = out + x
return out
def non_hash_merge(self, *args):
"""This merge uses the exploits the __output__ flag of a row instead of it's hashed contents
This allows merging of of rows that contain unhashable mutable data such as sets or dict.
This doesn't remove duplicate rows but is slightly faster and can handle all datatyps.
Note: This merge is effectively single-threaded and editing the outputflag during
running will effect results of the merge and may have unattended conquences on the
state of this selection.
"""
with NonHashMergeLock:
if not all(self.__apimother__ is x.__apimother__ for x in args):
raise ValueError("non_hash_merge only accepts rows from same origin")
outputstore = tuple(x.__output__ for x in self.__apimother__)
self.__apimother__.no_output()
for x in ((self,) + args):
for row in x:
+row
result = self.__apimother__.outputtedrows
for x, row in zip(outputstore, self.__apimother__.rows):
if x:
+row
else:
-row
return result
def _find_all(self, func):
for x in self.rows:
if func(x):
yield x
def single_find(self, selectionfirstarg_data=None, **kwargs):
"""Find a single row based off search criteria given.
will raise error if returns more than one result'"""
try:
result = None
func = generate_func(selectionfirstarg_data, kwargs)
g = self._find_all(func)
result = next(g)
next(g)
raise ValueError(msg.singlefindmsg)
except StopIteration:
return result
def single_find_any(self, selectionfirstarg_data=None, **kwargs):
"""Find a single row based off search criteria given.
Only one condition needs to be Trues.
will raise error if returns more than one result"""
try:
result = None
func = generate_func_any(selectionfirstarg_data, kwargs)
g = self._find_all(func)
result = next(g)
next(g)
raise ValueError(msg.singlefindmsg)
except StopIteration:
return result
def find(self, selectionfirstarg_data=None, **kwargs):
try:
func = generate_func(selectionfirstarg_data, kwargs)
g = self._find_all(func)
return next(g)
except StopIteration:
return None
def find_any(self, selectionfirstarg_data=None, **kwargs):
try:
func = generate_func_any(selectionfirstarg_data, kwargs)
g = self._find_all(func)
return next(g)
except StopIteration:
return None
def fast_find(self, **kwargs):
"""Much faster find. Returns the last row the fulfilled any kwargs. Only accept one kwargs.
Note: All keynames must be unique to be used effectively, else latest row will be returned"""
if len(kwargs) != 1:
raise ValueError(msg.badfastfind)
k, v = tuple(kwargs.items())[0]
index_value = self.index(k)
return index_value.get(v)
def find_all(self, selectionfirstarg_data=None, **kwargs):
func = generate_func(selectionfirstarg_data, kwargs)
return tuple(self._find_all(func))
def find_all_any(self, selectionfirstarg_data=None, **kwargs):
func = generate_func_any(selectionfirstarg_data, kwargs)
return tuple(self._find_all(func))
def flip_output(self):
"""flips all output boolean for all rows in this selection"""
for x in self.rows:
~x
return self
def no_output(self):
"""Sets all rows to not output"""
for x in self.rows:
-x
return self
def all_output(self):
"""Sets all rows to output"""
for x in self.rows:
+x
return self
def lenoutput(self):
return len(tuple(filter(lambda x: x.outputrow, self.rows)))
def len_no_output(self):
return len(tuple(filter(lambda x: not x.outputrow, self.rows)))
def enable(self, selectionfirstarg_data=None, **kwargs):
v = generate_func(selectionfirstarg_data, kwargs)
for x in self.rows:
if bool(v(x)):
+x
return self
def disable(self, selectionfirstarg_data=None, **kwargs):
v = generate_func(selectionfirstarg_data, kwargs)
for x in self.rows:
if bool(v(x)):
-x
return self
def flip(self, selectionfirstarg_data=None, **kwargs):
v = generate_func(selectionfirstarg_data, kwargs)
for x in self.rows:
if bool(v(x)):
~x
return self
def select(self, selectionfirstarg_data=None, **kwargs):
"""Method for selecting part of the csv document.
generates a function based of the parameters given.
All conditions must be true for a row to be selected
Uses Lazy Loading, doesn't process till needed.
"""
if not selectionfirstarg_data and not kwargs:
return Selection(self.__rows__, self.__apimother__)
func = generate_func(selectionfirstarg_data, kwargs)
return self[func]
def any(self, selectionfirstarg_data=None, **kwargs):
"""Method for selecting part of the csv document.
generates a function based of the parameters given.
only one condition must be True for the row to be
selected.
Uses Lazy Loading, doesn't process till needed.
"""
if not selectionfirstarg_data and not kwargs:
return Selection(self.__rows__, self.__apimother__)
func = generate_func_any(selectionfirstarg_data, kwargs)
return self[func]
def safe_select(self, selectionfirstarg_data=None, **kwargs):
"""Method for selecting part of the csv document.
generates a function based off the parameters given.
This instantly processes the select instead of
lazily loading it at a later time.
Preventing race conditions under most uses cases.
if the same select is being worked on in multiple
threads or other cases such as rows being edited
before the selected is processed.
"""
if not selectionfirstarg_data and not kwargs:
return Selection(self.__rows__, self.__apimother__)
func = generate_func(selectionfirstarg_data, kwargs)
return self._safe_select(func)
def safe_any(self, selectionfirstarg_data=None, **kwargs):
"""Method for selecting part of the csv document.
generates a function based off the parameters given.
only one condition must be True for the row to be selected.
This instantly processes the select instead of
lazily loading it at a later time.
Preventing race conditions under most uses cases.
if the same select is being worked on in multiple
threads or other cases such as rows being edited
before the selected is processed.
"""
if not selectionfirstarg_data and not kwargs:
return Selection(self.__rows__, self.__apimother__)
func = generate_func_any(selectionfirstarg_data, kwargs)
return self._safe_select(func)
def grab(self, *args):
"""Grabs specified columns from every row
:returns: :class:`tuple` of the result.
"""
arg = tuple(args)
if len(arg) > 1:
return tuple(self[arg])
elif len(arg) == 1:
return tuple(self[arg[0]])
else:
raise ValueError(msg.badgrab)
def remove_duplicates(self, soft=True):
"""Removes duplicates rows
if soft is true, return a selection
else: edit this object
Note: All rows must contain hashable data
"""
if soft:
return self.merge(self)
else:
self.__rows__ = self.merge(self).rows
def unique(self, *args):
"""Grabs specified columns from every row
:returns: :class:`set` of the result.
"""
arg = tuple(args)
if len(arg) > 1:
return set(self[arg])
elif len(arg) == 1:
return set(self[arg[0]])
else:
raise ValueError(msg.badgrab)
def _safe_select(self, func):
return Selection(tuple(_index_function_gen(self, func)), self.__apimother__)
def index(self, keyname, keyvalue=None):
""" Indexs a Column to a dict """
if keyvalue is None:
return dict(self[keyname, ROW_OBJ])
else:
return dict(self[keyname, keyvalue])
@property
def outputtedrows(self):
return self.safe_select(lambda x: x.outputrow)
@property
def nonoutputtedrows(self):
return self.safe_select(lambda x: not x.outputrow)
def tabulate(self, limit=100, format="grid", only_ascii=True,
columns=None, text_limit=None, remove_newline=True):
data = [x.longcolumn() for x in self.rows[:limit]]
sortedcolumns = self.columns if not columns else columns
if remove_newline:
for i, longcolumn in enumerate(data):
for key in longcolumn:
if isinstance(longcolumn[key], str):
longcolumn[key] = longcolumn[key].replace("\n", "")
result = tabulate(
[sortedcolumns] + [[limit_text(x[c], text_limit)
for c in sortedcolumns] for x in data],
headers="firstrow",
tablefmt=format)
if only_ascii:
return asciireplace(result)
return result
def output(self, f=None, columns=None, quote_all=None, encoding="utf-8"):
if not columns:
columns = self.columns
outputfile(f, self.rows, columns,
quote_all=quote_all, encoding=encoding)
def outputs(self, columns=None, quote_all=None, encoding="utf-8"):
"""Outputs to str"""
if not columns:
columns = self.columns
return outputstr(self.rows, columns, quote_all=quote_all, encoding=encoding)
| Dolphman/PSV | psv/core/objects/selections.py | Python | mit | 15,237 |
<?php
/* $Id: StockCostUpdate.php 6945 2014-10-27 07:20:48Z daintree $*/
$UpdateSecurity =10;
include('includes/session.inc');
$Title = _('Stock Cost Update');
include('includes/header.inc');
include('includes/SQL_CommonFunctions.inc');
if (isset($_GET['StockID'])){
$StockID = trim(mb_strtoupper($_GET['StockID']));
} elseif (isset($_POST['StockID'])){
$StockID =trim(mb_strtoupper($_POST['StockID']));
}
echo '<a href="' . $RootPath . '/SelectProduct.php">' . _('Back to Items') . '</a><br />';
echo '<p class="page_title_text">
<img src="'.$RootPath.'/css/'.$Theme.'/images/supplier.png" title="' . _('Inventory Adjustment') . '" alt="" />
' . ' ' . $Title . '</p>';
if (isset($_POST['UpdateData'])){
$sql = "SELECT materialcost,
labourcost,
overheadcost,
mbflag,
sum(quantity) as totalqoh
FROM stockmaster INNER JOIN locstock
ON stockmaster.stockid=locstock.stockid
WHERE stockmaster.stockid='".$StockID."'
GROUP BY description,
units,
lastcost,
actualcost,
materialcost,
labourcost,
overheadcost,
mbflag";
$ErrMsg = _('The entered item code does not exist');
$OldResult = DB_query($sql,$ErrMsg);
$OldRow = DB_fetch_array($OldResult);
$_POST['QOH'] = $OldRow['totalqoh'];
$_POST['OldMaterialCost'] = $OldRow['materialcost'];
if ($OldRow['mbflag']=='M') {
$_POST['OldLabourCost'] = $OldRow['labourcost'];
$_POST['OldOverheadCost'] = $OldRow['overheadcost'];
} else {
$_POST['OldLabourCost'] = 0;
$_POST['OldOverheadCost'] = 0;
$_POST['LabourCost'] = 0;
$_POST['OverheadCost'] = 0;
}
DB_free_result($OldResult);
$OldCost = $_POST['OldMaterialCost'] + $_POST['OldLabourCost'] + $_POST['OldOverheadCost'];
$NewCost = filter_number_format($_POST['MaterialCost']) + filter_number_format($_POST['LabourCost']) + filter_number_format($_POST['OverheadCost']);
$result = DB_query("SELECT * FROM stockmaster WHERE stockid='" . $StockID . "'");
$myrow = DB_fetch_row($result);
if (DB_num_rows($result)==0) {
prnMsg (_('The entered item code does not exist'),'error',_('Non-existent Item'));
} elseif ($OldCost != $NewCost){
$Result = DB_Txn_Begin();
ItemCostUpdateGL($db, $StockID, $NewCost, $OldCost, $_POST['QOH']);
$SQL = "UPDATE stockmaster SET materialcost='" . filter_number_format($_POST['MaterialCost']) . "',
labourcost='" . filter_number_format($_POST['LabourCost']) . "',
overheadcost='" . filter_number_format($_POST['OverheadCost']) . "',
lastcost='" . $OldCost . "',
lastcostupdate ='" . Date('Y-m-d')."'
WHERE stockid='" . $StockID . "'";
$ErrMsg = _('The cost details for the stock item could not be updated because');
$DbgMsg = _('The SQL that failed was');
$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
$Result = DB_Txn_Commit();
UpdateCost($db, $StockID); //Update any affected BOMs
}
}
$ErrMsg = _('The cost details for the stock item could not be retrieved because');
$DbgMsg = _('The SQL that failed was');
$result = DB_query("SELECT description,
units,
lastcost,
actualcost,
materialcost,
labourcost,
overheadcost,
mbflag,
stocktype,
lastcostupdate,
sum(quantity) as totalqoh
FROM stockmaster INNER JOIN locstock
ON stockmaster.stockid=locstock.stockid
INNER JOIN stockcategory
ON stockmaster.categoryid = stockcategory.categoryid
WHERE stockmaster.stockid='" . $StockID . "'
GROUP BY description,
units,
lastcost,
actualcost,
materialcost,
labourcost,
overheadcost,
mbflag,
stocktype",
$ErrMsg,
$DbgMsg);
$myrow = DB_fetch_array($result);
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '" method="post">
<div>
<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
<table cellpadding="2" class="selection">
<tr>
<th colspan="2">' . _('Item Code') . ':<input type="text" name="StockID" value="' . $StockID . '" maxlength="20" /><input type="submit" name="Show" value="' . _('Show Cost Details') . '" /></th>
</tr>
<tr>
<th colspan="2">' . $StockID . ' - ' . $myrow['description'] . '</th>
</tr>
<tr>
<th colspan="2">' . _('Total Quantity On Hand') . ': ' . $myrow['totalqoh'] . ' ' . $myrow['units'] . '</th>
</tr>
<tr>
<th colspan="2">' . _('Last Cost update on') . ': ' . ConvertSQLDate($myrow['lastcostupdate']) . '</th>
</tr>';
if (($myrow['mbflag']=='D' AND $myrow['stocktype'] != 'L')
OR $myrow['mbflag']=='A'
OR $myrow['mbflag']=='K'){
echo '</div>
</form>'; // Close the form
if ($myrow['mbflag']=='D'){
echo '<br />' . $StockID .' ' . _('is a service item');
} else if ($myrow['mbflag']=='A'){
echo '<br />' . $StockID .' ' . _('is an assembly part');
} else if ($myrow['mbflag']=='K'){
echo '<br />' . $StockID . ' ' . _('is a kit set part');
}
prnMsg(_('Cost information cannot be modified for kits assemblies or service items') . '. ' . _('Please select a different part'),'warn');
include('includes/footer.inc');
exit;
}
echo '<tr><td>';
echo '<input type="hidden" name="OldMaterialCost" value="' . $myrow['materialcost'] .'" />';
echo '<input type="hidden" name="OldLabourCost" value="' . $myrow['labourcost'] .'" />';
echo '<input type="hidden" name="OldOverheadCost" value="' . $myrow['overheadcost'] .'" />';
echo '<input type="hidden" name="QOH" value="' . $myrow['totalqoh'] .'" />';
echo _('Last Cost') .':</td>
<td class="number">' . locale_number_format($myrow['lastcost'],$_SESSION['StandardCostDecimalPlaces']) . '</td></tr>';
if (! in_array($_SESSION['PageSecurityArray']['CostUpdate'],$_SESSION['AllowedPageSecurityTokens'])){
echo '<tr>
<td>' . _('Cost') . ':</td>
<td class="number">' . locale_number_format($myrow['materialcost']+$myrow['labourcost']+$myrow['overheadcost'],$_SESSION['StandardCostDecimalPlaces']) . '</td>
</tr>
</table>';
} else {
if ($myrow['mbflag']=='M'){
echo '<tr>
<td>' . _('Standard Material Cost Per Unit') .':</td>
<td class="number"><input type="text" class="number" name="MaterialCost" value="' . locale_number_format($myrow['materialcost'],$_SESSION['StandardCostDecimalPlaces']) . '" /></td>
</tr>
<tr>
<td>' . _('Standard Labour Cost Per Unit') . ':</td>
<td class="number"><input type="text" class="number" name="LabourCost" value="' . locale_number_format($myrow['labourcost'],$_SESSION['StandardCostDecimalPlaces']) . '" /></td>
</tr>
<tr>
<td>' . _('Standard Overhead Cost Per Unit') . ':</td>
<td class="number"><input type="text" class="number" name="OverheadCost" value="' . locale_number_format($myrow['overheadcost'],$_SESSION['StandardCostDecimalPlaces']) . '" /></td>
</tr>';
} elseif ($myrow['mbflag']=='B' OR $myrow['mbflag']=='D') {
echo '<tr>
<td>' . _('Standard Cost') .':</td>
<td class="number"><input type="text" class="number" name="MaterialCost" value="' . locale_number_format($myrow['materialcost'],$_SESSION['StandardCostDecimalPlaces']) . '" /></td>
</tr>';
} else {
echo '<tr><td><input type="hidden" name="LabourCost" value="0" />';
echo '<input type="hidden" name="OverheadCost" value="0" /></td></tr>';
}
echo '</table>
<br />
<div class="centre">
<input type="submit" name="UpdateData" value="' . _('Update') . '" />
</div>
<br />
<br />';
}
if ($myrow['mbflag']!='D'){
echo '<div class="centre"><a href="' . $RootPath . '/StockStatus.php?StockID=' . $StockID . '">' . _('Show Stock Status') . '</a>';
echo '<br /><a href="' . $RootPath . '/StockMovements.php?StockID=' . $StockID . '">' . _('Show Stock Movements') . '</a>';
echo '<br /><a href="' . $RootPath . '/StockUsage.php?StockID=' . $StockID . '">' . _('Show Stock Usage') . '</a>';
echo '<br /><a href="' . $RootPath . '/SelectSalesOrder.php?SelectedStockItem=' . $StockID . '">' . _('Search Outstanding Sales Orders') . '</a>';
echo '<br /><a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedStockItem=' . $StockID . '">' . _('Search Completed Sales Orders') . '</a></div>';
}
echo '</div>
</form>';
include('includes/footer.inc');
?> | whp0011/weberp | StockCostUpdate.php | PHP | mit | 8,383 |
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/energi-config.h"
#endif
#include "util.h"
#include "uritests.h"
#include "compattests.h"
#include "trafficgraphdatatests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
#endif
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("Energi-Qt-test");
SSL_library_init();
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
if (QTest::qExec(&test2) != 0)
fInvalid = true;
#endif
CompatTests test4;
if (QTest::qExec(&test4) != 0)
fInvalid = true;
TrafficGraphDataTests test5;
if (QTest::qExec(&test5) != 0)
fInvalid = true;
return fInvalid;
}
| rsdevgun16e/energi | src/qt/test/test_main.cpp | C++ | mit | 1,487 |
<?php>
echo HelloWorld;
phpinfo();
<?>
| cappetta/SecDevOps-Toolkit | tooling/terraform/Armor_test/index.php | PHP | mit | 40 |
var debug = require('debug')('zuul');
var open = require('opener');
var Batch = require('batch');
var EventEmitter = require('events').EventEmitter;
var control_app = require('./control-app');
var frameworks = require('../frameworks');
var setup_test_instance = require('./setup');
var SauceBrowser = require('./SauceBrowser');
var PhantomBrowser = require('./PhantomBrowser');
module.exports = Zuul;
function Zuul(config) {
if (!(this instanceof Zuul)) {
return new Zuul(config);
}
var self = this;
var ui = config.ui;
var framework_dir = frameworks[ui];
if (!framework_dir) {
throw new Error('unsupported ui: ' + ui);
}
config.framework_dir = framework_dir;
self._config = config;
// list of browsers to test
self._browsers = [];
self._concurrency = config.concurrency || 3;
}
Zuul.prototype.__proto__ = EventEmitter.prototype;
Zuul.prototype._setup = function(cb) {
var self = this;
var config = self._config;
// we only need one control app
var control_server = control_app(config).listen(0, function() {
debug('control server active on port %d', control_server.address().port);
cb(null, control_server.address().port);
});
};
Zuul.prototype.browser = function(info) {
var self = this;
var config = self._config;
self._browsers.push(SauceBrowser({
name: config.name,
build: process.env.TRAVIS_BUILD_NUMBER,
firefox_profile: info.firefox_profile,
username: config.username,
key: config.key,
browser: info.name,
version: info.version,
platform: info.platform,
capabilities: config.capabilities
}, config));
};
Zuul.prototype.run = function(done) {
var self = this;
var config = self._config;
self._setup(function(err, control_port) {
config.control_port = control_port;
if (config.local) {
setup_test_instance(config, function(err, url) {
if (err) {
console.error(err.stack);
process.exit(1);
return;
}
if (config.open) {
open(url);
}
else {
console.log('open the following url in a browser:');
console.log(url);
}
});
return;
}
// TODO love and care
if (config.phantom) {
var phantom = PhantomBrowser(config);
self.emit('browser', phantom);
phantom.once('done', function(results) {
done(results.failed === 0 && results.passed > 0);
});
return phantom.start();
}
var batch = new Batch();
batch.concurrency(self._concurrency);
var passed = true;
self._browsers.forEach(function(browser) {
self.emit('browser', browser);
var retry = 3;
browser.on('error', function(err) {
if (--retry >= 0) {
debug('browser error (%s), restarting', err.message)
self.emit('restart', browser);
return browser.start();
}
self.emit('error', err);
});
batch.push(function(done) {
browser.once('done', function(results) {
// if no tests passed, then this is also a problem
// indicates potential error to even run tests
if (results.failed || results.passed === 0) {
passed = false;
}
done();
});
browser.start();
});
});
batch.end(function(err) {
debug('batch done');
done(err || passed);
});
});
};
| wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/should/node_modules/zuul/lib/zuul.js | JavaScript | mit | 3,918 |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
namespace TASessionManager
{
public class TASessionManager
{
public class ApiUser
{
public string UserId { get; set; }
}
public User GetTAUser()
{
var debugUser = ConfigurationManager.AppSettings["DebugUserId"];
if (debugUser != null)
{
return new User { UserId = debugUser };
}
if (HttpContext.Current == null) return null;
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(ConfigurationManager.AppSettings["CookieName"]);
if (cookie == null)
{
return null;
}
User user = HttpContext.Current.Session["user"] as User;
string userSession = HttpContext.Current.Session["usersession"] as string;
if (user != null && userSession != null && userSession == cookie.Value)
{
return user;
}
var userData = Api.GetData<ApiUser>("api/session/" + cookie.Value);
if (userData == null) return null;
user = new User { UserId = userData.UserId };
HttpContext.Current.Session["user"] = user;
HttpContext.Current.Session["usersession"] = cookie.Value;
return user;
}
}
} | textadventures/quest | WebEditor/WebEditor/Services/TextAdventures/TASessionManager.cs | C# | mit | 1,473 |
require 'rails_helper'
RSpec.describe Archived::EmailConstituenciesJob, type: :job do
let!(:petition) { FactoryBot.create(:archived_petition) }
let!(:mailshot) { FactoryBot.create(:archived_petition_mailshot, petition: petition) }
let!(:constituency_ids) { %w[3427 3320 3703] }
let!(:requested_at) { Time.now }
let!(:requested_at_iso8601) { requested_at.getutc.iso8601(6) }
it "enqueues an Archived::EmailConstituencyJob job for every constituency" do
described_class.perform_now(mailshot, constituency_ids, requested_at: requested_at)
expect(Archived::EmailConstituencyJob).to have_been_enqueued
.on_queue(:high_priority).with(
petition: petition,
mailshot: mailshot,
scope: { constituency_id: "3427" },
requested_at: requested_at_iso8601
)
expect(Archived::EmailConstituencyJob).to have_been_enqueued
.on_queue(:high_priority).with(
petition: petition,
mailshot: mailshot,
scope: { constituency_id: "3320" },
requested_at: requested_at_iso8601
)
expect(Archived::EmailConstituencyJob).to have_been_enqueued
.on_queue(:high_priority).with(
petition: petition,
mailshot: mailshot,
scope: { constituency_id: "3703" },
requested_at: requested_at_iso8601
)
end
end
| unboxed/e-petitions | spec/jobs/archived/email_constituencies_job_spec.rb | Ruby | mit | 1,329 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\TwigBundle\Extension;
use Symfony\Bundle\TwigBundle\TokenParser\RenderTokenParser;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
/**
* Twig extension for Symfony actions helper.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 2.2, to be removed in 3.0.
*/
class ActionsExtension extends \Twig_Extension
{
private $handler;
/**
* @param FragmentHandler|ContainerInterface $handler
*
* @deprecated Passing a ContainerInterface as a first argument is deprecated since 2.7 and will be removed in 3.0.
*/
public function __construct($handler)
{
if ($handler instanceof FragmentHandler) {
$this->handler = $handler;
} elseif ($handler instanceof ContainerInterface) {
trigger_error('The ability to pass a ContainerInterface instance as a first argument to '.__METHOD__.' method is deprecated since version 2.7 and will be removed in 3.0. Pass a FragmentHandler instance instead.', E_USER_DEPRECATED);
$this->handler = $handler->get('fragment.handler');
} else {
throw new \BadFunctionCallException(sprintf('%s takes a FragmentHandler or a ContainerInterface object as its first argument.', __METHOD__));
}
$this->handler = $handler;
}
/**
* Returns the Response content for a given URI.
*
* @param string $uri A URI
* @param array $options An array of options
*
* @see FragmentHandler::render()
*/
public function renderUri($uri, array $options = array())
{
$strategy = isset($options['strategy']) ? $options['strategy'] : 'inline';
unset($options['strategy']);
return $this->handler->render($uri, $strategy, $options);
}
/**
* Returns the token parser instance to add to the existing list.
*
* @return array An array of \Twig_TokenParser instances
*/
public function getTokenParsers()
{
return array(
// {% render url('post_list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error' } %}
new RenderTokenParser(),
);
}
public function getName()
{
return 'actions';
}
}
| sof1105/symfony | src/Symfony/Bundle/TwigBundle/Extension/ActionsExtension.php | PHP | mit | 2,550 |
import heapq
# Wrapper class around heapq so that we can directly pass the key and dont have to make tuples
class Heap( object ):
def __init__( self, initial = None, key = lambda x : x ):
self.key = key
if initial:
self._data = [ ( key( item ), item ) for item in initial ]
heapq.heapify( self._data )
else:
self._data = [ ]
def push( self, item ):
heapq.heappush( self._data, ( self.key( item ), item ) )
def pop( self ):
if len( self._data ) > 0:
return heapq.heappop( self._data )[ 1 ]
else:
return None
def top( self ):
return self._data[ 0 ][ 1 ]
def size( self ):
return len( self._data )
| cvquant/trade-analysis | cdefs/heap.py | Python | mit | 754 |
<?php
/**
* Test case for container class for dependecy injection.
*
* @copyright 2015 Fernando Val
* @author Allan Marques <allan.marques@ymail.com>
* @author Fernando Val <fernando.val@gmail.com>
*
* @version 1.0.0.6
*/
use PHPUnit\Framework\TestCase;
use Springy\Container\DIContainer;
/**
* Test case for container class for dependecy injection.
*/
class DIContainerTest extends TestCase
{
private $data;
public function setUp()
{
$this->data = [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'key4' => 'value4',
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testThatContainerCanStoreRawValues()
{
$DI = new DIContainer();
//Basic
$DI->raw('key1', $this->data['key1']);
$this->assertEquals($this->data['key1'], $DI->param('key1'));
//Array like
$DI['key2'] = $this->data['key2'];
$this->assertEquals($this->data['key2'], $DI['key2']);
//Function filter #1
$DI['key3'] = $DI->raw(function ($container) {
return $this->data['key3'];
});
$this->assertEquals($this->data['key3'], $DI->param('key3'));
//Function filter #2
$DI->raw('key4', function ($container) {
return $this->data['key4'];
});
$this->assertEquals($this->data['key4'], $DI->param('key4'));
//Forgeting
$DI->forget('key4');
$DI->param('key4');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testThatContainerCanCreateObjectsOnTheFly()
{
$DI = new DIContainer();
//Basic
$DI->bind('object1', function ($attr = null, $val = null) {
$obj = $this->createMock('SomeClass', ['someMethod']);
if (is_string($attr)) {
$obj->$attr = $val;
}
return $obj;
});
$this->assertTrue(is_object($DI->make('object1')));
$this->assertTrue(method_exists($DI->make('object1'), 'someMethod'));
$this->assertInstanceOf('SomeClass', $DI->make('object1'));
$object1 = $DI->make('object1');
$object2 = $DI->make('object1');
$this->assertNotSame($object1, $object2);
//With params
$objectWithParam = $DI->make('object1', ['name', 'Jack']);
$this->assertObjectHasAttribute('name', $objectWithParam);
$this->assertEquals('Jack', $objectWithParam->name);
//Array like
$DI['object2'] = function () {
return $this->createMock('AnotherClass', ['otherMethod']);
};
$this->assertNotInstanceOf('Closure', $DI['object2']);
$this->assertTrue(method_exists($DI['object2'], 'otherMethod'));
$this->assertInstanceOf('AnotherClass', $DI['object2']);
$object3 = $DI['object2'];
$object4 = $DI['object2'];
$this->assertNotSame($object3, $object4);
//Unbinding
$DI->forget('object2');
$DI->make('object2');
}
public function testThatContainerCanExtendFactories()
{
$DI = new DIContainer();
$DI['some.service'] = function ($container) {
return $this->getMockBuilder('someService');
};
$DI->extend('some.service', function ($someService, $container) {
$someService->someAttribute = 'someValue';
return $someService;
});
$this->assertObjectHasAttribute('someAttribute', $DI['some.service']);
$this->assertEquals('someValue', $DI['some.service']->someAttribute);
$extended1 = $DI['some.service'];
$extended2 = $DI['some.service'];
$this->assertNotSame($extended1, $extended2);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testThatContainerCanBindObjectsAndShareInstances()
{
$DI = new DIContainer();
$object1 = $this->getMockBuilder('MockedClass');
$object2 = $this->getMockBuilder('AnotherMockedClass');
$object3 = $this->getMockBuilder('MockedInstance');
$object4 = $this->getMockBuilder('AnotherMockedInstance');
//Basic
$DI->instance('object1', $object1);
$this->assertSame($object1, $DI->shared('object1'));
//Array like
$DI['object2'] = $object2;
$this->assertSame($object2, $DI['object2']);
//Function filter #1
$DI['object3'] = $DI->instance(function ($container) use ($object3) {
return $object3;
});
$this->assertSame($object3, $DI->shared('object3'));
//Function filter #2
$DI->instance('object4', function ($container) use ($object4) {
return $object4;
});
$this->assertSame($object4, $DI->shared('object4'));
//Forgeting
$DI->forget('object4');
$DI->shared('object4');
}
}
class AnotherClass
{
public function otherMethod()
{
return true;
}
}
class SomeClass
{
public function someMethod()
{
return true;
}
}
| fernandoval/FVAL-PHP-Framework | tests/Container/DIContainerTest.php | PHP | mit | 5,165 |
package com.example.tom.HushText;
import android.util.Base64;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
/**
* Created by tom on 3/22/2015.
* Class created for testing purposes, performs a series of simply crypto tests by encrypting and
* decrypting the string "life imitates art", generally this class will not actually be used in the
* regular usage of the application.
*/
public class CryptoTest {
/**
* Performs the crypto test and prints results to standard output.
*/
public static void test() {
System.out.println("#####################################################################");
System.out.println("########################Starting Crypto Test#########################");
System.out.println("#####################################################################");
String message = "life imitates art";
System.out.println("Test message is: " + message);
try {
InitKeyExchange ike = new InitKeyExchange(
HushTextConstants.ASYMMETRIC_ENCRYPTION_ALGORITHM,
HushTextConstants.ASYMMETRIC_ENCRYPTION_SIZE);
PrivateKey pri = ike.getPrivateKey();
PublicKey pub = ike.getPublicKey();
//--------------------------------------------------//
System.out.println("Doing basic symm key test");
SecretKey key = SymmetricCryptoUtils.generateSymmetricKey("AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.ENCRYPT_MODE, key);
byte[] messageBytes = message.getBytes();
String encryptedMessageString = Base64.encodeToString(c1.doFinal(messageBytes), Base64.DEFAULT);
byte[] decodedMessageBytes = Base64.decode(encryptedMessageString, Base64.DEFAULT);
c1 = Cipher.getInstance("AES");
c1.init(Cipher.DECRYPT_MODE, key);
String finalString = new String(c1.doFinal(decodedMessageBytes));
System.out.println("HEAR YEEE HEAR YEE THE UNECRYPTED MESSAGE IS: " + finalString + " !!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("Done!!!");
//--------------------------------------------------//
System.out.println("Doing Secondary symm key test");
String encryptedMessage2 = Base64.encodeToString(SymmetricCryptoUtils.encryptMessage(message, key), Base64.DEFAULT);
byte[] decodedMessageBytes2 = Base64.decode(encryptedMessage2, Base64.DEFAULT);
//String decryptedMessage2 = new String(Base64.decode(SymmetricCryptoUtils.decryptMessage(decodedMessageBytes2, key), Base64.DEFAULT));
String decryptedMessage2 = new String(SymmetricCryptoUtils.decryptMessage(decodedMessageBytes2, key));
System.out.println("HEAR YEEE HEAR YEE THE SECOND UNECRYPTED MESSAGE IS: " + decryptedMessage2 + " !!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("Done!!!");
//--------------------------------------------------//
String keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
System.out.println("Encoded Symmetric Key: " + keyString);
Base64.decode(keyString, Base64.DEFAULT);
SymmetricCryptoUtils.encryptMessage(message, key);
}
catch (Exception e) {
}
System.out.println("#####################################################################");
System.out.println("########################Ending Crypto Test#########################");
System.out.println("#####################################################################");
}
}
| tommyp1ckles/HushText | SecureText/app/src/main/java/com/example/tom/HushText/CryptoTest.java | Java | mit | 3,731 |