code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
<?php namespace Aws\Sqs; use Aws\AwsClient; use Aws\CommandInterface; use Aws\Sqs\Exception\SqsException; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\RequestInterface; /** * Client used to interact Amazon Simple Queue Service (Amazon SQS) * * @method \Aws\Result addPermission(array $args = []) * @method \GuzzleHttp\Promise\Promise addPermissionAsync(array $args = []) * @method \Aws\Result changeMessageVisibility(array $args = []) * @method \GuzzleHttp\Promise\Promise changeMessageVisibilityAsync(array $args = []) * @method \Aws\Result changeMessageVisibilityBatch(array $args = []) * @method \GuzzleHttp\Promise\Promise changeMessageVisibilityBatchAsync(array $args = []) * @method \Aws\Result createQueue(array $args = []) * @method \GuzzleHttp\Promise\Promise createQueueAsync(array $args = []) * @method \Aws\Result deleteMessage(array $args = []) * @method \GuzzleHttp\Promise\Promise deleteMessageAsync(array $args = []) * @method \Aws\Result deleteMessageBatch(array $args = []) * @method \GuzzleHttp\Promise\Promise deleteMessageBatchAsync(array $args = []) * @method \Aws\Result deleteQueue(array $args = []) * @method \GuzzleHttp\Promise\Promise deleteQueueAsync(array $args = []) * @method \Aws\Result getQueueAttributes(array $args = []) * @method \GuzzleHttp\Promise\Promise getQueueAttributesAsync(array $args = []) * @method \Aws\Result getQueueUrl(array $args = []) * @method \GuzzleHttp\Promise\Promise getQueueUrlAsync(array $args = []) * @method \Aws\Result listDeadLetterSourceQueues(array $args = []) * @method \GuzzleHttp\Promise\Promise listDeadLetterSourceQueuesAsync(array $args = []) * @method \Aws\Result listQueues(array $args = []) * @method \GuzzleHttp\Promise\Promise listQueuesAsync(array $args = []) * @method \Aws\Result purgeQueue(array $args = []) * @method \GuzzleHttp\Promise\Promise purgeQueueAsync(array $args = []) * @method \Aws\Result receiveMessage(array $args = []) * @method \GuzzleHttp\Promise\Promise receiveMessageAsync(array $args = []) * @method \Aws\Result removePermission(array $args = []) * @method \GuzzleHttp\Promise\Promise removePermissionAsync(array $args = []) * @method \Aws\Result sendMessage(array $args = []) * @method \GuzzleHttp\Promise\Promise sendMessageAsync(array $args = []) * @method \Aws\Result sendMessageBatch(array $args = []) * @method \GuzzleHttp\Promise\Promise sendMessageBatchAsync(array $args = []) * @method \Aws\Result setQueueAttributes(array $args = []) * @method \GuzzleHttp\Promise\Promise setQueueAttributesAsync(array $args = []) */ class SqsClient extends AwsClient { public function __construct(array $config) { parent::__construct($config); $list = $this->getHandlerList(); $list->appendBuild($this->queueUrl(), 'sqs.queue_url'); $list->appendSign($this->validateMd5(), 'sqs.md5'); } /** * Converts a queue URL into a queue ARN. * * @param string $queueUrl The queue URL to perform the action on. * Retrieved when the queue is first created. * * @return string An ARN representation of the queue URL. */ public function getQueueArn($queueUrl) { return strtr($queueUrl, array( 'http://' => 'arn:aws:', 'https://' => 'arn:aws:', '.amazonaws.com' => '', '/' => ':', '.' => ':', )); } /** * Moves the URI of the queue to the URI in the input parameter. * * @return callable */ private function queueUrl() { return static function (callable $handler) { return function ( CommandInterface $c, RequestInterface $r = null ) use ($handler) { if ($c->hasParam('QueueUrl')) { $uri = Uri::resolve($r->getUri(), $c['QueueUrl']); $r = $r->withUri($uri); } return $handler($c, $r); }; }; } /** * Validates ReceiveMessage body MD5s * * @return callable */ private function validateMd5() { return static function (callable $handler) { return function ( CommandInterface $c, RequestInterface $r = null ) use ($handler) { if ($c->getName() !== 'ReceiveMessage') { return $handler($c, $r); } return $handler($c, $r) ->then( function ($result) use ($c, $r) { foreach ((array) $result['Messages'] as $msg) { if (isset($msg['MD5OfBody']) && md5($msg['Body']) !== $msg['MD5OfBody'] ) { throw new SqsException( sprintf( 'MD5 mismatch. Expected %s, found %s', $msg['MD5OfBody'], md5($msg['Body']) ), $c, [ 'code' => 'ClientChecksumMismatch', 'request' => $r ] ); } } return $result; } ); }; }; } }
kironuniversity/main-website
plugins/october/drivers/vendor/aws/aws-sdk-php/src/Sqs/SqsClient.php
PHP
apache-2.0
5,742
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package app import ( "github.com/golang/glog" "golang.org/x/exp/inotify" ) func watchForLockfileContention(path string, done chan struct{}) error { watcher, err := inotify.NewWatcher() if err != nil { glog.Errorf("unable to create watcher for lockfile: %v", err) return err } if err = watcher.AddWatch(path, inotify.IN_OPEN|inotify.IN_DELETE_SELF); err != nil { glog.Errorf("unable to watch lockfile: %v", err) return err } go func() { select { case ev := <-watcher.Event: glog.Infof("inotify event: %v", ev) case err = <-watcher.Error: glog.Errorf("inotify watcher error: %v", err) } close(done) }() return nil }
ksshanam/kubernetes
cmd/kubelet/app/server_linux.go
GO
apache-2.0
1,221
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview A basic example of working with Chrome on Android. Before * running this example, you must start adb and connect a device (or start an * AVD). */ var webdriver = require('..'), By = webdriver.By, until = webdriver.until, chrome = require('../chrome'); var driver = new webdriver.Builder() .forBrowser('chrome') .setChromeOptions(new chrome.Options().androidChrome()) .build(); driver.get('http://www.google.com/ncr'); driver.findElement(By.name('q')).sendKeys('webdriver'); driver.findElement(By.name('btnG')).click(); driver.wait(until.titleIs('webdriver - Google Search'), 1000); driver.quit();
alb-i986/selenium
javascript/node/selenium-webdriver/example/chrome_android.js
JavaScript
apache-2.0
1,452
var baseIsMatch = require('./_baseIsMatch'), getMatchData = require('./_getMatchData'); /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } module.exports = isMatchWith;
jeiker26/react
node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-es2015-duplicate-keys/node_modules/babel-types/node_modules/lodash/isMatchWith.js
JavaScript
apache-2.0
1,329
/* * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package tests; import java.util.Collection; import java.util.Collections; class CompileTest2 { class Request<R extends Request<R, V>,V> {} class DeltaRequest extends Request<DeltaRequest, double[]> {} class RequestMap<V> { public <R extends Request<R, W>, W extends V> R test (Collection<R> c) { // In my real code I make use of W of course return null; } } public void f () { RequestMap<Object> m = new RequestMap<Object> (); Collection<DeltaRequest> c = Collections.singleton (new DeltaRequest ()); // This line not compile? DeltaRequest o = m.<DeltaRequest, double[]>test (c); } }
gijsleussink/ceylon
compiler-java/langtools/test/tools/javac/generics/inference/6359106/Orig.java
Java
apache-2.0
1,841
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.elasticsearch.common.inject.internal; import org.elasticsearch.common.util.CollectionUtils; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Objects; /** * Utility for joining pieces of text separated by a delimiter. It can handle * iterators, collections, arrays, and varargs, and can append to any * {@link Appendable} or just return a {@link String}. For example, * {@code join(":", "a", "b", "c")} returns {@code "a:b:c"}. * <p> * All methods of this class throw {@link NullPointerException} when a value * of {@code null} is supplied for any parameter. The elements within the * collection, iterator, array, or varargs parameter list <i>may</i> be null -- * these will be represented in the output by the string {@code "null"}. * * @author Kevin Bourrillion */ public final class Join { private Join() { } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Iterable<?> tokens) { return join(delimiter, tokens.iterator()); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Object[] tokens) { return join(delimiter, Arrays.asList(tokens)); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param firstToken the first object to append * @param otherTokens subsequent objects to append * @return a string consisting of the joined elements */ public static String join( String delimiter, @Nullable Object firstToken, Object... otherTokens) { Objects.requireNonNull(otherTokens); return join(delimiter, CollectionUtils.asArrayList(firstToken, otherTokens)); } /** * Returns a string containing the {@code tokens}, converted to strings if * necessary, separated by {@code delimiter}. If {@code tokens} is empty, it * returns an empty string. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return a string consisting of the joined elements */ public static String join(String delimiter, Iterator<?> tokens) { StringBuilder sb = new StringBuilder(); join(sb, delimiter, tokens); return sb.toString(); } /** * Returns a string containing the contents of {@code map}, with entries * separated by {@code entryDelimiter}, and keys and values separated with * {@code keyValueSeparator}. * <p> * Each key and value will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param keyValueSeparator a string to append between every key and its * associated value * @param entryDelimiter a string to append between every entry, but not at * the beginning or end * @param map the map containing the data to join * @return a string consisting of the joined entries of the map; empty if the * map is empty */ public static String join( String keyValueSeparator, String entryDelimiter, Map<?, ?> map) { return join(new StringBuilder(), keyValueSeparator, entryDelimiter, map) .toString(); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Iterable<?> tokens) { return join(appendable, delimiter, tokens.iterator()); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Object[] tokens) { return join(appendable, delimiter, Arrays.asList(tokens)); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param firstToken the first object to append * @param otherTokens subsequent objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join(T appendable, String delimiter, @Nullable Object firstToken, Object... otherTokens) { Objects.requireNonNull(otherTokens); return join(appendable, delimiter, CollectionUtils.asArrayList(firstToken, otherTokens)); } /** * Appends each of the {@code tokens} to {@code appendable}, separated by * {@code delimiter}. * <p> * Each token will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param delimiter a string to append between every element, but not at the * beginning or end * @param tokens objects to append * @return the same {@code Appendable} instance that was passed in * @throws JoinException if an {@link IOException} occurs */ public static <T extends Appendable> T join( T appendable, String delimiter, Iterator<?> tokens) { /* This method is the workhorse of the class */ Objects.requireNonNull(appendable); Objects.requireNonNull(delimiter); if (tokens.hasNext()) { try { appendOneToken(appendable, tokens.next()); while (tokens.hasNext()) { appendable.append(delimiter); appendOneToken(appendable, tokens.next()); } } catch (IOException e) { throw new JoinException(e); } } return appendable; } /** * Appends the contents of {@code map} to {@code appendable}, with entries * separated by {@code entryDelimiter}, and keys and values separated with * {@code keyValueSeparator}. * <p> * Each key and value will be converted to a {@link CharSequence} using * {@link String#valueOf(Object)}, if it isn't a {@link CharSequence} already. * Note that this implies that null tokens will be appended as the * four-character string {@code "null"}. * * @param appendable the object to append the results to * @param keyValueSeparator a string to append between every key and its * associated value * @param entryDelimiter a string to append between every entry, but not at * the beginning or end * @param map the map containing the data to join * @return the same {@code Appendable} instance that was passed in */ public static <T extends Appendable> T join(T appendable, String keyValueSeparator, String entryDelimiter, Map<?, ?> map) { Objects.requireNonNull(appendable); Objects.requireNonNull(keyValueSeparator); Objects.requireNonNull(entryDelimiter); Iterator<? extends Map.Entry<?, ?>> entries = map.entrySet().iterator(); if (entries.hasNext()) { try { appendOneEntry(appendable, keyValueSeparator, entries.next()); while (entries.hasNext()) { appendable.append(entryDelimiter); appendOneEntry(appendable, keyValueSeparator, entries.next()); } } catch (IOException e) { throw new JoinException(e); } } return appendable; } private static void appendOneEntry( Appendable appendable, String keyValueSeparator, Map.Entry<?, ?> entry) throws IOException { appendOneToken(appendable, entry.getKey()); appendable.append(keyValueSeparator); appendOneToken(appendable, entry.getValue()); } private static void appendOneToken(Appendable appendable, Object token) throws IOException { appendable.append(toCharSequence(token)); } private static CharSequence toCharSequence(Object token) { return (token instanceof CharSequence) ? (CharSequence) token : String.valueOf(token); } /** * Exception thrown in response to an {@link IOException} from the supplied * {@link Appendable}. This is used because most callers won't want to * worry about catching an IOException. */ public static class JoinException extends RuntimeException { private JoinException(IOException cause) { super(cause); } } }
mmaracic/elasticsearch
core/src/main/java/org/elasticsearch/common/inject/internal/Join.java
Java
apache-2.0
13,659
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This package contains hand-coded set implementations that should be similar // to the autogenerated ones in pkg/util/sets. // We can't simply use net.IPNet as a map-key in Go (because it contains a // []byte). // We could use the same workaround we use here (a string representation as the // key) to autogenerate sets. If we do that, or decide on an alternate // approach, we should replace the implementations in this package with the // autogenerated versions. // It is expected that callers will alias this import as "netsets" i.e. import // netsets "k8s.io/kubernetes/pkg/util/net/sets" package sets
Q-Lee/kubernetes
pkg/util/net/sets/doc.go
GO
apache-2.0
1,181
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2017, British Columbia Institute of Technology * * 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 CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 2.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * CodeIgniter Memcached Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author EllisLab Dev Team * @link */ class CI_Cache_memcached extends CI_Driver { /** * Holds the memcached object * * @var object */ protected $_memcached; /** * Memcached configuration * * @var array */ protected $_config = array( 'default' => array( 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 1 ) ); // ------------------------------------------------------------------------ /** * Class constructor * * Setup Memcache(d) * * @return void */ public function __construct() { // Try to load memcached server info from the config file. $CI =& get_instance(); $defaults = $this->_config['default']; if ($CI->config->load('memcached', TRUE, TRUE)) { $this->_config = $CI->config->config['memcached']; } if (class_exists('Memcached', FALSE)) { $this->_memcached = new Memcached(); } elseif (class_exists('Memcache', FALSE)) { $this->_memcached = new Memcache(); } else { log_message('error', 'Cache: Failed to create Memcache(d) object; extension not loaded?'); return; } foreach ($this->_config as $cache_server) { isset($cache_server['hostname']) OR $cache_server['hostname'] = $defaults['host']; isset($cache_server['port']) OR $cache_server['port'] = $defaults['port']; isset($cache_server['weight']) OR $cache_server['weight'] = $defaults['weight']; if ($this->_memcached instanceof Memcache) { // Third parameter is persistance and defaults to TRUE. $this->_memcached->addServer( $cache_server['hostname'], $cache_server['port'], TRUE, $cache_server['weight'] ); } elseif ($this->_memcached instanceof Memcached) { $this->_memcached->addServer( $cache_server['hostname'], $cache_server['port'], $cache_server['weight'] ); } } } // ------------------------------------------------------------------------ /** * Fetch from cache * * @param string $id Cache ID * @return mixed Data on success, FALSE on failure */ public function get($id) { $data = $this->_memcached->get($id); return is_array($data) ? $data[0] : $data; } // ------------------------------------------------------------------------ /** * Save * * @param string $id Cache ID * @param mixed $data Data being cached * @param int $ttl Time to live * @param bool $raw Whether to store the raw value * @return bool TRUE on success, FALSE on failure */ public function save($id, $data, $ttl = 60, $raw = FALSE) { if ($raw !== TRUE) { $data = array($data, time(), $ttl); } if ($this->_memcached instanceof Memcached) { return $this->_memcached->set($id, $data, $ttl); } elseif ($this->_memcached instanceof Memcache) { return $this->_memcached->set($id, $data, 0, $ttl); } return FALSE; } // ------------------------------------------------------------------------ /** * Delete from Cache * * @param mixed $id key to be deleted. * @return bool true on success, false on failure */ public function delete($id) { return $this->_memcached->delete($id); } // ------------------------------------------------------------------------ /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function increment($id, $offset = 1) { return $this->_memcached->increment($id, $offset); } // ------------------------------------------------------------------------ /** * Decrement a raw value * * @param string $id Cache ID * @param int $offset Step/value to reduce by * @return mixed New value on success or FALSE on failure */ public function decrement($id, $offset = 1) { return $this->_memcached->decrement($id, $offset); } // ------------------------------------------------------------------------ /** * Clean the Cache * * @return bool false on failure/true on success */ public function clean() { return $this->_memcached->flush(); } // ------------------------------------------------------------------------ /** * Cache Info * * @return mixed array on success, false on failure */ public function cache_info() { return $this->_memcached->getStats(); } // ------------------------------------------------------------------------ /** * Get Cache Metadata * * @param mixed $id key to get cache metadata on * @return mixed FALSE on failure, array on success. */ public function get_metadata($id) { $stored = $this->_memcached->get($id); if (count($stored) !== 3) { return FALSE; } list($data, $time, $ttl) = $stored; return array( 'expire' => $time + $ttl, 'mtime' => $time, 'data' => $data ); } // ------------------------------------------------------------------------ /** * Is supported * * Returns FALSE if memcached is not supported on the system. * If it is, we setup the memcached object & return TRUE * * @return bool */ public function is_supported() { return (extension_loaded('memcached') OR extension_loaded('memcache')); } // ------------------------------------------------------------------------ /** * Class destructor * * Closes the connection to Memcache(d) if present. * * @return void */ public function __destruct() { if ($this->_memcached instanceof Memcache) { $this->_memcached->close(); } elseif ($this->_memcached instanceof Memcached && method_exists($this->_memcached, 'quit')) { $this->_memcached->quit(); } } }
johnotaalo/hivselftest
system/libraries/Cache/drivers/Cache_memcached.php
PHP
apache-2.0
7,435
package bbolt import ( "bytes" "fmt" "unsafe" ) const ( // MaxKeySize is the maximum length of a key, in bytes. MaxKeySize = 32768 // MaxValueSize is the maximum length of a value, in bytes. MaxValueSize = (1 << 31) - 2 ) const bucketHeaderSize = int(unsafe.Sizeof(bucket{})) const ( minFillPercent = 0.1 maxFillPercent = 1.0 ) // DefaultFillPercent is the percentage that split pages are filled. // This value can be changed by setting Bucket.FillPercent. const DefaultFillPercent = 0.5 // Bucket represents a collection of key/value pairs inside the database. type Bucket struct { *bucket tx *Tx // the associated transaction buckets map[string]*Bucket // subbucket cache page *page // inline page reference rootNode *node // materialized node for the root page. nodes map[pgid]*node // node cache // Sets the threshold for filling nodes when they split. By default, // the bucket will fill to 50% but it can be useful to increase this // amount if you know that your write workloads are mostly append-only. // // This is non-persisted across transactions so it must be set in every Tx. FillPercent float64 } // bucket represents the on-file representation of a bucket. // This is stored as the "value" of a bucket key. If the bucket is small enough, // then its root page can be stored inline in the "value", after the bucket // header. In the case of inline buckets, the "root" will be 0. type bucket struct { root pgid // page id of the bucket's root-level page sequence uint64 // monotonically incrementing, used by NextSequence() } // newBucket returns a new bucket associated with a transaction. func newBucket(tx *Tx) Bucket { var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} if tx.writable { b.buckets = make(map[string]*Bucket) b.nodes = make(map[pgid]*node) } return b } // Tx returns the tx of the bucket. func (b *Bucket) Tx() *Tx { return b.tx } // Root returns the root of the bucket. func (b *Bucket) Root() pgid { return b.root } // Writable returns whether the bucket is writable. func (b *Bucket) Writable() bool { return b.tx.writable } // Cursor creates a cursor associated with the bucket. // The cursor is only valid as long as the transaction is open. // Do not use a cursor after the transaction is closed. func (b *Bucket) Cursor() *Cursor { // Update transaction statistics. b.tx.stats.CursorCount++ // Allocate and return a cursor. return &Cursor{ bucket: b, stack: make([]elemRef, 0), } } // Bucket retrieves a nested bucket by name. // Returns nil if the bucket does not exist. // The bucket instance is only valid for the lifetime of the transaction. func (b *Bucket) Bucket(name []byte) *Bucket { if b.buckets != nil { if child := b.buckets[string(name)]; child != nil { return child } } // Move cursor to key. c := b.Cursor() k, v, flags := c.seek(name) // Return nil if the key doesn't exist or it is not a bucket. if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { return nil } // Otherwise create a bucket and cache it. var child = b.openBucket(v) if b.buckets != nil { b.buckets[string(name)] = child } return child } // Helper method that re-interprets a sub-bucket value // from a parent into a Bucket func (b *Bucket) openBucket(value []byte) *Bucket { var child = newBucket(b.tx) // If unaligned load/stores are broken on this arch and value is // unaligned simply clone to an aligned byte array. unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 if unaligned { value = cloneBytes(value) } // If this is a writable transaction then we need to copy the bucket entry. // Read-only transactions can point directly at the mmap entry. if b.tx.writable && !unaligned { child.bucket = &bucket{} *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) } else { child.bucket = (*bucket)(unsafe.Pointer(&value[0])) } // Save a reference to the inline page if the bucket is inline. if child.root == 0 { child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) } return &child } // CreateBucket creates a new bucket at the given key and returns the new bucket. // Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long. // The bucket instance is only valid for the lifetime of the transaction. func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) { if b.tx.db == nil { return nil, ErrTxClosed } else if !b.tx.writable { return nil, ErrTxNotWritable } else if len(key) == 0 { return nil, ErrBucketNameRequired } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if there is an existing key. if bytes.Equal(key, k) { if (flags & bucketLeafFlag) != 0 { return nil, ErrBucketExists } return nil, ErrIncompatibleValue } // Create empty, inline bucket. var bucket = Bucket{ bucket: &bucket{}, rootNode: &node{isLeaf: true}, FillPercent: DefaultFillPercent, } var value = bucket.write() // Insert into node. key = cloneBytes(key) c.node().put(key, key, value, 0, bucketLeafFlag) // Since subbuckets are not allowed on inline buckets, we need to // dereference the inline page, if it exists. This will cause the bucket // to be treated as a regular, non-inline bucket for the rest of the tx. b.page = nil return b.Bucket(key), nil } // CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. // Returns an error if the bucket name is blank, or if the bucket name is too long. // The bucket instance is only valid for the lifetime of the transaction. func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { child, err := b.CreateBucket(key) if err == ErrBucketExists { return b.Bucket(key), nil } else if err != nil { return nil, err } return child, nil } // DeleteBucket deletes a bucket at the given key. // Returns an error if the bucket does not exists, or if the key represents a non-bucket value. func (b *Bucket) DeleteBucket(key []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if bucket doesn't exist or is not a bucket. if !bytes.Equal(key, k) { return ErrBucketNotFound } else if (flags & bucketLeafFlag) == 0 { return ErrIncompatibleValue } // Recursively delete all child buckets. child := b.Bucket(key) err := child.ForEach(func(k, v []byte) error { if v == nil { if err := child.DeleteBucket(k); err != nil { return fmt.Errorf("delete bucket: %s", err) } } return nil }) if err != nil { return err } // Remove cached copy. delete(b.buckets, string(key)) // Release all bucket pages to freelist. child.nodes = nil child.rootNode = nil child.free() // Delete the node if we have a matching key. c.node().del(key) return nil } // Get retrieves the value for a key in the bucket. // Returns a nil value if the key does not exist or if the key is a nested bucket. // The returned value is only valid for the life of the transaction. func (b *Bucket) Get(key []byte) []byte { k, v, flags := b.Cursor().seek(key) // Return nil if this is a bucket. if (flags & bucketLeafFlag) != 0 { return nil } // If our target node isn't the same key as what's passed in then return nil. if !bytes.Equal(key, k) { return nil } return v } // Put sets the value for a key in the bucket. // If the key exist then its previous value will be overwritten. // Supplied value must remain valid for the life of the transaction. // Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. func (b *Bucket) Put(key []byte, value []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } else if len(key) == 0 { return ErrKeyRequired } else if len(key) > MaxKeySize { return ErrKeyTooLarge } else if int64(len(value)) > MaxValueSize { return ErrValueTooLarge } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return an error if there is an existing key with a bucket value. if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { return ErrIncompatibleValue } // Insert into node. key = cloneBytes(key) c.node().put(key, key, value, 0, 0) return nil } // Delete removes a key from the bucket. // If the key does not exist then nothing is done and a nil error is returned. // Returns an error if the bucket was created from a read-only transaction. func (b *Bucket) Delete(key []byte) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Move cursor to correct position. c := b.Cursor() k, _, flags := c.seek(key) // Return nil if the key doesn't exist. if !bytes.Equal(key, k) { return nil } // Return an error if there is already existing bucket value. if (flags & bucketLeafFlag) != 0 { return ErrIncompatibleValue } // Delete the node if we have a matching key. c.node().del(key) return nil } // Sequence returns the current integer for the bucket without incrementing it. func (b *Bucket) Sequence() uint64 { return b.bucket.sequence } // SetSequence updates the sequence number for the bucket. func (b *Bucket) SetSequence(v uint64) error { if b.tx.db == nil { return ErrTxClosed } else if !b.Writable() { return ErrTxNotWritable } // Materialize the root node if it hasn't been already so that the // bucket will be saved during commit. if b.rootNode == nil { _ = b.node(b.root, nil) } // Increment and return the sequence. b.bucket.sequence = v return nil } // NextSequence returns an autoincrementing integer for the bucket. func (b *Bucket) NextSequence() (uint64, error) { if b.tx.db == nil { return 0, ErrTxClosed } else if !b.Writable() { return 0, ErrTxNotWritable } // Materialize the root node if it hasn't been already so that the // bucket will be saved during commit. if b.rootNode == nil { _ = b.node(b.root, nil) } // Increment and return the sequence. b.bucket.sequence++ return b.bucket.sequence, nil } // ForEach executes a function for each key/value pair in a bucket. // If the provided function returns an error then the iteration is stopped and // the error is returned to the caller. The provided function must not modify // the bucket; this will result in undefined behavior. func (b *Bucket) ForEach(fn func(k, v []byte) error) error { if b.tx.db == nil { return ErrTxClosed } c := b.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { if err := fn(k, v); err != nil { return err } } return nil } // Stat returns stats on a bucket. func (b *Bucket) Stats() BucketStats { var s, subStats BucketStats pageSize := b.tx.db.pageSize s.BucketN += 1 if b.root == 0 { s.InlineBucketN += 1 } b.forEachPage(func(p *page, depth int) { if (p.flags & leafPageFlag) != 0 { s.KeyN += int(p.count) // used totals the used bytes for the page used := pageHeaderSize if p.count != 0 { // If page has any elements, add all element headers. used += leafPageElementSize * int(p.count-1) // Add all element key, value sizes. // The computation takes advantage of the fact that the position // of the last element's key/value equals to the total of the sizes // of all previous elements' keys and values. // It also includes the last element's header. lastElement := p.leafPageElement(p.count - 1) used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) } if b.root == 0 { // For inlined bucket just update the inline stats s.InlineBucketInuse += used } else { // For non-inlined bucket update all the leaf stats s.LeafPageN++ s.LeafInuse += used s.LeafOverflowN += int(p.overflow) // Collect stats from sub-buckets. // Do that by iterating over all element headers // looking for the ones with the bucketLeafFlag. for i := uint16(0); i < p.count; i++ { e := p.leafPageElement(i) if (e.flags & bucketLeafFlag) != 0 { // For any bucket element, open the element value // and recursively call Stats on the contained bucket. subStats.Add(b.openBucket(e.value()).Stats()) } } } } else if (p.flags & branchPageFlag) != 0 { s.BranchPageN++ lastElement := p.branchPageElement(p.count - 1) // used totals the used bytes for the page // Add header and all element headers. used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) // Add size of all keys and values. // Again, use the fact that last element's position equals to // the total of key, value sizes of all previous elements. used += int(lastElement.pos + lastElement.ksize) s.BranchInuse += used s.BranchOverflowN += int(p.overflow) } // Keep track of maximum page depth. if depth+1 > s.Depth { s.Depth = (depth + 1) } }) // Alloc stats can be computed from page counts and pageSize. s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize // Add the max depth of sub-buckets to get total nested depth. s.Depth += subStats.Depth // Add the stats for all sub-buckets s.Add(subStats) return s } // forEachPage iterates over every page in a bucket, including inline pages. func (b *Bucket) forEachPage(fn func(*page, int)) { // If we have an inline page then just use that. if b.page != nil { fn(b.page, 0) return } // Otherwise traverse the page hierarchy. b.tx.forEachPage(b.root, 0, fn) } // forEachPageNode iterates over every page (or node) in a bucket. // This also includes inline pages. func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) { // If we have an inline page or root node then just use that. if b.page != nil { fn(b.page, nil, 0) return } b._forEachPageNode(b.root, 0, fn) } func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) { var p, n = b.pageNode(pgid) // Execute function. fn(p, n, depth) // Recursively loop over children. if p != nil { if (p.flags & branchPageFlag) != 0 { for i := 0; i < int(p.count); i++ { elem := p.branchPageElement(uint16(i)) b._forEachPageNode(elem.pgid, depth+1, fn) } } } else { if !n.isLeaf { for _, inode := range n.inodes { b._forEachPageNode(inode.pgid, depth+1, fn) } } } } // spill writes all the nodes for this bucket to dirty pages. func (b *Bucket) spill() error { // Spill all child buckets first. for name, child := range b.buckets { // If the child bucket is small enough and it has no child buckets then // write it inline into the parent bucket's page. Otherwise spill it // like a normal bucket and make the parent value a pointer to the page. var value []byte if child.inlineable() { child.free() value = child.write() } else { if err := child.spill(); err != nil { return err } // Update the child bucket header in this bucket. value = make([]byte, unsafe.Sizeof(bucket{})) var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *child.bucket } // Skip writing the bucket if there are no materialized nodes. if child.rootNode == nil { continue } // Update parent node. var c = b.Cursor() k, _, flags := c.seek([]byte(name)) if !bytes.Equal([]byte(name), k) { panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) } if flags&bucketLeafFlag == 0 { panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) } c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) } // Ignore if there's not a materialized root node. if b.rootNode == nil { return nil } // Spill nodes. if err := b.rootNode.spill(); err != nil { return err } b.rootNode = b.rootNode.root() // Update the root node for this bucket. if b.rootNode.pgid >= b.tx.meta.pgid { panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) } b.root = b.rootNode.pgid return nil } // inlineable returns true if a bucket is small enough to be written inline // and if it contains no subbuckets. Otherwise returns false. func (b *Bucket) inlineable() bool { var n = b.rootNode // Bucket must only contain a single leaf node. if n == nil || !n.isLeaf { return false } // Bucket is not inlineable if it contains subbuckets or if it goes beyond // our threshold for inline bucket size. var size = pageHeaderSize for _, inode := range n.inodes { size += leafPageElementSize + len(inode.key) + len(inode.value) if inode.flags&bucketLeafFlag != 0 { return false } else if size > b.maxInlineBucketSize() { return false } } return true } // Returns the maximum total size of a bucket to make it a candidate for inlining. func (b *Bucket) maxInlineBucketSize() int { return b.tx.db.pageSize / 4 } // write allocates and writes a bucket to a byte slice. func (b *Bucket) write() []byte { // Allocate the appropriate size. var n = b.rootNode var value = make([]byte, bucketHeaderSize+n.size()) // Write a bucket header. var bucket = (*bucket)(unsafe.Pointer(&value[0])) *bucket = *b.bucket // Convert byte slice to a fake page and write the root node. var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) n.write(p) return value } // rebalance attempts to balance all nodes. func (b *Bucket) rebalance() { for _, n := range b.nodes { n.rebalance() } for _, child := range b.buckets { child.rebalance() } } // node creates a node from a page and associates it with a given parent. func (b *Bucket) node(pgid pgid, parent *node) *node { _assert(b.nodes != nil, "nodes map expected") // Retrieve node if it's already been created. if n := b.nodes[pgid]; n != nil { return n } // Otherwise create a node and cache it. n := &node{bucket: b, parent: parent} if parent == nil { b.rootNode = n } else { parent.children = append(parent.children, n) } // Use the inline page if this is an inline bucket. var p = b.page if p == nil { p = b.tx.page(pgid) } // Read the page into the node and cache it. n.read(p) b.nodes[pgid] = n // Update statistics. b.tx.stats.NodeCount++ return n } // free recursively frees all pages in the bucket. func (b *Bucket) free() { if b.root == 0 { return } var tx = b.tx b.forEachPageNode(func(p *page, n *node, _ int) { if p != nil { tx.db.freelist.free(tx.meta.txid, p) } else { n.free() } }) b.root = 0 } // dereference removes all references to the old mmap. func (b *Bucket) dereference() { if b.rootNode != nil { b.rootNode.root().dereference() } for _, child := range b.buckets { child.dereference() } } // pageNode returns the in-memory node, if it exists. // Otherwise returns the underlying page. func (b *Bucket) pageNode(id pgid) (*page, *node) { // Inline buckets have a fake page embedded in their value so treat them // differently. We'll return the rootNode (if available) or the fake page. if b.root == 0 { if id != 0 { panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) } if b.rootNode != nil { return nil, b.rootNode } return b.page, nil } // Check the node cache for non-inline buckets. if b.nodes != nil { if n := b.nodes[id]; n != nil { return nil, n } } // Finally lookup the page from the transaction if no node is materialized. return b.tx.page(id), nil } // BucketStats records statistics about resources used by a bucket. type BucketStats struct { // Page count statistics. BranchPageN int // number of logical branch pages BranchOverflowN int // number of physical branch overflow pages LeafPageN int // number of logical leaf pages LeafOverflowN int // number of physical leaf overflow pages // Tree statistics. KeyN int // number of keys/value pairs Depth int // number of levels in B+tree // Page size utilization. BranchAlloc int // bytes allocated for physical branch pages BranchInuse int // bytes actually used for branch data LeafAlloc int // bytes allocated for physical leaf pages LeafInuse int // bytes actually used for leaf data // Bucket statistics BucketN int // total number of buckets including the top bucket InlineBucketN int // total number on inlined buckets InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse) } func (s *BucketStats) Add(other BucketStats) { s.BranchPageN += other.BranchPageN s.BranchOverflowN += other.BranchOverflowN s.LeafPageN += other.LeafPageN s.LeafOverflowN += other.LeafOverflowN s.KeyN += other.KeyN if s.Depth < other.Depth { s.Depth = other.Depth } s.BranchAlloc += other.BranchAlloc s.BranchInuse += other.BranchInuse s.LeafAlloc += other.LeafAlloc s.LeafInuse += other.LeafInuse s.BucketN += other.BucketN s.InlineBucketN += other.InlineBucketN s.InlineBucketInuse += other.InlineBucketInuse } // cloneBytes returns a copy of a given slice. func cloneBytes(v []byte) []byte { var clone = make([]byte, len(v)) copy(clone, v) return clone }
SvenDowideit/docker
vendor/go.etcd.io/bbolt/bucket.go
GO
apache-2.0
21,323
module Sass module Selector # An operator-separated sequence of # {SimpleSequence simple selector sequences}. class Sequence < AbstractSequence # Sets the line of the Sass template on which this selector was declared. # This also sets the line for all child selectors. # # @param line [Fixnum] # @return [Fixnum] def line=(line) members.each {|m| m.line = line if m.is_a?(SimpleSequence)} @line = line end # Sets the name of the file in which this selector was declared, # or `nil` if it was not declared in a file (e.g. on stdin). # This also sets the filename for all child selectors. # # @param filename [String, nil] # @return [String, nil] def filename=(filename) members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)} filename end # The array of {SimpleSequence simple selector sequences}, operators, and # newlines. The operators are strings such as `"+"` and `">"` representing # the corresponding CSS operators, or interpolated SassScript. Newlines # are also newline strings; these aren't semantically relevant, but they # do affect formatting. # # @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] attr_reader :members # @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] # See \{#members} def initialize(seqs_and_ops) @members = seqs_and_ops end # Resolves the {Parent} selectors within this selector # by replacing them with the given parent selector, # handling commas appropriately. # # @param super_cseq [CommaSequence] The parent selector # @param implicit_parent [Boolean] Whether the the parent # selector should automatically be prepended to the resolved # selector if it contains no parent refs. # @return [CommaSequence] This selector, with parent references resolved # @raise [Sass::SyntaxError] If a parent selector is invalid def resolve_parent_refs(super_cseq, implicit_parent) members = @members.dup nl = (members.first == "\n" && members.shift) contains_parent_ref = contains_parent_ref? return CommaSequence.new([self]) if !implicit_parent && !contains_parent_ref unless contains_parent_ref old_members, members = members, [] members << nl if nl members << SimpleSequence.new([Parent.new], false) members += old_members end CommaSequence.new(Sass::Util.paths(members.map do |sseq_or_op| next [sseq_or_op] unless sseq_or_op.is_a?(SimpleSequence) sseq_or_op.resolve_parent_refs(super_cseq).members end).map do |path| Sequence.new(path.map do |seq_or_op| next seq_or_op unless seq_or_op.is_a?(Sequence) seq_or_op.members end.flatten) end) end # Returns whether there's a {Parent} selector anywhere in this sequence. # # @return [Boolean] def contains_parent_ref? members.any? do |sseq_or_op| next false unless sseq_or_op.is_a?(SimpleSequence) next true if sseq_or_op.members.first.is_a?(Parent) sseq_or_op.members.any? do |sel| sel.is_a?(Pseudo) && sel.selector && sel.selector.contains_parent_ref? end end end # Non-destructively extends this selector with the extensions specified in a hash # (which should come from {Sass::Tree::Visitors::Cssize}). # # @param extends [Sass::Util::SubsetMap{Selector::Simple => # Sass::Tree::Visitors::Cssize::Extend}] # The extensions to perform on this selector # @param parent_directives [Array<Sass::Tree::DirectiveNode>] # The directives containing this selector. # @param replace [Boolean] # Whether to replace the original selector entirely or include # it in the result. # @param seen [Set<Array<Selector::Simple>>] # The set of simple sequences that are currently being replaced. # @param original [Boolean] # Whether this is the original selector being extended, as opposed to # the result of a previous extension that's being re-extended. # @return [Array<Sequence>] A list of selectors generated # by extending this selector with `extends`. # These correspond to a {CommaSequence}'s {CommaSequence#members members array}. # @see CommaSequence#do_extend def do_extend(extends, parent_directives, replace, seen, original) extended_not_expanded = members.map do |sseq_or_op| next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence) extended = sseq_or_op.do_extend(extends, parent_directives, replace, seen) # The First Law of Extend says that the generated selector should have # specificity greater than or equal to that of the original selector. # In order to ensure that, we record the original selector's # (`extended.first`) original specificity. extended.first.add_sources!([self]) if original && !has_placeholder? extended.map {|seq| seq.members} end weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)} trim(weaves).map {|p| Sequence.new(p)} end # Unifies this with another selector sequence to produce a selector # that matches (a subset of) the intersection of the two inputs. # # @param other [Sequence] # @return [CommaSequence, nil] The unified selector, or nil if unification failed. # @raise [Sass::SyntaxError] If this selector cannot be unified. # This will only ever occur when a dynamic selector, # such as {Parent} or {Interpolation}, is used in unification. # Since these selectors should be resolved # by the time extension and unification happen, # this exception will only ever be raised as a result of programmer error def unify(other) base = members.last other_base = other.members.last return unless base.is_a?(SimpleSequence) && other_base.is_a?(SimpleSequence) return unless (unified = other_base.unify(base)) woven = weave([members[0...-1], other.members[0...-1] + [unified]]) CommaSequence.new(woven.map {|w| Sequence.new(w)}) end # Returns whether or not this selector matches all elements # that the given selector matches (as well as possibly more). # # @example # (.foo).superselector?(.foo.bar) #=> true # (.foo).superselector?(.bar) #=> false # @param cseq [Sequence] # @return [Boolean] def superselector?(seq) _superselector?(members, seq.members) end # @see AbstractSequence#to_s def to_s(opts = {}) @members.map {|m| m.is_a?(String) ? m : m.to_s(opts)}.join(" ").gsub(/ ?\n ?/, "\n") end # Returns a string representation of the sequence. # This is basically the selector string. # # @return [String] def inspect members.map {|m| m.inspect}.join(" ") end # Add to the {SimpleSequence#sources} sets of the child simple sequences. # This destructively modifies this sequence's members array, but not the # child simple sequences. # # @param sources [Set<Sequence>] def add_sources!(sources) members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m} end # Converts the subject operator "!", if it exists, into a ":has()" # selector. # # @retur [Sequence] def subjectless pre_subject = [] has = [] subject = nil members.each do |sseq_or_op| if subject has << sseq_or_op elsif sseq_or_op.is_a?(String) || !sseq_or_op.subject? pre_subject << sseq_or_op else subject = sseq_or_op.dup subject.members = sseq_or_op.members.dup subject.subject = false has = [] end end return self unless subject unless has.empty? subject.members << Pseudo.new(:class, 'has', nil, CommaSequence.new([Sequence.new(has)])) end Sequence.new(pre_subject + [subject]) end private # Conceptually, this expands "parenthesized selectors". That is, if we # have `.A .B {@extend .C}` and `.D .C {...}`, this conceptually expands # into `.D .C, .D (.A .B)`, and this function translates `.D (.A .B)` into # `.D .A .B, .A .D .B`. For thoroughness, `.A.D .B` would also be # required, but including merged selectors results in exponential output # for very little gain. # # @param path [Array<Array<SimpleSequence or String>>] # A list of parenthesized selector groups. # @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors. def weave(path) # This function works by moving through the selector path left-to-right, # building all possible prefixes simultaneously. prefixes = [[]] path.each do |current| next if current.empty? current = current.dup last_current = [current.pop] prefixes = prefixes.map do |prefix| sub = subweave(prefix, current) next [] unless sub sub.map {|seqs| seqs + last_current} end.flatten(1) end prefixes end # This interweaves two lists of selectors, # returning all possible orderings of them (including using unification) # that maintain the relative ordering of the input arrays. # # For example, given `.foo .bar` and `.baz .bang`, # this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`, # `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`, # and so on until `.baz .bang .foo .bar`. # # Semantically, for selectors A and B, this returns all selectors `AB_i` # such that the union over all i of elements matched by `AB_i X` is # identical to the intersection of all elements matched by `A X` and all # elements matched by `B X`. Some `AB_i` are elided to reduce the size of # the output. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<Array<SimpleSequence or String>>] def subweave(seq1, seq2) return [seq2] if seq1.empty? return [seq1] if seq2.empty? seq1, seq2 = seq1.dup, seq2.dup return unless (init = merge_initial_ops(seq1, seq2)) return unless (fin = merge_final_ops(seq1, seq2)) # Make sure there's only one root selector in the output. root1 = has_root?(seq1.first) && seq1.shift root2 = has_root?(seq2.first) && seq2.shift if root1 && root2 return unless (root = root1.unify(root2)) seq1.unshift root seq2.unshift root elsif root1 seq2.unshift root1 elsif root2 seq1.unshift root2 end seq1 = group_selectors(seq1) seq2 = group_selectors(seq2) lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2| next s1 if s1 == s2 next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence) next s2 if parent_superselector?(s1, s2) next s1 if parent_superselector?(s2, s1) end diff = [[init]] until lcs.empty? diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift] seq1.shift seq2.shift end diff << chunks(seq1, seq2) {|s| s.empty?} diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]} diff.reject! {|c| c.empty?} Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)} end # Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`) # from two sequences and merges them together into a single array of # selector combinators. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<String>, nil] If there are no operators in the merged # sequence, this will be the empty array. If the operators cannot be # merged, this will be nil. def merge_initial_ops(seq1, seq2) ops1, ops2 = [], [] ops1 << seq1.shift while seq1.first.is_a?(String) ops2 << seq2.shift while seq2.first.is_a?(String) newline = false newline ||= !!ops1.shift if ops1.first == "\n" newline ||= !!ops2.shift if ops2.first == "\n" # If neither sequence is a subsequence of the other, they cannot be # merged successfully lcs = Sass::Util.lcs(ops1, ops2) return unless lcs == ops1 || lcs == ops2 (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2) end # Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the # selectors to which they apply from two sequences and merges them # together into a single array. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<SimpleSequence or String or # Array<Array<SimpleSequence or String>>] # If there are no trailing combinators to be merged, this will be the # empty array. If the trailing combinators cannot be merged, this will # be nil. Otherwise, this will contained the merged selector. Array # elements are [Sass::Util#paths]-style options; conceptually, an "or" # of multiple selectors. # @comment # rubocop:disable MethodLength def merge_final_ops(seq1, seq2, res = []) ops1, ops2 = [], [] ops1 << seq1.pop while seq1.last.is_a?(String) ops2 << seq2.pop while seq2.last.is_a?(String) # Not worth the headache of trying to preserve newlines here. The most # important use of newlines is at the beginning of the selector to wrap # across lines anyway. ops1.reject! {|o| o == "\n"} ops2.reject! {|o| o == "\n"} return res if ops1.empty? && ops2.empty? if ops1.size > 1 || ops2.size > 1 # If there are multiple operators, something hacky's going on. If one # is a supersequence of the other, use that, otherwise give up. lcs = Sass::Util.lcs(ops1, ops2) return unless lcs == ops1 || lcs == ops2 res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse) return res end # This code looks complicated, but it's actually just a bunch of special # cases for interactions between different combinators. op1, op2 = ops1.first, ops2.first if op1 && op2 sel1 = seq1.pop sel2 = seq2.pop if op1 == '~' && op2 == '~' if sel1.superselector?(sel2) res.unshift sel2, '~' elsif sel2.superselector?(sel1) res.unshift sel1, '~' else merged = sel1.unify(sel2) res.unshift [ [sel1, '~', sel2, '~'], [sel2, '~', sel1, '~'], ([merged, '~'] if merged) ].compact end elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~') if op1 == '~' tilde_sel, plus_sel = sel1, sel2 else tilde_sel, plus_sel = sel2, sel1 end if tilde_sel.superselector?(plus_sel) res.unshift plus_sel, '+' else merged = plus_sel.unify(tilde_sel) res.unshift [ [tilde_sel, '~', plus_sel, '+'], ([merged, '+'] if merged) ].compact end elsif op1 == '>' && %w(~ +).include?(op2) res.unshift sel2, op2 seq1.push sel1, op1 elsif op2 == '>' && %w(~ +).include?(op1) res.unshift sel1, op1 seq2.push sel2, op2 elsif op1 == op2 merged = sel1.unify(sel2) return unless merged res.unshift merged, op1 else # Unknown selector combinators can't be unified return end return merge_final_ops(seq1, seq2, res) elsif op1 seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last) res.unshift seq1.pop, op1 return merge_final_ops(seq1, seq2, res) else # op2 seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last) res.unshift seq2.pop, op2 return merge_final_ops(seq1, seq2, res) end end # @comment # rubocop:enable MethodLength # Takes initial subsequences of `seq1` and `seq2` and returns all # orderings of those subsequences. The initial subsequences are determined # by a block. # # Destructively removes the initial subsequences of `seq1` and `seq2`. # # For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|` # denoting the boundary of the initial subsequence), this would return # `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and # `(3 4 5)`. # # @param seq1 [Array] # @param seq2 [Array] # @yield [a] Used to determine when to cut off the initial subsequences. # Called repeatedly for each sequence until it returns true. # @yieldparam a [Array] A final subsequence of one input sequence after # cutting off some initial subsequence. # @yieldreturn [Boolean] Whether or not to cut off the initial subsequence # here. # @return [Array<Array>] All possible orderings of the initial subsequences. def chunks(seq1, seq2) chunk1 = [] chunk1 << seq1.shift until yield seq1 chunk2 = [] chunk2 << seq2.shift until yield seq2 return [] if chunk1.empty? && chunk2.empty? return [chunk2] if chunk1.empty? return [chunk1] if chunk2.empty? [chunk1 + chunk2, chunk2 + chunk1] end # Groups a sequence into subsequences. The subsequences are determined by # strings; adjacent non-string elements will be put into separate groups, # but any element adjacent to a string will be grouped with that string. # # For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D) # (E "F" G "H" "I" J)]`. # # @param seq [Array] # @return [Array<Array>] def group_selectors(seq) newseq = [] tail = seq.dup until tail.empty? head = [] begin head << tail.shift end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String) newseq << head end newseq end # Given two selector sequences, returns whether `seq1` is a # superselector of `seq2`; that is, whether `seq1` matches every # element `seq2` matches. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Boolean] def _superselector?(seq1, seq2) seq1 = seq1.reject {|e| e == "\n"} seq2 = seq2.reject {|e| e == "\n"} # Selectors with leading or trailing operators are neither # superselectors nor subselectors. return if seq1.last.is_a?(String) || seq2.last.is_a?(String) || seq1.first.is_a?(String) || seq2.first.is_a?(String) # More complex selectors are never superselectors of less complex ones return if seq1.size > seq2.size return seq1.first.superselector?(seq2.last, seq2[0...-1]) if seq1.size == 1 _, si = Sass::Util.enum_with_index(seq2).find do |e, i| return if i == seq2.size - 1 next if e.is_a?(String) seq1.first.superselector?(e, seq2[0...i]) end return unless si if seq1[1].is_a?(String) return unless seq2[si + 1].is_a?(String) # .foo ~ .bar is a superselector of .foo + .bar return unless seq1[1] == "~" ? seq2[si + 1] != ">" : seq1[1] == seq2[si + 1] # .foo > .baz is not a superselector of .foo > .bar > .baz or .foo > # .bar .baz, despite the fact that .baz is a superselector of .bar > # .baz and .bar .baz. Same goes for + and ~. return if seq1.length == 3 && seq2.length > 3 return _superselector?(seq1[2..-1], seq2[si + 2..-1]) elsif seq2[si + 1].is_a?(String) return unless seq2[si + 1] == ">" return _superselector?(seq1[1..-1], seq2[si + 2..-1]) else return _superselector?(seq1[1..-1], seq2[si + 1..-1]) end end # Like \{#_superselector?}, but compares the selectors in the # context of parent selectors, as though they shared an implicit # base simple selector. For example, `B` is not normally a # superselector of `B A`, since it doesn't match `A` elements. # However, it is a parent superselector, since `B X` is a # superselector of `B A X`. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Boolean] def parent_superselector?(seq1, seq2) base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')], false) _superselector?(seq1 + [base], seq2 + [base]) end # Removes redundant selectors from between multiple lists of # selectors. This takes a list of lists of selector sequences; # each individual list is assumed to have no redundancy within # itself. A selector is only removed if it's redundant with a # selector in another list. # # "Redundant" here means that one selector is a superselector of # the other. The more specific selector is removed. # # @param seqses [Array<Array<Array<SimpleSequence or String>>>] # @return [Array<Array<SimpleSequence or String>>] def trim(seqses) # Avoid truly horrific quadratic behavior. TODO: I think there # may be a way to get perfect trimming without going quadratic. return seqses.flatten(1) if seqses.size > 100 # Keep the results in a separate array so we can be sure we aren't # comparing against an already-trimmed selector. This ensures that two # identical selectors don't mutually trim one another. result = seqses.dup # This is n^2 on the sequences, but only comparing between # separate sequences should limit the quadratic behavior. seqses.each_with_index do |seqs1, i| result[i] = seqs1.reject do |seq1| # The maximum specificity of the sources that caused [seq1] to be # generated. In order for [seq1] to be removed, there must be # another selector that's a superselector of it *and* that has # specificity greater or equal to this. max_spec = _sources(seq1).map do |seq| spec = seq.specificity spec.is_a?(Range) ? spec.max : spec end.max || 0 result.any? do |seqs2| next if seqs1.equal?(seqs2) # Second Law of Extend: the specificity of a generated selector # should never be less than the specificity of the extending # selector. # # See https://github.com/nex3/sass/issues/324. seqs2.any? do |seq2| spec2 = _specificity(seq2) spec2 = spec2.begin if spec2.is_a?(Range) spec2 >= max_spec && _superselector?(seq2, seq1) end end end end result.flatten(1) end def _hash members.reject {|m| m == "\n"}.hash end def _eql?(other) other.members.reject {|m| m == "\n"}.eql?(members.reject {|m| m == "\n"}) end private def path_has_two_subjects?(path) subject = false path.each do |sseq_or_op| next unless sseq_or_op.is_a?(SimpleSequence) next unless sseq_or_op.subject? return true if subject subject = true end false end def _sources(seq) s = Set.new seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)} s end def extended_not_expanded_to_s(extended_not_expanded) extended_not_expanded.map do |choices| choices = choices.map do |sel| next sel.first.to_s if sel.size == 1 "#{sel.join ' '}" end next choices.first if choices.size == 1 && !choices.include?(' ') "(#{choices.join ', '})" end.join ' ' end def has_root?(sseq) sseq.is_a?(SimpleSequence) && sseq.members.any? {|sel| sel.is_a?(Pseudo) && sel.normalized_name == "root"} end end end end
MFAnderson/gocd
server/webapp/WEB-INF/rails.new/vendor/bundle/jruby/1.9/gems/sass-3.4.22/lib/sass/selector/sequence.rb
Ruby
apache-2.0
25,575
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.strategy; import org.apache.camel.Exchange; import org.apache.camel.component.file.GenericFile; import org.apache.camel.component.file.GenericFileEndpoint; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.apache.camel.component.file.GenericFileOperations; public class GenericFileDeleteProcessStrategy<T> extends GenericFileProcessStrategySupport<T> { private GenericFileRenamer<T> failureRenamer; private GenericFileRenamer<T> beginRenamer; @Override public boolean begin(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { // must invoke super boolean result = super.begin(operations, endpoint, exchange, file); if (!result) { return false; } // okay we got the file then execute the begin renamer if (beginRenamer != null) { GenericFile<T> newName = beginRenamer.renameFile(exchange, file); GenericFile<T> to = renameFile(operations, file, newName); if (to != null) { to.bindToExchange(exchange); } } return true; } @Override public void commit(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { // special for file lock strategy as we must release that lock first before we can delete the file boolean releaseEager = exclusiveReadLockStrategy instanceof FileLockExclusiveReadLockStrategy; if (releaseEager) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnCommit(operations, file, exchange); } try { deleteLocalWorkFile(exchange); operations.releaseRetreivedFileResources(exchange); int retries = 3; boolean deleted = false; while (retries > 0 && !deleted) { retries--; if (operations.deleteFile(file.getAbsoluteFilePath())) { // file is deleted deleted = true; break; } // some OS can report false when deleting but the file is still deleted // use exists to check instead boolean exits = operations.existsFile(file.getAbsoluteFilePath()); if (!exits) { deleted = true; } else { log.trace("File was not deleted at this attempt will try again in 1 sec.: {}", file); // sleep a bit and try again Thread.sleep(1000); } } if (!deleted) { throw new GenericFileOperationFailedException("Cannot delete file: " + file); } } finally { // must release lock last if (!releaseEager && exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnCommit(operations, file, exchange); } } } @Override public void rollback(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint, Exchange exchange, GenericFile<T> file) throws Exception { try { deleteLocalWorkFile(exchange); operations.releaseRetreivedFileResources(exchange); // moved the failed file if specifying the moveFailed option if (failureRenamer != null) { // create a copy and bind the file to the exchange to be used by the renamer to evaluate the file name Exchange copy = exchange.copy(); file.bindToExchange(copy); // must preserve message id copy.getIn().setMessageId(exchange.getIn().getMessageId()); copy.setExchangeId(exchange.getExchangeId()); GenericFile<T> newName = failureRenamer.renameFile(copy, file); renameFile(operations, file, newName); } } finally { // must release lock last if (exclusiveReadLockStrategy != null) { exclusiveReadLockStrategy.releaseExclusiveReadLockOnRollback(operations, file, exchange); } } } public GenericFileRenamer<T> getFailureRenamer() { return failureRenamer; } public void setFailureRenamer(GenericFileRenamer<T> failureRenamer) { this.failureRenamer = failureRenamer; } public GenericFileRenamer<T> getBeginRenamer() { return beginRenamer; } public void setBeginRenamer(GenericFileRenamer<T> beginRenamer) { this.beginRenamer = beginRenamer; } }
partis/camel
camel-core/src/main/java/org/apache/camel/component/file/strategy/GenericFileDeleteProcessStrategy.java
Java
apache-2.0
5,580
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.wikinotes.db.WikiNote; /** * Wikinote editor activity. This is a very simple activity that allows the user * to edit a wikinote using a text editor and confirm or cancel the changes. The * title and body for the wikinote to edit are passed in using the extras bundle * and the onFreeze() method provisions for those values to be stored in the * icicle on a lifecycle event, so that the user retains control over whether * the changes are committed to the database. */ public class WikiNoteEditor extends Activity { protected static final String ACTIVITY_RESULT = "com.google.android.wikinotes.EDIT"; private EditText mNoteEdit; private String mWikiNoteTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.wiki_note_edit); mNoteEdit = (EditText) findViewById(R.id.noteEdit); // Check to see if the icicle has body and title values to restore String wikiNoteText = icicle == null ? null : icicle.getString(WikiNote.Notes.BODY); String wikiNoteTitle = icicle == null ? null : icicle.getString(WikiNote.Notes.TITLE); // If not, check to see if the extras bundle has these values passed in if (wikiNoteTitle == null) { Bundle extras = getIntent().getExtras(); wikiNoteText = extras == null ? null : extras .getString(WikiNote.Notes.BODY); wikiNoteTitle = extras == null ? null : extras .getString(WikiNote.Notes.TITLE); } // If we have no title information, this is an invalid intent request if (TextUtils.isEmpty(wikiNoteTitle)) { // no note title - bail setResult(RESULT_CANCELED); finish(); return; } mWikiNoteTitle = wikiNoteTitle; // but if the body is null, just set it to empty - first edit of this // note wikiNoteText = wikiNoteText == null ? "" : wikiNoteText; // set the title so we know which note we are editing setTitle(getString(R.string.wiki_editing, wikiNoteTitle)); // set the note body to edit mNoteEdit.setText(wikiNoteText); // set listeners for the confirm and cancel buttons ((Button) findViewById(R.id.confirmButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = new Intent(); i.putExtra(ACTIVITY_RESULT, mNoteEdit.getText() .toString()); setResult(RESULT_OK, i); finish(); } }); ((Button) findViewById(R.id.cancelButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish(); } }); if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(WikiNote.Notes.TITLE, mWikiNoteTitle); outState.putString(WikiNote.Notes.BODY, mNoteEdit.getText().toString()); } }
felipecousin/apps-for-android
WikiNotes/src/com/google/android/wikinotes/WikiNoteEditor.java
Java
apache-2.0
3,997
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // 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. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.3', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); } catch(e) { // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); } }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
jboyens/grails-springcache
test/projects/content-caching/web-app/js/prototype/scriptaculous.js
JavaScript
apache-2.0
2,936
// Package v4 implements signing for AWS V4 signer // // Provides request signing for request that need to be signed with // AWS V4 Signatures. // // Standalone Signer // // Generally using the signer outside of the SDK should not require any additional // logic when using Go v1.5 or higher. The signer does this by taking advantage // of the URL.EscapedPath method. If your request URI requires additional escaping // you many need to use the URL.Opaque to define what the raw URI should be sent // to the service as. // // The signer will first check the URL.Opaque field, and use its value if set. // The signer does require the URL.Opaque field to be set in the form of: // // "//<hostname>/<path>" // // // e.g. // "//example.com/some/path" // // The leading "//" and hostname are required or the URL.Opaque escaping will // not work correctly. // // If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() // method and using the returned value. If you're using Go v1.4 you must set // URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with // Go v1.5 the signer will fallback to URL.Path. // // AWS v4 signature validation requires that the canonical string's URI path // element must be the URI escaped form of the HTTP request's path. // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html // // The Go HTTP client will perform escaping automatically on the request. Some // of these escaping may cause signature validation errors because the HTTP // request differs from the URI path or query that the signature was generated. // https://golang.org/pkg/net/url/#URL.EscapedPath // // Because of this, it is recommended that when using the signer outside of the // SDK that explicitly escaping the request prior to being signed is preferable, // and will help prevent signature validation errors. This can be done by setting // the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then // call URL.EscapedPath() if Opaque is not set. // // If signing a request intended for HTTP2 server, and you're using Go 1.6.2 // through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the // request URL. https://github.com/golang/go/issues/16847 points to a bug in // Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP // message. URL.Opaque generally will force Go to make requests with absolute URL. // URL.RawPath does not do this, but RawPath must be a valid escaping of Path // or url.EscapedPath will ignore the RawPath escaping. // // Test `TestStandaloneSign` provides a complete example of using the signer // outside of the SDK and pre-escaping the URI path. package v4 import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "net/http" "net/url" "sort" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/internal/sdkio" "github.com/aws/aws-sdk-go/private/protocol/rest" ) const ( authorizationHeader = "Authorization" authHeaderSignatureElem = "Signature=" signatureQueryKey = "X-Amz-Signature" authHeaderPrefix = "AWS4-HMAC-SHA256" timeFormat = "20060102T150405Z" shortTimeFormat = "20060102" awsV4Request = "aws4_request" // emptyStringSHA256 is a SHA256 of an empty string emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` ) var ignoredHeaders = rules{ blacklist{ mapRule{ authorizationHeader: struct{}{}, "User-Agent": struct{}{}, "X-Amzn-Trace-Id": struct{}{}, }, }, } // requiredSignedHeaders is a whitelist for build canonical headers. var requiredSignedHeaders = rules{ whitelist{ mapRule{ "Cache-Control": struct{}{}, "Content-Disposition": struct{}{}, "Content-Encoding": struct{}{}, "Content-Language": struct{}{}, "Content-Md5": struct{}{}, "Content-Type": struct{}{}, "Expires": struct{}{}, "If-Match": struct{}{}, "If-Modified-Since": struct{}{}, "If-None-Match": struct{}{}, "If-Unmodified-Since": struct{}{}, "Range": struct{}{}, "X-Amz-Acl": struct{}{}, "X-Amz-Copy-Source": struct{}{}, "X-Amz-Copy-Source-If-Match": struct{}{}, "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, "X-Amz-Copy-Source-If-None-Match": struct{}{}, "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, "X-Amz-Copy-Source-Range": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Grant-Full-control": struct{}{}, "X-Amz-Grant-Read": struct{}{}, "X-Amz-Grant-Read-Acp": struct{}{}, "X-Amz-Grant-Write": struct{}{}, "X-Amz-Grant-Write-Acp": struct{}{}, "X-Amz-Metadata-Directive": struct{}{}, "X-Amz-Mfa": struct{}{}, "X-Amz-Request-Payer": struct{}{}, "X-Amz-Server-Side-Encryption": struct{}{}, "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Storage-Class": struct{}{}, "X-Amz-Tagging": struct{}{}, "X-Amz-Website-Redirect-Location": struct{}{}, "X-Amz-Content-Sha256": struct{}{}, }, }, patterns{"X-Amz-Meta-"}, } // allowedHoisting is a whitelist for build query headers. The boolean value // represents whether or not it is a pattern. var allowedQueryHoisting = inclusiveRules{ blacklist{requiredSignedHeaders}, patterns{"X-Amz-"}, } // Signer applies AWS v4 signing to given request. Use this to sign requests // that need to be signed with AWS V4 Signatures. type Signer struct { // The authentication credentials the request will be signed against. // This value must be set to sign requests. Credentials *credentials.Credentials // Sets the log level the signer should use when reporting information to // the logger. If the logger is nil nothing will be logged. See // aws.LogLevelType for more information on available logging levels // // By default nothing will be logged. Debug aws.LogLevelType // The logger loging information will be written to. If there the logger // is nil, nothing will be logged. Logger aws.Logger // Disables the Signer's moving HTTP header key/value pairs from the HTTP // request header to the request's query string. This is most commonly used // with pre-signed requests preventing headers from being added to the // request's query string. DisableHeaderHoisting bool // Disables the automatic escaping of the URI path of the request for the // siganture's canonical string's path. For services that do not need additional // escaping then use this to disable the signer escaping the path. // // S3 is an example of a service that does not need additional escaping. // // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html DisableURIPathEscaping bool // Disables the automatical setting of the HTTP request's Body field with the // io.ReadSeeker passed in to the signer. This is useful if you're using a // custom wrapper around the body for the io.ReadSeeker and want to preserve // the Body value on the Request.Body. // // This does run the risk of signing a request with a body that will not be // sent in the request. Need to ensure that the underlying data of the Body // values are the same. DisableRequestBodyOverwrite bool // currentTimeFn returns the time value which represents the current time. // This value should only be used for testing. If it is nil the default // time.Now will be used. currentTimeFn func() time.Time // UnsignedPayload will prevent signing of the payload. This will only // work for services that have support for this. UnsignedPayload bool } // NewSigner returns a Signer pointer configured with the credentials and optional // option values provided. If not options are provided the Signer will use its // default configuration. func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { v4 := &Signer{ Credentials: credentials, } for _, option := range options { option(v4) } return v4 } type signingCtx struct { ServiceName string Region string Request *http.Request Body io.ReadSeeker Query url.Values Time time.Time ExpireTime time.Duration SignedHeaderVals http.Header DisableURIPathEscaping bool credValues credentials.Value isPresign bool unsignedPayload bool bodyDigest string signedHeaders string canonicalHeaders string canonicalString string credentialString string stringToSign string signature string authorization string } // Sign signs AWS v4 requests with the provided body, service name, region the // request is made to, and time the request is signed at. The signTime allows // you to specify that a request is signed for the future, and cannot be // used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. Generally for signed requests this value // is not needed as the full request context will be captured by the http.Request // value. It is included for reference though. // // Sign will set the request's Body to be the `body` parameter passed in. If // the body is not already an io.ReadCloser, it will be wrapped within one. If // a `nil` body parameter passed to Sign, the request's Body field will be // also set to nil. Its important to note that this functionality will not // change the request's ContentLength of the request. // // Sign differs from Presign in that it will sign the request using HTTP // header values. This type of signing is intended for http.Request values that // will not be shared, or are shared in a way the header values on the request // will not be lost. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, 0, false, signTime) } // Presign signs AWS v4 requests with the provided body, service name, region // the request is made to, and time the request is signed at. The signTime // allows you to specify that a request is signed for the future, and cannot // be used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. For presigned requests these headers // and their values must be included on the HTTP request when it is made. This // is helpful to know what header values need to be shared with the party the // presigned request will be distributed to. // // Presign differs from Sign in that it will sign the request using query string // instead of header values. This allows you to share the Presigned Request's // URL with third parties, or distribute it throughout your system with minimal // dependencies. // // Presign also takes an exp value which is the duration the // signed request will be valid after the signing time. This is allows you to // set when the request will expire. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. // // Presigning a S3 request will not compute the body's SHA256 hash by default. // This is done due to the general use case for S3 presigned URLs is to share // PUT/GET capabilities. If you would like to include the body's SHA256 in the // presigned request's signature you can set the "X-Amz-Content-Sha256" // HTTP header and that will be included in the request's signature. func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, exp, true, signTime) } func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { currentTimeFn := v4.currentTimeFn if currentTimeFn == nil { currentTimeFn = time.Now } ctx := &signingCtx{ Request: r, Body: body, Query: r.URL.Query(), Time: signTime, ExpireTime: exp, isPresign: isPresign, ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, unsignedPayload: v4.UnsignedPayload, } for key := range ctx.Query { sort.Strings(ctx.Query[key]) } if ctx.isRequestSigned() { ctx.Time = currentTimeFn() ctx.handlePresignRemoval() } var err error ctx.credValues, err = v4.Credentials.GetWithContext(requestContext(r)) if err != nil { return http.Header{}, err } ctx.sanitizeHostForHeader() ctx.assignAmzQueryValues() if err := ctx.build(v4.DisableHeaderHoisting); err != nil { return nil, err } // If the request is not presigned the body should be attached to it. This // prevents the confusion of wanting to send a signed request without // the body the request was signed for attached. if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { var reader io.ReadCloser if body != nil { var ok bool if reader, ok = body.(io.ReadCloser); !ok { reader = ioutil.NopCloser(body) } } r.Body = reader } if v4.Debug.Matches(aws.LogDebugWithSigning) { v4.logSigningInfo(ctx) } return ctx.SignedHeaderVals, nil } func (ctx *signingCtx) sanitizeHostForHeader() { request.SanitizeHostForHeader(ctx.Request) } func (ctx *signingCtx) handlePresignRemoval() { if !ctx.isPresign { return } // The credentials have expired for this request. The current signing // is invalid, and needs to be request because the request will fail. ctx.removePresign() // Update the request's query string to ensure the values stays in // sync in the case retrieving the new credentials fails. ctx.Request.URL.RawQuery = ctx.Query.Encode() } func (ctx *signingCtx) assignAmzQueryValues() { if ctx.isPresign { ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) if ctx.credValues.SessionToken != "" { ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } else { ctx.Query.Del("X-Amz-Security-Token") } return } if ctx.credValues.SessionToken != "" { ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } } // SignRequestHandler is a named request handler the SDK will use to sign // service client request with using the V4 signature. var SignRequestHandler = request.NamedHandler{ Name: "v4.SignRequestHandler", Fn: SignSDKRequest, } // SignSDKRequest signs an AWS request with the V4 signature. This // request handler should only be used with the SDK's built in service client's // API operation requests. // // This function should not be used on its on its own, but in conjunction with // an AWS service client's API operation call. To sign a standalone request // not created by a service client's API operation method use the "Sign" or // "Presign" functions of the "Signer" type. // // If the credentials of the request's config are set to // credentials.AnonymousCredentials the request will not be signed. func SignSDKRequest(req *request.Request) { SignSDKRequestWithCurrentTime(req, time.Now) } // BuildNamedHandler will build a generic handler for signing. func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { return request.NamedHandler{ Name: name, Fn: func(req *request.Request) { SignSDKRequestWithCurrentTime(req, time.Now, opts...) }, } } // SignSDKRequestWithCurrentTime will sign the SDK's request using the time // function passed in. Behaves the same as SignSDKRequest with the exception // the request is signed with the value returned by the current time function. func SignSDKRequestWithCurrentTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { return } region := req.ClientInfo.SigningRegion if region == "" { region = aws.StringValue(req.Config.Region) } name := req.ClientInfo.SigningName if name == "" { name = req.ClientInfo.ServiceName } v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { v4.Debug = req.Config.LogLevel.Value() v4.Logger = req.Config.Logger v4.DisableHeaderHoisting = req.NotHoist v4.currentTimeFn = curTimeFn if name == "s3" { // S3 service should not have any escaping applied v4.DisableURIPathEscaping = true } // Prevents setting the HTTPRequest's Body. Since the Body could be // wrapped in a custom io.Closer that we do not want to be stompped // on top of by the signer. v4.DisableRequestBodyOverwrite = true }) for _, opt := range opts { opt(v4) } curTime := curTimeFn() signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), name, region, req.ExpireTime, req.ExpireTime > 0, curTime, ) if err != nil { req.Error = err req.SignedHeaderVals = nil return } req.SignedHeaderVals = signedHeaders req.LastSignedAt = curTime } const logSignInfoMsg = `DEBUG: Request Signature: ---[ CANONICAL STRING ]----------------------------- %s ---[ STRING TO SIGN ]-------------------------------- %s%s -----------------------------------------------------` const logSignedURLMsg = ` ---[ SIGNED URL ]------------------------------------ %s` func (v4 *Signer) logSigningInfo(ctx *signingCtx) { signedURLMsg := "" if ctx.isPresign { signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) } msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) v4.Logger.Log(msg) } func (ctx *signingCtx) build(disableHeaderHoisting bool) error { ctx.buildTime() // no depends ctx.buildCredentialString() // no depends if err := ctx.buildBodyDigest(); err != nil { return err } unsignedHeaders := ctx.Request.Header if ctx.isPresign { if !disableHeaderHoisting { urlValues := url.Values{} urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends for k := range urlValues { ctx.Query[k] = urlValues[k] } } } ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) ctx.buildCanonicalString() // depends on canon headers / signed headers ctx.buildStringToSign() // depends on canon string ctx.buildSignature() // depends on string to sign if ctx.isPresign { ctx.Request.URL.RawQuery += "&" + signatureQueryKey + "=" + ctx.signature } else { parts := []string{ authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, "SignedHeaders=" + ctx.signedHeaders, authHeaderSignatureElem + ctx.signature, } ctx.Request.Header.Set(authorizationHeader, strings.Join(parts, ", ")) } return nil } // GetSignedRequestSignature attempts to extract the signature of the request. // Returning an error if the request is unsigned, or unable to extract the // signature. func GetSignedRequestSignature(r *http.Request) ([]byte, error) { if auth := r.Header.Get(authorizationHeader); len(auth) != 0 { ps := strings.Split(auth, ", ") for _, p := range ps { if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 { sig := p[len(authHeaderSignatureElem):] if len(sig) == 0 { return nil, fmt.Errorf("invalid request signature authorization header") } return hex.DecodeString(sig) } } } if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 { return hex.DecodeString(sig) } return nil, fmt.Errorf("request not signed") } func (ctx *signingCtx) buildTime() { if ctx.isPresign { duration := int64(ctx.ExpireTime / time.Second) ctx.Query.Set("X-Amz-Date", formatTime(ctx.Time)) ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) } else { ctx.Request.Header.Set("X-Amz-Date", formatTime(ctx.Time)) } } func (ctx *signingCtx) buildCredentialString() { ctx.credentialString = buildSigningScope(ctx.Region, ctx.ServiceName, ctx.Time) if ctx.isPresign { ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) } } func buildQuery(r rule, header http.Header) (url.Values, http.Header) { query := url.Values{} unsignedHeaders := http.Header{} for k, h := range header { if r.IsValid(k) { query[k] = h } else { unsignedHeaders[k] = h } } return query, unsignedHeaders } func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { var headers []string headers = append(headers, "host") for k, v := range header { if !r.IsValid(k) { continue // ignored header } if ctx.SignedHeaderVals == nil { ctx.SignedHeaderVals = make(http.Header) } lowerCaseKey := strings.ToLower(k) if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { // include additional values ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) continue } headers = append(headers, lowerCaseKey) ctx.SignedHeaderVals[lowerCaseKey] = v } sort.Strings(headers) ctx.signedHeaders = strings.Join(headers, ";") if ctx.isPresign { ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) } headerValues := make([]string, len(headers)) for i, k := range headers { if k == "host" { if ctx.Request.Host != "" { headerValues[i] = "host:" + ctx.Request.Host } else { headerValues[i] = "host:" + ctx.Request.URL.Host } } else { headerValues[i] = k + ":" + strings.Join(ctx.SignedHeaderVals[k], ",") } } stripExcessSpaces(headerValues) ctx.canonicalHeaders = strings.Join(headerValues, "\n") } func (ctx *signingCtx) buildCanonicalString() { ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) uri := getURIPath(ctx.Request.URL) if !ctx.DisableURIPathEscaping { uri = rest.EscapePath(uri, false) } ctx.canonicalString = strings.Join([]string{ ctx.Request.Method, uri, ctx.Request.URL.RawQuery, ctx.canonicalHeaders + "\n", ctx.signedHeaders, ctx.bodyDigest, }, "\n") } func (ctx *signingCtx) buildStringToSign() { ctx.stringToSign = strings.Join([]string{ authHeaderPrefix, formatTime(ctx.Time), ctx.credentialString, hex.EncodeToString(hashSHA256([]byte(ctx.canonicalString))), }, "\n") } func (ctx *signingCtx) buildSignature() { creds := deriveSigningKey(ctx.Region, ctx.ServiceName, ctx.credValues.SecretAccessKey, ctx.Time) signature := hmacSHA256(creds, []byte(ctx.stringToSign)) ctx.signature = hex.EncodeToString(signature) } func (ctx *signingCtx) buildBodyDigest() error { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { includeSHA256Header := ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" s3Presign := ctx.isPresign && ctx.ServiceName == "s3" if ctx.unsignedPayload || s3Presign { hash = "UNSIGNED-PAYLOAD" includeSHA256Header = !s3Presign } else if ctx.Body == nil { hash = emptyStringSHA256 } else { if !aws.IsReaderSeekable(ctx.Body) { return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) } hashBytes, err := makeSha256Reader(ctx.Body) if err != nil { return err } hash = hex.EncodeToString(hashBytes) } if includeSHA256Header { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } ctx.bodyDigest = hash return nil } // isRequestSigned returns if the request is currently signed or presigned func (ctx *signingCtx) isRequestSigned() bool { if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { return true } if ctx.Request.Header.Get("Authorization") != "" { return true } return false } // unsign removes signing flags for both signed and presigned requests. func (ctx *signingCtx) removePresign() { ctx.Query.Del("X-Amz-Algorithm") ctx.Query.Del("X-Amz-Signature") ctx.Query.Del("X-Amz-Security-Token") ctx.Query.Del("X-Amz-Date") ctx.Query.Del("X-Amz-Expires") ctx.Query.Del("X-Amz-Credential") ctx.Query.Del("X-Amz-SignedHeaders") } func hmacSHA256(key []byte, data []byte) []byte { hash := hmac.New(sha256.New, key) hash.Write(data) return hash.Sum(nil) } func hashSHA256(data []byte) []byte { hash := sha256.New() hash.Write(data) return hash.Sum(nil) } func makeSha256Reader(reader io.ReadSeeker) (hashBytes []byte, err error) { hash := sha256.New() start, err := reader.Seek(0, sdkio.SeekCurrent) if err != nil { return nil, err } defer func() { // ensure error is return if unable to seek back to start of payload. _, err = reader.Seek(start, sdkio.SeekStart) }() // Use CopyN to avoid allocating the 32KB buffer in io.Copy for bodies // smaller than 32KB. Fall back to io.Copy if we fail to determine the size. size, err := aws.SeekerLen(reader) if err != nil { io.Copy(hash, reader) } else { io.CopyN(hash, reader, size) } return hash.Sum(nil), nil } const doubleSpace = " " // stripExcessSpaces will rewrite the passed in slice's string values to not // contain multiple side-by-side spaces. func stripExcessSpaces(vals []string) { var j, k, l, m, spaces int for i, str := range vals { // Trim trailing spaces for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { } // Trim leading spaces for k = 0; k < j && str[k] == ' '; k++ { } str = str[k : j+1] // Strip multiple spaces. j = strings.Index(str, doubleSpace) if j < 0 { vals[i] = str continue } buf := []byte(str) for k, m, l = j, j, len(buf); k < l; k++ { if buf[k] == ' ' { if spaces == 0 { // First space. buf[m] = buf[k] m++ } spaces++ } else { // End of multiple spaces. spaces = 0 buf[m] = buf[k] m++ } } vals[i] = string(buf[:m]) } } func buildSigningScope(region, service string, dt time.Time) string { return strings.Join([]string{ formatShortTime(dt), region, service, awsV4Request, }, "/") } func deriveSigningKey(region, service, secretKey string, dt time.Time) []byte { kDate := hmacSHA256([]byte("AWS4"+secretKey), []byte(formatShortTime(dt))) kRegion := hmacSHA256(kDate, []byte(region)) kService := hmacSHA256(kRegion, []byte(service)) signingKey := hmacSHA256(kService, []byte(awsV4Request)) return signingKey } func formatShortTime(dt time.Time) string { return dt.UTC().Format(shortTimeFormat) } func formatTime(dt time.Time) string { return dt.UTC().Format(timeFormat) }
fgimenez/kubernetes
vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go
GO
apache-2.0
28,227
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package upgrades import ( "regexp" "time" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/kubernetes/test/e2e/framework" "k8s.io/kubernetes/test/e2e/scheduling" imageutils "k8s.io/kubernetes/test/utils/image" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) // NvidiaGPUUpgradeTest tests that gpu resource is available before and after // a cluster upgrade. type NvidiaGPUUpgradeTest struct { } func (NvidiaGPUUpgradeTest) Name() string { return "nvidia-gpu-upgrade [sig-node] [sig-scheduling]" } // Setup creates a job requesting gpu. func (t *NvidiaGPUUpgradeTest) Setup(f *framework.Framework) { scheduling.SetupNVIDIAGPUNode(f, false) By("Creating a job requesting gpu") t.startJob(f) } // Test waits for the upgrade to complete, and then verifies that the // cuda pod started by the gpu job can successfully finish. func (t *NvidiaGPUUpgradeTest) Test(f *framework.Framework, done <-chan struct{}, upgrade UpgradeType) { <-done By("Verifying gpu job success") t.verifyJobPodSuccess(f) if upgrade == MasterUpgrade { // MasterUpgrade should be totally hitless. job, err := framework.GetJob(f.ClientSet, f.Namespace.Name, "cuda-add") Expect(err).NotTo(HaveOccurred()) Expect(job.Status.Failed).To(BeZero(), "Job pods failed during master upgrade: %v", job.Status.Failed) } } // Teardown cleans up any remaining resources. func (t *NvidiaGPUUpgradeTest) Teardown(f *framework.Framework) { // rely on the namespace deletion to clean up everything } // startJob creates a job that requests gpu and runs a simple cuda container. func (t *NvidiaGPUUpgradeTest) startJob(f *framework.Framework) { var activeSeconds int64 = 3600 // Specifies 100 completions to make sure the job life spans across the upgrade. testJob := framework.NewTestJob("succeed", "cuda-add", v1.RestartPolicyAlways, 1, 100, &activeSeconds, 6) testJob.Spec.Template.Spec = v1.PodSpec{ RestartPolicy: v1.RestartPolicyOnFailure, Containers: []v1.Container{ { Name: "vector-addition", Image: imageutils.GetE2EImage(imageutils.CudaVectorAdd), Command: []string{"/bin/sh", "-c", "./vectorAdd && sleep 60"}, Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ framework.NVIDIAGPUResourceName: *resource.NewQuantity(1, resource.DecimalSI), }, }, }, }, } ns := f.Namespace.Name _, err := framework.CreateJob(f.ClientSet, ns, testJob) Expect(err).NotTo(HaveOccurred()) framework.Logf("Created job %v", testJob) By("Waiting for gpu job pod start") err = framework.WaitForAllJobPodsRunning(f.ClientSet, ns, testJob.Name, 1) Expect(err).NotTo(HaveOccurred()) By("Done with gpu job pod start") } // verifyJobPodSuccess verifies that the started cuda pod successfully passes. func (t *NvidiaGPUUpgradeTest) verifyJobPodSuccess(f *framework.Framework) { // Wait for client pod to complete. ns := f.Namespace.Name err := framework.WaitForAllJobPodsRunning(f.ClientSet, f.Namespace.Name, "cuda-add", 1) Expect(err).NotTo(HaveOccurred()) pods, err := framework.GetJobPods(f.ClientSet, f.Namespace.Name, "cuda-add") Expect(err).NotTo(HaveOccurred()) createdPod := pods.Items[0].Name framework.Logf("Created pod %v", createdPod) f.PodClient().WaitForSuccess(createdPod, 5*time.Minute) logs, err := framework.GetPodLogs(f.ClientSet, ns, createdPod, "vector-addition") framework.ExpectNoError(err, "Should be able to get pod logs") framework.Logf("Got pod logs: %v", logs) regex := regexp.MustCompile("PASSED") Expect(regex.MatchString(logs)).To(BeTrue()) }
clairew/kubernetes
test/e2e/upgrades/nvidia-gpu.go
GO
apache-2.0
4,126
tinymce.PluginManager.add("template",function(a){function b(b){return function(){var c=a.settings.templates;"string"==typeof c?tinymce.util.XHR.send({url:c,success:function(a){b(tinymce.util.JSON.parse(a))}}):b(c)}}function c(b){function c(b){function c(b){if(-1==b.indexOf("<html>")){var c="";tinymce.each(a.contentCSS,function(b){c+='<link type="text/css" rel="stylesheet" href="'+a.documentBaseURI.toAbsolute(b)+'">'}),b="<!DOCTYPE html><html><head>"+c+"</head><body>"+b+"</body></html>"}b=f(b,"template_preview_replace_values");var e=d.find("iframe")[0].getEl().contentWindow.document;e.open(),e.write(b),e.close()}var g=b.control.value();g.url?tinymce.util.XHR.send({url:g.url,success:function(a){e=a,c(e)}}):(e=g.content,c(e)),d.find("#description")[0].text(b.control.value().description)}var d,e,h=[];return b&&0!==b.length?(tinymce.each(b,function(a){h.push({selected:!h.length,text:a.title,value:{url:a.url,content:a.content,description:a.description}})}),d=a.windowManager.open({title:"Insert template",layout:"flex",direction:"column",align:"stretch",padding:15,spacing:10,items:[{type:"form",flex:0,padding:0,items:[{type:"container",label:"Templates",items:{type:"listbox",label:"Templates",name:"template",values:h,onselect:c}}]},{type:"label",name:"description",label:"Description",text:"\xa0"},{type:"iframe",flex:1,border:1}],onsubmit:function(){g(!1,e)},width:a.getParam("template_popup_width",600),height:a.getParam("template_popup_height",500)}),void d.find("listbox")[0].fire("select")):void a.windowManager.alert("No templates defined")}function d(b,c){function d(a,b){if(a=""+a,a.length<b)for(var c=0;c<b-a.length;c++)a="0"+a;return a}var e="Sun Mon Tue Wed Thu Fri Sat Sun".split(" "),f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "),g="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),h="January February March April May June July August September October November December".split(" ");return c=c||new Date,b=b.replace("%D","%m/%d/%Y"),b=b.replace("%r","%I:%M:%S %p"),b=b.replace("%Y",""+c.getFullYear()),b=b.replace("%y",""+c.getYear()),b=b.replace("%m",d(c.getMonth()+1,2)),b=b.replace("%d",d(c.getDate(),2)),b=b.replace("%H",""+d(c.getHours(),2)),b=b.replace("%M",""+d(c.getMinutes(),2)),b=b.replace("%S",""+d(c.getSeconds(),2)),b=b.replace("%I",""+((c.getHours()+11)%12+1)),b=b.replace("%p",""+(c.getHours()<12?"AM":"PM")),b=b.replace("%B",""+a.translate(h[c.getMonth()])),b=b.replace("%b",""+a.translate(g[c.getMonth()])),b=b.replace("%A",""+a.translate(f[c.getDay()])),b=b.replace("%a",""+a.translate(e[c.getDay()])),b=b.replace("%%","%")}function e(b){var c=a.dom,d=a.getParam("template_replace_values");h(c.select("*",b),function(a){h(d,function(b,e){c.hasClass(a,e)&&"function"==typeof d[e]&&d[e](a)})})}function f(b,c){return h(a.getParam(c),function(a,c){"function"==typeof a&&(a=a(c)),b=b.replace(new RegExp("\\{\\$"+c+"\\}","g"),a)}),b}function g(b,c){function g(a,b){return new RegExp("\\b"+b+"\\b","g").test(a.className)}var i,j,k=a.dom,l=a.selection.getContent();c=f(c,"template_replace_values"),i=k.create("div",null,c),j=k.select(".mceTmpl",i),j&&j.length>0&&(i=k.create("div",null),i.appendChild(j[0].cloneNode(!0))),h(k.select("*",i),function(b){g(b,a.getParam("template_cdate_classes","cdate").replace(/\s+/g,"|"))&&(b.innerHTML=d(a.getParam("template_cdate_format",a.getLang("template.cdate_format")))),g(b,a.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))&&(b.innerHTML=d(a.getParam("template_mdate_format",a.getLang("template.mdate_format")))),g(b,a.getParam("template_selected_content_classes","selcontent").replace(/\s+/g,"|"))&&(b.innerHTML=l)}),e(i),a.execCommand("mceInsertContent",!1,i.innerHTML),a.addVisual()}var h=tinymce.each;a.addCommand("mceInsertTemplate",g),a.addButton("template",{title:"Insert template",onclick:b(c)}),a.addMenuItem("template",{text:"Insert template",onclick:b(c),context:"insert"}),a.on("PreProcess",function(b){var c=a.dom;h(c.select("div",b.node),function(b){c.hasClass(b,"mceTmpl")&&(h(c.select("*",b),function(b){c.hasClass(b,a.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))&&(b.innerHTML=d(a.getParam("template_mdate_format",a.getLang("template.mdate_format"))))}),e(b))})})});
pasindujw/product-mdm
modules/apps/jaggery/emm-web-agent/src/emm-web-agent/units/desktop-theme/public/js/tinymce/plugins/template/plugin.min.js
JavaScript
apache-2.0
4,239
/* Copyright (C) 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a], ["typ",/^:[\dA-Za-z-]+/]]),["clj"]);
diegocgaona/titanic_project
Titanic_Pitch/libraries/frameworks/io2012/js/prettify/lang-clj.js
JavaScript
apache-2.0
1,444
// Copyright 2013-2015 Apcera Inc. All rights reserved. // +build darwin linux freebsd package gssapi /* #cgo linux LDFLAGS: -ldl #cgo freebsd pkg-config: heimdal-gssapi #include <gssapi/gssapi.h> #include <dlfcn.h> #include <stdlib.h> // Name-Types. These are standardized in the RFCs. The library requires that // a given name be usable for resolution, but it's typically a macro, there's // no guarantee about the name exported from the library. But since they're // static, and well-defined, we can just define them ourselves. // RFC2744-mandated values, mapping from as-near-as-possible to cut&paste const gss_OID_desc *_GSS_C_NT_USER_NAME = & (gss_OID_desc) { 10, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x01" }; const gss_OID_desc *_GSS_C_NT_MACHINE_UID_NAME = & (gss_OID_desc) { 10, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02" }; const gss_OID_desc *_GSS_C_NT_STRING_UID_NAME = & (gss_OID_desc) { 10, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x03" }; const gss_OID_desc *_GSS_C_NT_HOSTBASED_SERVICE_X = & (gss_OID_desc) { 6, "\x2b\x06\x01\x05\x06\x02" }; const gss_OID_desc *_GSS_C_NT_HOSTBASED_SERVICE = & (gss_OID_desc) { 10, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x04" }; const gss_OID_desc *_GSS_C_NT_ANONYMOUS = & (gss_OID_desc) { 6, "\x2b\x06\x01\x05\x06\x03" }; // original had \01 const gss_OID_desc *_GSS_C_NT_EXPORT_NAME = & (gss_OID_desc) { 6, "\x2b\x06\x01\x05\x06\x04" }; // from gssapi_krb5.h: This name form shall be represented by the Object // Identifier {iso(1) member-body(2) United States(840) mit(113554) infosys(1) // gssapi(2) krb5(2) krb5_name(1)}. The recommended symbolic name for this // type is "GSS_KRB5_NT_PRINCIPAL_NAME". const gss_OID_desc *_GSS_KRB5_NT_PRINCIPAL_NAME = & (gss_OID_desc) { 10, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01" }; // { 1 2 840 113554 1 2 2 2 } const gss_OID_desc *_GSS_KRB5_NT_PRINCIPAL = & (gss_OID_desc) { 10, "\x2A\x86\x48\x86\xF7\x12\x01\x02\x02\x02" }; // known mech OIDs const gss_OID_desc *_GSS_MECH_KRB5 = & (gss_OID_desc) { 9, "\x2A\x86\x48\x86\xF7\x12\x01\x02\x02" }; const gss_OID_desc *_GSS_MECH_KRB5_LEGACY = & (gss_OID_desc) { 9, "\x2A\x86\x48\x82\xF7\x12\x01\x02\x02" }; const gss_OID_desc *_GSS_MECH_KRB5_OLD = & (gss_OID_desc) { 5, "\x2B\x05\x01\x05\x02" }; const gss_OID_desc *_GSS_MECH_SPNEGO = & (gss_OID_desc) { 6, "\x2b\x06\x01\x05\x05\x02" }; const gss_OID_desc *_GSS_MECH_IAKERB = & (gss_OID_desc) { 6, "\x2b\x06\x01\x05\x02\x05" }; const gss_OID_desc *_GSS_MECH_NTLMSSP = & (gss_OID_desc) { 10, "\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a" }; */ import "C" import ( "fmt" "os" "reflect" "runtime" "strings" "unsafe" ) // Values for Options.LoadDefault const ( MIT = iota Heimdal ) type Severity uint // Values for Options.Log severity indices const ( Emerg = Severity(iota) Alert Crit Err Warn Notice Info Debug MaxSeverity ) var severityNames = []string{ "Emerg", "Alert", "Crit", "Err", "Warn", "Notice", "Info", "Debug", } // String returns the string name of a log Severity. func (s Severity) String() string { if s >= MaxSeverity { return "" } return severityNames[s] } // Printer matches the log package, not fmt type Printer interface { Print(a ...interface{}) } // Options denote the options used to load a GSSAPI library. If a user supplies // a LibPath, we use that. Otherwise, based upon the default and the current OS, // we try to construct the library path. type Options struct { LibPath string Krb5Config string Krb5Ktname string LoadDefault int Printers []Printer `json:"-"` } // ftable fields will be initialized to the corresponding function pointers from // the GSSAPI library. They must be of form Fp_function_name (Capital 'F' so // that we can use reflect. type ftable struct { // buffer.go Fp_gss_release_buffer unsafe.Pointer Fp_gss_import_name unsafe.Pointer // context.go Fp_gss_init_sec_context unsafe.Pointer Fp_gss_accept_sec_context unsafe.Pointer Fp_gss_delete_sec_context unsafe.Pointer Fp_gss_process_context_token unsafe.Pointer Fp_gss_context_time unsafe.Pointer Fp_gss_inquire_context unsafe.Pointer Fp_gss_wrap_size_limit unsafe.Pointer Fp_gss_export_sec_context unsafe.Pointer Fp_gss_import_sec_context unsafe.Pointer // credential.go Fp_gss_acquire_cred unsafe.Pointer Fp_gss_add_cred unsafe.Pointer Fp_gss_inquire_cred unsafe.Pointer Fp_gss_inquire_cred_by_mech unsafe.Pointer Fp_gss_release_cred unsafe.Pointer // message.go Fp_gss_get_mic unsafe.Pointer Fp_gss_verify_mic unsafe.Pointer Fp_gss_wrap unsafe.Pointer Fp_gss_unwrap unsafe.Pointer // misc.go Fp_gss_indicate_mechs unsafe.Pointer // name.go Fp_gss_canonicalize_name unsafe.Pointer Fp_gss_compare_name unsafe.Pointer Fp_gss_display_name unsafe.Pointer Fp_gss_duplicate_name unsafe.Pointer Fp_gss_export_name unsafe.Pointer Fp_gss_inquire_mechs_for_name unsafe.Pointer Fp_gss_inquire_names_for_mech unsafe.Pointer Fp_gss_release_name unsafe.Pointer // oid_set.go Fp_gss_create_empty_oid_set unsafe.Pointer Fp_gss_add_oid_set_member unsafe.Pointer Fp_gss_release_oid_set unsafe.Pointer Fp_gss_test_oid_set_member unsafe.Pointer // status.go Fp_gss_display_status unsafe.Pointer // krb5_keytab.go -- where does this come from? // Fp_gsskrb5_register_acceptor_identity unsafe.Pointer } // constants are a number of constant initialized in initConstants. type constants struct { GSS_C_NO_BUFFER *Buffer GSS_C_NO_OID *OID GSS_C_NO_OID_SET *OIDSet GSS_C_NO_CONTEXT *CtxId GSS_C_NO_CREDENTIAL *CredId // when adding new OID constants also need to update OID.DebugString GSS_C_NT_USER_NAME *OID GSS_C_NT_MACHINE_UID_NAME *OID GSS_C_NT_STRING_UID_NAME *OID GSS_C_NT_HOSTBASED_SERVICE_X *OID GSS_C_NT_HOSTBASED_SERVICE *OID GSS_C_NT_ANONYMOUS *OID GSS_C_NT_EXPORT_NAME *OID GSS_KRB5_NT_PRINCIPAL_NAME *OID GSS_KRB5_NT_PRINCIPAL *OID GSS_MECH_KRB5 *OID GSS_MECH_KRB5_LEGACY *OID GSS_MECH_KRB5_OLD *OID GSS_MECH_SPNEGO *OID GSS_MECH_IAKERB *OID GSS_MECH_NTLMSSP *OID GSS_C_NO_CHANNEL_BINDINGS ChannelBindings // implicitly initialized as nil } // Lib encapsulates both the GSSAPI and the library dlopen()'d for it. The // handle represents the dynamically-linked gssapi library handle. type Lib struct { LastStatus *Error // Should contain a gssapi.Printer for each severity level to be // logged, up to gssapi.MaxSeverity items Printers []Printer handle unsafe.Pointer ftable constants } const ( fpPrefix = "Fp_" ) // Path returns the chosen gssapi library path that we're looking for. func (o *Options) Path() string { switch { case o.LibPath != "": return o.LibPath case o.LoadDefault == MIT: return appendOSExt("libgssapi_krb5") case o.LoadDefault == Heimdal: return appendOSExt("libgssapi") } return "" } // Load attempts to load a dynamically-linked gssapi library from the path // specified by the supplied Options. func Load(o *Options) (*Lib, error) { if o == nil { o = &Options{} } // We get the error in a separate call, so we need to lock OS thread runtime.LockOSThread() defer runtime.UnlockOSThread() lib := &Lib{ Printers: o.Printers, } if o.Krb5Config != "" { err := os.Setenv("KRB5_CONFIG", o.Krb5Config) if err != nil { return nil, err } } if o.Krb5Ktname != "" { err := os.Setenv("KRB5_KTNAME", o.Krb5Ktname) if err != nil { return nil, err } } path := o.Path() lib.Debug(fmt.Sprintf("Loading %q", path)) lib_cs := C.CString(path) defer C.free(unsafe.Pointer(lib_cs)) // we don't use RTLD_FIRST, it might be the case that the GSSAPI lib // delegates symbols to other libs it links against (eg, Kerberos) lib.handle = C.dlopen(lib_cs, C.RTLD_NOW|C.RTLD_LOCAL) if lib.handle == nil { return nil, fmt.Errorf("%s", C.GoString(C.dlerror())) } err := lib.populateFunctions() if err != nil { lib.Unload() return nil, err } lib.initConstants() return lib, nil } // Unload closes the handle to the dynamically-linked gssapi library. func (lib *Lib) Unload() error { if lib == nil || lib.handle == nil { return nil } runtime.LockOSThread() defer runtime.UnlockOSThread() i := C.dlclose(lib.handle) if i == -1 { return fmt.Errorf("%s", C.GoString(C.dlerror())) } lib.handle = nil return nil } func appendOSExt(path string) string { ext := ".so" if runtime.GOOS == "darwin" { ext = ".dylib" } if !strings.HasSuffix(path, ext) { path += ext } return path } // populateFunctions ranges over the library's ftable, initializing each // function inside. Assumes that the caller executes runtime.LockOSThread. func (lib *Lib) populateFunctions() error { libT := reflect.TypeOf(lib.ftable) functionsV := reflect.ValueOf(lib).Elem().FieldByName("ftable") n := libT.NumField() for i := 0; i < n; i++ { // Get the field name, and make sure it's an Fp_. f := libT.FieldByIndex([]int{i}) if !strings.HasPrefix(f.Name, fpPrefix) { return fmt.Errorf( "Unexpected: field %q does not start with %q", f.Name, fpPrefix) } // Resolve the symbol. cfname := C.CString(f.Name[len(fpPrefix):]) v := C.dlsym(lib.handle, cfname) C.free(unsafe.Pointer(cfname)) if v == nil { return fmt.Errorf("%s", C.GoString(C.dlerror())) } // Save the value into the struct functionsV.FieldByIndex([]int{i}).SetPointer(v) } return nil } // initConstants sets the initial values of a library's set of 'constants'. func (lib *Lib) initConstants() { lib.GSS_C_NO_BUFFER = &Buffer{ Lib: lib, // C_gss_buffer_t: C.GSS_C_NO_BUFFER, already nil // alloc: allocNone, already 0 } lib.GSS_C_NO_OID = lib.NewOID() lib.GSS_C_NO_OID_SET = lib.NewOIDSet() lib.GSS_C_NO_CONTEXT = lib.NewCtxId() lib.GSS_C_NO_CREDENTIAL = lib.NewCredId() lib.GSS_C_NT_USER_NAME = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_USER_NAME} lib.GSS_C_NT_MACHINE_UID_NAME = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_MACHINE_UID_NAME} lib.GSS_C_NT_STRING_UID_NAME = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_MACHINE_UID_NAME} lib.GSS_C_NT_HOSTBASED_SERVICE_X = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_HOSTBASED_SERVICE_X} lib.GSS_C_NT_HOSTBASED_SERVICE = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_HOSTBASED_SERVICE} lib.GSS_C_NT_ANONYMOUS = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_ANONYMOUS} lib.GSS_C_NT_EXPORT_NAME = &OID{Lib: lib, C_gss_OID: C._GSS_C_NT_EXPORT_NAME} lib.GSS_KRB5_NT_PRINCIPAL_NAME = &OID{Lib: lib, C_gss_OID: C._GSS_KRB5_NT_PRINCIPAL_NAME} lib.GSS_KRB5_NT_PRINCIPAL = &OID{Lib: lib, C_gss_OID: C._GSS_KRB5_NT_PRINCIPAL} lib.GSS_MECH_KRB5 = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_KRB5} lib.GSS_MECH_KRB5_LEGACY = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_KRB5_LEGACY} lib.GSS_MECH_KRB5_OLD = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_KRB5_OLD} lib.GSS_MECH_SPNEGO = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_SPNEGO} lib.GSS_MECH_IAKERB = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_IAKERB} lib.GSS_MECH_NTLMSSP = &OID{Lib: lib, C_gss_OID: C._GSS_MECH_NTLMSSP} } // Print outputs a log line to the specified severity. func (lib *Lib) Print(level Severity, a ...interface{}) { if lib == nil || lib.Printers == nil || level >= Severity(len(lib.Printers)) { return } lib.Printers[level].Print(a...) } func (lib *Lib) Emerg(a ...interface{}) { lib.Print(Emerg, a...) } func (lib *Lib) Alert(a ...interface{}) { lib.Print(Alert, a...) } func (lib *Lib) Crit(a ...interface{}) { lib.Print(Crit, a...) } func (lib *Lib) Err(a ...interface{}) { lib.Print(Err, a...) } func (lib *Lib) Warn(a ...interface{}) { lib.Print(Warn, a...) } func (lib *Lib) Notice(a ...interface{}) { lib.Print(Notice, a...) } func (lib *Lib) Info(a ...interface{}) { lib.Print(Info, a...) } func (lib *Lib) Debug(a ...interface{}) { lib.Print(Debug, a...) }
louyihua/origin
vendor/github.com/apcera/gssapi/lib.go
GO
apache-2.0
12,081
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package flexvolume import ( "encoding/json" "errors" "fmt" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/volume" ) const ( // Driver calls initCmd = "init" getVolumeNameCmd = "getvolumename" isAttached = "isattached" attachCmd = "attach" waitForAttachCmd = "waitforattach" mountDeviceCmd = "mountdevice" detachCmd = "detach" waitForDetachCmd = "waitfordetach" unmountDeviceCmd = "unmountdevice" mountCmd = "mount" unmountCmd = "unmount" // Option keys optionFSType = "kubernetes.io/fsType" optionReadWrite = "kubernetes.io/readwrite" optionKeySecret = "kubernetes.io/secret" optionFSGroup = "kubernetes.io/fsGroup" optionMountsDir = "kubernetes.io/mountsDir" ) const ( // StatusSuccess represents the successful completion of command. StatusSuccess = "Success" // StatusFailed represents that the command failed. StatusFailure = "Failed" // StatusNotSupported represents that the command is not supported. StatusNotSupported = "Not supported" ) var ( TimeoutError = fmt.Errorf("Timeout") ) // DriverCall implements the basic contract between FlexVolume and its driver. // The caller is responsible for providing the required args. type DriverCall struct { Command string Timeout time.Duration plugin *flexVolumePlugin args []string } func (plugin *flexVolumePlugin) NewDriverCall(command string) *DriverCall { return plugin.NewDriverCallWithTimeout(command, 0) } func (plugin *flexVolumePlugin) NewDriverCallWithTimeout(command string, timeout time.Duration) *DriverCall { return &DriverCall{ Command: command, Timeout: timeout, plugin: plugin, args: []string{command}, } } func (dc *DriverCall) Append(arg string) { dc.args = append(dc.args, arg) } func (dc *DriverCall) AppendSpec(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) error { optionsForDriver, err := NewOptionsForDriver(spec, host, extraOptions) if err != nil { return err } jsonBytes, err := json.Marshal(optionsForDriver) if err != nil { return fmt.Errorf("Failed to marshal spec, error: %s", err.Error()) } dc.Append(string(jsonBytes)) return nil } func (dc *DriverCall) Run() (*DriverStatus, error) { if dc.plugin.isUnsupported(dc.Command) { return nil, errors.New(StatusNotSupported) } execPath := dc.plugin.getExecutable() cmd := dc.plugin.runner.Command(execPath, dc.args...) timeout := false if dc.Timeout > 0 { timer := time.AfterFunc(dc.Timeout, func() { timeout = true cmd.Stop() }) defer timer.Stop() } output, execErr := cmd.CombinedOutput() if execErr != nil { if timeout { return nil, TimeoutError } _, err := handleCmdResponse(dc.Command, output) if err == nil { glog.Errorf("FlexVolume: driver bug: %s: exec error (%s) but no error in response.", execPath, execErr) return nil, execErr } if isCmdNotSupportedErr(err) { dc.plugin.unsupported(dc.Command) } else { glog.Warningf("FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %s", execPath, dc.args, execErr.Error(), output) } return nil, err } status, err := handleCmdResponse(dc.Command, output) if err != nil { if isCmdNotSupportedErr(err) { dc.plugin.unsupported(dc.Command) } return nil, err } return status, nil } // OptionsForDriver represents the spec given to the driver. type OptionsForDriver map[string]string func NewOptionsForDriver(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) (OptionsForDriver, error) { volSource, readOnly := getVolumeSource(spec) options := map[string]string{} options[optionFSType] = volSource.FSType if readOnly { options[optionReadWrite] = "ro" } else { options[optionReadWrite] = "rw" } for key, value := range extraOptions { options[key] = value } for key, value := range volSource.Options { options[key] = value } return OptionsForDriver(options), nil } // DriverStatus represents the return value of the driver callout. type DriverStatus struct { // Status of the callout. One of "Success", "Failure" or "Not supported". Status string `json:"status"` // Reason for success/failure. Message string `json:"message,omitempty"` // Path to the device attached. This field is valid only for attach calls. // ie: /dev/sdx DevicePath string `json:"device,omitempty"` // Cluster wide unique name of the volume. VolumeName string `json:"volumeName,omitempty"` // Represents volume is attached on the node Attached bool `json:"attached,omitempty"` } // isCmdNotSupportedErr checks if the error corresponds to command not supported by // driver. func isCmdNotSupportedErr(err error) bool { if err != nil && err.Error() == StatusNotSupported { return true } return false } // handleCmdResponse processes the command output and returns the appropriate // error code or message. func handleCmdResponse(cmd string, output []byte) (*DriverStatus, error) { var status DriverStatus if err := json.Unmarshal(output, &status); err != nil { glog.Errorf("Failed to unmarshal output for command: %s, output: %s, error: %s", cmd, string(output), err.Error()) return nil, err } else if status.Status == StatusNotSupported { glog.V(5).Infof("%s command is not supported by the driver", cmd) return nil, errors.New(status.Status) } else if status.Status != StatusSuccess { errMsg := fmt.Sprintf("%s command failed, status: %s, reason: %s", cmd, status.Status, status.Message) glog.Errorf(errMsg) return nil, fmt.Errorf("%s", errMsg) } return &status, nil }
WillemMali/kops
vendor/k8s.io/kubernetes/pkg/volume/flexvolume/driver-call.go
GO
apache-2.0
6,126
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.remote.server.handler.html5; import org.openqa.selenium.remote.server.Session; import org.openqa.selenium.remote.server.handler.WebDriverHandler; import java.util.Set; public class GetSessionStorageKeys extends WebDriverHandler<Set<String>> { public GetSessionStorageKeys(Session session) { super(session); } @Override public Set<String> call() throws Exception { return Utils.getWebStorage(getUnwrappedDriver()) .getSessionStorage().keySet(); } @Override public String toString() { return "[get session storage key set]"; } }
houchj/selenium
java/server/src/org/openqa/selenium/remote/server/handler/html5/GetSessionStorageKeys.java
Java
apache-2.0
1,401
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // 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. /* The unmarshal plugin generates a Unmarshal method for each message. The `Unmarshal([]byte) error` method results in the fact that the message implements the Unmarshaler interface. The allows proto.Unmarshal to be faster by calling the generated Unmarshal method rather than using reflect. If is enabled by the following extensions: - unmarshaler - unmarshaler_all Or the following extensions: - unsafe_unmarshaler - unsafe_unmarshaler_all That is if you want to use the unsafe package in your generated code. The speed up using the unsafe package is not very significant. The generation of unmarshalling tests are enabled using one of the following extensions: - testgen - testgen_all And benchmarks given it is enabled using one of the following extensions: - benchgen - benchgen_all Let us look at: github.com/gogo/protobuf/test/example/example.proto Btw all the output can be seen at: github.com/gogo/protobuf/test/example/* The following message: option (gogoproto.unmarshaler_all) = true; message B { option (gogoproto.description) = true; optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true]; repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false]; } given to the unmarshal plugin, will generate the following code: func (m *B) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) switch fieldNum { case 1: if wireType != 2 { return proto.ErrWrongType } var msglen int for shift := uint(0); ; shift += 7 { if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := m.A.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 2: if wireType != 2 { return proto.ErrWrongType } var byteLen int for shift := uint(0); ; shift += 7 { if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } m.G = append(m.G, github_com_gogo_protobuf_test_custom.Uint128{}) if err := m.G[len(m.G)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: var sizeOfWire int for { sizeOfWire++ wire >>= 7 if wire == 0 { break } } iNdEx -= sizeOfWire skippy, err := skip(dAtA[iNdEx:]) if err != nil { return err } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } return nil } Remember when using this code to call proto.Unmarshal. This will call m.Reset and invoke the generated Unmarshal method for you. If you call m.Unmarshal without m.Reset you could be merging protocol buffers. */ package unmarshal import ( "fmt" "strconv" "strings" "github.com/gogo/protobuf/gogoproto" "github.com/gogo/protobuf/proto" descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" "github.com/gogo/protobuf/protoc-gen-gogo/generator" ) type unmarshal struct { *generator.Generator generator.PluginImports atleastOne bool ioPkg generator.Single mathPkg generator.Single typesPkg generator.Single binaryPkg generator.Single localName string } func NewUnmarshal() *unmarshal { return &unmarshal{} } func (p *unmarshal) Name() string { return "unmarshal" } func (p *unmarshal) Init(g *generator.Generator) { p.Generator = g } func (p *unmarshal) decodeVarint(varName string, typName string) { p.P(`for shift := uint(0); ; shift += 7 {`) p.In() p.P(`if shift >= 64 {`) p.In() p.P(`return ErrIntOverflow` + p.localName) p.Out() p.P(`}`) p.P(`if iNdEx >= l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(`b := dAtA[iNdEx]`) p.P(`iNdEx++`) p.P(varName, ` |= `, typName, `(b&0x7F) << shift`) p.P(`if b < 0x80 {`) p.In() p.P(`break`) p.Out() p.P(`}`) p.Out() p.P(`}`) } func (p *unmarshal) decodeFixed32(varName string, typeName string) { p.P(`if (iNdEx+4) > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(varName, ` = `, typeName, `(`, p.binaryPkg.Use(), `.LittleEndian.Uint32(dAtA[iNdEx:]))`) p.P(`iNdEx += 4`) } func (p *unmarshal) decodeFixed64(varName string, typeName string) { p.P(`if (iNdEx+8) > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(varName, ` = `, typeName, `(`, p.binaryPkg.Use(), `.LittleEndian.Uint64(dAtA[iNdEx:]))`) p.P(`iNdEx += 8`) } func (p *unmarshal) declareMapField(varName string, nullable bool, customType bool, field *descriptor.FieldDescriptorProto) { switch field.GetType() { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: p.P(`var `, varName, ` float64`) case descriptor.FieldDescriptorProto_TYPE_FLOAT: p.P(`var `, varName, ` float32`) case descriptor.FieldDescriptorProto_TYPE_INT64: p.P(`var `, varName, ` int64`) case descriptor.FieldDescriptorProto_TYPE_UINT64: p.P(`var `, varName, ` uint64`) case descriptor.FieldDescriptorProto_TYPE_INT32: p.P(`var `, varName, ` int32`) case descriptor.FieldDescriptorProto_TYPE_FIXED64: p.P(`var `, varName, ` uint64`) case descriptor.FieldDescriptorProto_TYPE_FIXED32: p.P(`var `, varName, ` uint32`) case descriptor.FieldDescriptorProto_TYPE_BOOL: p.P(`var `, varName, ` bool`) case descriptor.FieldDescriptorProto_TYPE_STRING: cast, _ := p.GoType(nil, field) cast = strings.Replace(cast, "*", "", 1) p.P(`var `, varName, ` `, cast) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: if gogoproto.IsStdTime(field) { p.P(varName, ` := new(time.Time)`) } else if gogoproto.IsStdDuration(field) { p.P(varName, ` := new(time.Duration)`) } else if gogoproto.IsStdDouble(field) { p.P(varName, ` := new(float64)`) } else if gogoproto.IsStdFloat(field) { p.P(varName, ` := new(float32)`) } else if gogoproto.IsStdInt64(field) { p.P(varName, ` := new(int64)`) } else if gogoproto.IsStdUInt64(field) { p.P(varName, ` := new(uint64)`) } else if gogoproto.IsStdInt32(field) { p.P(varName, ` := new(int32)`) } else if gogoproto.IsStdUInt32(field) { p.P(varName, ` := new(uint32)`) } else if gogoproto.IsStdBool(field) { p.P(varName, ` := new(bool)`) } else if gogoproto.IsStdString(field) { p.P(varName, ` := new(string)`) } else if gogoproto.IsStdBytes(field) { p.P(varName, ` := new([]byte)`) } else { desc := p.ObjectNamed(field.GetTypeName()) msgname := p.TypeName(desc) if nullable { p.P(`var `, varName, ` *`, msgname) } else { p.P(varName, ` := &`, msgname, `{}`) } } case descriptor.FieldDescriptorProto_TYPE_BYTES: if customType { _, ctyp, err := generator.GetCustomType(field) if err != nil { panic(err) } p.P(`var `, varName, `1 `, ctyp) p.P(`var `, varName, ` = &`, varName, `1`) } else { p.P(varName, ` := []byte{}`) } case descriptor.FieldDescriptorProto_TYPE_UINT32: p.P(`var `, varName, ` uint32`) case descriptor.FieldDescriptorProto_TYPE_ENUM: typName := p.TypeName(p.ObjectNamed(field.GetTypeName())) p.P(`var `, varName, ` `, typName) case descriptor.FieldDescriptorProto_TYPE_SFIXED32: p.P(`var `, varName, ` int32`) case descriptor.FieldDescriptorProto_TYPE_SFIXED64: p.P(`var `, varName, ` int64`) case descriptor.FieldDescriptorProto_TYPE_SINT32: p.P(`var `, varName, ` int32`) case descriptor.FieldDescriptorProto_TYPE_SINT64: p.P(`var `, varName, ` int64`) } } func (p *unmarshal) mapField(varName string, customType bool, field *descriptor.FieldDescriptorProto) { switch field.GetType() { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: p.P(`var `, varName, `temp uint64`) p.decodeFixed64(varName+"temp", "uint64") p.P(varName, ` = `, p.mathPkg.Use(), `.Float64frombits(`, varName, `temp)`) case descriptor.FieldDescriptorProto_TYPE_FLOAT: p.P(`var `, varName, `temp uint32`) p.decodeFixed32(varName+"temp", "uint32") p.P(varName, ` = `, p.mathPkg.Use(), `.Float32frombits(`, varName, `temp)`) case descriptor.FieldDescriptorProto_TYPE_INT64: p.decodeVarint(varName, "int64") case descriptor.FieldDescriptorProto_TYPE_UINT64: p.decodeVarint(varName, "uint64") case descriptor.FieldDescriptorProto_TYPE_INT32: p.decodeVarint(varName, "int32") case descriptor.FieldDescriptorProto_TYPE_FIXED64: p.decodeFixed64(varName, "uint64") case descriptor.FieldDescriptorProto_TYPE_FIXED32: p.decodeFixed32(varName, "uint32") case descriptor.FieldDescriptorProto_TYPE_BOOL: p.P(`var `, varName, `temp int`) p.decodeVarint(varName+"temp", "int") p.P(varName, ` = bool(`, varName, `temp != 0)`) case descriptor.FieldDescriptorProto_TYPE_STRING: p.P(`var stringLen`, varName, ` uint64`) p.decodeVarint("stringLen"+varName, "uint64") p.P(`intStringLen`, varName, ` := int(stringLen`, varName, `)`) p.P(`if intStringLen`, varName, ` < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postStringIndex`, varName, ` := iNdEx + intStringLen`, varName) p.P(`if postStringIndex`, varName, ` < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postStringIndex`, varName, ` > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) cast, _ := p.GoType(nil, field) cast = strings.Replace(cast, "*", "", 1) p.P(varName, ` = `, cast, `(dAtA[iNdEx:postStringIndex`, varName, `])`) p.P(`iNdEx = postStringIndex`, varName) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: p.P(`var mapmsglen int`) p.decodeVarint("mapmsglen", "int") p.P(`if mapmsglen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postmsgIndex := iNdEx + mapmsglen`) p.P(`if postmsgIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postmsgIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) buf := `dAtA[iNdEx:postmsgIndex]` if gogoproto.IsStdTime(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdDuration(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdDouble(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdFloat(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdUInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdUInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdBool(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdString(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else if gogoproto.IsStdBytes(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(`, varName, `, `, buf, `); err != nil {`) } else { desc := p.ObjectNamed(field.GetTypeName()) msgname := p.TypeName(desc) p.P(varName, ` = &`, msgname, `{}`) p.P(`if err := `, varName, `.Unmarshal(`, buf, `); err != nil {`) } p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`iNdEx = postmsgIndex`) case descriptor.FieldDescriptorProto_TYPE_BYTES: p.P(`var mapbyteLen uint64`) p.decodeVarint("mapbyteLen", "uint64") p.P(`intMapbyteLen := int(mapbyteLen)`) p.P(`if intMapbyteLen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postbytesIndex := iNdEx + intMapbyteLen`) p.P(`if postbytesIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postbytesIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) if customType { p.P(`if err := `, varName, `.Unmarshal(dAtA[iNdEx:postbytesIndex]); err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) } else { p.P(varName, ` = make([]byte, mapbyteLen)`) p.P(`copy(`, varName, `, dAtA[iNdEx:postbytesIndex])`) } p.P(`iNdEx = postbytesIndex`) case descriptor.FieldDescriptorProto_TYPE_UINT32: p.decodeVarint(varName, "uint32") case descriptor.FieldDescriptorProto_TYPE_ENUM: typName := p.TypeName(p.ObjectNamed(field.GetTypeName())) p.decodeVarint(varName, typName) case descriptor.FieldDescriptorProto_TYPE_SFIXED32: p.decodeFixed32(varName, "int32") case descriptor.FieldDescriptorProto_TYPE_SFIXED64: p.decodeFixed64(varName, "int64") case descriptor.FieldDescriptorProto_TYPE_SINT32: p.P(`var `, varName, `temp int32`) p.decodeVarint(varName+"temp", "int32") p.P(varName, `temp = int32((uint32(`, varName, `temp) >> 1) ^ uint32(((`, varName, `temp&1)<<31)>>31))`) p.P(varName, ` = int32(`, varName, `temp)`) case descriptor.FieldDescriptorProto_TYPE_SINT64: p.P(`var `, varName, `temp uint64`) p.decodeVarint(varName+"temp", "uint64") p.P(varName, `temp = (`, varName, `temp >> 1) ^ uint64((int64(`, varName, `temp&1)<<63)>>63)`) p.P(varName, ` = int64(`, varName, `temp)`) } } func (p *unmarshal) noStarOrSliceType(msg *generator.Descriptor, field *descriptor.FieldDescriptorProto) string { typ, _ := p.GoType(msg, field) if typ[0] == '*' { return typ[1:] } if typ[0] == '[' && typ[1] == ']' { return typ[2:] } return typ } func (p *unmarshal) field(file *generator.FileDescriptor, msg *generator.Descriptor, field *descriptor.FieldDescriptorProto, fieldname string, proto3 bool) { repeated := field.IsRepeated() nullable := gogoproto.IsNullable(field) typ := p.noStarOrSliceType(msg, field) oneof := field.OneofIndex != nil switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: p.P(`var v uint64`) p.decodeFixed64("v", "uint64") if oneof { p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{`, typ, "(", p.mathPkg.Use(), `.Float64frombits(v))}`) } else if repeated { p.P(`v2 := `, typ, "(", p.mathPkg.Use(), `.Float64frombits(v))`) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v2)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = `, typ, "(", p.mathPkg.Use(), `.Float64frombits(v))`) } else { p.P(`v2 := `, typ, "(", p.mathPkg.Use(), `.Float64frombits(v))`) p.P(`m.`, fieldname, ` = &v2`) } case descriptor.FieldDescriptorProto_TYPE_FLOAT: p.P(`var v uint32`) p.decodeFixed32("v", "uint32") if oneof { p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{`, typ, "(", p.mathPkg.Use(), `.Float32frombits(v))}`) } else if repeated { p.P(`v2 := `, typ, "(", p.mathPkg.Use(), `.Float32frombits(v))`) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v2)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = `, typ, "(", p.mathPkg.Use(), `.Float32frombits(v))`) } else { p.P(`v2 := `, typ, "(", p.mathPkg.Use(), `.Float32frombits(v))`) p.P(`m.`, fieldname, ` = &v2`) } case descriptor.FieldDescriptorProto_TYPE_INT64: if oneof { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeVarint("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_UINT64: if oneof { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeVarint("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_INT32: if oneof { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeVarint("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_FIXED64: if oneof { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeFixed64("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_FIXED32: if oneof { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeFixed32("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_BOOL: p.P(`var v int`) p.decodeVarint("v", "int") if oneof { p.P(`b := `, typ, `(v != 0)`) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{b}`) } else if repeated { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, `, typ, `(v != 0))`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = `, typ, `(v != 0)`) } else { p.P(`b := `, typ, `(v != 0)`) p.P(`m.`, fieldname, ` = &b`) } case descriptor.FieldDescriptorProto_TYPE_STRING: p.P(`var stringLen uint64`) p.decodeVarint("stringLen", "uint64") p.P(`intStringLen := int(stringLen)`) p.P(`if intStringLen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postIndex := iNdEx + intStringLen`) p.P(`if postIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) if oneof { p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{`, typ, `(dAtA[iNdEx:postIndex])}`) } else if repeated { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, `, typ, `(dAtA[iNdEx:postIndex]))`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = `, typ, `(dAtA[iNdEx:postIndex])`) } else { p.P(`s := `, typ, `(dAtA[iNdEx:postIndex])`) p.P(`m.`, fieldname, ` = &s`) } p.P(`iNdEx = postIndex`) case descriptor.FieldDescriptorProto_TYPE_GROUP: panic(fmt.Errorf("unmarshaler does not support group %v", fieldname)) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: desc := p.ObjectNamed(field.GetTypeName()) msgname := p.TypeName(desc) p.P(`var msglen int`) p.decodeVarint("msglen", "int") p.P(`if msglen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postIndex := iNdEx + msglen`) p.P(`if postIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) if oneof { buf := `dAtA[iNdEx:postIndex]` if gogoproto.IsStdTime(field) { if nullable { p.P(`v := new(time.Time)`) p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := time.Time{}`) p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdDuration(field) { if nullable { p.P(`v := new(time.Duration)`) p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := time.Duration(0)`) p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdDouble(field) { if nullable { p.P(`v := new(float64)`) p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdFloat(field) { if nullable { p.P(`v := new(float32)`) p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdInt64(field) { if nullable { p.P(`v := new(int64)`) p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdUInt64(field) { if nullable { p.P(`v := new(uint64)`) p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdInt32(field) { if nullable { p.P(`v := new(int32)`) p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdUInt32(field) { if nullable { p.P(`v := new(uint32)`) p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := 0`) p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdBool(field) { if nullable { p.P(`v := new(bool)`) p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := false`) p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdString(field) { if nullable { p.P(`v := new(string)`) p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`v := ""`) p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(&v, `, buf, `); err != nil {`) } } else if gogoproto.IsStdBytes(field) { if nullable { p.P(`v := new([]byte)`) p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(v, `, buf, `); err != nil {`) } else { p.P(`var v []byte`) p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(&v, `, buf, `); err != nil {`) } } else { p.P(`v := &`, msgname, `{}`) p.P(`if err := v.Unmarshal(`, buf, `); err != nil {`) } p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if p.IsMap(field) { m := p.GoMapType(nil, field) keygoTyp, _ := p.GoType(nil, m.KeyField) keygoAliasTyp, _ := p.GoType(nil, m.KeyAliasField) // keys may not be pointers keygoTyp = strings.Replace(keygoTyp, "*", "", 1) keygoAliasTyp = strings.Replace(keygoAliasTyp, "*", "", 1) valuegoTyp, _ := p.GoType(nil, m.ValueField) valuegoAliasTyp, _ := p.GoType(nil, m.ValueAliasField) // if the map type is an alias and key or values are aliases (type Foo map[Bar]Baz), // we need to explicitly record their use here. if gogoproto.IsCastKey(field) { p.RecordTypeUse(m.KeyAliasField.GetTypeName()) } if gogoproto.IsCastValue(field) { p.RecordTypeUse(m.ValueAliasField.GetTypeName()) } nullable, valuegoTyp, valuegoAliasTyp = generator.GoMapValueTypes(field, m.ValueField, valuegoTyp, valuegoAliasTyp) if gogoproto.IsStdType(field) { valuegoTyp = valuegoAliasTyp } p.P(`if m.`, fieldname, ` == nil {`) p.In() p.P(`m.`, fieldname, ` = make(`, m.GoType, `)`) p.Out() p.P(`}`) p.declareMapField("mapkey", false, false, m.KeyAliasField) p.declareMapField("mapvalue", nullable, gogoproto.IsCustomType(field), m.ValueAliasField) p.P(`for iNdEx < postIndex {`) p.In() p.P(`entryPreIndex := iNdEx`) p.P(`var wire uint64`) p.decodeVarint("wire", "uint64") p.P(`fieldNum := int32(wire >> 3)`) p.P(`if fieldNum == 1 {`) p.In() p.mapField("mapkey", false, m.KeyAliasField) p.Out() p.P(`} else if fieldNum == 2 {`) p.In() p.mapField("mapvalue", gogoproto.IsCustomType(field), m.ValueAliasField) p.Out() p.P(`} else {`) p.In() p.P(`iNdEx = entryPreIndex`) p.P(`skippy, err := skip`, p.localName, `(dAtA[iNdEx:])`) p.P(`if err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`if (skippy < 0) || (iNdEx + skippy) < 0 {`) p.In() p.P(`return ErrInvalidLength`, p.localName) p.Out() p.P(`}`) p.P(`if (iNdEx + skippy) > postIndex {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(`iNdEx += skippy`) p.Out() p.P(`}`) p.Out() p.P(`}`) s := `m.` + fieldname if keygoTyp == keygoAliasTyp { s += `[mapkey]` } else { s += `[` + keygoAliasTyp + `(mapkey)]` } v := `mapvalue` if (m.ValueField.IsMessage() || gogoproto.IsCustomType(field)) && !nullable { v = `*` + v } if valuegoTyp != valuegoAliasTyp { v = `((` + valuegoAliasTyp + `)(` + v + `))` } p.P(s, ` = `, v) } else if repeated { if gogoproto.IsStdTime(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(time.Time))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, time.Time{})`) } } else if gogoproto.IsStdDuration(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(time.Duration))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, time.Duration(0))`) } } else if gogoproto.IsStdDouble(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(float64))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdFloat(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(float32))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdInt64(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(int64))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdUInt64(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(uint64))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdInt32(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(int32))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdUInt32(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(uint32))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, 0)`) } } else if gogoproto.IsStdBool(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(bool))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, false)`) } } else if gogoproto.IsStdString(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new(string))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, "")`) } } else if gogoproto.IsStdBytes(field) { if nullable { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, new([]byte))`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, []byte{})`) } } else if nullable && !gogoproto.IsCustomType(field) { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, &`, msgname, `{})`) } else { goType, _ := p.GoType(nil, field) // remove the slice from the type, i.e. []*T -> *T goType = goType[2:] p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, `, goType, `{})`) } varName := `m.` + fieldname + `[len(m.` + fieldname + `)-1]` buf := `dAtA[iNdEx:postIndex]` if gogoproto.IsStdTime(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdDuration(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdDouble(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdFloat(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdInt64(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdUInt64(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdInt32(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdUInt32(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdBool(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdString(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else if gogoproto.IsStdBytes(field) { if nullable { p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(`, varName, `,`, buf, `); err != nil {`) } else { p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(&(`, varName, `),`, buf, `); err != nil {`) } } else { p.P(`if err := `, varName, `.Unmarshal(`, buf, `); err != nil {`) } p.In() p.P(`return err`) p.Out() p.P(`}`) } else if nullable { p.P(`if m.`, fieldname, ` == nil {`) p.In() if gogoproto.IsStdTime(field) { p.P(`m.`, fieldname, ` = new(time.Time)`) } else if gogoproto.IsStdDuration(field) { p.P(`m.`, fieldname, ` = new(time.Duration)`) } else if gogoproto.IsStdDouble(field) { p.P(`m.`, fieldname, ` = new(float64)`) } else if gogoproto.IsStdFloat(field) { p.P(`m.`, fieldname, ` = new(float32)`) } else if gogoproto.IsStdInt64(field) { p.P(`m.`, fieldname, ` = new(int64)`) } else if gogoproto.IsStdUInt64(field) { p.P(`m.`, fieldname, ` = new(uint64)`) } else if gogoproto.IsStdInt32(field) { p.P(`m.`, fieldname, ` = new(int32)`) } else if gogoproto.IsStdUInt32(field) { p.P(`m.`, fieldname, ` = new(uint32)`) } else if gogoproto.IsStdBool(field) { p.P(`m.`, fieldname, ` = new(bool)`) } else if gogoproto.IsStdString(field) { p.P(`m.`, fieldname, ` = new(string)`) } else if gogoproto.IsStdBytes(field) { p.P(`m.`, fieldname, ` = new([]byte)`) } else { goType, _ := p.GoType(nil, field) // remove the star from the type p.P(`m.`, fieldname, ` = &`, goType[1:], `{}`) } p.Out() p.P(`}`) if gogoproto.IsStdTime(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdDuration(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdDouble(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdFloat(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdUInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdUInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdBool(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdString(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdBytes(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else { p.P(`if err := m.`, fieldname, `.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) } p.In() p.P(`return err`) p.Out() p.P(`}`) } else { if gogoproto.IsStdTime(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdTimeUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdDuration(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDurationUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdDouble(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdDoubleUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdFloat(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdFloatUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt64Unmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdUInt64(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt64Unmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdInt32Unmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdUInt32(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdUInt32Unmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdBool(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBoolUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdString(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdStringUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else if gogoproto.IsStdBytes(field) { p.P(`if err := `, p.typesPkg.Use(), `.StdBytesUnmarshal(&m.`, fieldname, `, dAtA[iNdEx:postIndex]); err != nil {`) } else { p.P(`if err := m.`, fieldname, `.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) } p.In() p.P(`return err`) p.Out() p.P(`}`) } p.P(`iNdEx = postIndex`) case descriptor.FieldDescriptorProto_TYPE_BYTES: p.P(`var byteLen int`) p.decodeVarint("byteLen", "int") p.P(`if byteLen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postIndex := iNdEx + byteLen`) p.P(`if postIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) if !gogoproto.IsCustomType(field) { if oneof { p.P(`v := make([]byte, postIndex-iNdEx)`) p.P(`copy(v, dAtA[iNdEx:postIndex])`) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, make([]byte, postIndex-iNdEx))`) p.P(`copy(m.`, fieldname, `[len(m.`, fieldname, `)-1], dAtA[iNdEx:postIndex])`) } else { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `[:0] , dAtA[iNdEx:postIndex]...)`) p.P(`if m.`, fieldname, ` == nil {`) p.In() p.P(`m.`, fieldname, ` = []byte{}`) p.Out() p.P(`}`) } } else { _, ctyp, err := generator.GetCustomType(field) if err != nil { panic(err) } if oneof { p.P(`var vv `, ctyp) p.P(`v := &vv`) p.P(`if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{*v}`) } else if repeated { p.P(`var v `, ctyp) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) p.P(`if err := m.`, fieldname, `[len(m.`, fieldname, `)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) } else if nullable { p.P(`var v `, ctyp) p.P(`m.`, fieldname, ` = &v`) p.P(`if err := m.`, fieldname, `.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) } else { p.P(`if err := m.`, fieldname, `.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) } } p.P(`iNdEx = postIndex`) case descriptor.FieldDescriptorProto_TYPE_UINT32: if oneof { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeVarint("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_ENUM: typName := p.TypeName(p.ObjectNamed(field.GetTypeName())) if oneof { p.P(`var v `, typName) p.decodeVarint("v", typName) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typName) p.decodeVarint("v", typName) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeVarint("m."+fieldname, typName) } else { p.P(`var v `, typName) p.decodeVarint("v", typName) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_SFIXED32: if oneof { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeFixed32("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeFixed32("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_SFIXED64: if oneof { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = 0`) p.decodeFixed64("m."+fieldname, typ) } else { p.P(`var v `, typ) p.decodeFixed64("v", typ) p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_SINT32: p.P(`var v `, typ) p.decodeVarint("v", typ) p.P(`v = `, typ, `((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31))`) if oneof { p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{v}`) } else if repeated { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, v)`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = v`) } else { p.P(`m.`, fieldname, ` = &v`) } case descriptor.FieldDescriptorProto_TYPE_SINT64: p.P(`var v uint64`) p.decodeVarint("v", "uint64") p.P(`v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63)`) if oneof { p.P(`m.`, fieldname, ` = &`, p.OneOfTypeName(msg, field), `{`, typ, `(v)}`) } else if repeated { p.P(`m.`, fieldname, ` = append(m.`, fieldname, `, `, typ, `(v))`) } else if proto3 || !nullable { p.P(`m.`, fieldname, ` = `, typ, `(v)`) } else { p.P(`v2 := `, typ, `(v)`) p.P(`m.`, fieldname, ` = &v2`) } default: panic("not implemented") } } func (p *unmarshal) Generate(file *generator.FileDescriptor) { proto3 := gogoproto.IsProto3(file.FileDescriptorProto) p.PluginImports = generator.NewPluginImports(p.Generator) p.atleastOne = false p.localName = generator.FileName(file) p.ioPkg = p.NewImport("io") p.mathPkg = p.NewImport("math") p.typesPkg = p.NewImport("github.com/gogo/protobuf/types") p.binaryPkg = p.NewImport("encoding/binary") fmtPkg := p.NewImport("fmt") protoPkg := p.NewImport("github.com/gogo/protobuf/proto") if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) { protoPkg = p.NewImport("github.com/golang/protobuf/proto") } for _, message := range file.Messages() { ccTypeName := generator.CamelCaseSlice(message.TypeName()) if !gogoproto.IsUnmarshaler(file.FileDescriptorProto, message.DescriptorProto) && !gogoproto.IsUnsafeUnmarshaler(file.FileDescriptorProto, message.DescriptorProto) { continue } if message.DescriptorProto.GetOptions().GetMapEntry() { continue } p.atleastOne = true // build a map required field_id -> bitmask offset rfMap := make(map[int32]uint) rfNextId := uint(0) for _, field := range message.Field { if field.IsRequired() { rfMap[field.GetNumber()] = rfNextId rfNextId++ } } rfCount := len(rfMap) p.P(`func (m *`, ccTypeName, `) Unmarshal(dAtA []byte) error {`) p.In() if rfCount > 0 { p.P(`var hasFields [`, strconv.Itoa(1+(rfCount-1)/64), `]uint64`) } p.P(`l := len(dAtA)`) p.P(`iNdEx := 0`) p.P(`for iNdEx < l {`) p.In() p.P(`preIndex := iNdEx`) p.P(`var wire uint64`) p.decodeVarint("wire", "uint64") p.P(`fieldNum := int32(wire >> 3)`) if len(message.Field) > 0 || !message.IsGroup() { p.P(`wireType := int(wire & 0x7)`) } if !message.IsGroup() { p.P(`if wireType == `, strconv.Itoa(proto.WireEndGroup), ` {`) p.In() p.P(`return `, fmtPkg.Use(), `.Errorf("proto: `+message.GetName()+`: wiretype end group for non-group")`) p.Out() p.P(`}`) } p.P(`if fieldNum <= 0 {`) p.In() p.P(`return `, fmtPkg.Use(), `.Errorf("proto: `+message.GetName()+`: illegal tag %d (wire type %d)", fieldNum, wire)`) p.Out() p.P(`}`) p.P(`switch fieldNum {`) p.In() for _, field := range message.Field { fieldname := p.GetFieldName(message, field) errFieldname := fieldname if field.OneofIndex != nil { errFieldname = p.GetOneOfFieldName(message, field) } possiblyPacked := field.IsScalar() && field.IsRepeated() p.P(`case `, strconv.Itoa(int(field.GetNumber())), `:`) p.In() wireType := field.WireType() if possiblyPacked { p.P(`if wireType == `, strconv.Itoa(wireType), `{`) p.In() p.field(file, message, field, fieldname, false) p.Out() p.P(`} else if wireType == `, strconv.Itoa(proto.WireBytes), `{`) p.In() p.P(`var packedLen int`) p.decodeVarint("packedLen", "int") p.P(`if packedLen < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`postIndex := iNdEx + packedLen`) p.P(`if postIndex < 0 {`) p.In() p.P(`return ErrInvalidLength` + p.localName) p.Out() p.P(`}`) p.P(`if postIndex > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(`var elementCount int`) switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: p.P(`elementCount = packedLen/`, 8) case descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: p.P(`elementCount = packedLen/`, 4) case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: p.P(`var count int`) p.P(`for _, integer := range dAtA[iNdEx:postIndex] {`) p.In() p.P(`if integer < 128 {`) p.In() p.P(`count++`) p.Out() p.P(`}`) p.Out() p.P(`}`) p.P(`elementCount = count`) case descriptor.FieldDescriptorProto_TYPE_BOOL: p.P(`elementCount = packedLen`) } p.P(`if elementCount != 0 && len(m.`, fieldname, `) == 0 {`) p.In() p.P(`m.`, fieldname, ` = make([]`, p.noStarOrSliceType(message, field), `, 0, elementCount)`) p.Out() p.P(`}`) p.P(`for iNdEx < postIndex {`) p.In() p.field(file, message, field, fieldname, false) p.Out() p.P(`}`) p.Out() p.P(`} else {`) p.In() p.P(`return ` + fmtPkg.Use() + `.Errorf("proto: wrong wireType = %d for field ` + errFieldname + `", wireType)`) p.Out() p.P(`}`) } else { p.P(`if wireType != `, strconv.Itoa(wireType), `{`) p.In() p.P(`return ` + fmtPkg.Use() + `.Errorf("proto: wrong wireType = %d for field ` + errFieldname + `", wireType)`) p.Out() p.P(`}`) p.field(file, message, field, fieldname, proto3) } if field.IsRequired() { fieldBit, ok := rfMap[field.GetNumber()] if !ok { panic("field is required, but no bit registered") } p.P(`hasFields[`, strconv.Itoa(int(fieldBit/64)), `] |= uint64(`, fmt.Sprintf("0x%08x", uint64(1)<<(fieldBit%64)), `)`) } } p.Out() p.P(`default:`) p.In() if message.DescriptorProto.HasExtension() { c := []string{} for _, erange := range message.GetExtensionRange() { c = append(c, `((fieldNum >= `+strconv.Itoa(int(erange.GetStart()))+") && (fieldNum<"+strconv.Itoa(int(erange.GetEnd()))+`))`) } p.P(`if `, strings.Join(c, "||"), `{`) p.In() p.P(`var sizeOfWire int`) p.P(`for {`) p.In() p.P(`sizeOfWire++`) p.P(`wire >>= 7`) p.P(`if wire == 0 {`) p.In() p.P(`break`) p.Out() p.P(`}`) p.Out() p.P(`}`) p.P(`iNdEx-=sizeOfWire`) p.P(`skippy, err := skip`, p.localName+`(dAtA[iNdEx:])`) p.P(`if err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`if (skippy < 0) || (iNdEx + skippy) < 0 {`) p.In() p.P(`return ErrInvalidLength`, p.localName) p.Out() p.P(`}`) p.P(`if (iNdEx + skippy) > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(protoPkg.Use(), `.AppendExtension(m, int32(fieldNum), dAtA[iNdEx:iNdEx+skippy])`) p.P(`iNdEx += skippy`) p.Out() p.P(`} else {`) p.In() } p.P(`iNdEx=preIndex`) p.P(`skippy, err := skip`, p.localName, `(dAtA[iNdEx:])`) p.P(`if err != nil {`) p.In() p.P(`return err`) p.Out() p.P(`}`) p.P(`if (skippy < 0) || (iNdEx + skippy) < 0 {`) p.In() p.P(`return ErrInvalidLength`, p.localName) p.Out() p.P(`}`) p.P(`if (iNdEx + skippy) > l {`) p.In() p.P(`return `, p.ioPkg.Use(), `.ErrUnexpectedEOF`) p.Out() p.P(`}`) if gogoproto.HasUnrecognized(file.FileDescriptorProto, message.DescriptorProto) { p.P(`m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)`) } p.P(`iNdEx += skippy`) p.Out() if message.DescriptorProto.HasExtension() { p.Out() p.P(`}`) } p.Out() p.P(`}`) p.Out() p.P(`}`) for _, field := range message.Field { if !field.IsRequired() { continue } fieldBit, ok := rfMap[field.GetNumber()] if !ok { panic("field is required, but no bit registered") } p.P(`if hasFields[`, strconv.Itoa(int(fieldBit/64)), `] & uint64(`, fmt.Sprintf("0x%08x", uint64(1)<<(fieldBit%64)), `) == 0 {`) p.In() if !gogoproto.ImportsGoGoProto(file.FileDescriptorProto) { p.P(`return new(`, protoPkg.Use(), `.RequiredNotSetError)`) } else { p.P(`return `, protoPkg.Use(), `.NewRequiredNotSetError("`, field.GetName(), `")`) } p.Out() p.P(`}`) } p.P() p.P(`if iNdEx > l {`) p.In() p.P(`return ` + p.ioPkg.Use() + `.ErrUnexpectedEOF`) p.Out() p.P(`}`) p.P(`return nil`) p.Out() p.P(`}`) } if !p.atleastOne { return } p.P(`func skip` + p.localName + `(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflow` + p.localName + ` } if iNdEx >= l { return 0, ` + p.ioPkg.Use() + `.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflow` + p.localName + ` } if iNdEx >= l { return 0, ` + p.ioPkg.Use() + `.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } case 1: iNdEx += 8 case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflow` + p.localName + ` } if iNdEx >= l { return 0, ` + p.ioPkg.Use() + `.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLength` + p.localName + ` } iNdEx += length case 3: depth++ case 4: if depth == 0 { return 0, ErrUnexpectedEndOfGroup` + p.localName + ` } depth-- case 5: iNdEx += 4 default: return 0, ` + fmtPkg.Use() + `.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { return 0, ErrInvalidLength` + p.localName + ` } if depth == 0 { return iNdEx, nil } } return 0, ` + p.ioPkg.Use() + `.ErrUnexpectedEOF } var ( ErrInvalidLength` + p.localName + ` = ` + fmtPkg.Use() + `.Errorf("proto: negative length found during unmarshaling") ErrIntOverflow` + p.localName + ` = ` + fmtPkg.Use() + `.Errorf("proto: integer overflow") ErrUnexpectedEndOfGroup` + p.localName + ` = ` + fmtPkg.Use() + `.Errorf("proto: unexpected end of group") ) `) } func init() { generator.RegisterPlugin(NewUnmarshal()) }
cblecker/kubernetes
vendor/github.com/gogo/protobuf/plugin/unmarshal/unmarshal.go
GO
apache-2.0
55,284
/*! * Express - View * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var path = require('path') , utils = require('../utils') , extname = path.extname , dirname = path.dirname , basename = path.basename , fs = require('fs') , stat = fs.statSync; /** * Expose `View`. */ exports = module.exports = View; /** * Require cache. */ var cache = {}; /** * Initialize a new `View` with the given `view` path and `options`. * * @param {String} view * @param {Object} options * @api private */ function View(view, options) { options = options || {}; this.view = view; this.root = options.root; this.relative = false !== options.relative; this.defaultEngine = options.defaultEngine; this.parent = options.parentView; this.basename = basename(view); this.engine = this.resolveEngine(); this.extension = '.' + this.engine; this.name = this.basename.replace(this.extension, ''); this.path = this.resolvePath(); this.dirname = dirname(this.path); if (options.attempts) { if (!~options.attempts.indexOf(this.path)) options.attempts.push(this.path); } }; /** * Check if the view path exists. * * @return {Boolean} * @api public */ View.prototype.__defineGetter__('exists', function(){ try { stat(this.path); return true; } catch (err) { return false; } }); /** * Resolve view engine. * * @return {String} * @api private */ View.prototype.resolveEngine = function(){ // Explicit if (~this.basename.indexOf('.')) return extname(this.basename).substr(1); // Inherit from parent if (this.parent) return this.parent.engine; // Default return this.defaultEngine; }; /** * Resolve view path. * * @return {String} * @api private */ View.prototype.resolvePath = function(){ var path = this.view; // Implicit engine if (!~this.basename.indexOf('.')) path += this.extension; // Absolute if (utils.isAbsolute(path)) return path; // Relative to parent if (this.relative && this.parent) return this.parent.dirname + '/' + path; // Relative to root return this.root ? this.root + '/' + path : path; }; /** * Get view contents. This is a one-time hit, so we * can afford to be sync. * * @return {String} * @api public */ View.prototype.__defineGetter__('contents', function(){ return fs.readFileSync(this.path, 'utf8'); }); /** * Get template engine api, cache exports to reduce * require() calls. * * @return {Object} * @api public */ View.prototype.__defineGetter__('templateEngine', function(){ var ext = this.extension; return cache[ext] || (cache[ext] = require(this.engine)); }); /** * Return root path alternative. * * @return {String} * @api public */ View.prototype.__defineGetter__('rootPath', function(){ this.relative = false; return this.resolvePath(); }); /** * Return index path alternative. * * @return {String} * @api public */ View.prototype.__defineGetter__('indexPath', function(){ return this.dirname + '/' + this.basename.replace(this.extension, '') + '/index' + this.extension; }); /** * Return ../<name>/index path alternative. * * @return {String} * @api public */ View.prototype.__defineGetter__('upIndexPath', function(){ return this.dirname + '/../' + this.name + '/index' + this.extension; }); /** * Return _ prefix path alternative * * @return {String} * @api public */ View.prototype.__defineGetter__('prefixPath', function(){ return this.dirname + '/_' + this.basename; }); /** * Register the given template engine `exports` * as `ext`. For example we may wish to map ".html" * files to jade: * * app.register('.html', require('jade')); * * or * * app.register('html', require('jade')); * * This is also useful for libraries that may not * match extensions correctly. For example my haml.js * library is installed from npm as "hamljs" so instead * of layout.hamljs, we can register the engine as ".haml": * * app.register('.haml', require('haml-js')); * * @param {String} ext * @param {Object} obj * @api public */ exports.register = function(ext, exports) { if ('.' != ext[0]) ext = '.' + ext; cache[ext] = exports; };
webOS-ports/enyo-1.0
support/enyo-compress/node_modules/express/lib/view/view.js
JavaScript
apache-2.0
4,231
;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.slider = { name : 'slider', version : '5.5.3', settings : { start : 0, end : 100, step : 1, precision : 2, initial : null, display_selector : '', vertical : false, trigger_input_change : false, on_change : function () {} }, cache : {}, init : function (scope, method, options) { Foundation.inherit(this, 'throttle'); this.bindings(method, options); this.reflow(); }, events : function () { var self = this; $(this.scope) .off('.slider') .on('mousedown.fndtn.slider touchstart.fndtn.slider pointerdown.fndtn.slider', '[' + self.attr_name() + ']:not(.disabled, [disabled]) .range-slider-handle', function (e) { if (!self.cache.active) { e.preventDefault(); self.set_active_slider($(e.target)); } }) .on('mousemove.fndtn.slider touchmove.fndtn.slider pointermove.fndtn.slider', function (e) { if (!!self.cache.active) { e.preventDefault(); if ($.data(self.cache.active[0], 'settings').vertical) { var scroll_offset = 0; if (!e.pageY) { scroll_offset = window.scrollY; } self.calculate_position(self.cache.active, self.get_cursor_position(e, 'y') + scroll_offset); } else { self.calculate_position(self.cache.active, self.get_cursor_position(e, 'x')); } } }) .on('mouseup.fndtn.slider touchend.fndtn.slider pointerup.fndtn.slider', function (e) { if(!self.cache.active) { // if the user has just clicked into the slider without starting to drag the handle var slider = $(e.target).attr('role') === 'slider' ? $(e.target) : $(e.target).closest('.range-slider').find("[role='slider']"); if (slider.length && (!slider.parent().hasClass('disabled') && !slider.parent().attr('disabled'))) { self.set_active_slider(slider); if ($.data(self.cache.active[0], 'settings').vertical) { var scroll_offset = 0; if (!e.pageY) { scroll_offset = window.scrollY; } self.calculate_position(self.cache.active, self.get_cursor_position(e, 'y') + scroll_offset); } else { self.calculate_position(self.cache.active, self.get_cursor_position(e, 'x')); } } } self.remove_active_slider(); }) .on('change.fndtn.slider', function (e) { self.settings.on_change(); }); self.S(window) .on('resize.fndtn.slider', self.throttle(function (e) { self.reflow(); }, 300)); // update slider value as users change input value this.S('[' + this.attr_name() + ']').each(function () { var slider = $(this), handle = slider.children('.range-slider-handle')[0], settings = self.initialize_settings(handle); if (settings.display_selector != '') { $(settings.display_selector).each(function(){ if ($(this).attr('value')) { $(this).off('change').on('change', function () { slider.foundation("slider", "set_value", $(this).val()); }); } }); } }); }, get_cursor_position : function (e, xy) { var pageXY = 'page' + xy.toUpperCase(), clientXY = 'client' + xy.toUpperCase(), position; if (typeof e[pageXY] !== 'undefined') { position = e[pageXY]; } else if (typeof e.originalEvent[clientXY] !== 'undefined') { position = e.originalEvent[clientXY]; } else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0][clientXY] !== 'undefined') { position = e.originalEvent.touches[0][clientXY]; } else if (e.currentPoint && typeof e.currentPoint[xy] !== 'undefined') { position = e.currentPoint[xy]; } return position; }, set_active_slider : function ($handle) { this.cache.active = $handle; }, remove_active_slider : function () { this.cache.active = null; }, calculate_position : function ($handle, cursor_x) { var self = this, settings = $.data($handle[0], 'settings'), handle_l = $.data($handle[0], 'handle_l'), handle_o = $.data($handle[0], 'handle_o'), bar_l = $.data($handle[0], 'bar_l'), bar_o = $.data($handle[0], 'bar_o'); requestAnimationFrame(function () { var pct; if (Foundation.rtl && !settings.vertical) { pct = self.limit_to(((bar_o + bar_l - cursor_x) / bar_l), 0, 1); } else { pct = self.limit_to(((cursor_x - bar_o) / bar_l), 0, 1); } pct = settings.vertical ? 1 - pct : pct; var norm = self.normalized_value(pct, settings.start, settings.end, settings.step, settings.precision); self.set_ui($handle, norm); }); }, set_ui : function ($handle, value) { var settings = $.data($handle[0], 'settings'), handle_l = $.data($handle[0], 'handle_l'), bar_l = $.data($handle[0], 'bar_l'), norm_pct = this.normalized_percentage(value, settings.start, settings.end), handle_offset = norm_pct * (bar_l - handle_l) - 1, progress_bar_length = norm_pct * 100, $handle_parent = $handle.parent(), $hidden_inputs = $handle.parent().children('input[type=hidden]'); if (Foundation.rtl && !settings.vertical) { handle_offset = -handle_offset; } handle_offset = settings.vertical ? -handle_offset + bar_l - handle_l + 1 : handle_offset; this.set_translate($handle, handle_offset, settings.vertical); if (settings.vertical) { $handle.siblings('.range-slider-active-segment').css('height', progress_bar_length + '%'); } else { $handle.siblings('.range-slider-active-segment').css('width', progress_bar_length + '%'); } $handle_parent.attr(this.attr_name(), value).trigger('change.fndtn.slider'); $hidden_inputs.val(value); if (settings.trigger_input_change) { $hidden_inputs.trigger('change.fndtn.slider'); } if (!$handle[0].hasAttribute('aria-valuemin')) { $handle.attr({ 'aria-valuemin' : settings.start, 'aria-valuemax' : settings.end }); } $handle.attr('aria-valuenow', value); if (settings.display_selector != '') { $(settings.display_selector).each(function () { if (this.hasAttribute('value')) { $(this).val(value); } else { $(this).text(value); } }); } }, normalized_percentage : function (val, start, end) { return Math.min(1, (val - start) / (end - start)); }, normalized_value : function (val, start, end, step, precision) { var range = end - start, point = val * range, mod = (point - (point % step)) / step, rem = point % step, round = ( rem >= step * 0.5 ? step : 0); return ((mod * step + round) + start).toFixed(precision); }, set_translate : function (ele, offset, vertical) { if (vertical) { $(ele) .css('-webkit-transform', 'translateY(' + offset + 'px)') .css('-moz-transform', 'translateY(' + offset + 'px)') .css('-ms-transform', 'translateY(' + offset + 'px)') .css('-o-transform', 'translateY(' + offset + 'px)') .css('transform', 'translateY(' + offset + 'px)'); } else { $(ele) .css('-webkit-transform', 'translateX(' + offset + 'px)') .css('-moz-transform', 'translateX(' + offset + 'px)') .css('-ms-transform', 'translateX(' + offset + 'px)') .css('-o-transform', 'translateX(' + offset + 'px)') .css('transform', 'translateX(' + offset + 'px)'); } }, limit_to : function (val, min, max) { return Math.min(Math.max(val, min), max); }, initialize_settings : function (handle) { var settings = $.extend({}, this.settings, this.data_options($(handle).parent())), decimal_places_match_result; if (settings.precision === null) { decimal_places_match_result = ('' + settings.step).match(/\.([\d]*)/); settings.precision = decimal_places_match_result && decimal_places_match_result[1] ? decimal_places_match_result[1].length : 0; } if (settings.vertical) { $.data(handle, 'bar_o', $(handle).parent().offset().top); $.data(handle, 'bar_l', $(handle).parent().outerHeight()); $.data(handle, 'handle_o', $(handle).offset().top); $.data(handle, 'handle_l', $(handle).outerHeight()); } else { $.data(handle, 'bar_o', $(handle).parent().offset().left); $.data(handle, 'bar_l', $(handle).parent().outerWidth()); $.data(handle, 'handle_o', $(handle).offset().left); $.data(handle, 'handle_l', $(handle).outerWidth()); } $.data(handle, 'bar', $(handle).parent()); return $.data(handle, 'settings', settings); }, set_initial_position : function ($ele) { var settings = $.data($ele.children('.range-slider-handle')[0], 'settings'), initial = ((typeof settings.initial == 'number' && !isNaN(settings.initial)) ? settings.initial : Math.floor((settings.end - settings.start) * 0.5 / settings.step) * settings.step + settings.start), $handle = $ele.children('.range-slider-handle'); this.set_ui($handle, initial); }, set_value : function (value) { var self = this; $('[' + self.attr_name() + ']', this.scope).each(function () { $(this).attr(self.attr_name(), value); }); if (!!$(this.scope).attr(self.attr_name())) { $(this.scope).attr(self.attr_name(), value); } self.reflow(); }, reflow : function () { var self = this; self.S('[' + this.attr_name() + ']').each(function () { var handle = $(this).children('.range-slider-handle')[0], val = $(this).attr(self.attr_name()); self.initialize_settings(handle); if (val) { self.set_ui($(handle), parseFloat(val)); } else { self.set_initial_position($(this)); } }); } }; }(jQuery, window, window.document));
CarolineHe/12-cheat-sheet-emmet
js/foundation/foundation.slider.js
JavaScript
apache-2.0
10,659
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( batchv1 "k8s.io/api/batch/v1" "k8s.io/apimachinery/pkg/runtime" ) func addDefaultingFuncs(scheme *runtime.Scheme) error { return RegisterDefaults(scheme) } func SetDefaults_Job(obj *batchv1.Job) { // For a non-parallel job, you can leave both `.spec.completions` and // `.spec.parallelism` unset. When both are unset, both are defaulted to 1. if obj.Spec.Completions == nil && obj.Spec.Parallelism == nil { obj.Spec.Completions = new(int32) *obj.Spec.Completions = 1 obj.Spec.Parallelism = new(int32) *obj.Spec.Parallelism = 1 } if obj.Spec.Parallelism == nil { obj.Spec.Parallelism = new(int32) *obj.Spec.Parallelism = 1 } if obj.Spec.BackoffLimit == nil { obj.Spec.BackoffLimit = new(int32) *obj.Spec.BackoffLimit = 6 } labels := obj.Spec.Template.Labels if labels != nil && len(obj.Labels) == 0 { obj.Labels = labels } }
erwinvaneyk/kubernetes
pkg/apis/batch/v1/defaults.go
GO
apache-2.0
1,451
package mount // import "github.com/docker/docker/pkg/mount" import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) func parseInfoFile(r io.Reader, filter FilterFunc) ([]*Info, error) { s := bufio.NewScanner(r) out := []*Info{} for s.Scan() { if err := s.Err(); err != nil { return nil, err } /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) (1) mount ID: unique identifier of the mount (may be reused after umount) (2) parent ID: ID of parent (or of self for the top of the mount tree) (3) major:minor: value of st_dev for files on filesystem (4) root: root of the mount within the filesystem (5) mount point: mount point relative to the process's root (6) mount options: per mount options (7) optional fields: zero or more fields of the form "tag[:value]" (8) separator: marks the end of the optional fields (9) filesystem type: name of filesystem of the form "type[.subtype]" (10) mount source: filesystem specific information or "none" (11) super options: per super block options */ text := s.Text() fields := strings.Split(text, " ") numFields := len(fields) if numFields < 10 { // should be at least 10 fields return nil, fmt.Errorf("Parsing '%s' failed: not enough fields (%d)", text, numFields) } p := &Info{} // ignore any numbers parsing errors, as there should not be any p.ID, _ = strconv.Atoi(fields[0]) p.Parent, _ = strconv.Atoi(fields[1]) mm := strings.Split(fields[2], ":") if len(mm) != 2 { return nil, fmt.Errorf("Parsing '%s' failed: unexpected minor:major pair %s", text, mm) } p.Major, _ = strconv.Atoi(mm[0]) p.Minor, _ = strconv.Atoi(mm[1]) p.Root = fields[3] p.Mountpoint = fields[4] p.Opts = fields[5] var skip, stop bool if filter != nil { // filter out entries we're not interested in skip, stop = filter(p) if skip { continue } } // one or more optional fields, when a separator (-) i := 6 for ; i < numFields && fields[i] != "-"; i++ { switch i { case 6: p.Optional = fields[6] default: /* NOTE there might be more optional fields before the such as fields[7]...fields[N] (where N < sepIndex), although as of Linux kernel 4.15 the only known ones are mount propagation flags in fields[6]. The correct behavior is to ignore any unknown optional fields. */ break } } if i == numFields { return nil, fmt.Errorf("Parsing '%s' failed: missing separator ('-')", text) } // There should be 3 fields after the separator... if i+4 > numFields { return nil, fmt.Errorf("Parsing '%s' failed: not enough fields after a separator", text) } // ... but in Linux <= 3.9 mounting a cifs with spaces in a share name // (like "//serv/My Documents") _may_ end up having a space in the last field // of mountinfo (like "unc=//serv/My Documents"). Since kernel 3.10-rc1, cifs // option unc= is ignored, so a space should not appear. In here we ignore // those "extra" fields caused by extra spaces. p.Fstype = fields[i+1] p.Source = fields[i+2] p.VfsOpts = fields[i+3] out = append(out, p) if stop { break } } return out, nil } // Parse /proc/self/mountinfo because comparing Dev and ino does not work from // bind mounts func parseMountTable(filter FilterFunc) ([]*Info, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } defer f.Close() return parseInfoFile(f, filter) } // PidMountInfo collects the mounts for a specific process ID. If the process // ID is unknown, it is better to use `GetMounts` which will inspect // "/proc/self/mountinfo" instead. func PidMountInfo(pid int) ([]*Info, error) { f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) if err != nil { return nil, err } defer f.Close() return parseInfoFile(f, nil) }
projectatomic/skopeo
vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go
GO
apache-2.0
3,982
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.common.config; import java.io.File; import java.io.IOException; import java.util.Map; import org.springframework.core.io.DefaultResourceLoader; import com.ckfinder.connector.ServletContextFactory; import com.google.common.collect.Maps; import com.thinkgem.jeesite.common.utils.PropertiesLoader; import com.thinkgem.jeesite.common.utils.StringUtils; /** * 全局配置类 * @author ThinkGem * @version 2014-06-25 */ public class Global { /** * 当前对象实例 */ private static Global global = new Global(); /** * 保存全局属性值 */ private static Map<String, String> map = Maps.newHashMap(); /** * 属性文件加载对象 */ private static PropertiesLoader loader = new PropertiesLoader("jeesite.properties"); /** * 显示/隐藏 */ public static final String SHOW = "1"; public static final String HIDE = "0"; /** * 是/否 */ public static final String YES = "1"; public static final String NO = "0"; /** * 对/错 */ public static final String TRUE = "true"; public static final String FALSE = "false"; /** * 上传文件基础虚拟路径 */ public static final String USERFILES_BASE_URL = "/userfiles/"; /** * 获取当前对象实例 */ public static Global getInstance() { return global; } /** * 获取配置 * @see ${fns:getConfig('adminPath')} */ public static String getConfig(String key) { String value = map.get(key); if (value == null){ value = loader.getProperty(key); map.put(key, value != null ? value : StringUtils.EMPTY); } return value; } /** * 获取管理端根路径 */ public static String getAdminPath() { return getConfig("adminPath"); } /** * 获取前端根路径 */ public static String getFrontPath() { return getConfig("frontPath"); } /** * 获取URL后缀 */ public static String getUrlSuffix() { return getConfig("urlSuffix"); } /** * 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权 */ public static Boolean isDemoMode() { String dm = getConfig("demoMode"); return "true".equals(dm) || "1".equals(dm); } /** * 在修改系统用户和角色时是否同步到Activiti */ public static Boolean isSynActivitiIndetity() { String dm = getConfig("activiti.isSynActivitiIndetity"); return "true".equals(dm) || "1".equals(dm); } /** * 页面获取常量 * @see ${fns:getConst('YES')} */ public static Object getConst(String field) { try { return Global.class.getField(field).get(null); } catch (Exception e) { // 异常代表无配置,这里什么也不做 } return null; } /** * 获取上传文件的根目录 * @return */ public static String getUserfilesBaseDir() { String dir = getConfig("userfiles.basedir"); if (StringUtils.isBlank(dir)){ try { dir = ServletContextFactory.getServletContext().getRealPath("/"); } catch (Exception e) { return ""; } } if(!dir.endsWith("/")) { dir += "/"; } // System.out.println("userfiles.basedir: " + dir); return dir; } /** * 获取工程路径 * @return */ public static String getProjectPath(){ // 如果配置了工程路径,则直接返回,否则自动获取。 String projectPath = Global.getConfig("projectPath"); if (StringUtils.isNotBlank(projectPath)){ return projectPath; } try { File file = new DefaultResourceLoader().getResource("").getFile(); if (file != null){ while(true){ File f = new File(file.getPath() + File.separator + "src" + File.separator + "main"); if (f == null || f.exists()){ break; } if (file.getParentFile() != null){ file = file.getParentFile(); }else{ break; } } projectPath = file.toString(); } } catch (IOException e) { e.printStackTrace(); } return projectPath; } }
gufengye/jeesite
src/main/java/com/thinkgem/jeesite/common/config/Global.java
Java
apache-2.0
4,030
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.spring.management; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @version */ public class SpringJmxRecipientListTest extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/management/SpringJmxRecipientListTest.xml"); } protected MBeanServer getMBeanServer() { return context.getManagementStrategy().getManagementAgent().getMBeanServer(); } public void testJmxEndpointsAddedDynamicallyDefaultRegister() throws Exception { MockEndpoint x = getMockEndpoint("mock:x"); MockEndpoint y = getMockEndpoint("mock:y"); MockEndpoint z = getMockEndpoint("mock:z"); x.expectedBodiesReceived("answer"); y.expectedBodiesReceived("answer"); z.expectedBodiesReceived("answer"); template.sendBodyAndHeader("direct:a", "answer", "recipientListHeader", "mock:x,mock:y,mock:z"); assertMockEndpointsSatisfied(); MBeanServer mbeanServer = getMBeanServer(); // this endpoint is part of the route and should be registered ObjectName name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"direct://a\""); assertTrue("Should be registered", mbeanServer.isRegistered(name)); // endpoints added after routes has been started is by default not registered name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://x\""); assertFalse("Should not be registered", mbeanServer.isRegistered(name)); name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://y\""); assertFalse("Should not be registered", mbeanServer.isRegistered(name)); name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://z\""); assertFalse("Should not be registered", mbeanServer.isRegistered(name)); // however components is always registered name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=components,name=\"mock\""); assertTrue("Should be registered", mbeanServer.isRegistered(name)); } }
gyc567/camel
components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringJmxRecipientListTest.java
Java
apache-2.0
3,359
.hll { background-color: #ffc; } .c { color: #999; } /* Comment */ .err { color: #a00; background-color: #faa } /* Error */ .k { color: #069; } /* Keyword */ .o { color: #555 } /* Operator */ .cm { color: #09f; font-style: italic } /* Comment.Multiline */ .cp { color: #099 } /* Comment.Preproc */ .c1 { color: #999; } /* Comment.Single */ .cs { color: #999; } /* Comment.Special */ .gd { background-color: #fcc; border: 1px solid #c00 } /* Generic.Deleted */ .ge { font-style: italic } /* Generic.Emph */ .gr { color: #f00 } /* Generic.Error */ .gh { color: #030; } /* Generic.Heading */ .gi { background-color: #cfc; border: 1px solid #0c0 } /* Generic.Inserted */ .go { color: #aaa } /* Generic.Output */ .gp { color: #009; } /* Generic.Prompt */ .gs { } /* Generic.Strong */ .gu { color: #030; } /* Generic.Subheading */ .gt { color: #9c6 } /* Generic.Traceback */ .kc { color: #069; } /* Keyword.Constant */ .kd { color: #069; } /* Keyword.Declaration */ .kn { color: #069; } /* Keyword.Namespace */ .kp { color: #069 } /* Keyword.Pseudo */ .kr { color: #069; } /* Keyword.Reserved */ .kt { color: #078; } /* Keyword.Type */ .m { color: #f60 } /* Literal.Number */ .s { color: #d44950 } /* Literal.String */ .na { color: #4f9fcf } /* Name.Attribute */ .nb { color: #366 } /* Name.Builtin */ .nc { color: #0a8; } /* Name.Class */ .no { color: #360 } /* Name.Constant */ .nd { color: #99f } /* Name.Decorator */ .ni { color: #999; } /* Name.Entity */ .ne { color: #c00; } /* Name.Exception */ .nf { color: #c0f } /* Name.Function */ .nl { color: #99f } /* Name.Label */ .nn { color: #0cf; } /* Name.Namespace */ .nt { color: #2f6f9f; } /* Name.Tag */ .nv { color: #033 } /* Name.Variable */ .ow { color: #000; } /* Operator.Word */ .w { color: #bbb } /* Text.Whitespace */ .mf { color: #f60 } /* Literal.Number.Float */ .mh { color: #f60 } /* Literal.Number.Hex */ .mi { color: #f60 } /* Literal.Number.Integer */ .mo { color: #f60 } /* Literal.Number.Oct */ .sb { color: #c30 } /* Literal.String.Backtick */ .sc { color: #c30 } /* Literal.String.Char */ .sd { color: #c30; font-style: italic } /* Literal.String.Doc */ .s2 { color: #c30 } /* Literal.String.Double */ .se { color: #c30; } /* Literal.String.Escape */ .sh { color: #c30 } /* Literal.String.Heredoc */ .si { color: #a00 } /* Literal.String.Interpol */ .sx { color: #c30 } /* Literal.String.Other */ .sr { color: #3aa } /* Literal.String.Regex */ .s1 { color: #c30 } /* Literal.String.Single */ .ss { color: #fc3 } /* Literal.String.Symbol */ .bp { color: #366 } /* Name.Builtin.Pseudo */ .vc { color: #033 } /* Name.Variable.Class */ .vg { color: #033 } /* Name.Variable.Global */ .vi { color: #033 } /* Name.Variable.Instance */ .il { color: #f60 } /* Literal.Number.Integer.Long */ .css .o, .css .o + .nt, .css .nt + .nt { color: #999; }
blokadaorg/blokadaorg.github.io
api/v4/content_dns/ja_JP/css/syntax.css
CSS
apache-2.0
2,808
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // CrossVersionObjectReference contains enough information to let you identify the referred resource. type CrossVersionObjectReference struct { // Kind of the referent; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds" Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` // Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // API version of the referent // +optional APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,3,opt,name=apiVersion"` } // specification of a horizontal pod autoscaler. type HorizontalPodAutoscalerSpec struct { // reference to scaled resource; horizontal pod autoscaler will learn the current resource consumption // and will set the desired number of pods by using its Scale subresource. ScaleTargetRef CrossVersionObjectReference `json:"scaleTargetRef" protobuf:"bytes,1,opt,name=scaleTargetRef"` // lower limit for the number of pods that can be set by the autoscaler, default 1. // +optional MinReplicas *int32 `json:"minReplicas,omitempty" protobuf:"varint,2,opt,name=minReplicas"` // upper limit for the number of pods that can be set by the autoscaler; cannot be smaller than MinReplicas. MaxReplicas int32 `json:"maxReplicas" protobuf:"varint,3,opt,name=maxReplicas"` // target average CPU utilization (represented as a percentage of requested CPU) over all the pods; // if not specified the default autoscaling policy will be used. // +optional TargetCPUUtilizationPercentage *int32 `json:"targetCPUUtilizationPercentage,omitempty" protobuf:"varint,4,opt,name=targetCPUUtilizationPercentage"` } // current status of a horizontal pod autoscaler type HorizontalPodAutoscalerStatus struct { // most recent generation observed by this autoscaler. // +optional ObservedGeneration *int64 `json:"observedGeneration,omitempty" protobuf:"varint,1,opt,name=observedGeneration"` // last time the HorizontalPodAutoscaler scaled the number of pods; // used by the autoscaler to control how often the number of pods is changed. // +optional LastScaleTime *metav1.Time `json:"lastScaleTime,omitempty" protobuf:"bytes,2,opt,name=lastScaleTime"` // current number of replicas of pods managed by this autoscaler. CurrentReplicas int32 `json:"currentReplicas" protobuf:"varint,3,opt,name=currentReplicas"` // desired number of replicas of pods managed by this autoscaler. DesiredReplicas int32 `json:"desiredReplicas" protobuf:"varint,4,opt,name=desiredReplicas"` // current average CPU utilization over all pods, represented as a percentage of requested CPU, // e.g. 70 means that an average pod is using now 70% of its requested CPU. // +optional CurrentCPUUtilizationPercentage *int32 `json:"currentCPUUtilizationPercentage,omitempty" protobuf:"varint,5,opt,name=currentCPUUtilizationPercentage"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // configuration of a horizontal pod autoscaler. type HorizontalPodAutoscaler struct { metav1.TypeMeta `json:",inline"` // Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // behaviour of autoscaler. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. // +optional Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // current information about the autoscaler. // +optional Status HorizontalPodAutoscalerStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // list of horizontal pod autoscaler objects. type HorizontalPodAutoscalerList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata. // +optional metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // list of horizontal pod autoscaler objects. Items []HorizontalPodAutoscaler `json:"items" protobuf:"bytes,2,rep,name=items"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // Scale represents a scaling request for a resource. type Scale struct { metav1.TypeMeta `json:",inline"` // Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata. // +optional metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. // +optional Spec ScaleSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // current status of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. Read-only. // +optional Status ScaleStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // ScaleSpec describes the attributes of a scale subresource. type ScaleSpec struct { // desired number of instances for the scaled object. // +optional Replicas int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` } // ScaleStatus represents the current status of a scale subresource. type ScaleStatus struct { // actual number of observed instances of the scaled object. Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // label query over pods that should match the replicas count. This is same // as the label selector but in the string format to avoid introspection // by clients. The string will be in the same format as the query-param syntax. // More info about label selectors: http://kubernetes.io/docs/user-guide/labels#label-selectors // +optional Selector string `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` } // the types below are used in the alpha metrics annotation // MetricSourceType indicates the type of metric. type MetricSourceType string var ( // ObjectMetricSourceType is a metric describing a kubernetes object // (for example, hits-per-second on an Ingress object). ObjectMetricSourceType MetricSourceType = "Object" // PodsMetricSourceType is a metric describing each pod in the current scale // target (for example, transactions-processed-per-second). The values // will be averaged together before being compared to the target value. PodsMetricSourceType MetricSourceType = "Pods" // ResourceMetricSourceType is a resource metric known to Kubernetes, as // specified in requests and limits, describing each pod in the current // scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available // to normal per-pod metrics (the "pods" source). ResourceMetricSourceType MetricSourceType = "Resource" ) // MetricSpec specifies how to scale based on a single metric // (only `type` and one other matching field should be set at once). type MetricSpec struct { // type is the type of metric source. It should match one of the fields below. Type MetricSourceType `json:"type" protobuf:"bytes,1,name=type"` // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional Object *ObjectMetricSource `json:"object,omitempty" protobuf:"bytes,2,opt,name=object"` // pods refers to a metric describing each pod in the current scale target // (for example, transactions-processed-per-second). The values will be // averaged together before being compared to the target value. // +optional Pods *PodsMetricSource `json:"pods,omitempty" protobuf:"bytes,3,opt,name=pods"` // resource refers to a resource metric (such as those specified in // requests and limits) known to Kubernetes describing each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available // to normal per-pod metrics using the "pods" source. // +optional Resource *ResourceMetricSource `json:"resource,omitempty" protobuf:"bytes,4,opt,name=resource"` } // ObjectMetricSource indicates how to scale on a metric describing a // kubernetes object (for example, hits-per-second on an Ingress object). type ObjectMetricSource struct { // target is the described Kubernetes object. Target CrossVersionObjectReference `json:"target" protobuf:"bytes,1,name=target"` // metricName is the name of the metric in question. MetricName string `json:"metricName" protobuf:"bytes,2,name=metricName"` // targetValue is the target value of the metric (as a quantity). TargetValue resource.Quantity `json:"targetValue" protobuf:"bytes,3,name=targetValue"` } // PodsMetricSource indicates how to scale on a metric describing each pod in // the current scale target (for example, transactions-processed-per-second). // The values will be averaged together before being compared to the target // value. type PodsMetricSource struct { // metricName is the name of the metric in question MetricName string `json:"metricName" protobuf:"bytes,1,name=metricName"` // targetAverageValue is the target value of the average of the // metric across all relevant pods (as a quantity) TargetAverageValue resource.Quantity `json:"targetAverageValue" protobuf:"bytes,2,name=targetAverageValue"` } // ResourceMetricSource indicates how to scale on a resource metric known to // Kubernetes, as specified in requests and limits, describing each pod in the // current scale target (e.g. CPU or memory). The values will be averaged // together before being compared to the target. Such metrics are built in to // Kubernetes, and have special scaling options on top of those available to // normal per-pod metrics using the "pods" source. Only one "target" type // should be set. type ResourceMetricSource struct { // name is the name of the resource in question. Name v1.ResourceName `json:"name" protobuf:"bytes,1,name=name"` // targetAverageUtilization is the target value of the average of the // resource metric across all relevant pods, represented as a percentage of // the requested value of the resource for the pods. // +optional TargetAverageUtilization *int32 `json:"targetAverageUtilization,omitempty" protobuf:"varint,2,opt,name=targetAverageUtilization"` // targetAverageValue is the target value of the average of the // resource metric across all relevant pods, as a raw value (instead of as // a percentage of the request), similar to the "pods" metric source type. // +optional TargetAverageValue *resource.Quantity `json:"targetAverageValue,omitempty" protobuf:"bytes,3,opt,name=targetAverageValue"` } // MetricStatus describes the last-read state of a single metric. type MetricStatus struct { // type is the type of metric source. It will match one of the fields below. Type MetricSourceType `json:"type" protobuf:"bytes,1,name=type"` // object refers to a metric describing a single kubernetes object // (for example, hits-per-second on an Ingress object). // +optional Object *ObjectMetricStatus `json:"object,omitempty" protobuf:"bytes,2,opt,name=object"` // pods refers to a metric describing each pod in the current scale target // (for example, transactions-processed-per-second). The values will be // averaged together before being compared to the target value. // +optional Pods *PodsMetricStatus `json:"pods,omitempty" protobuf:"bytes,3,opt,name=pods"` // resource refers to a resource metric (such as those specified in // requests and limits) known to Kubernetes describing each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available // to normal per-pod metrics using the "pods" source. // +optional Resource *ResourceMetricStatus `json:"resource,omitempty" protobuf:"bytes,4,opt,name=resource"` } // HorizontalPodAutoscalerConditionType are the valid conditions of // a HorizontalPodAutoscaler. type HorizontalPodAutoscalerConditionType string var ( // ScalingActive indicates that the HPA controller is able to scale if necessary: // it's correctly configured, can fetch the desired metrics, and isn't disabled. ScalingActive HorizontalPodAutoscalerConditionType = "ScalingActive" // AbleToScale indicates a lack of transient issues which prevent scaling from occuring, // such as being in a backoff window, or being unable to access/update the target scale. AbleToScale HorizontalPodAutoscalerConditionType = "AbleToScale" // ScalingLimited indicates that the calculated scale based on metrics would be above or // below the range for the HPA, and has thus been capped. ScalingLimited HorizontalPodAutoscalerConditionType = "ScalingLimited" ) // HorizontalPodAutoscalerCondition describes the state of // a HorizontalPodAutoscaler at a certain point. type HorizontalPodAutoscalerCondition struct { // type describes the current condition Type HorizontalPodAutoscalerConditionType `json:"type" protobuf:"bytes,1,name=type"` // status is the status of the condition (True, False, Unknown) Status v1.ConditionStatus `json:"status" protobuf:"bytes,2,name=status"` // lastTransitionTime is the last time the condition transitioned from // one status to another // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" protobuf:"bytes,3,opt,name=lastTransitionTime"` // reason is the reason for the condition's last transition. // +optional Reason string `json:"reason,omitempty" protobuf:"bytes,4,opt,name=reason"` // message is a human-readable explanation containing details about // the transition // +optional Message string `json:"message,omitempty" protobuf:"bytes,5,opt,name=message"` } // ObjectMetricStatus indicates the current value of a metric describing a // kubernetes object (for example, hits-per-second on an Ingress object). type ObjectMetricStatus struct { // target is the described Kubernetes object. Target CrossVersionObjectReference `json:"target" protobuf:"bytes,1,name=target"` // metricName is the name of the metric in question. MetricName string `json:"metricName" protobuf:"bytes,2,name=metricName"` // currentValue is the current value of the metric (as a quantity). CurrentValue resource.Quantity `json:"currentValue" protobuf:"bytes,3,name=currentValue"` } // PodsMetricStatus indicates the current value of a metric describing each pod in // the current scale target (for example, transactions-processed-per-second). type PodsMetricStatus struct { // metricName is the name of the metric in question MetricName string `json:"metricName" protobuf:"bytes,1,name=metricName"` // currentAverageValue is the current value of the average of the // metric across all relevant pods (as a quantity) CurrentAverageValue resource.Quantity `json:"currentAverageValue" protobuf:"bytes,2,name=currentAverageValue"` } // ResourceMetricStatus indicates the current value of a resource metric known to // Kubernetes, as specified in requests and limits, describing each pod in the // current scale target (e.g. CPU or memory). Such metrics are built in to // Kubernetes, and have special scaling options on top of those available to // normal per-pod metrics using the "pods" source. type ResourceMetricStatus struct { // name is the name of the resource in question. Name v1.ResourceName `json:"name" protobuf:"bytes,1,name=name"` // currentAverageUtilization is the current value of the average of the // resource metric across all relevant pods, represented as a percentage of // the requested value of the resource for the pods. It will only be // present if `targetAverageValue` was set in the corresponding metric // specification. // +optional CurrentAverageUtilization *int32 `json:"currentAverageUtilization,omitempty" protobuf:"bytes,2,opt,name=currentAverageUtilization"` // currentAverageValue is the current value of the average of the // resource metric across all relevant pods, as a raw value (instead of as // a percentage of the request), similar to the "pods" metric source type. // It will always be set, regardless of the corresponding metric specification. CurrentAverageValue resource.Quantity `json:"currentAverageValue" protobuf:"bytes,3,name=currentAverageValue"` }
sdemos/container-linux-update-operator
vendor/k8s.io/api/autoscaling/v1/types.go
GO
apache-2.0
17,127
* html{ /* background-image:url(about:blank);*/ background-attachment:fixed; } html pre {word-wrap: break-word} .header {background-image: none;background-color: #F0F6E4;} .ieSuggest {display:block;} .shortcuts button.cn {filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='apiCss/img/chinese.png');background-image: none;} .shortcuts button.en {filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='apiCss/img/english.png');background-image: none;} .light-bulb {filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='apiCss/img/lightbulb.png');background-image: none;} .contentBox {background-image: none;background-color: #F0F6E4;} .zTreeInfo {background-image: none;background-color: #F0F6E4;} .content button.ico16 {*background-image:url("img/apiMenu.gif")} .siteTag {background-image: none;} .apiContent .right {float: right;padding-right: 50px;} div.baby_overlay {background-color: #3C6E31;background-image:none;color:#fff;} div.baby_overlay .close {filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='apiCss/img/overlay_close_IE6.gif');background-image: none;} .baby_overlay_arrow {background-image:url(img/overlay_arrow.gif);} .apiDetail button {background-image:url("img/zTreeStandard.gif")}
ljx2014/webplus
src/main/webapp/static/jquery-ztree/3.5.12/api/apiCss/common_ie6.css
CSS
apache-2.0
1,248
/* Copyright (C) 2008 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xA0]+/,null,"\t\n\r \u00a0"],["com",/^#(?:if[\t\n\r \xA0]+(?:[a-z_$][\w\']*|``[^\r\n\t`]*(?:``|$))|else|endif|light)/i,null,"#"],["str",/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])(?:\'|$))/,null,"\"'"]],[["com",/^(?:\/\/[^\r\n]*|\(\*[\s\S]*?\*\))/],["kwd",/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/], ["lit",/^[+\-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],["pln",/^(?:[a-z_][\w']*[!?#]?|``[^\r\n\t`]*(?:``|$))/i],["pun",/^[^\t\n\r \xA0\"\'\w]+/]]),["fs","ml"]);
loftuxab/media-viewers
media-viewers-share/src/main/amp/web/extras/modules/prettify/lang-ml.js
JavaScript
apache-2.0
1,693
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "net" "runtime" "syscall" "time" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var _ net.PacketConn = &PacketConn{} // A PacketConn represents a packet network endpoint that uses either // ICMPv4 or ICMPv6. type PacketConn struct { c net.PacketConn p4 *ipv4.PacketConn p6 *ipv6.PacketConn } func (c *PacketConn) ok() bool { return c != nil && c.c != nil } // IPv4PacketConn returns the ipv4.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv4. func (c *PacketConn) IPv4PacketConn() *ipv4.PacketConn { if !c.ok() { return nil } return c.p4 } // IPv6PacketConn returns the ipv6.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv6. func (c *PacketConn) IPv6PacketConn() *ipv6.PacketConn { if !c.ok() { return nil } return c.p6 } // ReadFrom reads an ICMP message from the connection. func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) { if !c.ok() { return 0, nil, syscall.EINVAL } // Please be informed that ipv4.NewPacketConn enables // IP_STRIPHDR option by default on Darwin. // See golang.org/issue/9395 for futher information. if runtime.GOOS == "darwin" && c.p4 != nil { n, _, peer, err := c.p4.ReadFrom(b) return n, peer, err } return c.c.ReadFrom(b) } // WriteTo writes the ICMP message b to dst. // Dst must be net.UDPAddr when c is a non-privileged // datagram-oriented ICMP endpoint. Otherwise it must be net.IPAddr. func (c *PacketConn) WriteTo(b []byte, dst net.Addr) (int, error) { if !c.ok() { return 0, syscall.EINVAL } return c.c.WriteTo(b, dst) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.ok() { return syscall.EINVAL } return c.c.Close() } // LocalAddr returns the local network address. func (c *PacketConn) LocalAddr() net.Addr { if !c.ok() { return nil } return c.c.LocalAddr() } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetWriteDeadline(t) }
four43/coreos-kubernetes
multi-node/aws/vendor/golang.org/x/net/icmp/endpoint.go
GO
apache-2.0
2,680
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerDynamicEditException; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.QueueEntitlement; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.Before; import org.junit.Test; public class TestReservationQueue { CapacitySchedulerConfiguration csConf; CapacitySchedulerContext csContext; final static int DEF_MAX_APPS = 10000; final static int GB = 1024; private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator(); ReservationQueue reservationQueue; @Before public void setup() throws IOException { // setup a context / conf csConf = new CapacitySchedulerConfiguration(); YarnConfiguration conf = new YarnConfiguration(); csContext = mock(CapacitySchedulerContext.class); when(csContext.getConfiguration()).thenReturn(csConf); when(csContext.getConf()).thenReturn(conf); when(csContext.getMinimumResourceCapability()).thenReturn( Resources.createResource(GB, 1)); when(csContext.getMaximumResourceCapability()).thenReturn( Resources.createResource(16 * GB, 32)); when(csContext.getClusterResource()).thenReturn( Resources.createResource(100 * 16 * GB, 100 * 32)); when(csContext.getResourceCalculator()).thenReturn(resourceCalculator); RMContext mockRMContext = TestUtils.getMockRMContext(); when(csContext.getRMContext()).thenReturn(mockRMContext); // create a queue PlanQueue pq = new PlanQueue(csContext, "root", null, null); reservationQueue = new ReservationQueue(csContext, "a", pq); } private void validateReservationQueue(double capacity) { assertTrue(" actual capacity: " + reservationQueue.getCapacity(), reservationQueue.getCapacity() - capacity < CSQueueUtils.EPSILON); assertEquals(reservationQueue.maxApplications, DEF_MAX_APPS); assertEquals(reservationQueue.maxApplicationsPerUser, DEF_MAX_APPS); } @Test public void testAddSubtractCapacity() throws Exception { // verify that setting, adding, subtracting capacity works reservationQueue.setCapacity(1.0F); validateReservationQueue(1); reservationQueue.setEntitlement(new QueueEntitlement(0.9f, 1f)); validateReservationQueue(0.9); reservationQueue.setEntitlement(new QueueEntitlement(1f, 1f)); validateReservationQueue(1); reservationQueue.setEntitlement(new QueueEntitlement(0f, 1f)); validateReservationQueue(0); try { reservationQueue.setEntitlement(new QueueEntitlement(1.1f, 1f)); fail(); } catch (SchedulerDynamicEditException iae) { // expected validateReservationQueue(1); } try { reservationQueue.setEntitlement(new QueueEntitlement(-0.1f, 1f)); fail(); } catch (SchedulerDynamicEditException iae) { // expected validateReservationQueue(1); } } }
venkateshu/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservationQueue.java
Java
apache-2.0
4,290
<?php /** * Database Repair and Optimization Script. * * @package WordPress * @subpackage Database */ define('WP_REPAIRING', true); require_once( dirname( dirname( dirname( __FILE__ ) ) ) . '/wp-load.php' ); header( 'Content-Type: text/html; charset=utf-8' ); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex,nofollow" /> <title><?php _e( 'WordPress &rsaquo; Database Repair' ); ?></title> <?php wp_admin_css( 'install', true ); ?> </head> <body class="wp-core-ui"> <p id="logo"><a href="<?php echo esc_url( __( 'https://wordpress.org/' ) ); ?>" tabindex="-1"><?php _e( 'WordPress' ); ?></a></p> <?php if ( ! defined( 'WP_ALLOW_REPAIR' ) ) { echo '<h1 class="screen-reader-text">' . __( 'Allow automatic database repair' ) . '</h1>'; echo '<p>' . __( 'To allow use of this page to automatically repair database problems, please add the following line to your <code>wp-config.php</code> file. Once this line is added to your config, reload this page.' ) . "</p><p><code>define('WP_ALLOW_REPAIR', true);</code></p>"; $default_key = 'put your unique phrase here'; $missing_key = false; $duplicated_keys = array(); foreach ( array( 'AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY', 'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT' ) as $key ) { if ( defined( $key ) ) { // Check for unique values of each key. $duplicated_keys[ constant( $key ) ] = isset( $duplicated_keys[ constant( $key ) ] ); } else { // If a constant is not defined, it's missing. $missing_key = true; } } // If at least one key uses the default value, consider it duplicated. if ( isset( $duplicated_keys[ $default_key ] ) ) { $duplicated_keys[ $default_key ] = true; } // Weed out all unique, non-default values. $duplicated_keys = array_filter( $duplicated_keys ); if ( $duplicated_keys || $missing_key ) { echo '<h2 class="screen-reader-text">' . __( 'Check secret keys' ) . '</h2>'; // Translators: 1: wp-config.php; 2: Secret key service URL. echo '<p>' . sprintf( __( 'While you are editing your %1$s file, take a moment to make sure you have all 8 keys and that they are unique. You can generate these using the <a href="%2$s">WordPress.org secret key service</a>.' ), '<code>wp-config.php</code>', 'https://api.wordpress.org/secret-key/1.1/salt/' ) . '</p>'; } } elseif ( isset( $_GET['repair'] ) ) { echo '<h1 class="screen-reader-text">' . __( 'Database repair results' ) . '</h1>'; $optimize = 2 == $_GET['repair']; $okay = true; $problems = array(); $tables = $wpdb->tables(); // Sitecategories may not exist if global terms are disabled. $query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $wpdb->sitecategories ) ); if ( is_multisite() && ! $wpdb->get_var( $query ) ) { unset( $tables['sitecategories'] ); } /** * Filter additional database tables to repair. * * @since 3.0.0 * * @param array $tables Array of prefixed table names to be repaired. */ $tables = array_merge( $tables, (array) apply_filters( 'tables_to_repair', array() ) ); // Loop over the tables, checking and repairing as needed. foreach ( $tables as $table ) { $check = $wpdb->get_row( "CHECK TABLE $table" ); echo '<p>'; if ( 'OK' == $check->Msg_text ) { /* translators: %s: table name */ printf( __( 'The %s table is okay.' ), "<code>$table</code>" ); } else { /* translators: 1: table name, 2: error message, */ printf( __( 'The %1$s table is not okay. It is reporting the following error: %2$s. WordPress will attempt to repair this table&hellip;' ) , "<code>$table</code>", "<code>$check->Msg_text</code>" ); $repair = $wpdb->get_row( "REPAIR TABLE $table" ); echo '<br />&nbsp;&nbsp;&nbsp;&nbsp;'; if ( 'OK' == $check->Msg_text ) { /* translators: %s: table name */ printf( __( 'Successfully repaired the %s table.' ), "<code>$table</code>" ); } else { /* translators: 1: table name, 2: error message, */ echo sprintf( __( 'Failed to repair the %1$s table. Error: %2$s' ), "<code>$table</code>", "<code>$check->Msg_text</code>" ) . '<br />'; $problems[$table] = $check->Msg_text; $okay = false; } } if ( $okay && $optimize ) { $check = $wpdb->get_row( "ANALYZE TABLE $table" ); echo '<br />&nbsp;&nbsp;&nbsp;&nbsp;'; if ( 'Table is already up to date' == $check->Msg_text ) { /* translators: %s: table name */ printf( __( 'The %s table is already optimized.' ), "<code>$table</code>" ); } else { $check = $wpdb->get_row( "OPTIMIZE TABLE $table" ); echo '<br />&nbsp;&nbsp;&nbsp;&nbsp;'; if ( 'OK' == $check->Msg_text || 'Table is already up to date' == $check->Msg_text ) { /* translators: %s: table name */ printf( __( 'Successfully optimized the %s table.' ), "<code>$table</code>" ); } else { /* translators: 1: table name, 2: error message, */ printf( __( 'Failed to optimize the %1$s table. Error: %2$s' ), "<code>$table</code>", "<code>$check->Msg_text</code>" ); } } } echo '</p>'; } if ( $problems ) { printf( '<p>' . __('Some database problems could not be repaired. Please copy-and-paste the following list of errors to the <a href="%s">WordPress support forums</a> to get additional assistance.') . '</p>', __( 'https://wordpress.org/support/forum/how-to-and-troubleshooting' ) ); $problem_output = ''; foreach ( $problems as $table => $problem ) $problem_output .= "$table: $problem\n"; echo '<p><textarea name="errors" id="errors" rows="20" cols="60">' . esc_textarea( $problem_output ) . '</textarea></p>'; } else { echo '<p>' . __( 'Repairs complete. Please remove the following line from wp-config.php to prevent this page from being used by unauthorized users.' ) . "</p><p><code>define('WP_ALLOW_REPAIR', true);</code></p>"; } } else { echo '<h1 class="screen-reader-text">' . __( 'WordPress database repair' ) . '</h1>'; if ( isset( $_GET['referrer'] ) && 'is_blog_installed' == $_GET['referrer'] ) echo '<p>' . __( 'One or more database tables are unavailable. To allow WordPress to attempt to repair these tables, press the &#8220;Repair Database&#8221; button. Repairing can take a while, so please be patient.' ) . '</p>'; else echo '<p>' . __( 'WordPress can automatically look for some common database problems and repair them. Repairing can take a while, so please be patient.' ) . '</p>'; ?> <p class="step"><a class="button button-large" href="repair.php?repair=1"><?php _e( 'Repair Database' ); ?></a></p> <p><?php _e( 'WordPress can also attempt to optimize the database. This improves performance in some situations. Repairing and optimizing the database can take a long time and the database will be locked while optimizing.' ); ?></p> <p class="step"><a class="button button-large" href="repair.php?repair=2"><?php _e( 'Repair and Optimize Database' ); ?></a></p> <?php } ?> </body> </html>
ZloVolk/TQ
vinehurst.com/wp-admin/maint/repair.php
PHP
apache-2.0
7,107
/* ----------------------------------------------------------------------- java_raw_api.c - Copyright (c) 1999, 2007, 2008 Red Hat, Inc. Cloned from raw_api.c Raw_api.c author: Kresten Krab Thorup <krab@gnu.org> Java_raw_api.c author: Hans-J. Boehm <hboehm@hpl.hp.com> $Id $ 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. ----------------------------------------------------------------------- */ /* This defines a Java- and 64-bit specific variant of the raw API. */ /* It assumes that "raw" argument blocks look like Java stacks on a */ /* 64-bit machine. Arguments that can be stored in a single stack */ /* stack slots (longs, doubles) occupy 128 bits, but only the first */ /* 64 bits are actually used. */ #include <ffi.h> #include <ffi_common.h> #include <stdlib.h> #if !defined(NO_JAVA_RAW_API) && !defined(FFI_NO_RAW_API) size_t ffi_java_raw_size (ffi_cif *cif) { size_t result = 0; int i; ffi_type **at = cif->arg_types; for (i = cif->nargs-1; i >= 0; i--, at++) { switch((*at) -> type) { case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: result += 2 * FFI_SIZEOF_JAVA_RAW; break; case FFI_TYPE_STRUCT: /* No structure parameters in Java. */ abort(); default: result += FFI_SIZEOF_JAVA_RAW; } } return result; } void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args) { unsigned i; ffi_type **tp = cif->arg_types; #if WORDS_BIGENDIAN for (i = 0; i < cif->nargs; i++, tp++, args++) { switch ((*tp)->type) { case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: *args = (void*) ((char*)(raw++) + 3); break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: *args = (void*) ((char*)(raw++) + 2); break; #if FFI_SIZEOF_JAVA_RAW == 8 case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: *args = (void *)raw; raw += 2; break; #endif case FFI_TYPE_POINTER: *args = (void*) &(raw++)->ptr; break; default: *args = raw; raw += ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); } } #else /* WORDS_BIGENDIAN */ #if !PDP /* then assume little endian */ for (i = 0; i < cif->nargs; i++, tp++, args++) { #if FFI_SIZEOF_JAVA_RAW == 8 switch((*tp)->type) { case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: *args = (void*) raw; raw += 2; break; default: *args = (void*) raw++; } #else /* FFI_SIZEOF_JAVA_RAW != 8 */ *args = (void*) raw; raw += ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); #endif /* FFI_SIZEOF_JAVA_RAW == 8 */ } #else #error "pdp endian not supported" #endif /* ! PDP */ #endif /* WORDS_BIGENDIAN */ } void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw) { unsigned i; ffi_type **tp = cif->arg_types; for (i = 0; i < cif->nargs; i++, tp++, args++) { switch ((*tp)->type) { case FFI_TYPE_UINT8: #if WORDS_BIGENDIAN *(UINT32*)(raw++) = *(UINT8*) (*args); #else (raw++)->uint = *(UINT8*) (*args); #endif break; case FFI_TYPE_SINT8: #if WORDS_BIGENDIAN *(SINT32*)(raw++) = *(SINT8*) (*args); #else (raw++)->sint = *(SINT8*) (*args); #endif break; case FFI_TYPE_UINT16: #if WORDS_BIGENDIAN *(UINT32*)(raw++) = *(UINT16*) (*args); #else (raw++)->uint = *(UINT16*) (*args); #endif break; case FFI_TYPE_SINT16: #if WORDS_BIGENDIAN *(SINT32*)(raw++) = *(SINT16*) (*args); #else (raw++)->sint = *(SINT16*) (*args); #endif break; case FFI_TYPE_UINT32: #if WORDS_BIGENDIAN *(UINT32*)(raw++) = *(UINT32*) (*args); #else (raw++)->uint = *(UINT32*) (*args); #endif break; case FFI_TYPE_SINT32: #if WORDS_BIGENDIAN *(SINT32*)(raw++) = *(SINT32*) (*args); #else (raw++)->sint = *(SINT32*) (*args); #endif break; case FFI_TYPE_FLOAT: (raw++)->flt = *(FLOAT32*) (*args); break; #if FFI_SIZEOF_JAVA_RAW == 8 case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: raw->uint = *(UINT64*) (*args); raw += 2; break; #endif case FFI_TYPE_POINTER: (raw++)->ptr = **(void***) args; break; default: #if FFI_SIZEOF_JAVA_RAW == 8 FFI_ASSERT(0); /* Should have covered all cases */ #else memcpy ((void*) raw->data, (void*)*args, (*tp)->size); raw += ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw); #endif } } } #if !FFI_NATIVE_RAW_API static void ffi_java_rvalue_to_raw (ffi_cif *cif, void *rvalue) { #if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8 switch (cif->rtype->type) { case FFI_TYPE_UINT8: case FFI_TYPE_UINT16: case FFI_TYPE_UINT32: *(UINT64 *)rvalue <<= 32; break; case FFI_TYPE_SINT8: case FFI_TYPE_SINT16: case FFI_TYPE_SINT32: case FFI_TYPE_INT: #if FFI_SIZEOF_JAVA_RAW == 4 case FFI_TYPE_POINTER: #endif *(SINT64 *)rvalue <<= 32; break; default: break; } #endif } static void ffi_java_raw_to_rvalue (ffi_cif *cif, void *rvalue) { #if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8 switch (cif->rtype->type) { case FFI_TYPE_UINT8: case FFI_TYPE_UINT16: case FFI_TYPE_UINT32: *(UINT64 *)rvalue >>= 32; break; case FFI_TYPE_SINT8: case FFI_TYPE_SINT16: case FFI_TYPE_SINT32: case FFI_TYPE_INT: #if FFI_SIZEOF_JAVA_RAW == 4 case FFI_TYPE_POINTER: #endif *(SINT64 *)rvalue >>= 32; break; default: break; } #endif } /* This is a generic definition of ffi_raw_call, to be used if the * native system does not provide a machine-specific implementation. * Having this, allows code to be written for the raw API, without * the need for system-specific code to handle input in that format; * these following couple of functions will handle the translation forth * and back automatically. */ void ffi_java_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_java_raw *raw) { void **avalue = (void**) alloca (cif->nargs * sizeof (void*)); ffi_java_raw_to_ptrarray (cif, raw, avalue); ffi_call (cif, fn, rvalue, avalue); ffi_java_rvalue_to_raw (cif, rvalue); } #if FFI_CLOSURES /* base system provides closures */ static void ffi_java_translate_args (ffi_cif *cif, void *rvalue, void **avalue, void *user_data) { ffi_java_raw *raw = (ffi_java_raw*)alloca (ffi_java_raw_size (cif)); ffi_raw_closure *cl = (ffi_raw_closure*)user_data; ffi_java_ptrarray_to_raw (cif, avalue, raw); (*cl->fun) (cif, rvalue, raw, cl->user_data); ffi_java_raw_to_rvalue (cif, rvalue); } ffi_status ffi_prep_java_raw_closure_loc (ffi_java_raw_closure* cl, ffi_cif *cif, void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data, void *codeloc) { ffi_status status; status = ffi_prep_closure_loc ((ffi_closure*) cl, cif, &ffi_java_translate_args, codeloc, codeloc); if (status == FFI_OK) { cl->fun = fun; cl->user_data = user_data; } return status; } /* Again, here is the generic version of ffi_prep_raw_closure, which * will install an intermediate "hub" for translation of arguments from * the pointer-array format, to the raw format */ ffi_status ffi_prep_java_raw_closure (ffi_java_raw_closure* cl, ffi_cif *cif, void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data) { return ffi_prep_java_raw_closure_loc (cl, cif, fun, user_data, cl); } #endif /* FFI_CLOSURES */ #endif /* !FFI_NATIVE_RAW_API */ #endif /* !FFI_NO_RAW_API */
cristiana214/cristianachavez214-cristianachavez
python-build/libffi/src/java_raw_api.c
C
apache-2.0
8,536
# WSDL4R - SOAP complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/xmlSchema/complexType' require 'soap/mapping' module WSDL module XMLSchema class ComplexType < Info def compoundtype @compoundtype ||= check_type end def check_type if content if attributes.empty? and content.elements.size == 1 and content.elements[0].maxoccurs != '1' if name == ::SOAP::Mapping::MapQName :TYPE_MAP else :TYPE_ARRAY end else :TYPE_STRUCT end elsif complexcontent if complexcontent.base == ::SOAP::ValueArrayName :TYPE_ARRAY else complexcontent.basetype.check_type end elsif simplecontent :TYPE_SIMPLE elsif !attributes.empty? :TYPE_STRUCT else # empty complexType definition (seen in partner.wsdl of salesforce) :TYPE_EMPTY end end def child_type(name = nil) case compoundtype when :TYPE_STRUCT if ele = find_element(name) ele.type elsif ele = find_element_by_name(name.name) ele.type end when :TYPE_ARRAY @contenttype ||= content_arytype when :TYPE_MAP item_ele = find_element_by_name("item") or raise RuntimeError.new("'item' element not found in Map definition.") content = item_ele.local_complextype or raise RuntimeError.new("No complexType definition for 'item'.") if ele = content.find_element(name) ele.type elsif ele = content.find_element_by_name(name.name) ele.type end else raise NotImplementedError.new("Unknown kind of complexType.") end end def child_defined_complextype(name) ele = nil case compoundtype when :TYPE_STRUCT, :TYPE_MAP unless ele = find_element(name) if name.namespace.nil? ele = find_element_by_name(name.name) end end when :TYPE_ARRAY if content.elements.size == 1 ele = content.elements[0] else raise RuntimeError.new("Assert: must not reach.") end else raise RuntimeError.new("Assert: Not implemented.") end unless ele raise RuntimeError.new("Cannot find #{name} as a children of #{@name}.") end ele.local_complextype end def find_arytype unless compoundtype == :TYPE_ARRAY raise RuntimeError.new("Assert: not for array") end if complexcontent complexcontent.attributes.each do |attribute| if attribute.ref == ::SOAP::AttrArrayTypeName return attribute.arytype end end if check_array_content(complexcontent.content) return element_simpletype(complexcontent.content.elements[0]) end elsif check_array_content(content) return element_simpletype(content.elements[0]) end raise RuntimeError.new("Assert: Unknown array definition.") end def find_aryelement unless compoundtype == :TYPE_ARRAY raise RuntimeError.new("Assert: not for array") end if complexcontent if check_array_content(complexcontent.content) return complexcontent.content.elements[0] end elsif check_array_content(content) return content.elements[0] end nil # use default item name end private def element_simpletype(element) if element.type element.type elsif element.local_simpletype element.local_simpletype.base else nil end end def check_array_content(content) content and content.elements.size == 1 and content.elements[0].maxoccurs != '1' end def content_arytype if arytype = find_arytype ns = arytype.namespace name = arytype.name.sub(/\[(?:,)*\]$/, '') XSD::QName.new(ns, name) else nil end end end end end
babble/babble
include/ruby/lib/ruby/1.8/wsdl/soap/complexType.rb
Ruby
apache-2.0
4,014
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package system import ( "github.com/golang/glog" "k8s.io/apimachinery/pkg/util/errors" ) // Validator is the interface for all validators. type Validator interface { // Name is the name of the validator. Name() string // Validate is the validate function. Validate(SysSpec) (error, error) } // Reporter is the interface for the reporters for the validators. type Reporter interface { // Report reports the results of the system verification Report(string, string, ValidationResultType) error } // Validate uses validators to validate the system and returns a warning or error. func Validate(spec SysSpec, validators []Validator) (error, error) { var errs []error var warns []error for _, v := range validators { glog.Infof("Validating %s...", v.Name()) warn, err := v.Validate(spec) errs = append(errs, err) warns = append(warns, warn) } return errors.NewAggregate(warns), errors.NewAggregate(errs) } // ValidateDefault uses all default validators to validate the system and writes to stdout. func ValidateDefault(runtime string) (error, error) { // OS-level validators. var osValidators = []Validator{ &OSValidator{Reporter: DefaultReporter}, &KernelValidator{Reporter: DefaultReporter}, &CgroupsValidator{Reporter: DefaultReporter}, } // Docker-specific validators. var dockerValidators = []Validator{ &DockerValidator{Reporter: DefaultReporter}, } validators := osValidators switch runtime { case "docker": validators = append(validators, dockerValidators...) } return Validate(DefaultSysSpec, validators) }
rootfs/snapshot
vendor/k8s.io/kubernetes/test/e2e_node/system/validators.go
GO
apache-2.0
2,131
// go run mksysnum.go http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master // Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,netbsd package unix const ( SYS_EXIT = 1 // { void|sys||exit(int rval); } SYS_FORK = 2 // { int|sys||fork(void); } SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } SYS_CLOSE = 6 // { int|sys||close(int fd); } SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } SYS_SYNC = 36 // { void|sys||sync(void); } SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } SYS_DUP = 41 // { int|sys||dup(int fd); } SYS_PIPE = 42 // { int|sys||pipe(void); } SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } SYS_ACCT = 51 // { int|sys||acct(const char *path); } SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } SYS_VFORK = 66 // { int|sys||vfork(void); } SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } SYS_SSTK = 70 // { int|sys||sstk(int incr); } SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } SYS_FSYNC = 95 // { int|sys||fsync(int fd); } SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } SYS_SETSID = 147 // { int|sys||setsid(void); } SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } SYS_KQUEUE = 344 // { int|sys||kqueue(void); } SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } )
kawych/k8s-stackdriver
kubelet-to-gcm/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go
GO
apache-2.0
26,338
'use strict'; module.exports = function generate_anyOf(it, $keyword) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $noEmptySchema = $schema.every(function($sch) { return it.util.schemaHasRules($sch, it.RULES.all); }); if ($noEmptySchema) { var $currentBaseId = $it.baseId; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; $closingBraces += '}'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should match some schema in anyOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } out = it.util.cleanUpCode(out); } else { if ($breakOnError) { out += ' if (true) { '; } } return out; }
bhathiya/test
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/ajv/lib/dotjs/anyOf.js
JavaScript
apache-2.0
2,583
package main import ( "fmt" "os/exec" "strings" "time" "io/ioutil" "github.com/go-check/check" ) // See issue docker/docker#8141 func (s *DockerRegistrySuite) TestPullImageWithAliases(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) repos := []string{} for _, tag := range []string{"recent", "fresh"} { repos = append(repos, fmt.Sprintf("%v:%v", repoName, tag)) } // Tag and push the same image multiple times. for _, repo := range repos { dockerCmd(c, "tag", "busybox", repo) dockerCmd(c, "push", repo) } // Clear local images store. args := append([]string{"rmi"}, repos...) dockerCmd(c, args...) // Pull a single tag and verify it doesn't bring down all aliases. dockerCmd(c, "pull", repos[0]) dockerCmd(c, "inspect", repos[0]) for _, repo := range repos[1:] { if _, _, err := dockerCmdWithError("inspect", repo); err == nil { c.Fatalf("Image %v shouldn't have been pulled down", repo) } } } // pulling library/hello-world should show verified message func (s *DockerSuite) TestPullVerified(c *check.C) { c.Skip("Skipping hub dependent test") // Image must be pulled from central repository to get verified message // unless keychain is manually updated to contain the daemon's sign key. verifiedName := "hello-world" // pull it expected := "The image you are pulling has been verified" if out, exitCode, err := dockerCmdWithError("pull", verifiedName); err != nil || !strings.Contains(out, expected) { if err != nil || exitCode != 0 { c.Skip(fmt.Sprintf("pulling the '%s' image from the registry has failed: %v", verifiedName, err)) } c.Fatalf("pulling a verified image failed. expected: %s\ngot: %s, %v", expected, out, err) } // pull it again if out, exitCode, err := dockerCmdWithError("pull", verifiedName); err != nil || strings.Contains(out, expected) { if err != nil || exitCode != 0 { c.Skip(fmt.Sprintf("pulling the '%s' image from the registry has failed: %v", verifiedName, err)) } c.Fatalf("pulling a verified image failed. unexpected verify message\ngot: %s, %v", out, err) } } // pulling an image from the central registry should work func (s *DockerSuite) TestPullImageFromCentralRegistry(c *check.C) { testRequires(c, Network) dockerCmd(c, "pull", "hello-world") } // pulling a non-existing image from the central registry should return a non-zero exit code func (s *DockerSuite) TestPullNonExistingImage(c *check.C) { testRequires(c, Network) name := "sadfsadfasdf" out, _, err := dockerCmdWithError("pull", name) if err == nil || !strings.Contains(out, fmt.Sprintf("Error: image library/%s:latest not found", name)) { c.Fatalf("expected non-zero exit status when pulling non-existing image: %s", out) } } // pulling an image from the central registry using official names should work // ensure all pulls result in the same image func (s *DockerSuite) TestPullImageOfficialNames(c *check.C) { testRequires(c, Network) names := []string{ "library/hello-world", "docker.io/library/hello-world", "index.docker.io/library/hello-world", } for _, name := range names { out, exitCode, err := dockerCmdWithError("pull", name) if err != nil || exitCode != 0 { c.Errorf("pulling the '%s' image from the registry has failed: %s", name, err) continue } // ensure we don't have multiple image names. out, _ = dockerCmd(c, "images") if strings.Contains(out, name) { c.Errorf("images should not have listed '%s'", name) } } } func (s *DockerSuite) TestPullScratchNotAllowed(c *check.C) { testRequires(c, Network) out, exitCode, err := dockerCmdWithError("pull", "scratch") if err == nil { c.Fatal("expected pull of scratch to fail, but it didn't") } if exitCode != 1 { c.Fatalf("pulling scratch expected exit code 1, got %d", exitCode) } if strings.Contains(out, "Pulling repository scratch") { c.Fatalf("pulling scratch should not have begun: %s", out) } if !strings.Contains(out, "'scratch' is a reserved name") { c.Fatalf("unexpected output pulling scratch: %s", out) } } // pulling an image with --all-tags=true func (s *DockerSuite) TestPullImageWithAllTagFromCentralRegistry(c *check.C) { testRequires(c, Network) dockerCmd(c, "pull", "busybox") outImageCmd, _ := dockerCmd(c, "images", "busybox") dockerCmd(c, "pull", "--all-tags=true", "busybox") outImageAllTagCmd, _ := dockerCmd(c, "images", "busybox") if strings.Count(outImageCmd, "busybox") >= strings.Count(outImageAllTagCmd, "busybox") { c.Fatalf("Pulling with all tags should get more images") } // FIXME has probably no effect (tags already pushed) dockerCmd(c, "pull", "-a", "busybox") outImageAllTagCmd, _ = dockerCmd(c, "images", "busybox") if strings.Count(outImageCmd, "busybox") >= strings.Count(outImageAllTagCmd, "busybox") { c.Fatalf("Pulling with all tags should get more images") } } func (s *DockerTrustSuite) TestTrustedPull(c *check.C) { repoName := s.setupTrustedImage(c, "trusted-pull") // Try pull pullCmd := exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err := runCommandWithOutput(pullCmd) if err != nil { c.Fatalf("Error running trusted pull: %s\n%s", err, out) } if !strings.Contains(string(out), "Tagging") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } dockerCmd(c, "rmi", repoName) // Try untrusted pull to ensure we pushed the tag to the registry pullCmd = exec.Command(dockerBinary, "pull", "--disable-content-trust=true", repoName) s.trustedCmd(pullCmd) out, _, err = runCommandWithOutput(pullCmd) if err != nil { c.Fatalf("Error running trusted pull: %s\n%s", err, out) } if !strings.Contains(string(out), "Status: Downloaded") { c.Fatalf("Missing expected output on trusted pull with --disable-content-trust:\n%s", out) } } func (s *DockerTrustSuite) TestTrustedIsolatedPull(c *check.C) { repoName := s.setupTrustedImage(c, "trusted-isolatd-pull") // Try pull (run from isolated directory without trust information) pullCmd := exec.Command(dockerBinary, "--config", "/tmp/docker-isolated", "pull", repoName) s.trustedCmd(pullCmd) out, _, err := runCommandWithOutput(pullCmd) if err != nil { c.Fatalf("Error running trusted pull: %s\n%s", err, out) } if !strings.Contains(string(out), "Tagging") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } dockerCmd(c, "rmi", repoName) } func (s *DockerTrustSuite) TestUntrustedPull(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL) // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoName) dockerCmd(c, "push", repoName) dockerCmd(c, "rmi", repoName) // Try trusted pull on untrusted tag pullCmd := exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err := runCommandWithOutput(pullCmd) if err == nil { c.Fatalf("Error expected when running trusted pull with:\n%s", out) } if !strings.Contains(string(out), "no trust data available") { c.Fatalf("Missing expected output on trusted pull:\n%s", out) } } func (s *DockerTrustSuite) TestPullWhenCertExpired(c *check.C) { c.Skip("Currently changes system time, causing instability") repoName := s.setupTrustedImage(c, "trusted-cert-expired") // Certificates have 10 years of expiration elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11) runAtDifferentDate(elevenYearsFromNow, func() { // Try pull pullCmd := exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err := runCommandWithOutput(pullCmd) if err == nil { c.Fatalf("Error running trusted pull in the distant future: %s\n%s", err, out) } if !strings.Contains(string(out), "could not validate the path to a trusted root") { c.Fatalf("Missing expected output on trusted pull in the distant future:\n%s", out) } }) runAtDifferentDate(elevenYearsFromNow, func() { // Try pull pullCmd := exec.Command(dockerBinary, "pull", "--disable-content-trust", repoName) s.trustedCmd(pullCmd) out, _, err := runCommandWithOutput(pullCmd) if err != nil { c.Fatalf("Error running untrusted pull in the distant future: %s\n%s", err, out) } if !strings.Contains(string(out), "Status: Downloaded") { c.Fatalf("Missing expected output on untrusted pull in the distant future:\n%s", out) } }) } func (s *DockerTrustSuite) TestTrustedPullFromBadTrustServer(c *check.C) { repoName := fmt.Sprintf("%v/dockerclievilpull/trusted:latest", privateRegistryURL) evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir") if err != nil { c.Fatalf("Failed to create local temp dir") } // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoName) pushCmd := exec.Command(dockerBinary, "push", repoName) s.trustedCmd(pushCmd) out, _, err := runCommandWithOutput(pushCmd) if err != nil { c.Fatalf("Error running trusted push: %s\n%s", err, out) } if !strings.Contains(string(out), "Signing and pushing trust metadata") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } dockerCmd(c, "rmi", repoName) // Try pull pullCmd := exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err = runCommandWithOutput(pullCmd) if err != nil { c.Fatalf("Error running trusted pull: %s\n%s", err, out) } if !strings.Contains(string(out), "Tagging") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } dockerCmd(c, "rmi", repoName) // Kill the notary server, start a new "evil" one. s.not.Close() s.not, err = newTestNotary(c) if err != nil { c.Fatalf("Restarting notary server failed.") } // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data. // tag an image and upload it to the private registry dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName) // Push up to the new server pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName) s.trustedCmd(pushCmd) out, _, err = runCommandWithOutput(pushCmd) if err != nil { c.Fatalf("Error running trusted push: %s\n%s", err, out) } if !strings.Contains(string(out), "Signing and pushing trust metadata") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } // Now, try pulling with the original client from this new trust server. This should fail. pullCmd = exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err = runCommandWithOutput(pullCmd) if err == nil { c.Fatalf("Expected to fail on this pull due to different remote data: %s\n%s", err, out) } if !strings.Contains(string(out), "failed to validate data with current trusted certificates") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } } func (s *DockerTrustSuite) TestTrustedPullWithExpiredSnapshot(c *check.C) { c.Skip("Currently changes system time, causing instability") repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppull/trusted:latest", privateRegistryURL) // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoName) // Push with default passphrases pushCmd := exec.Command(dockerBinary, "push", repoName) s.trustedCmd(pushCmd) out, _, err := runCommandWithOutput(pushCmd) if err != nil { c.Fatalf("trusted push failed: %s\n%s", err, out) } if !strings.Contains(string(out), "Signing and pushing trust metadata") { c.Fatalf("Missing expected output on trusted push:\n%s", out) } dockerCmd(c, "rmi", repoName) // Snapshots last for three years. This should be expired fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4) // Should succeed because the server transparently re-signs one runAtDifferentDate(fourYearsLater, func() { // Try pull pullCmd := exec.Command(dockerBinary, "pull", repoName) s.trustedCmd(pullCmd) out, _, err = runCommandWithOutput(pullCmd) if err == nil { c.Fatalf("Missing expected error running trusted pull with expired snapshots") } if !strings.Contains(string(out), "repository out-of-date") { c.Fatalf("Missing expected output on trusted pull with expired snapshot:\n%s", out) } }) }
dezon/docker
integration-cli/docker_cli_pull_test.go
GO
apache-2.0
12,180
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * */ using System; using System.Web; using System.Net; using System.IO; using Thrift.Protocol; namespace Thrift.Transport { public class THttpHandler : IHttpHandler { protected TProcessor processor; protected TProtocolFactory inputProtocolFactory; protected TProtocolFactory outputProtocolFactory; protected const string contentType = "application/x-thrift"; protected System.Text.Encoding encoding = System.Text.Encoding.UTF8; public THttpHandler(TProcessor processor) : this(processor, new TBinaryProtocol.Factory()) { } public THttpHandler(TProcessor processor, TProtocolFactory protocolFactory) : this(processor, protocolFactory, protocolFactory) { } public THttpHandler(TProcessor processor, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory) { this.processor = processor; this.inputProtocolFactory = inputProtocolFactory; this.outputProtocolFactory = outputProtocolFactory; } public void ProcessRequest(HttpListenerContext context) { context.Response.ContentType = contentType; context.Response.ContentEncoding = encoding; ProcessRequest(context.Request.InputStream, context.Response.OutputStream); } public void ProcessRequest(HttpContext context) { context.Response.ContentType = contentType; context.Response.ContentEncoding = encoding; ProcessRequest(context.Request.InputStream, context.Response.OutputStream); } public void ProcessRequest(Stream input, Stream output) { TTransport transport = new TStreamTransport(input,output); try { var inputProtocol = inputProtocolFactory.GetProtocol(transport); var outputProtocol = outputProtocolFactory.GetProtocol(transport); while (processor.Process(inputProtocol, outputProtocol)) { } } catch (TTransportException) { // Client died, just move on } finally { transport.Close(); } } public bool IsReusable { get { return true; } } } }
siemens/thrift
lib/csharp/src/Transport/THttpHandler.cs
C#
apache-2.0
3,236
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Scaffolding · Bootstrap</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/bootstrap-responsive.css" rel="stylesheet"> <link href="assets/css/docs.css" rel="stylesheet"> <link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="assets/js/html5shiv.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="assets/ico/favicon.png"> </head> <body data-spy="scroll" data-target=".bs-docs-sidebar"> <!-- Navbar ================================================== --> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="./index.html">Bootstrap</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class=""> <a href="./index.html">Home</a> </li> <li class=""> <a href="./getting-started.html">Get started</a> </li> <li class="active"> <a href="./scaffolding.html">Scaffolding</a> </li> <li class=""> <a href="./base-css.html">Base CSS</a> </li> <li class=""> <a href="./components.html">Components</a> </li> <li class=""> <a href="./javascript.html">JavaScript</a> </li> <li class=""> <a href="./customize.html">Customize</a> </li> </ul> </div> </div> </div> </div> <!-- Subhead ================================================== --> <header class="jumbotron subhead" id="overview"> <div class="container"> <h1>Scaffolding</h1> <p class="lead">Bootstrap is built on responsive 12-column grids, layouts, and components.</p> </div> </header> <div class="container"> <!-- Docs nav ================================================== --> <div class="row"> <div class="span3 bs-docs-sidebar"> <ul class="nav nav-list bs-docs-sidenav"> <li><a href="#global"><i class="icon-chevron-right"></i> Global styles</a></li> <li><a href="#gridSystem"><i class="icon-chevron-right"></i> Grid system</a></li> <li><a href="#fluidGridSystem"><i class="icon-chevron-right"></i> Fluid grid system</a></li> <li><a href="#layouts"><i class="icon-chevron-right"></i> Layouts</a></li> <li><a href="#responsive"><i class="icon-chevron-right"></i> Responsive design</a></li> </ul> </div> <div class="span9"> <!-- Global Bootstrap settings ================================================== --> <section id="global"> <div class="page-header"> <h1>Global settings</h1> </div> <h3>Requires HTML5 doctype</h3> <p>Bootstrap makes use of certain HTML elements and CSS properties that require the use of the HTML5 doctype. Include it at the beginning of all your projects.</p> <pre class="prettyprint linenums"> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; ... &lt;/html&gt; </pre> <h3>Typography and links</h3> <p>Bootstrap sets basic global display, typography, and link styles. Specifically, we:</p> <ul> <li>Remove <code>margin</code> on the body</li> <li>Set <code>background-color: white;</code> on the <code>body</code></li> <li>Use the <code>@baseFontFamily</code>, <code>@baseFontSize</code>, and <code>@baseLineHeight</code> attributes as our typographic base</li> <li>Set the global link color via <code>@linkColor</code> and apply link underlines only on <code>:hover</code></li> </ul> <p>These styles can be found within <strong>scaffolding.less</strong>.</p> <h3>Reset via Normalize</h3> <p>With Bootstrap 2, the old reset block has been dropped in favor of <a href="http://necolas.github.com/normalize.css/" target="_blank">Normalize.css</a>, a project by <a href="http://twitter.com/necolas" target="_blank">Nicolas Gallagher</a> and <a href="http://twitter.com/jon_neal" target="_blank">Jonathan Neal</a> that also powers the <a href="http://html5boilerplate.com" target="_blank">HTML5 Boilerplate</a>. While we use much of Normalize within our <strong>reset.less</strong>, we have removed some elements specifically for Bootstrap.</p> </section> <!-- Grid system ================================================== --> <section id="gridSystem"> <div class="page-header"> <h1>Default grid system</h1> </div> <h2>Live grid example</h2> <p>The default Bootstrap grid system utilizes <strong>12 columns</strong>, making for a 940px wide container without <a href="./scaffolding.html#responsive">responsive features</a> enabled. With the responsive CSS file added, the grid adapts to be 724px and 1170px wide depending on your viewport. Below 767px viewports, the columns become fluid and stack vertically.</p> <div class="bs-docs-grid"> <div class="row show-grid"> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> </div> <div class="row show-grid"> <div class="span2">2</div> <div class="span3">3</div> <div class="span4">4</div> </div> <div class="row show-grid"> <div class="span4">4</div> <div class="span5">5</div> </div> <div class="row show-grid"> <div class="span9">9</div> </div> </div> <h3>Basic grid HTML</h3> <p>For a simple two column layout, create a <code>.row</code> and add the appropriate number of <code>.span*</code> columns. As this is a 12-column grid, each <code>.span*</code> spans a number of those 12 columns, and should always add up to 12 for each row (or the number of columns in the parent).</p> <pre class="prettyprint linenums"> &lt;div class="row"&gt; &lt;div class="span4"&gt;...&lt;/div&gt; &lt;div class="span8"&gt;...&lt;/div&gt; &lt;/div&gt; </pre> <p>Given this example, we have <code>.span4</code> and <code>.span8</code>, making for 12 total columns and a complete row.</p> <h2>Offsetting columns</h2> <p>Move columns to the right using <code>.offset*</code> classes. Each class increases the left margin of a column by a whole column. For example, <code>.offset4</code> moves <code>.span4</code> over four columns.</p> <div class="bs-docs-grid"> <div class="row show-grid"> <div class="span4">4</div> <div class="span3 offset2">3 offset 2</div> </div><!-- /row --> <div class="row show-grid"> <div class="span3 offset1">3 offset 1</div> <div class="span3 offset2">3 offset 2</div> </div><!-- /row --> <div class="row show-grid"> <div class="span6 offset3">6 offset 3</div> </div><!-- /row --> </div> <pre class="prettyprint linenums"> &lt;div class="row"&gt; &lt;div class="span4"&gt;...&lt;/div&gt; &lt;div class="span3 offset2"&gt;...&lt;/div&gt; &lt;/div&gt; </pre> <h2>Nesting columns</h2> <p>To nest your content with the default grid, add a new <code>.row</code> and set of <code>.span*</code> columns within an existing <code>.span*</code> column. Nested rows should include a set of columns that add up to the number of columns of its parent.</p> <div class="row show-grid"> <div class="span9"> Level 1 column <div class="row show-grid"> <div class="span6"> Level 2 </div> <div class="span3"> Level 2 </div> </div> </div> </div> <pre class="prettyprint linenums"> &lt;div class="row"&gt; &lt;div class="span9"&gt; Level 1 column &lt;div class="row"&gt; &lt;div class="span6"&gt;Level 2&lt;/div&gt; &lt;div class="span3"&gt;Level 2&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </pre> </section> <!-- Fluid grid system ================================================== --> <section id="fluidGridSystem"> <div class="page-header"> <h1>Fluid grid system</h1> </div> <h2>Live fluid grid example</h2> <p>The fluid grid system uses percents instead of pixels for column widths. It has the same responsive capabilities as our fixed grid system, ensuring proper proportions for key screen resolutions and devices.</p> <div class="bs-docs-grid"> <div class="row-fluid show-grid"> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> <div class="span1">1</div> </div> <div class="row-fluid show-grid"> <div class="span4">4</div> <div class="span4">4</div> <div class="span4">4</div> </div> <div class="row-fluid show-grid"> <div class="span4">4</div> <div class="span8">8</div> </div> <div class="row-fluid show-grid"> <div class="span6">6</div> <div class="span6">6</div> </div> <div class="row-fluid show-grid"> <div class="span12">12</div> </div> </div> <h3>Basic fluid grid HTML</h3> <p>Make any row "fluid" by changing <code>.row</code> to <code>.row-fluid</code>. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.</p> <pre class="prettyprint linenums"> &lt;div class="row-fluid"&gt; &lt;div class="span4"&gt;...&lt;/div&gt; &lt;div class="span8"&gt;...&lt;/div&gt; &lt;/div&gt; </pre> <h2>Fluid offsetting</h2> <p>Operates the same way as the fixed grid system offsetting: add <code>.offset*</code> to any column to offset by that many columns.</p> <div class="bs-docs-grid"> <div class="row-fluid show-grid"> <div class="span4">4</div> <div class="span4 offset4">4 offset 4</div> </div><!-- /row --> <div class="row-fluid show-grid"> <div class="span3 offset3">3 offset 3</div> <div class="span3 offset3">3 offset 3</div> </div><!-- /row --> <div class="row-fluid show-grid"> <div class="span6 offset6">6 offset 6</div> </div><!-- /row --> </div> <pre class="prettyprint linenums"> &lt;div class="row-fluid"&gt; &lt;div class="span4"&gt;...&lt;/div&gt; &lt;div class="span4 offset2"&gt;...&lt;/div&gt; &lt;/div&gt; </pre> <h2>Fluid nesting</h2> <p>Fluid grids utilize nesting differently: each nested level of columns should add up to 12 columns. This is because the fluid grid uses percentages, not pixels, for setting widths.</p> <div class="row-fluid show-grid"> <div class="span12"> Fluid 12 <div class="row-fluid show-grid"> <div class="span6"> Fluid 6 <div class="row-fluid show-grid"> <div class="span6"> Fluid 6 </div> <div class="span6"> Fluid 6 </div> </div> </div> <div class="span6"> Fluid 6 </div> </div> </div> </div> <pre class="prettyprint linenums"> &lt;div class="row-fluid"&gt; &lt;div class="span12"&gt; Fluid 12 &lt;div class="row-fluid"&gt; &lt;div class="span6"&gt; Fluid 6 &lt;div class="row-fluid"&gt; &lt;div class="span6"&gt;Fluid 6&lt;/div&gt; &lt;div class="span6"&gt;Fluid 6&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="span6"&gt;Fluid 6&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </pre> </section> <!-- Layouts (Default and fluid) ================================================== --> <section id="layouts"> <div class="page-header"> <h1>Layouts</h1> </div> <h2>Fixed layout</h2> <p>Provides a common fixed-width (and optionally responsive) layout with only <code>&lt;div class="container"&gt;</code> required.</p> <div class="mini-layout"> <div class="mini-layout-body"></div> </div> <pre class="prettyprint linenums"> &lt;body&gt; &lt;div class="container"&gt; ... &lt;/div&gt; &lt;/body&gt; </pre> <h2>Fluid layout</h2> <p>Create a fluid, two-column page with <code>&lt;div class="container-fluid"&gt;</code>&mdash;great for applications and docs.</p> <div class="mini-layout fluid"> <div class="mini-layout-sidebar"></div> <div class="mini-layout-body"></div> </div> <pre class="prettyprint linenums"> &lt;div class="container-fluid"&gt; &lt;div class="row-fluid"&gt; &lt;div class="span2"&gt; &lt;!--Sidebar content--&gt; &lt;/div&gt; &lt;div class="span10"&gt; &lt;!--Body content--&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </pre> </section> <!-- Responsive design ================================================== --> <section id="responsive"> <div class="page-header"> <h1>Responsive design</h1> </div> <h2>Enabling responsive features</h2> <p>Turn on responsive CSS in your project by including the proper meta tag and additional stylesheet within the <code>&lt;head&gt;</code> of your document. If you've compiled Bootstrap from the Customize page, you need only include the meta tag.</p> <pre class="prettyprint linenums"> &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link href="assets/css/bootstrap-responsive.css" rel="stylesheet"&gt; </pre> <p><span class="label label-info">Heads up!</span> Bootstrap doesn't include responsive features by default at this time as not everything needs to be responsive. Instead of encouraging developers to remove this feature, we figure it best to enable it as needed.</p> <h2>About responsive Bootstrap</h2> <img src="assets/img/responsive-illustrations.png" alt="Responsive devices" style="float: right; margin: 0 0 20px 20px;"> <p>Media queries allow for custom CSS based on a number of conditions&mdash;ratios, widths, display type, etc&mdash;but usually focuses around <code>min-width</code> and <code>max-width</code>.</p> <ul> <li>Modify the width of column in our grid</li> <li>Stack elements instead of float wherever necessary</li> <li>Resize headings and text to be more appropriate for devices</li> </ul> <p>Use media queries responsibly and only as a start to your mobile audiences. For larger projects, do consider dedicated code bases and not layers of media queries.</p> <h2>Supported devices</h2> <p>Bootstrap supports a handful of media queries in a single file to help make your projects more appropriate on different devices and screen resolutions. Here's what's included:</p> <table class="table table-bordered table-striped"> <thead> <tr> <th>Label</th> <th>Layout width</th> <th>Column width</th> <th>Gutter width</th> </tr> </thead> <tbody> <tr> <td>Large display</td> <td>1200px and up</td> <td>70px</td> <td>30px</td> </tr> <tr> <td>Default</td> <td>980px and up</td> <td>60px</td> <td>20px</td> </tr> <tr> <td>Portrait tablets</td> <td>768px and above</td> <td>42px</td> <td>20px</td> </tr> <tr> <td>Phones to tablets</td> <td>767px and below</td> <td class="muted" colspan="2">Fluid columns, no fixed widths</td> </tr> <tr> <td>Phones</td> <td>480px and below</td> <td class="muted" colspan="2">Fluid columns, no fixed widths</td> </tr> </tbody> </table> <pre class="prettyprint linenums"> /* Large desktop */ @media (min-width: 1200px) { ... } /* Portrait tablet to landscape and desktop */ @media (min-width: 768px) and (max-width: 979px) { ... } /* Landscape phone to portrait tablet */ @media (max-width: 767px) { ... } /* Landscape phones and down */ @media (max-width: 480px) { ... } </pre> <h2>Responsive utility classes</h2> <p>For faster mobile-friendly development, use these utility classes for showing and hiding content by device. Below is a table of the available classes and their effect on a given media query layout (labeled by device). They can be found in <code>responsive.less</code>.</p> <table class="table table-bordered table-striped responsive-utilities"> <thead> <tr> <th>Class</th> <th>Phones <small>767px and below</small></th> <th>Tablets <small>979px to 768px</small></th> <th>Desktops <small>Default</small></th> </tr> </thead> <tbody> <tr> <th><code>.visible-phone</code></th> <td class="is-visible">Visible</td> <td class="is-hidden">Hidden</td> <td class="is-hidden">Hidden</td> </tr> <tr> <th><code>.visible-tablet</code></th> <td class="is-hidden">Hidden</td> <td class="is-visible">Visible</td> <td class="is-hidden">Hidden</td> </tr> <tr> <th><code>.visible-desktop</code></th> <td class="is-hidden">Hidden</td> <td class="is-hidden">Hidden</td> <td class="is-visible">Visible</td> </tr> <tr> <th><code>.hidden-phone</code></th> <td class="is-hidden">Hidden</td> <td class="is-visible">Visible</td> <td class="is-visible">Visible</td> </tr> <tr> <th><code>.hidden-tablet</code></th> <td class="is-visible">Visible</td> <td class="is-hidden">Hidden</td> <td class="is-visible">Visible</td> </tr> <tr> <th><code>.hidden-desktop</code></th> <td class="is-visible">Visible</td> <td class="is-visible">Visible</td> <td class="is-hidden">Hidden</td> </tr> </tbody> </table> <h3>When to use</h3> <p>Use on a limited basis and avoid creating entirely different versions of the same site. Instead, use them to complement each device's presentation. Responsive utilities should not be used with tables, and as such are not supported.</p> <h3>Responsive utilities test case</h3> <p>Resize your browser or load on different devices to test the above classes.</p> <h4>Visible on...</h4> <p>Green checkmarks indicate that class is visible in your current viewport.</p> <ul class="responsive-utilities-test"> <li>Phone<span class="visible-phone">&#10004; Phone</span></li> <li>Tablet<span class="visible-tablet">&#10004; Tablet</span></li> <li>Desktop<span class="visible-desktop">&#10004; Desktop</span></li> </ul> <h4>Hidden on...</h4> <p>Here, green checkmarks indicate that class is hidden in your current viewport.</p> <ul class="responsive-utilities-test hidden-on"> <li>Phone<span class="hidden-phone">&#10004; Phone</span></li> <li>Tablet<span class="hidden-tablet">&#10004; Tablet</span></li> <li>Desktop<span class="hidden-desktop">&#10004; Desktop</span></li> </ul> </section> </div> </div> </div> <!-- Footer ================================================== --> <footer class="footer"> <div class="container"> <p>Designed and built with all the love in the world by <a href="http://twitter.com/mdo" target="_blank">@mdo</a> and <a href="http://twitter.com/fat" target="_blank">@fat</a>.</p> <p>Code licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License v2.0</a>, documentation under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p> <p><a href="http://glyphicons.com">Glyphicons Free</a> licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.</p> <ul class="footer-links"> <li><a href="http://blog.getbootstrap.com">Blog</a></li> <li class="muted">&middot;</li> <li><a href="https://github.com/twitter/bootstrap/issues?state=open">Issues</a></li> <li class="muted">&middot;</li> <li><a href="https://github.com/twitter/bootstrap/blob/master/CHANGELOG.md">Changelog</a></li> </ul> </div> </footer> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script src="assets/js/jquery.js"></script> <script src="assets/js/bootstrap-transition.js"></script> <script src="assets/js/bootstrap-alert.js"></script> <script src="assets/js/bootstrap-modal.js"></script> <script src="assets/js/bootstrap-dropdown.js"></script> <script src="assets/js/bootstrap-scrollspy.js"></script> <script src="assets/js/bootstrap-tab.js"></script> <script src="assets/js/bootstrap-tooltip.js"></script> <script src="assets/js/bootstrap-popover.js"></script> <script src="assets/js/bootstrap-button.js"></script> <script src="assets/js/bootstrap-collapse.js"></script> <script src="assets/js/bootstrap-carousel.js"></script> <script src="assets/js/bootstrap-typeahead.js"></script> <script src="assets/js/bootstrap-affix.js"></script> <script src="assets/js/holder/holder.js"></script> <script src="assets/js/google-code-prettify/prettify.js"></script> <script src="assets/js/application.js"></script> </body> </html>
codedayday/jeesite
src/main/webapp/static/bootstrap/2.3.1/docs/scaffolding.html
HTML
apache-2.0
25,153
module TypeScript.Parser { class SyntaxCursor { public currentNode(): SyntaxNode { return null; } } } module TypeScript { export interface ISyntaxElement { }; export interface ISyntaxToken { }; export class PositionedElement { public childIndex(child: ISyntaxElement) { return Syntax.childIndex(); } } export class PositionedToken { constructor(parent: PositionedElement, token: ISyntaxToken, fullStart: number) { } } } module TypeScript { export class SyntaxNode { public findToken(position: number, includeSkippedTokens: boolean = false): PositionedToken { var positionedToken = this.findTokenInternal(null, position, 0); return null; } findTokenInternal(x, y, z) { return null; } } } module TypeScript.Syntax { export function childIndex() { } export class VariableWidthTokenWithTrailingTrivia implements ISyntaxToken { private findTokenInternal(parent: PositionedElement, position: number, fullStart: number) { return new PositionedToken(parent, this, fullStart); } } }
mmoskal/TypeScript
tests/cases/compiler/moduleMemberWithoutTypeAnnotation1.ts
TypeScript
apache-2.0
1,248
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package prometheus provides embeddable metric primitives for servers and // standardized exposition of telemetry through a web services interface. // // All exported functions and methods are safe to be used concurrently unless // specified otherwise. // // To expose metrics registered with the Prometheus registry, an HTTP server // needs to know about the Prometheus handler. The usual endpoint is "/metrics". // // http.Handle("/metrics", prometheus.Handler()) // // As a starting point a very basic usage example: // // package main // // import ( // "net/http" // // "github.com/prometheus/client_golang/prometheus" // ) // // var ( // cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{ // Name: "cpu_temperature_celsius", // Help: "Current temperature of the CPU.", // }) // hdFailures = prometheus.NewCounter(prometheus.CounterOpts{ // Name: "hd_errors_total", // Help: "Number of hard-disk errors.", // }) // ) // // func init() { // prometheus.MustRegister(cpuTemp) // prometheus.MustRegister(hdFailures) // } // // func main() { // cpuTemp.Set(65.3) // hdFailures.Inc() // // http.Handle("/metrics", prometheus.Handler()) // http.ListenAndServe(":8080", nil) // } // // // This is a complete program that exports two metrics, a Gauge and a Counter. // It also exports some stats about the HTTP usage of the /metrics // endpoint. (See the Handler function for more detail.) // // Two more advanced metric types are the Summary and Histogram. // // In addition to the fundamental metric types Gauge, Counter, Summary, and // Histogram, a very important part of the Prometheus data model is the // partitioning of samples along dimensions called labels, which results in // metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec, // and HistogramVec. // // Those are all the parts needed for basic usage. Detailed documentation and // examples are provided below. // // Everything else this package offers is essentially for "power users" only. A // few pointers to "power user features": // // All the various ...Opts structs have a ConstLabels field for labels that // never change their value (which is only useful under special circumstances, // see documentation of the Opts type). // // The Untyped metric behaves like a Gauge, but signals the Prometheus server // not to assume anything about its type. // // Functions to fine-tune how the metric registry works: EnableCollectChecks, // PanicOnCollectError, Register, Unregister, SetMetricFamilyInjectionHook. // // For custom metric collection, there are two entry points: Custom Metric // implementations and custom Collector implementations. A Metric is the // fundamental unit in the Prometheus data model: a sample at a point in time // together with its meta-data (like its fully-qualified name and any number of // pairs of label name and label value) that knows how to marshal itself into a // data transfer object (aka DTO, implemented as a protocol buffer). A Collector // gets registered with the Prometheus registry and manages the collection of // one or more Metrics. Many parts of this package are building blocks for // Metrics and Collectors. Desc is the metric descriptor, actually used by all // metrics under the hood, and by Collectors to describe the Metrics to be // collected, but only to be dealt with by users if they implement their own // Metrics or Collectors. To create a Desc, the BuildFQName function will come // in handy. Other useful components for Metric and Collector implementation // include: LabelPairSorter to sort the DTO version of label pairs, // NewConstMetric and MustNewConstMetric to create "throw away" Metrics at // collection time, MetricVec to bundle custom Metrics into a metric vector // Collector, SelfCollector to make a custom Metric collect itself. // // A good example for a custom Collector is the ExpVarCollector included in this // package, which exports variables exported via the "expvar" package as // Prometheus metrics. package prometheus
derekparker/kubernetes
vendor/github.com/prometheus/client_golang/prometheus/doc.go
GO
apache-2.0
4,687
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.timer; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class TimerRouteWithTracerTest extends TimerRouteTest { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { getContext().setTracing(true); from("timer://foo?fixedRate=true&delay=0&period=500").to("bean:myBean", "mock:result"); } }; } }
woj-i/camel
camel-core/src/test/java/org/apache/camel/component/timer/TimerRouteWithTracerTest.java
Java
apache-2.0
1,319
# SOAP4R - SOAP EncodingStyle handler library # Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'soap/encodingstyle/handler' module SOAP module EncodingStyle class SOAPHandler < Handler Namespace = SOAP::EncodingNamespace add_handler def initialize(charset = nil) super(charset) @refpool = [] @idpool = [] @textbuf = '' @is_first_top_ele = true end ### ## encode interface. # def encode_data(generator, ns, data, parent) attrs = encode_attrs(generator, ns, data, parent) if parent && parent.is_a?(SOAPArray) && parent.position attrs[ns.name(AttrPositionName)] = "[#{parent.position.join(',')}]" end name = generator.encode_name(ns, data, attrs) case data when SOAPReference attrs['href'] = data.refidstr generator.encode_tag(name, attrs) when SOAPExternalReference data.referred attrs['href'] = data.refidstr generator.encode_tag(name, attrs) when SOAPRawString generator.encode_tag(name, attrs) generator.encode_rawstring(data.to_s) when XSD::XSDString generator.encode_tag(name, attrs) generator.encode_string(@charset ? XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s) when XSD::XSDAnySimpleType generator.encode_tag(name, attrs) generator.encode_string(data.to_s) when SOAPStruct generator.encode_tag(name, attrs) data.each do |key, value| generator.encode_child(ns, value, data) end when SOAPArray generator.encode_tag(name, attrs) data.traverse do |child, *rank| data.position = data.sparse ? rank : nil generator.encode_child(ns, child, data) end else raise EncodingStyleError.new( "unknown object:#{data} in this encodingStyle") end end def encode_data_end(generator, ns, data, parent) name = generator.encode_name_end(ns, data) cr = data.is_a?(SOAPCompoundtype) generator.encode_tag_end(name, cr) end ### ## decode interface. # class SOAPTemporalObject attr_accessor :parent attr_accessor :position attr_accessor :id attr_accessor :root def initialize @parent = nil @position = nil @id = nil @root = nil end end class SOAPUnknown < SOAPTemporalObject attr_reader :type attr_accessor :definedtype attr_reader :extraattr def initialize(handler, elename, type, extraattr) super() @handler = handler @elename = elename @type = type @extraattr = extraattr @definedtype = nil end def as_struct o = SOAPStruct.decode(@elename, @type) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_string o = SOAPString.decode(@elename) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_nil o = SOAPNil.decode(@elename) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end end def decode_tag(ns, elename, attrs, parent) @textbuf = '' is_nil, type, arytype, root, offset, position, href, id, extraattr = decode_attrs(ns, attrs) o = nil if is_nil o = SOAPNil.decode(elename) elsif href o = SOAPReference.decode(elename, href) @refpool << o elsif @decode_typemap o = decode_tag_by_wsdl(ns, elename, type, parent.node, arytype, extraattr) else o = decode_tag_by_type(ns, elename, type, parent.node, arytype, extraattr) end if o.is_a?(SOAPArray) if offset o.offset = decode_arypos(offset) o.sparse = true else o.sparse = false end end o.parent = parent o.id = id o.root = root o.position = position unless o.is_a?(SOAPTemporalObject) @idpool << o if o.id decode_parent(parent, o) end o end def decode_tag_end(ns, node) o = node.node if o.is_a?(SOAPUnknown) newnode = if /\A\s*\z/ =~ @textbuf o.as_struct else o.as_string end if newnode.id @idpool << newnode end node.replace_node(newnode) o = node.node end decode_textbuf(o) # unlink definedtype o.definedtype = nil end def decode_text(ns, text) @textbuf << text end def decode_prologue @refpool.clear @idpool.clear @is_first_top_ele = true end def decode_epilogue decode_resolve_id end def decode_parent(parent, node) return unless parent.node case parent.node when SOAPUnknown newparent = parent.node.as_struct node.parent = newparent if newparent.id @idpool << newparent end parent.replace_node(newparent) decode_parent(parent, node) when SOAPStruct parent.node.add(node.elename.name, node) node.parent = parent.node when SOAPArray if node.position parent.node[*(decode_arypos(node.position))] = node parent.node.sparse = true else parent.node.add(node) end node.parent = parent.node else raise EncodingStyleError.new("illegal parent: #{parent.node}") end end private def content_ranksize(typename) typename.scan(/\[[\d,]*\]$/)[0] end def content_typename(typename) typename.sub(/\[,*\]$/, '') end def create_arytype(ns, data) XSD::QName.new(data.arytype.namespace, content_typename(data.arytype.name) + "[#{data.size.join(',')}]") end def encode_attrs(generator, ns, data, parent) attrs = {} return attrs if data.is_a?(SOAPReference) if !parent || parent.encodingstyle != EncodingNamespace if @generate_explicit_type SOAPGenerator.assign_ns(attrs, ns, EnvelopeNamespace) attrs[ns.name(AttrEncodingStyleName)] = EncodingNamespace end data.encodingstyle = EncodingNamespace end if data.is_a?(SOAPNil) attrs[ns.name(XSD::AttrNilName)] = XSD::NilValue elsif @generate_explicit_type if data.type.namespace SOAPGenerator.assign_ns(attrs, ns, data.type.namespace) end if data.is_a?(SOAPArray) if data.arytype.namespace SOAPGenerator.assign_ns(attrs, ns, data.arytype.namespace) end SOAPGenerator.assign_ns(attrs, ns, EncodingNamespace) attrs[ns.name(AttrArrayTypeName)] = ns.name(create_arytype(ns, data)) if data.type.name attrs[ns.name(XSD::AttrTypeName)] = ns.name(data.type) end elsif parent && parent.is_a?(SOAPArray) && (parent.arytype == data.type) # No need to add. elsif !data.type.namespace # No need to add. else attrs[ns.name(XSD::AttrTypeName)] = ns.name(data.type) end end data.extraattr.each do |key, value| SOAPGenerator.assign_ns(attrs, ns, key.namespace) attrs[ns.name(key)] = encode_attr_value(generator, ns, key, value) end if data.id attrs['id'] = data.id end attrs end def encode_attr_value(generator, ns, qname, value) if value.is_a?(SOAPType) ref = SOAPReference.new(value) generator.add_reftarget(qname.name, value) ref.refidstr else value.to_s end end def decode_tag_by_wsdl(ns, elename, typestr, parent, arytypestr, extraattr) o = nil if parent.class == SOAPBody # root element: should branch by root attribute? if @is_first_top_ele # Unqualified name is allowed here. @is_first_top_ele = false type = @decode_typemap[elename] || @decode_typemap.find_name(elename.name) if type o = SOAPStruct.new(elename) o.definedtype = type return o end end # multi-ref element. if typestr typename = ns.parse(typestr) typedef = @decode_typemap[typename] if typedef return decode_definedtype(elename, typename, typedef, arytypestr) end end return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end if parent.type == XSD::AnyTypeName return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end # parent.definedtype == nil means the parent is SOAPUnknown. SOAPUnknown # is generated by decode_tag_by_type when its type is anyType. parenttype = parent.definedtype || @decode_typemap[parent.type] unless parenttype return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end definedtype_name = parenttype.child_type(elename) if definedtype_name and (klass = TypeMap[definedtype_name]) return decode_basetype(klass, elename) elsif definedtype_name == XSD::AnyTypeName return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end if definedtype_name typedef = @decode_typemap[definedtype_name] else typedef = parenttype.child_defined_complextype(elename) end decode_definedtype(elename, definedtype_name, typedef, arytypestr) end def decode_definedtype(elename, typename, typedef, arytypestr) unless typedef raise EncodingStyleError.new("unknown type '#{typename}'") end if typedef.is_a?(::WSDL::XMLSchema::SimpleType) decode_defined_simpletype(elename, typename, typedef, arytypestr) else decode_defined_complextype(elename, typename, typedef, arytypestr) end end def decode_basetype(klass, elename) klass.decode(elename) end def decode_defined_simpletype(elename, typename, typedef, arytypestr) o = decode_basetype(TypeMap[typedef.base], elename) o.definedtype = typedef o end def decode_defined_complextype(elename, typename, typedef, arytypestr) case typedef.compoundtype when :TYPE_STRUCT, :TYPE_MAP o = SOAPStruct.decode(elename, typename) o.definedtype = typedef return o when :TYPE_ARRAY expected_arytype = typedef.find_arytype if arytypestr actual_arytype = XSD::QName.new(expected_arytype.namespace, content_typename(expected_arytype.name) << content_ranksize(arytypestr)) o = SOAPArray.decode(elename, typename, actual_arytype) else o = SOAPArray.new(typename, 1, expected_arytype) o.elename = elename end o.definedtype = typedef return o when :TYPE_EMPTY o = SOAPNil.decode(elename) o.definedtype = typedef return o else raise RuntimeError.new( "Unknown kind of complexType: #{typedef.compoundtype}") end nil end def decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) if arytypestr type = typestr ? ns.parse(typestr) : ValueArrayName node = SOAPArray.decode(elename, type, ns.parse(arytypestr)) node.extraattr.update(extraattr) return node end type = nil if typestr type = ns.parse(typestr) elsif parent.is_a?(SOAPArray) type = parent.arytype else # Since it's in dynamic(without any type) encoding process, # assumes entity as its type itself. # <SOAP-ENC:Array ...> => type Array in SOAP-ENC. # <Country xmlns="foo"> => type Country in foo. type = elename end if (klass = TypeMap[type]) node = decode_basetype(klass, elename) node.extraattr.update(extraattr) return node end # Unknown type... Struct or String SOAPUnknown.new(self, elename, type, extraattr) end def decode_textbuf(node) case node when XSD::XSDHexBinary, XSD::XSDBase64Binary node.set_encoded(@textbuf) when XSD::XSDString if @charset @textbuf = XSD::Charset.encoding_from_xml(@textbuf, @charset) end if node.definedtype node.definedtype.check_lexical_format(@textbuf) end node.set(@textbuf) when SOAPNil # Nothing to do. when SOAPBasetype node.set(@textbuf) else # Nothing to do... end @textbuf = '' end NilLiteralMap = { 'true' => true, '1' => true, 'false' => false, '0' => false } RootLiteralMap = { '1' => 1, '0' => 0 } def decode_attrs(ns, attrs) is_nil = false type = nil arytype = nil root = nil offset = nil position = nil href = nil id = nil extraattr = {} attrs.each do |key, value| qname = ns.parse(key) case qname.namespace when XSD::InstanceNamespace case qname.name when XSD::NilLiteral is_nil = NilLiteralMap[value] or raise EncodingStyleError.new("cannot accept attribute value: #{value} as the value of xsi:#{XSD::NilLiteral} (expected 'true', 'false', '1', or '0')") next when XSD::AttrType type = value next end when EncodingNamespace case qname.name when AttrArrayType arytype = value next when AttrRoot root = RootLiteralMap[value] or raise EncodingStyleError.new( "illegal root attribute value: #{value}") next when AttrOffset offset = value next when AttrPosition position = value next end end if key == 'href' href = value next elsif key == 'id' id = value next end qname = ns.parse_local(key) extraattr[qname] = decode_attr_value(ns, qname, value) end return is_nil, type, arytype, root, offset, position, href, id, extraattr end def decode_attr_value(ns, qname, value) if /\A#/ =~ value o = SOAPReference.decode(nil, value) @refpool << o o else value end end def decode_arypos(position) /^\[(.+)\]$/ =~ position $1.split(',').collect { |s| s.to_i } end def decode_resolve_id count = @refpool.length # To avoid infinite loop while !@refpool.empty? && count > 0 @refpool = @refpool.find_all { |ref| o = @idpool.find { |item| item.id == ref.refid } if o.is_a?(SOAPReference) true # link of link. elsif o ref.__setobj__(o) false elsif o = ref.rootnode.external_content[ref.refid] ref.__setobj__(o) false else raise EncodingStyleError.new("unresolved reference: #{ref.refid}") end } count -= 1 end end end SOAPHandler.new end end
jeffmccune/gocd
tools/jruby-1.7.11/lib/ruby/1.8/soap/encodingstyle/soapHandler.rb
Ruby
apache-2.0
14,675
var assert = require('assert'); var Traverse = require('traverse'); var util = require('util'); exports.circular = function () { var obj = { x : 3 }; obj.y = obj; var foundY = false; Traverse(obj).forEach(function (x) { if (this.path.join('') == 'y') { assert.equal( util.inspect(this.circular.node), util.inspect(obj) ); foundY = true; } }); assert.ok(foundY); }; exports.deepCirc = function () { var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; obj.y[2] = obj; var times = 0; Traverse(obj).forEach(function (x) { if (this.circular) { assert.deepEqual(this.circular.path, []); assert.deepEqual(this.path, [ 'y', 2 ]); times ++; } }); assert.deepEqual(times, 1); }; exports.doubleCirc = function () { var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; obj.y[2] = obj; obj.x.push(obj.y); var circs = []; Traverse(obj).forEach(function (x) { if (this.circular) { circs.push({ circ : this.circular, self : this, node : x }); } }); assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]); assert.deepEqual(circs[0].circ.path, []); assert.deepEqual(circs[1].self.path, [ 'y', 2 ]); assert.deepEqual(circs[1].circ.path, []); assert.deepEqual(circs.length, 2); }; exports.circDubForEach = function () { var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; obj.y[2] = obj; obj.x.push(obj.y); Traverse(obj).forEach(function (x) { if (this.circular) this.update('...'); }); assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); }; exports.circDubMap = function () { var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; obj.y[2] = obj; obj.x.push(obj.y); var c = Traverse(obj).map(function (x) { if (this.circular) { this.update('...'); } }); assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); }; exports.circClone = function () { var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; obj.y[2] = obj; obj.x.push(obj.y); var clone = Traverse.clone(obj); assert.ok(obj !== clone); assert.ok(clone.y[2] === clone); assert.ok(clone.y[2] !== obj); assert.ok(clone.x[3][2] === clone); assert.ok(clone.x[3][2] !== obj); assert.deepEqual(clone.x.slice(0,3), [1,2,3]); assert.deepEqual(clone.y.slice(0,2), [4,5]); }; exports.circMapScrub = function () { var obj = { a : 1, b : 2 }; obj.c = obj; var scrubbed = Traverse(obj).map(function (node) { if (this.circular) this.remove(); }); assert.deepEqual( Object.keys(scrubbed).sort(), [ 'a', 'b' ] ); assert.ok(Traverse.deepEqual(scrubbed, { a : 1, b : 2 })); assert.equal(obj.c, obj); };
ProxyPrint/proxyprint-kitchen
scripts/node_modules/ngrok/node_modules/decompress-zip/node_modules/binary/node_modules/chainsaw/node_modules/traverse/test/circular.js
JavaScript
apache-2.0
2,952
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. function OptionLocatorTest(name) { TestCase.call(this,name); } OptionLocatorTest.prototype = new TestCase(); OptionLocatorTest.prototype.setUp = function() { this.mockSelect = {}; this.mockSelect.options = [{text: "Option Zero", value: "option0"}, {text: "Option One", value: "option1"}, {text: "Option Two", value: "option2"}, {text: "", value: ""}]; this.mockSelect.selectedIndex = 1; this.optionLocatorFactory = new OptionLocatorFactory(); } OptionLocatorTest.prototype.testSample = function() { this.assertTrue(true); } OptionLocatorTest.prototype.testSelectByIndexSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("index=2"); var option = locator.findOption(this.mockSelect); this.assertEquals("option2", option.value); } OptionLocatorTest.prototype.testSelectByIndexOutOfBounds = function() { var locator = this.optionLocatorFactory.fromLocatorString("index=" + this.mockSelect.options.length); this.assertCallFails("Should not be able to find an option out of bounds", function() {locator.findOption(this.mockSelect);}); } OptionLocatorTest.prototype.testSelectByLabelSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("label=Opt*Two"); var option = locator.findOption(this.mockSelect); this.assertEquals("option2", option.value); } OptionLocatorTest.prototype.testSelectByLabelFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("label=nosuchlabel"); this.assertCallFails( "Should not be able to find an option with label of 'nosuchlabel'", function() {locator.findOption(this.mockSelect);}); } OptionLocatorTest.prototype.testSelectByValueSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("value=opt*2"); var option = locator.findOption(this.mockSelect); this.assertEquals("option2", option.value); } OptionLocatorTest.prototype.testSelectByValueFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("value=nosuchvalue"); this.assertCallFails( "Should not be able to find an option with label of 'nosuchvalue'", function() {locator.findOption(this.mockSelect);}); } OptionLocatorTest.prototype.testIsSelectedByLabelSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("label=Option One"); locator.assertSelected(this.mockSelect); } OptionLocatorTest.prototype.testIsSelectedByLabelFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("label=O*ion Two"); try { locator.assertSelected(this.mockSelect); this.fail(); } catch (e){} } OptionLocatorTest.prototype.testIsSelectedByValueSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("value=opt*n1"); locator.assertSelected(this.mockSelect); } OptionLocatorTest.prototype.testIsSelectedByValueFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("value=option2"); try { locator.assertSelected(this.mockSelect); this.fail(); } catch (e){} } OptionLocatorTest.prototype.testIsSelectedByIndexSuccess = function() { var locator = this.optionLocatorFactory.fromLocatorString("index=1"); locator.assertSelected(this.mockSelect); } OptionLocatorTest.prototype.testIsSelectedByIndexFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("index=2"); try { locator.assertSelected(this.mockSelect); this.fail(); } catch (e){} } OptionLocatorTest.prototype.testIsSelectedByEmptyLabelSuccess = function() { this.mockSelect.selectedIndex = 3; var locator = this.optionLocatorFactory.fromLocatorString("label="); locator.assertSelected(this.mockSelect); } OptionLocatorTest.prototype.testIsSelectedByEmptyLabelFailure = function() { var locator = this.optionLocatorFactory.fromLocatorString("label="); try { locator.assertSelected(this.mockSelect); this.fail(); } catch (e){} } OptionLocatorTest.prototype.testIsSelectedWithIndexOutOfBounds = function() { var locator = this.optionLocatorFactory.fromLocatorString("index=" + this.mockSelect.options.length); try { locator.assertSelected(this.mockSelect); this.fail(); } catch (e){} } OptionLocatorTest.prototype.testOptionLocatorWithBadLocatorType = function() { var self = this; this.assertCallFails( "Should not be able to create a locator with an unkown type", function() {self.optionLocatorFactory.fromLocatorString("badtype=foo");}); } OptionLocatorTest.prototype.testOptionLocatorWithBadIndex = function() { var self = this; this.assertCallFails( "Should not be able to create a locator with a bad index.", function() {self.optionLocatorFactory.fromLocatorString("index=foo");}); } OptionLocatorTest.prototype.testOptionLocatorWithNegativeIndex = function() { var self = this; this.assertCallFails( "Should not be able to create a locator with a bad index.", function() {self.optionLocatorFactory.fromLocatorString("index=-100");}); } OptionLocatorTest.prototype.assertCallFails = function(message, theCall, expectedFailureMessage) { try { theCall(); } catch (expected) { if (expectedFailureMessage) { this.assertEquals(expectedFailureMessage, e.failureMessage); } return; } this.fail(message); } OptionLocatorTest.prototype.assertAssertionFails = function(message, theCall, expectedFailureMessage) { try { theCall(); } catch (e) { if (!e.isAssertionFailedError) { throw e; } if (expectedFailureMessage) { this.assertEquals(expectedFailureMessage, e.failureMessage); } return; } this.fail(message); }
amikey/selenium
javascript/selenium-core/test/OptionLocatorTest.js
JavaScript
apache-2.0
6,801
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode.ha; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.google.common.base.Objects; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.HAUtil; import org.apache.hadoop.hdfs.server.namenode.NameNode; import com.google.common.base.Preconditions; /** * Information about a single remote NameNode */ public class RemoteNameNodeInfo { public static List<RemoteNameNodeInfo> getRemoteNameNodes(Configuration conf) throws IOException { String nsId = DFSUtil.getNamenodeNameServiceId(conf); return getRemoteNameNodes(conf, nsId); } public static List<RemoteNameNodeInfo> getRemoteNameNodes(Configuration conf, String nsId) throws IOException { // there is only a single NN configured (and no federation) so we don't have any more NNs if (nsId == null) { return Collections.emptyList(); } List<Configuration> otherNodes = HAUtil.getConfForOtherNodes(conf); List<RemoteNameNodeInfo> nns = new ArrayList<RemoteNameNodeInfo>(); for (Configuration otherNode : otherNodes) { String otherNNId = HAUtil.getNameNodeId(otherNode, nsId); // don't do any validation here as in some cases, it can be overwritten later InetSocketAddress otherIpcAddr = NameNode.getServiceAddress(otherNode, true); final String scheme = DFSUtil.getHttpClientScheme(conf); URL otherHttpAddr = DFSUtil.getInfoServerWithDefaultHost(otherIpcAddr.getHostName(), otherNode, scheme).toURL(); nns.add(new RemoteNameNodeInfo(otherNode, otherNNId, otherIpcAddr, otherHttpAddr)); } return nns; } private final Configuration conf; private final String nnId; private InetSocketAddress ipcAddress; private final URL httpAddress; private RemoteNameNodeInfo(Configuration conf, String nnId, InetSocketAddress ipcAddress, URL httpAddress) { this.conf = conf; this.nnId = nnId; this.ipcAddress = ipcAddress; this.httpAddress = httpAddress; } public InetSocketAddress getIpcAddress() { return this.ipcAddress; } public String getNameNodeID() { return this.nnId; } public URL getHttpAddress() { return this.httpAddress; } public Configuration getConfiguration() { return this.conf; } public void setIpcAddress(InetSocketAddress ipc) { this.ipcAddress = ipc; } @Override public String toString() { return "RemoteNameNodeInfo [nnId=" + nnId + ", ipcAddress=" + ipcAddress + ", httpAddress=" + httpAddress + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteNameNodeInfo that = (RemoteNameNodeInfo) o; if (!nnId.equals(that.nnId)) return false; if (!ipcAddress.equals(that.ipcAddress)) return false; // convert to the standard strings since URL.equals does address resolution, which is a // blocking call and a a FindBugs issue. String httpString = httpAddress.toString(); String thatHttpString = that.httpAddress.toString(); return httpString.equals(thatHttpString); } @Override public int hashCode() { int result = nnId.hashCode(); result = 31 * result + ipcAddress.hashCode(); // toString rather than hashCode b/c Url.hashCode is a blocking call. result = 31 * result + httpAddress.toString().hashCode(); return result; } }
EasonYi/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RemoteNameNodeInfo.java
Java
apache-2.0
4,394
// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com> // All rights reservefs. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package storage import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "time" "github.com/syndtr/goleveldb/leveldb/util" ) var errFileOpen = errors.New("leveldb/storage: file still open") type fileLock interface { release() error } type fileStorageLock struct { fs *fileStorage } func (lock *fileStorageLock) Release() { fs := lock.fs fs.mu.Lock() defer fs.mu.Unlock() if fs.slock == lock { fs.slock = nil } return } // fileStorage is a file-system backed storage. type fileStorage struct { path string mu sync.Mutex flock fileLock slock *fileStorageLock logw *os.File buf []byte // Opened file counter; if open < 0 means closed. open int day int } // OpenFile returns a new filesytem-backed storage implementation with the given // path. This also hold a file lock, so any subsequent attempt to open the same // path will fail. // // The storage must be closed after use, by calling Close method. func OpenFile(path string) (Storage, error) { if err := os.MkdirAll(path, 0755); err != nil { return nil, err } flock, err := newFileLock(filepath.Join(path, "LOCK")) if err != nil { return nil, err } defer func() { if err != nil { flock.release() } }() rename(filepath.Join(path, "LOG"), filepath.Join(path, "LOG.old")) logw, err := os.OpenFile(filepath.Join(path, "LOG"), os.O_WRONLY|os.O_CREATE, 0644) if err != nil { return nil, err } fs := &fileStorage{path: path, flock: flock, logw: logw} runtime.SetFinalizer(fs, (*fileStorage).Close) return fs, nil } func (fs *fileStorage) Lock() (util.Releaser, error) { fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return nil, ErrClosed } if fs.slock != nil { return nil, ErrLocked } fs.slock = &fileStorageLock{fs: fs} return fs.slock, nil } func itoa(buf []byte, i int, wid int) []byte { var u uint = uint(i) if u == 0 && wid <= 1 { return append(buf, '0') } // Assemble decimal in reverse order. var b [32]byte bp := len(b) for ; u > 0 || wid > 0; u /= 10 { bp-- wid-- b[bp] = byte(u%10) + '0' } return append(buf, b[bp:]...) } func (fs *fileStorage) printDay(t time.Time) { if fs.day == t.Day() { return } fs.day = t.Day() fs.logw.Write([]byte("=============== " + t.Format("Jan 2, 2006 (MST)") + " ===============\n")) } func (fs *fileStorage) doLog(t time.Time, str string) { fs.printDay(t) hour, min, sec := t.Clock() msec := t.Nanosecond() / 1e3 // time fs.buf = itoa(fs.buf[:0], hour, 2) fs.buf = append(fs.buf, ':') fs.buf = itoa(fs.buf, min, 2) fs.buf = append(fs.buf, ':') fs.buf = itoa(fs.buf, sec, 2) fs.buf = append(fs.buf, '.') fs.buf = itoa(fs.buf, msec, 6) fs.buf = append(fs.buf, ' ') // write fs.buf = append(fs.buf, []byte(str)...) fs.buf = append(fs.buf, '\n') fs.logw.Write(fs.buf) } func (fs *fileStorage) Log(str string) { t := time.Now() fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return } fs.doLog(t, str) } func (fs *fileStorage) log(str string) { fs.doLog(time.Now(), str) } func (fs *fileStorage) GetFile(num uint64, t FileType) File { return &file{fs: fs, num: num, t: t} } func (fs *fileStorage) GetFiles(t FileType) (ff []File, err error) { fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return nil, ErrClosed } dir, err := os.Open(fs.path) if err != nil { return } fnn, err := dir.Readdirnames(0) // Close the dir first before checking for Readdirnames error. if err := dir.Close(); err != nil { fs.log(fmt.Sprintf("close dir: %v", err)) } if err != nil { return } f := &file{fs: fs} for _, fn := range fnn { if f.parse(fn) && (f.t&t) != 0 { ff = append(ff, f) f = &file{fs: fs} } } return } func (fs *fileStorage) GetManifest() (f File, err error) { fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return nil, ErrClosed } dir, err := os.Open(fs.path) if err != nil { return } fnn, err := dir.Readdirnames(0) // Close the dir first before checking for Readdirnames error. if err := dir.Close(); err != nil { fs.log(fmt.Sprintf("close dir: %v", err)) } if err != nil { return } // Find latest CURRENT file. var rem []string var pend bool var cerr error for _, fn := range fnn { if strings.HasPrefix(fn, "CURRENT") { pend1 := len(fn) > 7 // Make sure it is valid name for a CURRENT file, otherwise skip it. if pend1 { if fn[7] != '.' || len(fn) < 9 { fs.log(fmt.Sprintf("skipping %s: invalid file name", fn)) continue } if _, e1 := strconv.ParseUint(fn[8:], 10, 0); e1 != nil { fs.log(fmt.Sprintf("skipping %s: invalid file num: %v", fn, e1)) continue } } path := filepath.Join(fs.path, fn) r, e1 := os.OpenFile(path, os.O_RDONLY, 0) if e1 != nil { return nil, e1 } b, e1 := ioutil.ReadAll(r) if e1 != nil { r.Close() return nil, e1 } f1 := &file{fs: fs} if len(b) < 1 || b[len(b)-1] != '\n' || !f1.parse(string(b[:len(b)-1])) { fs.log(fmt.Sprintf("skipping %s: corrupted or incomplete", fn)) if pend1 { rem = append(rem, fn) } if !pend1 || cerr == nil { cerr = fmt.Errorf("leveldb/storage: corrupted or incomplete %s file", fn) } } else if f != nil && f1.Num() < f.Num() { fs.log(fmt.Sprintf("skipping %s: obsolete", fn)) if pend1 { rem = append(rem, fn) } } else { f = f1 pend = pend1 } if err := r.Close(); err != nil { fs.log(fmt.Sprintf("close %s: %v", fn, err)) } } } // Don't remove any files if there is no valid CURRENT file. if f == nil { if cerr != nil { err = cerr } else { err = os.ErrNotExist } return } // Rename pending CURRENT file to an effective CURRENT. if pend { path := fmt.Sprintf("%s.%d", filepath.Join(fs.path, "CURRENT"), f.Num()) if err := rename(path, filepath.Join(fs.path, "CURRENT")); err != nil { fs.log(fmt.Sprintf("CURRENT.%d -> CURRENT: %v", f.Num(), err)) } } // Remove obsolete or incomplete pending CURRENT files. for _, fn := range rem { path := filepath.Join(fs.path, fn) if err := os.Remove(path); err != nil { fs.log(fmt.Sprintf("remove %s: %v", fn, err)) } } return } func (fs *fileStorage) SetManifest(f File) (err error) { fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return ErrClosed } f2, ok := f.(*file) if !ok || f2.t != TypeManifest { return ErrInvalidFile } defer func() { if err != nil { fs.log(fmt.Sprintf("CURRENT: %v", err)) } }() path := fmt.Sprintf("%s.%d", filepath.Join(fs.path, "CURRENT"), f2.Num()) w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return err } _, err = fmt.Fprintln(w, f2.name()) // Close the file first. if err := w.Close(); err != nil { fs.log(fmt.Sprintf("close CURRENT.%d: %v", f2.num, err)) } if err != nil { return err } return rename(path, filepath.Join(fs.path, "CURRENT")) } func (fs *fileStorage) Close() error { fs.mu.Lock() defer fs.mu.Unlock() if fs.open < 0 { return ErrClosed } // Clear the finalizer. runtime.SetFinalizer(fs, nil) if fs.open > 0 { fs.log(fmt.Sprintf("refuse to close, %d files still open", fs.open)) return fmt.Errorf("leveldb/storage: cannot close, %d files still open", fs.open) } fs.open = -1 e1 := fs.logw.Close() err := fs.flock.release() if err == nil { err = e1 } return err } type fileWrap struct { *os.File f *file } func (fw fileWrap) Sync() error { if err := fw.File.Sync(); err != nil { return err } if fw.f.Type() == TypeManifest { // Also sync parent directory if file type is manifest. // See: https://code.google.com/p/leveldb/issues/detail?id=190. if err := syncDir(fw.f.fs.path); err != nil { return err } } return nil } func (fw fileWrap) Close() error { f := fw.f f.fs.mu.Lock() defer f.fs.mu.Unlock() if !f.open { return ErrClosed } f.open = false f.fs.open-- err := fw.File.Close() if err != nil { f.fs.log(fmt.Sprintf("close %s.%d: %v", f.Type(), f.Num(), err)) } return err } type file struct { fs *fileStorage num uint64 t FileType open bool } func (f *file) Open() (Reader, error) { f.fs.mu.Lock() defer f.fs.mu.Unlock() if f.fs.open < 0 { return nil, ErrClosed } if f.open { return nil, errFileOpen } of, err := os.OpenFile(f.path(), os.O_RDONLY, 0) if err != nil { if f.hasOldName() && os.IsNotExist(err) { of, err = os.OpenFile(f.oldPath(), os.O_RDONLY, 0) if err == nil { goto ok } } return nil, err } ok: f.open = true f.fs.open++ return fileWrap{of, f}, nil } func (f *file) Create() (Writer, error) { f.fs.mu.Lock() defer f.fs.mu.Unlock() if f.fs.open < 0 { return nil, ErrClosed } if f.open { return nil, errFileOpen } of, err := os.OpenFile(f.path(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return nil, err } f.open = true f.fs.open++ return fileWrap{of, f}, nil } func (f *file) Replace(newfile File) error { f.fs.mu.Lock() defer f.fs.mu.Unlock() if f.fs.open < 0 { return ErrClosed } newfile2, ok := newfile.(*file) if !ok { return ErrInvalidFile } if f.open || newfile2.open { return errFileOpen } return rename(newfile2.path(), f.path()) } func (f *file) Type() FileType { return f.t } func (f *file) Num() uint64 { return f.num } func (f *file) Remove() error { f.fs.mu.Lock() defer f.fs.mu.Unlock() if f.fs.open < 0 { return ErrClosed } if f.open { return errFileOpen } err := os.Remove(f.path()) if err != nil { f.fs.log(fmt.Sprintf("remove %s.%d: %v", f.Type(), f.Num(), err)) } // Also try remove file with old name, just in case. if f.hasOldName() { if e1 := os.Remove(f.oldPath()); !os.IsNotExist(e1) { f.fs.log(fmt.Sprintf("remove %s.%d: %v (old name)", f.Type(), f.Num(), err)) err = e1 } } return err } func (f *file) hasOldName() bool { return f.t == TypeTable } func (f *file) oldName() string { switch f.t { case TypeTable: return fmt.Sprintf("%06d.sst", f.num) } return f.name() } func (f *file) oldPath() string { return filepath.Join(f.fs.path, f.oldName()) } func (f *file) name() string { switch f.t { case TypeManifest: return fmt.Sprintf("MANIFEST-%06d", f.num) case TypeJournal: return fmt.Sprintf("%06d.log", f.num) case TypeTable: return fmt.Sprintf("%06d.ldb", f.num) case TypeTemp: return fmt.Sprintf("%06d.tmp", f.num) default: panic("invalid file type") } } func (f *file) path() string { return filepath.Join(f.fs.path, f.name()) } func (f *file) parse(name string) bool { var num uint64 var tail string _, err := fmt.Sscanf(name, "%d.%s", &num, &tail) if err == nil { switch tail { case "log": f.t = TypeJournal case "ldb", "sst": f.t = TypeTable case "tmp": f.t = TypeTemp default: return false } f.num = num return true } n, _ := fmt.Sscanf(name, "MANIFEST-%d%s", &num, &tail) if n == 1 { f.t = TypeManifest f.num = num return true } return false }
hustbill/prometheus
Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go
GO
apache-2.0
11,132
var baseIsEqual = require('../internal/baseIsEqual'), bindCallback = require('../internal/bindCallback'); /** * Performs a deep comparison between two values to determine if they are * equivalent. If `customizer` is provided it's invoked to compare values. * If `customizer` returns `undefined` comparisons are handled by the method * instead. The `customizer` is bound to `thisArg` and invoked with up to * three arguments: (value, other [, index|key]). * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. Functions and DOM nodes * are **not** supported. Provide a customizer function to extend support * for comparing other values. * * @static * @memberOf _ * @alias eq * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * object == other; * // => false * * _.isEqual(object, other); * // => true * * // using a customizer callback * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqual(array, other, function(value, other) { * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { * return true; * } * }); * // => true */ function isEqual(value, other, customizer, thisArg) { customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } module.exports = isEqual;
eric-dum/behance-api-template
node_modules/gulp-less/node_modules/accord/node_modules/lodash/lang/isEqual.js
JavaScript
apache-2.0
1,965
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.web; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.ImageReader; import com.google.zxing.common.GlobalHistogramBinarizer; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.multi.GenericMultipleBarcodeReader; import com.google.zxing.multi.MultipleBarcodeReader; import com.google.common.io.Resources; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; /** * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will * retrieve the image and decode it. It can also process image files uploaded via POST. * * @author Sean Owen */ @MultipartConfig( maxFileSize = 10_000_000, maxRequestSize = 10_000_000, fileSizeThreshold = 1_000_000, location = "/tmp") @WebServlet(value = "/w/decode", loadOnStartup = 1) public final class DecodeServlet extends HttpServlet { private static final Logger log = Logger.getLogger(DecodeServlet.class.getName()); // No real reason to let people upload more than a 10MB image private static final long MAX_IMAGE_SIZE = 10_000_000L; // No real reason to deal with more than maybe 10 megapixels private static final int MAX_PIXELS = 10_000_000; private static final byte[] REMAINDER_BUFFER = new byte[32768]; private static final Map<DecodeHintType,Object> HINTS; private static final Map<DecodeHintType,Object> HINTS_PURE; static { HINTS = new EnumMap<>(DecodeHintType.class); HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class)); HINTS_PURE = new EnumMap<>(HINTS); HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); } private Iterable<String> blockedURLSubstrings; @Override public void init(ServletConfig servletConfig) throws ServletException { Logger logger = Logger.getLogger("com.google.zxing"); ServletContext context = servletConfig.getServletContext(); logger.addHandler(new ServletContextLogHandler(context)); URL blockURL = context.getClassLoader().getResource("/private/uri-block-substrings.txt"); if (blockURL == null) { blockedURLSubstrings = Collections.emptyList(); } else { try { blockedURLSubstrings = Resources.readLines(blockURL, StandardCharsets.UTF_8); } catch (IOException ioe) { throw new ServletException(ioe); } log.info("Blocking URIs containing: " + blockedURLSubstrings); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.isEmpty()) { log.info("URI was empty"); errorResponse(request, response, "badurl"); return; } imageURIString = imageURIString.trim(); for (CharSequence substring : blockedURLSubstrings) { if (imageURIString.contains(substring)) { log.info("Disallowed URI " + imageURIString); errorResponse(request, response, "badurl"); return; } } URI imageURI; try { imageURI = new URI(imageURIString); // Assume http: if not specified if (imageURI.getScheme() == null) { imageURI = new URI("http://" + imageURIString); } } catch (URISyntaxException urise) { log.info("URI " + imageURIString + " was not valid: " + urise); errorResponse(request, response, "badurl"); return; } // Shortcut for data URI if ("data".equals(imageURI.getScheme())) { try { BufferedImage image = ImageReader.readDataURIImage(imageURI); processImage(image, request, response); } catch (IOException ioe) { log.info(ioe.toString()); errorResponse(request, response, "badurl"); } return; } URL imageURL; try { imageURL = imageURI.toURL(); } catch (MalformedURLException ignored) { log.info("URI was not valid: " + imageURIString); errorResponse(request, response, "badurl"); return; } String protocol = imageURL.getProtocol(); if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) { log.info("URI was not valid: " + imageURIString); errorResponse(request, response, "badurl"); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) imageURL.openConnection(); } catch (IllegalArgumentException ignored) { log.info("URI could not be opened: " + imageURL); errorResponse(request, response, "badurl"); return; } connection.setAllowUserInteraction(false); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestProperty(HttpHeaders.USER_AGENT, "zxing.org"); connection.setRequestProperty(HttpHeaders.CONNECTION, "close"); try { connection.connect(); } catch (IOException | IllegalArgumentException e) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.info(e.toString()); errorResponse(request, response, "badurl"); return; } try (InputStream is = connection.getInputStream()) { try { if (connection.getResponseCode() != HttpServletResponse.SC_OK) { log.info("Unsuccessful return code: " + connection.getResponseCode()); errorResponse(request, response, "badurl"); return; } if (connection.getHeaderFieldInt(HttpHeaders.CONTENT_LENGTH, 0) > MAX_IMAGE_SIZE) { log.info("Too large"); errorResponse(request, response, "badimage"); return; } log.info("Decoding " + imageURL); processStream(is, request, response); } finally { consumeRemainder(is); } } catch (IOException ioe) { log.info(ioe.toString()); errorResponse(request, response, "badurl"); } finally { connection.disconnect(); } } private static void consumeRemainder(InputStream is) { try { int available; while ((available = is.available()) > 0) { is.read(REMAINDER_BUFFER, 0, available); // don't care about value, or collision } } catch (IOException | IndexOutOfBoundsException ioe) { // sun.net.www.http.ChunkedInputStream.read is throwing IndexOutOfBoundsException // continue } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection<Part> parts; try { parts = request.getParts(); } catch (IllegalStateException ise) { log.info("File upload was too large or invalid"); errorResponse(request, response, "badimage"); return; } catch (IOException ioe) { log.info(ioe.toString()); errorResponse(request, response, "badurl"); return; } Part fileUploadPart = null; for (Part part : parts) { if (part.getHeader(HttpHeaders.CONTENT_DISPOSITION) != null) { fileUploadPart = part; break; } } if (fileUploadPart == null) { log.info("File upload was not multipart"); errorResponse(request, response, "badimage"); } else { log.info("Decoding uploaded file"); try (InputStream is = fileUploadPart.getInputStream()) { processStream(is, request, response); } } } private static void processStream(InputStream is, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException | CMMException | IllegalArgumentException ioe) { log.info(ioe.toString()); // Have seen these in some logs errorResponse(request, response, "badimage"); return; } if (image == null) { errorResponse(request, response, "badimage"); return; } if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.info("Dimensions out of bounds: " + image.getWidth() + 'x' + image.getHeight()); errorResponse(request, response, "badimage"); return; } processImage(image, request, response); } private static void processImage(BufferedImage image, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<>(1); try { Reader reader = new MultiFormatReader(); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { throw savedException == null ? NotFoundException.getNotFoundInstance() : savedException; } catch (FormatException | ChecksumException e) { log.info(e.getMessage()); errorResponse(request, response, "format"); } catch (ReaderException e) { // Including NotFoundException log.info(e.getMessage()); errorResponse(request, response, "notfound"); } return; } } catch (RuntimeException re) { // Call out unexpected errors in the log clearly log.log(Level.WARNING, "Unexpected exception from library", re); throw new ServletException(re); } String fullParameter = request.getParameter("full"); boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter); if (minimalOutput) { response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } } private static void errorResponse(HttpServletRequest request, HttpServletResponse response, String key) throws ServletException, IOException { Locale locale = request.getLocale(); if (locale == null) { locale = Locale.ENGLISH; } ResourceBundle bundle = ResourceBundle.getBundle("Strings", locale); String title = bundle.getString("response.error." + key + ".title"); String text = bundle.getString("response.error." + key + ".text"); request.setAttribute("title", title); request.setAttribute("text", text); request.getRequestDispatcher("response.jspx").forward(request, response); } }
eight-pack-abdominals/ZXing
zxingorg/src/main/java/com/google/zxing/web/DecodeServlet.java
Java
apache-2.0
14,859
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; import java.util.Objects; /** * Named analyzer is an analyzer wrapper around an actual analyzer ({@link #analyzer} that is associated * with a name ({@link #name()}. */ public class NamedAnalyzer extends DelegatingAnalyzerWrapper { private final String name; private final AnalyzerScope scope; private final Analyzer analyzer; private final int positionIncrementGap; public NamedAnalyzer(NamedAnalyzer analyzer, int positionIncrementGap) { this(analyzer.name(), analyzer.scope(), analyzer.analyzer(), positionIncrementGap); } public NamedAnalyzer(String name, Analyzer analyzer) { this(name, AnalyzerScope.INDEX, analyzer); } public NamedAnalyzer(String name, AnalyzerScope scope, Analyzer analyzer) { this(name, scope, analyzer, Integer.MIN_VALUE); } public NamedAnalyzer(String name, AnalyzerScope scope, Analyzer analyzer, int positionIncrementGap) { super(ERROR_STRATEGY); this.name = name; this.scope = scope; this.analyzer = analyzer; this.positionIncrementGap = positionIncrementGap; } /** * The name of the analyzer. */ public String name() { return this.name; } /** * The scope of the analyzer. */ public AnalyzerScope scope() { return this.scope; } /** * The actual analyzer. */ public Analyzer analyzer() { return this.analyzer; } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { return this.analyzer; } @Override public int getPositionIncrementGap(String fieldName) { if (positionIncrementGap != Integer.MIN_VALUE) { return positionIncrementGap; } return super.getPositionIncrementGap(fieldName); } @Override public String toString() { return "analyzer name[" + name + "], analyzer [" + analyzer + "]"; } /** It is an error if this is ever used, it means we screwed up! */ static final ReuseStrategy ERROR_STRATEGY = new Analyzer.ReuseStrategy() { @Override public TokenStreamComponents getReusableComponents(Analyzer a, String f) { throw new IllegalStateException("NamedAnalyzer cannot be wrapped with a wrapper, only a delegator"); } @Override public void setReusableComponents(Analyzer a, String f, TokenStreamComponents c) { throw new IllegalStateException("NamedAnalyzer cannot be wrapped with a wrapper, only a delegator"); } }; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NamedAnalyzer)) return false; NamedAnalyzer that = (NamedAnalyzer) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } }
jango2015/elasticsearch
core/src/main/java/org/elasticsearch/index/analysis/NamedAnalyzer.java
Java
apache-2.0
3,834
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.rss; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class RssHttpNoCamelParametersTest extends CamelTestSupport { @Test public void testRssHttpNoCamelParameters() throws Exception { RssEndpoint rss = context.getEndpoint("rss://http://www.iafrica.com/pls/cms/grapevine.xml?sortEntries=true&feedHeader=true", RssEndpoint.class); assertNotNull(rss); assertEquals("http://www.iafrica.com/pls/cms/grapevine.xml", rss.getFeedUri()); assertEquals(true, rss.isFeedHeader()); assertEquals(true, rss.isSortEntries()); } @Test public void testRssHttpNoCamelParametersAndOneFeedParameter() throws Exception { RssEndpoint rss = context.getEndpoint("rss://http://www.iafrica.com/pls/cms/grapevine.xml?sortEntries=true&feedHeader=true&foo=bar", RssEndpoint.class); assertNotNull(rss); assertEquals("http://www.iafrica.com/pls/cms/grapevine.xml?foo=bar", rss.getFeedUri()); assertEquals(true, rss.isFeedHeader()); assertEquals(true, rss.isSortEntries()); } }
arnaud-deprez/camel
components/camel-rss/src/test/java/org/apache/camel/component/rss/RssHttpNoCamelParametersTest.java
Java
apache-2.0
1,930
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.printer; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Locale; import java.util.UUID; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.Copies; import javax.print.attribute.standard.JobName; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.Sides; import org.apache.camel.util.IOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PrinterOperations implements PrinterOperationsInterface { private static final Logger LOG = LoggerFactory.getLogger(PrinterOperations.class); private PrintService printService; private DocFlavor flavor; private PrintRequestAttributeSet printRequestAttributeSet; private Doc doc; public PrinterOperations() throws PrintException { printService = PrintServiceLookup.lookupDefaultPrintService(); if (printService == null) { throw new PrintException("Printer lookup failure. No default printer set up for this host"); } flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE; printRequestAttributeSet = new HashPrintRequestAttributeSet(); printRequestAttributeSet.add(new Copies(1)); printRequestAttributeSet.add(MediaSizeName.NA_LETTER); printRequestAttributeSet.add(Sides.ONE_SIDED); } public PrinterOperations(PrintService printService, DocFlavor flavor, PrintRequestAttributeSet printRequestAttributeSet) throws PrintException { this.setPrintService(printService); this.setFlavor(flavor); this.setPrintRequestAttributeSet(printRequestAttributeSet); } public void print(Doc doc, int copies, boolean sendToPrinter, String mimeType, String jobName) throws PrintException { LOG.trace("Print Service: " + this.printService.getName()); LOG.trace("About to print " + copies + " copy(s)"); for (int i = 0; i < copies; i++) { if (!sendToPrinter) { LOG.debug("Print flag is set to false. This job will not be printed until this setting remains in effect." + " Please set the flag to true or remove the setting."); File file; if (mimeType.equalsIgnoreCase("GIF") || mimeType.equalsIgnoreCase("RENDERABLE_IMAGE")) { file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".gif"); } else if (mimeType.equalsIgnoreCase("JPEG")) { file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".jpeg"); } else if (mimeType.equalsIgnoreCase("PDF")) { file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".pdf"); } else { file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".txt"); } LOG.debug("Writing print job to file: " + file.getAbsolutePath()); try { InputStream in = doc.getStreamForBytes(); FileOutputStream fos = new FileOutputStream(file); IOHelper.copyAndCloseInput(in, fos); IOHelper.close(fos); } catch (Exception e) { throw new PrintException("Error writing Document to the target file " + file.getAbsolutePath()); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Issuing Job {} to Printer: {}", i, this.printService.getName()); } print(doc, jobName); } } } public void print(Doc doc, String jobName) throws PrintException { // we need create a new job for each print DocPrintJob job = getPrintService().createPrintJob(); PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(printRequestAttributeSet); attrs.add(new JobName(jobName, Locale.getDefault())); job.print(doc, attrs); } public PrintService getPrintService() { return printService; } public void setPrintService(PrintService printService) { this.printService = printService; } public DocFlavor getFlavor() { return flavor; } public void setFlavor(DocFlavor flavor) { this.flavor = flavor; } public PrintRequestAttributeSet getPrintRequestAttributeSet() { return printRequestAttributeSet; } public void setPrintRequestAttributeSet(PrintRequestAttributeSet printRequestAttributeSet) { this.printRequestAttributeSet = printRequestAttributeSet; } public Doc getDoc() { return doc; } public void setDoc(Doc doc) { this.doc = doc; } }
hqstevenson/camel
components/camel-printer/src/main/java/org/apache/camel/component/printer/PrinterOperations.java
Java
apache-2.0
5,934
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management.mbean; import org.apache.camel.CamelContext; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.api.management.mbean.ManagedStopMBean; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.processor.StopProcessor; /** * @version */ @ManagedResource(description = "Managed Stop") public class ManagedStop extends ManagedProcessor implements ManagedStopMBean { private final StopProcessor processor; public ManagedStop(CamelContext context, StopProcessor processor, ProcessorDefinition<?> definition) { super(context, processor, definition); this.processor = processor; } }
noelo/camel
camel-core/src/main/java/org/apache/camel/management/mbean/ManagedStop.java
Java
apache-2.0
1,497
/* * Copyright 2015 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.netty.util.internal; import java.util.AbstractQueue; import java.util.Iterator; /** * Forked from <a href="https://github.com/JCTools/JCTools">JCTools</a>. * * A concurrent access enabling class used by circular array based queues this class exposes an offset computation * method along with differently memory fenced load/store methods into the underlying array. The class is pre-padded and * the array is padded on either side to help with False sharing prvention. It is expected theat subclasses handle post * padding. * <p> * Offset calculation is separate from access to enable the reuse of a give compute offset. * <p> * Load/Store methods using a <i>buffer</i> parameter are provided to allow the prevention of final field reload after a * LoadLoad barrier. * <p> * * @param <E> */ abstract class ConcurrentCircularArrayQueue<E> extends ConcurrentCircularArrayQueueL0Pad<E> { protected static final int REF_BUFFER_PAD; private static final long REF_ARRAY_BASE; private static final int REF_ELEMENT_SHIFT; static { final int scale = PlatformDependent0.UNSAFE.arrayIndexScale(Object[].class); if (4 == scale) { REF_ELEMENT_SHIFT = 2; } else if (8 == scale) { REF_ELEMENT_SHIFT = 3; } else { throw new IllegalStateException("Unknown pointer size"); } // 2 cache lines pad // TODO: replace 64 with the value we can detect REF_BUFFER_PAD = (64 * 2) / scale; // Including the buffer pad in the array base offset REF_ARRAY_BASE = PlatformDependent0.UNSAFE.arrayBaseOffset(Object[].class) + (REF_BUFFER_PAD * scale); } protected final long mask; // @Stable :( protected final E[] buffer; @SuppressWarnings("unchecked") public ConcurrentCircularArrayQueue(int capacity) { int actualCapacity = roundToPowerOfTwo(capacity); mask = actualCapacity - 1; // pad data on either end with some empty slots. buffer = (E[]) new Object[actualCapacity + REF_BUFFER_PAD * 2]; } private static int roundToPowerOfTwo(final int value) { return 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); } /** * @param index desirable element index * @return the offset in bytes within the array for a given index. */ protected final long calcElementOffset(long index) { return calcElementOffset(index, mask); } /** * @param index desirable element index * @param mask * @return the offset in bytes within the array for a given index. */ protected static final long calcElementOffset(long index, long mask) { return REF_ARRAY_BASE + ((index & mask) << REF_ELEMENT_SHIFT); } /** * A plain store (no ordering/fences) of an element to a given offset * * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @param e a kitty */ protected final void spElement(long offset, E e) { spElement(buffer, offset, e); } /** * A plain store (no ordering/fences) of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @param e an orderly kitty */ protected static final <E> void spElement(E[] buffer, long offset, E e) { PlatformDependent0.UNSAFE.putObject(buffer, offset, e); } /** * An ordered store(store + StoreStore barrier) of an element to a given offset * * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @param e an orderly kitty */ protected final void soElement(long offset, E e) { soElement(buffer, offset, e); } /** * An ordered store(store + StoreStore barrier) of an element to a given offset * * @param buffer this.buffer * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @param e an orderly kitty */ protected static final <E> void soElement(E[] buffer, long offset, E e) { PlatformDependent0.UNSAFE.putOrderedObject(buffer, offset, e); } /** * A plain load (no ordering/fences) of an element from a given offset. * * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @return the element at the offset */ protected final E lpElement(long offset) { return lpElement(buffer, offset); } /** * A plain load (no ordering/fences) of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") protected static final <E> E lpElement(E[] buffer, long offset) { return (E) PlatformDependent0.UNSAFE.getObject(buffer, offset); } /** * A volatile load (load + LoadLoad barrier) of an element from a given offset. * * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @return the element at the offset */ protected final E lvElement(long offset) { return lvElement(buffer, offset); } /** * A volatile load (load + LoadLoad barrier) of an element from a given offset. * * @param buffer this.buffer * @param offset computed via {@link ConcurrentCircularArrayQueue#calcElementOffset(long)} * @return the element at the offset */ @SuppressWarnings("unchecked") protected static final <E> E lvElement(E[] buffer, long offset) { return (E) PlatformDependent0.UNSAFE.getObjectVolatile(buffer, offset); } @Override public Iterator<E> iterator() { throw new UnsupportedOperationException(); } @Override public void clear() { while (poll() != null || !isEmpty()) { // looping } } public int capacity() { return (int) (mask + 1); } } abstract class ConcurrentCircularArrayQueueL0Pad<E> extends AbstractQueue<E> { long p00, p01, p02, p03, p04, p05, p06, p07; long p30, p31, p32, p33, p34, p35, p36, p37; }
lznhust/netty
common/src/main/java/io/netty/util/internal/ConcurrentCircularArrayQueue.java
Java
apache-2.0
7,512
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package podresources import ( "context" "k8s.io/kubernetes/pkg/kubelet/metrics" "k8s.io/kubelet/pkg/apis/podresources/v1" "k8s.io/kubelet/pkg/apis/podresources/v1alpha1" ) // podResourcesServerV1alpha1 implements PodResourcesListerServer type v1alpha1PodResourcesServer struct { podsProvider PodsProvider devicesProvider DevicesProvider } // NewV1alpha1PodResourcesServer returns a PodResourcesListerServer which lists pods provided by the PodsProvider // with device information provided by the DevicesProvider func NewV1alpha1PodResourcesServer(podsProvider PodsProvider, devicesProvider DevicesProvider) v1alpha1.PodResourcesListerServer { return &v1alpha1PodResourcesServer{ podsProvider: podsProvider, devicesProvider: devicesProvider, } } func v1DevicesToAlphaV1(alphaDevs []*v1.ContainerDevices) []*v1alpha1.ContainerDevices { var devs []*v1alpha1.ContainerDevices for _, alphaDev := range alphaDevs { dev := v1alpha1.ContainerDevices{ ResourceName: alphaDev.ResourceName, DeviceIds: alphaDev.DeviceIds, } devs = append(devs, &dev) } return devs } // List returns information about the resources assigned to pods on the node func (p *v1alpha1PodResourcesServer) List(ctx context.Context, req *v1alpha1.ListPodResourcesRequest) (*v1alpha1.ListPodResourcesResponse, error) { metrics.PodResourcesEndpointRequestsTotalCount.WithLabelValues("v1alpha1").Inc() pods := p.podsProvider.GetPods() podResources := make([]*v1alpha1.PodResources, len(pods)) p.devicesProvider.UpdateAllocatedDevices() for i, pod := range pods { pRes := v1alpha1.PodResources{ Name: pod.Name, Namespace: pod.Namespace, Containers: make([]*v1alpha1.ContainerResources, len(pod.Spec.Containers)), } for j, container := range pod.Spec.Containers { pRes.Containers[j] = &v1alpha1.ContainerResources{ Name: container.Name, Devices: v1DevicesToAlphaV1(p.devicesProvider.GetDevices(string(pod.UID), container.Name)), } } podResources[i] = &pRes } return &v1alpha1.ListPodResourcesResponse{ PodResources: podResources, }, nil }
chrislovecnm/kubernetes
pkg/kubelet/apis/podresources/server_v1alpha1.go
GO
apache-2.0
2,668
package logrus import ( "bytes" "fmt" "regexp" "sort" "strings" "time" ) const ( nocolor = 0 red = 31 green = 32 yellow = 33 blue = 34 gray = 37 ) var ( baseTimestamp time.Time isTerminal bool noQuoteNeeded *regexp.Regexp ) func init() { baseTimestamp = time.Now() isTerminal = IsTerminal() } func miniTS() int { return int(time.Since(baseTimestamp) / time.Second) } type TextFormatter struct { // Set to true to bypass checking for a TTY before outputting colors. ForceColors bool // Force disabling colors. DisableColors bool // Disable timestamp logging. useful when output is redirected to logging // system that already adds timestamps. DisableTimestamp bool // Enable logging the full timestamp when a TTY is attached instead of just // the time passed since beginning of execution. FullTimestamp bool // The fields are sorted by default for a consistent output. For applications // that log extremely frequently and don't use the JSON formatter this may not // be desired. DisableSorting bool } func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { var keys []string = make([]string, 0, len(entry.Data)) for k := range entry.Data { keys = append(keys, k) } if !f.DisableSorting { sort.Strings(keys) } b := &bytes.Buffer{} prefixFieldClashes(entry.Data) isColored := (f.ForceColors || isTerminal) && !f.DisableColors if isColored { f.printColored(b, entry, keys) } else { if !f.DisableTimestamp { f.appendKeyValue(b, "time", entry.Time.Format(time.RFC3339)) } f.appendKeyValue(b, "level", entry.Level.String()) f.appendKeyValue(b, "msg", entry.Message) for _, key := range keys { f.appendKeyValue(b, key, entry.Data[key]) } } b.WriteByte('\n') return b.Bytes(), nil } func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string) { var levelColor int switch entry.Level { case DebugLevel: levelColor = gray case WarnLevel: levelColor = yellow case ErrorLevel, FatalLevel, PanicLevel: levelColor = red default: levelColor = blue } levelText := strings.ToUpper(entry.Level.String())[0:4] if !f.FullTimestamp { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) } else { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(time.RFC3339), entry.Message) } for _, k := range keys { v := entry.Data[k] fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v) } } func needsQuoting(text string) bool { for _, ch := range text { if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '.') { return false } } return true } func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) { switch value.(type) { case string: if needsQuoting(value.(string)) { fmt.Fprintf(b, "%v=%s ", key, value) } else { fmt.Fprintf(b, "%v=%q ", key, value) } case error: if needsQuoting(value.(error).Error()) { fmt.Fprintf(b, "%v=%s ", key, value) } else { fmt.Fprintf(b, "%v=%q ", key, value) } default: fmt.Fprintf(b, "%v=%v ", key, value) } }
spf13/docker
vendor/src/github.com/Sirupsen/logrus/text_formatter.go
GO
apache-2.0
3,196
// Package storage implements the Azure ARM Storage service API version // 2016-01-01. // // The Storage Management Client. package storage // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" ) const ( // APIVersion is the version of the Storage APIVersion = "2016-01-01" // DefaultBaseURI is the default URI used for the service Storage DefaultBaseURI = "https://management.azure.com" ) // ManagementClient is the base client for Storage. type ManagementClient struct { autorest.Client BaseURI string APIVersion string SubscriptionID string } // New creates an instance of the ManagementClient client. func New(subscriptionID string) ManagementClient { return NewWithBaseURI(DefaultBaseURI, subscriptionID) } // NewWithBaseURI creates an instance of the ManagementClient client. func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, APIVersion: APIVersion, SubscriptionID: subscriptionID, } }
radanalyticsio/oshinko-cli
vendor/github.com/openshift/origin/pkg/build/builder/vendor/github.com/docker/distribution/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/client.go
GO
apache-2.0
1,849
package yaml import ( "io" "os" ) func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) // Check if we can move the queue at the beginning of the buffer. if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { if parser.tokens_head != len(parser.tokens) { copy(parser.tokens, parser.tokens[parser.tokens_head:]) } parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] parser.tokens_head = 0 } parser.tokens = append(parser.tokens, *token) if pos < 0 { return } copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) parser.tokens[parser.tokens_head+pos] = *token } // Create a new parser object. func yaml_parser_initialize(parser *yaml_parser_t) bool { *parser = yaml_parser_t{ raw_buffer: make([]byte, 0, input_raw_buffer_size), buffer: make([]byte, 0, input_buffer_size), } return true } // Destroy a parser object. func yaml_parser_delete(parser *yaml_parser_t) { *parser = yaml_parser_t{} } // String read handler. func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { if parser.input_pos == len(parser.input) { return 0, io.EOF } n = copy(buffer, parser.input[parser.input_pos:]) parser.input_pos += n return n, nil } // File read handler. func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { return parser.input_file.Read(buffer) } // Set a string input. func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { if parser.read_handler != nil { panic("must set the input source only once") } parser.read_handler = yaml_string_read_handler parser.input = input parser.input_pos = 0 } // Set a file input. func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) { if parser.read_handler != nil { panic("must set the input source only once") } parser.read_handler = yaml_file_read_handler parser.input_file = file } // Set the source encoding. func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { if parser.encoding != yaml_ANY_ENCODING { panic("must set the encoding only once") } parser.encoding = encoding } // Create a new emitter object. func yaml_emitter_initialize(emitter *yaml_emitter_t) bool { *emitter = yaml_emitter_t{ buffer: make([]byte, output_buffer_size), raw_buffer: make([]byte, 0, output_raw_buffer_size), states: make([]yaml_emitter_state_t, 0, initial_stack_size), events: make([]yaml_event_t, 0, initial_queue_size), } return true } // Destroy an emitter object. func yaml_emitter_delete(emitter *yaml_emitter_t) { *emitter = yaml_emitter_t{} } // String write handler. func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { *emitter.output_buffer = append(*emitter.output_buffer, buffer...) return nil } // File write handler. func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error { _, err := emitter.output_file.Write(buffer) return err } // Set a string output. func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { if emitter.write_handler != nil { panic("must set the output target only once") } emitter.write_handler = yaml_string_write_handler emitter.output_buffer = output_buffer } // Set a file output. func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) { if emitter.write_handler != nil { panic("must set the output target only once") } emitter.write_handler = yaml_file_write_handler emitter.output_file = file } // Set the output encoding. func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { if emitter.encoding != yaml_ANY_ENCODING { panic("must set the output encoding only once") } emitter.encoding = encoding } // Set the canonical output style. func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { emitter.canonical = canonical } //// Set the indentation increment. func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { if indent < 2 || indent > 9 { indent = 2 } emitter.best_indent = indent } // Set the preferred line width. func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { if width < 0 { width = -1 } emitter.best_width = width } // Set if unescaped non-ASCII characters are allowed. func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { emitter.unicode = unicode } // Set the preferred line break character. func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { emitter.line_break = line_break } ///* // * Destroy a token object. // */ // //YAML_DECLARE(void) //yaml_token_delete(yaml_token_t *token) //{ // assert(token); // Non-NULL token object expected. // // switch (token.type) // { // case YAML_TAG_DIRECTIVE_TOKEN: // yaml_free(token.data.tag_directive.handle); // yaml_free(token.data.tag_directive.prefix); // break; // // case YAML_ALIAS_TOKEN: // yaml_free(token.data.alias.value); // break; // // case YAML_ANCHOR_TOKEN: // yaml_free(token.data.anchor.value); // break; // // case YAML_TAG_TOKEN: // yaml_free(token.data.tag.handle); // yaml_free(token.data.tag.suffix); // break; // // case YAML_SCALAR_TOKEN: // yaml_free(token.data.scalar.value); // break; // // default: // break; // } // // memset(token, 0, sizeof(yaml_token_t)); //} // ///* // * Check if a string is a valid UTF-8 sequence. // * // * Check 'reader.c' for more details on UTF-8 encoding. // */ // //static int //yaml_check_utf8(yaml_char_t *start, size_t length) //{ // yaml_char_t *end = start+length; // yaml_char_t *pointer = start; // // while (pointer < end) { // unsigned char octet; // unsigned int width; // unsigned int value; // size_t k; // // octet = pointer[0]; // width = (octet & 0x80) == 0x00 ? 1 : // (octet & 0xE0) == 0xC0 ? 2 : // (octet & 0xF0) == 0xE0 ? 3 : // (octet & 0xF8) == 0xF0 ? 4 : 0; // value = (octet & 0x80) == 0x00 ? octet & 0x7F : // (octet & 0xE0) == 0xC0 ? octet & 0x1F : // (octet & 0xF0) == 0xE0 ? octet & 0x0F : // (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; // if (!width) return 0; // if (pointer+width > end) return 0; // for (k = 1; k < width; k ++) { // octet = pointer[k]; // if ((octet & 0xC0) != 0x80) return 0; // value = (value << 6) + (octet & 0x3F); // } // if (!((width == 1) || // (width == 2 && value >= 0x80) || // (width == 3 && value >= 0x800) || // (width == 4 && value >= 0x10000))) return 0; // // pointer += width; // } // // return 1; //} // // Create STREAM-START. func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool { *event = yaml_event_t{ typ: yaml_STREAM_START_EVENT, encoding: encoding, } return true } // Create STREAM-END. func yaml_stream_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_STREAM_END_EVENT, } return true } // Create DOCUMENT-START. func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t, tag_directives []yaml_tag_directive_t, implicit bool) bool { *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, version_directive: version_directive, tag_directives: tag_directives, implicit: implicit, } return true } // Create DOCUMENT-END. func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool { *event = yaml_event_t{ typ: yaml_DOCUMENT_END_EVENT, implicit: implicit, } return true } ///* // * Create ALIAS. // */ // //YAML_DECLARE(int) //yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) //{ // mark yaml_mark_t = { 0, 0, 0 } // anchor_copy *yaml_char_t = NULL // // assert(event) // Non-NULL event object is expected. // assert(anchor) // Non-NULL anchor is expected. // // if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 // // anchor_copy = yaml_strdup(anchor) // if (!anchor_copy) // return 0 // // ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) // // return 1 //} // Create SCALAR. func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { *event = yaml_event_t{ typ: yaml_SCALAR_EVENT, anchor: anchor, tag: tag, value: value, implicit: plain_implicit, quoted_implicit: quoted_implicit, style: yaml_style_t(style), } return true } // Create SEQUENCE-START. func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { *event = yaml_event_t{ typ: yaml_SEQUENCE_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } return true } // Create SEQUENCE-END. func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_SEQUENCE_END_EVENT, } return true } // Create MAPPING-START. func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool { *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } return true } // Create MAPPING-END. func yaml_mapping_end_event_initialize(event *yaml_event_t) bool { *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, } return true } // Destroy an event object. func yaml_event_delete(event *yaml_event_t) { *event = yaml_event_t{} } ///* // * Create a document object. // */ // //YAML_DECLARE(int) //yaml_document_initialize(document *yaml_document_t, // version_directive *yaml_version_directive_t, // tag_directives_start *yaml_tag_directive_t, // tag_directives_end *yaml_tag_directive_t, // start_implicit int, end_implicit int) //{ // struct { // error yaml_error_type_t // } context // struct { // start *yaml_node_t // end *yaml_node_t // top *yaml_node_t // } nodes = { NULL, NULL, NULL } // version_directive_copy *yaml_version_directive_t = NULL // struct { // start *yaml_tag_directive_t // end *yaml_tag_directive_t // top *yaml_tag_directive_t // } tag_directives_copy = { NULL, NULL, NULL } // value yaml_tag_directive_t = { NULL, NULL } // mark yaml_mark_t = { 0, 0, 0 } // // assert(document) // Non-NULL document object is expected. // assert((tag_directives_start && tag_directives_end) || // (tag_directives_start == tag_directives_end)) // // Valid tag directives are expected. // // if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error // // if (version_directive) { // version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) // if (!version_directive_copy) goto error // version_directive_copy.major = version_directive.major // version_directive_copy.minor = version_directive.minor // } // // if (tag_directives_start != tag_directives_end) { // tag_directive *yaml_tag_directive_t // if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) // goto error // for (tag_directive = tag_directives_start // tag_directive != tag_directives_end; tag_directive ++) { // assert(tag_directive.handle) // assert(tag_directive.prefix) // if (!yaml_check_utf8(tag_directive.handle, // strlen((char *)tag_directive.handle))) // goto error // if (!yaml_check_utf8(tag_directive.prefix, // strlen((char *)tag_directive.prefix))) // goto error // value.handle = yaml_strdup(tag_directive.handle) // value.prefix = yaml_strdup(tag_directive.prefix) // if (!value.handle || !value.prefix) goto error // if (!PUSH(&context, tag_directives_copy, value)) // goto error // value.handle = NULL // value.prefix = NULL // } // } // // DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, // tag_directives_copy.start, tag_directives_copy.top, // start_implicit, end_implicit, mark, mark) // // return 1 // //error: // STACK_DEL(&context, nodes) // yaml_free(version_directive_copy) // while (!STACK_EMPTY(&context, tag_directives_copy)) { // value yaml_tag_directive_t = POP(&context, tag_directives_copy) // yaml_free(value.handle) // yaml_free(value.prefix) // } // STACK_DEL(&context, tag_directives_copy) // yaml_free(value.handle) // yaml_free(value.prefix) // // return 0 //} // ///* // * Destroy a document object. // */ // //YAML_DECLARE(void) //yaml_document_delete(document *yaml_document_t) //{ // struct { // error yaml_error_type_t // } context // tag_directive *yaml_tag_directive_t // // context.error = YAML_NO_ERROR // Eliminate a compliler warning. // // assert(document) // Non-NULL document object is expected. // // while (!STACK_EMPTY(&context, document.nodes)) { // node yaml_node_t = POP(&context, document.nodes) // yaml_free(node.tag) // switch (node.type) { // case YAML_SCALAR_NODE: // yaml_free(node.data.scalar.value) // break // case YAML_SEQUENCE_NODE: // STACK_DEL(&context, node.data.sequence.items) // break // case YAML_MAPPING_NODE: // STACK_DEL(&context, node.data.mapping.pairs) // break // default: // assert(0) // Should not happen. // } // } // STACK_DEL(&context, document.nodes) // // yaml_free(document.version_directive) // for (tag_directive = document.tag_directives.start // tag_directive != document.tag_directives.end // tag_directive++) { // yaml_free(tag_directive.handle) // yaml_free(tag_directive.prefix) // } // yaml_free(document.tag_directives.start) // // memset(document, 0, sizeof(yaml_document_t)) //} // ///** // * Get a document node. // */ // //YAML_DECLARE(yaml_node_t *) //yaml_document_get_node(document *yaml_document_t, index int) //{ // assert(document) // Non-NULL document object is expected. // // if (index > 0 && document.nodes.start + index <= document.nodes.top) { // return document.nodes.start + index - 1 // } // return NULL //} // ///** // * Get the root object. // */ // //YAML_DECLARE(yaml_node_t *) //yaml_document_get_root_node(document *yaml_document_t) //{ // assert(document) // Non-NULL document object is expected. // // if (document.nodes.top != document.nodes.start) { // return document.nodes.start // } // return NULL //} // ///* // * Add a scalar node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_scalar(document *yaml_document_t, // tag *yaml_char_t, value *yaml_char_t, length int, // style yaml_scalar_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // value_copy *yaml_char_t = NULL // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // assert(value) // Non-NULL value is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (length < 0) { // length = strlen((char *)value) // } // // if (!yaml_check_utf8(value, length)) goto error // value_copy = yaml_malloc(length+1) // if (!value_copy) goto error // memcpy(value_copy, value, length) // value_copy[length] = '\0' // // SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // yaml_free(tag_copy) // yaml_free(value_copy) // // return 0 //} // ///* // * Add a sequence node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_sequence(document *yaml_document_t, // tag *yaml_char_t, style yaml_sequence_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // struct { // start *yaml_node_item_t // end *yaml_node_item_t // top *yaml_node_item_t // } items = { NULL, NULL, NULL } // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error // // SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, // style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // STACK_DEL(&context, items) // yaml_free(tag_copy) // // return 0 //} // ///* // * Add a mapping node to a document. // */ // //YAML_DECLARE(int) //yaml_document_add_mapping(document *yaml_document_t, // tag *yaml_char_t, style yaml_mapping_style_t) //{ // struct { // error yaml_error_type_t // } context // mark yaml_mark_t = { 0, 0, 0 } // tag_copy *yaml_char_t = NULL // struct { // start *yaml_node_pair_t // end *yaml_node_pair_t // top *yaml_node_pair_t // } pairs = { NULL, NULL, NULL } // node yaml_node_t // // assert(document) // Non-NULL document object is expected. // // if (!tag) { // tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG // } // // if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error // tag_copy = yaml_strdup(tag) // if (!tag_copy) goto error // // if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error // // MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, // style, mark, mark) // if (!PUSH(&context, document.nodes, node)) goto error // // return document.nodes.top - document.nodes.start // //error: // STACK_DEL(&context, pairs) // yaml_free(tag_copy) // // return 0 //} // ///* // * Append an item to a sequence node. // */ // //YAML_DECLARE(int) //yaml_document_append_sequence_item(document *yaml_document_t, // sequence int, item int) //{ // struct { // error yaml_error_type_t // } context // // assert(document) // Non-NULL document is required. // assert(sequence > 0 // && document.nodes.start + sequence <= document.nodes.top) // // Valid sequence id is required. // assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) // // A sequence node is required. // assert(item > 0 && document.nodes.start + item <= document.nodes.top) // // Valid item id is required. // // if (!PUSH(&context, // document.nodes.start[sequence-1].data.sequence.items, item)) // return 0 // // return 1 //} // ///* // * Append a pair of a key and a value to a mapping node. // */ // //YAML_DECLARE(int) //yaml_document_append_mapping_pair(document *yaml_document_t, // mapping int, key int, value int) //{ // struct { // error yaml_error_type_t // } context // // pair yaml_node_pair_t // // assert(document) // Non-NULL document is required. // assert(mapping > 0 // && document.nodes.start + mapping <= document.nodes.top) // // Valid mapping id is required. // assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) // // A mapping node is required. // assert(key > 0 && document.nodes.start + key <= document.nodes.top) // // Valid key id is required. // assert(value > 0 && document.nodes.start + value <= document.nodes.top) // // Valid value id is required. // // pair.key = key // pair.value = value // // if (!PUSH(&context, // document.nodes.start[mapping-1].data.mapping.pairs, pair)) // return 0 // // return 1 //} // //
mikedanese/contrib
ingress/vendor/gopkg.in/yaml.v2/apic.go
GO
apache-2.0
21,246
/* NUGET: BEGIN LICENSE TEXT jQuery v1.9.1 Microsoft grants you the right to use these script files for the sole purpose of either: (i) interacting through your browser with the Microsoft website, subject to the website's terms of use; or (ii) using the files as included with a Microsoft product subject to that product's license terms. Microsoft reserves all other rights to the files not expressly granted by Microsoft, whether by implication, estoppel or otherwise. The notices and licenses below are for informational purposes only. *************************************************** * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors ******************************** * Includes Sizzle CSS Selector Engine * http://sizzlejs.com/ * Copyright 2012 jQuery Foundation and other contributors ******************************************************** Provided for Informational Purposes Only MIT License 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 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. * NUGET: END LICENSE TEXT */ intellisense.annotate(jQuery, { 'ajax': function() { /// <signature> /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="settings" type="PlainObject">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.</param> /// <returns type="jqXHR" /> /// </signature> /// <signature> /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> /// <param name="settings" type="PlainObject">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().</param> /// <returns type="jqXHR" /> /// </signature> }, 'ajaxPrefilter': function() { /// <signature> /// <summary>Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().</summary> /// <param name="dataTypes" type="String">An optional string containing one or more space-separated dataTypes</param> /// <param name="handler(options, originalOptions, jqXHR)" type="Function">A handler to set default values for future Ajax requests.</param> /// </signature> }, 'ajaxSetup': function() { /// <signature> /// <summary>Set default values for future Ajax requests.</summary> /// <param name="options" type="PlainObject">A set of key/value pairs that configure the default Ajax request. All options are optional.</param> /// </signature> }, 'ajaxTransport': function() { /// <signature> /// <summary>Creates an object that handles the actual transmission of Ajax data.</summary> /// <param name="dataType" type="String">A string identifying the data type to use</param> /// <param name="handler(options, originalOptions, jqXHR)" type="Function">A handler to return the new transport object to use with the data type provided in the first argument.</param> /// </signature> }, 'boxModel': function() { /// <summary>Deprecated in jQuery 1.3 (see jQuery.support). States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model.</summary> /// <returns type="Boolean" /> }, 'browser': function() { /// <summary>Contains flags for the useragent, read from navigator.userAgent. We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.</summary> /// <returns type="PlainObject" /> }, 'browser.version': function() { /// <summary>The version number of the rendering engine for the user's browser.</summary> /// <returns type="String" /> }, 'Callbacks': function() { /// <signature> /// <summary>A multi-purpose callbacks list object that provides a powerful way to manage callback lists.</summary> /// <param name="flags" type="String">An optional list of space-separated flags that change how the callback list behaves.</param> /// <returns type="Callbacks" /> /// </signature> }, 'contains': function() { /// <signature> /// <summary>Check to see if a DOM element is a descendant of another DOM element.</summary> /// <param name="container" type="Element">The DOM element that may contain the other element.</param> /// <param name="contained" type="Element">The DOM element that may be contained by (a descendant of) the other element.</param> /// <returns type="Boolean" /> /// </signature> }, 'cssHooks': function() { /// <summary>Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.</summary> /// <returns type="Object" /> }, 'data': function() { /// <signature> /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> /// <param name="element" type="Element">The DOM element to query for the data.</param> /// <param name="key" type="String">Name of the data stored.</param> /// <returns type="Object" /> /// </signature> /// <signature> /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> /// <param name="element" type="Element">The DOM element to query for the data.</param> /// <returns type="Object" /> /// </signature> }, 'Deferred': function() { /// <signature> /// <summary>A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.</summary> /// <param name="beforeStart" type="Function">A function that is called just before the constructor returns.</param> /// <returns type="Deferred" /> /// </signature> }, 'dequeue': function() { /// <signature> /// <summary>Execute the next function on the queue for the matched element.</summary> /// <param name="element" type="Element">A DOM element from which to remove and execute a queued function.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// </signature> }, 'each': function() { /// <signature> /// <summary>A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.</summary> /// <param name="collection" type="Object">The object or array to iterate over.</param> /// <param name="callback(indexInArray, valueOfElement)" type="Function">The function that will be executed on every object.</param> /// <returns type="Object" /> /// </signature> }, 'error': function() { /// <signature> /// <summary>Takes a string and throws an exception containing it.</summary> /// <param name="message" type="String">The message to send out.</param> /// </signature> }, 'extend': function() { /// <signature> /// <summary>Merge the contents of two or more objects together into the first object.</summary> /// <param name="target" type="Object">An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.</param> /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> /// <returns type="Object" /> /// </signature> /// <signature> /// <summary>Merge the contents of two or more objects together into the first object.</summary> /// <param name="deep" type="Boolean">If true, the merge becomes recursive (aka. deep copy).</param> /// <param name="target" type="Object">The object to extend. It will receive the new properties.</param> /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> /// <returns type="Object" /> /// </signature> }, 'get': function() { /// <signature> /// <summary>Load data from the server using a HTTP GET request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="String">A plain object or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).</param> /// <returns type="jqXHR" /> /// </signature> }, 'getJSON': function() { /// <signature> /// <summary>Load JSON-encoded data from the server using a GET HTTP request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="PlainObject">A plain object or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <returns type="jqXHR" /> /// </signature> }, 'getScript': function() { /// <signature> /// <summary>Load a JavaScript file from the server using a GET HTTP request, then execute it.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="success(script, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <returns type="jqXHR" /> /// </signature> }, 'globalEval': function() { /// <signature> /// <summary>Execute some JavaScript code globally.</summary> /// <param name="code" type="String">The JavaScript code to execute.</param> /// </signature> }, 'grep': function() { /// <signature> /// <summary>Finds the elements of an array which satisfy a filter function. The original array is not affected.</summary> /// <param name="array" type="Array">The array to search through.</param> /// <param name="function(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.</param> /// <param name="invert" type="Boolean">If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.</param> /// <returns type="Array" /> /// </signature> }, 'hasData': function() { /// <signature> /// <summary>Determine whether an element has any jQuery data associated with it.</summary> /// <param name="element" type="Element">A DOM element to be checked for data.</param> /// <returns type="Boolean" /> /// </signature> }, 'holdReady': function() { /// <signature> /// <summary>Holds or releases the execution of jQuery's ready event.</summary> /// <param name="hold" type="Boolean">Indicates whether the ready hold is being requested or released</param> /// </signature> }, 'inArray': function() { /// <signature> /// <summary>Search for a specified value within an array and return its index (or -1 if not found).</summary> /// <param name="value" type="Anything">The value to search for.</param> /// <param name="array" type="Array">An array through which to search.</param> /// <param name="fromIndex" type="Number">The index of the array at which to begin the search. The default is 0, which will search the whole array.</param> /// <returns type="Number" /> /// </signature> }, 'isArray': function() { /// <signature> /// <summary>Determine whether the argument is an array.</summary> /// <param name="obj" type="Object">Object to test whether or not it is an array.</param> /// <returns type="boolean" /> /// </signature> }, 'isEmptyObject': function() { /// <signature> /// <summary>Check to see if an object is empty (contains no enumerable properties).</summary> /// <param name="object" type="Object">The object that will be checked to see if it's empty.</param> /// <returns type="Boolean" /> /// </signature> }, 'isFunction': function() { /// <signature> /// <summary>Determine if the argument passed is a Javascript function object.</summary> /// <param name="obj" type="PlainObject">Object to test whether or not it is a function.</param> /// <returns type="boolean" /> /// </signature> }, 'isNumeric': function() { /// <signature> /// <summary>Determines whether its argument is a number.</summary> /// <param name="value" type="PlainObject">The value to be tested.</param> /// <returns type="Boolean" /> /// </signature> }, 'isPlainObject': function() { /// <signature> /// <summary>Check to see if an object is a plain object (created using "{}" or "new Object").</summary> /// <param name="object" type="PlainObject">The object that will be checked to see if it's a plain object.</param> /// <returns type="Boolean" /> /// </signature> }, 'isWindow': function() { /// <signature> /// <summary>Determine whether the argument is a window.</summary> /// <param name="obj" type="PlainObject">Object to test whether or not it is a window.</param> /// <returns type="boolean" /> /// </signature> }, 'isXMLDoc': function() { /// <signature> /// <summary>Check to see if a DOM node is within an XML document (or is an XML document).</summary> /// <param name="node" type="Element">The DOM node that will be checked to see if it's in an XML document.</param> /// <returns type="Boolean" /> /// </signature> }, 'makeArray': function() { /// <signature> /// <summary>Convert an array-like object into a true JavaScript array.</summary> /// <param name="obj" type="PlainObject">Any object to turn into a native Array.</param> /// <returns type="Array" /> /// </signature> }, 'map': function() { /// <signature> /// <summary>Translate all items in an array or object to new array of items.</summary> /// <param name="array" type="Array">The Array to translate.</param> /// <param name="callback(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.</param> /// <returns type="Array" /> /// </signature> /// <signature> /// <summary>Translate all items in an array or object to new array of items.</summary> /// <param name="arrayOrObject" type="Object">The Array or Object to translate.</param> /// <param name="callback( value, indexOrKey )" type="Function">The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.</param> /// <returns type="Array" /> /// </signature> }, 'merge': function() { /// <signature> /// <summary>Merge the contents of two arrays together into the first array.</summary> /// <param name="first" type="Array">The first array to merge, the elements of second added.</param> /// <param name="second" type="Array">The second array to merge into the first, unaltered.</param> /// <returns type="Array" /> /// </signature> }, 'noConflict': function() { /// <signature> /// <summary>Relinquish jQuery's control of the $ variable.</summary> /// <param name="removeAll" type="Boolean">A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).</param> /// <returns type="Object" /> /// </signature> }, 'noop': function() { /// <summary>An empty function.</summary> }, 'now': function() { /// <summary>Return a number representing the current time.</summary> /// <returns type="Number" /> }, 'param': function() { /// <signature> /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> /// <param name="obj" type="Object">An array or object to serialize.</param> /// <returns type="String" /> /// </signature> /// <signature> /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> /// <param name="obj" type="Object">An array or object to serialize.</param> /// <param name="traditional" type="Boolean">A Boolean indicating whether to perform a traditional "shallow" serialization.</param> /// <returns type="String" /> /// </signature> }, 'parseHTML': function() { /// <signature> /// <summary>Parses a string into an array of DOM nodes.</summary> /// <param name="data" type="String">HTML string to be parsed</param> /// <param name="context" type="Element">DOM element to serve as the context in which the HTML fragment will be created</param> /// <param name="keepScripts" type="Boolean">A Boolean indicating whether to include scripts passed in the HTML string</param> /// <returns type="Array" /> /// </signature> }, 'parseJSON': function() { /// <signature> /// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary> /// <param name="json" type="String">The JSON string to parse.</param> /// <returns type="Object" /> /// </signature> }, 'parseXML': function() { /// <signature> /// <summary>Parses a string into an XML document.</summary> /// <param name="data" type="String">a well-formed XML string to be parsed</param> /// <returns type="XMLDocument" /> /// </signature> }, 'post': function() { /// <signature> /// <summary>Load data from the server using a HTTP POST request.</summary> /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> /// <param name="data" type="String">A plain object or string that is sent to the server with the request.</param> /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).</param> /// <returns type="jqXHR" /> /// </signature> }, 'proxy': function() { /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="function" type="Function">The function whose context will be changed.</param> /// <param name="context" type="PlainObject">The object to which the context (this) of the function should be set.</param> /// <returns type="Function" /> /// </signature> /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="context" type="PlainObject">The object to which the context of the function should be set.</param> /// <param name="name" type="String">The name of the function whose context will be changed (should be a property of the context object).</param> /// <returns type="Function" /> /// </signature> /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="function" type="Function">The function whose context will be changed.</param> /// <param name="context" type="PlainObject">The object to which the context (this) of the function should be set.</param> /// <param name="additionalArguments" type="Anything">Any number of arguments to be passed to the function referenced in the function argument.</param> /// <returns type="Function" /> /// </signature> /// <signature> /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> /// <param name="context" type="PlainObject">The object to which the context of the function should be set.</param> /// <param name="name" type="String">The name of the function whose context will be changed (should be a property of the context object).</param> /// <param name="additionalArguments" type="Anything">Any number of arguments to be passed to the function named in the name argument.</param> /// <returns type="Function" /> /// </signature> }, 'queue': function() { /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> /// <param name="element" type="Element">A DOM element where the array of queued functions is attached.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> /// <param name="element" type="Element">A DOM element on which to add a queued function.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="callback()" type="Function">The new function to add to the queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeData': function() { /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="element" type="Element">A DOM element from which to remove data.</param> /// <param name="name" type="String">A string naming the piece of data to remove.</param> /// <returns type="jQuery" /> /// </signature> }, 'sub': function() { /// <summary>Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.</summary> /// <returns type="jQuery" /> }, 'support': function() { /// <summary>A collection of properties that represent the presence of different browser features or bugs. Primarily intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance.</summary> /// <returns type="Object" /> }, 'trim': function() { /// <signature> /// <summary>Remove the whitespace from the beginning and end of a string.</summary> /// <param name="str" type="String">The string to trim.</param> /// <returns type="String" /> /// </signature> }, 'type': function() { /// <signature> /// <summary>Determine the internal JavaScript [[Class]] of an object.</summary> /// <param name="obj" type="PlainObject">Object to get the internal JavaScript [[Class]] of.</param> /// <returns type="String" /> /// </signature> }, 'unique': function() { /// <signature> /// <summary>Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.</summary> /// <param name="array" type="Array">The Array of DOM elements.</param> /// <returns type="Array" /> /// </signature> }, 'when': function() { /// <signature> /// <summary>Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.</summary> /// <param name="deferreds" type="Deferred">One or more Deferred objects, or plain JavaScript objects.</param> /// <returns type="Promise" /> /// </signature> }, }); var _1228819969 = jQuery.Callbacks; jQuery.Callbacks = function(flags) { var _object = _1228819969(flags); intellisense.annotate(_object, { 'add': function() { /// <signature> /// <summary>Add a callback or a collection of callbacks to a callback list.</summary> /// <param name="callbacks" type="Array">A function, or array of functions, that are to be added to the callback list.</param> /// <returns type="Callbacks" /> /// </signature> }, 'disable': function() { /// <summary>Disable a callback list from doing anything more.</summary> /// <returns type="Callbacks" /> }, 'disabled': function() { /// <summary>Determine if the callbacks list has been disabled.</summary> /// <returns type="Boolean" /> }, 'empty': function() { /// <summary>Remove all of the callbacks from a list.</summary> /// <returns type="Callbacks" /> }, 'fire': function() { /// <signature> /// <summary>Call all of the callbacks with the given arguments</summary> /// <param name="arguments" type="Anything">The argument or list of arguments to pass back to the callback list.</param> /// <returns type="Callbacks" /> /// </signature> }, 'fired': function() { /// <summary>Determine if the callbacks have already been called at least once.</summary> /// <returns type="Boolean" /> }, 'fireWith': function() { /// <signature> /// <summary>Call all callbacks in a list with the given context and arguments.</summary> /// <param name="context" type="">A reference to the context in which the callbacks in the list should be fired.</param> /// <param name="args" type="">An argument, or array of arguments, to pass to the callbacks in the list.</param> /// <returns type="Callbacks" /> /// </signature> }, 'has': function() { /// <signature> /// <summary>Determine whether a supplied callback is in a list</summary> /// <param name="callback" type="Function">The callback to search for.</param> /// <returns type="Boolean" /> /// </signature> }, 'lock': function() { /// <summary>Lock a callback list in its current state.</summary> /// <returns type="Callbacks" /> }, 'locked': function() { /// <summary>Determine if the callbacks list has been locked.</summary> /// <returns type="Boolean" /> }, 'remove': function() { /// <signature> /// <summary>Remove a callback or a collection of callbacks from a callback list.</summary> /// <param name="callbacks" type="Array">A function, or array of functions, that are to be removed from the callback list.</param> /// <returns type="Callbacks" /> /// </signature> }, }); return _object; }; intellisense.redirectDefinition(jQuery.Callbacks, _1228819969); var _731531622 = jQuery.Deferred; jQuery.Deferred = function(func) { var _object = _731531622(func); intellisense.annotate(_object, { 'always': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is either resolved or rejected.</summary> /// <param name="alwaysCallbacks" type="Function">A function, or array of functions, that is called when the Deferred is resolved or rejected.</param> /// <param name="alwaysCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.</param> /// <returns type="Deferred" /> /// </signature> }, 'done': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is resolved.</param> /// <param name="doneCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.</param> /// <returns type="Deferred" /> /// </signature> }, 'fail': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is rejected.</summary> /// <param name="failCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is rejected.</param> /// <param name="failCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.</param> /// <returns type="Deferred" /> /// </signature> }, 'isRejected': function() { /// <summary>Determine whether a Deferred object has been rejected.</summary> /// <returns type="Boolean" /> }, 'isResolved': function() { /// <summary>Determine whether a Deferred object has been resolved.</summary> /// <returns type="Boolean" /> }, 'notify': function() { /// <signature> /// <summary>Call the progressCallbacks on a Deferred object with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'notifyWith': function() { /// <signature> /// <summary>Call the progressCallbacks on a Deferred object with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the progressCallbacks as the this object.</param> /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'pipe': function() { /// <signature> /// <summary>Utility method to filter and/or chain Deferreds.</summary> /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> /// <returns type="Promise" /> /// </signature> /// <signature> /// <summary>Utility method to filter and/or chain Deferreds.</summary> /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> /// <param name="progressFilter" type="Function">An optional function that is called when progress notifications are sent to the Deferred.</param> /// <returns type="Promise" /> /// </signature> }, 'progress': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object generates progress notifications.</summary> /// <param name="progressCallbacks" type="Function">A function, or array of functions, that is called when the Deferred generates progress notifications.</param> /// <returns type="Deferred" /> /// </signature> }, 'promise': function() { /// <signature> /// <summary>Return a Deferred's Promise object.</summary> /// <param name="target" type="Object">Object onto which the promise methods have to be attached</param> /// <returns type="Promise" /> /// </signature> }, 'reject': function() { /// <signature> /// <summary>Reject a Deferred object and call any failCallbacks with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the failCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'rejectWith': function() { /// <signature> /// <summary>Reject a Deferred object and call any failCallbacks with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the failCallbacks as the this object.</param> /// <param name="args" type="Array">An optional array of arguments that are passed to the failCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'resolve': function() { /// <signature> /// <summary>Resolve a Deferred object and call any doneCallbacks with the given args.</summary> /// <param name="args" type="Object">Optional arguments that are passed to the doneCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'resolveWith': function() { /// <signature> /// <summary>Resolve a Deferred object and call any doneCallbacks with the given context and args.</summary> /// <param name="context" type="Object">Context passed to the doneCallbacks as the this object.</param> /// <param name="args" type="Array">An optional array of arguments that are passed to the doneCallbacks.</param> /// <returns type="Deferred" /> /// </signature> }, 'state': function() { /// <summary>Determine the current state of a Deferred object.</summary> /// <returns type="String" /> }, 'then': function() { /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.</summary> /// <param name="doneFilter" type="Function">A function that is called when the Deferred is resolved.</param> /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> /// <param name="progressFilter" type="Function">An optional function that is called when progress notifications are sent to the Deferred.</param> /// <returns type="Promise" /> /// </signature> /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> /// <returns type="Promise" /> /// </signature> /// <signature> /// <summary>Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.</summary> /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> /// <param name="progressCallbacks" type="Function">A function, or array of functions, called when the Deferred notifies progress.</param> /// <returns type="Promise" /> /// </signature> }, }); return _object; }; intellisense.redirectDefinition(jQuery.Callbacks, _731531622); intellisense.annotate(jQuery.Event.prototype, { 'currentTarget': function() { /// <summary>The current DOM element within the event bubbling phase.</summary> /// <returns type="Element" /> }, 'data': function() { /// <summary>An optional object of data passed to an event method when the current executing handler is bound.</summary> /// <returns type="Object" /> }, 'delegateTarget': function() { /// <summary>The element where the currently-called jQuery event handler was attached.</summary> /// <returns type="Element" /> }, 'isDefaultPrevented': function() { /// <summary>Returns whether event.preventDefault() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'isImmediatePropagationStopped': function() { /// <summary>Returns whether event.stopImmediatePropagation() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'isPropagationStopped': function() { /// <summary>Returns whether event.stopPropagation() was ever called on this event object.</summary> /// <returns type="Boolean" /> }, 'metaKey': function() { /// <summary>Indicates whether the META key was pressed when the event fired.</summary> /// <returns type="Boolean" /> }, 'namespace': function() { /// <summary>The namespace specified when the event was triggered.</summary> /// <returns type="String" /> }, 'pageX': function() { /// <summary>The mouse position relative to the left edge of the document.</summary> /// <returns type="Number" /> }, 'pageY': function() { /// <summary>The mouse position relative to the top edge of the document.</summary> /// <returns type="Number" /> }, 'preventDefault': function() { /// <summary>If this method is called, the default action of the event will not be triggered.</summary> }, 'relatedTarget': function() { /// <summary>The other DOM element involved in the event, if any.</summary> /// <returns type="Element" /> }, 'result': function() { /// <summary>The last value returned by an event handler that was triggered by this event, unless the value was undefined.</summary> /// <returns type="Object" /> }, 'stopImmediatePropagation': function() { /// <summary>Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.</summary> }, 'stopPropagation': function() { /// <summary>Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.</summary> }, 'target': function() { /// <summary>The DOM element that initiated the event.</summary> /// <returns type="Element" /> }, 'timeStamp': function() { /// <summary>The difference in milliseconds between the time the browser created the event and January 1, 1970.</summary> /// <returns type="Number" /> }, 'type': function() { /// <summary>Describes the nature of the event.</summary> /// <returns type="String" /> }, 'which': function() { /// <summary>For key or mouse events, this property indicates the specific key or button that was pressed.</summary> /// <returns type="Number" /> }, }); intellisense.annotate(jQuery.fn, { 'add': function() { /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="elements" type="Array">One or more elements to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="html" type="String">An HTML fragment to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="jQuery object" type="jQuery object ">An existing jQuery object to add to the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add elements to the set of matched elements.</summary> /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> /// <param name="context" type="Element">The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.</param> /// <returns type="jQuery" /> /// </signature> }, 'addBack': function() { /// <signature> /// <summary>Add the previous set of elements on the stack to the current set, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'addClass': function() { /// <signature> /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> /// <param name="className" type="String">One or more space-separated classes to be added to the class attribute of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> /// <param name="function(index, currentClass)" type="Function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'after': function() { /// <signature> /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxComplete': function() { /// <signature> /// <summary>Register a handler to be called when Ajax requests complete. This is an AjaxEvent.</summary> /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxError': function() { /// <signature> /// <summary>Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.</summary> /// <param name="handler(event, jqXHR, ajaxSettings, thrownError)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxSend': function() { /// <signature> /// <summary>Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.</summary> /// <param name="handler(event, jqXHR, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxStart': function() { /// <signature> /// <summary>Register a handler to be called when the first Ajax request begins. This is an Ajax Event.</summary> /// <param name="handler()" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxStop': function() { /// <signature> /// <summary>Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.</summary> /// <param name="handler()" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'ajaxSuccess': function() { /// <signature> /// <summary>Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.</summary> /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> /// <returns type="jQuery" /> /// </signature> }, 'all': function() { /// <summary>Selects all elements.</summary> }, 'andSelf': function() { /// <summary>Add the previous set of elements on the stack to the current set.</summary> /// <returns type="jQuery" /> }, 'animate': function() { /// <signature> /// <summary>Perform a custom animation of a set of CSS properties.</summary> /// <param name="properties" type="PlainObject">An object of CSS properties and values that the animation will move toward.</param> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Perform a custom animation of a set of CSS properties.</summary> /// <param name="properties" type="PlainObject">An object of CSS properties and values that the animation will move toward.</param> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> }, 'animated': function() { /// <summary>Select all elements that are in the progress of an animation at the time the selector is run.</summary> }, 'append': function() { /// <signature> /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'appendTo': function() { /// <signature> /// <summary>Insert every element in the set of matched elements to the end of the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'attr': function() { /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="attributeName" type="String">The name of the attribute to set.</param> /// <param name="value" type="Number">A value to set for the attribute.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="attributes" type="PlainObject">An object of attribute-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more attributes for the set of matched elements.</summary> /// <param name="attributeName" type="String">The name of the attribute to set.</param> /// <param name="function(index, attr)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'attributeContains': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value containing the a given substring.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeContainsPrefix': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeContainsWord': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeEndsWith': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeEquals': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value exactly equal to a certain value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeHas': function() { /// <signature> /// <summary>Selects elements that have the specified attribute, with any value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// </signature> }, 'attributeMultiple': function() { /// <signature> /// <summary>Matches elements that match all of the specified attribute filters.</summary> /// <param name="attributeFilter1" type="String">An attribute filter.</param> /// <param name="attributeFilter2" type="String">Another attribute filter, reducing the selection even more</param> /// <param name="attributeFilterN" type="String">As many more attribute filters as necessary</param> /// </signature> }, 'attributeNotEqual': function() { /// <signature> /// <summary>Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'attributeStartsWith': function() { /// <signature> /// <summary>Selects elements that have the specified attribute with a value beginning exactly with a given string.</summary> /// <param name="attribute" type="String">An attribute name.</param> /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> /// </signature> }, 'before': function() { /// <signature> /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> /// <param name="function" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'bind': function() { /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="preventBubble" type="Boolean">Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements.</summary> /// <param name="events" type="Object">An object containing one or more DOM event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'blur': function() { /// <signature> /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'button': function() { /// <summary>Selects all button elements and elements of type button.</summary> }, 'change': function() { /// <signature> /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'checkbox': function() { /// <summary>Selects all elements of type checkbox.</summary> }, 'checked': function() { /// <summary>Matches all elements that are checked.</summary> }, 'child': function() { /// <signature> /// <summary>Selects all direct child elements specified by "child" of elements specified by "parent".</summary> /// <param name="parent" type="String">Any valid selector.</param> /// <param name="child" type="String">A selector to filter the child elements.</param> /// </signature> }, 'children': function() { /// <signature> /// <summary>Get the children of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'class': function() { /// <signature> /// <summary>Selects all elements with the given class.</summary> /// <param name="class" type="String">A class to search for. An element can have multiple classes; only one of them must match.</param> /// </signature> }, 'clearQueue': function() { /// <signature> /// <summary>Remove from the queue all items that have not yet been run.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'click': function() { /// <signature> /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'clone': function() { /// <signature> /// <summary>Create a deep copy of the set of matched elements.</summary> /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Create a deep copy of the set of matched elements.</summary> /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.</param> /// <param name="deepWithDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).</param> /// <returns type="jQuery" /> /// </signature> }, 'closest': function() { /// <signature> /// <summary>For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <param name="context" type="Element">A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.</summary> /// <param name="jQuery object" type="jQuery">A jQuery object to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.</summary> /// <param name="element" type="Element">An element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'contains': function() { /// <signature> /// <summary>Select all elements that contain the specified text.</summary> /// <param name="text" type="String">A string of text to look for. It's case sensitive.</param> /// </signature> }, 'contents': function() { /// <summary>Get the children of each element in the set of matched elements, including text and comment nodes.</summary> /// <returns type="jQuery" /> }, 'context': function() { /// <summary>The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.</summary> /// <returns type="Element" /> }, 'css': function() { /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">A CSS property name.</param> /// <param name="value" type="Number">A value to set for the property.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">A CSS property name.</param> /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more CSS properties for the set of matched elements.</summary> /// <param name="properties" type="PlainObject">An object of property-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> }, 'data': function() { /// <signature> /// <summary>Store arbitrary data associated with the matched elements.</summary> /// <param name="key" type="String">A string naming the piece of data to set.</param> /// <param name="value" type="Object">The new data value; it can be any Javascript type including Array or Object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Store arbitrary data associated with the matched elements.</summary> /// <param name="obj" type="Object">An object of key-value pairs of data to update.</param> /// <returns type="jQuery" /> /// </signature> }, 'dblclick': function() { /// <signature> /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'delay': function() { /// <signature> /// <summary>Set a timer to delay execution of subsequent items in the queue.</summary> /// <param name="duration" type="Number">An integer indicating the number of milliseconds to delay execution of the next item in the queue.</param> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'delegate': function() { /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> /// <param name="events" type="PlainObject">A plain object of one or more event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'dequeue': function() { /// <signature> /// <summary>Execute the next function on the queue for the matched elements.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <returns type="jQuery" /> /// </signature> }, 'descendant': function() { /// <signature> /// <summary>Selects all elements that are descendants of a given ancestor.</summary> /// <param name="ancestor" type="String">Any valid selector.</param> /// <param name="descendant" type="String">A selector to filter the descendant elements.</param> /// </signature> }, 'detach': function() { /// <signature> /// <summary>Remove the set of matched elements from the DOM.</summary> /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'die': function() { /// <signature> /// <summary>Remove event handlers previously attached using .live() from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or keydown.</param> /// <param name="handler" type="String">The function that is no longer to be executed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove event handlers previously attached using .live() from the elements.</summary> /// <param name="events" type="PlainObject">A plain object of one or more event types, such as click or keydown and their corresponding functions that are no longer to be executed.</param> /// <returns type="jQuery" /> /// </signature> }, 'disabled': function() { /// <summary>Selects all elements that are disabled.</summary> }, 'each': function() { /// <signature> /// <summary>Iterate over a jQuery object, executing a function for each matched element.</summary> /// <param name="function(index, Element)" type="Function">A function to execute for each matched element.</param> /// <returns type="jQuery" /> /// </signature> }, 'element': function() { /// <signature> /// <summary>Selects all elements with the given tag name.</summary> /// <param name="element" type="String">An element to search for. Refers to the tagName of DOM nodes.</param> /// </signature> }, 'empty': function() { /// <summary>Select all elements that have no children (including text nodes).</summary> }, 'enabled': function() { /// <summary>Selects all elements that are enabled.</summary> }, 'end': function() { /// <summary>End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.</summary> /// <returns type="jQuery" /> }, 'eq': function() { /// <signature> /// <summary>Select the element at index n within the matched set.</summary> /// <param name="index" type="Number">Zero-based index of the element to match.</param> /// </signature> /// <signature> /// <summary>Select the element at index n within the matched set.</summary> /// <param name="-index" type="Number">Zero-based index of the element to match, counting backwards from the last element.</param> /// </signature> }, 'error': function() { /// <signature> /// <summary>Bind an event handler to the "error" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "error" JavaScript event.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'even': function() { /// <summary>Selects even elements, zero-indexed. See also odd.</summary> }, 'fadeIn': function() { /// <signature> /// <summary>Display the matched elements by fading them to opaque.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements by fading them to opaque.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements by fading them to opaque.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeOut': function() { /// <signature> /// <summary>Hide the matched elements by fading them to transparent.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements by fading them to transparent.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements by fading them to transparent.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeTo': function() { /// <signature> /// <summary>Adjust the opacity of the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Adjust the opacity of the matched elements.</summary> /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'fadeToggle': function() { /// <signature> /// <summary>Display or hide the matched elements by animating their opacity.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements by animating their opacity.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> }, 'file': function() { /// <summary>Selects all elements of type file.</summary> }, 'filter': function() { /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="selector" type="String">A string containing a selector expression to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="element" type="Element">An element to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'find': function() { /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="jQuery object" type="Object">A jQuery object to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> /// <param name="element" type="Element">An element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'finish': function() { /// <signature> /// <summary>Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.</summary> /// <param name="queue" type="String">The name of the queue in which to stop animations.</param> /// <returns type="jQuery" /> /// </signature> }, 'first': function() { /// <summary>Selects the first matched element.</summary> }, 'first-child': function() { /// <summary>Selects all elements that are the first child of their parent.</summary> }, 'first-of-type': function() { /// <summary>Selects all elements that are the first among siblings of the same element name.</summary> }, 'focus': function() { /// <signature> /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'focusin': function() { /// <signature> /// <summary>Bind an event handler to the "focusin" event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focusin" event.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'focusout': function() { /// <signature> /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> /// <param name="eventData" type="Object">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'get': function() { /// <signature> /// <summary>Retrieve the DOM elements matched by the jQuery object.</summary> /// <param name="index" type="Number">A zero-based integer indicating which element to retrieve.</param> /// <returns type="Element, Array" /> /// </signature> }, 'gt': function() { /// <signature> /// <summary>Select all elements at an index greater than index within the matched set.</summary> /// <param name="index" type="Number">Zero-based index.</param> /// </signature> }, 'has': function() { /// <signature> /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> /// <param name="contained" type="Element">A DOM element to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'hasClass': function() { /// <signature> /// <summary>Determine whether any of the matched elements are assigned the given class.</summary> /// <param name="className" type="String">The class name to search for.</param> /// <returns type="Boolean" /> /// </signature> }, 'header': function() { /// <summary>Selects all elements that are headers, like h1, h2, h3 and so on.</summary> }, 'height': function() { /// <signature> /// <summary>Set the CSS height of every matched element.</summary> /// <param name="value" type="Number">An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the CSS height of every matched element.</summary> /// <param name="function(index, height)" type="Function">A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'hidden': function() { /// <summary>Selects all elements that are hidden.</summary> }, 'hide': function() { /// <signature> /// <summary>Hide the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'hover': function() { /// <signature> /// <summary>Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.</summary> /// <param name="handlerIn(eventObject)" type="Function">A function to execute when the mouse pointer enters the element.</param> /// <param name="handlerOut(eventObject)" type="Function">A function to execute when the mouse pointer leaves the element.</param> /// <returns type="jQuery" /> /// </signature> }, 'html': function() { /// <signature> /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> /// <param name="htmlString" type="String">A string of HTML to set as the content of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> /// <param name="function(index, oldhtml)" type="Function">A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'id': function() { /// <signature> /// <summary>Selects a single element with the given id attribute.</summary> /// <param name="id" type="String">An ID to search for, specified via the id attribute of an element.</param> /// </signature> }, 'image': function() { /// <summary>Selects all elements of type image.</summary> }, 'index': function() { /// <signature> /// <summary>Search for a given element from among the matched elements.</summary> /// <param name="selector" type="String">A selector representing a jQuery collection in which to look for an element.</param> /// <returns type="Number" /> /// </signature> /// <signature> /// <summary>Search for a given element from among the matched elements.</summary> /// <param name="element" type="jQuery">The DOM element or first element within the jQuery object to look for.</param> /// <returns type="Number" /> /// </signature> }, 'init': function() { /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="selector" type="String">A string containing a selector expression</param> /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="object" type="PlainObject">A plain object to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="jQuery object" type="PlainObject">An existing jQuery object to clone.</param> /// <returns type="jQuery" /> /// </signature> }, 'innerHeight': function() { /// <summary>Get the current computed height for the first element in the set of matched elements, including padding but not border.</summary> /// <returns type="Integer" /> }, 'innerWidth': function() { /// <summary>Get the current computed width for the first element in the set of matched elements, including padding but not border.</summary> /// <returns type="Integer" /> }, 'input': function() { /// <summary>Selects all input, textarea, select and button elements.</summary> }, 'insertAfter': function() { /// <signature> /// <summary>Insert every element in the set of matched elements after the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'insertBefore': function() { /// <signature> /// <summary>Insert every element in the set of matched elements before the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'is': function() { /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="function(index)" type="Function">A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> /// <returns type="Boolean" /> /// </signature> /// <signature> /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> /// <param name="element" type="Element">An element to match the current set of elements against.</param> /// <returns type="Boolean" /> /// </signature> }, 'jquery': function() { /// <summary>A string containing the jQuery version number.</summary> /// <returns type="String" /> }, 'keydown': function() { /// <signature> /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'keypress': function() { /// <signature> /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'keyup': function() { /// <signature> /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'lang': function() { /// <signature> /// <summary>Selects all elements of the specified language.</summary> /// <param name="language" type="String">A language code.</param> /// </signature> }, 'last': function() { /// <summary>Selects the last matched element.</summary> }, 'last-child': function() { /// <summary>Selects all elements that are the last child of their parent.</summary> }, 'last-of-type': function() { /// <summary>Selects all elements that are the last among siblings of the same element name.</summary> }, 'length': function() { /// <summary>The number of elements in the jQuery object.</summary> /// <returns type="Number" /> }, 'live': function() { /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> /// <param name="data" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> /// <param name="events" type="PlainObject">A plain object of one or more JavaScript event types and functions to execute for them.</param> /// <returns type="jQuery" /> /// </signature> }, 'load': function() { /// <signature> /// <summary>Bind an event handler to the "load" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "load" JavaScript event.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'lt': function() { /// <signature> /// <summary>Select all elements at an index less than index within the matched set.</summary> /// <param name="index" type="Number">Zero-based index.</param> /// </signature> }, 'map': function() { /// <signature> /// <summary>Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.</summary> /// <param name="callback(index, domElement)" type="Function">A function object that will be invoked for each element in the current set.</param> /// <returns type="jQuery" /> /// </signature> }, 'mousedown': function() { /// <signature> /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseenter': function() { /// <signature> /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseleave': function() { /// <signature> /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mousemove': function() { /// <signature> /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseout': function() { /// <signature> /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseover': function() { /// <signature> /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'mouseup': function() { /// <signature> /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'multiple': function() { /// <signature> /// <summary>Selects the combined results of all the specified selectors.</summary> /// <param name="selector1" type="String">Any valid selector.</param> /// <param name="selector2" type="String">Another valid selector.</param> /// <param name="selectorN" type="String">As many more valid selectors as you like.</param> /// </signature> }, 'next': function() { /// <signature> /// <summary>Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'next adjacent': function() { /// <signature> /// <summary>Selects all next elements matching "next" that are immediately preceded by a sibling "prev".</summary> /// <param name="prev" type="String">Any valid selector.</param> /// <param name="next" type="String">A selector to match the element that is next to the first selector.</param> /// </signature> }, 'next siblings': function() { /// <signature> /// <summary>Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.</summary> /// <param name="prev" type="String">Any valid selector.</param> /// <param name="siblings" type="String">A selector to filter elements that are the following siblings of the first selector.</param> /// </signature> }, 'nextAll': function() { /// <signature> /// <summary>Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'nextUntil': function() { /// <signature> /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching following sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching following sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'not': function() { /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="elements" type="Array">One or more DOM elements to remove from the matched set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="jQuery object" type="PlainObject">An existing jQuery object to match the current set of elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'nth-child': function() { /// <signature> /// <summary>Selects all elements that are the nth-child of their parent.</summary> /// <param name="index" type="String">The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) )</param> /// </signature> }, 'nth-last-child': function() { /// <signature> /// <summary>Selects all elements that are the nth-child of their parent, counting from the last element to the first.</summary> /// <param name="index" type="String">The index of each child to match, starting with the last one (1), the string even or odd, or an equation ( eg. :nth-last-child(even), :nth-last-child(4n) )</param> /// </signature> }, 'nth-last-of-type': function() { /// <signature> /// <summary>Selects all elements that are the nth-child of their parent, counting from the last element to the first.</summary> /// <param name="index" type="String">The index of each child to match, starting with the last one (1), the string even or odd, or an equation ( eg. :nth-last-of-type(even), :nth-last-of-type(4n) )</param> /// </signature> }, 'nth-of-type': function() { /// <signature> /// <summary>Selects all elements that are the nth child of their parent in relation to siblings with the same element name.</summary> /// <param name="index" type="String">The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-of-type(even), :nth-of-type(4n) )</param> /// </signature> }, 'odd': function() { /// <summary>Selects odd elements, zero-indexed. See also even.</summary> }, 'off': function() { /// <signature> /// <summary>Remove an event handler.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".</param> /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> /// <param name="handler(eventObject)" type="Function">A handler function previously attached for the event(s), or the special value false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove an event handler.</summary> /// <param name="events" type="PlainObject">An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).</param> /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> /// <returns type="jQuery" /> /// </signature> }, 'offset': function() { /// <signature> /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> /// <param name="coordinates" type="PlainObject">An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> /// <param name="function(index, coords)" type="Function">A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.</param> /// <returns type="jQuery" /> /// </signature> }, 'offsetParent': function() { /// <summary>Get the closest ancestor element that is positioned.</summary> /// <returns type="jQuery" /> }, 'on': function() { /// <signature> /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> /// <param name="events" type="PlainObject">An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> /// <returns type="jQuery" /> /// </signature> }, 'one': function() { /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events" type="String">A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.</param> /// <param name="data" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> /// <param name="events" type="PlainObject">An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> /// <returns type="jQuery" /> /// </signature> }, 'only-child': function() { /// <summary>Selects all elements that are the only child of their parent.</summary> }, 'only-of-type': function() { /// <summary>Selects all elements that have no siblings with the same element name.</summary> }, 'outerHeight': function() { /// <signature> /// <summary>Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements.</summary> /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> /// <returns type="Integer" /> /// </signature> }, 'outerWidth': function() { /// <signature> /// <summary>Get the current computed width for the first element in the set of matched elements, including padding and border.</summary> /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> /// <returns type="Integer" /> /// </signature> }, 'parent': function() { /// <signature> /// <summary>Get the parent of each element in the current set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'parents': function() { /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'parentsUntil': function() { /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching ancestor elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching ancestor elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'password': function() { /// <summary>Selects all elements of type password.</summary> }, 'position': function() { /// <summary>Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.</summary> /// <returns type="Object" /> }, 'prepend': function() { /// <signature> /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> /// <param name="content" type="jQuery">DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.</param> /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'prependTo': function() { /// <signature> /// <summary>Insert every element in the set of matched elements to the beginning of the target.</summary> /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.</param> /// <returns type="jQuery" /> /// </signature> }, 'prev': function() { /// <signature> /// <summary>Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'prevAll': function() { /// <signature> /// <summary>Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'prevUntil': function() { /// <signature> /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching preceding sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching preceding sibling elements.</param> /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'promise': function() { /// <signature> /// <summary>Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.</summary> /// <param name="type" type="String">The type of queue that needs to be observed.</param> /// <param name="target" type="PlainObject">Object onto which the promise methods have to be attached</param> /// <returns type="Promise" /> /// </signature> }, 'prop': function() { /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to set.</param> /// <param name="value" type="Boolean">A value to set for the property.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="properties" type="PlainObject">An object of property-value pairs to set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set one or more properties for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to set.</param> /// <param name="function(index, oldPropertyValue)" type="Function">A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.</param> /// <returns type="jQuery" /> /// </signature> }, 'pushStack': function() { /// <signature> /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> /// <param name="name" type="String">The name of a jQuery method that generated the array of elements.</param> /// <param name="arguments" type="Array">The arguments that were passed in to the jQuery method (for serialization).</param> /// <returns type="jQuery" /> /// </signature> }, 'queue': function() { /// <signature> /// <summary>Manipulate the queue of functions to be executed, once for each matched element.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Manipulate the queue of functions to be executed, once for each matched element.</summary> /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> /// <param name="callback( next )" type="Function">The new function to add to the queue, with a function to call that will dequeue the next item.</param> /// <returns type="jQuery" /> /// </signature> }, 'radio': function() { /// <summary>Selects all elements of type radio.</summary> }, 'ready': function() { /// <signature> /// <summary>Specify a function to execute when the DOM is fully loaded.</summary> /// <param name="handler" type="Function">A function to execute after the DOM is ready.</param> /// <returns type="jQuery" /> /// </signature> }, 'remove': function() { /// <signature> /// <summary>Remove the set of matched elements from the DOM.</summary> /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeAttr': function() { /// <signature> /// <summary>Remove an attribute from each element in the set of matched elements.</summary> /// <param name="attributeName" type="String">An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeClass': function() { /// <signature> /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> /// <param name="className" type="String">One or more space-separated classes to be removed from the class attribute of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> /// <param name="function(index, class)" type="Function">A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeData': function() { /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="name" type="String">A string naming the piece of data to delete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-stored piece of data.</summary> /// <param name="list" type="String">An array or space-separated string naming the pieces of data to delete.</param> /// <returns type="jQuery" /> /// </signature> }, 'removeProp': function() { /// <signature> /// <summary>Remove a property for the set of matched elements.</summary> /// <param name="propertyName" type="String">The name of the property to remove.</param> /// <returns type="jQuery" /> /// </signature> }, 'replaceAll': function() { /// <signature> /// <summary>Replace each target element with the set of matched elements.</summary> /// <param name="target" type="String">A selector expression indicating which element(s) to replace.</param> /// <returns type="jQuery" /> /// </signature> }, 'replaceWith': function() { /// <signature> /// <summary>Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.</summary> /// <param name="newContent" type="jQuery">The content to insert. May be an HTML string, DOM element, or jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.</summary> /// <param name="function" type="Function">A function that returns content with which to replace the set of matched elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'reset': function() { /// <summary>Selects all elements of type reset.</summary> }, 'resize': function() { /// <signature> /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'root': function() { /// <signature> /// <summary>Selects the element that is the root of the document.</summary> /// <param name="index" type="String">The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-last-child(even), :nth-last-child(4n) )</param> /// </signature> }, 'scroll': function() { /// <signature> /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'scrollLeft': function() { /// <signature> /// <summary>Set the current horizontal position of the scroll bar for each of the set of matched elements.</summary> /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> /// <returns type="jQuery" /> /// </signature> }, 'scrollTop': function() { /// <signature> /// <summary>Set the current vertical position of the scroll bar for each of the set of matched elements.</summary> /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> /// <returns type="jQuery" /> /// </signature> }, 'select': function() { /// <signature> /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'selected': function() { /// <summary>Selects all elements that are selected.</summary> }, 'selector': function() { /// <summary>A selector representing selector originally passed to jQuery().</summary> /// <returns type="String" /> }, 'serialize': function() { /// <summary>Encode a set of form elements as a string for submission.</summary> /// <returns type="String" /> }, 'serializeArray': function() { /// <summary>Encode a set of form elements as an array of names and values.</summary> /// <returns type="Array" /> }, 'show': function() { /// <signature> /// <summary>Display the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'siblings': function() { /// <signature> /// <summary>Get the siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> /// <returns type="jQuery" /> /// </signature> }, 'size': function() { /// <summary>Return the number of elements in the jQuery object.</summary> /// <returns type="Number" /> }, 'slice': function() { /// <signature> /// <summary>Reduce the set of matched elements to a subset specified by a range of indices.</summary> /// <param name="start" type="Number">An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.</param> /// <param name="end" type="Number">An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideDown': function() { /// <signature> /// <summary>Display the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements with a sliding motion.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideToggle': function() { /// <signature> /// <summary>Display or hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements with a sliding motion.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'slideUp': function() { /// <signature> /// <summary>Hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements with a sliding motion.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Hide the matched elements with a sliding motion.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> }, 'stop': function() { /// <signature> /// <summary>Stop the currently-running animation on the matched elements.</summary> /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Stop the currently-running animation on the matched elements.</summary> /// <param name="queue" type="String">The name of the queue in which to stop animations.</param> /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> /// <returns type="jQuery" /> /// </signature> }, 'submit': function() { /// <signature> /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> /// <param name="eventData" type="PlainObject">An object containing data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'target': function() { /// <summary>Selects the target element indicated by the fragment identifier of the document's URI.</summary> }, 'text': function() { /// <signature> /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> /// <param name="textString" type="String">A string of text to set as the content of each matched element.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> /// <param name="function(index, text)" type="Function">A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'toArray': function() { /// <summary>Retrieve all the DOM elements contained in the jQuery set, as an array.</summary> /// <returns type="Array" /> }, 'toggle': function() { /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="options" type="PlainObject">A map of additional options to pass to the method.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="duration" type="">A string or number determining how long the animation will run.</param> /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> /// <param name="complete" type="Function">A function to call once the animation is complete.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Display or hide the matched elements.</summary> /// <param name="showOrHide" type="Boolean">A Boolean indicating whether to show or hide the elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'toggleClass': function() { /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> /// <param name="switch" type="Boolean">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> /// <param name="function(index, class, switch)" type="Function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param> /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> /// <returns type="jQuery" /> /// </signature> }, 'trigger': function() { /// <signature> /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="extraParameters" type="PlainObject">Additional parameters to pass along to the event handler.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> /// <param name="event" type="Event">A jQuery.Event object.</param> /// <returns type="jQuery" /> /// </signature> }, 'triggerHandler': function() { /// <signature> /// <summary>Execute all handlers attached to an element for an event.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="extraParameters" type="Array">An array of additional parameters to pass along to the event handler.</param> /// <returns type="Object" /> /// </signature> }, 'unbind': function() { /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="handler(eventObject)" type="Function">The function that is to be no longer executed.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> /// <param name="false" type="Boolean">Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a previously-attached event handler from the elements.</summary> /// <param name="event" type="Object">A JavaScript event object as passed to an event handler.</param> /// <returns type="jQuery" /> /// </signature> }, 'undelegate': function() { /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> /// <param name="events" type="PlainObject">An object of one or more event types and previously bound functions to unbind from them.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> /// <param name="namespace" type="String">A string containing a namespace to unbind all events from.</param> /// <returns type="jQuery" /> /// </signature> }, 'unload': function() { /// <signature> /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> /// <param name="eventData" type="Object">A plain object of data that will be passed to the event handler.</param> /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> /// <returns type="jQuery" /> /// </signature> }, 'unwrap': function() { /// <summary>Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.</summary> /// <returns type="jQuery" /> }, 'val': function() { /// <signature> /// <summary>Set the value of each element in the set of matched elements.</summary> /// <param name="value" type="Array">A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the value of each element in the set of matched elements.</summary> /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> /// <returns type="jQuery" /> /// </signature> }, 'visible': function() { /// <summary>Selects all elements that are visible.</summary> }, 'width': function() { /// <signature> /// <summary>Set the CSS width of each element in the set of matched elements.</summary> /// <param name="value" type="Number">An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Set the CSS width of each element in the set of matched elements.</summary> /// <param name="function(index, width)" type="Function">A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrap': function() { /// <signature> /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrapAll': function() { /// <signature> /// <summary>Wrap an HTML structure around all elements in the set of matched elements.</summary> /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> /// <returns type="jQuery" /> /// </signature> }, 'wrapInner': function() { /// <signature> /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> /// <param name="wrappingElement" type="String">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> /// <param name="function(index)" type="Function">A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> /// <returns type="jQuery" /> /// </signature> }, }); intellisense.annotate(window, { '$': function() { /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="selector" type="String">A string containing a selector expression</param> /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="object" type="PlainObject">A plain object to wrap in a jQuery object.</param> /// <returns type="jQuery" /> /// </signature> /// <signature> /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> /// <param name="jQuery object" type="PlainObject">An existing jQuery object to clone.</param> /// <returns type="jQuery" /> /// </signature> }, });
kevhoyt/PnP
Samples/Core.MailApps/Core.MailAppsWeb/Scripts/jquery-1.9.1.intellisense.js
JavaScript
apache-2.0
160,971
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jetty; import java.util.HashMap; import java.util.Map; import org.apache.camel.builder.RouteBuilder; import org.eclipse.jetty.server.Server; import org.junit.Test; public class JettyRouteWithUnknownSslSocketPropertiesTest extends BaseJettyTest { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testUnknownProperty() throws Exception { if (!Server.getVersion().startsWith("8")) { // SocketConnector props do not work for jetty 9 return; } context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { // define socket connector properties Map<String, Object> properties = new HashMap<String, Object>(); properties.put("acceptors", 4); properties.put("statsOn", "false"); properties.put("soLingerTime", "5000"); properties.put("doesNotExist", 2000); JettyHttpComponent jetty = getContext().getComponent("jetty", JettyHttpComponent.class); jetty.setSslSocketConnectorProperties(properties); from("jetty:https://localhost:{{port}}/myapp/myservice").to("log:foo"); } }); try { context.start(); fail("Should have thrown exception"); } catch (Exception e) { IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertTrue("Actual message: " + iae.getMessage(), iae.getMessage().endsWith("Unknown parameters=[{doesNotExist=2000}]")); } } }
anton-k11/camel
components/camel-jetty9/src/test/java/org/apache/camel/component/jetty/JettyRouteWithUnknownSslSocketPropertiesTest.java
Java
apache-2.0
2,525
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing.Route * @since CakePHP(tm) v 2.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ App::uses('CakeResponse', 'Network'); App::uses('CakeRoute', 'Routing/Route'); /** * Redirect route will perform an immediate redirect. Redirect routes * are useful when you want to have Routing layer redirects occur in your * application, for when URLs move. * * @package Cake.Routing.Route */ class RedirectRoute extends CakeRoute { /** * A CakeResponse object * * @var CakeResponse */ public $response = null; /** * The location to redirect to. Either a string or a CakePHP array URL. * * @var mixed */ public $redirect; /** * Flag for disabling exit() when this route parses a URL. * * @var boolean */ public $stop = true; /** * Constructor * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param array $options Array of additional options for the Route */ public function __construct($template, $defaults = array(), $options = array()) { parent::__construct($template, $defaults, $options); $this->redirect = (array)$defaults; } /** * Parses a string URL into an array. Parsed URLs will result in an automatic * redirection * * @param string $url The URL to parse * @return boolean False on failure */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } if (!$this->response) { $this->response = new CakeResponse(); } $redirect = $this->redirect; if (count($this->redirect) === 1 && !isset($this->redirect['controller'])) { $redirect = $this->redirect[0]; } if (isset($this->options['persist']) && is_array($redirect)) { $redirect += array('named' => $params['named'], 'pass' => $params['pass'], 'url' => array()); if (is_array($this->options['persist'])) { foreach ($this->options['persist'] as $elem) { if (isset($params[$elem])) { $redirect[$elem] = $params[$elem]; } } } $redirect = Router::reverse($redirect); } $status = 301; if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) { $status = $this->options['status']; } $this->response->header(array('Location' => Router::url($redirect, true))); $this->response->statusCode($status); $this->response->send(); $this->_stop(); } /** * There is no reverse routing redirection routes * * @param array $url Array of parameters to convert to a string. * @return mixed either false or a string URL. */ public function match($url) { return false; } /** * Stop execution of the current script. Wraps exit() making * testing easier. * * @param integer|string $code See http://php.net/exit for values * @return void */ protected function _stop($code = 0) { if ($this->stop) { exit($code); } } }
jan-randis/php-db2-mysql-buildpack
cf_spec/fixtures/cake_local_deps/lib/Cake/Routing/Route/RedirectRoute.php
PHP
apache-2.0
3,420
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package rc2 implements the RC2 cipher /* https://www.ietf.org/rfc/rfc2268.txt http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf This code is licensed under the MIT license. */ package rc2 import ( "crypto/cipher" "encoding/binary" ) // The rc2 block size in bytes const BlockSize = 8 type rc2Cipher struct { k [64]uint16 } // New returns a new rc2 cipher with the given key and effective key length t1 func New(key []byte, t1 int) (cipher.Block, error) { // TODO(dgryski): error checking for key length return &rc2Cipher{ k: expandKey(key, t1), }, nil } func (*rc2Cipher) BlockSize() int { return BlockSize } var piTable = [256]byte{ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, } func expandKey(key []byte, t1 int) [64]uint16 { l := make([]byte, 128) copy(l, key) var t = len(key) var t8 = (t1 + 7) / 8 var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) for i := len(key); i < 128; i++ { l[i] = piTable[l[i-1]+l[uint8(i-t)]] } l[128-t8] = piTable[l[128-t8]&tm] for i := 127 - t8; i >= 0; i-- { l[i] = piTable[l[i+1]^l[i+t8]] } var k [64]uint16 for i := range k { k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 } return k } func rotl16(x uint16, b uint) uint16 { return (x >> (16 - b)) | (x << b) } func (c *rc2Cipher) Encrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) var j int for j <= 16 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 40 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } r0 = r0 + c.k[r3&63] r1 = r1 + c.k[r0&63] r2 = r2 + c.k[r1&63] r3 = r3 + c.k[r2&63] for j <= 60 { // mix r0 r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) r0 = rotl16(r0, 1) j++ // mix r1 r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) r1 = rotl16(r1, 2) j++ // mix r2 r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) r2 = rotl16(r2, 3) j++ // mix r3 r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) r3 = rotl16(r3, 5) j++ } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) } func (c *rc2Cipher) Decrypt(dst, src []byte) { r0 := binary.LittleEndian.Uint16(src[0:]) r1 := binary.LittleEndian.Uint16(src[2:]) r2 := binary.LittleEndian.Uint16(src[4:]) r3 := binary.LittleEndian.Uint16(src[6:]) j := 63 for j >= 44 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 20 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } r3 = r3 - c.k[r2&63] r2 = r2 - c.k[r1&63] r1 = r1 - c.k[r0&63] r0 = r0 - c.k[r3&63] for j >= 0 { // unmix r3 r3 = rotl16(r3, 16-5) r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) j-- // unmix r2 r2 = rotl16(r2, 16-3) r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) j-- // unmix r1 r1 = rotl16(r1, 16-2) r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) j-- // unmix r0 r0 = rotl16(r0, 16-1) r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) j-- } binary.LittleEndian.PutUint16(dst[0:], r0) binary.LittleEndian.PutUint16(dst[2:], r1) binary.LittleEndian.PutUint16(dst[4:], r2) binary.LittleEndian.PutUint16(dst[6:], r3) }
wanghaoran1988/origin
cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go
GO
apache-2.0
6,333
/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package lru implements an LRU cache. package lru import "container/list" // Cache is an LRU cache. It is not safe for concurrent access. type Cache struct { // MaxEntries is the maximum number of cache entries before // an item is evicted. Zero means no limit. MaxEntries int // OnEvicted optionally specificies a callback function to be // executed when an entry is purged from the cache. OnEvicted func(key Key, value interface{}) ll *list.List cache map[interface{}]*list.Element } // A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators type Key interface{} type entry struct { key Key value interface{} } // New creates a new Cache. // If maxEntries is zero, the cache has no limit and it's assumed // that eviction is done by the caller. func New(maxEntries int) *Cache { return &Cache{ MaxEntries: maxEntries, ll: list.New(), cache: make(map[interface{}]*list.Element), } } // Add adds a value to the cache. func (c *Cache) Add(key Key, value interface{}) { if c.cache == nil { c.cache = make(map[interface{}]*list.Element) c.ll = list.New() } if ee, ok := c.cache[key]; ok { c.ll.MoveToFront(ee) ee.Value.(*entry).value = value return } ele := c.ll.PushFront(&entry{key, value}) c.cache[key] = ele if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { c.RemoveOldest() } } // Get looks up a key's value from the cache. func (c *Cache) Get(key Key) (value interface{}, ok bool) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.ll.MoveToFront(ele) return ele.Value.(*entry).value, true } return } // Remove removes the provided key from the cache. func (c *Cache) Remove(key Key) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.removeElement(ele) } } // RemoveOldest removes the oldest item from the cache. func (c *Cache) RemoveOldest() { if c.cache == nil { return } ele := c.ll.Back() if ele != nil { c.removeElement(ele) } } func (c *Cache) removeElement(e *list.Element) { c.ll.Remove(e) kv := e.Value.(*entry) delete(c.cache, kv.key) if c.OnEvicted != nil { c.OnEvicted(kv.key, kv.value) } } // Len returns the number of items in the cache. func (c *Cache) Len() int { if c.cache == nil { return 0 } return c.ll.Len() }
jmccarty3/kubernetes
Godeps/_workspace/src/github.com/golang/groupcache/lru/lru.go
GO
apache-2.0
2,883
/*! * depd * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module exports. * @public */ module.exports = depd /** * Create deprecate for namespace in caller. */ function depd(namespace) { if (!namespace) { throw new TypeError('argument namespace is required') } function deprecate(message) { // no-op in browser } deprecate._file = undefined deprecate._ignored = true deprecate._namespace = namespace deprecate._traced = false deprecate._warned = Object.create(null) deprecate.function = wrapfunction deprecate.property = wrapproperty return deprecate } /** * Return a wrapped function in a deprecation message. * * This is a no-op version of the wrapper, which does nothing but call * validation. */ function wrapfunction(fn, message) { if (typeof fn !== 'function') { throw new TypeError('argument fn must be a function') } return fn } /** * Wrap property in a deprecation message. * * This is a no-op version of the wrapper, which does nothing but call * validation. */ function wrapproperty(obj, prop, message) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('argument obj must be object') } var descriptor = Object.getOwnPropertyDescriptor(obj, prop) if (!descriptor) { throw new TypeError('must call property on owner object') } if (!descriptor.configurable) { throw new TypeError('property must be configurable') } return }
dyf102/TinyURL
server/node_modules/depd/lib/browser/index.js
JavaScript
apache-2.0
1,518
package util import ( "strings" "testing" ) func TestReadInputFromTerminal(t *testing.T) { testcases := map[string]struct { Input string Output string }{ "empty": {}, "empty newline": {Input: "\n"}, "empty windows newline": {Input: "\r\n"}, "empty newline with extra": {Input: "\nextra"}, "leading space": {Input: " data", Output: " data"}, "leading space newline": {Input: " data\n", Output: " data"}, "leading space windows newline": {Input: " data\r\n", Output: " data"}, "leading space newline with extra": {Input: " data\nextra", Output: " data"}, "trailing space": {Input: " data ", Output: " data "}, "trailing space newline": {Input: " data \n", Output: " data "}, "trailing space windows newline": {Input: " data \r\n", Output: " data "}, "trailing space newline with extra": {Input: " data \nextra", Output: " data "}, } for k, tc := range testcases { output := readInputFromTerminal(strings.NewReader(tc.Input)) if output != tc.Output { t.Errorf("%s: Expected '%s', got '%s'", k, tc.Output, output) } } }
jhadvig/origin
pkg/cmd/util/terminal_test.go
GO
apache-2.0
1,203
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview Initializes the remote client UI. */ goog.require('remote.ui.Client'); goog.require('webdriver.http.Executor'); goog.require('webdriver.http.XhrClient'); goog.exportSymbol('init', function() { // On the java Selenium server, this script and other files in the UI // are served by org.openqa.selenium.remote.server.DriverServlet under // the /static/resource path. We need to drop this so commands are // relative to the DriverServlet's root. var loc = window.location; var href = [ loc.protocol, '//', loc.host, loc.pathname.replace(/\/static\/resource(?:\/[^\/]*)?$/, '') ].join(''); var executor = new webdriver.http.Executor( new webdriver.http.XhrClient(href)); var client = new remote.ui.Client(href, executor); client.init(); });
gemini-testing/selenium
javascript/remote/client.js
JavaScript
apache-2.0
1,602
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty4.codec; import java.net.InetSocketAddress; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.AddressedEnvelope; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.DefaultAddressedEnvelope; import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.handler.codec.serialization.ClassResolver; public class DatagramPacketObjectDecoder extends MessageToMessageDecoder<AddressedEnvelope<Object, InetSocketAddress>> { private final ObjectDecoder delegateDecoder; public DatagramPacketObjectDecoder(ClassResolver resolver) { delegateDecoder = new ObjectDecoder(resolver); } @Override protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception { if (msg.content() instanceof ByteBuf) { ByteBuf payload = (ByteBuf) msg.content(); Object result = delegateDecoder.decode(ctx, payload); AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<Object, InetSocketAddress>(result, msg.recipient(), msg.sender()); out.add(addressedEnvelop); } } }
tarilabs/camel
components/camel-netty4/src/main/java/org/apache/camel/component/netty4/codec/DatagramPacketObjectDecoder.java
Java
apache-2.0
2,105
<!doctype html> <html lang="{{ config('app.locale') }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @if (Auth::check()) <a href="{{ url('/home') }}">Home</a> @else <a href="{{ url('/login') }}">Login</a> <a href="{{ url('/register') }}">Register</a> @endif </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> <div class="links"> <a href="https://laravel.com/docs">Documentation</a> <a href="https://laracasts.com">Laracasts</a> <a href="https://laravel-news.com">News</a> <a href="https://forge.laravel.com">Forge</a> <a href="https://github.com/laravel/laravel">GitHub</a> </div> </div> </div> </body> </html>
canylmz/Laravel-5.4-Blog
resources/views/welcome.blade.php
PHP
apache-2.0
2,748
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package scheme import ( apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" serializer "k8s.io/apimachinery/pkg/runtime/serializer" utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) var Scheme = runtime.NewScheme() var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ apiextensionsv1beta1.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // // import ( // "k8s.io/client-go/kubernetes" // clientsetscheme "k8s.io/client-go/kubernetes/scheme" // aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" // ) // // kclientset, _ := kubernetes.NewForConfig(c) // _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. var AddToScheme = localSchemeBuilder.AddToScheme func init() { v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) utilruntime.Must(AddToScheme(Scheme)) }
krzyzacy/kubernetes
staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/register.go
GO
apache-2.0
1,939
#!/usr/bin/env bash # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # This script invokes dist_mnist.py multiple times concurrently to test the # TensorFlow's distributed runtime over a Kubernetes (k8s) cluster with the # grpc pods and service set up. # # Usage: # dist_mnist_test.sh [--existing_servers (True|False)] # [--ps_hosts <PS_HOSTS>] # [--worker_hosts <WORKER_HOSTS>] # [--num_gpus <NUM_GPUS>] # [--sync_replicas] # # --existing_servers # Use TensorFlow GRPC servers that are already created and running. # # --sync_replicas # Use the synchronized-replica mode. The parameter updates from the replicas # (workers) will be aggregated before applied, which avoids stale parameter # updates. # # ps_hosts/worker_hosts is the list of IP addresses or the GRPC URLs of the ps/worker of # the worker sessions, separated with "," # e.g., "localhost:2222,localhost:2223" # # --num_gpus <NUM_GPUS>: # Specifies the number of gpus to use # # NOTES: # If you have the error "$'\r': command not found" # Please run the command below to remove trailing '\r' character that causes the error: # sed -i 's/\r$//' dist_mnist_test.sh # Configurations TIMEOUT=120 # Timeout for MNIST replica sessions # Helper functions die() { echo $@ exit 1 } if [[ $# == "0" ]]; then die "Usage: $0 [--ps_hosts <PS_HOSTS>] [--worker_hosts <WORKER_HOSTS>] "\ "[--num_gpus <NUM_GPUS>] [--sync_replicas]" fi # Process additional input arguments SYNC_REPLICAS=0 N_GPUS=0 EXISTING_SERVERS=False while true; do if [[ "$1" == "--ps_hosts" ]]; then PS_HOSTS=$2 shift 2 elif [[ "$1" == "--worker_hosts" ]]; then WORKER_HOSTS=$2 shift 2 elif [[ "$1" == "--existing_servers" ]]; then EXISTING_SERVERS=$2 shift 2 if [[ "${EXISTING_SERVERS}" != "True" ]] && \ [[ "${EXISTING_SERVERS}" != "False" ]]; then die "Invalid value for --existing_servers: should be (True|False)" fi elif [[ "$1" == "--num_gpus" ]]; then N_GPUS=$2 shift 2 elif [[ "$1" == "--sync_replicas" ]]; then SYNC_REPLICAS="1" shift 1 fi if [[ -z "$1" ]]; then break fi done if [[ ${SYNC_REPLICAS} == "1" ]] && [[ EXISTING_SERVERS == "1" ]]; then die "ERROR: --sync_replicas (synchronized-replicas) mode is not fully "\ "supported under the --existing_servers mode yet." # TODO(cais): Remove error message once sync_replicas is fully supported. fi SYNC_REPLICAS_FLAG="" if [[ ${SYNC_REPLICAS} == "1" ]]; then SYNC_REPLICAS_FLAG="True" else SYNC_REPLICAS_FLAG="False" fi echo "EXISTING_SERVERS = ${EXISTING_SERVERS}" echo "PS_HOSTS = ${PS_HOSTS}" echo "WORKER_HOSTS = ${WORKER_HOSTS}" echo "NUM_GPUS = ${N_GPUS}" echo "SYNC_REPLICAS = ${SYNC_REPLICAS}" echo "SYNC_REPLICAS_FLAG = ${SYNC_REPLICAS_FLAG}" # Current working directory DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PY_DIR=$(dirname "${DIR}")/python MNIST_REPLICA="${PY_DIR}/mnist_replica.py" WKR_LOG_PREFIX="/tmp/worker" PS_LOG_PREFIX="/tmp/ps" # First, download the data from a single process, to avoid race-condition # during data downloading # Pre-download data files. timeout ${TIMEOUT} python "${MNIST_REPLICA}" \ --ps_hosts="${PS_HOSTS}" \ --worker_hosts="${WORKER_HOSTS}" \ --job_name="worker" \ --task_index=0 \ --num_gpus=${N_GPUS} \ --sync_replicas=${SYNC_REPLICAS_FLAG} \ --download_only || \ die "Download-only step of MNIST replica FAILED" # Get N_PS by PS_HOSTS N_PS=$(echo ${PS_HOSTS} | awk -F "," '{printf NF}') # Replace the delimiter with " " PS_ARRAY=($(echo ${PS_HOSTS} | awk -F "," '{for(i=1;i<=NF;i++){printf $i" "}}')) # Run a number of ps in parallel. In general, we only set 1 ps. echo "${N_PS} ps process(es) running in parallel..." if [[ ${EXISTING_SERVERS} == "False" ]]; then echo "Hello" # Create parameter servers. IDX=0 PS=($PS_HOSTS) while true; do python "${MNIST_REPLICA}" \ --existing_servers="${EXISTING_SERVERS}" \ --ps_hosts="${PS_HOSTS}" \ --worker_hosts="${WORKER_HOSTS}" \ --job_name="ps" \ --task_index=${IDX} \ --num_gpus=${N_GPUS} \ --sync_replicas=${SYNC_REPLICAS_FLAG} 2>&1 | tee "${PS_LOG_PREFIX}${IDX}.log" & echo "PS ${IDX}: " echo " PS HOST: ${PS_ARRAY[IDX]}" echo " log file: ${PS_LOG_PREFIX}${IDX}.log" ((IDX++)) if [[ "${IDX}" == "${N_PS}" ]]; then break fi done fi # Get N_WORKERS by WORKER_HOSTS N_WORKERS=$(echo ${WORKER_HOSTS} | awk -F "," '{printf NF}') # Replace the delimiter with " " WORKER_ARRAY=($(echo ${WORKER_HOSTS} | awk -F "," '{for(i=1;i<=NF;i++){printf $i" "}}')) # Run a number of workers in parallel echo "${N_WORKERS} worker process(es) running in parallel..." INDICES="" IDX=0 while true; do timeout ${TIMEOUT} python "${MNIST_REPLICA}" \ --existing_servers="${EXISTING_SERVERS}" \ --ps_hosts="${PS_HOSTS}" \ --worker_hosts="${WORKER_HOSTS}" \ --job_name="worker" \ --task_index=${IDX} \ --num_gpus=${N_GPUS} \ --train_steps=500 \ --sync_replicas=${SYNC_REPLICAS_FLAG} 2>&1 | tee "${WKR_LOG_PREFIX}${IDX}.log" & echo "Worker ${IDX}: " echo " WORKER HOST: ${WORKER_ARRAY[IDX]}" echo " log file: ${WKR_LOG_PREFIX}${IDX}.log" INDICES="${INDICES} ${IDX}" ((IDX++)) if [[ "${IDX}" == "${N_WORKERS}" ]]; then break fi done # Poll until all final validation cross entropy values become available or # operation times out COUNTER=0 while true; do ((COUNTER++)) if [[ "${COUNTER}" -gt "${TIMEOUT}" ]]; then die "Reached maximum polling steps while polling for final validation "\ "cross entropies from all workers" fi N_AVAIL=0 VAL_XENT="" for N in ${INDICES}; do if [[ ! -z $(grep "Training ends " "${WKR_LOG_PREFIX}${N}.log") ]]; then ((N_AVAIL++)) fi done if [[ "${N_AVAIL}" == "${N_WORKERS}" ]]; then # Print out the content of the log files for M in ${INDICES}; do ORD=$(expr ${M} + 1) echo "===================================================" echo "=== Log file from worker ${ORD} / ${N_WORKERS} ===" cat "${WKR_LOG_PREFIX}${M}.log" echo "===================================================" echo "" done break else sleep 1 fi done # Function for getting final validation cross entropy from worker log files get_final_val_xent() { echo $(cat $1 | grep "^After.*validation cross entropy = " | \ awk '{print $NF}') } VAL_XENT=$(get_final_val_xent "${WKR_LOG_PREFIX}0.log") # Sanity check on the validation entropies # TODO(cais): In addition to this basic sanity check, we could run the training # with 1 and 2 workers, each for a few times and use scipy.stats to do a t-test # to verify that the 2-worker training gives significantly lower final cross # entropy echo "Final validation cross entropy from worker0: ${VAL_XENT}" if [[ $(python -c "print(${VAL_XENT}>0)") != "True" ]]; then die "Sanity checks on the final validation cross entropy values FAILED" fi
jostep/tensorflow
tensorflow/tools/dist_test/scripts/dist_mnist_test.sh
Shell
apache-2.0
7,732
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.http.websocketx; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.StringUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.nio.channels.ClosedChannelException; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * Base class for server side web socket opening and closing handshakes */ public abstract class WebSocketServerHandshaker { protected static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandshaker.class); private static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = new ClosedChannelException(); static { CLOSED_CHANNEL_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); } private final String uri; private final String[] subprotocols; private final WebSocketVersion version; private final int maxFramePayloadLength; private String selectedSubprotocol; /** * Use this as wildcard to support all requested sub-protocols */ public static final String SUB_PROTOCOL_WILDCARD = "*"; /** * Constructor specifying the destination web socket location * * @param version * the protocol version * @param uri * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be * sent to this URL. * @param subprotocols * CSV of supported protocols. Null if sub protocols not supported. * @param maxFramePayloadLength * Maximum length of a frame's payload */ protected WebSocketServerHandshaker( WebSocketVersion version, String uri, String subprotocols, int maxFramePayloadLength) { this.version = version; this.uri = uri; if (subprotocols != null) { String[] subprotocolArray = StringUtil.split(subprotocols, ','); for (int i = 0; i < subprotocolArray.length; i++) { subprotocolArray[i] = subprotocolArray[i].trim(); } this.subprotocols = subprotocolArray; } else { this.subprotocols = EmptyArrays.EMPTY_STRINGS; } this.maxFramePayloadLength = maxFramePayloadLength; } /** * Returns the URL of the web socket */ public String uri() { return uri; } /** * Returns the CSV of supported sub protocols */ public Set<String> subprotocols() { Set<String> ret = new LinkedHashSet<String>(); Collections.addAll(ret, subprotocols); return ret; } /** * Returns the version of the specification being supported */ public WebSocketVersion version() { return version; } /** * Gets the maximum length for any frame's payload. * * @return The maximum length for a frame's payload */ public int maxFramePayloadLength() { return maxFramePayloadLength; } /** * Performs the opening handshake. When call this method you <strong>MUST NOT</strong> retain the * {@link FullHttpRequest} which is passed in. * * @param channel * Channel * @param req * HTTP Request * @return future * The {@link ChannelFuture} which is notified once the opening handshake completes */ public ChannelFuture handshake(Channel channel, FullHttpRequest req) { return handshake(channel, req, null, channel.newPromise()); } /** * Performs the opening handshake * * When call this method you <strong>MUST NOT</strong> retain the {@link FullHttpRequest} which is passed in. * * @param channel * Channel * @param req * HTTP Request * @param responseHeaders * Extra headers to add to the handshake response or {@code null} if no extra headers should be added * @param promise * the {@link ChannelPromise} to be notified when the opening handshake is done * @return future * the {@link ChannelFuture} which is notified when the opening handshake is done */ public final ChannelFuture handshake(Channel channel, FullHttpRequest req, HttpHeaders responseHeaders, final ChannelPromise promise) { if (logger.isDebugEnabled()) { logger.debug("{} WebSocket version {} server handshake", channel, version()); } FullHttpResponse response = newHandshakeResponse(req, responseHeaders); ChannelPipeline p = channel.pipeline(); if (p.get(HttpObjectAggregator.class) != null) { p.remove(HttpObjectAggregator.class); } if (p.get(HttpContentCompressor.class) != null) { p.remove(HttpContentCompressor.class); } ChannelHandlerContext ctx = p.context(HttpRequestDecoder.class); final String encoderName; if (ctx == null) { // this means the user use a HttpServerCodec ctx = p.context(HttpServerCodec.class); if (ctx == null) { promise.setFailure( new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline")); return promise; } p.addBefore(ctx.name(), "wsdecoder", newWebsocketDecoder()); p.addBefore(ctx.name(), "wsencoder", newWebSocketEncoder()); encoderName = ctx.name(); } else { p.replace(ctx.name(), "wsdecoder", newWebsocketDecoder()); encoderName = p.context(HttpResponseEncoder.class).name(); p.addBefore(encoderName, "wsencoder", newWebSocketEncoder()); } channel.writeAndFlush(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ChannelPipeline p = future.channel().pipeline(); p.remove(encoderName); promise.setSuccess(); } else { promise.setFailure(future.cause()); } } }); return promise; } /** * Performs the opening handshake. When call this method you <strong>MUST NOT</strong> retain the * {@link FullHttpRequest} which is passed in. * * @param channel * Channel * @param req * HTTP Request * @return future * The {@link ChannelFuture} which is notified once the opening handshake completes */ public ChannelFuture handshake(Channel channel, HttpRequest req) { return handshake(channel, req, null, channel.newPromise()); } /** * Performs the opening handshake * * When call this method you <strong>MUST NOT</strong> retain the {@link HttpRequest} which is passed in. * * @param channel * Channel * @param req * HTTP Request * @param responseHeaders * Extra headers to add to the handshake response or {@code null} if no extra headers should be added * @param promise * the {@link ChannelPromise} to be notified when the opening handshake is done * @return future * the {@link ChannelFuture} which is notified when the opening handshake is done */ public final ChannelFuture handshake(final Channel channel, HttpRequest req, final HttpHeaders responseHeaders, final ChannelPromise promise) { if (req instanceof FullHttpRequest) { return handshake(channel, (FullHttpRequest) req, responseHeaders, promise); } if (logger.isDebugEnabled()) { logger.debug("{} WebSocket version {} server handshake", channel, version()); } ChannelPipeline p = channel.pipeline(); ChannelHandlerContext ctx = p.context(HttpRequestDecoder.class); if (ctx == null) { // this means the user use a HttpServerCodec ctx = p.context(HttpServerCodec.class); if (ctx == null) { promise.setFailure( new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline")); return promise; } } // Add aggregator and ensure we feed the HttpRequest so it is aggregated. A limit o 8192 should be more then // enough for the websockets handshake payload. // // TODO: Make handshake work without HttpObjectAggregator at all. String aggregatorName = "httpAggregator"; p.addAfter(ctx.name(), aggregatorName, new HttpObjectAggregator(8192)); p.addAfter(aggregatorName, "handshaker", new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { // Remove ourself and do the actual handshake ctx.pipeline().remove(this); handshake(channel, msg, responseHeaders, promise); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // Remove ourself and fail the handshake promise. ctx.pipeline().remove(this); promise.tryFailure(cause); ctx.fireExceptionCaught(cause); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // Fail promise if Channel was closed promise.tryFailure(CLOSED_CHANNEL_EXCEPTION); ctx.fireChannelInactive(); } }); try { ctx.fireChannelRead(ReferenceCountUtil.retain(req)); } catch (Throwable cause) { promise.setFailure(cause); } return promise; } /** * Returns a new {@link FullHttpResponse) which will be used for as response to the handshake request. */ protected abstract FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders responseHeaders); /** * Performs the closing handshake * * @param channel * Channel * @param frame * Closing Frame that was received */ public ChannelFuture close(Channel channel, CloseWebSocketFrame frame) { if (channel == null) { throw new NullPointerException("channel"); } return close(channel, frame, channel.newPromise()); } /** * Performs the closing handshake * * @param channel * Channel * @param frame * Closing Frame that was received * @param promise * the {@link ChannelPromise} to be notified when the closing handshake is done */ public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) { if (channel == null) { throw new NullPointerException("channel"); } return channel.writeAndFlush(frame, promise).addListener(ChannelFutureListener.CLOSE); } /** * Selects the first matching supported sub protocol * * @param requestedSubprotocols * CSV of protocols to be supported. e.g. "chat, superchat" * @return First matching supported sub protocol. Null if not found. */ protected String selectSubprotocol(String requestedSubprotocols) { if (requestedSubprotocols == null || subprotocols.length == 0) { return null; } String[] requestedSubprotocolArray = StringUtil.split(requestedSubprotocols, ','); for (String p: requestedSubprotocolArray) { String requestedSubprotocol = p.trim(); for (String supportedSubprotocol: subprotocols) { if (SUB_PROTOCOL_WILDCARD.equals(supportedSubprotocol) || requestedSubprotocol.equals(supportedSubprotocol)) { selectedSubprotocol = requestedSubprotocol; return requestedSubprotocol; } } } // No match found return null; } /** * Returns the selected subprotocol. Null if no subprotocol has been selected. * <p> * This is only available AFTER <tt>handshake()</tt> has been called. * </p> */ public String selectedSubprotocol() { return selectedSubprotocol; } /** * Returns the decoder to use after handshake is complete. */ protected abstract WebSocketFrameDecoder newWebsocketDecoder(); /** * Returns the encoder to use after the handshake is complete. */ protected abstract WebSocketFrameEncoder newWebSocketEncoder(); }
yawkat/netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java
Java
apache-2.0
14,627
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package term import ( "io" "os" "github.com/docker/docker/pkg/term" wordwrap "github.com/mitchellh/go-wordwrap" ) type wordWrapWriter struct { limit uint writer io.Writer } // NewResponsiveWriter creates a Writer that detects the column width of the // terminal we are in, and adjusts every line width to fit and use recommended // terminal sizes for better readability. Does proper word wrapping automatically. // if terminal width >= 120 columns use 120 columns // if terminal width >= 100 columns use 100 columns // if terminal width >= 80 columns use 80 columns // In case we're not in a terminal or if it's smaller than 80 columns width, // doesn't do any wrapping. func NewResponsiveWriter(w io.Writer) io.Writer { file, ok := w.(*os.File) if !ok { return w } fd := file.Fd() if !term.IsTerminal(fd) { return w } terminalSize := GetSize(fd) if terminalSize == nil { return w } var limit uint switch { case terminalSize.Width >= 120: limit = 120 case terminalSize.Width >= 100: limit = 100 case terminalSize.Width >= 80: limit = 80 } return NewWordWrapWriter(w, limit) } // NewWordWrapWriter is a Writer that supports a limit of characters on every line // and does auto word wrapping that respects that limit. func NewWordWrapWriter(w io.Writer, limit uint) io.Writer { return &wordWrapWriter{ limit: limit, writer: w, } } func (w wordWrapWriter) Write(p []byte) (nn int, err error) { if w.limit == 0 { return w.writer.Write(p) } original := string(p) wrapped := wordwrap.WrapString(original, w.limit) return w.writer.Write([]byte(wrapped)) } // NewPunchCardWriter is a NewWordWrapWriter that limits the line width to 80 columns. func NewPunchCardWriter(w io.Writer) io.Writer { return NewWordWrapWriter(w, 80) } type maxWidthWriter struct { maxWidth uint currentWidth uint written uint writer io.Writer } // NewMaxWidthWriter is a Writer that supports a limit of characters on every // line, but doesn't do any word wrapping automatically. func NewMaxWidthWriter(w io.Writer, maxWidth uint) io.Writer { return &maxWidthWriter{ maxWidth: maxWidth, writer: w, } } func (m maxWidthWriter) Write(p []byte) (nn int, err error) { for _, b := range p { if m.currentWidth == m.maxWidth { m.writer.Write([]byte{'\n'}) m.currentWidth = 0 } if b == '\n' { m.currentWidth = 0 } _, err := m.writer.Write([]byte{b}) if err != nil { return int(m.written), err } m.written++ m.currentWidth++ } return len(p), nil }
simo5/origin
vendor/k8s.io/kubernetes/pkg/util/term/term_writer.go
GO
apache-2.0
3,114
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package unversioned import ( "encoding/json" "time" ) // Duration is a wrapper around time.Duration which supports correct // marshaling to YAML and JSON. In particular, it marshals into strings, which // can be used as map keys in json. type Duration struct { time.Duration `protobuf:"varint,1,opt,name=duration,casttype=time.Duration"` } // UnmarshalJSON implements the json.Unmarshaller interface. func (d *Duration) UnmarshalJSON(b []byte) error { var str string json.Unmarshal(b, &str) pd, err := time.ParseDuration(str) if err != nil { return err } d.Duration = pd return nil } // MarshalJSON implements the json.Marshaler interface. func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Duration.String()) }
erjohnso/tectonic-installer
installer/vendor/k8s.io/client-go/pkg/api/unversioned/duration.go
GO
apache-2.0
1,322
package dbus import ( "errors" "fmt" "reflect" "strings" ) var ( errmsgInvalidArg = Error{ "org.freedesktop.DBus.Error.InvalidArgs", []interface{}{"Invalid type / number of args"}, } errmsgNoObject = Error{ "org.freedesktop.DBus.Error.NoSuchObject", []interface{}{"No such object"}, } errmsgUnknownMethod = Error{ "org.freedesktop.DBus.Error.UnknownMethod", []interface{}{"Unknown / invalid method"}, } ) // exportWithMapping represents an exported struct along with a method name // mapping to allow for exporting lower-case methods, etc. type exportWithMapping struct { export interface{} // Method name mapping; key -> struct method, value -> dbus method. mapping map[string]string // Whether or not this export is for the entire subtree includeSubtree bool } // Sender is a type which can be used in exported methods to receive the message // sender. type Sender string func exportedMethod(export exportWithMapping, name string) reflect.Value { if export.export == nil { return reflect.Value{} } // If a mapping was included in the export, check the map to see if we // should be looking for a different method in the export. if export.mapping != nil { for key, value := range export.mapping { if value == name { name = key break } // Catch the case where a method is aliased but the client is calling // the original, e.g. the "Foo" method was exported mapped to // "foo," and dbus client called the original "Foo." if key == name { return reflect.Value{} } } } value := reflect.ValueOf(export.export) m := value.MethodByName(name) // Catch the case of attempting to call an unexported method method, ok := value.Type().MethodByName(name) if !m.IsValid() || !ok || method.PkgPath != "" { return reflect.Value{} } t := m.Type() if t.NumOut() == 0 || t.Out(t.NumOut()-1) != reflect.TypeOf(&errmsgInvalidArg) { return reflect.Value{} } return m } // searchHandlers will look through all registered handlers looking for one // to handle the given path. If a verbatim one isn't found, it will check for // a subtree registration for the path as well. func (conn *Conn) searchHandlers(path ObjectPath) (map[string]exportWithMapping, bool) { conn.handlersLck.RLock() defer conn.handlersLck.RUnlock() handlers, ok := conn.handlers[path] if ok { return handlers, ok } // If handlers weren't found for this exact path, look for a matching subtree // registration handlers = make(map[string]exportWithMapping) path = path[:strings.LastIndex(string(path), "/")] for len(path) > 0 { var subtreeHandlers map[string]exportWithMapping subtreeHandlers, ok = conn.handlers[path] if ok { for iface, handler := range subtreeHandlers { // Only include this handler if it registered for the subtree if handler.includeSubtree { handlers[iface] = handler } } break } path = path[:strings.LastIndex(string(path), "/")] } return handlers, ok } // handleCall handles the given method call (i.e. looks if it's one of the // pre-implemented ones and searches for a corresponding handler if not). func (conn *Conn) handleCall(msg *Message) { name := msg.Headers[FieldMember].value.(string) path := msg.Headers[FieldPath].value.(ObjectPath) ifaceName, hasIface := msg.Headers[FieldInterface].value.(string) sender, hasSender := msg.Headers[FieldSender].value.(string) serial := msg.serial if ifaceName == "org.freedesktop.DBus.Peer" { switch name { case "Ping": conn.sendReply(sender, serial) case "GetMachineId": conn.sendReply(sender, serial, conn.uuid) default: conn.sendError(errmsgUnknownMethod, sender, serial) } return } if len(name) == 0 { conn.sendError(errmsgUnknownMethod, sender, serial) } // Find the exported handler (if any) for this path handlers, ok := conn.searchHandlers(path) if !ok { conn.sendError(errmsgNoObject, sender, serial) return } var m reflect.Value if hasIface { iface := handlers[ifaceName] m = exportedMethod(iface, name) } else { for _, v := range handlers { m = exportedMethod(v, name) if m.IsValid() { break } } } if !m.IsValid() { conn.sendError(errmsgUnknownMethod, sender, serial) return } t := m.Type() vs := msg.Body pointers := make([]interface{}, t.NumIn()) decode := make([]interface{}, 0, len(vs)) for i := 0; i < t.NumIn(); i++ { tp := t.In(i) val := reflect.New(tp) pointers[i] = val.Interface() if tp == reflect.TypeOf((*Sender)(nil)).Elem() { val.Elem().SetString(sender) } else if tp == reflect.TypeOf((*Message)(nil)).Elem() { val.Elem().Set(reflect.ValueOf(*msg)) } else { decode = append(decode, pointers[i]) } } if len(decode) != len(vs) { conn.sendError(errmsgInvalidArg, sender, serial) return } if err := Store(vs, decode...); err != nil { conn.sendError(errmsgInvalidArg, sender, serial) return } // Extract parameters params := make([]reflect.Value, len(pointers)) for i := 0; i < len(pointers); i++ { params[i] = reflect.ValueOf(pointers[i]).Elem() } // Call method ret := m.Call(params) if em := ret[t.NumOut()-1].Interface().(*Error); em != nil { conn.sendError(*em, sender, serial) return } if msg.Flags&FlagNoReplyExpected == 0 { reply := new(Message) reply.Type = TypeMethodReply reply.serial = conn.getSerial() reply.Headers = make(map[HeaderField]Variant) if hasSender { reply.Headers[FieldDestination] = msg.Headers[FieldSender] } reply.Headers[FieldReplySerial] = MakeVariant(msg.serial) reply.Body = make([]interface{}, len(ret)-1) for i := 0; i < len(ret)-1; i++ { reply.Body[i] = ret[i].Interface() } if len(ret) != 1 { reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...)) } conn.outLck.RLock() if !conn.closed { conn.out <- reply } conn.outLck.RUnlock() } } // Emit emits the given signal on the message bus. The name parameter must be // formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost". func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error { if !path.IsValid() { return errors.New("dbus: invalid object path") } i := strings.LastIndex(name, ".") if i == -1 { return errors.New("dbus: invalid method name") } iface := name[:i] member := name[i+1:] if !isValidMember(member) { return errors.New("dbus: invalid method name") } if !isValidInterface(iface) { return errors.New("dbus: invalid interface name") } msg := new(Message) msg.Type = TypeSignal msg.serial = conn.getSerial() msg.Headers = make(map[HeaderField]Variant) msg.Headers[FieldInterface] = MakeVariant(iface) msg.Headers[FieldMember] = MakeVariant(member) msg.Headers[FieldPath] = MakeVariant(path) msg.Body = values if len(values) > 0 { msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...)) } conn.outLck.RLock() defer conn.outLck.RUnlock() if conn.closed { return ErrClosed } conn.out <- msg return nil } // Export registers the given value to be exported as an object on the // message bus. // // If a method call on the given path and interface is received, an exported // method with the same name is called with v as the receiver if the // parameters match and the last return value is of type *Error. If this // *Error is not nil, it is sent back to the caller as an error. // Otherwise, a method reply is sent with the other return values as its body. // // Any parameters with the special type Sender are set to the sender of the // dbus message when the method is called. Parameters of this type do not // contribute to the dbus signature of the method (i.e. the method is exposed // as if the parameters of type Sender were not there). // // Similarly, any parameters with the type Message are set to the raw message // received on the bus. Again, parameters of this type do not contribute to the // dbus signature of the method. // // Every method call is executed in a new goroutine, so the method may be called // in multiple goroutines at once. // // Method calls on the interface org.freedesktop.DBus.Peer will be automatically // handled for every object. // // Passing nil as the first parameter will cause conn to cease handling calls on // the given combination of path and interface. // // Export returns an error if path is not a valid path name. func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error { return conn.ExportWithMap(v, nil, path, iface) } // ExportWithMap works exactly like Export but provides the ability to remap // method names (e.g. export a lower-case method). // // The keys in the map are the real method names (exported on the struct), and // the values are the method names to be exported on DBus. func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error { return conn.exportWithMap(v, mapping, path, iface, false) } // ExportSubtree works exactly like Export but registers the given value for // an entire subtree rather under the root path provided. // // In order to make this useful, one parameter in each of the value's exported // methods should be a Message, in which case it will contain the raw message // (allowing one to get access to the path that caused the method to be called). // // Note that more specific export paths take precedence over less specific. For // example, a method call using the ObjectPath /foo/bar/baz will call a method // exported on /foo/bar before a method exported on /foo. func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) error { return conn.ExportSubtreeWithMap(v, nil, path, iface) } // ExportSubtreeWithMap works exactly like ExportSubtree but provides the // ability to remap method names (e.g. export a lower-case method). // // The keys in the map are the real method names (exported on the struct), and // the values are the method names to be exported on DBus. func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error { return conn.exportWithMap(v, mapping, path, iface, true) } // exportWithMap is the worker function for all exports/registrations. func (conn *Conn) exportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string, includeSubtree bool) error { if !path.IsValid() { return fmt.Errorf(`dbus: Invalid path name: "%s"`, path) } conn.handlersLck.Lock() defer conn.handlersLck.Unlock() // Remove a previous export if the interface is nil if v == nil { if _, ok := conn.handlers[path]; ok { delete(conn.handlers[path], iface) if len(conn.handlers[path]) == 0 { delete(conn.handlers, path) } } return nil } // If this is the first handler for this path, make a new map to hold all // handlers for this path. if _, ok := conn.handlers[path]; !ok { conn.handlers[path] = make(map[string]exportWithMapping) } // Finally, save this handler conn.handlers[path][iface] = exportWithMapping{export: v, mapping: mapping, includeSubtree: includeSubtree} return nil } // ReleaseName calls org.freedesktop.DBus.ReleaseName and awaits a response. func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error) { var r uint32 err := conn.busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&r) if err != nil { return 0, err } return ReleaseNameReply(r), nil } // RequestName calls org.freedesktop.DBus.RequestName and awaits a response. func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error) { var r uint32 err := conn.busObj.Call("org.freedesktop.DBus.RequestName", 0, name, flags).Store(&r) if err != nil { return 0, err } return RequestNameReply(r), nil } // ReleaseNameReply is the reply to a ReleaseName call. type ReleaseNameReply uint32 const ( ReleaseNameReplyReleased ReleaseNameReply = 1 + iota ReleaseNameReplyNonExistent ReleaseNameReplyNotOwner ) // RequestNameFlags represents the possible flags for a RequestName call. type RequestNameFlags uint32 const ( NameFlagAllowReplacement RequestNameFlags = 1 << iota NameFlagReplaceExisting NameFlagDoNotQueue ) // RequestNameReply is the reply to a RequestName call. type RequestNameReply uint32 const ( RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota RequestNameReplyInQueue RequestNameReplyExists RequestNameReplyAlreadyOwner )
aweiteka/cri-o
vendor/github.com/opencontainers/runc/Godeps/_workspace/src/github.com/godbus/dbus/export.go
GO
apache-2.0
12,388
/*! * Chart.js * http://chartjs.org/ * Version: 1.1.1 * * Copyright 2015 Nick Downie * Released under the MIT license * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md */ (function(){"use strict";var t=this,i=t.Chart,e=function(t){this.canvas=t.canvas,this.ctx=t;var i=function(t,i){return t["offset"+i]?t["offset"+i]:document.defaultView.getComputedStyle(t).getPropertyValue(i)};this.width=i(t.canvas,"Width")||t.canvas.width,this.height=i(t.canvas,"Height")||t.canvas.height;return this.aspectRatio=this.width/this.height,s.retinaScale(this),this};e.defaults={global:{animation:!0,animationSteps:60,animationEasing:"easeOutQuart",showScale:!0,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleIntegersOnly:!0,scaleBeginAtZero:!1,scaleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",responsive:!1,maintainAspectRatio:!0,showTooltips:!0,customTooltips:!1,tooltipEvents:["mousemove","touchstart","touchmove","mouseout"],tooltipFillColor:"rgba(0,0,0,0.8)",tooltipFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipFontSize:14,tooltipFontStyle:"normal",tooltipFontColor:"#fff",tooltipTitleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipTitleFontSize:14,tooltipTitleFontStyle:"bold",tooltipTitleFontColor:"#fff",tooltipTitleTemplate:"<%= label%>",tooltipYPadding:6,tooltipXPadding:6,tooltipCaretSize:8,tooltipCornerRadius:6,tooltipXOffset:10,tooltipTemplate:"<%if (label){%><%=label%>: <%}%><%= value %>",multiTooltipTemplate:"<%= datasetLabel %>: <%= value %>",multiTooltipKeyBackground:"#fff",segmentColorDefault:["#A6CEE3","#1F78B4","#B2DF8A","#33A02C","#FB9A99","#E31A1C","#FDBF6F","#FF7F00","#CAB2D6","#6A3D9A","#B4B482","#B15928"],segmentHighlightColorDefaults:["#CEF6FF","#47A0DC","#DAFFB2","#5BC854","#FFC2C1","#FF4244","#FFE797","#FFA728","#F2DAFE","#9265C2","#DCDCAA","#D98150"],onAnimationProgress:function(){},onAnimationComplete:function(){}}},e.types={};var s=e.helpers={},n=s.each=function(t,i,e){var s=Array.prototype.slice.call(arguments,3);if(t)if(t.length===+t.length){var n;for(n=0;n<t.length;n++)i.apply(e,[t[n],n].concat(s))}else for(var o in t)i.apply(e,[t[o],o].concat(s))},o=s.clone=function(t){var i={};return n(t,function(e,s){t.hasOwnProperty(s)&&(i[s]=e)}),i},a=s.extend=function(t){return n(Array.prototype.slice.call(arguments,1),function(i){n(i,function(e,s){i.hasOwnProperty(s)&&(t[s]=e)})}),t},h=s.merge=function(t,i){var e=Array.prototype.slice.call(arguments,0);return e.unshift({}),a.apply(null,e)},l=s.indexOf=function(t,i){if(Array.prototype.indexOf)return t.indexOf(i);for(var e=0;e<t.length;e++)if(t[e]===i)return e;return-1},r=(s.where=function(t,i){var e=[];return s.each(t,function(t){i(t)&&e.push(t)}),e},s.findNextWhere=function(t,i,e){e||(e=-1);for(var s=e+1;s<t.length;s++){var n=t[s];if(i(n))return n}},s.findPreviousWhere=function(t,i,e){e||(e=t.length);for(var s=e-1;s>=0;s--){var n=t[s];if(i(n))return n}},s.inherits=function(t){var i=this,e=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return i.apply(this,arguments)},s=function(){this.constructor=e};return s.prototype=i.prototype,e.prototype=new s,e.extend=r,t&&a(e.prototype,t),e.__super__=i.prototype,e}),c=s.noop=function(){},u=s.uid=function(){var t=0;return function(){return"chart-"+t++}}(),d=s.warn=function(t){window.console&&"function"==typeof window.console.warn&&console.warn(t)},p=s.amd="function"==typeof define&&define.amd,f=s.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},g=s.max=function(t){return Math.max.apply(Math,t)},m=s.min=function(t){return Math.min.apply(Math,t)},v=(s.cap=function(t,i,e){if(f(i)){if(t>i)return i}else if(f(e)&&e>t)return e;return t},s.getDecimalPlaces=function(t){if(t%1!==0&&f(t)){var i=t.toString();if(i.indexOf("e-")<0)return i.split(".")[1].length;if(i.indexOf(".")<0)return parseInt(i.split("e-")[1]);var e=i.split(".")[1].split("e-");return e[0].length+parseInt(e[1])}return 0}),S=s.radians=function(t){return t*(Math.PI/180)},C=(s.getAngleFromPoint=function(t,i){var e=i.x-t.x,s=i.y-t.y,n=Math.sqrt(e*e+s*s),o=2*Math.PI+Math.atan2(s,e);return 0>e&&0>s&&(o+=2*Math.PI),{angle:o,distance:n}},s.aliasPixel=function(t){return t%2===0?0:.5}),x=(s.splineCurve=function(t,i,e,s){var n=Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)),o=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2)),a=s*n/(n+o),h=s*o/(n+o);return{inner:{x:i.x-a*(e.x-t.x),y:i.y-a*(e.y-t.y)},outer:{x:i.x+h*(e.x-t.x),y:i.y+h*(e.y-t.y)}}},s.calculateOrderOfMagnitude=function(t){return Math.floor(Math.log(t)/Math.LN10)}),y=(s.calculateScaleRange=function(t,i,e,s,o){var a=2,h=Math.floor(i/(1.5*e)),l=a>=h,r=[];n(t,function(t){null==t||r.push(t)});var c=m(r),u=g(r);u===c&&(u+=.5,c>=.5&&!s?c-=.5:u+=.5);for(var d=Math.abs(u-c),p=x(d),f=Math.ceil(u/(1*Math.pow(10,p)))*Math.pow(10,p),v=s?0:Math.floor(c/(1*Math.pow(10,p)))*Math.pow(10,p),S=f-v,C=Math.pow(10,p),y=Math.round(S/C);(y>h||h>2*y)&&!l;)if(y>h)C*=2,y=Math.round(S/C),y%1!==0&&(l=!0);else if(o&&p>=0){if(C/2%1!==0)break;C/=2,y=Math.round(S/C)}else C/=2,y=Math.round(S/C);return l&&(y=a,C=S/y),{steps:y,stepValue:C,min:v,max:v+y*C}},s.template=function(t,i){function e(t,i){var e=/\W/.test(t)?new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+t.replace(/[\r\t\n]/g," ").split("<%").join(" ").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split(" ").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');"):s[t]=s[t];return i?e(i):e}if(t instanceof Function)return t(i);var s={};return e(t,i)}),b=(s.generateLabels=function(t,i,e,s){var o=new Array(i);return t&&n(o,function(i,n){o[n]=y(t,{value:e+s*(n+1)})}),o},s.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),-(s*Math.pow(2,10*(t-=1))*Math.sin((1*t-i)*(2*Math.PI)/e)))},easeOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),s*Math.pow(2,-10*t)*Math.sin((1*t-i)*(2*Math.PI)/e)+1)},easeInOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:2==(t/=.5)?1:(e||(e=1*(.3*1.5)),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),1>t?-.5*(s*Math.pow(2,10*(t-=1))*Math.sin((1*t-i)*(2*Math.PI)/e)):s*Math.pow(2,-10*(t-=1))*Math.sin((1*t-i)*(2*Math.PI)/e)*.5+1)},easeInBack:function(t){var i=1.70158;return 1*(t/=1)*t*((i+1)*t-i)},easeOutBack:function(t){var i=1.70158;return 1*((t=t/1-1)*t*((i+1)*t+i)+1)},easeInOutBack:function(t){var i=1.70158;return(t/=.5)<1?.5*(t*t*(((i*=1.525)+1)*t-i)):.5*((t-=2)*t*(((i*=1.525)+1)*t+i)+2)},easeInBounce:function(t){return 1-b.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?1*(7.5625*t*t):2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*b.easeInBounce(2*t):.5*b.easeOutBounce(2*t-1)+.5}}),w=s.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),P=(s.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),s.animationLoop=function(t,i,e,s,n,o){var a=0,h=b[e]||b.linear,l=function(){a++;var e=a/i,r=h(e);t.call(o,r,e,a),s.call(o,r,e),i>a?o.animationFrame=w(l):n.apply(o)};w(l)},s.getRelativePosition=function(t){var i,e,s=t.originalEvent||t,n=t.currentTarget||t.srcElement,o=n.getBoundingClientRect();return s.touches?(i=s.touches[0].clientX-o.left,e=s.touches[0].clientY-o.top):(i=s.clientX-o.left,e=s.clientY-o.top),{x:i,y:e}},s.addEvent=function(t,i,e){t.addEventListener?t.addEventListener(i,e):t.attachEvent?t.attachEvent("on"+i,e):t["on"+i]=e}),L=s.removeEvent=function(t,i,e){t.removeEventListener?t.removeEventListener(i,e,!1):t.detachEvent?t.detachEvent("on"+i,e):t["on"+i]=c},k=(s.bindEvents=function(t,i,e){t.events||(t.events={}),n(i,function(i){t.events[i]=function(){e.apply(t,arguments)},P(t.chart.canvas,i,t.events[i])})},s.unbindEvents=function(t,i){n(i,function(i,e){L(t.chart.canvas,e,i)})}),F=s.getMaximumWidth=function(t){var i=t.parentNode,e=parseInt(R(i,"padding-left"))+parseInt(R(i,"padding-right"));return i?i.clientWidth-e:0},A=s.getMaximumHeight=function(t){var i=t.parentNode,e=parseInt(R(i,"padding-bottom"))+parseInt(R(i,"padding-top"));return i?i.clientHeight-e:0},R=s.getStyle=function(t,i){return t.currentStyle?t.currentStyle[i]:document.defaultView.getComputedStyle(t,null).getPropertyValue(i)},T=(s.getMaximumSize=s.getMaximumWidth,s.retinaScale=function(t){var i=t.ctx,e=t.canvas.width,s=t.canvas.height;window.devicePixelRatio&&(i.canvas.style.width=e+"px",i.canvas.style.height=s+"px",i.canvas.height=s*window.devicePixelRatio,i.canvas.width=e*window.devicePixelRatio,i.scale(window.devicePixelRatio,window.devicePixelRatio))}),M=s.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},W=s.fontString=function(t,i,e){return i+" "+t+"px "+e},z=s.longestText=function(t,i,e){t.font=i;var s=0;return n(e,function(i){var e=t.measureText(i).width;s=e>s?e:s}),s},B=s.drawRoundedRectangle=function(t,i,e,s,n,o){t.beginPath(),t.moveTo(i+o,e),t.lineTo(i+s-o,e),t.quadraticCurveTo(i+s,e,i+s,e+o),t.lineTo(i+s,e+n-o),t.quadraticCurveTo(i+s,e+n,i+s-o,e+n),t.lineTo(i+o,e+n),t.quadraticCurveTo(i,e+n,i,e+n-o),t.lineTo(i,e+o),t.quadraticCurveTo(i,e,i+o,e),t.closePath()};e.instances={},e.Type=function(t,i,s){this.options=i,this.chart=s,this.id=u(),e.instances[this.id]=this,i.responsive&&this.resize(),this.initialize.call(this,t)},a(e.Type.prototype,{initialize:function(){return this},clear:function(){return M(this.chart),this},stop:function(){return e.animationService.cancelAnimation(this),this},resize:function(t){this.stop();var i=this.chart.canvas,e=F(this.chart.canvas),s=this.options.maintainAspectRatio?e/this.chart.aspectRatio:A(this.chart.canvas);return i.width=this.chart.width=e,i.height=this.chart.height=s,T(this.chart),"function"==typeof t&&t.apply(this,Array.prototype.slice.call(arguments,1)),this},reflow:c,render:function(t){if(t&&this.reflow(),this.options.animation&&!t){var i=new e.Animation;i.numSteps=this.options.animationSteps,i.easing=this.options.animationEasing,i.render=function(t,i){var e=s.easingEffects[i.easing],n=i.currentStep/i.numSteps,o=e(n);t.draw(o,n,i.currentStep)},i.onAnimationProgress=this.options.onAnimationProgress,i.onAnimationComplete=this.options.onAnimationComplete,e.animationService.addAnimation(this,i)}else this.draw(),this.options.onAnimationComplete.call(this);return this},generateLegend:function(){return s.template(this.options.legendTemplate,this)},destroy:function(){this.stop(),this.clear(),k(this,this.events);var t=this.chart.canvas;t.width=this.chart.width,t.height=this.chart.height,t.style.removeProperty?(t.style.removeProperty("width"),t.style.removeProperty("height")):(t.style.removeAttribute("width"),t.style.removeAttribute("height")),delete e.instances[this.id]},showTooltip:function(t,i){"undefined"==typeof this.activeElements&&(this.activeElements=[]);var o=function(t){var i=!1;return t.length!==this.activeElements.length?i=!0:(n(t,function(t,e){t!==this.activeElements[e]&&(i=!0)},this),i)}.call(this,t);if(o||i){if(this.activeElements=t,this.draw(),this.options.customTooltips&&this.options.customTooltips(!1),t.length>0)if(this.datasets&&this.datasets.length>1){for(var a,h,r=this.datasets.length-1;r>=0&&(a=this.datasets[r].points||this.datasets[r].bars||this.datasets[r].segments,h=l(a,t[0]),-1===h);r--);var c=[],u=[],d=function(t){var i,e,n,o,a,l=[],r=[],d=[];return s.each(this.datasets,function(t){i=t.points||t.bars||t.segments,i[h]&&i[h].hasValue()&&l.push(i[h])}),s.each(l,function(t){r.push(t.x),d.push(t.y),c.push(s.template(this.options.multiTooltipTemplate,t)),u.push({fill:t._saved.fillColor||t.fillColor,stroke:t._saved.strokeColor||t.strokeColor})},this),a=m(d),n=g(d),o=m(r),e=g(r),{x:o>this.chart.width/2?o:e,y:(a+n)/2}}.call(this,h);new e.MultiTooltip({x:d.x,y:d.y,xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,xOffset:this.options.tooltipXOffset,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,titleTextColor:this.options.tooltipTitleFontColor,titleFontFamily:this.options.tooltipTitleFontFamily,titleFontStyle:this.options.tooltipTitleFontStyle,titleFontSize:this.options.tooltipTitleFontSize,cornerRadius:this.options.tooltipCornerRadius,labels:c,legendColors:u,legendColorBackground:this.options.multiTooltipKeyBackground,title:y(this.options.tooltipTitleTemplate,t[0]),chart:this.chart,ctx:this.chart.ctx,custom:this.options.customTooltips}).draw()}else n(t,function(t){var i=t.tooltipPosition();new e.Tooltip({x:Math.round(i.x),y:Math.round(i.y),xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,caretHeight:this.options.tooltipCaretSize,cornerRadius:this.options.tooltipCornerRadius,text:y(this.options.tooltipTemplate,t),chart:this.chart,custom:this.options.customTooltips}).draw()},this);return this}},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)}}),e.Type.extend=function(t){var i=this,s=function(){return i.apply(this,arguments)};if(s.prototype=o(i.prototype),a(s.prototype,t),s.extend=e.Type.extend,t.name||i.prototype.name){var n=t.name||i.prototype.name,l=e.defaults[i.prototype.name]?o(e.defaults[i.prototype.name]):{};e.defaults[n]=a(l,t.defaults),e.types[n]=s,e.prototype[n]=function(t,i){var o=h(e.defaults.global,e.defaults[n],i||{});return new s(t,o,this)}}else d("Name not provided for this chart, so it hasn't been registered");return i},e.Element=function(t){a(this,t),this.initialize.apply(this,arguments),this.save()},a(e.Element.prototype,{initialize:function(){},restore:function(t){return t?n(t,function(t){this[t]=this._saved[t]},this):a(this,this._saved),this},save:function(){return this._saved=o(this),delete this._saved._saved,this},update:function(t){return n(t,function(t,i){this._saved[i]=this[i],this[i]=t},this),this},transition:function(t,i){return n(t,function(t,e){this[e]=(t-this._saved[e])*i+this._saved[e]},this),this},tooltipPosition:function(){return{x:this.x,y:this.y}},hasValue:function(){return f(this.value)}}),e.Element.extend=r,e.Point=e.Element.extend({display:!0,inRange:function(t,i){var e=this.hitDetectionRadius+this.radius;return Math.pow(t-this.x,2)+Math.pow(i-this.y,2)<Math.pow(e,2)},draw:function(){if(this.display){var t=this.ctx;t.beginPath(),t.arc(this.x,this.y,this.radius,0,2*Math.PI),t.closePath(),t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.fillStyle=this.fillColor,t.fill(),t.stroke()}}}),e.Arc=e.Element.extend({inRange:function(t,i){var e=s.getAngleFromPoint(this,{x:t,y:i}),n=e.angle%(2*Math.PI),o=(2*Math.PI+this.startAngle)%(2*Math.PI),a=(2*Math.PI+this.endAngle)%(2*Math.PI)||360,h=o>a?a>=n||n>=o:n>=o&&a>=n,l=e.distance>=this.innerRadius&&e.distance<=this.outerRadius;return h&&l},tooltipPosition:function(){var t=this.startAngle+(this.endAngle-this.startAngle)/2,i=(this.outerRadius-this.innerRadius)/2+this.innerRadius;return{x:this.x+Math.cos(t)*i,y:this.y+Math.sin(t)*i}},draw:function(t){var i=this.ctx;i.beginPath(),i.arc(this.x,this.y,this.outerRadius<0?0:this.outerRadius,this.startAngle,this.endAngle),i.arc(this.x,this.y,this.innerRadius<0?0:this.innerRadius,this.endAngle,this.startAngle,!0),i.closePath(),i.strokeStyle=this.strokeColor,i.lineWidth=this.strokeWidth,i.fillStyle=this.fillColor,i.fill(),i.lineJoin="bevel",this.showStroke&&i.stroke()}}),e.Rectangle=e.Element.extend({draw:function(){var t=this.ctx,i=this.width/2,e=this.x-i,s=this.x+i,n=this.base-(this.base-this.y),o=this.strokeWidth/2;this.showStroke&&(e+=o,s-=o,n+=o),t.beginPath(),t.fillStyle=this.fillColor,t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.moveTo(e,this.base),t.lineTo(e,n),t.lineTo(s,n),t.lineTo(s,this.base),t.fill(),this.showStroke&&t.stroke()},height:function(){return this.base-this.y},inRange:function(t,i){return t>=this.x-this.width/2&&t<=this.x+this.width/2&&i>=this.y&&i<=this.base}}),e.Animation=e.Element.extend({currentStep:null,numSteps:60,easing:"",render:null,onAnimationProgress:null,onAnimationComplete:null}),e.Tooltip=e.Element.extend({draw:function(){var t=this.chart.ctx;t.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.xAlign="center",this.yAlign="above";var i=this.caretPadding=2,e=t.measureText(this.text).width+2*this.xPadding,s=this.fontSize+2*this.yPadding,n=s+this.caretHeight+i;this.x+e/2>this.chart.width?this.xAlign="left":this.x-e/2<0&&(this.xAlign="right"),this.y-n<0&&(this.yAlign="below");var o=this.x-e/2,a=this.y-n;if(t.fillStyle=this.fillColor,this.custom)this.custom(this);else{switch(this.yAlign){case"above":t.beginPath(),t.moveTo(this.x,this.y-i),t.lineTo(this.x+this.caretHeight,this.y-(i+this.caretHeight)),t.lineTo(this.x-this.caretHeight,this.y-(i+this.caretHeight)),t.closePath(),t.fill();break;case"below":a=this.y+i+this.caretHeight,t.beginPath(),t.moveTo(this.x,this.y+i),t.lineTo(this.x+this.caretHeight,this.y+i+this.caretHeight),t.lineTo(this.x-this.caretHeight,this.y+i+this.caretHeight),t.closePath(),t.fill()}switch(this.xAlign){case"left":o=this.x-e+(this.cornerRadius+this.caretHeight);break;case"right":o=this.x-(this.cornerRadius+this.caretHeight)}B(t,o,a,e,s,this.cornerRadius),t.fill(),t.fillStyle=this.textColor,t.textAlign="center",t.textBaseline="middle",t.fillText(this.text,o+e/2,a+s/2)}}}),e.MultiTooltip=e.Element.extend({initialize:function(){this.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.titleFont=W(this.titleFontSize,this.titleFontStyle,this.titleFontFamily),this.titleHeight=this.title?1.5*this.titleFontSize:0,this.height=this.labels.length*this.fontSize+(this.labels.length-1)*(this.fontSize/2)+2*this.yPadding+this.titleHeight,this.ctx.font=this.titleFont;var t=this.ctx.measureText(this.title).width,i=z(this.ctx,this.font,this.labels)+this.fontSize+3,e=g([i,t]);this.width=e+2*this.xPadding;var s=this.height/2;this.y-s<0?this.y=s:this.y+s>this.chart.height&&(this.y=this.chart.height-s),this.x>this.chart.width/2?this.x-=this.xOffset+this.width:this.x+=this.xOffset},getLineHeight:function(t){var i=this.y-this.height/2+this.yPadding,e=t-1;return 0===t?i+this.titleHeight/3:i+(1.5*this.fontSize*e+this.fontSize/2)+this.titleHeight},draw:function(){if(this.custom)this.custom(this);else{B(this.ctx,this.x,this.y-this.height/2,this.width,this.height,this.cornerRadius);var t=this.ctx;t.fillStyle=this.fillColor,t.fill(),t.closePath(),t.textAlign="left",t.textBaseline="middle",t.fillStyle=this.titleTextColor,t.font=this.titleFont,t.fillText(this.title,this.x+this.xPadding,this.getLineHeight(0)),t.font=this.font,s.each(this.labels,function(i,e){t.fillStyle=this.textColor,t.fillText(i,this.x+this.xPadding+this.fontSize+3,this.getLineHeight(e+1)),t.fillStyle=this.legendColorBackground,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize),t.fillStyle=this.legendColors[e].fill,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize)},this)}}}),e.Scale=e.Element.extend({initialize:function(){this.fit()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}));this.yLabelWidth=this.display&&this.showLabels?z(this.ctx,this.font,this.yLabels)+10:0},addXLabel:function(t){this.xLabels.push(t),this.valuesCount++,this.fit()},removeXLabel:function(){this.xLabels.shift(),this.valuesCount--,this.fit()},fit:function(){this.startPoint=this.display?this.fontSize:0,this.endPoint=this.display?this.height-1.5*this.fontSize-5:this.height,this.startPoint+=this.padding,this.endPoint-=this.padding;var t,i=this.endPoint,e=this.endPoint-this.startPoint;for(this.calculateYRange(e),this.buildYLabels(),this.calculateXLabelRotation();e>this.endPoint-this.startPoint;)e=this.endPoint-this.startPoint,t=this.yLabelWidth,this.calculateYRange(e),this.buildYLabels(),t<this.yLabelWidth&&(this.endPoint=i,this.calculateXLabelRotation())},calculateXLabelRotation:function(){this.ctx.font=this.font;var t,i,e=this.ctx.measureText(this.xLabels[0]).width,s=this.ctx.measureText(this.xLabels[this.xLabels.length-1]).width;if(this.xScalePaddingRight=s/2+3,this.xScalePaddingLeft=e/2>this.yLabelWidth?e/2:this.yLabelWidth,this.xLabelRotation=0,this.display){var n,o=z(this.ctx,this.font,this.xLabels);this.xLabelWidth=o;for(var a=Math.floor(this.calculateX(1)-this.calculateX(0))-6;this.xLabelWidth>a&&0===this.xLabelRotation||this.xLabelWidth>a&&this.xLabelRotation<=90&&this.xLabelRotation>0;)n=Math.cos(S(this.xLabelRotation)),t=n*e,i=n*s,t+this.fontSize/2>this.yLabelWidth&&(this.xScalePaddingLeft=t+this.fontSize/2),this.xScalePaddingRight=this.fontSize/2,this.xLabelRotation++,this.xLabelWidth=n*o;this.xLabelRotation>0&&(this.endPoint-=Math.sin(S(this.xLabelRotation))*o+3)}else this.xLabelWidth=0,this.xScalePaddingRight=this.padding,this.xScalePaddingLeft=this.padding},calculateYRange:c,drawingArea:function(){return this.startPoint-this.endPoint},calculateY:function(t){var i=this.drawingArea()/(this.min-this.max);return this.endPoint-i*(t-this.min)},calculateX:function(t){var i=(this.xLabelRotation>0,this.width-(this.xScalePaddingLeft+this.xScalePaddingRight)),e=i/Math.max(this.valuesCount-(this.offsetGridLines?0:1),1),s=e*t+this.xScalePaddingLeft;return this.offsetGridLines&&(s+=e/2),Math.round(s)},update:function(t){s.extend(this,t),this.fit()},draw:function(){var t=this.ctx,i=(this.endPoint-this.startPoint)/this.steps,e=Math.round(this.xScalePaddingLeft);this.display&&(t.fillStyle=this.textColor,t.font=this.font,n(this.yLabels,function(n,o){var a=this.endPoint-i*o,h=Math.round(a),l=this.showHorizontalLines;t.textAlign="right",t.textBaseline="middle",this.showLabels&&t.fillText(n,e-10,a),0!==o||l||(l=!0),l&&t.beginPath(),o>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),h+=s.aliasPixel(t.lineWidth),l&&(t.moveTo(e,h),t.lineTo(this.width,h),t.stroke(),t.closePath()),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(e-5,h),t.lineTo(e,h),t.stroke(),t.closePath()},this),n(this.xLabels,function(i,e){var s=this.calculateX(e)+C(this.lineWidth),n=this.calculateX(e-(this.offsetGridLines?.5:0))+C(this.lineWidth),o=this.xLabelRotation>0,a=this.showVerticalLines;0!==e||a||(a=!0),a&&t.beginPath(),e>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),a&&(t.moveTo(n,this.endPoint),t.lineTo(n,this.startPoint-3),t.stroke(),t.closePath()),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(n,this.endPoint),t.lineTo(n,this.endPoint+5),t.stroke(),t.closePath(),t.save(),t.translate(s,o?this.endPoint+12:this.endPoint+8),t.rotate(-1*S(this.xLabelRotation)),t.font=this.font,t.textAlign=o?"right":"center",t.textBaseline=o?"middle":"top",t.fillText(i,0,0),t.restore()},this))}}),e.RadialScale=e.Element.extend({initialize:function(){this.size=m([this.height,this.width]),this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2},calculateCenterOffset:function(t){var i=this.drawingArea/(this.max-this.min);return(t-this.min)*i},update:function(){this.lineArc?this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2:this.setScaleSize(),this.buildYLabels()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}))},getCircumference:function(){return 2*Math.PI/this.valuesCount},setScaleSize:function(){var t,i,e,s,n,o,a,h,l,r,c,u,d=m([this.height/2-this.pointLabelFontSize-5,this.width/2]),p=this.width,g=0;for(this.ctx.font=W(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),i=0;i<this.valuesCount;i++)t=this.getPointPosition(i,d),e=this.ctx.measureText(y(this.templateString,{value:this.labels[i]})).width+5,0===i||i===this.valuesCount/2?(s=e/2,t.x+s>p&&(p=t.x+s,n=i),t.x-s<g&&(g=t.x-s,a=i)):i<this.valuesCount/2?t.x+e>p&&(p=t.x+e,n=i):i>this.valuesCount/2&&t.x-e<g&&(g=t.x-e,a=i);l=g,r=Math.ceil(p-this.width),o=this.getIndexAngle(n),h=this.getIndexAngle(a),c=r/Math.sin(o+Math.PI/2),u=l/Math.sin(h+Math.PI/2),c=f(c)?c:0,u=f(u)?u:0,this.drawingArea=d-(u+c)/2,this.setCenterPoint(u,c)},setCenterPoint:function(t,i){var e=this.width-i-this.drawingArea,s=t+this.drawingArea;this.xCenter=(s+e)/2,this.yCenter=this.height/2},getIndexAngle:function(t){var i=2*Math.PI/this.valuesCount;return t*i-Math.PI/2},getPointPosition:function(t,i){var e=this.getIndexAngle(t);return{x:Math.cos(e)*i+this.xCenter,y:Math.sin(e)*i+this.yCenter}},draw:function(){if(this.display){var t=this.ctx;if(n(this.yLabels,function(i,e){if(e>0){var s,n=e*(this.drawingArea/this.steps),o=this.yCenter-n;if(this.lineWidth>0)if(t.strokeStyle=this.lineColor,t.lineWidth=this.lineWidth,this.lineArc)t.beginPath(),t.arc(this.xCenter,this.yCenter,n,0,2*Math.PI),t.closePath(),t.stroke();else{t.beginPath();for(var a=0;a<this.valuesCount;a++)s=this.getPointPosition(a,this.calculateCenterOffset(this.min+e*this.stepValue)),0===a?t.moveTo(s.x,s.y):t.lineTo(s.x,s.y);t.closePath(),t.stroke()}if(this.showLabels){if(t.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.showLabelBackdrop){var h=t.measureText(i).width;t.fillStyle=this.backdropColor,t.fillRect(this.xCenter-h/2-this.backdropPaddingX,o-this.fontSize/2-this.backdropPaddingY,h+2*this.backdropPaddingX,this.fontSize+2*this.backdropPaddingY)}t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.fontColor,t.fillText(i,this.xCenter,o)}}},this),!this.lineArc){t.lineWidth=this.angleLineWidth,t.strokeStyle=this.angleLineColor;for(var i=this.valuesCount-1;i>=0;i--){var e=null,s=null;if(this.angleLineWidth>0&&i%this.angleLineInterval===0&&(e=this.calculateCenterOffset(this.max),s=this.getPointPosition(i,e),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(s.x,s.y),t.stroke(),t.closePath()),this.backgroundColors&&this.backgroundColors.length==this.valuesCount){null==e&&(e=this.calculateCenterOffset(this.max)),null==s&&(s=this.getPointPosition(i,e));var o=this.getPointPosition(0===i?this.valuesCount-1:i-1,e),a=this.getPointPosition(i===this.valuesCount-1?0:i+1,e),h={x:(o.x+s.x)/2,y:(o.y+s.y)/2},l={x:(s.x+a.x)/2,y:(s.y+a.y)/2};t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(h.x,h.y),t.lineTo(s.x,s.y),t.lineTo(l.x,l.y),t.fillStyle=this.backgroundColors[i],t.fill(),t.closePath()}var r=this.getPointPosition(i,this.calculateCenterOffset(this.max)+5);t.font=W(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),t.fillStyle=this.pointLabelFontColor;var c=this.labels.length,u=this.labels.length/2,d=u/2,p=d>i||i>c-d,f=i===d||i===c-d;0===i?t.textAlign="center":i===u?t.textAlign="center":u>i?t.textAlign="left":t.textAlign="right",f?t.textBaseline="middle":p?t.textBaseline="bottom":t.textBaseline="top",t.fillText(this.labels[i],r.x,r.y)}}}}}),e.animationService={frameDuration:17,animations:[],dropFrames:0,addAnimation:function(t,i){for(var e=0;e<this.animations.length;++e)if(this.animations[e].chartInstance===t)return void(this.animations[e].animationObject=i);this.animations.push({chartInstance:t,animationObject:i}),1==this.animations.length&&s.requestAnimFrame.call(window,this.digestWrapper)},cancelAnimation:function(t){var i=s.findNextWhere(this.animations,function(i){return i.chartInstance===t});i&&this.animations.splice(i,1)},digestWrapper:function(){e.animationService.startDigest.call(e.animationService)},startDigest:function(){var t=Date.now(),i=0;this.dropFrames>1&&(i=Math.floor(this.dropFrames),this.dropFrames-=i);for(var e=0;e<this.animations.length;e++)null===this.animations[e].animationObject.currentStep&&(this.animations[e].animationObject.currentStep=0),this.animations[e].animationObject.currentStep+=1+i,this.animations[e].animationObject.currentStep>this.animations[e].animationObject.numSteps&&(this.animations[e].animationObject.currentStep=this.animations[e].animationObject.numSteps),this.animations[e].animationObject.render(this.animations[e].chartInstance,this.animations[e].animationObject),this.animations[e].animationObject.currentStep==this.animations[e].animationObject.numSteps&&(this.animations[e].animationObject.onAnimationComplete.call(this.animations[e].chartInstance),this.animations.splice(e,1),e--);var n=Date.now(),o=n-t-this.frameDuration,a=o/this.frameDuration;a>1&&(this.dropFrames+=a),this.animations.length>0&&s.requestAnimFrame.call(window,this.digestWrapper)}},s.addEvent(window,"resize",function(){var t;return function(){clearTimeout(t),t=setTimeout(function(){n(e.instances,function(t){t.options.responsive&&t.resize(t.render,!0)})},50)}}()),p?define("Chart",[],function(){return e}):"object"==typeof module&&module.exports&&(module.exports=e),t.Chart=e,e.noConflict=function(){return t.Chart=i,e}}).call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleBeginAtZero:!0,scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,scaleShowHorizontalLines:!0,scaleShowVerticalLines:!0,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span class="<%=name.toLowerCase()%>-legend-icon" style="background-color:<%=datasets[i].fillColor%>"></span><span class="<%=name.toLowerCase()%>-legend-text"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>'};i.Type.extend({name:"Bar",defaults:s,initialize:function(t){var s=this.options;this.ScaleClass=i.Scale.extend({offsetGridLines:!0,calculateBarX:function(t,i,e){var n=this.calculateBaseWidth(),o=this.calculateX(e)-n/2,a=this.calculateBarWidth(t);return o+a*i+i*s.barDatasetSpacing+a/2},calculateBaseWidth:function(){return this.calculateX(1)-this.calculateX(0)-2*s.barValueSpacing; },calculateBarWidth:function(t){var i=this.calculateBaseWidth()-(t-1)*s.barDatasetSpacing;return i/t}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getBarsAtEvent(t):[];this.eachBars(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t&&(t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke)}),this.showTooltip(i)}),this.BarClass=i.Rectangle.extend({strokeWidth:this.options.barStrokeWidth,showStroke:this.options.barShowStroke,ctx:this.chart.ctx}),e.each(t.datasets,function(i,s){var n={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,bars:[]};this.datasets.push(n),e.each(i.data,function(e,s){n.bars.push(new this.BarClass({value:e,label:t.labels[s],datasetLabel:i.label,strokeColor:"object"==typeof i.strokeColor?i.strokeColor[s]:i.strokeColor,fillColor:"object"==typeof i.fillColor?i.fillColor[s]:i.fillColor,highlightFill:i.highlightFill?"object"==typeof i.highlightFill?i.highlightFill[s]:i.highlightFill:"object"==typeof i.fillColor?i.fillColor[s]:i.fillColor,highlightStroke:i.highlightStroke?"object"==typeof i.highlightStroke?i.highlightStroke[s]:i.highlightStroke:"object"==typeof i.strokeColor?i.strokeColor[s]:i.strokeColor}))},this)},this),this.buildScale(t.labels),this.BarClass.prototype.base=this.scale.endPoint,this.eachBars(function(t,i,s){e.extend(t,{width:this.scale.calculateBarWidth(this.datasets.length),x:this.scale.calculateBarX(this.datasets.length,s,i),y:this.scale.endPoint}),t.save()},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachBars(function(t){t.save()}),this.render()},eachBars:function(t){e.each(this.datasets,function(i,s){e.each(i.bars,t,this,s)},this)},getBarsAtEvent:function(t){for(var i,s=[],n=e.getRelativePosition(t),o=function(t){s.push(t.bars[i])},a=0;a<this.datasets.length;a++)for(i=0;i<this.datasets[a].bars.length;i++)if(this.datasets[a].bars[i].inRange(n.x,n.y))return e.each(this.datasets,o),s;return s},buildScale:function(t){var i=this,s=function(){var t=[];return i.eachBars(function(i){t.push(i.value)}),t},n={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(s(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,showHorizontalLines:this.options.scaleShowHorizontalLines,showVerticalLines:this.options.scaleShowVerticalLines,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.barShowStroke?this.options.barStrokeWidth:0,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(n,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new this.ScaleClass(n)},addData:function(t,i){e.each(t,function(t,e){this.datasets[e].bars.push(new this.BarClass({value:t,label:i,datasetLabel:this.datasets[e].label,x:this.scale.calculateBarX(this.datasets.length,e,this.scale.valuesCount+1),y:this.scale.endPoint,width:this.scale.calculateBarWidth(this.datasets.length),base:this.scale.endPoint,strokeColor:this.datasets[e].strokeColor,fillColor:this.datasets[e].fillColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.bars.shift()},this),this.update()},reflow:function(){e.extend(this.BarClass.prototype,{y:this.scale.endPoint,base:this.scale.endPoint});var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t,s){e.each(t.bars,function(t,e){t.hasValue()&&(t.base=this.scale.endPoint,t.transition({x:this.scale.calculateBarX(this.datasets.length,s,e),y:this.scale.calculateY(t.value),width:this.scale.calculateBarWidth(this.datasets.length)},i).draw())},this)},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span class="<%=name.toLowerCase()%>-legend-icon" style="background-color:<%=segments[i].fillColor%>"></span><span class="<%=name.toLowerCase()%>-legend-text"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>'};i.Type.extend({name:"Doughnut",defaults:s,initialize:function(t){this.segments=[],this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,this.SegmentArc=i.Arc.extend({ctx:this.chart.ctx,x:this.chart.width/2,y:this.chart.height/2}),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.calculateTotal(t),e.each(t,function(i,e){i.color||(i.color="hsl("+360*e/t.length+", 100%, 50%)"),this.addData(i,e,!0)},this),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,e,s){var n=void 0!==e?e:this.segments.length;"undefined"==typeof t.color&&(t.color=i.defaults.global.segmentColorDefault[n%i.defaults.global.segmentColorDefault.length],t.highlight=i.defaults.global.segmentHighlightColorDefaults[n%i.defaults.global.segmentHighlightColorDefaults.length]),this.segments.splice(n,0,new this.SegmentArc({value:t.value,outerRadius:this.options.animateScale?0:this.outerRadius,innerRadius:this.options.animateScale?0:this.outerRadius/100*this.options.percentageInnerCutout,fillColor:t.color,highlightColor:t.highlight||t.color,showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,startAngle:1.5*Math.PI,circumference:this.options.animateRotate?0:this.calculateCircumference(t.value),label:t.label})),s||(this.reflow(),this.update())},calculateCircumference:function(t){return this.total>0?2*Math.PI*(t/this.total):0},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=Math.abs(t.value)},this)},update:function(){this.calculateTotal(this.segments),e.each(this.activeElements,function(t){t.restore(["fillColor"])}),e.each(this.segments,function(t){t.save()}),this.render()},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,e.each(this.segments,function(t){t.update({outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout})},this)},draw:function(t){var i=t?t:1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.calculateCircumference(t.value),outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout},i),t.endAngle=t.startAngle+t.circumference,t.draw(),0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle)},this)}}),i.types.Doughnut.extend({name:"Pie",defaults:e.merge(s,{percentageInnerCutout:0})})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,scaleShowHorizontalLines:!0,scaleShowVerticalLines:!0,bezierCurve:!0,bezierCurveTension:.4,pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span class="<%=name.toLowerCase()%>-legend-icon" style="background-color:<%=datasets[i].strokeColor%>"></span><span class="<%=name.toLowerCase()%>-legend-text"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>',offsetGridLines:!1};i.Type.extend({name:"Line",defaults:s,initialize:function(t){this.PointClass=i.Point.extend({offsetGridLines:this.options.offsetGridLines,strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx,inRange:function(t){return Math.pow(t-this.x,2)<Math.pow(this.radius+this.hitDetectionRadius,2)}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(e,n){s.points.push(new this.PointClass({value:e,label:t.labels[n],datasetLabel:i.label,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this),this.buildScale(t.labels),this.eachPoints(function(t,i){e.extend(t,{x:this.scale.calculateX(i),y:this.scale.endPoint}),t.save()},this)},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachPoints(function(t){t.save()}),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.datasets,function(t){e.each(t.points,function(t){t.inRange(s.x,s.y)&&i.push(t)})},this),i},buildScale:function(t){var s=this,n=function(){var t=[];return s.eachPoints(function(i){t.push(i.value)}),t},o={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,offsetGridLines:this.options.offsetGridLines,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(n(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,showHorizontalLines:this.options.scaleShowHorizontalLines,showVerticalLines:this.options.scaleShowVerticalLines,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.pointDotRadius+this.options.pointDotStrokeWidth,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(o,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new i.Scale(o)},addData:function(t,i){e.each(t,function(t,e){this.datasets[e].points.push(new this.PointClass({value:t,label:i,datasetLabel:this.datasets[e].label,x:this.scale.calculateX(this.scale.valuesCount+1),y:this.scale.endPoint,strokeColor:this.datasets[e].pointStrokeColor,fillColor:this.datasets[e].pointColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.points.shift()},this),this.update()},reflow:function(){var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();var s=this.chart.ctx,n=function(t){return null!==t.value},o=function(t,i,s){return e.findNextWhere(i,n,s)||t},a=function(t,i,s){return e.findPreviousWhere(i,n,s)||t};this.scale&&(this.scale.draw(i),e.each(this.datasets,function(t){var h=e.where(t.points,n);e.each(t.points,function(t,e){t.hasValue()&&t.transition({y:this.scale.calculateY(t.value),x:this.scale.calculateX(e)},i)},this),this.options.bezierCurve&&e.each(h,function(t,i){var s=i>0&&i<h.length-1?this.options.bezierCurveTension:0;t.controlPoints=e.splineCurve(a(t,h,i),t,o(t,h,i),s),t.controlPoints.outer.y>this.scale.endPoint?t.controlPoints.outer.y=this.scale.endPoint:t.controlPoints.outer.y<this.scale.startPoint&&(t.controlPoints.outer.y=this.scale.startPoint),t.controlPoints.inner.y>this.scale.endPoint?t.controlPoints.inner.y=this.scale.endPoint:t.controlPoints.inner.y<this.scale.startPoint&&(t.controlPoints.inner.y=this.scale.startPoint)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(h,function(t,i){if(0===i)s.moveTo(t.x,t.y);else if(this.options.bezierCurve){var e=a(t,h,i);s.bezierCurveTo(e.controlPoints.outer.x,e.controlPoints.outer.y,t.controlPoints.inner.x,t.controlPoints.inner.y,t.x,t.y)}else s.lineTo(t.x,t.y)},this),this.options.datasetStroke&&s.stroke(),this.options.datasetFill&&h.length>0&&(s.lineTo(h[h.length-1].x,this.scale.endPoint),s.lineTo(h[0].x,this.scale.endPoint),s.fillStyle=t.fillColor,s.closePath(),s.fill()),e.each(h,function(t){t.draw()})},this))}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBeginAtZero:!0,scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,scaleShowLine:!0,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span class="<%=name.toLowerCase()%>-legend-icon" style="background-color:<%=segments[i].fillColor%>"></span><span class="<%=name.toLowerCase()%>-legend-text"><%if(segments[i].label){%><%=segments[i].label%><%}%></span></li><%}%></ul>'};i.Type.extend({name:"PolarArea",defaults:s,initialize:function(t){this.segments=[],this.SegmentArc=i.Arc.extend({showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,ctx:this.chart.ctx,innerRadius:0,x:this.chart.width/2,y:this.chart.height/2}),this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,lineArc:!0,width:this.chart.width,height:this.chart.height,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,valuesCount:t.length}),this.updateScaleRange(t),this.scale.update(),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({fillColor:t.color,highlightColor:t.highlight||t.color,label:t.label,value:t.value,outerRadius:this.options.animateScale?0:this.scale.calculateCenterOffset(t.value),circumference:this.options.animateRotate?0:this.scale.getCircumference(),startAngle:1.5*Math.PI})),e||(this.reflow(),this.update())},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this),this.scale.valuesCount=this.segments.length},updateScaleRange:function(t){var i=[];e.each(t,function(t){i.push(t.value)});var s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s,{size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2})},update:function(){this.calculateTotal(this.segments),e.each(this.segments,function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.updateScaleRange(this.segments),this.scale.update(),e.extend(this.scale,{xCenter:this.chart.width/2,yCenter:this.chart.height/2}),e.each(this.segments,function(t){t.update({outerRadius:this.scale.calculateCenterOffset(t.value)})},this)},draw:function(t){var i=t||1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.scale.getCircumference(),outerRadius:this.scale.calculateCenterOffset(t.value)},i),t.endAngle=t.startAngle+t.circumference,0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle),t.draw()},this),this.scale.draw()}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers;i.Type.extend({name:"Radar",defaults:{scaleShowLine:!0,angleShowLineOut:!0,scaleShowLabels:!1,scaleBeginAtZero:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,angleLineInterval:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:10,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span class="<%=name.toLowerCase()%>-legend-icon" style="background-color:<%=datasets[i].strokeColor%>"></span><span class="<%=name.toLowerCase()%>-legend-text"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>'},initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx}),this.datasets=[],this.buildScale(t),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(e,n){var o;this.scale.animation||(o=this.scale.getPointPosition(n,this.scale.calculateCenterOffset(e))),s.points.push(new this.PointClass({value:e,label:t.labels[n],datasetLabel:i.label,x:this.options.animation?this.scale.xCenter:o.x,y:this.options.animation?this.scale.yCenter:o.y,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this)},this),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=e.getRelativePosition(t),s=e.getAngleFromPoint({x:this.scale.xCenter,y:this.scale.yCenter},i),n=2*Math.PI/this.scale.valuesCount,o=Math.round((s.angle-1.5*Math.PI)/n),a=[];return(o>=this.scale.valuesCount||0>o)&&(o=0),s.distance<=this.scale.drawingArea&&e.each(this.datasets,function(t){a.push(t.points[o])}),a},buildScale:function(t){this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backgroundColors:this.options.scaleBackgroundColors,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,angleLineColor:this.options.angleLineColor,angleLineWidth:this.options.angleShowLineOut?this.options.angleLineWidth:0,angleLineInterval:this.options.angleLineInterval?this.options.angleLineInterval:1,pointLabelFontColor:this.options.pointLabelFontColor,pointLabelFontSize:this.options.pointLabelFontSize,pointLabelFontFamily:this.options.pointLabelFontFamily,pointLabelFontStyle:this.options.pointLabelFontStyle,height:this.chart.height,width:this.chart.width,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,labels:t.labels,valuesCount:t.datasets[0].data.length}),this.scale.setScaleSize(),this.updateScaleRange(t.datasets),this.scale.buildYLabels()},updateScaleRange:function(t){var i=function(){var i=[];return e.each(t,function(t){t.data?i=i.concat(t.data):e.each(t.points,function(t){i.push(t.value)})}),i}(),s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s)},addData:function(t,i){this.scale.valuesCount++,e.each(t,function(t,e){var s=this.scale.getPointPosition(this.scale.valuesCount,this.scale.calculateCenterOffset(t));this.datasets[e].points.push(new this.PointClass({value:t,label:i,datasetLabel:this.datasets[e].label,x:s.x,y:s.y,strokeColor:this.datasets[e].pointStrokeColor,fillColor:this.datasets[e].pointColor}))},this),this.scale.labels.push(i),this.reflow(),this.update()},removeData:function(){this.scale.valuesCount--,this.scale.labels.shift(),e.each(this.datasets,function(t){t.points.shift()},this),this.reflow(),this.update()},update:function(){this.eachPoints(function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.scale,{width:this.chart.width,height:this.chart.height,size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2}),this.updateScaleRange(this.datasets),this.scale.setScaleSize(),this.scale.buildYLabels()},draw:function(t){var i=t||1,s=this.chart.ctx;this.clear(),this.scale.draw(),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.hasValue()&&t.transition(this.scale.getPointPosition(e,this.scale.calculateCenterOffset(t.value)),i)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(t,i){0===i?s.moveTo(t.x,t.y):s.lineTo(t.x,t.y)},this),s.closePath(),s.stroke(),s.fillStyle=t.fillColor,this.options.datasetFill&&s.fill(),e.each(t.points,function(t){t.hasValue()&&t.draw()})},this)}})}.call(this);
fotomxq/ftmp-libs
template2/assets/plugins/chartjs/Chart.min.js
JavaScript
apache-2.0
57,275
package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bufio" "compress/gzip" "compress/zlib" "errors" "io" "net" "net/http" "strings" ) // OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting. var EnableContentEncoding = false // CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib) type CompressingResponseWriter struct { writer http.ResponseWriter compressor io.WriteCloser encoding string } // Header is part of http.ResponseWriter interface func (c *CompressingResponseWriter) Header() http.Header { return c.writer.Header() } // WriteHeader is part of http.ResponseWriter interface func (c *CompressingResponseWriter) WriteHeader(status int) { c.writer.WriteHeader(status) } // Write is part of http.ResponseWriter interface // It is passed through the compressor func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) { if c.isCompressorClosed() { return -1, errors.New("Compressing error: tried to write data using closed compressor") } return c.compressor.Write(bytes) } // CloseNotify is part of http.CloseNotifier interface func (c *CompressingResponseWriter) CloseNotify() <-chan bool { return c.writer.(http.CloseNotifier).CloseNotify() } // Close the underlying compressor func (c *CompressingResponseWriter) Close() error { if c.isCompressorClosed() { return errors.New("Compressing error: tried to close already closed compressor") } c.compressor.Close() if ENCODING_GZIP == c.encoding { currentCompressorProvider.ReleaseGzipWriter(c.compressor.(*gzip.Writer)) } if ENCODING_DEFLATE == c.encoding { currentCompressorProvider.ReleaseZlibWriter(c.compressor.(*zlib.Writer)) } // gc hint needed? c.compressor = nil return nil } func (c *CompressingResponseWriter) isCompressorClosed() bool { return nil == c.compressor } // Hijack implements the Hijacker interface // This is especially useful when combining Container.EnabledContentEncoding // in combination with websockets (for instance gorilla/websocket) func (c *CompressingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { hijacker, ok := c.writer.(http.Hijacker) if !ok { return nil, nil, errors.New("ResponseWriter doesn't support Hijacker interface") } return hijacker.Hijack() } // WantsCompressedResponse reads the Accept-Encoding header to see if and which encoding is requested. func wantsCompressedResponse(httpRequest *http.Request) (bool, string) { header := httpRequest.Header.Get(HEADER_AcceptEncoding) gi := strings.Index(header, ENCODING_GZIP) zi := strings.Index(header, ENCODING_DEFLATE) // use in order of appearance if gi == -1 { return zi != -1, ENCODING_DEFLATE } else if zi == -1 { return gi != -1, ENCODING_GZIP } else { if gi < zi { return true, ENCODING_GZIP } return true, ENCODING_DEFLATE } } // NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate} func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error) { httpWriter.Header().Set(HEADER_ContentEncoding, encoding) c := new(CompressingResponseWriter) c.writer = httpWriter var err error if ENCODING_GZIP == encoding { w := currentCompressorProvider.AcquireGzipWriter() w.Reset(httpWriter) c.compressor = w c.encoding = ENCODING_GZIP } else if ENCODING_DEFLATE == encoding { w := currentCompressorProvider.AcquireZlibWriter() w.Reset(httpWriter) c.compressor = w c.encoding = ENCODING_DEFLATE } else { return nil, errors.New("Unknown encoding:" + encoding) } return c, err }
bsalamat/kubernetes
vendor/github.com/emicklei/go-restful/compress.go
GO
apache-2.0
3,775
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Table editing support. * This file provides the class goog.editor.Table and two * supporting classes, goog.editor.TableRow and * goog.editor.TableCell. Together these provide support for * high level table modifications: Adding and deleting rows and columns, * and merging and splitting cells. * * @supported IE6+, WebKit 525+, Firefox 2+. */ goog.provide('goog.editor.Table'); goog.provide('goog.editor.TableCell'); goog.provide('goog.editor.TableRow'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.DomHelper'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.string.Unicode'); goog.require('goog.style'); /** * Class providing high level table editing functions. * @param {Element} node Element that is a table or descendant of a table. * @constructor */ goog.editor.Table = function(node) { this.element = goog.dom.getAncestorByTagNameAndClass(node, goog.dom.TagName.TABLE); if (!this.element) { this.logger_.severe( "Can't create Table based on a node " + "that isn't a table, or descended from a table."); } this.dom_ = goog.dom.getDomHelper(this.element); this.refresh(); }; /** * Logger object for debugging and error messages. * @type {goog.debug.Logger} * @private */ goog.editor.Table.prototype.logger_ = goog.debug.Logger.getLogger('goog.editor.Table'); /** * Walks the dom structure of this object's table element and populates * this.rows with goog.editor.TableRow objects. This is done initially * to populate the internal data structures, and also after each time the * DOM structure is modified. Currently this means that the all existing * information is discarded and re-read from the DOM. */ // TODO(user): support partial refresh to save cost of full update // every time there is a change to the DOM. goog.editor.Table.prototype.refresh = function() { var rows = this.rows = []; var tbody = this.element.getElementsByTagName(goog.dom.TagName.TBODY)[0]; if (!tbody) { return; } var trs = []; for (var child = tbody.firstChild; child; child = child.nextSibling) { if (child.nodeName == goog.dom.TagName.TR) { trs.push(child); } } for (var rowNum = 0, tr; tr = trs[rowNum]; rowNum++) { var existingRow = rows[rowNum]; var tds = goog.editor.Table.getChildCellElements(tr); var columnNum = 0; // A note on cellNum vs. columnNum: A cell is a td/th element. Cells may // use colspan/rowspan to extend over multiple rows/columns. cellNum // is the dom element number, columnNum is the logical column number. for (var cellNum = 0, td; td = tds[cellNum]; cellNum++) { // If there's already a cell extending into this column // (due to that cell's colspan/rowspan), increment the column counter. while (existingRow && existingRow.columns[columnNum]) { columnNum++; } var cell = new goog.editor.TableCell(td, rowNum, columnNum); // Place this cell in every row and column into which it extends. for (var i = 0; i < cell.rowSpan; i++) { var cellRowNum = rowNum + i; // Create TableRow objects in this.rows as needed. var cellRow = rows[cellRowNum]; if (!cellRow) { // TODO(user): try to avoid second trs[] lookup. rows.push( cellRow = new goog.editor.TableRow(trs[cellRowNum], cellRowNum)); } // Extend length of column array to make room for this cell. var minimumColumnLength = columnNum + cell.colSpan; if (cellRow.columns.length < minimumColumnLength) { cellRow.columns.length = minimumColumnLength; } for (var j = 0; j < cell.colSpan; j++) { var cellColumnNum = columnNum + j; cellRow.columns[cellColumnNum] = cell; } } columnNum += cell.colSpan; } } }; /** * Returns all child elements of a TR element that are of type TD or TH. * @param {Element} tr TR element in which to find children. * @return {Array.<Element>} array of child cell elements. */ goog.editor.Table.getChildCellElements = function(tr) { var cells = []; for (var i = 0, cell; cell = tr.childNodes[i]; i++) { if (cell.nodeName == goog.dom.TagName.TD || cell.nodeName == goog.dom.TagName.TH) { cells.push(cell); } } return cells; }; /** * Inserts a new row in the table. The row will be populated with new * cells, and existing rowspanned cells that overlap the new row will * be extended. * @param {number=} opt_rowIndex Index at which to insert the row. If * this is omitted the row will be appended to the end of the table. * @return {Element} The new row. */ goog.editor.Table.prototype.insertRow = function(opt_rowIndex) { var rowIndex = goog.isDefAndNotNull(opt_rowIndex) ? opt_rowIndex : this.rows.length; var refRow; var insertAfter; if (rowIndex == 0) { refRow = this.rows[0]; insertAfter = false; } else { refRow = this.rows[rowIndex - 1]; insertAfter = true; } var newTr = this.dom_.createElement('tr'); for (var i = 0, cell; cell = refRow.columns[i]; i += 1) { // Check whether the existing cell will span this new row. // If so, instead of creating a new cell, extend // the rowspan of the existing cell. if ((insertAfter && cell.endRow > rowIndex) || (!insertAfter && cell.startRow < rowIndex)) { cell.setRowSpan(cell.rowSpan + 1); if (cell.colSpan > 1) { i += cell.colSpan - 1; } } else { newTr.appendChild(this.createEmptyTd()); } if (insertAfter) { goog.dom.insertSiblingAfter(newTr, refRow.element); } else { goog.dom.insertSiblingBefore(newTr, refRow.element); } } this.refresh(); return newTr; }; /** * Inserts a new column in the table. The column will be created by * inserting new TD elements in each row, or extending the colspan * of existing TD elements. * @param {number=} opt_colIndex Index at which to insert the column. If * this is omitted the column will be appended to the right side of * the table. * @return {Array.<Element>} Array of new cell elements that were created * to populate the new column. */ goog.editor.Table.prototype.insertColumn = function(opt_colIndex) { // TODO(user): set column widths in a way that makes sense. var colIndex = goog.isDefAndNotNull(opt_colIndex) ? opt_colIndex : (this.rows[0] && this.rows[0].columns.length) || 0; var newTds = []; for (var rowNum = 0, row; row = this.rows[rowNum]; rowNum++) { var existingCell = row.columns[colIndex]; if (existingCell && existingCell.endCol >= colIndex && existingCell.startCol < colIndex) { existingCell.setColSpan(existingCell.colSpan + 1); rowNum += existingCell.rowSpan - 1; } else { var newTd = this.createEmptyTd(); // TODO(user): figure out a way to intelligently size new columns. newTd.style.width = goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH + 'px'; this.insertCellElement(newTd, rowNum, colIndex); newTds.push(newTd); } } this.refresh(); return newTds; }; /** * Removes a row from the table, removing the TR element and * decrementing the rowspan of any cells in other rows that overlap the row. * @param {number} rowIndex Index of the row to delete. */ goog.editor.Table.prototype.removeRow = function(rowIndex) { var row = this.rows[rowIndex]; if (!row) { this.logger_.warning( "Can't remove row at position " + rowIndex + ': no such row.'); } for (var i = 0, cell; cell = row.columns[i]; i += cell.colSpan) { if (cell.rowSpan > 1) { cell.setRowSpan(cell.rowSpan - 1); if (cell.startRow == rowIndex) { // Rowspanned cell started in this row - move it down to the next row. this.insertCellElement(cell.element, rowIndex + 1, cell.startCol); } } } row.element.parentNode.removeChild(row.element); this.refresh(); }; /** * Removes a column from the table. This is done by removing cell elements, * or shrinking the colspan of elements that span multiple columns. * @param {number} colIndex Index of the column to delete. */ goog.editor.Table.prototype.removeColumn = function(colIndex) { for (var i = 0, row; row = this.rows[i]; i++) { var cell = row.columns[colIndex]; if (!cell) { this.logger_.severe( "Can't remove cell at position " + i + ', ' + colIndex + ': no such cell.'); } if (cell.colSpan > 1) { cell.setColSpan(cell.colSpan - 1); } else { cell.element.parentNode.removeChild(cell.element); } // Skip over following rows that contain this same cell. i += cell.rowSpan - 1; } this.refresh(); }; /** * Merges multiple cells into a single cell, and sets the rowSpan and colSpan * attributes of the cell to take up the same space as the original cells. * @param {number} startRowIndex Top coordinate of the cells to merge. * @param {number} startColIndex Left coordinate of the cells to merge. * @param {number} endRowIndex Bottom coordinate of the cells to merge. * @param {number} endColIndex Right coordinate of the cells to merge. * @return {boolean} Whether or not the merge was possible. If the cells * in the supplied coordinates can't be merged this will return false. */ goog.editor.Table.prototype.mergeCells = function( startRowIndex, startColIndex, endRowIndex, endColIndex) { // TODO(user): take a single goog.math.Rect parameter instead? var cells = []; var cell; if (startRowIndex == endRowIndex && startColIndex == endColIndex) { this.logger_.warning("Can't merge single cell"); return false; } // Gather cells and do sanity check. for (var i = startRowIndex; i <= endRowIndex; i++) { for (var j = startColIndex; j <= endColIndex; j++) { cell = this.rows[i].columns[j]; if (cell.startRow < startRowIndex || cell.endRow > endRowIndex || cell.startCol < startColIndex || cell.endCol > endColIndex) { this.logger_.warning( "Can't merge cells: the cell in row " + i + ', column ' + j + 'extends outside the supplied rectangle.'); return false; } // TODO(user): this is somewhat inefficient, as we will add // a reference for a cell for each position, even if it's a single // cell with row/colspan. cells.push(cell); } } var targetCell = cells[0]; var targetTd = targetCell.element; var doc = this.dom_.getDocument(); // Merge cell contents and discard other cells. for (var i = 1; cell = cells[i]; i++) { var td = cell.element; if (!td.parentNode || td == targetTd) { // We've already handled this cell at one of its previous positions. continue; } // Add a space if needed, to keep merged content from getting squished // together. if (targetTd.lastChild && targetTd.lastChild.nodeType == goog.dom.NodeType.TEXT) { targetTd.appendChild(doc.createTextNode(' ')); } var childNode; while ((childNode = td.firstChild)) { targetTd.appendChild(childNode); } td.parentNode.removeChild(td); } targetCell.setColSpan((endColIndex - startColIndex) + 1); targetCell.setRowSpan((endRowIndex - startRowIndex) + 1); if (endColIndex > startColIndex) { // Clear width on target cell. // TODO(user): instead of clearing width, calculate width // based on width of input cells targetTd.removeAttribute('width'); targetTd.style.width = null; } this.refresh(); return true; }; /** * Splits a cell with colspans or rowspans into multiple descrete cells. * @param {number} rowIndex y coordinate of the cell to split. * @param {number} colIndex x coordinate of the cell to split. * @return {Array.<Element>} Array of new cell elements created by splitting * the cell. */ // TODO(user): support splitting only horizontally or vertically, // support splitting cells that aren't already row/colspanned. goog.editor.Table.prototype.splitCell = function(rowIndex, colIndex) { var row = this.rows[rowIndex]; var cell = row.columns[colIndex]; var newTds = []; for (var i = 0; i < cell.rowSpan; i++) { for (var j = 0; j < cell.colSpan; j++) { if (i > 0 || j > 0) { var newTd = this.createEmptyTd(); this.insertCellElement(newTd, rowIndex + i, colIndex + j); newTds.push(newTd); } } } cell.setColSpan(1); cell.setRowSpan(1); this.refresh(); return newTds; }; /** * Inserts a cell element at the given position. The colIndex is the logical * column index, not the position in the dom. This takes into consideration * that cells in a given logical row may actually be children of a previous * DOM row that have used rowSpan to extend into the row. * @param {Element} td The new cell element to insert. * @param {number} rowIndex Row in which to insert the element. * @param {number} colIndex Column in which to insert the element. */ goog.editor.Table.prototype.insertCellElement = function( td, rowIndex, colIndex) { var row = this.rows[rowIndex]; var nextSiblingElement = null; for (var i = colIndex, cell; cell = row.columns[i]; i += cell.colSpan) { if (cell.startRow == rowIndex) { nextSiblingElement = cell.element; break; } } row.element.insertBefore(td, nextSiblingElement); }; /** * Creates an empty TD element and fill it with some empty content so it will * show up with borders even in IE pre-7 or if empty-cells is set to 'hide' * @return {Element} a new TD element. */ goog.editor.Table.prototype.createEmptyTd = function() { // TODO(user): more cross-browser testing to determine best // and least annoying filler content. return this.dom_.createDom(goog.dom.TagName.TD, {}, goog.string.Unicode.NBSP); }; /** * Class representing a logical table row: a tr element and any cells * that appear in that row. * @param {Element} trElement This rows's underlying TR element. * @param {number} rowIndex This row's index in its parent table. * @constructor */ goog.editor.TableRow = function(trElement, rowIndex) { this.index = rowIndex; this.element = trElement; this.columns = []; }; /** * Class representing a table cell, which may span across multiple * rows and columns * @param {Element} td This cell's underlying TD or TH element. * @param {number} startRow Index of the row where this cell begins. * @param {number} startCol Index of the column where this cell begins. * @constructor */ goog.editor.TableCell = function(td, startRow, startCol) { this.element = td; this.colSpan = parseInt(td.colSpan, 10) || 1; this.rowSpan = parseInt(td.rowSpan, 10) || 1; this.startRow = startRow; this.startCol = startCol; this.updateCoordinates_(); }; /** * Calculates this cell's endRow/endCol coordinates based on rowSpan/colSpan * @private */ goog.editor.TableCell.prototype.updateCoordinates_ = function() { this.endCol = this.startCol + this.colSpan - 1; this.endRow = this.startRow + this.rowSpan - 1; }; /** * Set this cell's colSpan, updating both its colSpan property and the * underlying element's colSpan attribute. * @param {number} colSpan The new colSpan. */ goog.editor.TableCell.prototype.setColSpan = function(colSpan) { if (colSpan != this.colSpan) { if (colSpan > 1) { this.element.colSpan = colSpan; } else { this.element.colSpan = 1, this.element.removeAttribute('colSpan'); } this.colSpan = colSpan; this.updateCoordinates_(); } }; /** * Set this cell's rowSpan, updating both its rowSpan property and the * underlying element's rowSpan attribute. * @param {number} rowSpan The new rowSpan. */ goog.editor.TableCell.prototype.setRowSpan = function(rowSpan) { if (rowSpan != this.rowSpan) { if (rowSpan > 1) { this.element.rowSpan = rowSpan.toString(); } else { this.element.rowSpan = '1'; this.element.removeAttribute('rowSpan'); } this.rowSpan = rowSpan; this.updateCoordinates_(); } }; /** * Optimum size of empty cells (in pixels), if possible. * @type {number} */ goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH = 60; /** * Maximum width for new tables. * @type {number} */ goog.editor.Table.OPTIMUM_MAX_NEW_TABLE_WIDTH = 600; /** * Default color for table borders. * @type {string} */ goog.editor.Table.DEFAULT_BORDER_COLOR = '#888'; /** * Creates a new table element, populated with cells and formatted. * @param {Document} doc Document in which to create the table element. * @param {number} columns Number of columns in the table. * @param {number} rows Number of rows in the table. * @param {Object=} opt_tableStyle Object containing borderWidth and borderColor * properties, used to set the inital style of the table. * @return {Element} a table element. */ goog.editor.Table.createDomTable = function( doc, columns, rows, opt_tableStyle) { // TODO(user): define formatting properties as constants, // make separate formatTable() function var style = { borderWidth: '1', borderColor: goog.editor.Table.DEFAULT_BORDER_COLOR }; for (var prop in opt_tableStyle) { style[prop] = opt_tableStyle[prop]; } var dom = new goog.dom.DomHelper(doc); var tableElement = dom.createTable(rows, columns, true); var minimumCellWidth = 10; // Calculate a good cell width. var cellWidth = Math.max( minimumCellWidth, Math.min(goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH, goog.editor.Table.OPTIMUM_MAX_NEW_TABLE_WIDTH / columns)); var tds = tableElement.getElementsByTagName(goog.dom.TagName.TD); for (var i = 0, td; td = tds[i]; i++) { td.style.width = cellWidth + 'px'; } // Set border somewhat redundantly to make sure they show // up correctly in all browsers. goog.style.setStyle( tableElement, { 'borderCollapse': 'collapse', 'borderColor': style.borderColor, 'borderWidth': style.borderWidth + 'px' }); tableElement.border = style.borderWidth; tableElement.setAttribute('bordercolor', style.borderColor); tableElement.setAttribute('cellspacing', '0'); return tableElement; };
illicitonion/givabit
lib/misc/closure-library/closure/goog/editor/table.js
JavaScript
apache-2.0
18,922
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import io.airlift.slice.Slice; import java.io.IOException; import static io.airlift.slice.Slices.utf8Slice; public class SliceDeserializer extends JsonDeserializer<Slice> { @Override public Slice deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return utf8Slice(jsonParser.readValueAs(String.class)); } }
elonazoulay/presto
presto-main/src/main/java/com/facebook/presto/server/SliceDeserializer.java
Java
apache-2.0
1,169
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package types import ( "strconv" ) // ID represents a generic identifier which is canonically // stored as a uint64 but is typically represented as a // base-16 string for input/output type ID uint64 func (i ID) String() string { return strconv.FormatUint(uint64(i), 16) } // IDFromString attempts to create an ID from a base-16 string. func IDFromString(s string) (ID, error) { i, err := strconv.ParseUint(s, 16, 64) return ID(i), err } // IDSlice implements the sort interface type IDSlice []ID func (p IDSlice) Len() int { return len(p) } func (p IDSlice) Less(i, j int) bool { return uint64(p[i]) < uint64(p[j]) } func (p IDSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
bluebreezecf/docker
vendor/src/github.com/coreos/etcd/pkg/types/id.go
GO
apache-2.0
1,293
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.percolate; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.elasticsearch.action.ValidateActions.addValidationError; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringArrayValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue; /** * A multi percolate request that encapsulates multiple {@link PercolateRequest} instances in a single api call. */ public class MultiPercolateRequest extends ActionRequest<MultiPercolateRequest> implements CompositeIndicesRequest { private String[] indices; private String documentType; private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed(); private List<PercolateRequest> requests = new ArrayList<>(); /** * Embeds a percolate request to this multi percolate request */ public MultiPercolateRequest add(PercolateRequestBuilder requestBuilder) { return add(requestBuilder.request()); } /** * Embeds a percolate request to this multi percolate request */ public MultiPercolateRequest add(PercolateRequest request) { if (request.indices() == null && indices != null) { request.indices(indices); } if (request.documentType() == null && documentType != null) { request.documentType(documentType); } if (request.indicesOptions() == IndicesOptions.strictExpandOpenAndForbidClosed() && indicesOptions != IndicesOptions.strictExpandOpenAndForbidClosed()) { request.indicesOptions(indicesOptions); } requests.add(request); return this; } /** * Embeds a percolate request which request body is defined as raw bytes to this multi percolate request */ public MultiPercolateRequest add(byte[] data, int from, int length) throws Exception { return add(new BytesArray(data, from, length), true); } /** * Embeds a percolate request which request body is defined as raw bytes to this multi percolate request */ public MultiPercolateRequest add(BytesReference data, boolean allowExplicitIndex) throws Exception { XContent xContent = XContentFactory.xContent(data); int from = 0; int length = data.length(); byte marker = xContent.streamSeparator(); while (true) { int nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } // support first line with \n if (nextMarker == 0) { from = nextMarker + 1; continue; } PercolateRequest percolateRequest = new PercolateRequest(); if (indices != null) { percolateRequest.indices(indices); } if (documentType != null) { percolateRequest.documentType(documentType); } if (indicesOptions != IndicesOptions.strictExpandOpenAndForbidClosed()) { percolateRequest.indicesOptions(indicesOptions); } // now parse the action if (nextMarker - from > 0) { try (XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from))) { // Move to START_OBJECT, if token is null, its an empty data XContentParser.Token token = parser.nextToken(); if (token != null) { // Top level json object assert token == XContentParser.Token.START_OBJECT; token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new ElasticsearchParseException("Expected field"); } token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new ElasticsearchParseException("expected start object"); } String percolateAction = parser.currentName(); if ("percolate".equals(percolateAction)) { parsePercolateAction(parser, percolateRequest, allowExplicitIndex); } else if ("count".equals(percolateAction)) { percolateRequest.onlyCount(true); parsePercolateAction(parser, percolateRequest, allowExplicitIndex); } else { throw new ElasticsearchParseException("[{}] isn't a supported percolate operation", percolateAction); } } } } // move pointers from = nextMarker + 1; // now for the body nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } percolateRequest.source(data.slice(from, nextMarker - from)); // move pointers from = nextMarker + 1; add(percolateRequest); } return this; } @Override public List<? extends IndicesRequest> subRequests() { List<IndicesRequest> indicesRequests = new ArrayList<>(); for (PercolateRequest percolateRequest : this.requests) { indicesRequests.addAll(percolateRequest.subRequests()); } return indicesRequests; } private void parsePercolateAction(XContentParser parser, PercolateRequest percolateRequest, boolean allowExplicitIndex) throws IOException { String globalIndex = indices != null && indices.length > 0 ? indices[0] : null; Map<String, Object> header = parser.map(); if (header.containsKey("id")) { GetRequest getRequest = new GetRequest(globalIndex); percolateRequest.getRequest(getRequest); for (Map.Entry<String, Object> entry : header.entrySet()) { Object value = entry.getValue(); if ("id".equals(entry.getKey())) { getRequest.id(nodeStringValue(value, null)); header.put("id", entry.getValue()); } else if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if (!allowExplicitIndex) { throw new IllegalArgumentException("explicit index in multi percolate is not allowed"); } getRequest.index(nodeStringValue(value, null)); } else if ("type".equals(entry.getKey())) { getRequest.type(nodeStringValue(value, null)); } else if ("preference".equals(entry.getKey())) { getRequest.preference(nodeStringValue(value, null)); } else if ("routing".equals(entry.getKey())) { getRequest.routing(nodeStringValue(value, null)); } else if ("percolate_index".equals(entry.getKey()) || "percolate_indices".equals(entry.getKey()) || "percolateIndex".equals(entry.getKey()) || "percolateIndices".equals(entry.getKey())) { percolateRequest.indices(nodeStringArrayValue(value)); } else if ("percolate_type".equals(entry.getKey()) || "percolateType".equals(entry.getKey())) { percolateRequest.documentType(nodeStringValue(value, null)); } else if ("percolate_preference".equals(entry.getKey()) || "percolatePreference".equals(entry.getKey())) { percolateRequest.preference(nodeStringValue(value, null)); } else if ("percolate_routing".equals(entry.getKey()) || "percolateRouting".equals(entry.getKey())) { percolateRequest.routing(nodeStringValue(value, null)); } } // Setting values based on get request, if needed... if ((percolateRequest.indices() == null || percolateRequest.indices().length == 0) && getRequest.index() != null) { percolateRequest.indices(getRequest.index()); } if (percolateRequest.documentType() == null && getRequest.type() != null) { percolateRequest.documentType(getRequest.type()); } if (percolateRequest.routing() == null && getRequest.routing() != null) { percolateRequest.routing(getRequest.routing()); } if (percolateRequest.preference() == null && getRequest.preference() != null) { percolateRequest.preference(getRequest.preference()); } } else { for (Map.Entry<String, Object> entry : header.entrySet()) { Object value = entry.getValue(); if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if (!allowExplicitIndex) { throw new IllegalArgumentException("explicit index in multi percolate is not allowed"); } percolateRequest.indices(nodeStringArrayValue(value)); } else if ("type".equals(entry.getKey())) { percolateRequest.documentType(nodeStringValue(value, null)); } else if ("preference".equals(entry.getKey())) { percolateRequest.preference(nodeStringValue(value, null)); } else if ("routing".equals(entry.getKey())) { percolateRequest.routing(nodeStringValue(value, null)); } } } percolateRequest.indicesOptions(IndicesOptions.fromMap(header, indicesOptions)); } private int findNextMarker(byte marker, int from, BytesReference data, int length) { for (int i = from; i < length; i++) { if (data.get(i) == marker) { return i; } } return -1; } /** * @return The list of already set percolate requests. */ public List<PercolateRequest> requests() { return this.requests; } /** * @return Returns the {@link IndicesOptions} that is used as default for all percolate requests. */ public IndicesOptions indicesOptions() { return indicesOptions; } /** * Sets the {@link IndicesOptions} for all percolate request that don't have this set. * * Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests * will have no effect on any percolate requests already added. */ public MultiPercolateRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * @return The default indices for all percolate request. */ public String[] indices() { return indices; } /** * Sets the default indices for any percolate request that doesn't have indices defined. * * Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests * will have no effect on any percolate requests already added. */ public MultiPercolateRequest indices(String... indices) { this.indices = indices; return this; } /** * @return Sets the default type for all percolate requests */ public String documentType() { return documentType; } /** * Sets the default document type for any percolate request that doesn't have a document type set. * * Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests * will have no effect on any percolate requests already added. */ public MultiPercolateRequest documentType(String type) { this.documentType = type; return this; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = addValidationError("no requests added", validationException); } for (int i = 0; i < requests.size(); i++) { ActionRequestValidationException ex = requests.get(i).validate(); if (ex != null) { if (validationException == null) { validationException = new ActionRequestValidationException(); } validationException.addValidationErrors(ex.validationErrors()); } } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); indices = in.readStringArray(); documentType = in.readOptionalString(); indicesOptions = IndicesOptions.readIndicesOptions(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { PercolateRequest request = new PercolateRequest(); request.readFrom(in); requests.add(request); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); out.writeOptionalString(documentType); indicesOptions.writeIndicesOptions(out); out.writeVInt(requests.size()); for (PercolateRequest request : requests) { request.writeTo(out); } } }
huanzhong/elasticsearch
core/src/main/java/org/elasticsearch/action/percolate/MultiPercolateRequest.java
Java
apache-2.0
15,257
// +build go1.1 package pq import ( "bufio" "bytes" "database/sql" "database/sql/driver" "io" "math/rand" "net" "runtime" "strconv" "strings" "sync" "testing" "time" "github.com/lib/pq/oid" ) var ( selectStringQuery = "SELECT '" + strings.Repeat("0123456789", 10) + "'" selectSeriesQuery = "SELECT generate_series(1, 100)" ) func BenchmarkSelectString(b *testing.B) { var result string benchQuery(b, selectStringQuery, &result) } func BenchmarkSelectSeries(b *testing.B) { var result int benchQuery(b, selectSeriesQuery, &result) } func benchQuery(b *testing.B, query string, result interface{}) { b.StopTimer() db := openTestConn(b) defer db.Close() b.StartTimer() for i := 0; i < b.N; i++ { benchQueryLoop(b, db, query, result) } } func benchQueryLoop(b *testing.B, db *sql.DB, query string, result interface{}) { rows, err := db.Query(query) if err != nil { b.Fatal(err) } defer rows.Close() for rows.Next() { err = rows.Scan(result) if err != nil { b.Fatal("failed to scan", err) } } } // reading from circularConn yields content[:prefixLen] once, followed by // content[prefixLen:] over and over again. It never returns EOF. type circularConn struct { content string prefixLen int pos int net.Conn // for all other net.Conn methods that will never be called } func (r *circularConn) Read(b []byte) (n int, err error) { n = copy(b, r.content[r.pos:]) r.pos += n if r.pos >= len(r.content) { r.pos = r.prefixLen } return } func (r *circularConn) Write(b []byte) (n int, err error) { return len(b), nil } func (r *circularConn) Close() error { return nil } func fakeConn(content string, prefixLen int) *conn { c := &circularConn{content: content, prefixLen: prefixLen} return &conn{buf: bufio.NewReader(c), c: c} } // This benchmark is meant to be the same as BenchmarkSelectString, but takes // out some of the factors this package can't control. The numbers are less noisy, // but also the costs of network communication aren't accurately represented. func BenchmarkMockSelectString(b *testing.B) { b.StopTimer() // taken from a recorded run of BenchmarkSelectString // See: http://www.postgresql.org/docs/current/static/protocol-message-formats.html const response = "1\x00\x00\x00\x04" + "t\x00\x00\x00\x06\x00\x00" + "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + "Z\x00\x00\x00\x05I" + "2\x00\x00\x00\x04" + "D\x00\x00\x00n\x00\x01\x00\x00\x00d0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + "C\x00\x00\x00\rSELECT 1\x00" + "Z\x00\x00\x00\x05I" + "3\x00\x00\x00\x04" + "Z\x00\x00\x00\x05I" c := fakeConn(response, 0) b.StartTimer() for i := 0; i < b.N; i++ { benchMockQuery(b, c, selectStringQuery) } } var seriesRowData = func() string { var buf bytes.Buffer for i := 1; i <= 100; i++ { digits := byte(2) if i >= 100 { digits = 3 } else if i < 10 { digits = 1 } buf.WriteString("D\x00\x00\x00") buf.WriteByte(10 + digits) buf.WriteString("\x00\x01\x00\x00\x00") buf.WriteByte(digits) buf.WriteString(strconv.Itoa(i)) } return buf.String() }() func BenchmarkMockSelectSeries(b *testing.B) { b.StopTimer() var response = "1\x00\x00\x00\x04" + "t\x00\x00\x00\x06\x00\x00" + "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + "Z\x00\x00\x00\x05I" + "2\x00\x00\x00\x04" + seriesRowData + "C\x00\x00\x00\x0fSELECT 100\x00" + "Z\x00\x00\x00\x05I" + "3\x00\x00\x00\x04" + "Z\x00\x00\x00\x05I" c := fakeConn(response, 0) b.StartTimer() for i := 0; i < b.N; i++ { benchMockQuery(b, c, selectSeriesQuery) } } func benchMockQuery(b *testing.B, c *conn, query string) { stmt, err := c.Prepare(query) if err != nil { b.Fatal(err) } defer stmt.Close() rows, err := stmt.Query(nil) if err != nil { b.Fatal(err) } defer rows.Close() var dest [1]driver.Value for { if err := rows.Next(dest[:]); err != nil { if err == io.EOF { break } b.Fatal(err) } } } func BenchmarkPreparedSelectString(b *testing.B) { var result string benchPreparedQuery(b, selectStringQuery, &result) } func BenchmarkPreparedSelectSeries(b *testing.B) { var result int benchPreparedQuery(b, selectSeriesQuery, &result) } func benchPreparedQuery(b *testing.B, query string, result interface{}) { b.StopTimer() db := openTestConn(b) defer db.Close() stmt, err := db.Prepare(query) if err != nil { b.Fatal(err) } defer stmt.Close() b.StartTimer() for i := 0; i < b.N; i++ { benchPreparedQueryLoop(b, db, stmt, result) } } func benchPreparedQueryLoop(b *testing.B, db *sql.DB, stmt *sql.Stmt, result interface{}) { rows, err := stmt.Query() if err != nil { b.Fatal(err) } if !rows.Next() { rows.Close() b.Fatal("no rows") } defer rows.Close() for rows.Next() { err = rows.Scan(&result) if err != nil { b.Fatal("failed to scan") } } } // See the comment for BenchmarkMockSelectString. func BenchmarkMockPreparedSelectString(b *testing.B) { b.StopTimer() const parseResponse = "1\x00\x00\x00\x04" + "t\x00\x00\x00\x06\x00\x00" + "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + "Z\x00\x00\x00\x05I" const responses = parseResponse + "2\x00\x00\x00\x04" + "D\x00\x00\x00n\x00\x01\x00\x00\x00d0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" + "C\x00\x00\x00\rSELECT 1\x00" + "Z\x00\x00\x00\x05I" c := fakeConn(responses, len(parseResponse)) stmt, err := c.Prepare(selectStringQuery) if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { benchPreparedMockQuery(b, c, stmt) } } func BenchmarkMockPreparedSelectSeries(b *testing.B) { b.StopTimer() const parseResponse = "1\x00\x00\x00\x04" + "t\x00\x00\x00\x06\x00\x00" + "T\x00\x00\x00!\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xc1\xff\xfe\xff\xff\xff\xff\x00\x00" + "Z\x00\x00\x00\x05I" var responses = parseResponse + "2\x00\x00\x00\x04" + seriesRowData + "C\x00\x00\x00\x0fSELECT 100\x00" + "Z\x00\x00\x00\x05I" c := fakeConn(responses, len(parseResponse)) stmt, err := c.Prepare(selectSeriesQuery) if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { benchPreparedMockQuery(b, c, stmt) } } func benchPreparedMockQuery(b *testing.B, c *conn, stmt driver.Stmt) { rows, err := stmt.Query(nil) if err != nil { b.Fatal(err) } defer rows.Close() var dest [1]driver.Value for { if err := rows.Next(dest[:]); err != nil { if err == io.EOF { break } b.Fatal(err) } } } func BenchmarkEncodeInt64(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{}, int64(1234), oid.T_int8) } } func BenchmarkEncodeFloat64(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{}, 3.14159, oid.T_float8) } } var testByteString = []byte("abcdefghijklmnopqrstuvwxyz") func BenchmarkEncodeByteaHex(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{serverVersion: 90000}, testByteString, oid.T_bytea) } } func BenchmarkEncodeByteaEscape(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{serverVersion: 84000}, testByteString, oid.T_bytea) } } func BenchmarkEncodeBool(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{}, true, oid.T_bool) } } var testTimestamptz = time.Date(2001, time.January, 1, 0, 0, 0, 0, time.Local) func BenchmarkEncodeTimestamptz(b *testing.B) { for i := 0; i < b.N; i++ { encode(&parameterStatus{}, testTimestamptz, oid.T_timestamptz) } } var testIntBytes = []byte("1234") func BenchmarkDecodeInt64(b *testing.B) { for i := 0; i < b.N; i++ { decode(&parameterStatus{}, testIntBytes, oid.T_int8, formatText) } } var testFloatBytes = []byte("3.14159") func BenchmarkDecodeFloat64(b *testing.B) { for i := 0; i < b.N; i++ { decode(&parameterStatus{}, testFloatBytes, oid.T_float8, formatText) } } var testBoolBytes = []byte{'t'} func BenchmarkDecodeBool(b *testing.B) { for i := 0; i < b.N; i++ { decode(&parameterStatus{}, testBoolBytes, oid.T_bool, formatText) } } func TestDecodeBool(t *testing.T) { db := openTestConn(t) rows, err := db.Query("select true") if err != nil { t.Fatal(err) } rows.Close() } var testTimestamptzBytes = []byte("2013-09-17 22:15:32.360754-07") func BenchmarkDecodeTimestamptz(b *testing.B) { for i := 0; i < b.N; i++ { decode(&parameterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) } } func BenchmarkDecodeTimestamptzMultiThread(b *testing.B) { oldProcs := runtime.GOMAXPROCS(0) defer runtime.GOMAXPROCS(oldProcs) runtime.GOMAXPROCS(runtime.NumCPU()) globalLocationCache = newLocationCache() f := func(wg *sync.WaitGroup, loops int) { defer wg.Done() for i := 0; i < loops; i++ { decode(&parameterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) } } wg := &sync.WaitGroup{} b.ResetTimer() for j := 0; j < 10; j++ { wg.Add(1) go f(wg, b.N/10) } wg.Wait() } func BenchmarkLocationCache(b *testing.B) { globalLocationCache = newLocationCache() for i := 0; i < b.N; i++ { globalLocationCache.getLocation(rand.Intn(10000)) } } func BenchmarkLocationCacheMultiThread(b *testing.B) { oldProcs := runtime.GOMAXPROCS(0) defer runtime.GOMAXPROCS(oldProcs) runtime.GOMAXPROCS(runtime.NumCPU()) globalLocationCache = newLocationCache() f := func(wg *sync.WaitGroup, loops int) { defer wg.Done() for i := 0; i < loops; i++ { globalLocationCache.getLocation(rand.Intn(10000)) } } wg := &sync.WaitGroup{} b.ResetTimer() for j := 0; j < 10; j++ { wg.Add(1) go f(wg, b.N/10) } wg.Wait() } // Stress test the performance of parsing results from the wire. func BenchmarkResultParsing(b *testing.B) { b.StopTimer() db := openTestConn(b) defer db.Close() _, err := db.Exec("BEGIN") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { res, err := db.Query("SELECT generate_series(1, 50000)") if err != nil { b.Fatal(err) } res.Close() } }
jcgruenhage/dendrite
vendor/src/github.com/lib/pq/bench_test.go
GO
apache-2.0
10,212
/*! DataTables 1.10.2 * ©2008-2014 SpryMedia Ltd - datatables.net/license */ (function(za,O,l){var N=function(h){function T(a){var b,c,d={};h.each(a,function(e){if((b=e.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=e.replace(b[0],b[2].toLowerCase()),d[c]=e,"o"===b[1]&&T(a[e])});a._hungarianMap=d}function G(a,b,c){a._hungarianMap||T(a);var d;h.each(b,function(e){d=a._hungarianMap[e];if(d!==l&&(c||b[d]===l))"o"===d.charAt(0)?(b[d]||(b[d]={}),h.extend(!0,b[d],b[e]),G(a[d],b[d],c)):b[d]=b[e]})}function N(a){var b=p.defaults.oLanguage,c=a.sZeroRecords; !a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&D(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&D(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&cb(a)}function db(a){w(a,"ordering","bSort");w(a,"orderMulti","bSortMulti");w(a,"orderClasses","bSortClasses");w(a,"orderCellsTop","bSortCellsTop");w(a,"order","aaSorting");w(a,"orderFixed","aaSortingFixed");w(a,"paging","bPaginate"); w(a,"pagingType","sPaginationType");w(a,"pageLength","iDisplayLength");w(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&G(p.models.oSearch,a[b])}function eb(a){w(a,"orderable","bSortable");w(a,"orderData","aDataSort");w(a,"orderSequence","asSorting");w(a,"orderDataType","sortDataType")}function fb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",top:1,left:1,width:100, overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==c.offset().left;b.remove()}function gb(a,b,c,d,e,f){var g,j=!1;c!==l&&(g=c,j=!0);for(;d!==e;)a.hasOwnProperty(d)&&(g=j?b(g,a[d],d,a):a[d],j=!0,d+=f);return g}function Aa(a,b){var c=p.defaults.column,d=a.aoColumns.length,c=h.extend({},p.models.oColumn,c,{nTh:b?b:O.createElement("th"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML: "",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.mData:d,idx:d});a.aoColumns.push(c);c=a.aoPreSearchCols;c[d]=h.extend({},p.models.oSearch,c[d]);fa(a,d,null)}function fa(a,b,c){var b=a.aoColumns[b],d=a.oClasses,e=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=e.attr("width")||null;var f=(e.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==l&&null!==c&&(eb(c),G(p.defaults.column,c),c.mDataProp!==l&&!c.mData&&(c.mData=c.mDataProp),c.sType&&(b._sManualType=c.sType),c.className&& !c.sClass&&(c.sClass=c.className),h.extend(b,c),D(b,c,"sWidth","sWidthOrig"),"number"===typeof c.iDataSort&&(b.aDataSort=[c.iDataSort]),D(b,c,"aDataSort"));var g=b.mData,j=U(g),i=b.mRender?U(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var d=j(a,b,l,c);return i&&b?i(d,b,a,c):d};b.fnSetData=function(a,b,c){return Ba(g)(a,b,c)};a.oFeatures.bSort||(b.bSortable=!1,e.addClass(d.sSortableNone)); a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=d.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=d.sSortableAsc,b.sSortingClassJUI=d.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=d.sSortableDesc,b.sSortingClassJUI=d.sSortJUIDescAllowed):(b.sSortingClass=d.sSortable,b.sSortingClassJUI=d.sSortJUI)}function V(a){if(!1!==a.oFeatures.bAutoWidth){var b=a.aoColumns;Ca(a);for(var c=0,d=b.length;c<d;c++)b[c].nTh.style.width=b[c].sWidth}b= a.oScroll;(""!==b.sY||""!==b.sX)&&W(a);u(a,null,"column-sizing",[a])}function ga(a,b){var c=X(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function Y(a,b){var c=X(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function Z(a){return X(a,"bVisible").length}function X(a,b){var c=[];h.map(a.aoColumns,function(a,e){a[b]&&c.push(e)});return c}function Da(a){var b=a.aoColumns,c=a.aoData,d=p.ext.type.detect,e,f,g,j,i,h,m,o,k;e=0;for(f=b.length;e<f;e++)if(m=b[e],k=[],!m.sType&&m._sManualType)m.sType= m._sManualType;else if(!m.sType){g=0;for(j=d.length;g<j;g++){i=0;for(h=c.length;i<h&&!(k[i]===l&&(k[i]=A(a,i,e,"type")),o=d[g](k[i],a),!o||"html"===o);i++);if(o){m.sType=o;break}}m.sType||(m.sType="string")}}function hb(a,b,c,d){var e,f,g,j,i,n,m=a.aoColumns;if(b)for(e=b.length-1;0<=e;e--){n=b[e];var o=n.targets!==l?n.targets:n.aTargets;h.isArray(o)||(o=[o]);f=0;for(g=o.length;f<g;f++)if("number"===typeof o[f]&&0<=o[f]){for(;m.length<=o[f];)Aa(a);d(o[f],n)}else if("number"===typeof o[f]&&0>o[f])d(m.length+ o[f],n);else if("string"===typeof o[f]){j=0;for(i=m.length;j<i;j++)("_all"==o[f]||h(m[j].nTh).hasClass(o[f]))&&d(j,n)}}if(c){e=0;for(a=c.length;e<a;e++)d(e,c[e])}}function I(a,b,c,d){var e=a.aoData.length,f=h.extend(!0,{},p.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ea(a,e,f,A(a,e,f)),b[f].sType=null;a.aiDisplayMaster.push(e);(c||!a.oFeatures.bDeferRender)&&Fa(a,e,c,d);return e}function ha(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b, e){c=ia(a,e);return I(a,c.data,e,c.cells)})}function A(a,b,c,d){var e=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,c=f.fnGetData(g,d,{settings:a,row:b,col:c});if(c===l)return a.iDrawError!=e&&null===j&&(P(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=e),j;if((c===g||null===c)&&null!==j)c=j;else if("function"===typeof c)return c.call(g);return null===c&&"display"==d?"":c}function Ea(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData, d,{settings:a,row:b,col:c})}function Ga(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function U(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=U(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==l?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g, j;if(""!==f){j=Ga(f);for(var i=0,h=j.length;i<h;i++){f=j[i].match($);g=j[i].match(Q);if(f){j[i]=j[i].replace($,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");i=0;for(h=a.length;i<h;i++)g.push(c(a[i],b,j));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(Q,"");a=a[j[i]]();continue}if(null===a||a[j[i]]===l)return l;a=a[j[i]]}}return a};return function(b,e){return c(b,e,a)}}return function(b){return b[a]}}function Ba(a){if(h.isPlainObject(a))return Ba(a._); if(null===a)return function(){};if("function"===typeof a)return function(b,d,e){a(b,"set",d,e)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,d,e){var e=Ga(e),f;f=e[e.length-1];for(var g,j,i=0,h=e.length-1;i<h;i++){g=e[i].match($);j=e[i].match(Q);if(g){e[i]=e[i].replace($,"");a[e[i]]=[];f=e.slice();f.splice(0,i+1);g=f.join(".");j=0;for(h=d.length;j<h;j++)f={},b(f,d[j],g),a[e[i]].push(f);return}j&&(e[i]=e[i].replace(Q,""),a=a[e[i]](d));if(null=== a[e[i]]||a[e[i]]===l)a[e[i]]={};a=a[e[i]]}if(f.match(Q))a[f.replace(Q,"")](d);else a[f.replace($,"")]=d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Ha(a){return C(a.aoData,"_aData")}function ja(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function ka(a,b,c){for(var d=-1,e=0,f=a.length;e<f;e++)a[e]==b?d=e:a[e]>b&&a[e]--; -1!=d&&c===l&&a.splice(d,1)}function la(a,b,c,d){var e=a.aoData[b],f;if("dom"===c||(!c||"auto"===c)&&"dom"===e.src)e._aData= ia(a,e).data;else{var g=e.anCells,j;if(g){c=0;for(f=g.length;c<f;c++){for(j=g[c];j.childNodes.length;)j.removeChild(j.firstChild);g[c].innerHTML=A(a,b,c,"display")}}}e._aSortData=null;e._aFilterData=null;a=a.aoColumns;if(d!==l)a[d].sType=null;else{c=0;for(f=a.length;c<f;c++)a[c].sType=null}Ia(e)}function ia(a,b){var c=[],d=[],e=b.firstChild,f,g,j,i=0,n,m=a.aoColumns,o=function(a,b,c){"string"===typeof a&&(b=a.indexOf("@"),-1!==b&&(a=a.substring(b+1),j["@"+a]=c.getAttribute(a)))},k=function(a){g=m[i]; n=h.trim(a.innerHTML);g&&g._bAttrSrc?(j={display:n},o(g.mData.sort,j,a),o(g.mData.type,j,a),o(g.mData.filter,j,a),c.push(j)):c.push(n);i++};if(e)for(;e;){f=e.nodeName.toUpperCase();if("TD"==f||"TH"==f)k(e),d.push(e);e=e.nextSibling}else{d=b.anCells;e=0;for(f=d.length;e<f;e++)k(d[e])}return{data:c,cells:d}}function Fa(a,b,c,d){var e=a.aoData[b],f=e._aData,g=[],j,i,h,m,o;if(null===e.nTr){j=c||O.createElement("tr");e.nTr=j;e.anCells=g;j._DT_RowIndex=b;Ia(e);m=0;for(o=a.aoColumns.length;m<o;m++){h=a.aoColumns[m]; i=c?d[m]:O.createElement(h.sCellType);g.push(i);if(!c||h.mRender||h.mData!==m)i.innerHTML=A(a,b,m,"display");h.sClass&&(i.className+=" "+h.sClass);h.bVisible&&!c?j.appendChild(i):!h.bVisible&&c&&i.parentNode.removeChild(i);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,i,A(a,b,m),f,b,m)}u(a,"aoRowCreatedCallback",null,[j,f,b])}e.nTr.setAttribute("role","row")}function Ia(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var d=c.DT_RowClass.split(" ");a.__rowc=a.__rowc? Ja(a.__rowc.concat(d)):d;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowData&&h(b).data(c.DT_RowData)}}function ib(a){var b,c,d,e,f,g=a.nTHead,j=a.nTFoot,i=0===h("th, td",g).length,n=a.oClasses,m=a.aoColumns;i&&(e=h("<tr/>").appendTo(g));b=0;for(c=m.length;b<c;b++)f=m[b],d=h(f.nTh).addClass(f.sClass),i&&d.appendTo(e),a.oFeatures.bSort&&(d.addClass(f.sSortingClass),!1!==f.bSortable&&(d.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Ka(a,f.nTh,b))),f.sTitle!=d.html()&& d.html(f.sTitle),La(a,"header")(a,d,f,n);i&&aa(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(n.sHeaderTH);h(j).find(">tr>th, >tr>td").addClass(n.sFooterTH);if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=m[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ba(a,b,c){var d,e,f,g=[],j=[],i=a.aoColumns.length,n;if(b){c===l&&(c=!1);d=0;for(e=b.length;d<e;d++){g[d]=b[d].slice();g[d].nTr=b[d].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&& !c&&g[d].splice(f,1);j.push([])}d=0;for(e=g.length;d<e;d++){if(a=g[d].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[d].length;f<b;f++)if(n=i=1,j[d][f]===l){a.appendChild(g[d][f].cell);for(j[d][f]=1;g[d+i]!==l&&g[d][f].cell==g[d+i][f].cell;)j[d+i][f]=1,i++;for(;g[d][f+n]!==l&&g[d][f].cell==g[d][f+n].cell;){for(c=0;c<i;c++)j[d+c][f+n]=1;n++}h(g[d][f].cell).attr("rowspan",i).attr("colspan",n)}}}}function K(a){var b=u(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))B(a,!1);else{var b= [],c=0,d=a.asStripeClasses,e=d.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==z(a),i=a.aiDisplay;a.bDrawing=!0;g!==l&&-1!==g&&(a._iDisplayStart=j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,n=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,B(a,!1);else if(j){if(!a.bDestroying&&!jb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:n;for(j=j?0:g;j<f;j++){var m=i[j],o=a.aoData[m];null===o.nTr&&Fa(a,m);m=o.nTr;if(0!==e){var k=d[c%e];o._sRowStripe!= k&&(h(m).removeClass(o._sRowStripe).addClass(k),o._sRowStripe=k)}u(a,"aoRowCallback",null,[m,o._aData,c,j]);b.push(m);c++}}else c=f.sZeroRecords,1==a.iDraw&&"ajax"==z(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":e?d[0]:""}).append(h("<td />",{valign:"top",colSpan:Z(a),"class":a.oClasses.sRowEmpty}).html(c))[0];u(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],Ha(a),g,n,i]);u(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0], Ha(a),g,n,i]);d=h(a.nTBody);d.children().detach();d.append(h(b));u(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=!1}}function L(a,b){var c=a.oFeatures,d=c.bFilter;c.bSort&&kb(a);d?ca(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;K(a);a._drawHold=!1}function lb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),d=a.oFeatures,e=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)}); a.nHolding=c[0];a.nTableWrapper=e[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,n,m,o,k=0;k<f.length;k++){g=null;j=f[k];if("<"==j){i=h("<div/>")[0];n=f[k+1];if("'"==n||'"'==n){m="";for(o=2;f[k+o]!=n;)m+=f[k+o],o++;"H"==m?m=b.sJUIHeader:"F"==m&&(m=b.sJUIFooter);-1!=m.indexOf(".")?(n=m.split("."),i.id=n[0].substr(1,n[0].length-1),i.className=n[1]):"#"==m.charAt(0)?i.id=m.substr(1,m.length-1):i.className=m;k+=o}e.append(i);e=h(i)}else if(">"==j)e=e.parent();else if("l"== j&&d.bPaginate&&d.bLengthChange)g=mb(a);else if("f"==j&&d.bFilter)g=nb(a);else if("r"==j&&d.bProcessing)g=ob(a);else if("t"==j)g=pb(a);else if("i"==j&&d.bInfo)g=qb(a);else if("p"==j&&d.bPaginate)g=rb(a);else if(0!==p.ext.feature.length){i=p.ext.feature;o=0;for(n=i.length;o<n;o++)if(j==i[o].cFeature){g=i[o].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),e.append(g))}c.replaceWith(e)}function aa(a,b){var c=h(b).children("tr"),d,e,f,g,j,i,n,m,o,k;a.splice(0,a.length);f=0;for(i=c.length;f< i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){d=c[f];for(e=d.firstChild;e;){if("TD"==e.nodeName.toUpperCase()||"TH"==e.nodeName.toUpperCase()){m=1*e.getAttribute("colspan");o=1*e.getAttribute("rowspan");m=!m||0===m||1===m?1:m;o=!o||0===o||1===o?1:o;g=0;for(j=a[f];j[g];)g++;n=g;k=1===m?!0:!1;for(j=0;j<m;j++)for(g=0;g<o;g++)a[f+g][n+j]={cell:e,unique:k},a[f+g].nTr=d}e=e.nextSibling}}}function ma(a,b,c){var d=[];c||(c=a.aoHeader,b&&(c=[],aa(c,b)));for(var b=0,e=c.length;b<e;b++)for(var f=0,g=c[b].length;f< g;f++)if(c[b][f].unique&&(!d[f]||!a.bSortCellsTop))d[f]=c[b][f].cell;return d}function na(a,b,c){u(a,"aoServerParams","serverParams",[b]);if(b&&h.isArray(b)){var d={},e=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(e);c?(c=c[0],d[c]||(d[c]=[]),d[c].push(b.value)):d[b.name]=b.value});b=d}var f,g=a.ajax,j=a.oInstance;if(h.isPlainObject(g)&&g.data){f=g.data;var i=h.isFunction(f)?f(b):f,b=h.isFunction(f)&&i?i:h.extend(!0,b,i);delete g.data}i={data:b,success:function(b){var d=b.error||b.sError; d&&a.oApi._fnLog(a,0,d);a.json=b;u(a,null,"xhr",[a,b]);c(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,c){var d=a.oApi._fnLog;"parsererror"==c?d(a,0,"Invalid JSON response",1):4===b.readyState&&d(a,0,"Ajax error",7);B(a,!1)}};a.oAjaxData=b;u(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),c,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(i,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j, b,c,a):(a.jqXHR=h.ajax(h.extend(i,g)),g.data=f)}function jb(a){return a.bAjaxDataGet?(a.iDraw++,B(a,!0),na(a,sb(a),function(b){tb(a,b)}),!1):!0}function sb(a){var b=a.aoColumns,c=b.length,d=a.oFeatures,e=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,n,m,o=R(a);g=a._iDisplayStart;i=!1!==d.bPaginate?a._iDisplayLength:-1;var k=function(a,b){j.push({name:a,value:b})};k("sEcho",a.iDraw);k("iColumns",c);k("sColumns",C(b,"sName").join(","));k("iDisplayStart",g);k("iDisplayLength",i);var l={draw:a.iDraw, columns:[],order:[],start:g,length:i,search:{value:e.sSearch,regex:e.bRegex}};for(g=0;g<c;g++)n=b[g],m=f[g],i="function"==typeof n.mData?"function":n.mData,l.columns.push({data:i,name:n.sName,searchable:n.bSearchable,orderable:n.bSortable,search:{value:m.sSearch,regex:m.bRegex}}),k("mDataProp_"+g,i),d.bFilter&&(k("sSearch_"+g,m.sSearch),k("bRegex_"+g,m.bRegex),k("bSearchable_"+g,n.bSearchable)),d.bSort&&k("bSortable_"+g,n.bSortable);d.bFilter&&(k("sSearch",e.sSearch),k("bRegex",e.bRegex));d.bSort&& (h.each(o,function(a,b){l.order.push({column:b.col,dir:b.dir});k("iSortCol_"+a,b.col);k("sSortDir_"+a,b.dir)}),k("iSortingCols",o.length));b=p.ext.legacy.ajax;return null===b?a.sAjaxSource?j:l:b?j:l}function tb(a,b){var c=b.sEcho!==l?b.sEcho:b.draw,d=b.iTotalRecords!==l?b.iTotalRecords:b.recordsTotal,e=b.iTotalDisplayRecords!==l?b.iTotalDisplayRecords:b.recordsFiltered;if(c){if(1*c<a.iDraw)return;a.iDraw=1*c}ja(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(e,10);c=oa(a,b);d=0;for(e= c.length;d<e;d++)I(a,c[d]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;K(a);a._bInitComplete||pa(a,b);a.bAjaxDataGet=!0;B(a,!1)}function oa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==l?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?U(c)(b):b}function nb(a){var b=a.oClasses,c=a.sTableId,d=a.oLanguage,e=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=d.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>", {id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)),f=function(){var b=!this.value?"":this.value;b!=e.sSearch&&(ca(a,{sSearch:b,bRegex:e.bRegex,bSmart:e.bSmart,bCaseInsensitive:e.bCaseInsensitive}),a._iDisplayStart=0,K(a))},i=h("input",b).val(e.sSearch).attr("placeholder",d.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===z(a)?Ma(f,400):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT", function(b,c){if(a===c)try{i[0]!==O.activeElement&&i.val(e.sSearch)}catch(d){}});return b[0]}function ca(a,b,c){var d=a.oPreviousSearch,e=a.aoPreSearchCols,f=function(a){d.sSearch=a.sSearch;d.bRegex=a.bRegex;d.bSmart=a.bSmart;d.bCaseInsensitive=a.bCaseInsensitive};Da(a);if("ssp"!=z(a)){ub(a,b.sSearch,c,b.bEscapeRegex!==l?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<e.length;b++)vb(a,e[b].sSearch,b,e[b].bEscapeRegex!==l?!e[b].bEscapeRegex:e[b].bRegex,e[b].bSmart,e[b].bCaseInsensitive); wb(a)}else f(b);a.bFiltered=!0;u(a,null,"search",[a])}function wb(a){for(var b=p.ext.search,c=a.aiDisplay,d,e,f=0,g=b.length;f<g;f++){for(var j=[],i=0,h=c.length;i<h;i++)e=c[i],d=a.aoData[e],b[f](a,d._aFilterData,e,d._aData,i)&&j.push(e);c.length=0;c.push.apply(c,j)}}function vb(a,b,c,d,e,f){if(""!==b)for(var g=a.aiDisplay,d=Na(b,d,e,f),e=g.length-1;0<=e;e--)b=a.aoData[g[e]]._aFilterData[c],d.test(b)||g.splice(e,1)}function ub(a,b,c,d,e,f){var d=Na(b,d,e,f),e=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster, g;0!==p.ext.search.length&&(c=!0);g=xb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||e.length>b.length||0!==b.indexOf(e)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)d.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Na(a,b,c,d){a=b?a:Oa(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||"",function(a){return'"'===a.charAt(0)?a.match(/^"(.*)"$/)[1]:a}).join(")(?=.*?")+").*$");return RegExp(a,d?"i":"")}function Oa(a){return a.replace(Vb,"\\$1")}function xb(a){var b= a.aoColumns,c,d,e,f,g,j,i,h,m=p.ext.type.search;c=!1;d=0;for(f=a.aoData.length;d<f;d++)if(h=a.aoData[d],!h._aFilterData){j=[];e=0;for(g=b.length;e<g;e++)c=b[e],c.bSearchable?(i=A(a,d,e,"filter"),m[c.sType]&&(i=m[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(qa.innerHTML=i,i=Wb?qa.textContent:qa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join(" ");c=!0}return c}function yb(a){return{search:a.sSearch, smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function zb(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function qb(a){var b=a.sTableId,c=a.aanFeatures.i,d=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Ab,sName:"information"}),d.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return d[0]}function Ab(a){var b=a.aanFeatures.i;if(0!==b.length){var c= a.oLanguage,d=a._iDisplayStart+1,e=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Bb(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,d,e,f,g,j));h(b).html(j)}}function Bb(a,b){var c=a.fnFormatNumber,d=a._iDisplayStart+1,e=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===e;return b.replace(/_START_/g,c.call(a,d)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g, c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(d/e))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/e)))}function ra(a){var b,c,d=a.iInitDisplayStart,e=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){lb(a);ib(a);ba(a,a.aoHeader);ba(a,a.aoFooter);B(a,!0);c.bAutoWidth&&Ca(a);b=0;for(c=e.length;b<c;b++)f=e[b],f.sWidth&&(f.nTh.style.width=s(f.sWidth));L(a);e=z(a);"ssp"!=e&&("ajax"==e?na(a,[],function(c){var f=oa(a,c);for(b=0;b<f.length;b++)I(a,f[b]);a.iInitDisplayStart=d;L(a);B(a,!1);pa(a,c)},a): (B(a,!1),pa(a)))}else setTimeout(function(){ra(a)},200)}function pa(a,b){a._bInitComplete=!0;b&&V(a);u(a,"aoInitComplete","init",[a,b])}function Pa(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Qa(a);u(a,null,"length",[a,c])}function mb(a){for(var b=a.oClasses,c=a.sTableId,d=a.aLengthMenu,e=h.isArray(d[0]),f=e?d[0]:d,d=e?d[1]:d,e=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,j=f.length;g<j;g++)e[0][g]=new Option(d[g],f[g]);var i=h("<div><label/></div>").addClass(b.sLength); a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",e[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Pa(a,h(this).val());K(a)});h(a.nTable).bind("length.dt.DT",function(b,c,d){a===c&&h("select",i).val(d)});return i[0]}function rb(a){var b=a.sPaginationType,c=p.ext.pager[b],d="function"===typeof c,e=function(a){K(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],f=a.aanFeatures;d||c.fnInit(a,b,e);f.p||(b.id=a.sTableId+ "_paginate",a.aoDrawCallback.push({fn:function(a){if(d){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),m=-1===i,b=m?0:Math.ceil(b/i),i=m?1:Math.ceil(h/i),h=c(b,i),o,m=0;for(o=f.p.length;m<o;m++)La(a,"pageButton")(a,f.p[m],m,h,b,i)}else c.fnUpdate(a,e)},sName:"pagination"}));return b}function Ra(a,b,c){var d=a._iDisplayStart,e=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===e?d=0:"number"===typeof b?(d=b*e,d>f&&(d=0)):"first"==b?d=0:"previous"==b?(d=0<=e?d-e:0,0>d&&(d=0)):"next"== b?d+e<f&&(d+=e):"last"==b?d=Math.floor((f-1)/e)*e:P(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==d;a._iDisplayStart=d;b&&(u(a,null,"page",[a]),c&&K(a));return b}function ob(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function B(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");u(a,null,"processing",[a,b])}function pb(a){var b=h(a.nTable);b.attr("role", "grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var d=c.sX,e=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),n=h(b[0].cloneNode(!1)),m=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");m.length||(m=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:d?!d?null:s(d):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box", width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append(b.children("thead")))).append("top"===j?g:null)).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!e?null:s(e),width:!d?null:s(d)}).append(b));m&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:d?!d?null:s(d):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(n.removeAttr("id").css("margin-left",0).append(b.children("tfoot")))).append("bottom"===j?g: null));var b=c.children(),o=b[0],f=b[1],k=m?b[2]:null;d&&h(f).scroll(function(){var a=this.scrollLeft;o.scrollLeft=a;m&&(k.scrollLeft=a)});a.nScrollHead=o;a.nScrollBody=f;a.nScrollFoot=k;a.aoDrawCallback.push({fn:W,sName:"scrolling"});return c[0]}function W(a){var b=a.oScroll,c=b.sX,d=b.sXInner,e=b.sY,f=b.iBarWidth,g=h(a.nScrollHead),j=g[0].style,i=g.children("div"),n=i[0].style,m=i.children("table"),i=a.nScrollBody,o=h(i),k=i.style,l=h(a.nScrollFoot).children("div"),p=l.children("table"),r=h(a.nTHead), q=h(a.nTable),da=q[0],M=da.style,J=a.nTFoot?h(a.nTFoot):null,u=a.oBrowser,v=u.bScrollOversize,y,t,x,w,z,A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};q.children("thead, tfoot").remove();z=r.clone().prependTo(q);y=r.find("tr");x=z.find("tr");z.find("th, td").removeAttr("tabindex");J&&(w=J.clone().prependTo(q),t=J.find("tr"),w=w.find("tr"));c||(k.width="100%",g[0].style.width="100%");h.each(ma(a,z),function(b,c){D= ga(a,b);c.style.width=a.aoColumns[D].sWidth});J&&F(function(a){a.style.width=""},w);b.bCollapse&&""!==e&&(k.height=o[0].offsetHeight+r[0].offsetHeight+"px");g=q.outerWidth();if(""===c){if(M.width="100%",v&&(q.find("tbody").height()>i.offsetHeight||"scroll"==o.css("overflow-y")))M.width=s(q.outerWidth()-f)}else""!==d?M.width=s(d):g==o.width()&&o.height()<q.height()?(M.width=s(g-f),q.outerWidth()>g-f&&(M.width=s(g))):M.width=s(g);g=q.outerWidth();F(E,x);F(function(a){C.push(a.innerHTML);A.push(s(h(a).css("width")))}, x);F(function(a,b){a.style.width=A[b]},y);h(x).height(0);J&&(F(E,w),F(function(a){B.push(s(h(a).css("width")))},w),F(function(a,b){a.style.width=B[b]},t),h(w).height(0));F(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+C[b]+"</div>";a.style.width=A[b]},x);J&&F(function(a,b){a.innerHTML="";a.style.width=B[b]},w);if(q.outerWidth()<g){t=i.scrollHeight>i.offsetHeight||"scroll"==o.css("overflow-y")?g+f:g;if(v&&(i.scrollHeight>i.offsetHeight||"scroll"==o.css("overflow-y")))M.width= s(t-f);(""===c||""!==d)&&P(a,1,"Possible column misalignment",6)}else t="100%";k.width=s(t);j.width=s(t);J&&(a.nScrollFoot.style.width=s(t));!e&&v&&(k.height=s(da.offsetHeight+f));e&&b.bCollapse&&(k.height=s(e),b=c&&da.offsetWidth>i.offsetWidth?f:0,da.offsetHeight<i.offsetHeight&&(k.height=s(da.offsetHeight+b)));b=q.outerWidth();m[0].style.width=s(b);n.width=s(b);m=q.height()>i.clientHeight||"scroll"==o.css("overflow-y");u="padding"+(u.bScrollbarLeft?"Left":"Right");n[u]=m?f+"px":"0px";J&&(p[0].style.width= s(b),l[0].style.width=s(b),l[0].style[u]=m?f+"px":"0px");o.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)i.scrollTop=0}function F(a,b,c){for(var d=0,e=0,f=b.length,g,j;e<f;){g=b[e].firstChild;for(j=c?c[e].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,d):a(g,d),d++),g=g.nextSibling,j=c?j.nextSibling:null;e++}}function Ca(a){var b=a.nTable,c=a.aoColumns,d=a.oScroll,e=d.sY,f=d.sX,g=d.sXInner,j=c.length,d=X(a,"bVisible"),i=h("th",a.nTHead),n=b.getAttribute("width"),m=b.parentNode,o=!1,k,l;for(k=0;k< d.length;k++)l=c[d[k]],null!==l.sWidth&&(l.sWidth=Cb(l.sWidthOrig,m),o=!0);if(!o&&!f&&!e&&j==Z(a)&&j==i.length)for(k=0;k<j;k++)c[k].sWidth=s(i.eq(k).width());else{j=h(b).clone().empty().css("visibility","hidden").removeAttr("id").append(h(a.nTHead).clone(!1)).append(h(a.nTFoot).clone(!1)).append(h("<tbody><tr/></tbody>"));j.find("tfoot th, tfoot td").css("width","");var p=j.find("tbody tr"),i=ma(a,j.find("thead")[0]);for(k=0;k<d.length;k++)l=c[d[k]],i[k].style.width=null!==l.sWidthOrig&&""!==l.sWidthOrig? s(l.sWidthOrig):"";if(a.aoData.length)for(k=0;k<d.length;k++)o=d[k],l=c[o],h(Db(a,o)).clone(!1).append(l.sContentPadding).appendTo(p);j.appendTo(m);f&&g?j.width(g):f?(j.css("width","auto"),j.width()<m.offsetWidth&&j.width(m.offsetWidth)):e?j.width(m.offsetWidth):n&&j.width(n);Eb(a,j[0]);if(f){for(k=g=0;k<d.length;k++)l=c[d[k]],e=h(i[k]).outerWidth(),g+=null===l.sWidthOrig?e:parseInt(l.sWidth,10)+e-h(i[k]).width();j.width(s(g));b.style.width=s(g)}for(k=0;k<d.length;k++)if(l=c[d[k]],e=h(i[k]).width())l.sWidth= s(e);b.style.width=s(j.css("width"));j.remove()}n&&(b.style.width=s(n));if((n||f)&&!a._reszEvt)h(za).bind("resize.DT-"+a.sInstance,Ma(function(){V(a)})),a._reszEvt=!0}function Ma(a,b){var c=b||200,d,e;return function(){var b=this,g=+new Date,j=arguments;d&&g<d+c?(clearTimeout(e),e=setTimeout(function(){d=l;a.apply(b,j)},c)):d?(d=g,a.apply(b,j)):d=g}}function Cb(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||O.body),d=c[0].offsetWidth;c.remove();return d}function Eb(a,b){var c= a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Db(a,b){var c=Fb(a,b);if(0>c)return null;var d=a.aoData[c];return!d.nTr?h("<td/>").html(A(a,c,b,"display"))[0]:d.anCells[b]}function Fb(a,b){for(var c,d=-1,e=-1,f=0,g=a.aoData.length;f<g;f++)c=A(a,f,b,"display")+"",c=c.replace(Xb,""),c.length>d&&(d=c.length,e=f);return e}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Gb(){if(!p.__scrollbarWidth){var a= h("<p/>").css({width:"100%",height:200,padding:0})[0],b=h("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(a).appendTo("body"),c=a.offsetWidth;b.css("overflow","scroll");a=a.offsetWidth;c===a&&(a=b[0].clientWidth);b.remove();p.__scrollbarWidth=c-a}return p.__scrollbarWidth}function R(a){var b,c,d=[],e=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var n=[];f=function(a){a.length&&!h.isArray(a[0])?n.push(a):n.push.apply(n, a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<n.length;a++){i=n[a][0];f=e[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=e[g].sType||"string",d.push({src:i,col:g,dir:n[a][1],index:n[a][2],type:j,formatter:p.ext.type.order[j+"-pre"]})}return d}function kb(a){var b,c,d=[],e=p.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h;Da(a);h=R(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Hb(a,j.col);if("ssp"!=z(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)d[i[b]]= b;g===h.length?i.sort(function(a,b){var c,e,g,j,i=h.length,l=f[a]._aSortData,p=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=l[j.col],e=p[j.col],c=c<e?-1:c>e?1:0,0!==c)return"asc"===j.dir?c:-c;c=d[a];e=d[b];return c<e?-1:c>e?1:0}):i.sort(function(a,b){var c,g,j,i,l=h.length,p=f[a]._aSortData,r=f[b]._aSortData;for(j=0;j<l;j++)if(i=h[j],c=p[i.col],g=r[i.col],i=e[i.type+"-"+i.dir]||e["string-"+i.dir],c=i(c,g),0!==c)return c;c=d[a];g=d[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Ib(a){for(var b,c, d=a.aoColumns,e=R(a),a=a.oLanguage.oAria,f=0,g=d.length;f<g;f++){c=d[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<e.length&&e[0].col==f?(i.setAttribute("aria-sort","asc"==e[0].dir?"ascending":"descending"),c=j[e[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label",b)}}function Sa(a,b,c,d){var e=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a){var b=a._idx;b===l&&(b=h.inArray(a[1], f));return b+1>=f.length?0:b+1};"number"===typeof e[0]&&(e=a.aaSorting=[e]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,C(e,"0")),-1!==c?(b=g(e[c]),e[c][1]=f[b],e[c]._idx=b):(e.push([b,f[0],0]),e[e.length-1]._idx=0)):e.length&&e[0][0]==b?(b=g(e[0]),e.length=1,e[0][1]=f[b],e[0]._idx=b):(e.length=0,e.push([b,f[0]]),e[0]._idx=0);L(a);"function"==typeof d&&d(a)}function Ka(a,b,c,d){var e=a.aoColumns[c];Ta(b,{},function(b){!1!==e.bSortable&&(a.oFeatures.bProcessing?(B(a,!0),setTimeout(function(){Sa(a,c,b.shiftKey, d);"ssp"!==z(a)&&B(a,!1)},0)):Sa(a,c,b.shiftKey,d))})}function sa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,d=R(a),e=a.oFeatures,f,g;if(e.bSort&&e.bSortClasses){e=0;for(f=b.length;e<f;e++)g=b[e].src,h(C(a.aoData,"anCells",g)).removeClass(c+(2>e?e+1:3));e=0;for(f=d.length;e<f;e++)g=d[e].src,h(C(a.aoData,"anCells",g)).addClass(c+(2>e?e+1:3))}a.aLastSort=d}function Hb(a,b){var c=a.aoColumns[b],d=p.ext.order[c.sSortDataType],e;d&&(e=d.call(a.oInstance,a,b,Y(a,b)));for(var f,g=p.ext.type.order[c.sType+ "-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||d)f=d?e[j]:A(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ta(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),search:yb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,d){return{visible:b.bVisible,search:yb(a.aoPreSearchCols[d])}})};u(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState= b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Jb(a){var b,c,d=a.aoColumns;if(a.oFeatures.bStateSave){var e=a.fnStateLoadCallback.call(a.oInstance,a);if(e&&e.time&&(b=u(a,"aoStateLoadParams","stateLoadParams",[a,e]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&e.time<+new Date-1E3*b)&&d.length===e.columns.length))){a.oLoadedState=h.extend(!0,{},e);a._iDisplayStart=e.start;a.iInitDisplayStart=e.start;a._iDisplayLength=e.length;a.aaSorting=[];h.each(e.order,function(b,c){a.aaSorting.push(c[0]>= d.length?[0,c[1]]:c)});h.extend(a.oPreviousSearch,zb(e.search));b=0;for(c=e.columns.length;b<c;b++){var f=e.columns[b];d[b].bVisible=f.visible;h.extend(a.aoPreSearchCols[b],zb(f.search))}u(a,"aoStateLoaded","stateLoaded",[a,e])}}}function ua(a){var b=p.settings,a=h.inArray(a,C(b,"nTable"));return-1!==a?b[a]:null}function P(a,b,c,d){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;d&&(c+=". For more information about this error, please see http://datatables.net/tn/"+d);if(b)za.console&& console.log&&console.log(c);else if(a=p.ext,"alert"==(a.sErrMode||a.errMode))alert(c);else throw Error(c);}function D(a,b,c,d){h.isArray(c)?h.each(c,function(c,d){h.isArray(d)?D(a,b,d[0],d[1]):D(a,b,d)}):(d===l&&(d=c),b[c]!==l&&(a[d]=b[c]))}function Kb(a,b,c){var d,e;for(e in b)b.hasOwnProperty(e)&&(d=b[e],h.isPlainObject(d)?(h.isPlainObject(a[e])||(a[e]={}),h.extend(!0,a[e],d)):a[e]=c&&"data"!==e&&"aaData"!==e&&h.isArray(d)?d.slice():d);return a}function Ta(a,b,c){h(a).bind("click.DT",b,function(b){a.blur(); c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function x(a,b,c,d){c&&a[b].push({fn:c,sName:d})}function u(a,b,c,d){var e=[];b&&(e=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,d)}));null!==c&&h(a.nTable).trigger(c+".dt",d);return e}function Qa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),d=a._iDisplayLength;c===a.fnRecordsDisplay()&&(b=c-d);if(-1===d||0>b)b=0;a._iDisplayStart=b}function La(a,b){var c= a.renderer,d=p.ext.renderer[b];return h.isPlainObject(c)&&c[b]?d[c[b]]||d._:"string"===typeof c?d[c]||d._:d._}function z(a){return a.oFeatures.bServerSide?"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Ua(a,b){var c=[],c=Lb.numbers_length,d=Math.floor(c/2);b<=c?c=S(0,b):a<=d?(c=S(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-d?c=S(b-(c-2),b):(c=S(a-1,a+2),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function cb(a){h.each({num:function(b){return va(b, a)},"num-fmt":function(b){return va(b,a,Va)},"html-num":function(b){return va(b,a,wa)},"html-num-fmt":function(b){return va(b,a,wa,Va)}},function(b,c){t.type.order[b+a+"-pre"]=c})}function Mb(a){return function(){var b=[ua(this[p.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return p.ext.internal[a].apply(this,b)}}var p,t,q,r,v,Wa={},Nb=/[\r\n]/g,wa=/<.*?>/g,Yb=/^[\w\+\-]/,Zb=/[\w\+\-]$/,Vb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Va=/[',$\u00a3\u20ac\u00a5%\u2009\u202F]/g, H=function(a){return!a||!0===a||"-"===a?!0:!1},Ob=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Pb=function(a,b){Wa[b]||(Wa[b]=RegExp(Oa(b),"g"));return"string"===typeof a?a.replace(/\./g,"").replace(Wa[b],"."):a},Xa=function(a,b,c){var d="string"===typeof a;b&&d&&(a=Pb(a,b));c&&d&&(a=a.replace(Va,""));return H(a)||!isNaN(parseFloat(a))&&isFinite(a)},Qb=function(a,b,c){return H(a)?!0:!(H(a)||"string"===typeof a)?null:Xa(a.replace(wa,""),b,c)?!0:null},C=function(a,b,c){var d= [],e=0,f=a.length;if(c!==l)for(;e<f;e++)a[e]&&a[e][b]&&d.push(a[e][b][c]);else for(;e<f;e++)a[e]&&d.push(a[e][b]);return d},xa=function(a,b,c,d){var e=[],f=0,g=b.length;if(d!==l)for(;f<g;f++)e.push(a[b[f]][c][d]);else for(;f<g;f++)e.push(a[b[f]][c]);return e},S=function(a,b){var c=[],d;b===l?(b=0,d=a):(d=b,b=a);for(var e=b;e<d;e++)c.push(e);return c},Ja=function(a){var b=[],c,d,e=a.length,f,g=0;d=0;a:for(;d<e;d++){c=a[d];for(f=0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},w=function(a, b,c){a[b]!==l&&(a[c]=a[b])},$=/\[.*?\]$/,Q=/\(\)$/,qa=h("<div>")[0],Wb=qa.textContent!==l,Xb=/<.*?>/g;p=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new q(ua(this[t.iApiIndex])):new q(this)};this.fnAddData=function(a,b){var c=this.api(!0),d=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===l||b)&&c.draw();return d.flatten().toArray()};this.fnAdjustColumnSizing= function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],d=c.oScroll;a===l||a?b.draw(!1):(""!==d.sX||""!==d.sY)&&W(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===l||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var d=this.api(!0),a=d.rows(a),e=a.settings()[0],h=e.aoData[a[0][0]];a.remove();b&&b.call(this,e,h);(c===l||c)&&d.draw();return h};this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(!a)}; this.fnFilter=function(a,b,c,d,e,h){e=this.api(!0);null===b||b===l?e.search(a,c,d,h):e.column(b).search(a,c,d,h);e.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==l){var d=a.nodeName?a.nodeName.toLowerCase():"";return b!==l||"td"==d||"th"==d?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==l?b.row(a).node():b.rows().nodes().flatten().toArray()};this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase(); return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===l||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===l||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return ua(this[t.iApiIndex])}; this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,d,e){var h=this.api(!0);c===l||null===c?h.row(b).data(a):h.cell(b,c).data(a);(e===l||e)&&h.columns.adjust();(d===l||d)&&h.draw();return 0};this.fnVersionCheck=t.fnVersionCheck;var b=this,c=a===l,d=this.length;c&&(a={});this.oApi=this.internal=t.internal;for(var e in p.ext.internal)e&&(this[e]=Mb(e));this.each(function(){var e={},g=1<d?Kb(e,a,!0): a,j=0,i,n=this.getAttribute("id"),e=!1,m=p.defaults;if("table"!=this.nodeName.toLowerCase())P(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{db(m);eb(m.column);G(m,m,!0);G(m.column,m.column,!0);G(m,g);var o=p.settings,j=0;for(i=o.length;j<i;j++){if(o[j].nTable==this){i=g.bRetrieve!==l?g.bRetrieve:m.bRetrieve;if(c||i)return o[j].oInstance;if(g.bDestroy!==l?g.bDestroy:m.bDestroy){o[j].oInstance.fnDestroy();break}else{P(o[j],0,"Cannot reinitialise DataTable",3);return}}if(o[j].sTableId== this.id){o.splice(j,1);break}}if(null===n||""===n)this.id=n="DataTables_Table_"+p.ext._unique++;var k=h.extend(!0,{},p.models.oSettings,{nTable:this,oApi:b.internal,oInit:g,sDestroyWidth:h(this)[0].style.width,sInstance:n,sTableId:n});o.push(k);k.oInstance=1===b.length?b:h(this).dataTable();db(g);g.oLanguage&&N(g.oLanguage);g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=h.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]);g=Kb(h.extend(!0,{},m),g);D(k.oFeatures,g,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" ")); D(k,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);D(k.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"], ["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);D(k.oLanguage,g,"fnInfoCallback");x(k,"aoDrawCallback",g.fnDrawCallback,"user");x(k,"aoServerParams",g.fnServerParams,"user");x(k,"aoStateSaveParams",g.fnStateSaveParams,"user");x(k,"aoStateLoadParams",g.fnStateLoadParams,"user");x(k,"aoStateLoaded",g.fnStateLoaded,"user");x(k,"aoRowCallback",g.fnRowCallback,"user");x(k,"aoRowCreatedCallback",g.fnCreatedRow,"user");x(k,"aoHeaderCallback",g.fnHeaderCallback,"user");x(k,"aoFooterCallback",g.fnFooterCallback, "user");x(k,"aoInitComplete",g.fnInitComplete,"user");x(k,"aoPreDrawCallback",g.fnPreDrawCallback,"user");n=k.oClasses;g.bJQueryUI?(h.extend(n,p.ext.oJUIClasses,g.oClasses),g.sDom===m.sDom&&"lfrtip"===m.sDom&&(k.sDom='<"H"lfr>t<"F"ip>'),k.renderer)?h.isPlainObject(k.renderer)&&!k.renderer.header&&(k.renderer.header="jqueryui"):k.renderer="jqueryui":h.extend(n,p.ext.classes,g.oClasses);h(this).addClass(n.sTable);if(""!==k.oScroll.sX||""!==k.oScroll.sY)k.oScroll.iBarWidth=Gb();!0===k.oScroll.sX&&(k.oScroll.sX= "100%");k.iInitDisplayStart===l&&(k.iInitDisplayStart=g.iDisplayStart,k._iDisplayStart=g.iDisplayStart);null!==g.iDeferLoading&&(k.bDeferLoading=!0,j=h.isArray(g.iDeferLoading),k._iRecordsDisplay=j?g.iDeferLoading[0]:g.iDeferLoading,k._iRecordsTotal=j?g.iDeferLoading[1]:g.iDeferLoading);""!==g.oLanguage.sUrl?(k.oLanguage.sUrl=g.oLanguage.sUrl,h.getJSON(k.oLanguage.sUrl,null,function(a){N(a);G(m.oLanguage,a);h.extend(true,k.oLanguage,g.oLanguage,a);ra(k)}),e=!0):h.extend(!0,k.oLanguage,g.oLanguage); null===g.asStripeClasses&&(k.asStripeClasses=[n.sStripeOdd,n.sStripeEven]);var j=k.asStripeClasses,r=h("tbody tr:eq(0)",this);-1!==h.inArray(!0,h.map(j,function(a){return r.hasClass(a)}))&&(h("tbody tr",this).removeClass(j.join(" ")),k.asDestroyStripes=j.slice());var o=[],q,j=this.getElementsByTagName("thead");0!==j.length&&(aa(k.aoHeader,j[0]),o=ma(k));if(null===g.aoColumns){q=[];j=0;for(i=o.length;j<i;j++)q.push(null)}else q=g.aoColumns;j=0;for(i=q.length;j<i;j++)Aa(k,o?o[j]:null);hb(k,g.aoColumnDefs, q,function(a,b){fa(k,a,b)});if(r.length){var s=function(a,b){return a.getAttribute("data-"+b)?b:null};h.each(ia(k,r[0]).cells,function(a,b){var c=k.aoColumns[a];if(c.mData===a){var d=s(b,"sort")||s(b,"order"),e=s(b,"filter")||s(b,"search");if(d!==null||e!==null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:l,type:d!==null?a+".@data-"+d:l,filter:e!==null?a+".@data-"+e:l};fa(k,a)}}})}var t=k.oFeatures;g.bStateSave&&(t.bStateSave=!0,Jb(k,g),x(k,"aoDrawCallback",ta,"state_save"));if(g.aaSorting=== l){o=k.aaSorting;j=0;for(i=o.length;j<i;j++)o[j][1]=k.aoColumns[j].asSorting[0]}sa(k);t.bSort&&x(k,"aoDrawCallback",function(){if(k.bSorted){var a=R(k),b={};h.each(a,function(a,c){b[c.src]=c.dir});u(k,null,"order",[k,a,b]);Ib(k)}});x(k,"aoDrawCallback",function(){(k.bSorted||z(k)==="ssp"||t.bDeferRender)&&sa(k)},"sc");fb(k);j=h(this).children("caption").each(function(){this._captionSide=h(this).css("caption-side")});i=h(this).children("thead");0===i.length&&(i=h("<thead/>").appendTo(this));k.nTHead= i[0];i=h(this).children("tbody");0===i.length&&(i=h("<tbody/>").appendTo(this));k.nTBody=i[0];i=h(this).children("tfoot");if(0===i.length&&0<j.length&&(""!==k.oScroll.sX||""!==k.oScroll.sY))i=h("<tfoot/>").appendTo(this);0===i.length||0===i.children().length?h(this).addClass(n.sNoFooter):0<i.length&&(k.nTFoot=i[0],aa(k.aoFooter,k.nTFoot));if(g.aaData)for(j=0;j<g.aaData.length;j++)I(k,g.aaData[j]);else(k.bDeferLoading||"dom"==z(k))&&ha(k,h(k.nTBody).children("tr"));k.aiDisplay=k.aiDisplayMaster.slice(); k.bInitialised=!0;!1===e&&ra(k)}});b=null;return this};var Rb=[],y=Array.prototype,$b=function(a){var b,c,d=p.settings,e=h.map(d,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,e),-1!==b?[d[b]]:null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,e);return-1!==b?d[b]:null}).toArray()}; q=function(a,b){if(!this instanceof q)throw"DT API must be constructed as a new object";var c=[],d=function(a){(a=$b(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var e=0,f=a.length;e<f;e++)d(a[e]);else d(a);this.context=Ja(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null};q.extend(this,this,Rb)};p.Api=q;q.prototype={concat:y.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b= this.context;return b.length>a?new q(b[a],this[a]):null},filter:function(a){var b=[];if(y.filter)b=y.filter.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new q(this.context,b)},flatten:function(){var a=[];return new q(this.context,a.concat.apply(a,this.toArray()))},join:y.join,indexOf:y.indexOf||function(a,b){for(var c=b||0,d=this.length;c<d;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c){var d=[],e,f,g,h,i,n=this.context, m,o,k=this.selector;"string"===typeof a&&(c=b,b=a,a=!1);f=0;for(g=n.length;f<g;f++)if("table"===b)e=c(n[f],f),e!==l&&d.push(e);else if("columns"===b||"rows"===b)e=c(n[f],this[f],f),e!==l&&d.push(e);else if("column"===b||"column-rows"===b||"row"===b||"cell"===b){o=this[f];"column-rows"===b&&(m=Ya(n[f],k.opts));h=0;for(i=o.length;h<i;h++)e=o[h],e="cell"===b?c(n[f],e.row,e.column,f,h):c(n[f],e,f,h,m),e!==l&&d.push(e)}return d.length?(a=new q(n,a?d.concat.apply([],d):d),b=a.selector,b.rows=k.rows,b.cols= k.cols,b.opts=k.opts,a):this},lastIndexOf:y.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(y.map)b=y.map.call(this,a,this);else for(var c=0,d=this.length;c<d;c++)b.push(a.call(this,this[c],c));return new q(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:y.pop,push:y.push,reduce:y.reduce||function(a,b){return gb(this,a,b,0,this.length,1)},reduceRight:y.reduceRight||function(a,b){return gb(this, a,b,this.length-1,-1,-1)},reverse:y.reverse,selector:null,shift:y.shift,sort:y.sort,splice:y.splice,toArray:function(){return y.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},unique:function(){return new q(this.context,Ja(this))},unshift:y.unshift};q.extend=function(a,b,c){if(b&&(b instanceof q||b.__dt_wrapper)){var d,e,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);q.extend(d,d,c.methodExt);return d}};d=0;for(e=c.length;d<e;d++)f=c[d],b[f.name]= "function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,q.extend(a,b[f.name],f.propExt)}};q.register=r=function(a,b){if(h.isArray(a))for(var c=0,d=a.length;c<d;c++)q.register(a[c],b);else for(var e=a.split("."),f=Rb,g,j,c=0,d=e.length;c<d;c++){g=(j=-1!==e[c].indexOf("()"))?e[c].replace("()",""):e[c];var i;a:{i=0;for(var n=f.length;i<n;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===d-1?i.val=b:f=j?i.methodExt: i.propExt}};q.registerPlural=v=function(a,b,c){q.register(a,c);q.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof q?a.length?h.isArray(a[0])?new q(a.context,a[0]):a[0]:l:a})};r("tables()",function(a){var b;if(a){b=q;var c=this.context;if("number"===typeof a)a=[c[a]];else var d=h.map(c,function(a){return a.nTable}),a=h(d).filter(a).map(function(){var a=h.inArray(this,d);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a), b=a.context;return b.length?new q(b[0]):a});v("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable})});v("tables().body()","table().body()",function(){return this.iterator("table",function(a){return a.nTBody})});v("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead})});v("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot})});v("tables().containers()", "table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper})});r("draw()",function(a){return this.iterator("table",function(b){L(b,!1===a)})});r("page()",function(a){return a===l?this.page.info().page:this.iterator("table",function(b){Ra(b,a)})});r("page.info()",function(){if(0===this.context.length)return l;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,d=a.fnRecordsDisplay(),e=-1===c;return{page:e?0:Math.floor(b/c),pages:e?1:Math.ceil(d/c),start:b, end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:d}});r("page.len()",function(a){return a===l?0!==this.context.length?this.context[0]._iDisplayLength:l:this.iterator("table",function(b){Pa(b,a)})});var Sb=function(a,b,c){"ssp"==z(a)?L(a,b):(B(a,!0),na(a,[],function(c){ja(a);for(var c=oa(a,c),d=0,g=c.length;d<g;d++)I(a,c[d]);L(a,b);B(a,!1)}));if(c){var d=new q(a);d.one("draw",function(){c(d.ajax.json())})}};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json}); r("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Sb(c,!1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===l){if(0===b.length)return l;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Sb(c, !1===b,a)})});var Za=function(a,b){var c=[],d,e,f,g,j,i;if(!a||"string"===typeof a||a.length===l)a=[a];f=0;for(g=a.length;f<g;f++){e=a[f]&&a[f].split?a[f].split(","):[a[f]];j=0;for(i=e.length;j<i;j++)(d=b("string"===typeof e[j]?h.trim(e[j]):e[j]))&&d.length&&c.push.apply(c,d)}return c},$a=function(a){a||(a={});a.filter&&!a.search&&(a.search=a.filter);return{search:a.search||"none",order:a.order||"current",page:a.page||"all"}},ab=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]= a[b],a.length=1,a.context=[a.context[b]],a;a.length=0;return a},Ya=function(a,b){var c,d,e,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;d=b.order;e=b.page;if("ssp"==z(a))return"removed"===j?[]:S(0,c.length);if("current"==e){c=a._iDisplayStart;for(d=a.fnDisplayEnd();c<d;c++)f.push(g[c])}else if("current"==d||"applied"==d)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==d||"original"==d){c=0;for(d=a.aoData.length;c<d;c++)"none"== j?f.push(c):(e=h.inArray(c,g),(-1===e&&"removed"==j||0<=e&&"applied"==j)&&f.push(c))}return f};r("rows()",function(a,b){a===l?a="":h.isPlainObject(a)&&(b=a,a="");var b=$a(b),c=this.iterator("table",function(c){var e=b;return Za(a,function(a){var b=Ob(a);if(b!==null&&!e)return[b];var j=Ya(c,e);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;for(var b=[],i=0,n=j.length;i<n;i++)b.push(c.aoData[j[i]].nTr);return a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()})}); c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||l})});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return xa(a.aoData,b,"_aData")})});v("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var d=b.aoData[c];return"search"===a?d._aFilterData:d._aSortData})});v("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",function(b, c){la(b,c,a)})});v("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b})});v("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,d){var e=b.aoData;e.splice(c,1);for(var f=0,g=e.length;f<g;f++)null!==e[f].nTr&&(e[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);ka(b.aiDisplayMaster,c);ka(b.aiDisplay,c);ka(a[d],c,!1);Qa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c,f,g,h=[];f=0; for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ha(b,c)[0]):h.push(I(b,c));return h}),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return ab(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===l)return b.length&&this.length?b[0].aoData[this[0]]._aData:l;b[0].aoData[this[0]]._aData=a;la(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length?a[0].aoData[this[0]].nTr|| null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ha(b,a)[0]:I(b,a)});return this.row(b[0])});var bb=function(a){var b=a.context;b.length&&a.length&&(a=b[0].aoData[a[0]],a._details&&(a._details.remove(),a._detailsShow=l,a._details=l))},Tb=function(a,b){var c=a.context;if(c.length&&a.length){var d=c[0].aoData[a[0]];if(d._details){(d._detailsShow=b)?d._details.insertAfter(d.nTr):d._details.detach(); var e=c[0],f=new q(e),g=e.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<C(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){e===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(e===b)for(var c,d=Z(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",d)}),f.on("destroy.dt.DT_details",function(a, b){if(e===b)for(var c=0,d=g.length;c<d;c++)g[c]._details&&bb(g[c])}))}}};r("row().child()",function(a,b){var c=this.context;if(a===l)return c.length&&this.length?c[0].aoData[this[0]]._details:l;if(!0===a)this.child.show();else if(!1===a)bb(this);else if(c.length&&this.length){var d=c[0],c=c[0].aoData[this[0]],e=[],f=function(a,b){if(a.nodeName&&"tr"===a.nodeName.toLowerCase())e.push(a);else{var c=h("<tr><td/></tr>").addClass(b);h("td",c).addClass(b).html(a)[0].colSpan=Z(d);e.push(c[0])}};if(h.isArray(a)|| a instanceof h)for(var g=0,j=a.length;g<j;g++)f(a[g],b);else f(a,b);c._details&&c._details.remove();c._details=h(e);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Tb(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Tb(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){bb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&& this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var ac=/^(.+):(name|visIdx|visible)$/;r("columns()",function(a,b){a===l?a="":h.isPlainObject(a)&&(b=a,a="");var b=$a(b),c=this.iterator("table",function(b){var c=a,f=b.aoColumns,g=C(f,"sName"),j=C(f,"nTh");return Za(c,function(a){var c=Ob(a);if(a==="")return S(f.length);if(c!==null)return[c>=0?c:f.length+c];var e=typeof a==="string"?a.match(ac):"";if(e)switch(e[2]){case "visIdx":case "visible":a=parseInt(e[1],10);if(a<0){c=h.map(f,function(a, b){return a.bVisible?b:null});return[c[c.length+a]]}return[ga(b,a)];case "name":return h.map(g,function(a,b){return a===e[1]?b:null})}else return h(j).filter(a).map(function(){return h.inArray(this,j)}).toArray()})});c.selector.cols=a;c.selector.opts=b;return c});v("columns().header()","column().header()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh})});v("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf})}); v("columns().data()","column().data()",function(){return this.iterator("column-rows",function(a,b,c,d,e){for(var c=[],d=0,f=e.length;d<f;d++)c.push(A(a,e[d],b,""));return c})});v("columns().cache()","column().cache()",function(a){return this.iterator("column-rows",function(b,c,d,e,f){return xa(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)})});v("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,d,e){return xa(a.aoData,e,"anCells",b)})});v("columns().visible()", "column().visible()",function(a,b){return this.iterator("column",function(c,d){var e;if(a===l)e=c.aoColumns[d].bVisible;else{var f=c.aoColumns;e=f[d];var g=c.aoData,j,i,n;if(a===l)e=e.bVisible;else{if(e.bVisible!==a){if(a){var m=h.inArray(!0,C(f,"bVisible"),d+1);j=0;for(i=g.length;j<i;j++)n=g[j].nTr,f=g[j].anCells,n&&n.insertBefore(f[d],f[m]||null)}else h(C(c.aoData,"anCells",d)).detach();e.bVisible=a;ba(c,c.aoHeader);ba(c,c.aoFooter);if(b===l||b)V(c),(c.oScroll.sX||c.oScroll.sY)&&W(c);u(c,null,"column-visibility", [c,d,a]);ta(c)}e=void 0}}return e})});v("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?Y(b,c):c})});r("columns.adjust()",function(){return this.iterator("table",function(a){V(a)})});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return ga(c,b);if("fromData"===a||"toVisible"===a)return Y(c,b)}});r("column()",function(a,b){return ab(this.columns(a,b))});r("cells()", function(a,b,c){h.isPlainObject(a)&&(typeof a.row!==l?(c=b,b=null):(c=a,a=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===l)return this.iterator("table",function(b){var d=a,e=$a(c),f=b.aoData,g=Ya(b,e),e=xa(f,g,"anCells"),j=h([].concat.apply([],e)),i,m=b.aoColumns.length,n,p,r,q;return Za(d,function(a){if(a===null||a===l){n=[];p=0;for(r=g.length;p<r;p++){i=g[p];for(q=0;q<m;q++)n.push({row:i,column:q})}return n}return h.isPlainObject(a)?[a]:j.filter(a).map(function(a,b){i=b.parentNode._DT_RowIndex; return{row:i,column:h.inArray(b,f[i].anCells)}}).toArray()})});var d=this.columns(b,c),e=this.rows(a,c),f,g,j,i,n,m=this.iterator("table",function(a,b){f=[];g=0;for(j=e[b].length;g<j;g++){i=0;for(n=d[b].length;i<n;i++)f.push({row:e[b][g],column:d[b][i]})}return f});h.extend(m.selector,{cols:b,rows:a,opts:c});return m});v("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return a.aoData[b].anCells[c]})});r("cells().data()",function(){return this.iterator("cell", function(a,b,c){return A(a,b,c)})});v("cells().cache()","cell().cache()",function(a){a="search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,d){return b.aoData[c][a][d]})});v("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:Y(a,c)}})});r(["cells().invalidate()","cell().invalidate()"],function(a){var b=this.selector;this.rows(b.rows,b.opts).invalidate(a);return this});r("cell()",function(a,b, c){return ab(this.cells(a,b,c))});r("cell().data()",function(a){var b=this.context,c=this[0];if(a===l)return b.length&&c.length?A(b[0],c[0].row,c[0].column):l;Ea(b[0],c[0].row,c[0].column,a);la(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===l)return 0!==c.length?c[0].aaSorting:l;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})});r("order.listener()", function(a,b,c){return this.iterator("table",function(d){Ka(d,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,d){var e=[];h.each(b[d],function(b,c){e.push([c,a])});c.aaSorting=e})});r("search()",function(a,b,c,d){var e=this.context;return a===l?0!==e.length?e[0].oPreviousSearch.sSearch:l:this.iterator("table",function(e){e.oFeatures.bFilter&&ca(e,h.extend({},e.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0: c,bCaseInsensitive:null===d?!0:d}),1)})});v("columns().search()","column().search()",function(a,b,c,d){return this.iterator("column",function(e,f){var g=e.aoPreSearchCols;if(a===l)return g[f].sSearch;e.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===d?!0:d}),ca(e,e.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table",function(a){a.fnStateSaveCallback.call(a.oInstance, a,{})})});r("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){ta(a)})});p.versionCheck=p.fnVersionCheck=function(a){for(var b=p.version.split("."),a=a.split("."),c,d,e=0,f=a.length;e<f;e++)if(c=parseInt(b[e],10)||0,d=parseInt(a[e],10)||0,c!==d)return c>d;return!0};p.isDataTable=p.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(p.settings,function(a,e){if(e.nTable===b||e.nScrollHead=== b||e.nScrollFoot===b)c=!0});return c};p.tables=p.fnTables=function(a){return jQuery.map(p.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};p.camelToHungarian=G;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var d=h(this.tables().nodes());d[b].apply(d,a);return this})}); r("clear()",function(){return this.iterator("table",function(a){ja(a)})});r("settings()",function(){return new q(this.context,this.context)});r("data()",function(){return this.iterator("table",function(a){return C(a.aoData,"_aData")}).flatten()});r("destroy()",function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,d=b.oClasses,e=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(e),f=h(f),l=h(b.nTableWrapper),m=h.map(b.aoData,function(a){return a.nTr}),o;b.bDestroying= !0;u(b,"aoDestroyCallback","destroy",[b]);a||(new q(b)).columns().visible(!0);l.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(za).unbind(".DT-"+b.sInstance);e!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&e!=j.parentNode&&(i.children("tfoot").detach(),i.append(j));i.detach();l.detach();b.aaSorting=[];b.aaSortingFixed=[];sa(b);h(m).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(d.sSortable+" "+d.sSortableAsc+" "+d.sSortableDesc+" "+d.sSortableNone);b.bJUI&& (h("th span."+d.sSortIcon+", td span."+d.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+d.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(e,b.nTableReinsertBefore);f.children().detach();f.append(m);i.css("width",b.sDestroyWidth).removeClass(d.sTable);(o=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%o])});c=h.inArray(b,p.settings);-1!==c&&p.settings.splice(c,1)})});p.version="1.10.2";p.settings= [];p.models={};p.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};p.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};p.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std", sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};p.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1, fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null, fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"}, sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},p.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers", sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};T(p.defaults);p.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};T(p.defaults.column);p.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null, bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[], aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:l,oAjaxData:l, fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==z(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==z(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var a= this._iDisplayLength,b=this._iDisplayStart,c=b+a,d=this.aiDisplay.length,e=this.oFeatures,f=e.bPaginate;return e.bServerSide?!1===f||-1===a?b+d:Math.min(b+a,this._iRecordsDisplay):!f||c>d||-1===a?d:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};p.ext=t={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:p.fnVersionCheck, iApiIndex:0,oJUIClasses:{},sVersion:p.version};h.extend(t,{afnFiltering:t.search,aTypes:t.type.detect,ofnSearch:t.type.search,oSort:t.type.order,afnSortData:t.order,aoFeatures:t.feature,oApi:t.internal,oStdClasses:t.classes,oPagination:t.pager});h.extend(p.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter", sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody", sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var ya="",ya="",E=ya+"ui-state-default",ea=ya+"css_right ui-icon ui-icon-",Ub=ya+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(p.ext.oJUIClasses,p.ext.classes,{sPageButton:"fg-button ui-button "+E,sPageButtonActive:"ui-state-disabled", sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:E+" sorting_asc",sSortDesc:E+" sorting_desc",sSortable:E+" sorting",sSortableAsc:E+" sorting_asc_disabled",sSortableDesc:E+" sorting_desc_disabled",sSortableNone:E+" sorting_disabled",sSortJUIAsc:ea+"triangle-1-n",sSortJUIDesc:ea+"triangle-1-s",sSortJUI:ea+"carat-2-n-s",sSortJUIAscAllowed:ea+"carat-1-n",sSortJUIDescAllowed:ea+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper", sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+E,sScrollFoot:"dataTables_scrollFoot "+E,sHeaderTH:E,sFooterTH:E,sJUIHeader:Ub+" ui-corner-tl ui-corner-tr",sJUIFooter:Ub+" ui-corner-bl ui-corner-br"});var Lb=p.ext.pager;h.extend(Lb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous",Ua(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Ua(a,b),"next","last"]},_numbers:Ua, numbers_length:7});h.extend(!0,p.ext.renderer,{pageButton:{_:function(a,b,c,d,e,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i,l,m=0,o=function(b,d){var k,p,r,q,s=function(b){Ra(a,b.data.action,true)};k=0;for(p=d.length;k<p;k++){q=d[k];if(h.isArray(q)){r=h("<"+(q.DT_el||"div")+"/>").appendTo(b);o(r,q)}else{l=i="";switch(q){case "ellipsis":b.append("<span>&hellip;</span>");break;case "first":i=j.sFirst;l=q+(e>0?"":" "+g.sPageButtonDisabled);break;case "previous":i=j.sPrevious;l=q+(e>0?"":" "+g.sPageButtonDisabled); break;case "next":i=j.sNext;l=q+(e<f-1?"":" "+g.sPageButtonDisabled);break;case "last":i=j.sLast;l=q+(e<f-1?"":" "+g.sPageButtonDisabled);break;default:i=q+1;l=e===q?g.sPageButtonActive:""}if(i){r=h("<a>",{"class":g.sPageButton+" "+l,"aria-controls":a.sTableId,"data-dt-idx":m,tabindex:a.iTabIndex,id:c===0&&typeof q==="string"?a.sTableId+"_"+q:null}).html(i).appendTo(b);Ta(r,{action:q},s);m++}}}};try{var k=h(O.activeElement).data("dt-idx");o(h(b).empty(),d);k!==null&&h(b).find("[data-dt-idx="+k+"]").focus()}catch(p){}}}}); var va=function(a,b,c,d){if(!a||"-"===a)return-Infinity;b&&(a=Pb(a,b));a.replace&&(c&&(a=a.replace(c,"")),d&&(a=a.replace(d,"")));return 1*a};h.extend(t.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return H(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return H(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a> b?-1:0}});cb("");h.extend(p.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Xa(a,c)?"num"+c:null},function(a){if(a&&(!Yb.test(a)||!Zb.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||H(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Xa(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Qb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Qb(a,c,!0)?"html-num-fmt"+c:null},function(a){return H(a)||"string"=== typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(p.ext.type.search,{html:function(a){return H(a)?a:"string"===typeof a?a.replace(Nb," ").replace(wa,""):""},string:function(a){return H(a)?a:"string"===typeof a?a.replace(Nb," "):a}});h.extend(!0,p.ext.renderer,{header:{_:function(a,b,c,d){h(a.nTable).on("order.dt.DT",function(e,f,g,h){if(a===f){e=c.idx;b.removeClass(c.sSortingClass+" "+d.sSortAsc+" "+d.sSortDesc).addClass(h[e]=="asc"?d.sSortAsc:h[e]=="desc"?d.sSortDesc:c.sSortingClass)}})},jqueryui:function(a, b,c,d){var e=c.idx;h("<div/>").addClass(d.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(d.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(f,g,h,i){if(a===g){b.removeClass(d.sSortAsc+" "+d.sSortDesc).addClass(i[e]=="asc"?d.sSortAsc:i[e]=="desc"?d.sSortDesc:c.sSortingClass);b.find("span."+d.sSortIcon).removeClass(d.sSortJUIAsc+" "+d.sSortJUIDesc+" "+d.sSortJUI+" "+d.sSortJUIAscAllowed+" "+d.sSortJUIDescAllowed).addClass(i[e]=="asc"?d.sSortJUIAsc: i[e]=="desc"?d.sSortJUIDesc:c.sSortingClassJUI)}})}}});p.render={number:function(a,b,c,d){return{display:function(e){var f=0>e?"-":"",e=Math.abs(parseFloat(e)),g=parseInt(e,10),e=c?b+(e-g).toFixed(c).substring(2):"";return f+(d||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,a)+e}}}};h.extend(p.ext.internal,{_fnExternApiFunc:Mb,_fnBuildAjax:na,_fnAjaxUpdate:jb,_fnAjaxParameters:sb,_fnAjaxUpdateDraw:tb,_fnAjaxDataSrc:oa,_fnAddColumn:Aa,_fnColumnOptions:fa,_fnAdjustColumnSizing:V,_fnVisibleToColumnIndex:ga, _fnColumnIndexToVisible:Y,_fnVisbleColumns:Z,_fnGetColumns:X,_fnColumnTypes:Da,_fnApplyColumnDefs:hb,_fnHungarianMap:T,_fnCamelToHungarian:G,_fnLanguageCompat:N,_fnBrowserDetect:fb,_fnAddData:I,_fnAddTr:ha,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==l?b._DT_RowIndex:null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:A,_fnSetCellData:Ea,_fnSplitObjNotation:Ga,_fnGetObjectDataFn:U,_fnSetObjectDataFn:Ba,_fnGetDataMaster:Ha,_fnClearTable:ja, _fnDeleteIndex:ka,_fnInvalidateRow:la,_fnGetRowElements:ia,_fnCreateTr:Fa,_fnBuildHead:ib,_fnDrawHead:ba,_fnDraw:K,_fnReDraw:L,_fnAddOptionsHtml:lb,_fnDetectHeader:aa,_fnGetUniqueThs:ma,_fnFeatureHtmlFilter:nb,_fnFilterComplete:ca,_fnFilterCustom:wb,_fnFilterColumn:vb,_fnFilter:ub,_fnFilterCreateSearch:Na,_fnEscapeRegex:Oa,_fnFilterData:xb,_fnFeatureHtmlInfo:qb,_fnUpdateInfo:Ab,_fnInfoMacros:Bb,_fnInitialise:ra,_fnInitComplete:pa,_fnLengthChange:Pa,_fnFeatureHtmlLength:mb,_fnFeatureHtmlPaginate:rb, _fnPageChange:Ra,_fnFeatureHtmlProcessing:ob,_fnProcessingDisplay:B,_fnFeatureHtmlTable:pb,_fnScrollDraw:W,_fnApplyToChildren:F,_fnCalculateColumnWidths:Ca,_fnThrottle:Ma,_fnConvertToWidth:Cb,_fnScrollingWidthAdjust:Eb,_fnGetWidestNode:Db,_fnGetMaxLenString:Fb,_fnStringToCss:s,_fnScrollBarWidth:Gb,_fnSortFlatten:R,_fnSort:kb,_fnSortAria:Ib,_fnSortListener:Sa,_fnSortAttachListener:Ka,_fnSortingClasses:sa,_fnSortData:Hb,_fnSaveState:ta,_fnLoadState:Jb,_fnSettingsFromNode:ua,_fnLog:P,_fnMap:D,_fnBindAction:Ta, _fnCallbackReg:x,_fnCallbackFire:u,_fnLengthOverflow:Qa,_fnRenderer:La,_fnDataSource:z,_fnRowAttributes:Ia,_fnCalculateEnd:function(){}});h.fn.dataTable=p;h.fn.dataTableSettings=p.settings;h.fn.dataTableExt=p.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(p,function(a,b){h.fn.DataTable[a]=b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],N):"object"===typeof exports?N(require("jquery")):jQuery&&!jQuery.fn.dataTable&&N(jQuery)})(window, document);
zzsoszz/metronicv35
theme/assets/global/plugins/datatables/media/js/jquery.dataTables.min.js
JavaScript
apache-2.0
77,499
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Xml.php 24593 2012-01-05 20:35:02Z matthew $ */ require_once 'Zend/Tool/Project/Profile/FileParser/Interface.php'; require_once 'Zend/Tool/Project/Context/Repository.php'; require_once 'Zend/Tool/Project/Profile.php'; require_once 'Zend/Tool/Project/Profile/Resource.php'; /** * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Tool_Project_Profile_FileParser_Xml implements Zend_Tool_Project_Profile_FileParser_Interface { /** * @var Zend_Tool_Project_Profile */ protected $_profile = null; /** * @var Zend_Tool_Project_Context_Repository */ protected $_contextRepository = null; /** * __construct() * */ public function __construct() { $this->_contextRepository = Zend_Tool_Project_Context_Repository::getInstance(); } /** * serialize() * * create an xml string from the provided profile * * @param Zend_Tool_Project_Profile $profile * @return string */ public function serialize(Zend_Tool_Project_Profile $profile) { $profile = clone $profile; $this->_profile = $profile; $xmlElement = new SimpleXMLElement('<projectProfile />'); if ($profile->hasAttribute('type')) { $xmlElement->addAttribute('type', $profile->getAttribute('type')); } if ($profile->hasAttribute('version')) { $xmlElement->addAttribute('version', $profile->getAttribute('version')); } self::_serializeRecurser($profile, $xmlElement); $doc = new DOMDocument('1.0'); $doc->formatOutput = true; $domnode = dom_import_simplexml($xmlElement); $domnode = $doc->importNode($domnode, true); $domnode = $doc->appendChild($domnode); return $doc->saveXML(); } /** * unserialize() * * Create a structure in the object $profile from the structure specficied * in the xml string provided * * @param string xml data * @param Zend_Tool_Project_Profile The profile to use as the top node * @return Zend_Tool_Project_Profile */ public function unserialize($data, Zend_Tool_Project_Profile $profile) { if ($data == null) { throw new Exception('contents not available to unserialize.'); } $this->_profile = $profile; $xmlDataIterator = new SimpleXMLIterator($data); if ($xmlDataIterator->getName() != 'projectProfile') { throw new Exception('Profiles must start with a projectProfile node'); } if (isset($xmlDataIterator['type'])) { $this->_profile->setAttribute('type', (string) $xmlDataIterator['type']); } if (isset($xmlDataIterator['version'])) { $this->_profile->setAttribute('version', (string) $xmlDataIterator['version']); } // start un-serialization of the xml doc $this->_unserializeRecurser($xmlDataIterator); // contexts should be initialized after the unwinding of the profile structure $this->_lazyLoadContexts(); return $this->_profile; } /** * _serializeRecurser() * * This method will be used to traverse the depths of the structure * when *serializing* an xml structure into a string * * @param array $resources * @param SimpleXmlElement $xmlNode */ protected function _serializeRecurser($resources, SimpleXmlElement $xmlNode) { // @todo find a better way to handle concurrency.. if no clone, _position in node gets messed up //if ($resources instanceof Zend_Tool_Project_Profile_Resource) { // $resources = clone $resources; //} foreach ($resources as $resource) { if ($resource->isDeleted()) { continue; } $resourceName = $resource->getContext()->getName(); $resourceName[0] = strtolower($resourceName[0]); $newNode = $xmlNode->addChild($resourceName); //$reflectionClass = new ReflectionClass($resource->getContext()); if ($resource->isEnabled() == false) { $newNode->addAttribute('enabled', 'false'); } foreach ($resource->getPersistentAttributes() as $paramName => $paramValue) { $newNode->addAttribute($paramName, $paramValue); } if ($resource->hasChildren()) { self::_serializeRecurser($resource, $newNode); } } } /** * _unserializeRecurser() * * This method will be used to traverse the depths of the structure * as needed to *unserialize* the profile from an xmlIterator * * @param SimpleXMLIterator $xmlIterator * @param Zend_Tool_Project_Profile_Resource $resource */ protected function _unserializeRecurser(SimpleXMLIterator $xmlIterator, Zend_Tool_Project_Profile_Resource $resource = null) { foreach ($xmlIterator as $resourceName => $resourceData) { $contextName = $resourceName; $subResource = new Zend_Tool_Project_Profile_Resource($contextName); $subResource->setProfile($this->_profile); if ($resourceAttributes = $resourceData->attributes()) { $attributes = array(); foreach ($resourceAttributes as $attrName => $attrValue) { $attributes[$attrName] = (string) $attrValue; } $subResource->setAttributes($attributes); } if ($resource) { $resource->append($subResource, false); } else { $this->_profile->append($subResource); } if ($this->_contextRepository->isOverwritableContext($contextName) == false) { $subResource->initializeContext(); } if ($xmlIterator->hasChildren()) { self::_unserializeRecurser($xmlIterator->getChildren(), $subResource); } } } /** * _lazyLoadContexts() * * This method will call initializeContext on the resources in a profile * @todo determine if this method belongs inside the profile * */ protected function _lazyLoadContexts() { foreach ($this->_profile as $topResource) { $rii = new RecursiveIteratorIterator($topResource, RecursiveIteratorIterator::SELF_FIRST); foreach ($rii as $resource) { $resource->initializeContext(); } } } }
leomastakusuma/myindo
library/Zend/Tool/Project/Profile/FileParser/Xml.php
PHP
apache-2.0
7,475
package com.badlogic.gdx.graphics; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.glutils.KTXTextureData; /** Used by a {@link Cubemap} to load the pixel data. The Cubemap will request the CubemapData to prepare itself through * {@link #prepare()} and upload its data using {@link #consumeCubemapData()}. These are the first methods to be called by Cubemap. * After that the Cubemap will invoke the other methods to find out about the size of the image data, the format, whether the * CubemapData is able to manage the pixel data if the OpenGL ES context is lost.</p> * * Before a call to either {@link #consumeCubemapData()}, Cubemap will bind the OpenGL ES texture.</p> * * Look at {@link KTXTextureData} for example implementation of this interface. * @author Vincent Bousquet */ public interface CubemapData { /** @return whether the TextureData is prepared or not. */ public boolean isPrepared (); /** Prepares the TextureData for a call to {@link #consumeCubemapData()}. This method can be called from a non OpenGL thread and * should thus not interact with OpenGL. */ public void prepare (); /** Uploads the pixel data for the 6 faces of the cube to the OpenGL ES texture. The caller must bind an OpenGL ES texture. A * call to {@link #prepare()} must preceed a call to this method. Any internal data structures created in {@link #prepare()} * should be disposed of here. */ public void consumeCubemapData (); /** @return the width of the pixel data */ public int getWidth (); /** @return the height of the pixel data */ public int getHeight (); /** @return whether this implementation can cope with a EGL context loss. */ public boolean isManaged (); }
Heart2009/libgdx
gdx/src/com/badlogic/gdx/graphics/CubemapData.java
Java
apache-2.0
1,772
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" extensions "k8s.io/kubernetes/pkg/apis/extensions" ) // FakePodSecurityPolicies implements PodSecurityPolicyInterface type FakePodSecurityPolicies struct { Fake *FakeExtensions } var podsecuritypoliciesResource = schema.GroupVersionResource{Group: "extensions", Version: "", Resource: "podsecuritypolicies"} func (c *FakePodSecurityPolicies) Create(podSecurityPolicy *extensions.PodSecurityPolicy) (result *extensions.PodSecurityPolicy, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(podsecuritypoliciesResource, podSecurityPolicy), &extensions.PodSecurityPolicy{}) if obj == nil { return nil, err } return obj.(*extensions.PodSecurityPolicy), err } func (c *FakePodSecurityPolicies) Update(podSecurityPolicy *extensions.PodSecurityPolicy) (result *extensions.PodSecurityPolicy, err error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateAction(podsecuritypoliciesResource, podSecurityPolicy), &extensions.PodSecurityPolicy{}) if obj == nil { return nil, err } return obj.(*extensions.PodSecurityPolicy), err } func (c *FakePodSecurityPolicies) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteAction(podsecuritypoliciesResource, name), &extensions.PodSecurityPolicy{}) return err } func (c *FakePodSecurityPolicies) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewRootDeleteCollectionAction(podsecuritypoliciesResource, listOptions) _, err := c.Fake.Invokes(action, &extensions.PodSecurityPolicyList{}) return err } func (c *FakePodSecurityPolicies) Get(name string, options v1.GetOptions) (result *extensions.PodSecurityPolicy, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(podsecuritypoliciesResource, name), &extensions.PodSecurityPolicy{}) if obj == nil { return nil, err } return obj.(*extensions.PodSecurityPolicy), err } func (c *FakePodSecurityPolicies) List(opts v1.ListOptions) (result *extensions.PodSecurityPolicyList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(podsecuritypoliciesResource, opts), &extensions.PodSecurityPolicyList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &extensions.PodSecurityPolicyList{} for _, item := range obj.(*extensions.PodSecurityPolicyList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested podSecurityPolicies. func (c *FakePodSecurityPolicies) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(podsecuritypoliciesResource, opts)) } // Patch applies the patch and returns the patched podSecurityPolicy. func (c *FakePodSecurityPolicies) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *extensions.PodSecurityPolicy, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(podsecuritypoliciesResource, name, data, subresources...), &extensions.PodSecurityPolicy{}) if obj == nil { return nil, err } return obj.(*extensions.PodSecurityPolicy), err }
shawn-hurley/ansible-service-broker
vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/internalversion/fake/fake_podsecuritypolicy.go
GO
apache-2.0
4,133
// cgo -godefs -- -fsigned-char types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && freebsd // +build arm64,freebsd package unix const ( SizeofPtr = 0x8 SizeofShort = 0x2 SizeofInt = 0x4 SizeofLong = 0x8 SizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( _statfsVersion = 0x20140518 _dirblksiz = 0x400 ) type Stat_t struct { Dev uint64 Ino uint64 Nlink uint64 Mode uint16 _0 int16 Uid uint32 Gid uint32 _1 int32 Rdev uint64 Atim Timespec Mtim Timespec Ctim Timespec Btim Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint64 Spare [10]uint64 } type stat_freebsd11_t struct { Dev uint32 Ino uint32 Mode uint16 Nlink uint16 Uid uint32 Gid uint32 Rdev uint32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Btim Timespec } type Statfs_t struct { Version uint32 Type uint32 Flags uint64 Bsize uint64 Iosize uint64 Blocks uint64 Bfree uint64 Bavail int64 Files uint64 Ffree int64 Syncwrites uint64 Asyncwrites uint64 Syncreads uint64 Asyncreads uint64 Spare [10]uint64 Namemax uint32 Owner uint32 Fsid Fsid Charspare [80]int8 Fstypename [16]byte Mntfromname [1024]byte Mntonname [1024]byte } type statfs_freebsd11_t struct { Version uint32 Type uint32 Flags uint64 Bsize uint64 Iosize uint64 Blocks uint64 Bfree uint64 Bavail int64 Files uint64 Ffree int64 Syncwrites uint64 Asyncwrites uint64 Syncreads uint64 Asyncreads uint64 Spare [10]uint64 Namemax uint32 Owner uint32 Fsid Fsid Charspare [80]int8 Fstypename [16]byte Mntfromname [88]byte Mntonname [88]byte } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 Sysid int32 _ [4]byte } type Dirent struct { Fileno uint64 Off int64 Reclen uint16 Type uint8 Pad0 uint8 Namlen uint16 Pad1 uint16 Name [256]int8 } type dirent_freebsd11 struct { Fileno uint32 Reclen uint16 Type uint8 Namlen uint8 Name [256]int8 } type Fsid struct { Val [2]int32 } const ( PathMax = 0x400 ) const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 FADV_SEQUENTIAL = 0x2 FADV_WILLNEED = 0x3 FADV_DONTNEED = 0x4 FADV_NOREUSE = 0x5 ) type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [46]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Xucred struct { Version uint32 Uid uint32 Ngroups int16 Groups [16]uint32 _ *byte } type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofXucred = 0x58 SizeofLinger = 0x8 SizeofIovec = 0x10 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_ATTACH = 0xa PTRACE_CONT = 0x7 PTRACE_DETACH = 0xb PTRACE_GETFPREGS = 0x23 PTRACE_GETLWPLIST = 0xf PTRACE_GETNUMLWPS = 0xe PTRACE_GETREGS = 0x21 PTRACE_IO = 0xc PTRACE_KILL = 0x8 PTRACE_LWPEVENTS = 0x18 PTRACE_LWPINFO = 0xd PTRACE_SETFPREGS = 0x24 PTRACE_SETREGS = 0x22 PTRACE_SINGLESTEP = 0x9 PTRACE_TRACEME = 0x0 ) const ( PIOD_READ_D = 0x1 PIOD_WRITE_D = 0x2 PIOD_READ_I = 0x3 PIOD_WRITE_I = 0x4 ) const ( PL_FLAG_BORN = 0x100 PL_FLAG_EXITED = 0x200 PL_FLAG_SI = 0x20 ) const ( TRAP_BRKPT = 0x1 TRAP_TRACE = 0x2 ) type PtraceLwpInfoStruct struct { Lwpid int32 Event int32 Flags int32 Sigmask Sigset_t Siglist Sigset_t Siginfo __Siginfo Tdname [20]int8 Child_pid int32 Syscall_code uint32 Syscall_narg uint32 } type __Siginfo struct { Signo int32 Errno int32 Code int32 Pid int32 Uid uint32 Status int32 Addr *byte Value [8]byte _ [40]byte } type Sigset_t struct { Val [4]uint32 } type Reg struct { X [30]uint64 Lr uint64 Sp uint64 Elr uint64 Spsr uint32 _ [4]byte } type FpReg struct { Q [32][16]uint8 Sr uint32 Cr uint32 _ [8]byte } type PtraceIoDesc struct { Op int32 Offs *byte Addr *byte Len uint64 } type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [16]uint64 } const ( sizeofIfMsghdr = 0xa8 SizeofIfMsghdr = 0xa8 sizeofIfData = 0x98 SizeofIfData = 0x98 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x98 SizeofRtMetrics = 0x70 ) type ifMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ uint16 Data ifData } type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Data IfData } type ifData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Vhid uint8 Datalen uint16 Mtu uint32 Metric uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Oqdrops uint64 Noproto uint64 Hwassist uint64 _ [8]byte _ [16]byte } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Link_state uint8 Spare_char1 uint8 Spare_char2 uint8 Datalen uint8 Mtu uint64 Metric uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Hwassist uint64 Epoch int64 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ uint16 Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ uint16 } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ uint16 Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Fmask int32 Inits uint64 Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Hopcount uint64 Expire uint64 Recvpipe uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Pksent uint64 Weight uint64 Filler [3]uint64 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfZbuf = 0x18 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 SizeofBpfZbufHeader = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfZbuf struct { Bufa *byte Bufb *byte Buflen uint64 } type BpfProgram struct { Len uint32 Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 _ [6]byte } type BpfZbufHeader struct { Kernel_gen uint32 Kernel_len uint32 User_gen uint32 _ [5]uint32 } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x64 AT_EACCESS = 0x100 AT_SYMLINK_NOFOLLOW = 0x200 AT_SYMLINK_FOLLOW = 0x400 AT_REMOVEDIR = 0x800 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLINIGNEOF = 0x2000 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type CapRights struct { Rights [2]uint64 } type Utsname struct { Sysname [256]byte Nodename [256]byte Release [256]byte Version [256]byte Machine [256]byte } const SizeofClockinfo = 0x14 type Clockinfo struct { Hz int32 Tick int32 Spare int32 Stathz int32 Profhz int32 }
dixudx/kubernetes
vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go
GO
apache-2.0
10,834
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.itest.http; import java.io.IOException; import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.apache.http.Consts; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; @ContextConfiguration public class Http4MaxConnectionPerHostTest extends AbstractJUnit4SpringContextTests { protected static HttpTestServer localServer; @Autowired protected CamelContext camelContext; @EndpointInject(uri = "direct:start") protected ProducerTemplate producer; @EndpointInject(uri = "mock:result") protected MockEndpoint mock; @BeforeClass public static void setUp() throws Exception { localServer = new HttpTestServer(null, null); localServer.register("/", new HttpRequestHandler() { public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity("OK", Consts.ISO_8859_1)); } }); localServer.start(); } @AfterClass public static void tearDown() throws Exception { if (localServer != null) { localServer.stop(); } } @Test public void testMocksIsValid() throws Exception { mock.expectedMessageCount(1); producer.sendBody(null); mock.assertIsSatisfied(); } }
dpocock/camel
tests/camel-itest/src/test/java/org/apache/camel/itest/http/Http4MaxConnectionPerHostTest.java
Java
apache-2.0
2,897
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.support; import org.apache.lucene.store.AlreadyClosedException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.NoShardAvailableActionException; import org.elasticsearch.action.UnavailableShardsException; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.shard.IllegalIndexShardStateException; import org.elasticsearch.index.shard.ShardNotFoundException; public class TransportActions { public static boolean isShardNotAvailableException(final Throwable e) { final Throwable actual = ExceptionsHelper.unwrapCause(e); return (actual instanceof ShardNotFoundException || actual instanceof IndexNotFoundException || actual instanceof IllegalIndexShardStateException || actual instanceof NoShardAvailableActionException || actual instanceof UnavailableShardsException || actual instanceof AlreadyClosedException); } /** * If a failure is already present, should this failure override it or not for read operations. */ public static boolean isReadOverrideException(Exception e) { return !isShardNotAvailableException(e); } }
JervyShi/elasticsearch
core/src/main/java/org/elasticsearch/action/support/TransportActions.java
Java
apache-2.0
2,045
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.vm; import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultCamelContext; public class VmMultipleConsumersMultipleContextTest extends ContextTestSupport { public void testMultipleVMConsumersSameContext() throws Exception { CamelContext camelContext = new DefaultCamelContext(); ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); RouteBuilder builder = new RouteBuilder(camelContext) { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId("route1").to("mock:route1"); } }; RouteBuilder builder2 = new RouteBuilder(camelContext) { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId("route2").to("mock:route2"); } }; camelContext.addRoutes(builder); camelContext.addRoutes(builder2); camelContext.start(); MockEndpoint mock1 = (MockEndpoint) camelContext.getEndpoint("mock:route1"); MockEndpoint mock2 = (MockEndpoint) camelContext.getEndpoint("mock:route2"); mock1.expectedMessageCount(100); mock2.expectedMessageCount(100); for (int i = 0; i < 100; i++) { producerTemplate.sendBody("vm:producer?multipleConsumers=true", i); } MockEndpoint.assertIsSatisfied(mock1, mock2); camelContext.stop(); } public void testVmMultipleConsumersMultipleContext() throws Exception { // start context 1 CamelContext consumerContext1 = new DefaultCamelContext(); consumerContext1.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId("route1").to("mock:route1"); } }); consumerContext1.start(); MockEndpoint route1Mock = (MockEndpoint) consumerContext1.getEndpoint("mock:route1"); route1Mock.expectedMessageCount(100); // start up context 2 CamelContext consumerContext2 = new DefaultCamelContext(); consumerContext2.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId("route2").to("mock:route2"); } }); consumerContext2.start(); MockEndpoint route2Mock = (MockEndpoint) consumerContext2.getEndpoint("mock:route2"); route2Mock.expectedMessageCount(100); // use context part of contextTestSupport to send in messages for (int i = 0; i < 100; i++) { template.sendBody("vm:producer?multipleConsumers=true", i); } route1Mock.assertIsSatisfied(); route2Mock.assertIsSatisfied(); consumerContext1.stop(); consumerContext2.stop(); } private CamelContext buildConsumerContext(final String route) throws Exception { DefaultCamelContext rc = new DefaultCamelContext(); rc.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId(route).to("mock:" + route); } }); rc.start(); return rc; } public void testVmMultipleConsumersDifferentEndpoints() throws Exception { // start context 1 CamelContext consumerContext1 = new DefaultCamelContext(); consumerContext1.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("vm:producer?multipleConsumers=true").routeId("route1").to("mock:route1"); } }); consumerContext1.start(); MockEndpoint route1Mock = (MockEndpoint) consumerContext1.getEndpoint("mock:route1"); route1Mock.expectedMessageCount(100); // start up context 2 CamelContext consumerContext2 = new DefaultCamelContext(); consumerContext2.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("vm:foo?multipleConsumers=true").routeId("route2").to("mock:route2"); } }); consumerContext2.start(); MockEndpoint route2Mock = (MockEndpoint) consumerContext2.getEndpoint("mock:route2"); route2Mock.expectedMessageCount(0); // use context part of contextTestSupport to send in messages for (int i = 0; i < 100; i++) { template.sendBody("vm:producer?multipleConsumers=true", i); } route1Mock.assertIsSatisfied(); route2Mock.assertIsSatisfied(); consumerContext1.stop(); consumerContext2.stop(); } }
FingolfinTEK/camel
camel-core/src/test/java/org/apache/camel/component/vm/VmMultipleConsumersMultipleContextTest.java
Java
apache-2.0
5,914
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "STANDALONEMONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-fm", "localeID": "en_FM", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
inkeil/HunLier
public/assets/js/angular/i18n/angular-locale_en-fm.js
JavaScript
apache-2.0
2,710
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package secret import ( "fmt" "io/ioutil" "os" "path" "reflect" "runtime" "strings" "testing" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/empty_dir" volumetest "k8s.io/kubernetes/pkg/volume/testing" "k8s.io/kubernetes/pkg/volume/util" "github.com/stretchr/testify/assert" ) func TestMakePayload(t *testing.T) { caseMappingMode := int32(0400) cases := []struct { name string mappings []v1.KeyToPath secret *v1.Secret mode int32 optional bool payload map[string]util.FileProjection success bool }{ { name: "no overrides", secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "foo": {Data: []byte("foo"), Mode: 0644}, "bar": {Data: []byte("bar"), Mode: 0644}, }, success: true, }, { name: "basic 1", mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/foo.txt", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "path/to/foo.txt": {Data: []byte("foo"), Mode: 0644}, }, success: true, }, { name: "subdirs", mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "path/to/1/2/3/foo.txt": {Data: []byte("foo"), Mode: 0644}, }, success: true, }, { name: "subdirs 2", mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "path/to/1/2/3/foo.txt": {Data: []byte("foo"), Mode: 0644}, }, success: true, }, { name: "subdirs 3", mappings: []v1.KeyToPath{ { Key: "foo", Path: "path/to/1/2/3/foo.txt", }, { Key: "bar", Path: "another/path/to/the/esteemed/bar.bin", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "path/to/1/2/3/foo.txt": {Data: []byte("foo"), Mode: 0644}, "another/path/to/the/esteemed/bar.bin": {Data: []byte("bar"), Mode: 0644}, }, success: true, }, { name: "non existent key", mappings: []v1.KeyToPath{ { Key: "zab", Path: "path/to/foo.txt", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, success: false, }, { name: "mapping with Mode", mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", Mode: &caseMappingMode, }, { Key: "bar", Path: "bar.bin", Mode: &caseMappingMode, }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "foo.txt": {Data: []byte("foo"), Mode: caseMappingMode}, "bar.bin": {Data: []byte("bar"), Mode: caseMappingMode}, }, success: true, }, { name: "mapping with defaultMode", mappings: []v1.KeyToPath{ { Key: "foo", Path: "foo.txt", }, { Key: "bar", Path: "bar.bin", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, payload: map[string]util.FileProjection{ "foo.txt": {Data: []byte("foo"), Mode: 0644}, "bar.bin": {Data: []byte("bar"), Mode: 0644}, }, success: true, }, { name: "optional non existent key", mappings: []v1.KeyToPath{ { Key: "zab", Path: "path/to/foo.txt", }, }, secret: &v1.Secret{ Data: map[string][]byte{ "foo": []byte("foo"), "bar": []byte("bar"), }, }, mode: 0644, optional: true, payload: map[string]util.FileProjection{}, success: true, }, } for _, tc := range cases { actualPayload, err := MakePayload(tc.mappings, tc.secret, &tc.mode, tc.optional) if err != nil && tc.success { t.Errorf("%v: unexpected failure making payload: %v", tc.name, err) continue } if err == nil && !tc.success { t.Errorf("%v: unexpected success making payload", tc.name) continue } if !tc.success { continue } if e, a := tc.payload, actualPayload; !reflect.DeepEqual(e, a) { t.Errorf("%v: expected and actual payload do not match", tc.name) } } } func newTestHost(t *testing.T, clientset clientset.Interface) (string, volume.VolumeHost) { tempDir, err := ioutil.TempDir("/tmp", "secret_volume_test.") if err != nil { t.Fatalf("can't make a temp rootdir: %v", err) } return tempDir, volumetest.NewFakeVolumeHost(tempDir, clientset, empty_dir.ProbeVolumePlugins()) } func TestCanSupport(t *testing.T) { pluginMgr := volume.VolumePluginMgr{} tempDir, host := newTestHost(t, nil) defer os.RemoveAll(tempDir) pluginMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, host) plugin, err := pluginMgr.FindPluginByName(secretPluginName) if err != nil { t.Errorf("Can't find the plugin by name") } if plugin.GetPluginName() != secretPluginName { t.Errorf("Wrong name: %s", plugin.GetPluginName()) } if !plugin.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{Secret: &v1.SecretVolumeSource{SecretName: ""}}}}) { t.Errorf("Expected true") } if plugin.CanSupport(&volume.Spec{}) { t.Errorf("Expected false") } } func TestPlugin(t *testing.T) { var ( testPodUID = types.UID("test_pod_uid") testVolumeName = "test_volume_name" testNamespace = "test_secret_namespace" testName = "test_secret_name" volumeSpec = volumeSpec(testVolumeName, testName, 0644) secret = secret(testNamespace, testName) client = fake.NewSimpleClientset(&secret) pluginMgr = volume.VolumePluginMgr{} rootDir, host = newTestHost(t, client) ) defer os.RemoveAll(rootDir) pluginMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, host) plugin, err := pluginMgr.FindPluginByName(secretPluginName) if err != nil { t.Errorf("Can't find the plugin by name") } pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Fatalf("Got a nil Mounter") } volumePath := mounter.GetPath() if !strings.HasSuffix(volumePath, fmt.Sprintf("pods/test_pod_uid/volumes/kubernetes.io~secret/test_volume_name")) { t.Errorf("Got unexpected path: %s", volumePath) } err = mounter.SetUp(nil) if err != nil { t.Errorf("Failed to setup volume: %v", err) } if _, err := os.Stat(volumePath); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", volumePath) } else { t.Errorf("SetUp() failed: %v", err) } } // secret volume should create its own empty wrapper path podWrapperMetadataDir := fmt.Sprintf("%v/pods/test_pod_uid/plugins/kubernetes.io~empty-dir/wrapped_test_volume_name", rootDir) if _, err := os.Stat(podWrapperMetadataDir); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, empty-dir wrapper path is not created: %s", podWrapperMetadataDir) } else { t.Errorf("SetUp() failed: %v", err) } } doTestSecretDataInVolume(volumePath, secret, t) defer doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) // Metrics only supported on linux metrics, err := mounter.GetMetrics() if runtime.GOOS == "linux" { assert.NotEmpty(t, metrics) assert.NoError(t, err) } else { t.Skipf("Volume metrics not supported on %s", runtime.GOOS) } } // Test the case where the plugin's ready file exists, but the volume dir is not a // mountpoint, which is the state the system will be in after reboot. The dir // should be mounter and the secret data written to it. func TestPluginReboot(t *testing.T) { var ( testPodUID = types.UID("test_pod_uid3") testVolumeName = "test_volume_name" testNamespace = "test_secret_namespace" testName = "test_secret_name" volumeSpec = volumeSpec(testVolumeName, testName, 0644) secret = secret(testNamespace, testName) client = fake.NewSimpleClientset(&secret) pluginMgr = volume.VolumePluginMgr{} rootDir, host = newTestHost(t, client) ) defer os.RemoveAll(rootDir) pluginMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, host) plugin, err := pluginMgr.FindPluginByName(secretPluginName) if err != nil { t.Errorf("Can't find the plugin by name") } pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Fatalf("Got a nil Mounter") } podMetadataDir := fmt.Sprintf("%v/pods/test_pod_uid3/plugins/kubernetes.io~secret/test_volume_name", rootDir) util.SetReady(podMetadataDir) volumePath := mounter.GetPath() if !strings.HasSuffix(volumePath, fmt.Sprintf("pods/test_pod_uid3/volumes/kubernetes.io~secret/test_volume_name")) { t.Errorf("Got unexpected path: %s", volumePath) } err = mounter.SetUp(nil) if err != nil { t.Errorf("Failed to setup volume: %v", err) } if _, err := os.Stat(volumePath); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", volumePath) } else { t.Errorf("SetUp() failed: %v", err) } } doTestSecretDataInVolume(volumePath, secret, t) doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) } func TestPluginOptional(t *testing.T) { var ( testPodUID = types.UID("test_pod_uid") testVolumeName = "test_volume_name" testNamespace = "test_secret_namespace" testName = "test_secret_name" trueVal = true volumeSpec = volumeSpec(testVolumeName, testName, 0644) client = fake.NewSimpleClientset() pluginMgr = volume.VolumePluginMgr{} rootDir, host = newTestHost(t, client) ) volumeSpec.Secret.Optional = &trueVal defer os.RemoveAll(rootDir) pluginMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, host) plugin, err := pluginMgr.FindPluginByName(secretPluginName) if err != nil { t.Errorf("Can't find the plugin by name") } pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter") } volumePath := mounter.GetPath() if !strings.HasSuffix(volumePath, fmt.Sprintf("pods/test_pod_uid/volumes/kubernetes.io~secret/test_volume_name")) { t.Errorf("Got unexpected path: %s", volumePath) } err = mounter.SetUp(nil) if err != nil { t.Errorf("Failed to setup volume: %v", err) } if _, err := os.Stat(volumePath); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", volumePath) } else { t.Errorf("SetUp() failed: %v", err) } } // secret volume should create its own empty wrapper path podWrapperMetadataDir := fmt.Sprintf("%v/pods/test_pod_uid/plugins/kubernetes.io~empty-dir/wrapped_test_volume_name", rootDir) if _, err := os.Stat(podWrapperMetadataDir); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, empty-dir wrapper path is not created: %s", podWrapperMetadataDir) } else { t.Errorf("SetUp() failed: %v", err) } } datadirSymlink := path.Join(volumePath, "..data") datadir, err := os.Readlink(datadirSymlink) if err != nil && os.IsNotExist(err) { t.Fatalf("couldn't find volume path's data dir, %s", datadirSymlink) } else if err != nil { t.Fatalf("couldn't read symlink, %s", datadirSymlink) } datadirPath := path.Join(volumePath, datadir) infos, err := ioutil.ReadDir(volumePath) if err != nil { t.Fatalf("couldn't find volume path, %s", volumePath) } if len(infos) != 0 { for _, fi := range infos { if fi.Name() != "..data" && fi.Name() != datadir { t.Errorf("empty data volume directory, %s, is not empty. Contains: %s", datadirSymlink, fi.Name()) } } } infos, err = ioutil.ReadDir(datadirPath) if err != nil { t.Fatalf("couldn't find volume data path, %s", datadirPath) } if len(infos) != 0 { t.Errorf("empty data directory, %s, is not empty. Contains: %s", datadirSymlink, infos[0].Name()) } defer doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) } func TestPluginOptionalKeys(t *testing.T) { var ( testPodUID = types.UID("test_pod_uid") testVolumeName = "test_volume_name" testNamespace = "test_secret_namespace" testName = "test_secret_name" trueVal = true volumeSpec = volumeSpec(testVolumeName, testName, 0644) secret = secret(testNamespace, testName) client = fake.NewSimpleClientset(&secret) pluginMgr = volume.VolumePluginMgr{} rootDir, host = newTestHost(t, client) ) volumeSpec.VolumeSource.Secret.Items = []v1.KeyToPath{ {Key: "data-1", Path: "data-1"}, {Key: "data-2", Path: "data-2"}, {Key: "data-3", Path: "data-3"}, {Key: "missing", Path: "missing"}, } volumeSpec.Secret.Optional = &trueVal defer os.RemoveAll(rootDir) pluginMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, host) plugin, err := pluginMgr.FindPluginByName(secretPluginName) if err != nil { t.Errorf("Can't find the plugin by name") } pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: testNamespace, UID: testPodUID}} mounter, err := plugin.NewMounter(volume.NewSpecFromVolume(volumeSpec), pod, volume.VolumeOptions{}) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter") } volumePath := mounter.GetPath() if !strings.HasSuffix(volumePath, fmt.Sprintf("pods/test_pod_uid/volumes/kubernetes.io~secret/test_volume_name")) { t.Errorf("Got unexpected path: %s", volumePath) } err = mounter.SetUp(nil) if err != nil { t.Errorf("Failed to setup volume: %v", err) } if _, err := os.Stat(volumePath); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", volumePath) } else { t.Errorf("SetUp() failed: %v", err) } } // secret volume should create its own empty wrapper path podWrapperMetadataDir := fmt.Sprintf("%v/pods/test_pod_uid/plugins/kubernetes.io~empty-dir/wrapped_test_volume_name", rootDir) if _, err := os.Stat(podWrapperMetadataDir); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, empty-dir wrapper path is not created: %s", podWrapperMetadataDir) } else { t.Errorf("SetUp() failed: %v", err) } } doTestSecretDataInVolume(volumePath, secret, t) defer doTestCleanAndTeardown(plugin, testPodUID, testVolumeName, volumePath, t) // Metrics only supported on linux metrics, err := mounter.GetMetrics() if runtime.GOOS == "linux" { assert.NotEmpty(t, metrics) assert.NoError(t, err) } else { t.Skipf("Volume metrics not supported on %s", runtime.GOOS) } } func volumeSpec(volumeName, secretName string, defaultMode int32) *v1.Volume { return &v1.Volume{ Name: volumeName, VolumeSource: v1.VolumeSource{ Secret: &v1.SecretVolumeSource{ SecretName: secretName, DefaultMode: &defaultMode, }, }, } } func secret(namespace, name string) v1.Secret { return v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: name, }, Data: map[string][]byte{ "data-1": []byte("value-1"), "data-2": []byte("value-2"), "data-3": []byte("value-3"), }, } } func doTestSecretDataInVolume(volumePath string, secret v1.Secret, t *testing.T) { for key, value := range secret.Data { secretDataHostPath := path.Join(volumePath, key) if _, err := os.Stat(secretDataHostPath); err != nil { t.Fatalf("SetUp() failed, couldn't find secret data on disk: %v", secretDataHostPath) } else { actualSecretBytes, err := ioutil.ReadFile(secretDataHostPath) if err != nil { t.Fatalf("Couldn't read secret data from: %v", secretDataHostPath) } actualSecretValue := string(actualSecretBytes) if string(value) != actualSecretValue { t.Errorf("Unexpected value; expected %q, got %q", value, actualSecretValue) } } } } func doTestCleanAndTeardown(plugin volume.VolumePlugin, podUID types.UID, testVolumeName, volumePath string, t *testing.T) { unmounter, err := plugin.NewUnmounter(testVolumeName, podUID) if err != nil { t.Errorf("Failed to make a new Unmounter: %v", err) } if unmounter == nil { t.Fatalf("Got a nil Unmounter") } if err := unmounter.TearDown(); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(volumePath); err == nil { t.Errorf("TearDown() failed, volume path still exists: %s", volumePath) } else if !os.IsNotExist(err) { t.Errorf("TearDown() failed: %v", err) } }
liangxia/origin
vendor/k8s.io/kubernetes/pkg/volume/secret/secret_test.go
GO
apache-2.0
18,288
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.http; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.TooLongFrameException; /** * Decodes {@link ByteBuf}s into {@link HttpResponse}s and * {@link HttpContent}s. * * <h3>Parameters that prevents excessive memory consumption</h3> * <table border="1"> * <tr> * <th>Name</th><th>Meaning</th> * </tr> * <tr> * <td>{@code maxInitialLineLength}</td> * <td>The maximum length of the initial line (e.g. {@code "HTTP/1.0 200 OK"}) * If the length of the initial line exceeds this value, a * {@link TooLongFrameException} will be raised.</td> * </tr> * <tr> * <td>{@code maxHeaderSize}</td> * <td>The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongFrameException} will be raised.</td> * </tr> * <tr> * <td>{@code maxChunkSize}</td> * <td>The maximum length of the content or each chunk. If the content length * exceeds this value, the transfer encoding of the decoded response will be * converted to 'chunked' and the content will be split into multiple * {@link HttpContent}s. If the transfer encoding of the HTTP response is * 'chunked' already, each chunk will be split into smaller chunks if the * length of the chunk exceeds this value. If you prefer not to handle * {@link HttpContent}s in your handler, insert {@link HttpObjectAggregator} * after this decoder in the {@link ChannelPipeline}.</td> * </tr> * </table> * * <h3>Decoding a response for a <tt>HEAD</tt> request</h3> * <p> * Unlike other HTTP requests, the successful response of a <tt>HEAD</tt> * request does not have any content even if there is <tt>Content-Length</tt> * header. Because {@link HttpResponseDecoder} is not able to determine if the * response currently being decoded is associated with a <tt>HEAD</tt> request, * you must override {@link #isContentAlwaysEmpty(HttpMessage)} to return * <tt>true</tt> for the response of the <tt>HEAD</tt> request. * </p><p> * If you are writing an HTTP client that issues a <tt>HEAD</tt> request, * please use {@link HttpClientCodec} instead of this decoder. It will perform * additional state management to handle the responses for <tt>HEAD</tt> * requests correctly. * </p> * * <h3>Decoding a response for a <tt>CONNECT</tt> request</h3> * <p> * You also need to do additional state management to handle the response of a * <tt>CONNECT</tt> request properly, like you did for <tt>HEAD</tt>. One * difference is that the decoder should stop decoding completely after decoding * the successful 200 response since the connection is not an HTTP connection * anymore. * </p><p> * {@link HttpClientCodec} also handles this edge case correctly, so you have to * use {@link HttpClientCodec} if you are writing an HTTP client that issues a * <tt>CONNECT</tt> request. * </p> */ public class HttpResponseDecoder extends HttpObjectDecoder { private static final HttpResponseStatus UNKNOWN_STATUS = new HttpResponseStatus(999, "Unknown"); /** * Creates a new instance with the default * {@code maxInitialLineLength (4096)}, {@code maxHeaderSize (8192)}, and * {@code maxChunkSize (8192)}. */ public HttpResponseDecoder() { } /** * Creates a new instance with the specified parameters. */ public HttpResponseDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) { super(maxInitialLineLength, maxHeaderSize, maxChunkSize, true); } public HttpResponseDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders) { super(maxInitialLineLength, maxHeaderSize, maxChunkSize, true, validateHeaders); } @Override protected HttpMessage createMessage(String[] initialLine) { return new DefaultHttpResponse( HttpVersion.valueOf(initialLine[0]), new HttpResponseStatus(Integer.parseInt(initialLine[1]), initialLine[2]), validateHeaders); } @Override protected HttpMessage createInvalidMessage() { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, UNKNOWN_STATUS, validateHeaders); } @Override protected boolean isDecodingRequest() { return false; } }
BrunoColin/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseDecoder.java
Java
apache-2.0
4,997
/** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam;
aiuluna/cordova
appDemo/platforms/android/cordova/node_modules/lodash/function/restParam.js
JavaScript
apache-2.0
1,899
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty; import java.io.File; import java.security.Principal; import javax.net.ssl.SSLSession; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry; import org.junit.Test; public class NettySSLTest extends BaseNettyTest { @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry registry = super.createRegistry(); registry.bind("ksf", new File("src/test/resources/keystore.jks")); registry.bind("tsf", new File("src/test/resources/keystore.jks")); return registry; } @Override public boolean isUseRouteBuilder() { return false; } @Test public void testSSLInOutWithNettyConsumer() throws Exception { // ibm jdks dont have sun security algorithms if (isJavaVendor("ibm")) { return; } context.addRoutes(new RouteBuilder() { public void configure() { // needClientAuth=true so we can get the client certificate details from("netty:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf&needClientAuth=true") .process(new Processor() { public void process(Exchange exchange) throws Exception { SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); if (session != null) { javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); log.info("Client Cert SubjectDN: {}", principal.getName()); exchange.getOut().setBody("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today."); } else { exchange.getOut().setBody("Cannot start conversion without SSLSession"); } } }); } }); context.start(); String response = template.requestBody( "netty:tcp://localhost:{{port}}?sync=true&ssl=true&passphrase=changeit&keyStoreFile=#ksf&trustStoreFile=#tsf", "Epitaph in Kohima, India marking the WWII Battle of Kohima and Imphal, Burma Campaign - Attributed to John Maxwell Edmonds", String.class); assertEquals("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.", response); } }
MrCoder/camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettySSLTest.java
Java
apache-2.0
3,551
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { public class StatementGenerationTests : AbstractCodeGenerationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestThrowStatement1() { Test(f => f.ThrowStatement(), cs: "throw;", vb: "Throw"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestThrowStatement2() { Test(f => f.ThrowStatement( f.IdentifierName("e")), cs: "throw e;", vb: "Throw e"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestThrowStatement3() { Test(f => f.ThrowStatement( f.ObjectCreationExpression( CreateClass("NotImplementedException"))), cs: "throw new NotImplementedException();", vb: "Throw New NotImplementedException()"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestReturnStatement1() { Test(f => f.ReturnStatement(), cs: "return;", vb: "Return"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestReturnStatement2() { Test(f => f.ReturnStatement( f.IdentifierName("e")), cs: "return e;", vb: "Return e"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)] public void TestReturnStatement3() { Test(f => f.ReturnStatement( f.ObjectCreationExpression( CreateClass("NotImplementedException"))), cs: "return new NotImplementedException();", vb: "Return New NotImplementedException()"); } } }
KevinH-MS/roslyn
src/EditorFeatures/Test/CodeGeneration/StatementGenerationTests.cs
C#
apache-2.0
2,226
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.language; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringSimpleWeirdIssueTest extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/language/SpringSimpleWeirdIssueTest.xml"); } public void testSimple() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); } }
Thopap/camel
components/camel-spring/src/test/java/org/apache/camel/language/SpringSimpleWeirdIssueTest.java
Java
apache-2.0
1,547
// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package idna_test import ( "fmt" "golang.org/x/net/idna" ) func ExampleProfile() { // Raw Punycode has no restrictions and does no mappings. fmt.Println(idna.ToASCII("")) fmt.Println(idna.ToASCII("*.faß.com")) fmt.Println(idna.Punycode.ToASCII("*.faß.com")) // Rewrite IDN for lookup. This (currently) uses transitional mappings to // find a balance between IDNA2003 and IDNA2008 compatibility. fmt.Println(idna.Lookup.ToASCII("")) fmt.Println(idna.Lookup.ToASCII("www.faß.com")) // Convert an IDN to ASCII for registration purposes. This changes the // encoding, but reports an error if the input was illformed. fmt.Println(idna.Registration.ToASCII("")) fmt.Println(idna.Registration.ToASCII("www.faß.com")) // Output: // <nil> // *.xn--fa-hia.com <nil> // *.xn--fa-hia.com <nil> // <nil> // www.fass.com <nil> // idna: invalid label "" // www.xn--fa-hia.com <nil> } func ExampleNew() { var p *idna.Profile // Raw Punycode has no restrictions and does no mappings. p = idna.New() fmt.Println(p.ToASCII("*.faß.com")) // Do mappings. Note that star is not allowed in a DNS lookup. p = idna.New( idna.MapForLookup(), idna.Transitional(true)) // Map ß -> ss fmt.Println(p.ToASCII("*.faß.com")) // Lookup for registration. Also does not allow '*'. p = idna.New(idna.ValidateForRegistration()) fmt.Println(p.ToUnicode("*.faß.com")) // Set up a profile maps for lookup, but allows wild cards. p = idna.New( idna.MapForLookup(), idna.Transitional(true), // Map ß -> ss idna.StrictDomainName(false)) // Set more permissive ASCII rules. fmt.Println(p.ToASCII("*.faß.com")) // Output: // *.xn--fa-hia.com <nil> // *.fass.com idna: disallowed rune U+002A // *.faß.com idna: disallowed rune U+002A // *.fass.com <nil> }
adhocteam/soapbox
vendor/golang.org/x/net/idna/example_test.go
GO
apache-2.0
2,029