code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=50 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER void foo() {} struct S { S(): a(0) {} S(int v) : a(v) {} int a; typedef int type; }; template <typename T> class S7 : public T { protected: T a; S7() : a(0) {} public: S7(typename T::type v) : a(v) { #pragma omp parallel for private(a) private(this->a) private(T::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S7 &operator=(S7 &s) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < s.a.a; ++k) ++s.a.a; return *this; } }; // CHECK: #pragma omp parallel for private(this->a) private(this->a) private(T::a){{$}} // CHECK: #pragma omp parallel for private(this->a) private(this->a) // CHECK: #pragma omp parallel for private(this->a) private(this->a) private(this->S::a) class S8 : public S7<S> { S8() {} public: S8(int v) : S7<S>(v){ #pragma omp parallel for private(a) private(this->a) private(S7<S>::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S8 &operator=(S8 &s) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < s.a.a; ++k) ++s.a.a; return *this; } }; // CHECK: #pragma omp parallel for private(this->a) private(this->a) private(this->S7<S>::a) // CHECK: #pragma omp parallel for private(this->a) private(this->a) template <class T, int N> T tmain(T argc) { T b = argc, c, d, e, f, h; static T a; // CHECK: static T a; static T g; #pragma omp threadprivate(g) #pragma omp parallel for schedule(dynamic) default(none) copyin(g) linear(a) allocate(a) lastprivate(conditional: d, e,f) order(concurrent) // CHECK: #pragma omp parallel for schedule(dynamic) default(none) copyin(g) linear(a) allocate(a) lastprivate(conditional: d,e,f) order(concurrent) for (int i = 0; i < 2; ++i) a = 2; // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: a = 2; #pragma omp parallel for allocate(argc) private(argc, b), firstprivate(c, d), lastprivate(d, f) collapse(N) schedule(static, N) ordered(N) if (parallel :argc) num_threads(N) default(shared) shared(e) reduction(+ : h) for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) for (int j = 0; j < 2; ++j) foo(); // CHECK-NEXT: #pragma omp parallel for allocate(argc) private(argc,b) firstprivate(c,d) lastprivate(d,f) collapse(N) schedule(static, N) ordered(N) if(parallel: argc) num_threads(N) default(shared) shared(e) reduction(+: h) // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: for (int j = 0; j < 2; ++j) // CHECK-NEXT: foo(); return T(); } int increment () { #pragma omp for for (int i = 5 ; i != 0; ++i) ; // CHECK: int increment() { // CHECK-NEXT: #pragma omp for // CHECK-NEXT: for (int i = 5; i != 0; ++i) // CHECK-NEXT: ; return 0; } int decrement_nowait () { #pragma omp for nowait for (int j = 5 ; j != 0; --j) ; // CHECK: int decrement_nowait() { // CHECK-NEXT: #pragma omp for nowait // CHECK-NEXT: for (int j = 5; j != 0; --j) // CHECK-NEXT: ; return 0; } int main(int argc, char **argv) { int b = argc, c, d, e, f, h; static int a; // CHECK: static int a; static float g; #pragma omp threadprivate(g) #pragma omp parallel for schedule(guided, argc) default(none) copyin(g) linear(a) shared(argc) reduction(task,&:d) // CHECK: #pragma omp parallel for schedule(guided, argc) default(none) copyin(g) linear(a) shared(argc) reduction(task, &: d) for (int i = 0; i < 2; ++i) a = 2; // CHECK-NEXT: for (int i = 0; i < 2; ++i) // CHECK-NEXT: a = 2; #pragma omp parallel for private(argc, b), firstprivate(argv, c), lastprivate(d, f) collapse(2) schedule(auto) ordered if (argc) num_threads(a) default(shared) shared(e) reduction(+ : h) linear(a:-5) for (int i = 0; i < 10; ++i) for (int j = 0; j < 10; ++j) foo(); // CHECK-NEXT: #pragma omp parallel for private(argc,b) firstprivate(argv,c) lastprivate(d,f) collapse(2) schedule(auto) ordered if(argc) num_threads(a) default(shared) shared(e) reduction(+: h) linear(a: -5) // CHECK-NEXT: for (int i = 0; i < 10; ++i) // CHECK-NEXT: for (int j = 0; j < 10; ++j) // CHECK-NEXT: foo(); return (tmain<int, 5>(argc) + tmain<char, 1>(argv[0][0])); } #endif
endlessm/chromium-browser
third_party/llvm/clang/test/OpenMP/parallel_for_ast_print.cpp
C++
bsd-3-clause
5,443
<?php /** * Confirmation Validator * * @author Andres Gutierrez <andres@phalconphp.com> * @author Eduar Carvajal <eduar@phalconphp.com> * @author Wenzel Pünter <wenzel@phelix.me> * @version 1.2.6 * @package Phalcon */ namespace Phalcon\Validation\Validator; use \Phalcon\Validation\Validator; use \Phalcon\Validation\ValidatorInterface; use \Phalcon\Validation\Exception; use \Phalcon\Validation\Message; use \Phalcon\Validation; /** * Phalcon\Validation\Validator\Confirmation * * Checks that two values have the same value * *<code> *use Phalcon\Validation\Validator\Confirmation; * *$validator->add('password', new Confirmation(array( * 'message' => 'Password doesn\'t match confirmation', * 'with' => 'confirmPassword' *))); *</code> * * @see https://github.com/phalcon/cphalcon/blob/1.2.6/ext/validation/validator/confirmation.c */ class Confirmation extends Validator implements ValidatorInterface { /** * Executes the validation * * @param \Phalcon\Validation $validator * @param string $attribute * @return boolean * @throws Exception */ public function validate($validator, $attribute) { if (is_object($validator) === false || $validator instanceof Validation === false) { throw new Exception('Invalid parameter type.'); } if (is_string($attribute) === false) { throw new Exception('Invalid parameter type.'); } $withAttribute = $this->getOption('with'); $value = $validator->getValue($attribute); if ($value !== $withAttribute) { $message = $this->getOption('message'); if (empty($message) === true) { $message = 'Value of \''.$attribute.'\' and \''.$withAttribute.'\' don\'t match'; } $validator->appendMessage(new Message($message, $attribute, 'Confirmation')); return false; } return true; } }
scento/phalcon-php
src/Phalcon/Validation/Validator/Confirmation.php
PHP
bsd-3-clause
1,975
class AlterResponseAndTextToText < ActiveRecord::Migration def self.up change_column :text_histories, :text, :text change_column :text_histories, :response, :text end def self.down change_column :text_histories, :text, :string change_column :text_histories, :response, :string end end
danmelton/chatreach
db/migrate/20110930144605_alter_response_and_text_to_text.rb
Ruby
bsd-3-clause
314
<?php /* * Abraham Williams (abraham@abrah.am) http://abrah.am * * The first PHP Library to support OAuth for Twitter's REST API. Copyright (c) 2009 Abraham Williams - http://abrah.am - abraham@poseurte.ch 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. */ /* Load OAuth lib. You can find it at http://oauth.net */ require_once('OAuth.php'); /** * Twitter OAuth class */ class TwitterOAuth { /* Contains the last HTTP status code returned. */ public $http_code; /* Contains the last API call. */ public $url; /* Set up the API root URL. */ public $host = "https://api.twitter.com/1/"; /* Set timeout default. */ public $timeout = 30; /* Set connect timeout. */ public $connecttimeout = 30; /* Verify SSL Cert. */ public $ssl_verifypeer = FALSE; /* Respons format. */ public $format = 'json'; /* Decode returned json data. */ public $decode_json = TRUE; /* Contains the last HTTP headers returned. */ public $http_info; /* Set the useragnet. */ public $useragent = 'TwitterOAuth v0.2.0-beta2'; /* Immediately retry the API call if the response was not successful. */ //public $retry = TRUE; /** * Set API URLS */ function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; } function authenticateURL() { return 'https://twitter.com/oauth/authenticate'; } function authorizeURL() { return 'https://twitter.com/oauth/authorize'; } function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; } /** * Debug helpers */ function lastStatusCode() { return $this->http_status; } function lastAPICall() { return $this->last_api_call; } /** * construct TwitterOAuth object */ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); if (!empty($oauth_token) && !empty($oauth_token_secret)) { $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret); } else { $this->token = NULL; } } /** * Get a request_token from Twitter * * @returns a key/value array containing oauth_token and oauth_token_secret */ function getRequestToken($oauth_callback = NULL) { $parameters = array(); if (!empty($oauth_callback)) { $parameters['oauth_callback'] = $oauth_callback; } $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * Get the authorize URL * * @returns a string */ function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) { if (is_array($token)) { $token = $token['oauth_token']; } if (empty($sign_in_with_twitter)) { return $this->authorizeURL() . "?oauth_token={$token}"; } else { return $this->authenticateURL() . "?oauth_token={$token}"; } } /** * Exchange request token and secret for an access token and * secret, to sign API calls. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham") */ function getAccessToken($oauth_verifier = FALSE) { $parameters = array(); if (!empty($oauth_verifier)) { $parameters['oauth_verifier'] = $oauth_verifier; } $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * One time exchange of username and password for access token and secret. * * @returns array("oauth_token" => "the-access-token", * "oauth_token_secret" => "the-access-secret", * "user_id" => "9436992", * "screen_name" => "abraham", * "x_auth_expires" => "0") */ function getXAuthToken($username, $password) { $parameters = array(); $parameters['x_auth_username'] = $username; $parameters['x_auth_password'] = $password; $parameters['x_auth_mode'] = 'client_auth'; $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters); $token = OAuthUtil::parse_parameters($request); $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); return $token; } /** * GET wrapper for oAuthRequest. */ function get($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'GET', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * POST wrapper for oAuthRequest. */ function post($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'POST', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * DELETE wrapper for oAuthReqeust. */ function delete($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'DELETE', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; } /** * Format and sign an OAuth / API request */ function oAuthRequest($url, $method, $parameters) { if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) { $url = "{$this->host}{$url}.{$this->format}"; } $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); $request->sign_request($this->sha1_method, $this->consumer, $this->token); switch ($method) { case 'GET': return $this->http($request->to_url(), 'GET'); default: return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata()); } } /** * Make an HTTP request * * @return API results */ function http($url, $method, $postfields = NULL) { $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); curl_setopt($ci, CURLOPT_HEADER, FALSE); switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); $this->url = $url; curl_close ($ci); return $response; } /** * Get the header info to store. */ function getHeader($ch, $header) { $i = strpos($header, ':'); if (!empty($i)) { $key = str_replace('-', '_', strtolower(substr($header, 0, $i))); $value = trim(substr($header, $i + 2)); $this->http_header[$key] = $value; } return strlen($header); } }
cashmusic/Tweet-for-Track
lib/twitteroauth.php
PHP
bsd-3-clause
8,874
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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. */ using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Common base class for inventory nodes of different types (files, folders, etc.) /// </summary> public class InventoryNodeBase { /// <summary> /// The name of the node (64 characters or less) /// </summary> public virtual string Name { get { return m_name; } set { m_name = value; } } private string m_name = string.Empty; /// <summary> /// A UUID containing the ID for the inventory node itself /// </summary> public UUID ID { get { return m_id; } set { m_id = value; } } private UUID m_id; /// <summary> /// The agent who's inventory this is contained by /// </summary> public virtual UUID Owner { get { return m_owner; } set { m_owner = value; } } private UUID m_owner; } }
zekizeki/agentservice
OpenSim/Framework/InventoryNodeBase.cs
C#
bsd-3-clause
2,704
/* * Software License Agreement (BSD License) * * Copyright (c) 2011-2014, Willow Garage, Inc. * Copyright (c) 2014-2016, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Open Source Robotics Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** @author Jia Pan */ #include "fcl/narrowphase/detail/primitive_shape_algorithm/halfspace-inl.h" namespace fcl { namespace detail { //============================================================================== template <> float halfspaceIntersectTolerance() { return 0.0001f; } //============================================================================== template <> double halfspaceIntersectTolerance() { return 0.0000001; } //============================================================================== template bool sphereHalfspaceIntersect( const Sphere<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool ellipsoidHalfspaceIntersect( const Ellipsoid<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool boxHalfspaceIntersect( const Box<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2); //============================================================================== template bool boxHalfspaceIntersect( const Box<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool capsuleHalfspaceIntersect( const Capsule<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool cylinderHalfspaceIntersect( const Cylinder<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool coneHalfspaceIntersect( const Cone<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, std::vector<ContactPoint<double>>* contacts); //============================================================================== template bool convexHalfspaceIntersect( const Convex<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, Vector3<double>* contact_points, double* penetration_depth, Vector3<double>* normal); //============================================================================== template bool halfspaceTriangleIntersect( const Halfspace<double>& s1, const Transform3<double>& tf1, const Vector3<double>& P1, const Vector3<double>& P2, const Vector3<double>& P3, const Transform3<double>& tf2, Vector3<double>* contact_points, double* penetration_depth, Vector3<double>* normal); //============================================================================== template bool planeHalfspaceIntersect( const Plane<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, Plane<double>& pl, Vector3<double>& p, Vector3<double>& d, double& penetration_depth, int& ret); //============================================================================== template bool halfspacePlaneIntersect( const Halfspace<double>& s1, const Transform3<double>& tf1, const Plane<double>& s2, const Transform3<double>& tf2, Plane<double>& pl, Vector3<double>& p, Vector3<double>& d, double& penetration_depth, int& ret); //============================================================================== template bool halfspaceIntersect( const Halfspace<double>& s1, const Transform3<double>& tf1, const Halfspace<double>& s2, const Transform3<double>& tf2, Vector3<double>& p, Vector3<double>& d, Halfspace<double>& s, double& penetration_depth, int& ret); } // namespace detail } // namespace fcl
hsu/fcl
src/narrowphase/detail/primitive_shape_algorithm/halfspace.cpp
C++
bsd-3-clause
6,062
/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007-2008 The Florida State University * Copyright (c) 2009 The University of Edinburgh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Timothy M. Jones * Gabe Black * Stephen Hines */ #ifndef __ARCH_POWER_ISA_TRAITS_HH__ #define __ARCH_POWER_ISA_TRAITS_HH__ #include "arch/power/types.hh" #include "base/types.hh" namespace BigEndianGuest {} class StaticInstPtr; namespace PowerISA { using namespace BigEndianGuest; StaticInstPtr decodeInst(ExtMachInst); // POWER DOES NOT have a delay slot #define ISA_HAS_DELAY_SLOT 0 const Addr PageShift = 12; const Addr PageBytes = ULL(1) << PageShift; const Addr Page_Mask = ~(PageBytes - 1); const Addr PageOffset = PageBytes - 1; const Addr PteShift = 3; const Addr NPtePageShift = PageShift - PteShift; const Addr NPtePage = ULL(1) << NPtePageShift; const Addr PteMask = NPtePage - 1; const int LogVMPageSize = 12; // 4K bytes const int VMPageSize = (1 << LogVMPageSize); const int MachineBytes = 4; // This is ori 0, 0, 0 const ExtMachInst NoopMachInst = 0x60000000; // Memory accesses can be unaligned const bool HasUnalignedMemAcc = true; } // namespace PowerISA #endif // __ARCH_POWER_ISA_TRAITS_HH__
koparasy/faultinjection-gem5
src/arch/power/isa_traits.hh
C++
bsd-3-clause
2,751
# -*- coding: utf-8 -*- """ flaskbb.management.views ~~~~~~~~~~~~~~~~~~~~~~~~ This module handles the management views. :copyright: (c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import sys from flask import (Blueprint, current_app, request, redirect, url_for, flash, jsonify, __version__ as flask_version) from flask_login import current_user, login_fresh from flask_plugins import get_all_plugins, get_plugin, get_plugin_from_all from flask_babelplus import gettext as _ from flask_allows import Permission, Not from flaskbb import __version__ as flaskbb_version from flaskbb._compat import iteritems from flaskbb.forum.forms import UserSearchForm from flaskbb.utils.settings import flaskbb_config from flaskbb.utils.requirements import (IsAtleastModerator, IsAdmin, CanBanUser, CanEditUser, IsAtleastSuperModerator) from flaskbb.extensions import db, allows from flaskbb.utils.helpers import (render_template, time_diff, time_utcnow, get_online_users) from flaskbb.user.models import Guest, User, Group from flaskbb.forum.models import Post, Topic, Forum, Category, Report from flaskbb.management.models import Setting, SettingsGroup from flaskbb.management.forms import (AddUserForm, EditUserForm, AddGroupForm, EditGroupForm, EditForumForm, AddForumForm, CategoryForm) management = Blueprint("management", __name__) @management.before_request def check_fresh_login(): """Checks if the login is fresh for the current user, otherwise the user has to reauthenticate.""" if not login_fresh(): return current_app.login_manager.needs_refresh() @management.route("/") @allows.requires(IsAtleastModerator) def overview(): # user and group stats banned_users = User.query.filter( Group.banned == True, Group.id == User.primary_group_id ).count() if not current_app.config["REDIS_ENABLED"]: online_users = User.query.filter(User.lastseen >= time_diff()).count() else: online_users = len(get_online_users()) stats = { # user stats "all_users": User.query.count(), "banned_users": banned_users, "online_users": online_users, "all_groups": Group.query.count(), # forum stats "report_count": Report.query.count(), "topic_count": Topic.query.count(), "post_count": Post.query.count(), # misc stats "plugins": get_all_plugins(), "python_version": "%s.%s" % (sys.version_info[0], sys.version_info[1]), "flask_version": flask_version, "flaskbb_version": flaskbb_version } return render_template("management/overview.html", **stats) @management.route("/settings", methods=["GET", "POST"]) @management.route("/settings/<path:slug>", methods=["GET", "POST"]) @allows.requires(IsAdmin) def settings(slug=None): slug = slug if slug else "general" # get the currently active group active_group = SettingsGroup.query.filter_by(key=slug).first_or_404() # get all groups - used to build the navigation all_groups = SettingsGroup.query.all() SettingsForm = Setting.get_form(active_group) old_settings = Setting.get_settings(active_group) new_settings = {} form = SettingsForm() if form.validate_on_submit(): for key, values in iteritems(old_settings): try: # check if the value has changed if values['value'] == form[key].data: continue else: new_settings[key] = form[key].data except KeyError: pass Setting.update(settings=new_settings, app=current_app) flash(_("Settings saved."), "success") else: for key, values in iteritems(old_settings): try: form[key].data = values['value'] except (KeyError, ValueError): pass return render_template("management/settings.html", form=form, all_groups=all_groups, active_group=active_group) # Users @management.route("/users", methods=['GET', 'POST']) @allows.requires(IsAtleastModerator) def users(): page = request.args.get("page", 1, type=int) search_form = UserSearchForm() if search_form.validate(): users = search_form.get_results().\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/users.html", users=users, search_form=search_form) users = User.query. \ order_by(User.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/users.html", users=users, search_form=search_form) @management.route("/users/<int:user_id>/edit", methods=["GET", "POST"]) @allows.requires(IsAtleastModerator) def edit_user(user_id): user = User.query.filter_by(id=user_id).first_or_404() if not Permission(CanEditUser, identity=current_user): flash(_("You are not allowed to edit this user."), "danger") return redirect(url_for("management.users")) member_group = db.and_(*[db.not_(getattr(Group, p)) for p in ['admin', 'mod', 'super_mod', 'banned', 'guest']]) filt = db.or_( Group.id.in_(g.id for g in current_user.groups), member_group ) if Permission(IsAtleastSuperModerator, identity=current_user): filt = db.or_(filt, Group.mod) if Permission(IsAdmin, identity=current_user): filt = db.or_(filt, Group.admin, Group.super_mod) if Permission(CanBanUser, identity=current_user): filt = db.or_(filt, Group.banned) group_query = Group.query.filter(filt) form = EditUserForm(user) form.primary_group.query = group_query form.secondary_groups.query = group_query if form.validate_on_submit(): form.populate_obj(user) user.primary_group_id = form.primary_group.data.id # Don't override the password if form.password.data: user.password = form.password.data user.save(groups=form.secondary_groups.data) flash(_("User updated."), "success") return redirect(url_for("management.edit_user", user_id=user.id)) return render_template("management/user_form.html", form=form, title=_("Edit User")) @management.route("/users/delete", methods=["POST"]) @management.route("/users/<int:user_id>/delete", methods=["POST"]) @allows.requires(IsAdmin) def delete_user(user_id=None): # ajax request if request.is_xhr: ids = request.get_json()["ids"] data = [] for user in User.query.filter(User.id.in_(ids)).all(): # do not delete current user if current_user.id == user.id: continue if user.delete(): data.append({ "id": user.id, "type": "delete", "reverse": False, "reverse_name": None, "reverse_url": None }) return jsonify( message="{} users deleted.".format(len(data)), category="success", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() if current_user.id == user.id: flash(_("You cannot delete yourself.", "danger")) return redirect(url_for("management.users")) user.delete() flash(_("User deleted."), "success") return redirect(url_for("management.users")) @management.route("/users/add", methods=["GET", "POST"]) @allows.requires(IsAdmin) def add_user(): form = AddUserForm() if form.validate_on_submit(): form.save() flash(_("User added."), "success") return redirect(url_for("management.users")) return render_template("management/user_form.html", form=form, title=_("Add User")) @management.route("/users/banned", methods=["GET", "POST"]) @allows.requires(IsAtleastModerator) def banned_users(): page = request.args.get("page", 1, type=int) search_form = UserSearchForm() users = User.query.filter( Group.banned == True, Group.id == User.primary_group_id ).paginate(page, flaskbb_config['USERS_PER_PAGE'], False) if search_form.validate(): users = search_form.get_results().\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/banned_users.html", users=users, search_form=search_form) return render_template("management/banned_users.html", users=users, search_form=search_form) @management.route("/users/ban", methods=["POST"]) @management.route("/users/<int:user_id>/ban", methods=["POST"]) @allows.requires(IsAtleastModerator) def ban_user(user_id=None): if not Permission(CanBanUser, identity=current_user): flash(_("You do not have the permissions to ban this user."), "danger") return redirect(url_for("management.overview")) # ajax request if request.is_xhr: ids = request.get_json()["ids"] data = [] users = User.query.filter(User.id.in_(ids)).all() for user in users: # don't let a user ban himself and do not allow a moderator to ban # a admin user if ( current_user.id == user.id or Permission(IsAdmin, identity=user) and Permission(Not(IsAdmin), current_user) ): continue elif user.ban(): data.append({ "id": user.id, "type": "ban", "reverse": "unban", "reverse_name": _("Unban"), "reverse_url": url_for("management.unban_user", user_id=user.id) }) return jsonify( message="{} users banned.".format(len(data)), category="success", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() # Do not allow moderators to ban admins if Permission(IsAdmin, identity=user) and \ Permission(Not(IsAdmin), identity=current_user): flash(_("A moderator cannot ban an admin user."), "danger") return redirect(url_for("management.overview")) if not current_user.id == user.id and user.ban(): flash(_("User is now banned."), "success") else: flash(_("Could not ban user."), "danger") return redirect(url_for("management.banned_users")) @management.route("/users/unban", methods=["POST"]) @management.route("/users/<int:user_id>/unban", methods=["POST"]) @allows.requires(IsAtleastModerator) def unban_user(user_id=None): if not Permission(CanBanUser, identity=current_user): flash(_("You do not have the permissions to unban this user."), "danger") return redirect(url_for("management.overview")) # ajax request if request.is_xhr: ids = request.get_json()["ids"] data = [] for user in User.query.filter(User.id.in_(ids)).all(): if user.unban(): data.append({ "id": user.id, "type": "unban", "reverse": "ban", "reverse_name": _("Ban"), "reverse_url": url_for("management.ban_user", user_id=user.id) }) return jsonify( message="{} users unbanned.".format(len(data)), category="success", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() if user.unban(): flash(_("User is now unbanned."), "success") else: flash(_("Could not unban user."), "danger") return redirect(url_for("management.banned_users")) # Reports @management.route("/reports") @allows.requires(IsAtleastModerator) def reports(): page = request.args.get("page", 1, type=int) reports = Report.query.\ order_by(Report.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/reports.html", reports=reports) @management.route("/reports/unread") @allows.requires(IsAtleastModerator) def unread_reports(): page = request.args.get("page", 1, type=int) reports = Report.query.\ filter(Report.zapped == None).\ order_by(Report.id.desc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/unread_reports.html", reports=reports) @management.route("/reports/<int:report_id>/markread", methods=["POST"]) @management.route("/reports/markread", methods=["POST"]) @allows.requires(IsAtleastModerator) def report_markread(report_id=None): # AJAX request if request.is_xhr: ids = request.get_json()["ids"] data = [] for report in Report.query.filter(Report.id.in_(ids)).all(): report.zapped_by = current_user.id report.zapped = time_utcnow() report.save() data.append({ "id": report.id, "type": "read", "reverse": False, "reverse_name": None, "reverse_url": None }) return jsonify( message="{} reports marked as read.".format(len(data)), category="success", data=data, status=200 ) # mark single report as read if report_id: report = Report.query.filter_by(id=report_id).first_or_404() if report.zapped: flash(_("Report %(id)s is already marked as read.", id=report.id), "success") return redirect(url_for("management.reports")) report.zapped_by = current_user.id report.zapped = time_utcnow() report.save() flash(_("Report %(id)s marked as read.", id=report.id), "success") return redirect(url_for("management.reports")) # mark all as read reports = Report.query.filter(Report.zapped == None).all() report_list = [] for report in reports: report.zapped_by = current_user.id report.zapped = time_utcnow() report_list.append(report) db.session.add_all(report_list) db.session.commit() flash(_("All reports were marked as read."), "success") return redirect(url_for("management.reports")) # Groups @management.route("/groups") @allows.requires(IsAdmin) def groups(): page = request.args.get("page", 1, type=int) groups = Group.query.\ order_by(Group.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template("management/groups.html", groups=groups) @management.route("/groups/<int:group_id>/edit", methods=["GET", "POST"]) @allows.requires(IsAdmin) def edit_group(group_id): group = Group.query.filter_by(id=group_id).first_or_404() form = EditGroupForm(group) if form.validate_on_submit(): form.populate_obj(group) group.save() if group.guest: Guest.invalidate_cache() flash(_("Group updated."), "success") return redirect(url_for("management.groups", group_id=group.id)) return render_template("management/group_form.html", form=form, title=_("Edit Group")) @management.route("/groups/<int:group_id>/delete", methods=["POST"]) @management.route("/groups/delete", methods=["POST"]) @allows.requires(IsAdmin) def delete_group(group_id=None): if request.is_xhr: ids = request.get_json()["ids"] if not (set(ids) & set(["1", "2", "3", "4", "5"])): data = [] for group in Group.query.filter(Group.id.in_(ids)).all(): group.delete() data.append({ "id": group.id, "type": "delete", "reverse": False, "reverse_name": None, "reverse_url": None }) return jsonify( message="{} groups deleted.".format(len(data)), category="success", data=data, status=200 ) return jsonify( message=_("You cannot delete one of the standard groups."), category="danger", data=None, status=404 ) if group_id is not None: if group_id <= 5: # there are 5 standard groups flash(_("You cannot delete the standard groups. " "Try renaming it instead.", "danger")) return redirect(url_for("management.groups")) group = Group.query.filter_by(id=group_id).first_or_404() group.delete() flash(_("Group deleted."), "success") return redirect(url_for("management.groups")) flash(_("No group chosen."), "danger") return redirect(url_for("management.groups")) @management.route("/groups/add", methods=["GET", "POST"]) @allows.requires(IsAdmin) def add_group(): form = AddGroupForm() if form.validate_on_submit(): form.save() flash(_("Group added."), "success") return redirect(url_for("management.groups")) return render_template("management/group_form.html", form=form, title=_("Add Group")) # Forums and Categories @management.route("/forums") @allows.requires(IsAdmin) def forums(): categories = Category.query.order_by(Category.position.asc()).all() return render_template("management/forums.html", categories=categories) @management.route("/forums/<int:forum_id>/edit", methods=["GET", "POST"]) @allows.requires(IsAdmin) def edit_forum(forum_id): forum = Forum.query.filter_by(id=forum_id).first_or_404() form = EditForumForm(forum) if form.validate_on_submit(): form.save() flash(_("Forum updated."), "success") return redirect(url_for("management.edit_forum", forum_id=forum.id)) else: if forum.moderators: form.moderators.data = ",".join([ user.username for user in forum.moderators ]) else: form.moderators.data = None return render_template("management/forum_form.html", form=form, title=_("Edit Forum")) @management.route("/forums/<int:forum_id>/delete", methods=["POST"]) @allows.requires(IsAdmin) def delete_forum(forum_id): forum = Forum.query.filter_by(id=forum_id).first_or_404() involved_users = User.query.filter(Topic.forum_id == forum.id, Post.user_id == User.id).all() forum.delete(involved_users) flash(_("Forum deleted."), "success") return redirect(url_for("management.forums")) @management.route("/forums/add", methods=["GET", "POST"]) @management.route("/forums/<int:category_id>/add", methods=["GET", "POST"]) @allows.requires(IsAdmin) def add_forum(category_id=None): form = AddForumForm() if form.validate_on_submit(): form.save() flash(_("Forum added."), "success") return redirect(url_for("management.forums")) else: form.groups.data = Group.query.order_by(Group.id.asc()).all() if category_id: category = Category.query.filter_by(id=category_id).first() form.category.data = category return render_template("management/forum_form.html", form=form, title=_("Add Forum")) @management.route("/category/add", methods=["GET", "POST"]) @allows.requires(IsAdmin) def add_category(): form = CategoryForm() if form.validate_on_submit(): form.save() flash(_("Category added."), "success") return redirect(url_for("management.forums")) return render_template("management/category_form.html", form=form, title=_("Add Category")) @management.route("/category/<int:category_id>/edit", methods=["GET", "POST"]) @allows.requires(IsAdmin) def edit_category(category_id): category = Category.query.filter_by(id=category_id).first_or_404() form = CategoryForm(obj=category) if form.validate_on_submit(): form.populate_obj(category) flash(_("Category updated."), "success") category.save() return render_template("management/category_form.html", form=form, title=_("Edit Category")) @management.route("/category/<int:category_id>/delete", methods=["POST"]) @allows.requires(IsAdmin) def delete_category(category_id): category = Category.query.filter_by(id=category_id).first_or_404() involved_users = User.query.filter(Forum.category_id == category.id, Topic.forum_id == Forum.id, Post.user_id == User.id).all() category.delete(involved_users) flash(_("Category with all associated forums deleted."), "success") return redirect(url_for("management.forums")) # Plugins @management.route("/plugins") @allows.requires(IsAdmin) def plugins(): plugins = get_all_plugins() return render_template("management/plugins.html", plugins=plugins) @management.route("/plugins/<path:plugin>/enable", methods=["POST"]) @allows.requires(IsAdmin) def enable_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.enabled: flash(_("Plugin %(plugin)s is already enabled.", plugin=plugin.name), "info") return redirect(url_for("management.plugins")) try: plugin.enable() flash(_("Plugin %(plugin)s enabled. Please restart FlaskBB now.", plugin=plugin.name), "success") except OSError: flash(_("It seems that FlaskBB does not have enough filesystem " "permissions. Try removing the 'DISABLED' file by " "yourself instead."), "danger") return redirect(url_for("management.plugins")) @management.route("/plugins/<path:plugin>/disable", methods=["POST"]) @allows.requires(IsAdmin) def disable_plugin(plugin): try: plugin = get_plugin(plugin) except KeyError: flash(_("Plugin %(plugin)s not found.", plugin=plugin.name), "danger") return redirect(url_for("management.plugins")) try: plugin.disable() flash(_("Plugin %(plugin)s disabled. Please restart FlaskBB now.", plugin=plugin.name), "success") except OSError: flash(_("It seems that FlaskBB does not have enough filesystem " "permissions. Try creating the 'DISABLED' file by " "yourself instead."), "danger") return redirect(url_for("management.plugins")) @management.route("/plugins/<path:plugin>/uninstall", methods=["POST"]) @allows.requires(IsAdmin) def uninstall_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.uninstallable: plugin.uninstall() Setting.invalidate_cache() flash(_("Plugin has been uninstalled."), "success") else: flash(_("Cannot uninstall plugin."), "danger") return redirect(url_for("management.plugins")) @management.route("/plugins/<path:plugin>/install", methods=["POST"]) @allows.requires(IsAdmin) def install_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.installable and not plugin.uninstallable: plugin.install() Setting.invalidate_cache() flash(_("Plugin has been installed."), "success") else: flash(_("Cannot install plugin."), "danger") return redirect(url_for("management.plugins"))
realityone/flaskbb
flaskbb/management/views.py
Python
bsd-3-clause
24,085
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_version_info.h" #include "base/basictypes.h" #include "base/file_version_info.h" #include "base/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "build/build_config.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" // Generated header #include "chrome/common/chrome_release_version_info.h" namespace chrome { #if defined(OS_WIN) || defined(OS_MACOSX) // On Windows and Mac, we get the Chrome version info by querying // FileVersionInfo for the current module. VersionInfo::VersionInfo() { // The current module is already loaded in memory, so this will be cheap. base::ThreadRestrictions::ScopedAllowIO allow_io; version_info_.reset(FileVersionInfo::CreateFileVersionInfoForCurrentModule()); } VersionInfo::~VersionInfo() { } bool VersionInfo::is_valid() const { return version_info_.get() != NULL; } std::string VersionInfo::Name() const { if (!is_valid()) return std::string(); return UTF16ToUTF8(version_info_->product_name()); } std::string VersionInfo::Version() const { if (!is_valid()) return std::string(); return UTF16ToUTF8(version_info_->product_version()); } std::string VersionInfo::LastChange() const { if (!is_valid()) return std::string(); return UTF16ToUTF8(version_info_->last_change()); } bool VersionInfo::IsOfficialBuild() const { if (!is_valid()) return false; return version_info_->is_official_build(); } #elif defined(OS_POSIX) // We get chrome version information from chrome_version_info_posix.h, // a generated header. #include "chrome/common/chrome_version_info_posix.h" VersionInfo::VersionInfo() { } VersionInfo::~VersionInfo() { } bool VersionInfo::is_valid() const { return true; } std::string VersionInfo::Name() const { return PRODUCT_NAME; } std::string VersionInfo::Version() const { return PRODUCT_VERSION; } std::string VersionInfo::LastChange() const { return LAST_CHANGE; } bool VersionInfo::IsOfficialBuild() const { return IS_OFFICIAL_BUILD; } #endif std::string VersionInfo::CreateVersionString() const { std::string current_version; if (is_valid()) { current_version += Version(); #if 0 current_version += " ("; current_version += l10n_util::GetStringUTF8(IDS_ABOUT_VERSION_UNOFFICIAL); current_version += " "; current_version += LastChange(); current_version += " "; current_version += OSType(); current_version += ")"; #endif std::string modifier = GetVersionStringModifier(); if (!modifier.empty()) current_version += " " + modifier; } return current_version; } std::string VersionInfo::OSType() const { #if defined(OS_WIN) return "Windows"; #elif defined(OS_MACOSX) return "Mac OS X"; #elif defined(OS_CHROMEOS) if (ui::ResourceBundle::HasSharedInstance()) return UTF16ToASCII(l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_OS_NAME)); else return "Chromium OS"; #elif defined(OS_ANDROID) return "Android"; #elif defined(OS_LINUX) return "Linux"; #elif defined(OS_FREEBSD) return "FreeBSD"; #elif defined(OS_OPENBSD) return "OpenBSD"; #elif defined(OS_SOLARIS) return "Solaris"; #else return "Unknown"; #endif } std::string VersionInfo::ChromiumReleaseVersion() const { return CHROMIUM_RELEASE_VERSION; } } // namespace chrome
leiferikb/bitpop-private
chrome/common/chrome_version_info.cc
C++
bsd-3-clause
3,604
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/kernel/user_module.h" #include <vector> #include "xenia/base/byte_stream.h" #include "xenia/base/logging.h" #include "xenia/cpu/elf_module.h" #include "xenia/cpu/processor.h" #include "xenia/cpu/xex_module.h" #include "xenia/emulator.h" #include "xenia/kernel/xfile.h" #include "xenia/kernel/xthread.h" namespace xe { namespace kernel { UserModule::UserModule(KernelState* kernel_state) : XModule(kernel_state, ModuleType::kUserModule) {} UserModule::~UserModule() { Unload(); } uint32_t UserModule::title_id() const { if (module_format_ != kModuleFormatXex) { return 0; } auto header = xex_header(); for (uint32_t i = 0; i < header->header_count; i++) { auto& opt_header = header->headers[i]; if (opt_header.key == XEX_HEADER_EXECUTION_INFO) { auto opt_header_ptr = reinterpret_cast<const uint8_t*>(header) + opt_header.offset; auto opt_exec_info = reinterpret_cast<const xex2_opt_execution_info*>(opt_header_ptr); return static_cast<uint32_t>(opt_exec_info->title_id); } } return 0; } X_STATUS UserModule::LoadFromFile(std::string path) { X_STATUS result = X_STATUS_UNSUCCESSFUL; // Resolve the file to open. // TODO(benvanik): make this code shared? auto fs_entry = kernel_state()->file_system()->ResolvePath(path); if (!fs_entry) { XELOGE("File not found: %s", path.c_str()); return X_STATUS_NO_SUCH_FILE; } path_ = fs_entry->absolute_path(); name_ = NameFromPath(path_); // If the FS supports mapping, map the file in and load from that. if (fs_entry->can_map()) { // Map. auto mmap = fs_entry->OpenMapped(MappedMemory::Mode::kRead); if (!mmap) { return result; } // Load the module. result = LoadFromMemory(mmap->data(), mmap->size()); } else { std::vector<uint8_t> buffer(fs_entry->size()); // Open file for reading. vfs::File* file = nullptr; result = fs_entry->Open(vfs::FileAccess::kGenericRead, &file); if (XFAILED(result)) { return result; } // Read entire file into memory. // Ugh. size_t bytes_read = 0; result = file->ReadSync(buffer.data(), buffer.size(), 0, &bytes_read); if (XFAILED(result)) { return result; } // Load the module. result = LoadFromMemory(buffer.data(), bytes_read); // Close the file. file->Destroy(); } return result; } X_STATUS UserModule::LoadFromMemory(const void* addr, const size_t length) { auto processor = kernel_state()->processor(); auto magic = xe::load_and_swap<uint32_t>(addr); if (magic == 'XEX2') { module_format_ = kModuleFormatXex; } else if (magic == 0x7F454C46 /* 0x7F 'ELF' */) { module_format_ = kModuleFormatElf; } else { XELOGE("Unknown module magic: %.8X", magic); return X_STATUS_NOT_IMPLEMENTED; } if (module_format_ == kModuleFormatXex) { // Prepare the module for execution. // Runtime takes ownership. auto xex_module = std::make_unique<cpu::XexModule>(processor, kernel_state()); if (!xex_module->Load(name_, path_, addr, length)) { return X_STATUS_UNSUCCESSFUL; } processor_module_ = xex_module.get(); if (!processor->AddModule(std::move(xex_module))) { return X_STATUS_UNSUCCESSFUL; } // Copy the xex2 header into guest memory. auto header = this->xex_module()->xex_header(); auto security_header = this->xex_module()->xex_security_info(); guest_xex_header_ = memory()->SystemHeapAlloc(header->header_size); uint8_t* xex_header_ptr = memory()->TranslateVirtual(guest_xex_header_); std::memcpy(xex_header_ptr, header, header->header_size); // Setup the loader data entry auto ldr_data = memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(hmodule_ptr_); ldr_data->dll_base = 0; // GetProcAddress will read this. ldr_data->xex_header_base = guest_xex_header_; ldr_data->full_image_size = security_header->image_size; this->xex_module()->GetOptHeader(XEX_HEADER_ENTRY_POINT, &ldr_data->entry_point); xe::be<uint32_t>* image_base_ptr = nullptr; if (this->xex_module()->GetOptHeader(XEX_HEADER_IMAGE_BASE_ADDRESS, &image_base_ptr)) { ldr_data->image_base = *image_base_ptr; } // Cache some commonly used headers... this->xex_module()->GetOptHeader(XEX_HEADER_ENTRY_POINT, &entry_point_); this->xex_module()->GetOptHeader(XEX_HEADER_DEFAULT_STACK_SIZE, &stack_size_); is_dll_module_ = !!(header->module_flags & XEX_MODULE_DLL_MODULE); } else if (module_format_ == kModuleFormatElf) { auto elf_module = std::make_unique<cpu::ElfModule>(processor, kernel_state()); if (!elf_module->Load(name_, path_, addr, length)) { return X_STATUS_UNSUCCESSFUL; } entry_point_ = elf_module->entry_point(); stack_size_ = 1024 * 1024; // 1 MB is_dll_module_ = false; // Hardcoded not a DLL (for now) processor_module_ = elf_module.get(); if (!processor->AddModule(std::move(elf_module))) { return X_STATUS_UNSUCCESSFUL; } } OnLoad(); return X_STATUS_SUCCESS; } X_STATUS UserModule::Unload() { if (module_format_ == kModuleFormatXex && (!processor_module_ || !xex_module()->loaded())) { // Quick abort. return X_STATUS_SUCCESS; } if (module_format_ == kModuleFormatXex && processor_module_ && xex_module()->Unload()) { OnUnload(); return X_STATUS_SUCCESS; } return X_STATUS_UNSUCCESSFUL; } uint32_t UserModule::GetProcAddressByOrdinal(uint16_t ordinal) { return xex_module()->GetProcAddress(ordinal); } uint32_t UserModule::GetProcAddressByName(const char* name) { return xex_module()->GetProcAddress(name); } X_STATUS UserModule::GetSection(const char* name, uint32_t* out_section_data, uint32_t* out_section_size) { xex2_opt_resource_info* resource_header = nullptr; if (!cpu::XexModule::GetOptHeader(xex_header(), XEX_HEADER_RESOURCE_INFO, &resource_header)) { // No resources. return X_STATUS_NOT_FOUND; } uint32_t count = (resource_header->size - 4) / sizeof(xex2_resource); for (uint32_t i = 0; i < count; i++) { auto& res = resource_header->resources[i]; if (std::strncmp(name, res.name, 8) == 0) { // Found! *out_section_data = res.address; *out_section_size = res.size; return X_STATUS_SUCCESS; } } return X_STATUS_NOT_FOUND; } X_STATUS UserModule::GetOptHeader(xe_xex2_header_keys key, void** out_ptr) { assert_not_null(out_ptr); if (module_format_ == kModuleFormatElf) { // Quick die. return X_STATUS_UNSUCCESSFUL; } bool ret = xex_module()->GetOptHeader(key, out_ptr); if (!ret) { return X_STATUS_NOT_FOUND; } return X_STATUS_SUCCESS; } X_STATUS UserModule::GetOptHeader(xe_xex2_header_keys key, uint32_t* out_header_guest_ptr) { if (module_format_ == kModuleFormatElf) { // Quick die. return X_STATUS_UNSUCCESSFUL; } auto header = memory()->TranslateVirtual<const xex2_header*>(guest_xex_header_); if (!header) { return X_STATUS_UNSUCCESSFUL; } return GetOptHeader(memory()->virtual_membase(), header, key, out_header_guest_ptr); } X_STATUS UserModule::GetOptHeader(uint8_t* membase, const xex2_header* header, xe_xex2_header_keys key, uint32_t* out_header_guest_ptr) { assert_not_null(out_header_guest_ptr); uint32_t field_value = 0; bool field_found = false; for (uint32_t i = 0; i < header->header_count; i++) { auto& opt_header = header->headers[i]; if (opt_header.key != key) { continue; } field_found = true; switch (opt_header.key & 0xFF) { case 0x00: // Return data stored in header value. field_value = opt_header.value; break; case 0x01: // Return pointer to data stored in header value. field_value = static_cast<uint32_t>( reinterpret_cast<const uint8_t*>(&opt_header.value) - membase); break; default: // Data stored at offset to header. field_value = static_cast<uint32_t>( reinterpret_cast<const uint8_t*>(header) - membase) + opt_header.offset; break; } break; } *out_header_guest_ptr = field_value; if (!field_found) { return X_STATUS_NOT_FOUND; } return X_STATUS_SUCCESS; } object_ref<XThread> UserModule::Launch(uint32_t flags) { XELOGI("Launching module..."); // Create a thread to run in. // We start suspended so we can run the debugger prep. auto thread = object_ref<XThread>( new XThread(kernel_state(), stack_size_, 0, entry_point_, 0, X_CREATE_SUSPENDED, true, true)); // We know this is the 'main thread'. char thread_name[32]; std::snprintf(thread_name, xe::countof(thread_name), "Main XThread%08X", thread->handle()); thread->set_name(thread_name); X_STATUS result = thread->Create(); if (XFAILED(result)) { XELOGE("Could not create launch thread: %.8X", result); return nullptr; } // Waits for a debugger client, if desired. if (emulator()->debugger()) { emulator()->debugger()->PreLaunch(); } // Resume the thread now. // If the debugger has requested a suspend this will just decrement the // suspend count without resuming it until the debugger wants. thread->Resume(); return thread; } bool UserModule::Save(ByteStream* stream) { if (!XModule::Save(stream)) { return false; } // A lot of the information stored on this class can be reconstructed at // runtime. return true; } object_ref<UserModule> UserModule::Restore(KernelState* kernel_state, ByteStream* stream, std::string path) { auto module = new UserModule(kernel_state); // XModule::Save took care of this earlier... // TODO: Find a nicer way to represent that here. if (!module->RestoreObject(stream)) { return nullptr; } auto result = module->LoadFromFile(path); if (XFAILED(result)) { XELOGD("UserModule::Restore LoadFromFile(%s) FAILED - code %.8X", path.c_str(), result); return nullptr; } if (!kernel_state->RegisterUserModule(retain_object(module))) { // Already loaded? assert_always(); } return object_ref<UserModule>(module); } void UserModule::Dump() { if (module_format_ == kModuleFormatElf) { // Quick die. return; } StringBuffer sb; xe::cpu::ExportResolver* export_resolver = kernel_state_->emulator()->export_resolver(); auto header = xex_header(); // XEX header. sb.AppendFormat("Module %s:\n", path_.c_str()); sb.AppendFormat(" Module Flags: %.8X\n", (uint32_t)header->module_flags); // Security header auto security_info = xex_module()->xex_security_info(); sb.AppendFormat("Security Header:\n"); sb.AppendFormat(" Image Flags: %.8X\n", (uint32_t)security_info->image_flags); sb.AppendFormat(" Load Address: %.8X\n", (uint32_t)security_info->load_address); sb.AppendFormat(" Image Size: %.8X\n", (uint32_t)security_info->image_size); sb.AppendFormat(" Export Table: %.8X\n", (uint32_t)security_info->export_table); // Optional headers sb.AppendFormat("Optional Header Count: %d\n", (uint32_t)header->header_count); for (uint32_t i = 0; i < header->header_count; i++) { auto& opt_header = header->headers[i]; // Stash a pointer (although this isn't used in every case) auto opt_header_ptr = reinterpret_cast<const uint8_t*>(header) + opt_header.offset; switch (opt_header.key) { case XEX_HEADER_RESOURCE_INFO: { sb.AppendFormat(" XEX_HEADER_RESOURCE_INFO:\n"); auto opt_resource_info = reinterpret_cast<const xex2_opt_resource_info*>(opt_header_ptr); uint32_t count = (opt_resource_info->size - 4) / 16; for (uint32_t j = 0; j < count; j++) { auto& res = opt_resource_info->resources[j]; // Manually NULL-terminate the name. char name[9]; std::memcpy(name, res.name, sizeof(res.name)); name[8] = 0; sb.AppendFormat( " %-8s %.8X-%.8X, %db\n", name, (uint32_t)res.address, (uint32_t)res.address + (uint32_t)res.size, (uint32_t)res.size); } } break; case XEX_HEADER_FILE_FORMAT_INFO: { sb.AppendFormat(" XEX_HEADER_FILE_FORMAT_INFO (TODO):\n"); } break; case XEX_HEADER_DELTA_PATCH_DESCRIPTOR: { sb.AppendFormat(" XEX_HEADER_DELTA_PATCH_DESCRIPTOR (TODO):\n"); } break; case XEX_HEADER_BOUNDING_PATH: { auto opt_bound_path = reinterpret_cast<const xex2_opt_bound_path*>(opt_header_ptr); sb.AppendFormat(" XEX_HEADER_BOUNDING_PATH: %s\n", opt_bound_path->path); } break; case XEX_HEADER_ORIGINAL_BASE_ADDRESS: { sb.AppendFormat(" XEX_HEADER_ORIGINAL_BASE_ADDRESS: %.8X\n", (uint32_t)opt_header.value); } break; case XEX_HEADER_ENTRY_POINT: { sb.AppendFormat(" XEX_HEADER_ENTRY_POINT: %.8X\n", (uint32_t)opt_header.value); } break; case XEX_HEADER_IMAGE_BASE_ADDRESS: { sb.AppendFormat(" XEX_HEADER_IMAGE_BASE_ADDRESS: %.8X\n", (uint32_t)opt_header.value); } break; case XEX_HEADER_IMPORT_LIBRARIES: { sb.AppendFormat(" XEX_HEADER_IMPORT_LIBRARIES:\n"); auto opt_import_libraries = reinterpret_cast<const xex2_opt_import_libraries*>(opt_header_ptr); // FIXME: Don't know if 32 is the actual limit, but haven't seen more // than 2. const char* string_table[32]; std::memset(string_table, 0, sizeof(string_table)); // Parse the string table for (size_t l = 0, j = 0; l < opt_import_libraries->string_table_size; j++) { assert_true(j < xe::countof(string_table)); const char* str = opt_import_libraries->string_table + l; string_table[j] = str; l += std::strlen(str) + 1; // Padding if ((l % 4) != 0) { l += 4 - (l % 4); } } auto libraries = reinterpret_cast<const uint8_t*>(opt_import_libraries) + opt_import_libraries->string_table_size + 12; uint32_t library_offset = 0; uint32_t library_count = opt_import_libraries->library_count; for (uint32_t l = 0; l < library_count; l++) { auto library = reinterpret_cast<const xex2_import_library*>( libraries + library_offset); auto name = string_table[library->name_index & 0xFF]; sb.AppendFormat(" %s - %d imports\n", name, (uint16_t)library->count); // Manually byteswap these because of the bitfields. xex2_version version, version_min; version.value = xe::byte_swap<uint32_t>(library->version.value); version_min.value = xe::byte_swap<uint32_t>(library->version_min.value); sb.AppendFormat(" Version: %d.%d.%d.%d\n", version.major, version.minor, version.build, version.qfe); sb.AppendFormat(" Min Version: %d.%d.%d.%d\n", version_min.major, version_min.minor, version_min.build, version_min.qfe); library_offset += library->size; } } break; case XEX_HEADER_CHECKSUM_TIMESTAMP: { sb.AppendFormat(" XEX_HEADER_CHECKSUM_TIMESTAMP (TODO):\n"); } break; case XEX_HEADER_ORIGINAL_PE_NAME: { auto opt_pe_name = reinterpret_cast<const xex2_opt_original_pe_name*>(opt_header_ptr); sb.AppendFormat(" XEX_HEADER_ORIGINAL_PE_NAME: %s\n", opt_pe_name->name); } break; case XEX_HEADER_STATIC_LIBRARIES: { sb.AppendFormat(" XEX_HEADER_STATIC_LIBRARIES:\n"); auto opt_static_libraries = reinterpret_cast<const xex2_opt_static_libraries*>(opt_header_ptr); uint32_t count = (opt_static_libraries->size - 4) / 0x10; for (uint32_t l = 0; l < count; l++) { auto& library = opt_static_libraries->libraries[l]; sb.AppendFormat(" %-8s : %d.%d.%d.%d\n", library.name, static_cast<uint16_t>(library.version_major), static_cast<uint16_t>(library.version_minor), static_cast<uint16_t>(library.version_build), static_cast<uint16_t>(library.version_qfe)); } } break; case XEX_HEADER_TLS_INFO: { sb.AppendFormat(" XEX_HEADER_TLS_INFO:\n"); auto opt_tls_info = reinterpret_cast<const xex2_opt_tls_info*>(opt_header_ptr); sb.AppendFormat(" Slot Count: %d\n", static_cast<uint32_t>(opt_tls_info->slot_count)); sb.AppendFormat(" Raw Data Address: %.8X\n", static_cast<uint32_t>(opt_tls_info->raw_data_address)); sb.AppendFormat(" Data Size: %d\n", static_cast<uint32_t>(opt_tls_info->data_size)); sb.AppendFormat(" Raw Data Size: %d\n", static_cast<uint32_t>(opt_tls_info->raw_data_size)); } break; case XEX_HEADER_DEFAULT_STACK_SIZE: { sb.AppendFormat(" XEX_HEADER_DEFAULT_STACK_SIZE: %d\n", static_cast<uint32_t>(opt_header.value)); } break; case XEX_HEADER_DEFAULT_FILESYSTEM_CACHE_SIZE: { sb.AppendFormat(" XEX_HEADER_DEFAULT_FILESYSTEM_CACHE_SIZE: %d\n", static_cast<uint32_t>(opt_header.value)); } break; case XEX_HEADER_DEFAULT_HEAP_SIZE: { sb.AppendFormat(" XEX_HEADER_DEFAULT_HEAP_SIZE: %d\n", static_cast<uint32_t>(opt_header.value)); } break; case XEX_HEADER_PAGE_HEAP_SIZE_AND_FLAGS: { sb.AppendFormat(" XEX_HEADER_PAGE_HEAP_SIZE_AND_FLAGS (TODO):\n"); } break; case XEX_HEADER_SYSTEM_FLAGS: { sb.AppendFormat(" XEX_HEADER_SYSTEM_FLAGS: %.8X\n", static_cast<uint32_t>(opt_header.value)); } break; case XEX_HEADER_EXECUTION_INFO: { sb.AppendFormat(" XEX_HEADER_EXECUTION_INFO:\n"); auto opt_exec_info = reinterpret_cast<const xex2_opt_execution_info*>(opt_header_ptr); sb.AppendFormat(" Media ID: %.8X\n", static_cast<uint32_t>(opt_exec_info->media_id)); sb.AppendFormat(" Title ID: %.8X\n", static_cast<uint32_t>(opt_exec_info->title_id)); sb.AppendFormat(" Savegame ID: %.8X\n", static_cast<uint32_t>(opt_exec_info->title_id)); sb.AppendFormat(" Disc Number / Total: %d / %d\n", opt_exec_info->disc_number, opt_exec_info->disc_count); } break; case XEX_HEADER_TITLE_WORKSPACE_SIZE: { sb.AppendFormat(" XEX_HEADER_TITLE_WORKSPACE_SIZE: %d\n", uint32_t(opt_header.value)); } break; case XEX_HEADER_GAME_RATINGS: { sb.AppendFormat(" XEX_HEADER_GAME_RATINGS (TODO):\n"); } break; case XEX_HEADER_LAN_KEY: { sb.AppendFormat(" XEX_HEADER_LAN_KEY:"); auto opt_lan_key = reinterpret_cast<const xex2_opt_lan_key*>(opt_header_ptr); for (int l = 0; l < 16; l++) { sb.AppendFormat(" %.2X", opt_lan_key->key[l]); } sb.Append("\n"); } break; case XEX_HEADER_XBOX360_LOGO: { sb.AppendFormat(" XEX_HEADER_XBOX360_LOGO (TODO):\n"); } break; case XEX_HEADER_MULTIDISC_MEDIA_IDS: { sb.AppendFormat(" XEX_HEADER_MULTIDISC_MEDIA_IDS (TODO):\n"); } break; case XEX_HEADER_ALTERNATE_TITLE_IDS: { sb.AppendFormat(" XEX_HEADER_ALTERNATE_TITLE_IDS (TODO):\n"); } break; case XEX_HEADER_ADDITIONAL_TITLE_MEMORY: { sb.AppendFormat(" XEX_HEADER_ADDITIONAL_TITLE_MEMORY: %d\n", uint32_t(opt_header.value)); } break; case XEX_HEADER_EXPORTS_BY_NAME: { sb.AppendFormat(" XEX_HEADER_EXPORTS_BY_NAME:\n"); auto dir = reinterpret_cast<const xex2_opt_data_directory*>(opt_header_ptr); auto exe_address = xex_module()->xex_security_info()->load_address; auto e = memory()->TranslateVirtual<const X_IMAGE_EXPORT_DIRECTORY*>( exe_address + dir->offset); auto e_base = reinterpret_cast<uintptr_t>(e); // e->AddressOfX RVAs are relative to the IMAGE_EXPORT_DIRECTORY! auto function_table = reinterpret_cast<const uint32_t*>(e_base + e->AddressOfFunctions); // Names relative to directory. auto name_table = reinterpret_cast<const uint32_t*>(e_base + e->AddressOfNames); // Table of ordinals (by name). auto ordinal_table = reinterpret_cast<const uint16_t*>( e_base + e->AddressOfNameOrdinals); for (uint32_t n = 0; n < e->NumberOfNames; n++) { auto name = reinterpret_cast<const char*>(e_base + name_table[n]); uint16_t ordinal = ordinal_table[n]; uint32_t addr = exe_address + function_table[ordinal]; sb.AppendFormat(" %-28s - %.3X - %.8X\n", name, ordinal, addr); } } break; default: { sb.AppendFormat(" Unknown Header %.8X\n", (uint32_t)opt_header.key); } break; } } sb.AppendFormat("Sections:\n"); for (uint32_t i = 0, page = 0; i < security_info->page_descriptor_count; i++) { // Manually byteswap the bitfield data. xex2_page_descriptor page_descriptor; page_descriptor.value = xe::byte_swap(security_info->page_descriptors[i].value); const char* type = "UNKNOWN"; switch (page_descriptor.info) { case XEX_SECTION_CODE: type = "CODE "; break; case XEX_SECTION_DATA: type = "RWDATA "; break; case XEX_SECTION_READONLY_DATA: type = "RODATA "; break; } const uint32_t page_size = security_info->load_address < 0x90000000 ? 64 * 1024 : 4 * 1024; uint32_t start_address = security_info->load_address + (page * page_size); uint32_t end_address = start_address + (page_descriptor.size * page_size); sb.AppendFormat(" %3u %s %3u pages %.8X - %.8X (%d bytes)\n", page, type, page_descriptor.size, start_address, end_address, page_descriptor.size * page_size); page += page_descriptor.size; } // Print out imports. // TODO(benvanik): figure out a way to remove dependency on old xex header. auto old_header = xe_xex2_get_header(xex_module()->xex()); sb.AppendFormat("Imports:\n"); for (size_t n = 0; n < old_header->import_library_count; n++) { const xe_xex2_import_library_t* library = &old_header->import_libraries[n]; xe_xex2_import_info_t* import_infos; size_t import_info_count; if (!xe_xex2_get_import_infos(xex_module()->xex(), library, &import_infos, &import_info_count)) { sb.AppendFormat(" %s - %lld imports\n", library->name, import_info_count); sb.AppendFormat(" Version: %d.%d.%d.%d\n", library->version.major, library->version.minor, library->version.build, library->version.qfe); sb.AppendFormat(" Min Version: %d.%d.%d.%d\n", library->min_version.major, library->min_version.minor, library->min_version.build, library->min_version.qfe); sb.AppendFormat("\n"); // Counts. int known_count = 0; int unknown_count = 0; int impl_count = 0; int unimpl_count = 0; for (size_t m = 0; m < import_info_count; m++) { const xe_xex2_import_info_t* info = &import_infos[m]; if (kernel_state_->IsKernelModule(library->name)) { auto kernel_export = export_resolver->GetExportByOrdinal(library->name, info->ordinal); if (kernel_export) { known_count++; if (kernel_export->is_implemented()) { impl_count++; } else { unimpl_count++; } } else { unknown_count++; unimpl_count++; } } else { auto module = kernel_state_->GetModule(library->name); if (module) { uint32_t export_addr = module->GetProcAddressByOrdinal(info->ordinal); if (export_addr) { impl_count++; known_count++; } else { unimpl_count++; unknown_count++; } } else { unimpl_count++; unknown_count++; } } } float total_count = static_cast<float>(import_info_count) / 100.0f; sb.AppendFormat(" Total: %4llu\n", import_info_count); sb.AppendFormat(" Known: %3d%% (%d known, %d unknown)\n", static_cast<int>(known_count / total_count), known_count, unknown_count); sb.AppendFormat( " Implemented: %3d%% (%d implemented, %d unimplemented)\n", static_cast<int>(impl_count / total_count), impl_count, unimpl_count); sb.AppendFormat("\n"); // Listing. for (size_t m = 0; m < import_info_count; m++) { const xe_xex2_import_info_t* info = &import_infos[m]; const char* name = "UNKNOWN"; bool implemented = false; cpu::Export* kernel_export = nullptr; if (kernel_state_->IsKernelModule(library->name)) { kernel_export = export_resolver->GetExportByOrdinal(library->name, info->ordinal); if (kernel_export) { name = kernel_export->name; implemented = kernel_export->is_implemented(); } } else { auto module = kernel_state_->GetModule(library->name); if (module && module->GetProcAddressByOrdinal(info->ordinal)) { // TODO(benvanik): name lookup. implemented = true; } } if (kernel_export && kernel_export->type == cpu::Export::Type::kVariable) { sb.AppendFormat(" V %.8X %.3X (%3d) %s %s\n", info->value_address, info->ordinal, info->ordinal, implemented ? " " : "!!", name); } else if (info->thunk_address) { sb.AppendFormat(" F %.8X %.8X %.3X (%3d) %s %s\n", info->value_address, info->thunk_address, info->ordinal, info->ordinal, implemented ? " " : "!!", name); } } } sb.AppendFormat("\n"); } xe::LogLine('i', sb.GetString()); } } // namespace kernel } // namespace xe
galek/xenia
src/xenia/kernel/user_module.cc
C++
bsd-3-clause
27,968
var $box = $('.box'); var F = {}; F.getMousePos = function(e, $relaveDom) { var x = 0; var y = 0; if (!e) { var e = window.event; } if (e.pageX || e.pageY) { x = e.pageX; y = e.pageY; } else if (e.clientX || e.clientY) { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } if($relaveDom) { var offset = $relaveDom.offset(); x -= offset.left; y -= offset.top; } return {x:x, y:y}; }; var batteryWater = function(opts){ var self = this; this.opts = $.extend({ dom: '', content: [], color: {} }, opts) this.$dom = this.opts.dom; this.content = this.opts.content; this.timeScale = this.opts.timeScale; this.color = this.opts.color; this.canvas = this.$dom.find('canvas'); this.width = this.$dom.width(); this.height = this.$dom.height(); this.ctx = this.canvas.get(0).getContext('2d'); var pi = Math.PI; var o_x = 30.5; //原点坐标 var o_y = 185.5; var scale_width = 700; var each_width = parseInt(scale_width/(2 * this.timeScale.length)); var each_height = 25; var scale_height = each_height * 6; var point_radius = 2.5; //小点半径 var o_temp = 25; //原点坐标的起始温度 var y_height = 0; //每个点在动画过程中的纵坐标 var arr_pos = []; //存储每个点的坐标 this.makeScale = function(){ var ctx = this.ctx; ctx.save(); ctx.translate(o_x, o_y); //温度数字 ctx.beginPath(); ctx.font = '10px Arial'; ctx.fillStyle = self.color.gray; ctx.textBaseline = 'middle'; ctx.textAlign = 'right'; ctx.fillText(o_temp, -10, 0); ctx.closePath(); //温度横线 ctx.beginPath(); for( var i=1; i<7; i++){ ctx.fillText(o_temp + 5 * i , -10, -i * each_height); ctx.moveTo(0, -i * each_height); ctx.lineTo(scale_width, -i * each_height); } ctx.lineWidth = 1; ctx.strokeStyle = self.color.l_gray; ctx.stroke(); ctx.closePath(); ctx.restore(); }; this.drawTemp = function(y_height){ var ctx = this.ctx; ctx.save(); ctx.translate(o_x, o_y); for(var i=0; i<self.content.length; i++){ var temp_x = i * each_width; var ny = self.content[i].values - o_temp; var temp_y = -ny * 5 * y_height; if( i != self.content.length - 1 ){ var nny = self.content[i+1].values - o_temp; var temp_ny = -nny * 5 * y_height; } if( y_height >= 1 ){ arr_pos.push({x: temp_x, y: temp_y, values: self.content[i].values}); } //温度区间块 ctx.beginPath(); ctx.moveTo( temp_x, 0); ctx.lineTo( temp_x, temp_y); ctx.lineTo( (i+1) * each_width, temp_ny); ctx.lineTo( (i+1) * each_width, 0); ctx.lineTo( temp_x, 0); ctx.fillStyle = 'rgba(89, 103, 107, 0.05)'; ctx.fill(); ctx.closePath(); //竖线 ctx.beginPath(); ctx.moveTo(temp_x, 0); ctx.lineTo(temp_x, temp_y); ctx.strokeStyle = self.color.l_gray; ctx.lineWidth = 1; ctx.stroke(); ctx.closePath(); //点与点之间的连线(除了最后一个点); if( i != self.content.length - 1 ){ ctx.beginPath(); ctx.moveTo(temp_x, temp_y); ctx.lineTo( (i+1) * each_width, temp_ny); ctx.strokeStyle = self.color.black; ctx.lineWidth = 1; ctx.stroke(); ctx.closePath(); } //温度圆点的白色底 ctx.beginPath(); ctx.arc(temp_x, temp_y, point_radius-0.5, 0, 2*pi); ctx.fillStyle = '#fff'; ctx.fill(); ctx.closePath(); //温度圆点 ctx.beginPath(); ctx.arc(temp_x, temp_y, point_radius-0.5, 0, 2*pi); ctx.strokeStyle = self.color.black; ctx.stroke(); ctx.closePath(); } ctx.restore(); }; this.makeOy = function(){ var ctx = this.ctx; ctx.save(); ctx.translate(o_x, o_y); ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(scale_width, 0); ctx.strokeStyle = self.color.black; ctx.stroke(); ctx.closePath(); ctx.beginPath(); for(var i=0; i<this.timeScale.length; i++){ ctx.font = '10px Arial'; ctx.textAlign = 'center'; ctx.fillStyle = self.color.black; ctx.fillText(this.timeScale[i], (2 * i + 1)* each_width, 20); } ctx.closePath(); ctx.beginPath(); for(var j=0; j<2 * this.timeScale.length + 1; j+=2){ ctx.arc(j * each_width, 0, point_radius, 0, 2*pi); ctx.fillStyle = self.color.black; } ctx.fill(); ctx.closePath(); ctx.restore(); }; //鼠标悬浮 this.makeHover = function(pos){ var ctx = this.ctx; ctx.save(); ctx.translate(o_x, o_y); ctx.beginPath(); ctx.arc(pos.x, pos.y, point_radius+0.5, 0, 2*pi); ctx.fillStyle = '#fff'; ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.arc(pos.x, pos.y, point_radius+0.5, 0, 2*pi); ctx.strokeStyle = self.color.blue; ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(pos.x, pos.y, 1.5, 0, 2*pi); ctx.fillStyle = self.color.blue; ctx.fill(); ctx.closePath(); var r = 2; //圆角半径 var r_width = 36; //正方体框宽度 var r_height = 16; //正方体框高度 var a_width = 7; //小箭头宽度 var a_height = 3; //小箭头高度 var radius = 10; //温度数字框 ctx.beginPath(); var a_x = Math.floor(pos.x) - 0.5; var a_y = Math.floor(pos.y) - 25.5; ctx.moveTo(a_x, a_y); ctx.arcTo(r_width/2 + a_x, a_y, r_width/2 + a_x, 1 - a_y, r); ctx.arcTo(r_width/2 + a_x, r_height + a_y, r_width/2 + a_x - 1, r_height + a_y, r); ctx.lineTo( a_width/2 + a_x, r_height + a_y); ctx.lineTo( a_x, r_height + a_height + a_y); ctx.lineTo( a_x - a_width/2, r_height + a_y); ctx.arcTo(a_x - r_width/2, r_height + a_y, a_x - r_width/2, r_height + a_y - 1, r); ctx.arcTo(a_x - r_width/2, a_y, a_x - r_width/2 + 1, a_y, r); ctx.lineTo(a_x, a_y); ctx.fillStyle = self.color.blue; ctx.fill(); ctx.font = '12px Arial'; //ctx.font = '12px "Helvitica Neue" lighter'; //ctx.font = '12px "Helvitica Neue", Helvitica, Arial, "Microsoft YaHei", sans-serif lighter'; ctx.textAlign = 'center'; ctx.fillStyle = '#fff'; ctx.fillText(pos.values, a_x, Math.floor(pos.y) - 13); ctx.closePath(); ctx.restore(); }; this.run = function(){ if( y_height < 100 ){ y_height += 2; self.ctx.clearRect(0, 0, self.width, self.height); self.makeScale(); self.drawTemp(y_height/100); self.makeOy(); self.animation = requestAnimationFrame(self.run); } else { cancelAnimationFrame(this.animation); } }; this.animation = requestAnimationFrame(this.run); this.canvas.on('mousemove', function(ev){ if( y_height >= 100 ){ var mouse = F.getMousePos(ev, $(this)); //相对于原点的坐标轴位置 var pos = { x: mouse.x - o_x, y: mouse.y - o_y }; var now_one = Math.ceil( (pos.x - each_width/2) / each_width); if( pos.x > 0 && pos.y < 0 ){ self.ctx.clearRect(0, 0, self.width, self.height); self.makeScale(); self.drawTemp(1); self.makeOy(); self.makeHover(arr_pos[now_one]); } } }); }; var drawWater = new batteryWater({ dom: $box, timeScale: ['网络视频', '本地视频','电子书', '微博', '拍照', '游戏', '微信', '网页', '通话', '音乐'], content: [ {name: '起始点亮', values: '29.20'}, {name: '网络视频1', values: '33.30'}, {name: '网络视频2', values: '33.60'}, {name: '本地视频1', values: '32.50'}, {name: '本地视频2', values: '31.80'}, {name: '电子书1', values: '33.30'}, {name: '电子书2', values: '32.50'}, {name: '微博1', values: '33.40'}, {name: '微博2', values: '33.70'}, {name: '拍照1', values: '37.30'}, {name: '拍照2', values: '38.30'}, {name: '游戏1', values: '38.50'}, {name: '游戏2', values: '38.00'}, {name: '微信1', values: '35.60'}, {name: '微信2', values: '40.00'}, {name: '网页1', values: '40.00'}, {name: '网页2', values: '33.20'}, {name: '通话1', values: '29.50'}, {name: '通话2', values: '29.60'}, {name: '音乐1', values: '37.00'}, {name: '音乐2', values: '37.00'}, ], color: { blue: '#0096ff', green: '#44be05', yellow: '#ffc411', red: '#f86117', black: '#59676b', gray: '#b3b3b3', l_gray: '#e2e5e7' } });
comlewod/document
pages/lab_test/xian.js
JavaScript
bsd-3-clause
8,132
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Stdlib; use ArrayAccess; use Countable; use IteratorAggregate; use Serializable; /** * Custom framework ArrayObject implementation * * Extends version-specific "abstract" implementation. */ class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Countable { /** * Properties of the object have their normal functionality * when accessed as list (var_dump, foreach, etc.). */ const STD_PROP_LIST = 1; /** * Entries can be accessed as properties (read and write). */ const ARRAY_AS_PROPS = 2; /** * @var array */ protected $storage; /** * @var int */ protected $flag; /** * @var string */ protected $iteratorClass; /** * @var array */ protected $protectedProperties; /** * Constructor * * @param array $input * @param int $flags * @param string $iteratorClass */ public function __construct($input = array(), $flags = self::STD_PROP_LIST, $iteratorClass = 'ArrayIterator') { $this->setFlags($flags); $this->storage = $input; $this->setIteratorClass($iteratorClass); $this->protectedProperties = array_keys(get_object_vars($this)); } /** * Returns whether the requested key exists * * @param mixed $key * @return bool */ public function __isset($key) { if ($this->flag == self::ARRAY_AS_PROPS) { return $this->offsetExists($key); } if (in_array($key, $this->protectedProperties)) { throw new Exception\InvalidArgumentException('$key is a protected property, use a different key'); } return isset($this->$key); } /** * Sets the value at the specified key to value * * @param mixed $key * @param mixed $value * @return void */ public function __set($key, $value) { if ($this->flag == self::ARRAY_AS_PROPS) { return $this->offsetSet($key, $value); } if (in_array($key, $this->protectedProperties)) { throw new Exception\InvalidArgumentException('$key is a protected property, use a different key'); } $this->$key = $value; } /** * Unsets the value at the specified key * * @param mixed $key * @return void */ public function __unset($key) { if ($this->flag == self::ARRAY_AS_PROPS) { return $this->offsetUnset($key); } if (in_array($key, $this->protectedProperties)) { throw new Exception\InvalidArgumentException('$key is a protected property, use a different key'); } unset($this->$key); } /** * Returns the value at the specified key by reference * * @param mixed $key * @return mixed */ public function &__get($key) { $ret = null; if ($this->flag == self::ARRAY_AS_PROPS) { $ret =& $this->offsetGet($key); return $ret; } if (in_array($key, $this->protectedProperties)) { throw new Exception\InvalidArgumentException('$key is a protected property, use a different key'); } return $this->$key; } /** * Appends the value * * @param mixed $value * @return void */ public function append($value) { $this->storage[] = $value; } /** * Sort the entries by value * * @return void */ public function asort() { asort($this->storage); } /** * Get the number of public properties in the ArrayObject * * @return int */ public function count() { return count($this->storage); } /** * Exchange the array for another one. * * @param array|ArrayObject $data * @return array */ public function exchangeArray($data) { if (!is_array($data) && !is_object($data)) { throw new Exception\InvalidArgumentException('Passed variable is not an array or object, using empty array instead'); } if (is_object($data) && ($data instanceof self || $data instanceof \ArrayObject)) { $data = $data->getArrayCopy(); } if (!is_array($data)) { $data = (array) $data; } $storage = $this->storage; $this->storage = $data; return $storage; } /** * Creates a copy of the ArrayObject. * * @return array */ public function getArrayCopy() { return $this->storage; } /** * Gets the behavior flags. * * @return int */ public function getFlags() { return $this->flag; } /** * Create a new iterator from an ArrayObject instance * * @return \Iterator */ public function getIterator() { $class = $this->iteratorClass; return new $class($this->storage); } /** * Gets the iterator classname for the ArrayObject. * * @return string */ public function getIteratorClass() { return $this->iteratorClass; } /** * Sort the entries by key * * @return void */ public function ksort() { ksort($this->storage); } /** * Sort an array using a case insensitive "natural order" algorithm * * @return void */ public function natcasesort() { natcasesort($this->storage); } /** * Sort entries using a "natural order" algorithm * * @return void */ public function natsort() { natsort($this->storage); } /** * Returns whether the requested key exists * * @param mixed $key * @return bool */ public function offsetExists($key) { return isset($this->storage[$key]); } /** * Returns the value at the specified key * * @param mixed $key * @return mixed */ public function &offsetGet($key) { $ret = null; if (!$this->offsetExists($key)) { return $ret; } $ret =& $this->storage[$key]; return $ret; } /** * Sets the value at the specified key to value * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value) { $this->storage[$key] = $value; } /** * Unsets the value at the specified key * * @param mixed $key * @return void */ public function offsetUnset($key) { if ($this->offsetExists($key)) { unset($this->storage[$key]); } } /** * Serialize an ArrayObject * * @return string */ public function serialize() { return serialize(get_object_vars($this)); } /** * Sets the behavior flags * * @param int $flags * @return void */ public function setFlags($flags) { $this->flag = $flags; } /** * Sets the iterator classname for the ArrayObject * * @param string $class * @return void */ public function setIteratorClass($class) { if (class_exists($class)) { $this->iteratorClass = $class; return ; } if (strpos($class, '\\') === 0) { $class = '\\' . $class; if (class_exists($class)) { $this->iteratorClass = $class; return ; } } throw new Exception\InvalidArgumentException('The iterator class does not exist'); } /** * Sort the entries with a user-defined comparison function and maintain key association * * @param callable $function * @return void */ public function uasort($function) { if (is_callable($function)) { uasort($this->storage, $function); } } /** * Sort the entries by keys using a user-defined comparison function * * @param callable $function * @return void */ public function uksort($function) { if (is_callable($function)) { uksort($this->storage, $function); } } /** * Unserialize an ArrayObject * * @param string $data * @return void */ public function unserialize($data) { $ar = unserialize($data); $this->protectedProperties = array_keys(get_object_vars($this)); $this->setFlags($ar['flag']); $this->exchangeArray($ar['storage']); $this->setIteratorClass($ar['iteratorClass']); foreach ($ar as $k => $v) { switch ($k) { case 'flag': $this->setFlags($v); break; case 'storage': $this->exchangeArray($v); break; case 'iteratorClass': $this->setIteratorClass($v); break; case 'protectedProperties': continue; default: $this->__set($k, $v); } } } }
ishvaram/email-app
vendor/ZF2/library/Zend/Stdlib/ArrayObject.php
PHP
bsd-3-clause
10,069
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model backend\models\MasterKk */ $this->title = $model->master_kk_id; $this->params['breadcrumbs'][] = ['label' => 'Master Kks', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="master-kk-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->master_kk_id], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->master_kk_id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'master_kk_id', 'NIK', 'NAMA', 'TGL_LAHIR', 'ALAMAT_RUMAH', 'KOTA_RUMAH', 'vESG', 'TGL_MASUK', 'TGL_PENSIUN', 'TGL_CAPEG', 'BAND_POSISI', 'KLAS_POSISI', 'cDIVISI', 'vDIVISI', 'LOKASI_KERJA', 'PERSONALAREA', 'PERSONALSUBAREA', 'PENETAPAN_TPK_BERDASARKAN_TELECONFERENCE', 'PERSADMIN', 'YAKES_AREA', 'NO_KARTU_KELUARGA', 'NO_KTP', 'NO_BPJS', ], ]) ?> </div>
santhika29/yakes-app
frontend/views/master-kk/view.php
PHP
bsd-3-clause
1,506
/*! * jQuery JavaScript Library v2.2.4 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-05-20T17:23Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) //"use strict"; var arr = []; var document = window.document; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "2.2.4", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) var realStringObj = obj && obj.toString(); return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; }, isPlainObject: function( obj ) { var key; // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call( obj, "constructor" ) && !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a globals context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf( "use strict" ) === 1 ) { script = document.createElement( "script" ); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect globals eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A globals GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this globals in .jshintrc would create a danger of using the globals // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: iOS 8.2 (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-17 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, nidselect, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { groups[i] = nidselect + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update globals variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( (parent = document.defaultView) && parent.top !== parent ) { // Support: IE 11 if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( (oldCache = uniqueCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[ 0 ] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( pos ? pos.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], [ "notify", "progress", jQuery.Callbacks( "memory" ) ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. // If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .progress( updateFunc( i, progressContexts, progressValues ) ) .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } } ); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } } ); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE9-10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { register: function( owner, initial ) { var value = initial || {}; // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable, non-writable property // configurability must be true to allow the property to be // deleted with the delete operator } else { Object.defineProperty( owner, this.expando, { value: value, writable: true, configurable: true } ); } return owner[ this.expando ]; }, cache: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( !acceptData( owner ) ) { return {}; } // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ prop ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : owner[ this.expando ] && owner[ this.expando ][ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase( key ) ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key === undefined ) { this.register( owner ); } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <= 35-45+ // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://code.google.com/p/chromium/issues/detail?id=378607 if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data, camelKey; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = dataUser.get( elem, key ) || // Try to find dashed key if it exists (gh-2779) // This is for 2.2.x only dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); if ( data !== undefined ) { return data; } camelKey = jQuery.camelCase( key ); // Attempt to get data from the cache // with the key camelized data = dataUser.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... camelKey = jQuery.camelCase( key ); this.each( function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = dataUser.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* dataUser.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf( "-" ) > -1 && data !== undefined ) { dataUser.set( this, key, value ); } } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([\w:-]+)/ ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE9 option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE9-11+ // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0-4.3, Safari<=5.1 // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE9 // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support (at least): Chrome, IE9 // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // // Support: Firefox<=42+ // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push( { elem: cur, handlers: matches } ); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split( " " ), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + "screenX screenY toElement" ).split( " " ), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://code.google.com/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, // Support: IE 10-11, Edge 10240+ // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName( "tbody" )[ 0 ] || elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <= 35-45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <= 35-45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { // Keep domManip exposed until 3.0 (gh-2225) domManip: domManip, detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var iframe, elemdisplay = { // Support: Firefox // We have to pre-define these values for FF (#10227) HTML: "block", BODY: "block" }; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) ) .appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var documentElement = document.documentElement; ( function() { var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE9-11+ // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); } jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelMarginRight: function() { // Support: Android 4.0-4.3 // We're checking for boxSizingReliableVal here instead of pixelMarginRightVal // since that compresses better and they're computed together anyway. if ( boxSizingReliableVal == null ) { computeStyleTests(); } return pixelMarginRightVal; }, reliableMarginLeft: function() { // Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37 if ( boxSizingReliableVal == null ) { computeStyleTests(); } return reliableMarginLeftVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;box-sizing:content-box;" + "display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; documentElement.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight ); documentElement.removeChild( container ); div.removeChild( marginDiv ); return ret; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; // Support: Opera 12.1x only // Fall back to style even without computed // computed is undefined for elems on document fragments if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: IE9 // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // http://dev.w3.org/csswg/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE9-11+ // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = dataPriv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = dataPriv.access( elem, "olddisplay", defaultDisplay( elem.nodeName ) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { dataPriv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // Support: IE9-11+ // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { return swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? dataPriv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show // and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", {} ); } // Store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done( function() { jQuery( elem ).hide(); } ); } anim.done( function() { var prop; dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnotwhite ); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { window.clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS<=5.1, Android<=4.2+ // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE<=11+ // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: Android<=2.3 // Options inside disabled selects are incorrectly marked as disabled select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<=11+ // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); var rclass = /[\t\r\n\f]/g; function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnotwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + getClass( elem ) + " " ).replace( rclass, " " ) .indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g, rspaces = /[\x20\t\r\n\f]+/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace( rreturn, "" ) : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a globals ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where globals variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome, Safari // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // To know if globals events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for globals events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ).replace( rhash, "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE8-11+ // IE throws exception if url is malformed, e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE8-11+ // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire globals events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send globals event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( state === 2 ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the globals AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapAll( html.call( this, i ) ); } ); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function() { return this.parent().each( function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } } ).end(); } } ); jQuery.expr.filters.hidden = function( elem ) { return !jQuery.expr.filters.visible( elem ); }; jQuery.expr.filters.visible = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements // Use OR instead of AND as the element is not visible if either is true // See tickets #10406 and #13132 return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem.getClientRects().length > 0; }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE9 // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE9 // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).prop( { charset: s.scriptCharset, src: s.url } ).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } box = elem.getBoundingClientRect(); win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari<7-8+, Chrome<37-44+ // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, size: function() { return this.length; } } ); jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the globals so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a globals if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; } ); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
gorobetssergey/dashboard
vendor/bower/jquery/dist/jquery.js
JavaScript
bsd-3-clause
257,566
/* * $Id: PlotMark.java,v 1.1 2004/12/27 16:15:20 luca Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt; import java.awt.Component; import java.awt.Graphics; import java.awt.BorderLayout; import java.awt.FontMetrics; import java.awt.Font; import java.awt.Color; import javax.swing.*; import gov.noaa.pmel.util.Dimension2D; /** * Support class used to draw a PlotMark. Plot mark codes are defined * in the following table. <br> * * <P ALIGN="CENTER"><IMG SRC="plotmarkcodes.gif" ALIGN="BOTTOM" BORDER="0"> * * @author Donald Denbo * @version $Revision: 1.1 $, $Date: 2004/12/27 16:15:20 $ * @since 2.0 * @see PointCartesianRenderer * @see gov.noaa.pmel.sgt.swing.PlotMarkIcon */ public class PlotMark { protected int mark_; protected int tableSize_ = 51; protected int firstPoint_; protected int lastPoint_; protected double markHeight_; protected int fillMark_ = 44; protected boolean fill_ = false; protected boolean circle_ = false; protected static final int[][] markTable = {{ 5, 9}, { 11, 15}, { 14, 15}, { 11, 12}, // 0 { 26, 31}, { 32, 37}, { 38, 43}, { 44, 49}, // 4 { 1, 5}, { 64, 67}, { 5, 15}, { 50, 54}, // 8 { 1, 9}, { 55, 63}, { 15, 19}, { 21, 25}, // 12 { 50, 53}, { 51, 54}, { 72, 77}, { 84, 98}, // 16 { 18, 22}, { 11, 19}, { 64, 66}, { 68, 71}, // 20 { 68, 70}, { 78, 83}, {102, 106}, {113, 118}, // 24 {119, 124}, {125, 130}, {131, 136}, {105, 110}, // 28 {107, 112}, {137, 139}, { 99, 106}, {103, 108}, // 32 {140, 144}, {140, 147}, {156, 163}, {148, 155}, // 36 {170, 183}, {184, 189}, {188, 193}, {164, 169}, // 40 { 1, 5}, { 64, 67}, { 55, 63}, { 15, 19}, // 44 { 68, 71}, {164, 169}, {164, 169}}; // 48 protected static final int[] table = { 9, 41, 45, 13, 9, 45, 0, 13, 41, 0, // 0 25, 29, 0, 11, 43, 29, 11, 25, 43, 11, // 10 25, 29, 11, 43, 29, 18, 27, 34, 0, 27, // 20 24, 20, 27, 36, 0, 27, 30, 20, 27, 18, // 30 0, 3, 27, 36, 27, 34, 0, 27, 51, 41, // 40 13, 45, 9, 41, 4, 2, 16, 32, 50, 52, // 50 38, 22, 4, 9, 29, 41, 9, 13, 25, 45, // 60 13, 13, 27, 31, 0, 27, 45, 9, 27, 29, // 70 0, 27, 41, 13, 20, 18, 9, 0, 18, 34, // 80 0, 20, 36, 0, 45, 36, 34, 41, 19, 35, // 90 0, 21, 17, 33, 37, 21, 19, 35, 33, 17, // 100 21, 37, 20, 29, 25, 0, 17, 33, 21, 37, // 110 35, 19, 17, 33, 21, 37, 19, 35, 33, 17, // 120 21, 19, 43, 0, 37, 33, 21, 37, 25, 12, // 130 44, 0, 42, 10, 0, 17, 37, 26, 30, 0, // 140 12, 44, 0, 8, 40, 13, 45, 0, 43, 11, // 150 0, 9, 41, 4, 41, 30, 9, 52, 4, 12, // 160 20, 21, 13, 12, 0, 9, 45, 0, 33, 41, // 170 42, 34, 33, 14, 44, 10, 0, 9, 41, 0, // 180 42, 12, 46, 0, 0, 0, 0, 0, 0, 0}; // 190 /** * Construct a <code>PlotMark</code> using the code and height from the * <code>LineAttribute</code>. */ public PlotMark(LineAttribute attr) { setLineAttribute(attr); } /** * Construct a <code>PlotMark</code> using the code and height from the * <code>PointAttribute</code>. */ public PlotMark(PointAttribute attr) { setPointAttribute(attr); } /** * Construct a <code>PlotMark</code> using the code from the * mark code. Default height = 0.08. */ public PlotMark(int mark) { setMark(mark); markHeight_ = 0.08; } /** * Set the mark and height from the <code>PointAttribute</code>. */ public void setPointAttribute(PointAttribute attr) { int mark = attr.getMark(); setMark(mark); markHeight_ = attr.getMarkHeightP()/8.0; } /** * Set the mark and height from the <code>LineAttribute</code>. */ public void setLineAttribute(LineAttribute attr) { int mark = attr.getMark(); setMark(mark); markHeight_ = attr.getMarkHeightP()/8.0; } /** * Set the mark. */ public void setMark(int mark) { if(mark <= 0) mark = 0; fill_ = mark > fillMark_; circle_ = mark >= 50; if(circle_) fill_ = mark == 51; if(mark > tableSize_) mark = tableSize_; firstPoint_ = markTable[mark-1][0]-1; lastPoint_ = markTable[mark-1][1]; mark_ = mark; } /** * Get the mark code. */ public int getMark() { return mark_; } /** * Set the mark height. */ public void setMarkHeightP(double mHeight) { markHeight_ = mHeight/8.0; } /** * Get the mark height */ public double getMarkHeightP() { return markHeight_*8.0; } /** * Used internally by sgt. */ public void paintMark(Graphics g, Layer ly, int xp, int yp) { int count, ib; int xdOld = 0, ydOld = 0; int movex, movey; int xt, yt; double xscl = ly.getXSlope()*markHeight_; double yscl = ly.getYSlope()*markHeight_; if(circle_) { xt = (int)(xscl*-2) + xp; yt = (int)(xscl*-2) + yp; int w = (int)(xscl*4.0) - 1; if(fill_) { g.fillOval(xt, yt, w, w); } else { g.drawOval(xt, yt, w, w); } return; } int[] xl = new int[lastPoint_-firstPoint_]; int[] yl = new int[lastPoint_-firstPoint_]; boolean penf = false; int i=0; for(count = firstPoint_; count < lastPoint_; count++) { ib = table[count]; if(ib == 0) { penf = false; } else { movex = (ib>>3) - 3; movey = -((ib&7) - 3); xt = (int)(xscl*(double)movex) + xp; yt = (int)(yscl*(double)movey) + yp; if(penf) { if(fill_) { xl[i] = xt; yl[i] = yt; i++; } else { g.drawLine(xdOld, ydOld, xt, yt); } } penf = true; xdOld = xt; ydOld = yt; } if(fill_) g.fillPolygon(xl, yl, i); } } public static void main(String[] args) { /** * hack code to create a "list" of plot marks. */ JFrame frame = new JFrame("Plot Marks"); frame.getContentPane().setLayout(new BorderLayout()); frame.setSize(500, 700); JPane pane = new JPane("Plot Mark Pane", frame.getSize()); Layer layer = new Layer("Plot Mark Layer", new Dimension2D(5.0, 7.0)); pane.setBatch(true); pane.setLayout(new StackedLayout()); frame.getContentPane().add(pane, BorderLayout.CENTER); pane.add(layer); frame.setVisible(true); pane.setBatch(false); PlotMark pm = new PlotMark(1); Graphics g = pane.getGraphics(); g.setFont(new Font("Helvetica", Font.PLAIN, 18)); pm.setMarkHeightP(0.32); int w = pane.getSize().width; int h = pane.getSize().height; g.setColor(Color.white); g.fillRect(0, 0, w, h); g.setColor(Color.black); FontMetrics fm = g.getFontMetrics(); int hgt = fm.getAscent()/2; String label; int xt = 100; int yt = 400; int wid = 0; int mark = 1; for(int j=0; j < 13; j++) { yt = 45*j + 100; for(int i=0; i < 4; i++) { xt = 120*i + 75; label = mark + ":"; wid = fm.stringWidth(label) + 20; g.setColor(Color.blue.brighter()); g.drawString(label, xt - wid, yt); pm.setMark(mark); g.setColor(Color.black); pm.paintMark(g, layer, xt, yt - hgt); mark++; if(mark > 51) break; } } } public String toString() { return "PlotMark: " + mark_; } }
luttero/Maud
src/gov/noaa/pmel/sgt/PlotMark.java
Java
bsd-3-clause
7,985
'use strict'; angular.module('27th.common.services.alert', []) .service('alertService', class { constructor($rootScope) { this.alerts = []; this.$rootScope = $rootScope; } success(msg) { this.alerts.push({ type: 'success', message: msg }); this.$rootScope.$emit('alerts.new'); } error(msg) { let message = msg; if(typeof msg !== 'string') { if(msg.message) { message = msg.message; } else if(msg.error && msg.error.message) { message = msg.error.message; } } this.alerts.push({ type: 'error', message: message }); this.$rootScope.$emit('alerts.new'); } nextAlert() { return this.alerts.pop(); } });
brainling/27thvfw
src/common/client/services/alert-service.js
JavaScript
bsd-3-clause
900
<?php /* @var $this ViewelementsController */ /* @var $model Viewelements */ $this->breadcrumbs=array( 'Viewelements'=>array('index'), $model->id, ); $this->menu=array( array('label'=>'List Viewelements', 'url'=>array('index')), array('label'=>'Create Viewelements', 'url'=>array('create')), array('label'=>'Update Viewelements', 'url'=>array('update', 'id'=>$model->id)), array('label'=>'Delete Viewelements', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')), array('label'=>'Manage Viewelements', 'url'=>array('admin')), ); ?> <h1>View Viewelements #<?php echo $model->id; ?></h1> <?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'siteid', 'html', 'id', 'viewname', 'elemid', 'elemtype', 'elemparameters', 'elemcode', ), )); ?>
ranvirp/viewcreater
protected/views/viewelements/view.php
PHP
bsd-3-clause
887
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model backend\models\SkillsHobbies */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="skills-hobbies-form"> <?php $form = ActiveForm::begin(); ?> <div class="row"> <div class="col-xs-3"> <?= $form->field($model, 'hobby')->textInput(['maxlength' => true]) ?> </div> </div> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
diginmanager/digin
frontend/views/skills-hobbies/_form.php
PHP
bsd-3-clause
654
"""Schedule models. Much of this module is derived from the work of Eldarion on the `Symposion <https://github.com/pinax/symposion>`_ project. Copyright (c) 2010-2014, Eldarion, Inc. and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Eldarion, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from bisect import bisect_left from itertools import tee from cached_property import cached_property from sqlalchemy import func from pygotham.core import db __all__ = ('Day', 'Room', 'Slot', 'Presentation') def pairwise(iterable): """Return values from ``iterable`` two at a time. Recipe from https://docs.python.org/3/library/itertools.html#itertools-recipes. """ a, b = tee(iterable) next(b, None) return zip(a, b) rooms_slots = db.Table( 'rooms_slots', db.Column('slot_id', db.Integer, db.ForeignKey('slots.id')), db.Column('room_id', db.Integer, db.ForeignKey('rooms.id')), ) class Day(db.Model): """Day of talks.""" __tablename__ = 'days' id = db.Column(db.Integer, primary_key=True) date = db.Column(db.Date) event_id = db.Column( db.Integer, db.ForeignKey('events.id'), nullable=False) event = db.relationship( 'Event', backref=db.backref('days', lazy='dynamic')) def __str__(self): """Return a printable representation.""" return self.date.strftime('%B %d, %Y') @cached_property def rooms(self): """Return the rooms for the day.""" return Room.query.join(rooms_slots, Slot).filter( Slot.day == self).order_by(Room.order).all() def __iter__(self): """Iterate over the schedule for the day.""" if not self.rooms: raise StopIteration def rowspan(start, end): """Find the rowspan for an entry in the schedule table. This uses a binary search for the given end time from a sorted list of start times in order to find the index of the first start time that occurs after the given end time. This method is used to prevent issues that can occur with overlapping start and end times being included in the same list. """ return bisect_left(times, end) - times.index(start) times = sorted({slot.start for slot in self.slots}) # While we typically only care about the start times here, the # list is iterated over two items at a time. Without adding a # final element, the last time slot would be omitted. Any value # could be used here as bisect_left only assumes the list is # sorted, but using a meaningful value feels better. times.append(self.slots[-1].end) slots = db.session.query( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end, func.count(rooms_slots.c.slot_id).label('room_count'), func.min(Room.order).label('order'), ).join(rooms_slots, Room).filter(Slot.day == self).order_by( func.count(rooms_slots.c.slot_id), func.min(Room.order) ).group_by( Slot.id, Slot.content_override, Slot.kind, Slot.start, Slot.end ).all() for time, next_time in pairwise(times): row = {'time': time, 'slots': []} for slot in slots: if slot.start == time: slot.rowspan = rowspan(slot.start, slot.end) slot.colspan = slot.room_count if not slot.content_override: slot.presentation = Presentation.query.filter( Presentation.slot_id == slot.id).first() row['slots'].append(slot) if row['slots'] or next_time is None: yield row class Room(db.Model): """Room of talks.""" __tablename__ = 'rooms' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) order = db.Column(db.Integer, nullable=False) def __str__(self): """Return a printable representation.""" return self.name class Slot(db.Model): """Time slot.""" __tablename__ = 'slots' id = db.Column(db.Integer, primary_key=True) kind = db.Column( db.Enum( 'break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False, ) content_override = db.Column(db.Text) start = db.Column(db.Time, nullable=False) end = db.Column(db.Time, nullable=False) day_id = db.Column(db.Integer, db.ForeignKey('days.id'), nullable=False) day = db.relationship('Day', backref=db.backref('slots', lazy='dynamic')) rooms = db.relationship( 'Room', secondary=rooms_slots, backref=db.backref('slots', lazy='dynamic'), order_by=Room.order, ) def __str__(self): """Return a printable representation.""" start = self.start.strftime('%I:%M %p') end = self.end.strftime('%I:%M %p') rooms = ', '.join(map(str, self.rooms)) return '{} - {} on {}, {}'.format(start, end, self.day, rooms) @cached_property def duration(self): """Return the duration as a :class:`~datetime.timedelta`.""" return self.end - self.start class Presentation(db.Model): """Presentation of a talk.""" __tablename__ = 'presentations' id = db.Column(db.Integer, primary_key=True) slot_id = db.Column(db.Integer, db.ForeignKey('slots.id'), nullable=False) slot = db.relationship( 'Slot', backref=db.backref('presentation', uselist=False)) talk_id = db.Column(db.Integer, db.ForeignKey('talks.id'), nullable=False) talk = db.relationship( 'Talk', backref=db.backref('presentation', uselist=False)) def __str__(self): """Return a printable representation.""" return str(self.talk) def is_in_all_rooms(self): """Return whether the instance is in all rooms.""" return self.slot.number_of_rooms == 4 @cached_property def number_of_rooms(self): """Return the number of rooms for the instance.""" return len(self.slot.rooms)
djds23/pygotham-1
pygotham/schedule/models.py
Python
bsd-3-clause
7,610
// +build f10x_ld f10x_ld_vl f10x_md f10x_md_vl f10x_hd f10x_hd_vl f10x_xl f10x_cl f303xe l1xx_md l1xx_mdp l1xx_hd l1xx_xl package dma import ( "stm32/hal/raw/rcc" ) func (p *DMA) enableClock(_ bool) { bit := bit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn) bit.Set() bit.Load() // RCC delay (workaround for silicon bugs). } func (p *DMA) disableClock() { bit(p, &rcc.RCC.AHBENR.U32, rcc.DMA1ENn).Clear() } func (p *DMA) reset() {}
ziutek/emgo
egpath/src/stm32/hal/dma/rcc-f1f3l1.go
GO
bsd-3-clause
435
# proxy module from apptools.logger.util import *
enthought/etsproxy
enthought/logger/util.py
Python
bsd-3-clause
50
import re from django import template from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active(context, name): try: pattern = reverse(name) except NoReverseMatch: return '' if re.match(pattern, context['request'].path): return 'active' return ''
jbittel/django-signage
signage/templatetags/active.py
Python
bsd-3-clause
413
package com.oracle.ptsdemo.oscproxyclient.types; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/opportunities/opportunityService/}Opportunity" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "processOpportunityResponse") public class ProcessOpportunityResponse { protected List<Opportunity> result; /** * Gets the value of the result property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the result property. * * <p> * For example, to add a new item, do as follows: * <pre> * getResult().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Opportunity } * * */ public List<Opportunity> getResult() { if (result == null) { result = new ArrayList<Opportunity>(); } return this.result; } }
oracle-adf/PaaS-SaaS_UIAccelerator
OSCProxyClient/src/com/oracle/ptsdemo/oscproxyclient/types/ProcessOpportunityResponse.java
Java
bsd-3-clause
1,912
#include <util/logger.h> #include "a_star.h" namespace math { a_star::a_star(point const &start, point const &goal, scorer_t const &scorer): start_(start), goal_(goal), scorer_(scorer), failed_(false) { } a_star::~a_star() { } void a_star::calculate_path() { start(); run(); } std::vector<a_star::point> a_star::build_path(bool allow_best_heuristic_point) const { std::vector<point> result; point current_point = goal_; if (failed_) { if (allow_best_heuristic_point) { scalar best_cost = -1; point best_point; for (boost::unordered_map<point, point_record, point_hash>::const_iterator it = point_records_.begin(); it != point_records_.end(); ++it) { if (it->second.heuristic_cost < 0) continue; if (best_cost < 0 || it->second.heuristic_cost < best_cost) { best_cost = it->second.heuristic_cost; best_point = it->first; } } if (best_cost < 0) return result; current_point = best_point; } else { return result; } } result.push_back(current_point); while (current_point != start_) { current_point = point_records_.find(current_point)->second.came_from; result.push_back(current_point); } std::reverse(result.begin(), result.end()); return result; } void a_star::add_open_point(point const &p, scalar w) { open_points_.insert(p); weighted_open_points_.insert(std::make_pair(w, p)); } a_star::point a_star::pop_cheapest_open_point() { point p = weighted_open_points_.begin()->second; open_points_.erase(p); weighted_open_points_.erase(weighted_open_points_.begin()); return p; } void a_star::update_open_point_cost(point const &p, scalar prev_w, scalar new_w) { weighted_open_points_.erase(weighted_open_points_.find(std::make_pair(prev_w, p))); weighted_open_points_.insert(std::make_pair(new_w, p)); } void a_star::start() { point_record &pr = point_records_[start_]; pr.best_cost = 0; pr.heuristic_cost = scorer_(start_); pr.total_cost = pr.heuristic_cost; if (pr.heuristic_cost < 0) return; add_open_point(start_, pr.total_cost); } void a_star::run() { while (!weighted_open_points_.empty()) { if (is_point_open(goal_)) return; process_next_point(); } failed_ = true; } void a_star::process_next_point() { point p = pop_cheapest_open_point(); closed_points_.insert(p); point_record const &pr = point_records_.find(p)->second; process_point_neighbour(p, pr, p + point(-1, -1)); process_point_neighbour(p, pr, p + point(-1, 0)); process_point_neighbour(p, pr, p + point(-1, 1)); process_point_neighbour(p, pr, p + point( 0, -1)); process_point_neighbour(p, pr, p + point( 0, 1)); process_point_neighbour(p, pr, p + point( 1, -1)); process_point_neighbour(p, pr, p + point( 1, 0)); process_point_neighbour(p, pr, p + point( 1, 1)); } void a_star::process_point_neighbour(point const &p, point_record const &pr, point const &n) { if (closed_points_.find(n) != closed_points_.end()) return; scalar tentative_best_cost = pr.best_cost + 1; point_record &nr = point_records_[n]; if (!is_point_open(n)) { nr.came_from = p; nr.best_cost = tentative_best_cost; nr.heuristic_cost = scorer_(n); if (nr.heuristic_cost < 0) { nr.total_cost = -nr.best_cost; closed_points_.insert(n); return; } nr.total_cost = nr.best_cost + nr.heuristic_cost; add_open_point(n, nr.total_cost); } else if (nr.best_cost > tentative_best_cost) { nr.came_from = p; nr.best_cost = tentative_best_cost; scalar total_cost = nr.best_cost + nr.heuristic_cost; update_open_point_cost(n, nr.total_cost, total_cost); nr.total_cost = total_cost; } } }
manvelavetisian/scratch
src/math/a_star.cc
C++
bsd-3-clause
3,614
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Difference'] , ['LinearTrend'] , ['Seasonal_Hour'] , ['NoAR'] );
antoinecarme/pyaf
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_LinearTrend_Seasonal_Hour_NoAR.py
Python
bsd-3-clause
160
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <itkImageFileWriter.h> #include <itkMetaDataObject.h> #include <itkVectorImage.h> #include <mitkImageCast.h> #include <mitkBaseData.h> #include <mitkFiberBundle.h> #include "mitkCommandLineParser.h" #include <boost/lexical_cast.hpp> #include <mitkCoreObjectFactory.h> #include <mitkIOUtil.h> #include <itkTractDensityImageFilter.h> #include <itkTractsToFiberEndingsImageFilter.h> mitk::FiberBundle::Pointer LoadFib(std::string filename) { std::vector<mitk::BaseData::Pointer> fibInfile = mitk::IOUtil::Load(filename); if( fibInfile.empty() ) std::cout << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast<mitk::FiberBundle*>(baseData.GetPointer()); } /*! \brief Modify input tractogram: fiber resampling, compression, pruning and transformation. */ int main(int argc, char* argv[]) { mitkCommandLineParser parser; parser.setTitle("Tract Density"); parser.setCategory("Fiber Tracking and Processing Methods"); parser.setDescription("Generate tract density image, fiber envelope or fiber endpoints image."); parser.setContributor("MBI"); parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", mitkCommandLineParser::String, "Input:", "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("output", "o", mitkCommandLineParser::String, "Output:", "output image", us::Any(), false); parser.addArgument("binary", "", mitkCommandLineParser::Int, "Binary output:", "calculate binary tract envelope", us::Any()); parser.addArgument("endpoints", "", mitkCommandLineParser::Int, "Output endpoints image:", "calculate image of fiber endpoints instead of mask", us::Any()); parser.addArgument("reference_image", "", mitkCommandLineParser::String, "Reference image:", "output image will have geometry of this reference image", us::Any()); std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; bool binary = false; if (parsedArgs.count("binary")) binary = us::any_cast<int>(parsedArgs["binary"]); bool endpoints = false; if (parsedArgs.count("endpoints")) endpoints = us::any_cast<int>(parsedArgs["endpoints"]); std::string reference_image = ""; if (parsedArgs.count("reference_image")) reference_image = us::any_cast<std::string>(parsedArgs["reference_image"]); std::string inFileName = us::any_cast<std::string>(parsedArgs["input"]); std::string outFileName = us::any_cast<std::string>(parsedArgs["output"]); try { mitk::FiberBundle::Pointer fib = LoadFib(inFileName); mitk::Image::Pointer ref_img; MITK_INFO << reference_image; if (!reference_image.empty()) ref_img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadImage(reference_image).GetPointer()); if (endpoints) { typedef unsigned char OutPixType; typedef itk::Image<OutPixType, 3> OutImageType; typedef itk::TractsToFiberEndingsImageFilter< OutImageType > ImageGeneratorType; ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); generator->SetFiberBundle(fib); if (ref_img.IsNotNull()) { OutImageType::Pointer itkImage = OutImageType::New(); CastToItkImage(ref_img, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image typedef itk::Image<OutPixType,3> OutType; OutType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); mitk::IOUtil::SaveBaseData(img, outFileName ); } else if (binary) { typedef unsigned char OutPixType; typedef itk::Image<OutPixType, 3> OutImageType; itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(fib); generator->SetBinaryOutput(binary); generator->SetOutputAbsoluteValues(false); generator->SetWorkOnFiberCopy(false); if (ref_img.IsNotNull()) { OutImageType::Pointer itkImage = OutImageType::New(); CastToItkImage(ref_img, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image typedef itk::Image<OutPixType,3> OutType; OutType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); mitk::IOUtil::SaveBaseData(img, outFileName ); } else { typedef float OutPixType; typedef itk::Image<OutPixType, 3> OutImageType; itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(fib); generator->SetBinaryOutput(binary); generator->SetOutputAbsoluteValues(false); generator->SetWorkOnFiberCopy(false); if (ref_img.IsNotNull()) { OutImageType::Pointer itkImage = OutImageType::New(); CastToItkImage(ref_img, itkImage); generator->SetInputImage(itkImage); generator->SetUseImageGeometry(true); } generator->Update(); // get output image typedef itk::Image<OutPixType,3> OutType; OutType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); mitk::IOUtil::SaveBaseData(img, outFileName ); } } catch (itk::ExceptionObject e) { std::cout << e; return EXIT_FAILURE; } catch (std::exception e) { std::cout << e.what(); return EXIT_FAILURE; } catch (...) { std::cout << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
RabadanLab/MITKats
Modules/DiffusionImaging/MiniApps/TractDensity.cpp
C++
bsd-3-clause
7,272
#include "jsxmin_renaming.h" #include <assert.h> #include <stdio.h> #include <iostream> // Varaible renaming of JS files. // This file includes three renaming strategies: // 1. local variable renaming; // 2. global variable renaming in the current file scope; // 3. property renaming in the current file scope; // // Local variable renaming: // This is done in function level. The first pass collects all varabiles and // functions declared in the current scope (non-recursive), and choose a new // (shorter) name for local variables and functions. New names cannot be names // used in parent scopes (the global scope is root of all local scopes). // The second pass renames identifiers in the current function using // the mapping constructed in the local scope. Here is one example: // // // Starts from global scope // var a = 10; // function func(foo, bar) { // var gee = a; // } // First, it builds a gloabl scope with mappings // global_scope => {'a' -> 'a', 'func' -> 'func'} // When entering function 'func', a local scope is built: // func_scope => {'foo' -> 'foo', 'bar' -> 'bar', 'gee' -> 'gee'} // |__ parent -> {'a' -> 'a', 'func' -> 'func'} ( *global_scope* ) // // When renaming variables in func_scope, it starts with shortest name 'a', // but it first has to loopup the scope chain to see if 'a' is used as // new name in the current scope and parent scopes. In this case, 'a' is // not available, so 'b' is choosed as new name of 'foo'. The result // local scope looks like following: // func_scope => {'foo' -> 'b', 'bar' -> 'c', 'gee' => 'd'} // |__ parent -> {'a' -> 'a', 'func' -> 'func'} ( *global_scope* ) // // The next pass is to rename identifers in the code using scope info. // In this example, 'foo', 'bar', 'gee' are renamed to 'b', 'c', and 'd', // but the identifier 'a' in func is kept the same because the global scope // preserves its original name. // // When entering a function, a new scope is created with the current scope // as its parent scope. // // Global variable renaming and property renaming: // We use naming convention that name starting with exact one '_' is private // to the file or the class (function). Also this naming convention is // voilated in our code, but these are not common and are fixable. // // A tricky part of global variable and property renaming is that we don't // collect all property names and variables, so when chooseing new names, // the new name might be used already, but we don't know. // To solve this problem, we use naming convention here again. New names for // global variables and properties names always start with one exact '_'. // It works because we collect all names starting with exact one '_'. // // TODO : Property renaming in file scope is UNSAFE: // A construtor function can set a private property named _foo, it may call // another constructor function (as its parent class) that adds a property // named _bar. Because the child and parent constructor functions are in // different files, both can get renamed to the same name. using namespace std; using namespace fbjs; #define for_nodes(p, i) \ for (node_list_t::iterator i = (p)->childNodes().begin(); \ i != (p)->childNodes().end(); \ ++i) #define WARN(format, args...) // ---- NameFactory ----- string NameFactory::next() { string result = _prefix + _current; bool found = false; // move to the next for (size_t i = 0; i < _current.size(); i++) { char c = _current[i] + 1; if (c <= 'z') { _current[i] = c; found = true; break; } } if (!found) { _current.push_back('a'); } return result; } // ---- Scope ---- void Scope::declare(string name) { _replacement[name] = name; } string Scope::new_name(string orig_name) { rename_t::iterator it = _replacement.find(orig_name); if (it != _replacement.end()) { return it->second; } if (!_parent) { return orig_name; } return _parent->new_name(orig_name); } bool Scope::declared(string name) { if (_replacement.find(name) != _replacement.end()) { return true; } if (!_parent) { return false; } return _parent->declared(name); } bool Scope::in_use(string name) { if (_new_names.find(name) != _new_names.end()) { return true; } if (!_parent) { return false; } return _parent->in_use(name); } void Scope::dump() { int indention = 0; Scope* parent = _parent; while (parent != NULL) { indention += 2; parent = parent->_parent; } for (rename_t::iterator it = _replacement.begin(); it != _replacement.end(); it++) { cout<<"//"; for (int i = 0; i < indention; i++) { cout << " "; } cout << it->first.c_str() << " -> " << it->second.c_str() << "\n"; } } bool LocalScope::need_rename(const string& name) { return name != "event"; } void LocalScope::rename_vars() { NameFactory factory; for (rename_t::iterator it = _replacement.begin(); it != _replacement.end(); it++) { string var_name = it->first; string new_name = it->second; if (need_rename(var_name)) { new_name = factory.next(); while (_parent->in_use(new_name)) { new_name = factory.next(); } } rename_internal(var_name, new_name); } } // ---- GlobalScope ---- GlobalScope::GlobalScope(bool rename_private) : Scope(NULL) { this->_rename_private = rename_private; this->_name_factory.set_prefix("_"); } bool GlobalScope::need_rename(const string& name) { return this->_rename_private && name.length() > 1 && name[0] == '_' && name[1] != '_'; } void GlobalScope::rename_vars() { for (rename_t::iterator it = _replacement.begin(); it != _replacement.end(); it++) { string var_name = it->first; string new_name = it->second; if (need_rename(var_name)) { new_name = _name_factory.next(); while (this->in_use(new_name)) { new_name = _name_factory.next(); } } rename_internal(var_name, new_name); } } void GlobalScope::rename_var(const string& var_name) { string new_name = _name_factory.next(); while (this->in_use(new_name)) { new_name = _name_factory.next(); } rename_internal(var_name, new_name); } // ----- VariableRenaming ---- VariableRenaming::VariableRenaming() { this->_global_scope = new GlobalScope(/* rename_globals */ false); } VariableRenaming::~VariableRenaming() { delete this->_global_scope; } void VariableRenaming::process(NodeProgram* root) { // Collect all symbols in the file scope build_scope(root, this->_global_scope); this->_global_scope->rename_vars(); // Starts in the global scope. minify(root, this->_global_scope); } void VariableRenaming::minify(Node* node, Scope* scope) { if (node == NULL) { return; } if (typeid(*node) == typeid(NodeObjectLiteralProperty)) { // For {prop: value}, we can't rename the property with local scope rules. minify(node->childNodes().back(), scope); } else if (typeid(*node) == typeid(NodeStaticMemberExpression)) { // a.b case, cannot rename _b minify(node->childNodes().front(), scope); } else if (typeid(*node) == typeid(NodeIdentifier)) { NodeIdentifier* n = static_cast<NodeIdentifier*>(node); string name = n->name(); if (scope->declared(name)) { n->rename(scope->new_name(name)); } } else if ( (typeid(*node) == typeid(NodeFunctionDeclaration) || typeid(*node) == typeid(NodeFunctionExpression))) { if (!function_has_with_or_eval(node)){ node_list_t::iterator func = node->childNodes().begin(); // Skip function name. ++func; // Create a new local scope for the function using current scope // as parent. Then add arguments to the local scope and build // scope for variables declared in the function. LocalScope child_scope(scope); // First, add all the arguments to scope. for_nodes(*func, arg) { NodeIdentifier *arg_node = static_cast<NodeIdentifier*>(*arg); child_scope.declare(arg_node->name()); } // Now, look ahead and find all the local variable declarations. build_scope(*(++func), &child_scope); // Build renaming map in local scope child_scope.rename_vars(); // Finally, recurse with the new scope. // Function name can only be renamed in the parent scope. for_nodes(node, ii) { if (ii == node->childNodes().begin()) { minify(*ii, scope); } else { minify(*ii, &child_scope); } } } // If the function has with and eval, don't attempt to rename code further. } else { for_nodes(node, ii) { minify(*ii, scope); } } } // Iterate through all child nodes and find if it contains with or eval // statement, it also recursively check sub functions. bool VariableRenaming::function_has_with_or_eval(Node* node) { if (node == NULL) { return false; } for_nodes(node, ii) { Node* child = *ii; if (child == NULL) { continue; } if (typeid(*child) == typeid(NodeWith)) { WARN("function has 'with' statement at line %d\n", child->lineno()); return true; } NodeFunctionCall* call = dynamic_cast<NodeFunctionCall*>(child); if (call != NULL) { NodeIdentifier* iden = dynamic_cast<NodeIdentifier*>(call->childNodes().front()); if (iden != NULL && iden->name() == "eval") { WARN("function uses 'eval' at line %d\n", call->lineno()); return true; } } if ( (typeid(*child) == typeid(NodeFunctionDeclaration) || typeid(*child) == typeid(NodeFunctionExpression)) && function_has_with_or_eval(child) ) { return true; // Don't check the current child node again if it is a function // declaration or expression. } else if (function_has_with_or_eval(child)) { return true; } } return false; } void VariableRenaming::build_scope(Node *node, Scope* scope) { if (node == NULL) { return; } if (typeid(*node) == typeid(NodeFunctionExpression)) { return; } if (typeid(*node) == typeid(NodeFunctionDeclaration)) { NodeIdentifier* decl_name = dynamic_cast<NodeIdentifier*>(node->childNodes().front()); if (decl_name) { scope->declare(decl_name->name()); } return; } if (typeid(*node) == typeid(NodeVarDeclaration)) { for_nodes(node, ii) { NodeIdentifier *n = dynamic_cast<NodeIdentifier*>(*ii); if (!n) { n = dynamic_cast<NodeIdentifier*>((*ii)->childNodes().front()); } scope->declare(n->name()); } return; } // Special case for try ... catch(e) ... // Treat e as a local variable. if (typeid(*node) == typeid(NodeTry)) { // second child is the catch variable, either null of a node identifier. node_list_t::iterator it = node->childNodes().begin(); ++it; NodeIdentifier* var = dynamic_cast<NodeIdentifier*>(*it); if (var) { scope->declare(var->name()); } return; } // Special case for 'for (i in o)' and 'i = ...'. // In these cases, if 'i' is not declared before, we treat it as a global // variable. It is most likely the developer forgot to put a 'var' before // the variable name, and we give out a warning. if (typeid(*node) == typeid(NodeAssignment) || typeid(*node) == typeid(NodeForIn)) { NodeIdentifier* var = dynamic_cast<NodeIdentifier*>(node->childNodes().front()); if (var && !scope->declared(var->name())) { // 1. assignment to an undeclared variable is made in a local scope, or // 2. for-in loop variable is not declared. if (!scope->is_global() || typeid(*node) == typeid(NodeForIn)) { WARN("'%s' at line %d is not declared, 'var %s'?\n", var->name().c_str(), var->lineno(), var->name().c_str()); this->_global_scope->reserve(var->name()); } } // Fall through to process the rest part of statement. } for_nodes(node, ii) { build_scope(*ii, scope); } } // ----- PropertyRenaming ----- // Unsafe PropertyRenaming::PropertyRenaming() { this->_property_scope = new GlobalScope(true); } PropertyRenaming::~PropertyRenaming() { delete this->_property_scope; } void PropertyRenaming::process(NodeProgram* root) { // Rewrite nodes, this is necessary to make property renaming work correctly. // e.g., a['foo'] -> a.foo, and { 'foo' : 1 } -> { foo : 1 }. ReductionWalker walker; walker.walk(root); minify(root); } void PropertyRenaming::minify(Node* node) { if (node == NULL) { return; } if (typeid(*node) == typeid(NodeObjectLiteralProperty)) { // For {prop: value}, we can't rename the property with local scope rules. NodeIdentifier* n = dynamic_cast<NodeIdentifier*>(node->childNodes().front()); if (n && _property_scope->need_rename(n->name())) { string name = n->name(); if (!_property_scope->declared(name)) { _property_scope->declare(name); _property_scope->rename_var(name); } n->rename(_property_scope->new_name(name)); } minify(node->childNodes().back()); } else if (typeid(*node) == typeid(NodeStaticMemberExpression)) { // a._b. case, rename _b part minify(node->childNodes().front()); // Must be NodeIdentifier. NodeIdentifier* n = dynamic_cast<NodeIdentifier*>(node->childNodes().back()); assert(n != NULL); if (_property_scope->need_rename(n->name())) { string name = n->name(); if (!_property_scope->declared(name)) { _property_scope->declare(name); _property_scope->rename_var(name); } n->rename(_property_scope->new_name(name)); } } else { for_nodes(node, ii) { minify(*ii); } } }
phacility/javelin
support/jsxmin/jsxmin_renaming.cpp
C++
bsd-3-clause
13,931
// $Id: ByteArray.java,v 1.2 2003/10/07 21:45:57 idgay Exp $ /* tab:4 * "Copyright (c) 2000-2003 The Regents of the University of California. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Copyright (c) 2002-2003 Intel Corporation * All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE * file. If you do not find these files, copies can be found by writing to * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, * 94704. Attention: Intel License Inquiry. */ /* Authors: David Gay <dgay@intel-research.net> * Intel Research Berkeley Lab * */ /** * ByteArray class. A simple abstract, read-only byte array class. * * ByteArrays is the "interface" (in class form) expected by the * dataSet method of net.tinyos.message.Message. Users should extend * ByteArray and implement an appropriate get method. Example: * received.dataSet * (new ByteArray() { * public byte get(int index) { return msg.getData(index);} }); * @author David Gay <dgay@intel-research.net> * @author Intel Research Berkeley Lab */ package net.tinyos.message; abstract public class ByteArray { /** * Get the index'th byte of this array * @param index: index of byte to fetch */ public abstract byte get(int index); }
fresskarma/tinyos-1.x
tools/java/net/tinyos/message/ByteArray.java
Java
bsd-3-clause
2,317
/* Copyright (c) 2007 - 2010, Carlos Guzmán Álvarez All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; using System.Threading; using Hanoi.Serialization.Core.Sasl; namespace Hanoi.Authentication { /// <summary> /// <see cref = "Authenticator" /> implementation for the SASL Plain Authentication mechanism. /// </summary> /// <remarks> /// References: /// http://www.ietf.org/html.charters/sasl-charter.html /// http://www.ietf.org/internet-drafts/draft-ietf-sasl-plain-09.txt /// </remarks> internal sealed class SaslPlainAuthenticator : Authenticator { private readonly AutoResetEvent _waitEvent; /// <summary> /// Initializes a new instance of the <see cref="SaslPlainAuthenticator" /> class. /// </summary> public SaslPlainAuthenticator(Connection connection) : base(connection) { _waitEvent = new AutoResetEvent(false); } public override string FeatureKey { get { return "PLAIN"; } } /// <summary> /// Performs the authentication using the SASL Plain authentication mechanism. /// </summary> public override void Authenticate() { // Send authentication mechanism var auth = new Auth { Mechanism = XmppCodes.SaslPlainMechanism, Value = BuildMessage(), }; Connection.Send(auth); _waitEvent.WaitOne(); if (!AuthenticationFailed) { // Re-Initialize XMPP Stream Connection.InitializeXmppStream(); // Wait until we receive the Stream features Connection.WaitForStreamFeatures(); } } protected override void OnUnhandledMessage(object sender, UnhandledMessageEventArgs e) { if (e.StanzaInstance is Success) { _waitEvent.Set(); } } protected override void OnAuthenticationError(object sender, AuthenticationFailiureEventArgs e) { base.OnAuthenticationError(sender, e); _waitEvent.Set(); } private string BuildMessage() { string message = String.Format("\0{0}\0{1}", Connection.UserId.BareIdentifier, Connection.UserPassword); return Encoding.UTF8.GetBytes(message).ToBase64String(); } } }
MustafaUzumcuCom/Hanoi
source/Hanoi/Authentication/SaslPlainAuthenticator.cs
C#
bsd-3-clause
4,120
/* @flow */ import * as React from "react"; import { nest } from "d3-collection"; import { scaleLinear } from "d3-scale"; import TooltipContent from "../tooltip-content"; const parentPath = (d, pathArray) => { if (d.parent) { pathArray = parentPath(d.parent, [d.key, ...pathArray]); } else { pathArray = ["root", ...pathArray]; } return pathArray; }; const hierarchicalTooltip = (d, primaryKey, metric) => { const pathString = d.parent ? parentPath(d.parent, (d.key && [d.key]) || []).join("->") : ""; const content = []; if (!d.parent) { content.push(<h2 key="hierarchy-title">Root</h2>); } else if (d.key) { content.push(<h2 key="hierarchy-title">{d.key}</h2>); content.push(<p key="path-string">{pathString}</p>); content.push(<p key="hierarchy-value">Total Value: {d.value}</p>); content.push(<p key="hierarchy-children">Children: {d.children.length}</p>); } else { content.push( <p key="leaf-label"> {pathString} -> {primaryKey.map(p => d[p]).join(", ")} </p> ); content.push( <p key="hierarchy-value"> {metric}: {d[metric]} </p> ); } return content; }; const hierarchicalColor = (colorHash: Object, d: Object) => { if (d.depth === 0) return "white"; if (d.depth === 1) return colorHash[d.key]; let colorNode = d; for (let x = d.depth; x > 1; x--) { colorNode = colorNode.parent; } const lightenScale = scaleLinear() .domain([6, 1]) .clamp(true) .range(["white", colorHash[colorNode.key]]); return lightenScale(d.depth); }; export const semioticHierarchicalChart = ( data: Array<Object>, schema: Object, options: Object ) => { const { hierarchyType = "dendrogram", chart, selectedDimensions, primaryKey, colors } = options; const { metric1 } = chart; if (selectedDimensions.length === 0) { return {}; } const nestingParams = nest(); selectedDimensions.forEach(d => { nestingParams.key(p => p[d]); }); const colorHash = {}; const sanitizedData = []; data.forEach(d => { if (!colorHash[d[selectedDimensions[0]]]) colorHash[d[selectedDimensions[0]]] = colors[Object.keys(colorHash).length]; sanitizedData.push({ ...d, sanitizedR: d.r, r: undefined }); }); const entries = nestingParams.entries(sanitizedData); const rootNode = { values: entries }; return { edges: rootNode, edgeStyle: () => ({ fill: "lightgray", stroke: "gray" }), nodeStyle: (d: Object) => { return { fill: hierarchicalColor(colorHash, d), stroke: d.depth === 1 ? "white" : "black", strokeOpacity: d.depth * 0.1 + 0.2 }; }, networkType: { type: hierarchyType, hierarchySum: (d: Object) => d[metric1], hierarchyChildren: (d: Object) => d.values, padding: hierarchyType === "treemap" ? 3 : hierarchyType === "circlepack" ? 2 : 0 }, edgeRenderKey: (d: Object, i: number) => { return i; }, baseMarkProps: { forceUpdate: true }, margin: { left: 100, right: 100, top: 10, bottom: 10 }, hoverAnnotation: true, tooltipContent: (d: Object) => { return ( <TooltipContent> {hierarchicalTooltip(d, primaryKey, metric1)} </TooltipContent> ); } }; };
jdfreder/nteract
packages/transform-dataresource/src/charts/hierarchical.js
JavaScript
bsd-3-clause
3,353
#include <unistd.h> #include <iostream> #include <iomanip> #include <string> #include <sndfile.hh> #include "TemVoc.hpp" const string VERSION = "1.0"; using namespace std; int main(int argc, char *argv[]) try { string help_message {"temvoc [-hwv] [-f fftsize] <carrier path> <modulator path> <output path>"}; bool weighting = false; int fftsize {1024}; char c; while ((c = getopt (argc, argv, "vhwf:")) != -1) { double base; switch (c) { case 'v': cerr << "temporal vocoder (c)2014 analoq[labs]" << endl; cerr << "version: " << VERSION << endl; return 0; case 'h': cerr << help_message << endl << " -v Display version information\n" " -h Displays help\n" " -w Apply A-Weighting during matching\n" " -f <size> FFT size (powers of 2)\n" " <carrier path> Path to Carrier audio file\n" " <modulator path> Path to Modulator audio file\n" " <output path> Path to output audio file\n"; return 0; case 'w': weighting = true; break; case 'f': try { fftsize = stoi(optarg); } catch (invalid_argument &e) { cerr << "FFT Size could not be parsed" << endl; return 1; } if ( fftsize < 64 || fftsize > 8192 ) { cerr << "FFT Size must be between 64 and 8192." << endl; return 1; } base = log(fftsize)/log(2); if ( floor(base) != base ) { cerr << "FFT Size must be a power of 2." << endl; return 1; } break; case '?': if (optopt == 'f') cerr << "Option -" << (char)optopt << " requires an argument." << endl; else if (isprint (optopt)) cerr << "Unknown option `-" << (char)optopt << "'." << endl; else cerr << "Unknown option character `\\x" << optopt << "'." << endl; return 1; default: cerr << help_message << endl; } } if (argc - optind < 3) { cerr << help_message << endl; return 1; } string carrier_path {argv[optind]}; string modulator_path {argv[optind+1]}; string output_path {argv[optind+2]}; // load input files SndfileHandle carrier{carrier_path}; if ( carrier.error() != SF_ERR_NO_ERROR ) { cerr << "Could not load '" << carrier_path << "' - " << carrier.strError() << endl; return 1; } SndfileHandle modulator{modulator_path}; if ( modulator.error() != SF_ERR_NO_ERROR ) { cerr << "Could not load '" << modulator_path << "' - " << modulator.strError() << endl; return 1; } if ( carrier.channels() != 1 || modulator.channels() != 1 ) { cerr << "Input audio files must be be mono" << endl; return 1; } if (modulator.samplerate() != carrier.samplerate()) { cerr << "Carrier and Modulator sample rates must match." << endl; return 1; } cerr << "Carrier: " << carrier_path << endl << "Modulator: " << modulator_path << endl << "Output: " << output_path << endl << "FFT Size: " << fftsize << endl << "A-Weighting: " << (weighting ? "On" : "Off") << endl; TemVoc temvoc {fftsize, weighting, carrier, modulator}; temvoc.process(output_path, [](double p) { cerr << "Processing " << fixed << setprecision(0) << 100*p << "% \r"; }); cerr << endl; return 0; } catch (exception &e) { cerr << "Error: " << e.what() << endl; return -1; }
analoq/temvoc
main.cpp
C++
bsd-3-clause
3,703
#!/usr/bin/env python ''' isobands_matplotlib.py is a script for creating isobands. Works in a similar way as gdal_contour, but creating polygons instead of polylines This version requires matplotlib, but there is another one, isobands_gdal.py that uses only GDAL python Originally created by Roger Veciana i Rovira, made available via his blog post http://geoexamples.blogspot.com.au/2013/08/creating-vectorial-isobands-with-python.html and on Github at https://github.com/rveciana/geoexamples/tree/master/python/raster_isobands ''' from numpy import arange from numpy import meshgrid from osgeo import ogr from osgeo import gdal from osgeo import osr from math import floor from math import ceil from os.path import exists from os import remove from argparse import ArgumentParser import matplotlib.pyplot as plt def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def isobands(in_file, band, out_file, out_format, layer_name, attr_name, offset, interval, min_level = None, upper_val_output = False): ''' The method that calculates the isobands ''' ds_in = gdal.Open(in_file) band_in = ds_in.GetRasterBand(band) xsize_in = band_in.XSize ysize_in = band_in.YSize geotransform_in = ds_in.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt( ds_in.GetProjectionRef() ) #Creating the output vectorial file drv = ogr.GetDriverByName(out_format) if exists(out_file): remove(out_file) dst_ds = drv.CreateDataSource( out_file ) dst_layer = dst_ds.CreateLayer(layer_name, geom_type = ogr.wkbPolygon, srs = srs) fdef = ogr.FieldDefn( attr_name, ogr.OFTReal ) dst_layer.CreateField( fdef ) # Use the geotransform pixel size value to avoid weird rounding errors in # original approach. x_pos = [geotransform_in[0]+geotransform_in[1]*ii \ for ii in range(xsize_in)] y_pos = [geotransform_in[3]+geotransform_in[5]*ii \ for ii in range(ysize_in)] #x_pos = arange(geotransform_in[0], # geotransform_in[0] + xsize_in*geotransform_in[1], geotransform_in[1]) #y_pos = arange(geotransform_in[3], # geotransform_in[3] + ysize_in*geotransform_in[5], geotransform_in[5]) x_grid, y_grid = meshgrid(x_pos, y_pos) raster_values = band_in.ReadAsArray(0, 0, xsize_in, ysize_in) #stats = band_in.GetStatistics(True, True) min_value, max_value = band_in.ComputeRasterMinMax() if min_level == None: #min_value = stats[0] min_level = offset + interval * floor((min_value - offset)/interval) #max_value = stats[1] #Due to range issues, a level is added max_level = offset + interval * (1 + ceil((max_value - offset)/interval)) levels = arange(min_level, max_level, interval) contours = plt.contourf(x_grid, y_grid, raster_values, levels) for level in range(len(contours.collections)): paths = contours.collections[level].get_paths() for path in paths: feat_out = ogr.Feature( dst_layer.GetLayerDefn()) if upper_val_output: out_val = contours.levels[level] + interval else: out_val = contours.levels[level] feat_out.SetField( attr_name, out_val ) pol = ogr.Geometry(ogr.wkbPolygon) ring = None for i in range(len(path.vertices)): point = path.vertices[i] if path.codes[i] == 1: if ring != None: pol.AddGeometry(ring) ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint_2D(point[0], point[1]) pol.AddGeometry(ring) feat_out.SetGeometry(pol) if dst_layer.CreateFeature(feat_out) != 0: print "Failed to create feature in shapefile.\n" exit( 1 ) feat_out.Destroy() if __name__ == "__main__": PARSER = ArgumentParser( description="Calculates the isobands from a raster into a vector file") PARSER.add_argument("src_file", help="The raster source file") PARSER.add_argument("out_file", help="The vectorial out file") PARSER.add_argument("-b", help="The band in the source file to process (default 1)", type=int, default = 1, metavar = 'band') PARSER.add_argument("-off", help="The offset to start the isobands (default 0)", type=float, default = 0.0, metavar = 'offset') PARSER.add_argument("-i", help="The interval (default 0)", type=float, default = 0.0, metavar = 'interval') PARSER.add_argument("-nln", help="The out layer name (default bands)", default = 'bands', metavar = 'layer_name') PARSER.add_argument("-a", help="The out layer attribute name (default h)", default = 'h', metavar = 'attr_name') PARSER.add_argument("-f", help="The output file format name (default ESRI Shapefile)", default = 'ESRI Shapefile', metavar = 'formatname') PARSER.add_argument("-up", help="In the output file, whether to use the upper value of an " "isoband, as value name for polygons, rather than lower.", default = "False", metavar='upper_val_output') ARGS = PARSER.parse_args() isobands(ARGS.src_file, ARGS.b, ARGS.out_file, ARGS.f, ARGS.nln, ARGS.a, ARGS.off, ARGS.i, upper_val_output=str2bool(ARGS.up))
PatSunter/pyOTPA
Isochrones/isobands_matplotlib.py
Python
bsd-3-clause
5,552
// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/cgroup.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <signal.h> #include <errno.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <pwd.h> #include "common/logging.h" #include "common/util.h" #include "common/this_thread.h" #include "agent/downloader_manager.h" #include "agent/resource_collector.h" #include "agent/resource_collector_engine.h" #include "agent/utils.h" #include <gflags/gflags.h> DECLARE_string(task_acct); DECLARE_string(cgroup_root); DECLARE_int32(agent_cgroup_clear_retry_times); namespace galaxy { static const std::string RUNNER_META_PREFIX = "task_runner_"; static int CPU_CFS_PERIOD = 100000; static int MIN_CPU_CFS_QUOTA = 1000; static int CPU_SHARE_PER_CPU = 1024; static int MIN_CPU_SHARE = 10; int CGroupCtrl::Create(int64_t task_id, std::map<std::string, std::string>& sub_sys_map) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = mkdir(ss.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status != 0) { if (errno == EEXIST) { // TODO LOG(WARNING, "cgroup already there"); } else { LOG(FATAL, "fail to create subsystem %s ,status is %d", ss.str().c_str(), status); return status; } } sub_sys_map[*it] = ss.str(); LOG(INFO, "create subsystem %s successfully", ss.str().c_str()); } return 0; } static int GetCgroupTasks(const std::string& task_path, std::vector<int>* pids) { if (pids == NULL) { return -1; } FILE* fin = fopen(task_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed err[%d: %s]", task_path.c_str(), errno, strerror(errno)); return -1; } ssize_t read; char* line = NULL; size_t len = 0; while ((read = getline(&line, &len, fin)) != -1) { int pid = atoi(line); if (pid <= 0) { continue; } pids->push_back(pid); } if (line != NULL) { free(line); } fclose(fin); return 0; } //目前不支持递归删除 //删除前应该清空tasks文件 int CGroupCtrl::Destroy(int64_t task_id) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); int ret = 0; for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; std::string sub_cgroup_path = ss.str().c_str(); // TODO maybe cgroup.proc ? std::string task_path = sub_cgroup_path + "/tasks"; int clear_retry_times = 0; for (; clear_retry_times < FLAGS_agent_cgroup_clear_retry_times; ++clear_retry_times) { int status = rmdir(sub_cgroup_path.c_str()); if (status == 0 || errno == ENOENT) { break; } LOG(FATAL,"fail to delete subsystem %s status %d err[%d: %s]", sub_cgroup_path.c_str(), status, errno, strerror(errno)); // clear task in cgroup std::vector<int> pids; if (GetCgroupTasks(task_path, &pids) != 0) { LOG(WARNING, "fail to clear task file"); return -1; } LOG(WARNING, "get pids %ld from subsystem %s", pids.size(), sub_cgroup_path.c_str()); if (pids.size() != 0) { std::vector<int>::iterator it = pids.begin(); for (;it != pids.end(); ++it) { if (::kill(*it, SIGKILL) == -1) { if (errno != ESRCH) { LOG(WARNING, "kill process %d failed", *it); } } } common::ThisThread::Sleep(100); } } if (clear_retry_times >= FLAGS_agent_cgroup_clear_retry_times) { ret = -1; } } return ret; } int AbstractCtrl::AttachTask(pid_t pid) { std::string task_file = _my_cg_root + "/" + "tasks"; int ret = common::util::WriteIntToFile(task_file, pid); if (ret < 0) { //LOG(FATAL, "fail to attach pid %d for %s", pid, _my_cg_root.c_str()); return -1; }else{ //LOG(INFO,"attach pid %d for %s successfully",pid, _my_cg_root.c_str()); } return 0; } int MemoryCtrl::SetLimit(int64_t limit) { std::string limit_file = _my_cg_root + "/" + "memory.limit_in_bytes"; int ret = common::util::WriteIntToFile(limit_file, limit); if (ret < 0) { //LOG(FATAL, "fail to set limt %lld for %s", limit, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetSoftLimit(int64_t soft_limit) { std::string soft_limit_file = _my_cg_root + "/" + "memory.soft_limit_in_bytes"; int ret = common::util::WriteIntToFile(soft_limit_file, soft_limit); if (ret < 0) { LOG(FATAL, "fail to set soft limt %lld for %s", soft_limit, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuShare(int64_t cpu_share) { std::string cpu_share_file = _my_cg_root + "/" + "cpu.shares"; int ret = common::util::WriteIntToFile(cpu_share_file, cpu_share); if (ret < 0) { //LOG(FATAL, "fail to set cpu share %lld for %s", cpu_share, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuPeriod(int64_t cpu_period) { std::string cpu_period_file = _my_cg_root + "/" + "cpu.cfs_period_us"; int ret = common::util::WriteIntToFile(cpu_period_file, cpu_period); if (ret < 0) { LOG(FATAL, "fail to set cpu period %lld for %s", cpu_period, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuQuota(int64_t cpu_quota) { std::string cpu_quota_file = _my_cg_root + "/" + "cpu.cfs_quota_us"; int ret = common::util::WriteIntToFile(cpu_quota_file, cpu_quota); if (ret < 0) { //LOG(FATAL, "fail to set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return -1; } //LOG(INFO, "set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return 0; } ContainerTaskRunner::~ContainerTaskRunner() { if (collector_ != NULL) { ResourceCollectorEngine* engine = GetResourceCollectorEngine(); engine->DelCollector(collector_id_); delete collector_; collector_ = NULL; } delete _cg_ctrl; delete _mem_ctrl; delete _cpu_ctrl; delete _cpu_acct_ctrl; } int ContainerTaskRunner::Prepare() { LOG(INFO, "prepare container for task %ld", m_task_info.task_id()); //TODO std::vector<std::string> support_cg; support_cg.push_back("memory"); support_cg.push_back("cpu"); support_cg.push_back("cpuacct"); _cg_ctrl = new CGroupCtrl(_cg_root, support_cg); std::map<std::string, std::string> sub_sys_map; int status = _cg_ctrl->Create(m_task_info.task_id(), sub_sys_map); // NOTE multi thread safe if (collector_ == NULL) { std::string group_path = boost::lexical_cast<std::string>(m_task_info.task_id()); collector_ = new CGroupResourceCollector(group_path); ResourceCollectorEngine* engine = GetResourceCollectorEngine(); collector_id_ = engine->AddCollector(collector_); } else { collector_->ResetCgroupName( boost::lexical_cast<std::string>(m_task_info.task_id())); } if (status != 0) { LOG(FATAL, "fail to create subsystem for task %ld,status %d", m_task_info.task_id(), status); return status; } _mem_ctrl = new MemoryCtrl(sub_sys_map["memory"]); _cpu_ctrl = new CpuCtrl(sub_sys_map["cpu"]); _cpu_acct_ctrl = new CpuAcctCtrl(sub_sys_map["cpuacct"]); return Start(); } void ContainerTaskRunner::PutToCGroup(){ int64_t mem_size = m_task_info.required_mem(); double cpu_core = m_task_info.required_cpu(); // soft limit cpu.share double cpu_limit = cpu_core; // hard limit cpu.cfs_quota_us if (m_task_info.has_limited_cpu()) { cpu_limit = m_task_info.limited_cpu(); if (cpu_limit < cpu_core) { cpu_limit = cpu_core; } } assert(_mem_ctrl->SetLimit(mem_size) == 0); // set cpu hard limit first int64_t limit = static_cast<int64_t>(cpu_limit * CPU_CFS_PERIOD); if (limit < MIN_CPU_CFS_QUOTA) { limit = MIN_CPU_CFS_QUOTA; } assert(_cpu_ctrl->SetCpuQuota(limit) == 0); // set cpu qutoa int64_t quota = static_cast<int64_t>(cpu_core * CPU_SHARE_PER_CPU); if (quota < MIN_CPU_SHARE) { quota = MIN_CPU_SHARE; } assert(_cpu_ctrl->SetCpuShare(quota) == 0); pid_t my_pid = getpid(); assert(_mem_ctrl->AttachTask(my_pid) == 0); assert(_cpu_ctrl->AttachTask(my_pid) == 0); assert(_cpu_acct_ctrl->AttachTask(my_pid) == 0); } int ContainerTaskRunner::Start() { LOG(INFO, "start a task with id %ld", m_task_info.task_id()); if (IsRunning() == 0) { LOG(WARNING, "task with id %ld has been runing", m_task_info.task_id()); return -1; } int stdout_fd, stderr_fd; std::vector<int> fds; PrepareStart(fds, &stdout_fd, &stderr_fd); //sequence_id_ ++; passwd *pw = getpwnam(FLAGS_task_acct.c_str()); if (NULL == pw) { LOG(WARNING, "getpwnam %s failed", FLAGS_task_acct.c_str()); return -1; } uid_t userid = getuid(); if (pw->pw_uid != userid && 0 == userid) { if (!file::Chown(m_workspace->GetPath(), pw->pw_uid, pw->pw_gid)) { LOG(WARNING, "chown %s failed", m_workspace->GetPath().c_str()); return -1; } } m_child_pid = fork(); if (m_child_pid == 0) { pid_t my_pid = getpid(); int ret = setpgid(my_pid, my_pid); if (ret != 0) { assert(0); } std::string meta_file = persistence_path_dir_ + "/" + RUNNER_META_PREFIX + boost::lexical_cast<std::string>(sequence_id_); int meta_fd = open(meta_file.c_str(), O_WRONLY | O_CREAT, S_IRWXU); if (meta_fd == -1) { assert(0); } int64_t value = my_pid; int len = write(meta_fd, (void*)&value, sizeof(value)); if (len == -1) { close(meta_fd); assert(0); } value = m_task_info.task_id(); len = write(meta_fd, (void*)&value, sizeof(value)); if (len == -1) { close(meta_fd); assert(0); } if (0 != fsync(meta_fd)) { close(meta_fd); assert(0); } close(meta_fd); PutToCGroup(); StartTaskAfterFork(fds, stdout_fd, stderr_fd); } else { close(stdout_fd); close(stderr_fd); if (m_child_pid == -1) { LOG(WARNING, "task with id %ld fork failed err[%d: %s]", m_task_info.task_id(), errno, strerror(errno)); return -1; } m_group_pid = m_child_pid; SetStatus(RUNNING); } return 0; } void ContainerTaskRunner::Status(TaskStatus* status) { if (collector_ != NULL) { status->set_cpu_usage(collector_->GetCpuUsage()); status->set_memory_usage(collector_->GetMemoryUsage()); LOG(WARNING, "cpu usage %f memory usage %ld", status->cpu_usage(), status->memory_usage()); } status->set_job_id(m_task_info.job_id()); // check if it is running int ret = IsRunning(); if (ret == 0) { SetStatus(RUNNING); status->set_status(RUNNING); } else if (ret == 1) { SetStatus(COMPLETE); status->set_status(COMPLETE); } // last state is running ==> download finish else if (m_task_state == RUNNING || m_task_state == RESTART) { SetStatus(RESTART); if (ReStart() == 0) { status->set_status(RESTART); } else { SetStatus(ERROR); status->set_status(ERROR); } } // other state else { status->set_status(m_task_state); } LOG(WARNING, "task with id %ld state %s", m_task_info.task_id(), TaskState_Name(TaskState(m_task_state)).c_str()); return; } void ContainerTaskRunner::StopPost() { if (collector_ != NULL) { collector_->Clear(); } std::string meta_file = persistence_path_dir_ + "/" + RUNNER_META_PREFIX + boost::lexical_cast<std::string>(sequence_id_); if (!file::Remove(meta_file)) { LOG(WARNING, "remove %s failed", meta_file.c_str()); } return; } int ContainerTaskRunner::Stop(){ int status = AbstractTaskRunner::Stop(); LOG(INFO,"stop task %ld with status %d",m_task_info.task_id(),status); if(status != 0 ){ return status; } if (_cg_ctrl != NULL) { status = _cg_ctrl->Destroy(m_task_info.task_id()); LOG(INFO,"destroy cgroup for task %ld with status %d",m_task_info.task_id(),status); if (status != 0) { return status; } } StopPost(); return status; } bool ContainerTaskRunner::RecoverRunner(const std::string& persistence_path) { std::vector<std::string> files; if (!file::GetDirFilesByPrefix( persistence_path, RUNNER_META_PREFIX, &files)) { LOG(WARNING, "get meta files failed"); return false; } if (files.size() == 0) { return true; } int max_seq_id = -1; std::string last_meta_file; for (size_t i = 0; i < files.size(); i++) { std::string file = files[i]; size_t pos = file.find(RUNNER_META_PREFIX); if (pos == std::string::npos) { continue; } if (pos + RUNNER_META_PREFIX.size() >= file.size()) { LOG(WARNING, "meta file format err %s", file.c_str()); continue; } int cur_id = atoi(file.substr( pos + RUNNER_META_PREFIX.size()).c_str()); if (max_seq_id < cur_id) { max_seq_id = cur_id; last_meta_file = file; } } if (max_seq_id < 0) { return false; } std::string meta_file = last_meta_file; LOG(DEBUG, "start to recover %s", meta_file.c_str()); int fin = open(meta_file.c_str(), O_RDONLY); if (fin == -1) { LOG(WARNING, "open meta file failed %s err[%d: %s]", meta_file.c_str(), errno, strerror(errno)); return false; } size_t value; int len = read(fin, (void*)&value, sizeof(value)); if (len == -1) { LOG(WARNING, "read meta file failed err[%d: %s]", errno, strerror(errno)); close(fin); return false; } LOG(DEBUG, "recove gpid %lu", value); int ret = killpg((pid_t)value, 9); if (ret != 0 && errno != ESRCH) { LOG(WARNING, "fail to kill process group %lu", value); return false; } value = 0; len = read(fin, (void*)&value, sizeof(value)); if (len == -1) { LOG(WARNING, "read meta file failed err[%d: %s]", errno, strerror(errno)); close(fin); return false; } close(fin); std::vector<std::string> support_cgroup; // TODO configable support_cgroup.push_back("memory"); support_cgroup.push_back("cpu"); support_cgroup.push_back("cpuacct"); LOG(DEBUG, "destroy cgroup %lu", value); CGroupCtrl ctl(FLAGS_cgroup_root, support_cgroup); int max_retry_times = 10; ret = -1; while (max_retry_times-- > 0) { ret = ctl.Destroy(value); if (ret != 0) { common::ThisThread::Sleep(100); continue; } break; } if (ret == 0) { LOG(DEBUG, "destroy cgroup %lu success", value); return true; } return false; } }
leoYY/galaxy
src/agent/cgroup.cc
C++
bsd-3-clause
16,763
<?php return [ 'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=chicardi', 'username' => 'root', 'password' => 'sP#2p_31o!', 'charset' => 'utf8', 'enableSchemaCache' => true ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', ], 'rollbar' => [ 'environment' => 'chicardi.com', // you environment name ], ], ];
tolik505/baby
environments/chicardi.com/common/config/main-local.php
PHP
bsd-3-clause
555
process_is_foreground do with_feature :readline do require 'readline' require File.expand_path('../shared/size', __FILE__) describe "Readline::HISTORY.length" do it_behaves_like :readline_history_size, :length end end end
rubysl/rubysl-readline
spec/history/length_spec.rb
Ruby
bsd-3-clause
249
// ============================================================================ // Include files // ============================================================================ // Python // ============================================================================ #include "Python.h" // ============================================================================ // Ostap // ============================================================================ #include "Ostap/BLOB.h" #include "Ostap/PyBLOB.h" // ============================================================================ /** @file * Implementation file for functions form file Ostap/PyBLOB.h * @see Ostap::BLOB * @date 2019-04-24 * @author Vanya BELYAEV Ivan.Belyaev@itep.ru */ // ============================================================================ /* convert blob to python bytes * @see Ostap::BLOB * @param blob * @return PyBytes object from the blob */ // ============================================================================ PyObject* Ostap::blob_to_bytes ( const Ostap::BLOB& blob ) { #if defined (PY_MAJOR_VERSION) and PY_MAJOR_VERSION < 3 return PyString_FromStringAndSize ( (const char*) blob.buffer () , blob.size () ) ; #else return PyBytes_FromStringAndSize ( (const char*) blob.buffer () , blob.size () ) ; #endif } // ============================================================================ /* convert bytes to blob * @see Ostap::BLOB * @param blob the blib to be updated * @param bytes (INPUT) the bytes * @return True if conversion successul */ // ============================================================================ PyObject* Ostap::blob_from_bytes ( Ostap::BLOB& blob , PyObject* bytes ) { // // check the arguments // #if defined (PY_MAJOR_VERSION) and PY_MAJOR_VERSION < 3 if ( nullptr == bytes || !PyString_Check ( bytes ) ) #else if ( nullptr == bytes || !PyBytes_Check ( bytes ) ) #endif { PyErr_SetString( PyExc_TypeError, "Invalid bytes/string object" ) ; return NULL ; } // // set the blob // #if defined (PY_MAJOR_VERSION) and PY_MAJOR_VERSION < 3 blob.setBuffer ( PyString_Size ( bytes ) , PyString_AsString ( bytes ) ) ; #else blob.setBuffer ( PyBytes_Size ( bytes ) , PyBytes_AsString ( bytes ) ) ; #endif // Py_INCREF ( Py_True ); // return Py_True ; } // ========================================================================== // ============================================================================ // The END // ============================================================================
OstapHEP/ostap
source/src/PyBLOB.cpp
C++
bsd-3-clause
2,698
<?php namespace app\controllers; use Yii; use app\models\User; use app\models\UserSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\web\ForbiddenHttpException; use yii\filters\VerbFilter; use yii\db\IntegrityException; /** * UserController implements the CRUD actions for User model. */ class UserController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Displays a single User model. * @param integer $id * @return mixed */ public function actionView() { $model = new User(); $id = Yii::$app->request->post('id'); if(!$id){ $this->autorizaUsuario($id); $id = Yii::$app->user->identity->idusuario; //$model = User::findByEmail(Yii::$app->user->identity->email); } return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new User model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { if(!Yii::$app->user->isGuest) $this->redirect(['evento/index']); $model = new User(); if ($model->load(Yii::$app->request->post())) { if($model->save()){ $this->mensagens('success', 'Cadastro realizado', 'Cadastro efetuado com Sucesso'); return $this->redirect(['site/login']); }else{ return $this->render('create', [ 'model' => $model, ]); } } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing User model. * If update is successful, the browser will be redirected to the 'view' page. * * @param integer $id * @return mixed */ public function actionUpdate($id) { $this->autorizaUsuario ( $id ); $model = $this->findModel ( $id ); if(Yii::$app->user->identity->idusuario === $model->idusuario){ echo $model->senha."senha"; if ($model->load ( Yii::$app->request->post () ) ) { //$model->senha = md5($model->senha); if($model->save(false)){ return $this->redirect ( ['view', 'id' => $model->idusuario]); } } else { return $this->render('update', [ 'model' => $model, ]); } }else{ return $this->goBack(); } } /** * Deletes an existing User model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id){ $this->autorizaUsuario($id); $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return User the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('A página solicitada não foi encontrada.'); } } protected function autorizaUsuario($id){ if(Yii::$app->user->isGuest){ $this->redirect(['site/login']); } } /*Tipo: success, danger, warning*/ protected function mensagens($tipo, $titulo, $mensagem){ Yii::$app->session->setFlash($tipo, [ 'type' => $tipo, 'duration' => 1200, 'icon' => 'home', 'message' => $mensagem, 'title' => $titulo, 'positonY' => 'bottom', 'positonX' => 'right' ]); } }
schw/SGE3
controllers/UserController.php
PHP
bsd-3-clause
4,140
<?php use app\components\Common; use app\rbac\OwnPostRule; use yii\helpers\Html; ?> <article class="post hentry"> <header class="post-header"> <h3 class="content-title">Blog post title</h3> <div class="blog-entry-meta"> <div class="blog-entry-meta-date"> <i class="fa fa-clock-o"></i> <span class="blog-entry-meta-date-month"> <?= date('F', $model->updated_at); ?> </span> <span class="blog-entry-meta-date-day"> <?= date('d', $model->updated_at); ?>, </span> <span class="blog-entry-meta-date-year"> <?= date('Y', $model->updated_at); ?> </span> </div> <div class="blog-entry-meta-author"> <i class="fa fa-user"></i> <a href="#" class="blog-entry-meta-author"><?= $model->author->username ?></a> </div> <div class="blog-entry-meta-tags"> <i class="fa fa-tags"></i> <a href="#">Web Design</a>, <a href="#">Branding</a> </div> <div class="blog-entry-meta-comments"> <i class="fa fa-comments"></i> <a href="#" class="blog-entry-meta-comments">4 comments</a> </div> <?php $canEdit = \Yii::$app->user->can('updatePost') || \Yii::$app->user->can('updateOwnPost',['post'=>$model]); $canDelete = \Yii::$app->user->can('deletePost') || \Yii::$app->user->can('deleteOwnPost',['post'=>$model]); if($canEdit || $canDelete) { ?> <div class="blog-entry-admin"> <?php if($canEdit) { $options = [ 'title' => Yii::t('yii', 'Update'), 'aria-label' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ]; echo Html::a('<i class="fa fa-edit"></i>', '/post/update/'.$model->id, $options); } if($canDelete) { $options = [ 'title' => Yii::t('yii', 'Delete'), 'aria-label' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post', 'data-pjax' => '0', 'class' => 'blog-entry-admin-delete', ]; echo Html::a('<i class="fa fa-remove"></i>', '/post/delete/'.$model->id, $options); } ?> </div> <?php } ?> </div> </header> <div class="post-content"> <p> <?= Common::substrBoundary($model->content, 600); ?> </p> </div> <footer class="post-footer"> <a class="btn-small btn-color">Read More</a> </footer> </article> <div class="blog-divider"></div>
svd222/blog
themes/lamar/views/post/_post.php
PHP
bsd-3-clause
2,933
/* * Copyright (c) 2013, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE.txt file for terms. */ /*jslint nomen:true, node:true */ 'use strict'; var core = require('./core'); module.exports = { describe: { summary: 'Compile dust templates to yui modules', extensions: ['dust'], nameParser: core.name }, fileUpdated: function (evt, api) { var self = this, file = evt.file, source_path = file.fullPath, bundleName = file.bundleName, templateName = this.describe.nameParser(source_path), moduleName = bundleName + '-templates-' + templateName, destination_path = moduleName + '.js'; return api.promise(function (fulfill, reject) { var compiled, partials; try { partials = core.partials(source_path); compiled = core.compile(source_path, templateName); } catch (e) { reject(e); } // trying to write the destination file which will fulfill or reject the initial promise api.writeFileInBundle(bundleName, destination_path, self._wrapAsYUI(bundleName, templateName, moduleName, compiled, partials)) .then(function () { // provisioning the module to be used on the server side automatically evt.bundle.useServerModules = evt.bundle.useServerModules || []; evt.bundle.useServerModules.push(moduleName); // we are now ready to roll fulfill(); }, reject); }); }, _wrapAsYUI: function (bundleName, templateName, moduleName, compiled, partials) { // base dependency var dependencies = ["template-base", "template-dust"]; // each partial should be provisioned thru another yui module // and the name of the partial should translate into a yui module // to become a dependency partials = partials || []; partials.forEach(function (name) { // adding prefix to each partial dependencies.push(bundleName + '-templates-' + name); }); return [ 'YUI.add("' + moduleName + '",function(Y, NAME){', ' var dust = Y.config.global.dust;', '', compiled, '', ' Y.Template.register("' + bundleName + '/' + templateName + '", function (data) {', ' var content;', ' dust.render("' + templateName + '", data, function (err, content) {', ' result = content;', ' });', ' return result; // hack to make dust sync', ' });', '}, "", {requires: ' + JSON.stringify(dependencies) + '});' ].join('\n'); } };
yahoo/locator-dust
lib/plugin.js
JavaScript
bsd-3-clause
2,981
package com.ap.straight.unsupported; import java.sql.*; import java.sql.ResultSet; public abstract class AbstractStatement implements Statement { public int getResultSetHoldability() throws SQLException { throw new UnsupportedOperationException(); } public boolean getMoreResults(int current) throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, int[] columnIndexes) throws SQLException { throw new UnsupportedOperationException(); } public java.sql.ResultSet getGeneratedKeys() throws SQLException { throw new UnsupportedOperationException(); } public int executeUpdate(String sql, String[] columnNames) throws SQLException { throw new UnsupportedOperationException(); } public boolean execute(String sql, String[] columnNames) throws SQLException { throw new UnsupportedOperationException(); } public boolean isClosed() throws SQLException { throw new UnsupportedOperationException(); } public void setPoolable(boolean poolable) throws SQLException { throw new UnsupportedOperationException(); } public boolean isPoolable() throws SQLException { throw new UnsupportedOperationException(); } public void closeOnCompletion() throws SQLException { throw new UnsupportedOperationException(); } public boolean isCloseOnCompletion() throws SQLException { throw new UnsupportedOperationException(); } }
jeanlazarou/straight
src/com/ap/straight/unsupported/AbstractStatement.java
Java
bsd-3-clause
1,965
/* fileedit.cpp Редактирование файла - надстройка над editor.cpp */ /* Copyright © 1996 Eugene Roshal Copyright © 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ // BUGBUG #include "platform.headers.hpp" // Self: #include "fileedit.hpp" // Internal: #include "keyboard.hpp" #include "encoding.hpp" #include "macroopcode.hpp" #include "keys.hpp" #include "ctrlobj.hpp" #include "poscache.hpp" #include "filepanels.hpp" #include "panel.hpp" #include "dialog.hpp" #include "FarDlgBuilder.hpp" #include "fileview.hpp" #include "help.hpp" #include "manager.hpp" #include "namelist.hpp" #include "history.hpp" #include "cmdline.hpp" #include "scrbuf.hpp" #include "savescr.hpp" #include "filestr.hpp" #include "TPreRedrawFunc.hpp" #include "syslog.hpp" #include "taskbar.hpp" #include "interf.hpp" #include "message.hpp" #include "config.hpp" #include "delete.hpp" #include "datetime.hpp" #include "pathmix.hpp" #include "dirmix.hpp" #include "strmix.hpp" #include "exitcode.hpp" #include "constitle.hpp" #include "wakeful.hpp" #include "uuids.far.dialogs.hpp" #include "stddlg.hpp" #include "plugins.hpp" #include "lang.hpp" #include "keybar.hpp" #include "string_utils.hpp" #include "cvtname.hpp" #include "global.hpp" #include "file_io.hpp" // Platform: #include "platform.env.hpp" #include "platform.fs.hpp" // Common: #include "common/view/enumerate.hpp" // External: #include "format.hpp" //---------------------------------------------------------------------------- enum enumOpenEditor { ID_OE_TITLE, ID_OE_OPENFILETITLE, ID_OE_FILENAME, ID_OE_SEPARATOR1, ID_OE_CODEPAGETITLE, ID_OE_CODEPAGE, ID_OE_SEPARATOR2, ID_OE_OK, ID_OE_CANCEL, ID_OE_COUNT }; static intptr_t hndOpenEditor(Dialog* Dlg, intptr_t msg, intptr_t param1, void* param2) { if (msg == DN_INITDIALOG) { const auto codepage = *static_cast<uintptr_t*>(param2); codepages::instance().FillCodePagesList(Dlg, ID_OE_CODEPAGE, codepage, true, false, true, false, false); } if (msg == DN_CLOSE) { if (param1 == ID_OE_OK) { const auto param = reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr)); FarListPos pos={sizeof(FarListPos)}; Dlg->SendMessage(DM_LISTGETCURPOS, ID_OE_CODEPAGE, &pos); *param = Dlg->GetListItemSimpleUserData(ID_OE_CODEPAGE, pos.SelectPos); return TRUE; } } return Dlg->DefProc(msg, param1, param2); } bool dlgOpenEditor(string &strFileName, uintptr_t &codepage) { auto EditDlg = MakeDialogItems<ID_OE_COUNT>( { { DI_DOUBLEBOX, {{3, 1}, {72, 8}}, DIF_NONE, msg(lng::MEditTitle), }, { DI_TEXT, {{5, 2}, {0 , 2}}, DIF_NONE, msg(lng::MEditOpenCreateLabel), }, { DI_EDIT, {{5, 3}, {70, 3}}, DIF_FOCUS | DIF_HISTORY | DIF_USELASTHISTORY | DIF_EDITEXPAND | DIF_EDITPATH, }, { DI_TEXT, {{-1, 4}, {0, 4}}, DIF_SEPARATOR, {} }, { DI_TEXT, {{5, 5}, {0, 5}}, DIF_NONE, msg(lng::MEditCodePage), }, { DI_COMBOBOX, {{25, 5}, {70, 5}}, DIF_DROPDOWNLIST | DIF_LISTWRAPMODE | DIF_LISTAUTOHIGHLIGHT, }, { DI_TEXT, {{-1, 6}, {0, 6}}, DIF_SEPARATOR, {} }, { DI_BUTTON, {{0, 7}, {0, 7}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MOk), }, { DI_BUTTON, {{0, 7}, {0, 7}}, DIF_CENTERGROUP, msg(lng::MCancel), }, }); EditDlg[ID_OE_FILENAME].strHistory = L"NewEdit"sv; const auto Dlg = Dialog::create(EditDlg, hndOpenEditor, &codepage); Dlg->SetPosition({ -1, -1, 76, 10 }); Dlg->SetHelp(L"FileOpenCreate"sv); Dlg->SetId(FileOpenCreateId); Dlg->Process(); if (Dlg->GetExitCode() == ID_OE_OK) { strFileName = EditDlg[ID_OE_FILENAME].strData; return true; } return false; } static bool dlgBadEditorCodepage(uintptr_t& codepage) { DialogBuilder Builder(lng::MWarning); Builder.AddText(lng::MEditorLoadCPWarn1)->Flags = DIF_CENTERTEXT; Builder.AddText(lng::MEditorLoadCPWarn2)->Flags = DIF_CENTERTEXT; Builder.AddText(lng::MEditorSaveNotRecommended)->Flags = DIF_CENTERTEXT; Builder.AddSeparator(); IntOption cp_val; cp_val = codepage; std::vector<DialogBuilderListItem> Items; codepages::instance().FillCodePagesList(Items, true, false, true, false, false); Builder.AddComboBox(cp_val, 46, Items); Builder.AddOKCancel(); Builder.SetDialogMode(DMODE_WARNINGSTYLE); Builder.SetId(BadEditorCodePageId); if (!Builder.ShowDialog()) return false; codepage = cp_val; return true; } enum enumSaveFileAs { ID_SF_TITLE, ID_SF_SAVEASFILETITLE, ID_SF_FILENAME, ID_SF_SEPARATOR1, ID_SF_CODEPAGETITLE, ID_SF_CODEPAGE, ID_SF_SIGNATURE, ID_SF_SEPARATOR2, ID_SF_SAVEASFORMATTITLE, ID_SF_DONOTCHANGE, ID_SF_WINDOWS, ID_SF_UNIX, ID_SF_MAC, ID_SF_SEPARATOR3, ID_SF_OK, ID_SF_CANCEL, ID_SF_COUNT }; static intptr_t hndSaveFileAs(Dialog* Dlg, intptr_t msg, intptr_t param1, void* param2) { static uintptr_t CurrentCodepage = 0; switch (msg) { case DN_INITDIALOG: { CurrentCodepage = *reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr)); codepages::instance().FillCodePagesList(Dlg, ID_SF_CODEPAGE, CurrentCodepage, false, false, false, false, false); break; } case DN_CLOSE: { if (param1 == ID_SF_OK) { const auto CodepagePtr = reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr)); FarListPos pos={sizeof(FarListPos)}; Dlg->SendMessage(DM_LISTGETCURPOS, ID_SF_CODEPAGE, &pos); *CodepagePtr = Dlg->GetListItemSimpleUserData(ID_SF_CODEPAGE, pos.SelectPos); return TRUE; } break; } case DN_EDITCHANGE: { if (param1==ID_SF_CODEPAGE) { FarListPos pos={sizeof(FarListPos)}; Dlg->SendMessage(DM_LISTGETCURPOS,ID_SF_CODEPAGE,&pos); const uintptr_t cp = Dlg->GetListItemSimpleUserData(ID_SF_CODEPAGE, pos.SelectPos); if (cp != CurrentCodepage) { if (IsUnicodeOrUtfCodePage(cp)) { if (!IsUnicodeOrUtfCodePage(CurrentCodepage)) Dlg->SendMessage(DM_SETCHECK,ID_SF_SIGNATURE,ToPtr(Global->Opt->EdOpt.AddUnicodeBOM)); Dlg->SendMessage(DM_ENABLE,ID_SF_SIGNATURE,ToPtr(TRUE)); } else { Dlg->SendMessage(DM_SETCHECK,ID_SF_SIGNATURE,ToPtr(BSTATE_UNCHECKED)); Dlg->SendMessage(DM_ENABLE, ID_SF_SIGNATURE, ToPtr(FALSE)); } CurrentCodepage = cp; return TRUE; } } break; } default: break; } return Dlg->DefProc(msg, param1, param2); } static bool dlgSaveFileAs(string &strFileName, eol& Eol, uintptr_t &codepage, bool &AddSignature) { const auto ucp = IsUnicodeOrUtfCodePage(codepage); auto EditDlg = MakeDialogItems<ID_SF_COUNT>( { { DI_DOUBLEBOX, {{3, 1 }, {72, 15}}, DIF_NONE, msg(lng::MEditTitle), }, { DI_TEXT, {{5, 2 }, {0, 2 }}, DIF_NONE, msg(lng::MEditSaveAs), }, { DI_EDIT, {{5, 3 }, {70, 3 }}, DIF_FOCUS | DIF_HISTORY | DIF_EDITEXPAND | DIF_EDITPATH, }, { DI_TEXT, {{-1, 4 }, {0, 4 }}, DIF_SEPARATOR, }, { DI_TEXT, {{5, 5 }, {0, 5 }}, DIF_NONE, msg(lng::MEditCodePage), }, { DI_COMBOBOX, {{25, 5 }, {70, 5 }}, DIF_DROPDOWNLIST | DIF_LISTWRAPMODE | DIF_LISTAUTOHIGHLIGHT, }, { DI_CHECKBOX, {{5, 6 }, {0, 6 }}, ucp ? DIF_NONE : DIF_DISABLE,msg(lng::MEditAddSignature), }, { DI_TEXT, {{-1, 7 }, {0, 7 }}, DIF_SEPARATOR, }, { DI_TEXT, {{5, 8 }, {0, 8 }}, DIF_NONE, msg(lng::MEditSaveAsFormatTitle), }, { DI_RADIOBUTTON, {{5, 9 }, {0, 9 }}, DIF_GROUP, msg(lng::MEditSaveOriginal), }, { DI_RADIOBUTTON, {{5, 10}, {0, 10}}, DIF_NONE, msg(lng::MEditSaveDOS), }, { DI_RADIOBUTTON, {{5, 11}, {0, 11}}, DIF_NONE, msg(lng::MEditSaveUnix), }, { DI_RADIOBUTTON, {{5, 12}, {0, 12}}, DIF_NONE, msg(lng::MEditSaveMac), }, { DI_TEXT, {{-1, 13}, {0, 13}}, DIF_SEPARATOR, }, { DI_BUTTON, {{0, 14}, {0, 14}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MEditorSave), }, { DI_BUTTON, {{0, 14}, {0, 14}}, DIF_CENTERGROUP, msg(lng::MCancel), }, }); EditDlg[ID_SF_FILENAME].strHistory = L"NewEdit"sv; EditDlg[ID_SF_FILENAME].strData = (/*Flags.Check(FFILEEDIT_SAVETOSAVEAS)?strFullFileName:strFileName*/strFileName); EditDlg[ID_SF_SIGNATURE].Selected = AddSignature; if (const auto pos = EditDlg[ID_SF_FILENAME].strData.find(msg(lng::MNewFileName)); pos != string::npos) EditDlg[ID_SF_FILENAME].strData.resize(pos); const auto EolToIndex = [&]() { if (Eol == eol::win) return 1; if (Eol == eol::unix) return 2; if (Eol == eol::mac) return 3; return 0; }; EditDlg[ID_SF_DONOTCHANGE + EolToIndex()].Selected = TRUE; const auto Dlg = Dialog::create(EditDlg, hndSaveFileAs, &codepage); Dlg->SetPosition({ -1, -1, 76, 17 }); Dlg->SetHelp(L"FileSaveAs"sv); Dlg->SetId(FileSaveAsId); Dlg->Process(); if ((Dlg->GetExitCode() == ID_SF_OK) && !EditDlg[ID_SF_FILENAME].strData.empty()) { strFileName = EditDlg[ID_SF_FILENAME].strData; AddSignature=EditDlg[ID_SF_SIGNATURE].Selected!=0; if (EditDlg[ID_SF_DONOTCHANGE].Selected) Eol = eol::none; else if (EditDlg[ID_SF_WINDOWS].Selected) Eol = eol::win; else if (EditDlg[ID_SF_UNIX].Selected) Eol = eol::unix; else if (EditDlg[ID_SF_MAC].Selected) Eol = eol::mac; return true; } return false; } fileeditor_ptr FileEditor::create(const string_view Name, uintptr_t codepage, DWORD InitFlags, int StartLine, int StartChar, const string* PluginData, EDITOR_FLAGS OpenModeExstFile) { auto FileEditorPtr = std::make_shared<FileEditor>(private_tag()); FileEditorPtr->ScreenObjectWithShadow::SetPosition({ 0, 0, ScrX, ScrY }); FileEditorPtr->m_Flags.Set(InitFlags); FileEditorPtr->m_Flags.Set(FFILEEDIT_FULLSCREEN); FileEditorPtr->Init(Name, codepage, nullptr, StartLine, StartChar, PluginData, FALSE, nullptr, OpenModeExstFile); return FileEditorPtr; } fileeditor_ptr FileEditor::create(const string_view Name, uintptr_t codepage, DWORD InitFlags, int StartLine, int StartChar, const string* Title, rectangle Position, int DeleteOnClose, const window_ptr& Update, EDITOR_FLAGS OpenModeExstFile) { auto FileEditorPtr = std::make_shared<FileEditor>(private_tag()); FileEditorPtr->m_Flags.Set(InitFlags); // BUGBUG WHY ALL THIS? if (Position.left < 0) Position.left = 0; if (Position.right < 0 || Position.right > ScrX) Position.right = ScrX; if (Position.top < 0) Position.top = 0; if (Position.bottom < 0 || Position.bottom > ScrY) Position.bottom = ScrY; if (Position.left > Position.right) { Position.left = 0; Position.right = ScrX; } if (Position.top > Position.bottom) { Position.top = 0; Position.bottom = ScrY; } FileEditorPtr->SetPosition(Position); FileEditorPtr->m_Flags.Change(FFILEEDIT_FULLSCREEN, (!Position.left && !Position.top && Position.right == ScrX && Position.bottom == ScrY)); string EmptyTitle; FileEditorPtr->Init(Name, codepage, Title, StartLine, StartChar, &EmptyTitle, DeleteOnClose, Update, OpenModeExstFile); return FileEditorPtr; } /* $ 07.05.2001 DJ в деструкторе грохаем EditNamesList, если он был создан, а в SetNamesList() создаем EditNamesList и копируем туда значения */ /* Вызов деструкторов идет так: FileEditor::~FileEditor() Editor::~Editor() ... */ FileEditor::~FileEditor() { if (!m_Flags.Check(FFILEEDIT_OPENFAILED)) { /* $ 11.10.2001 IS Удалим файл вместе с каталогом, если это просится и файла с таким же именем не открыто в других окнах. */ /* $ 14.06.2001 IS Если установлен FEDITOR_DELETEONLYFILEONCLOSE и сброшен FEDITOR_DELETEONCLOSE, то удаляем только файл. */ if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE) && !Global->WindowManager->CountWindowsWithName(strFullFileName)) { if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE)) DeleteFileWithFolder(strFullFileName); else { (void)os::fs::set_file_attributes(strFullFileName,FILE_ATTRIBUTE_NORMAL); // BUGBUG (void)os::fs::delete_file(strFullFileName); //BUGBUG } } } } void FileEditor::Init( const string_view Name, uintptr_t codepage, const string* Title, int StartLine, int StartChar, const string* PluginData, int DeleteOnClose, const window_ptr& Update, EDITOR_FLAGS OpenModeExstFile ) { m_windowKeyBar = std::make_unique<KeyBar>(shared_from_this()); const auto BlankFileName = Name == msg(lng::MNewFileName) || Name.empty(); bEE_READ_Sent = false; bLoaded = false; m_bAddSignature = false; m_editor = std::make_unique<Editor>(shared_from_this(), codepage); m_codepage = codepage; *AttrStr=0; m_FileAttributes=INVALID_FILE_ATTRIBUTES; SetTitle(Title); // $ 17.08.2001 KM - Добавлено для поиска по AltF7. При редактировании найденного файла из архива для клавиши F2 сделать вызов ShiftF2. m_Flags.Change(FFILEEDIT_SAVETOSAVEAS, BlankFileName); if (BlankFileName && !m_Flags.Check(FFILEEDIT_CANNEWFILE)) { SetExitCode(XC_OPEN_ERROR); return; } SetPluginData(PluginData); m_editor->SetHostFileEditor(this); SetCanLoseFocus(m_Flags.Check(FFILEEDIT_ENABLEF6)); strStartDir = os::fs::GetCurrentDirectory(); if (!SetFileName(Name)) { SetExitCode(XC_OPEN_ERROR); return; } { if (auto EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName)) { int SwitchTo=FALSE; if (!EditorWindow->GetCanLoseFocus(true) || Global->Opt->Confirm.AllowReedit) { int Result = XC_EXISTS; if (OpenModeExstFile == EF_OPENMODE_QUERY) { int MsgCode; if (m_Flags.Check(FFILEEDIT_ENABLEF6)) { MsgCode = Message(0, msg(lng::MEditTitle), { strFullFileName, msg(lng::MAskReload) }, { lng::MCurrent, lng::MNewOpen, lng::MReload, lng::MCancel }, L"EditorReload"sv, &EditorReloadId); } else { MsgCode = Message(0, msg(lng::MEditTitle), { strFullFileName, msg(lng::MAskReload) }, { lng::MNewOpen, lng::MCancel }, L"EditorReload"sv, &EditorReloadModalId); if (MsgCode == Message::first_button) MsgCode = Message::second_button; } switch (MsgCode) { case Message::first_button: Result = XC_EXISTS; break; case Message::second_button: Result = XC_OPEN_NEWINSTANCE; break; case Message::third_button: Result = XC_RELOAD; break; default: SetExitCode(XC_LOADING_INTERRUPTED); return; } } else { if (m_Flags.Check(FFILEEDIT_ENABLEF6)) { switch (OpenModeExstFile) { case EF_OPENMODE_USEEXISTING: Result = XC_EXISTS; break; case EF_OPENMODE_NEWIFOPEN: Result = XC_OPEN_NEWINSTANCE; break; case EF_OPENMODE_RELOADIFOPEN: Result = XC_RELOAD; break; default: SetExitCode(XC_EXISTS); return; } } else { switch (OpenModeExstFile) { case EF_OPENMODE_NEWIFOPEN: Result = XC_OPEN_NEWINSTANCE; break; } } } switch (Result) { case XC_EXISTS: SwitchTo=TRUE; SetExitCode(Result); // ??? break; case XC_OPEN_NEWINSTANCE: SetExitCode(Result); // ??? break; case XC_RELOAD: { //файл могли уже закрыть. например макросом в диалоговой процедуре предыдущего Message. EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName); if (EditorWindow) { EditorWindow->SetFlags(FFILEEDIT_DISABLESAVEPOS); Global->WindowManager->DeleteWindow(EditorWindow); } SetExitCode(Result); // -2 ??? } break; } } else { SwitchTo=TRUE; SetExitCode((OpenModeExstFile != EF_OPENMODE_QUERY) ? XC_EXISTS : XC_MODIFIED); // TRUE??? } if (SwitchTo) { //файл могли уже закрыть. например макросом в диалоговой процедуре предыдущего Message. EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName); if (EditorWindow) { Global->WindowManager->ActivateWindow(EditorWindow); } return ; } } } /* $ 29.11.2000 SVS Если файл имеет атрибут ReadOnly или System или Hidden, И параметр на запрос выставлен, то сначала спросим. */ /* $ 03.12.2000 SVS System или Hidden - задаются отдельно */ /* $ 15.12.2000 SVS - Shift-F4, новый файл. Выдает сообщение :-( */ const os::fs::file_status FileStatus(Name); /* $ 05.06.2001 IS + посылаем подальше всех, кто пытается отредактировать каталог */ if (os::fs::is_directory(FileStatus)) { Message(MSG_WARNING, msg(lng::MEditTitle), { msg(lng::MEditCanNotEditDirectory) }, { lng::MOk }, {}, &EditorCanNotEditDirectoryId); SetExitCode(XC_OPEN_ERROR); return; } if (m_editor->EdOpt.ReadOnlyLock & 1_bit && FileStatus.check(FILE_ATTRIBUTE_READONLY | /* Hidden=0x2 System=0x4 - располагаются во 2-м полубайте, поэтому применяем маску 0110.0000 и сдвигаем на свое место => 0000.0110 и получаем те самые нужные атрибуты */ ((m_editor->EdOpt.ReadOnlyLock & 0b0110'0000) >> 4) ) ) { if (Message(MSG_WARNING, msg(lng::MEditTitle), { string(Name), msg(lng::MEditRSH), msg(lng::MEditROOpen) }, { lng::MYes, lng::MNo }, {}, &EditorOpenRSHId) != Message::first_button) { SetExitCode(XC_OPEN_ERROR); return; } } m_editor->SetPosition({ m_Where.left, m_Where.top + (IsTitleBarVisible()? 1 : 0), m_Where.right, m_Where.bottom - (IsKeyBarVisible()? 1 : 0) }); m_editor->SetStartPos(StartLine,StartChar); SetDeleteOnClose(DeleteOnClose); int UserBreak; /* $ 06.07.2001 IS При создании файла с нуля так же посылаем плагинам событие EE_READ, дабы не нарушать однообразие. */ if (!os::fs::exists(FileStatus)) m_Flags.Set(FFILEEDIT_NEW); if (BlankFileName && m_Flags.Check(FFILEEDIT_CANNEWFILE)) m_Flags.Set(FFILEEDIT_NEW); if (m_Flags.Check(FFILEEDIT_NEW)) m_bAddSignature = Global->Opt->EdOpt.AddUnicodeBOM; if (m_Flags.Check(FFILEEDIT_LOCKED)) m_editor->m_Flags.Set(Editor::FEDITOR_LOCKMODE); error_state_ex ErrorState; while (!LoadFile(strFullFileName,UserBreak, ErrorState)) { if (BlankFileName) { m_Flags.Clear(FFILEEDIT_OPENFAILED); //AY: ну так как редактор мы открываем то видимо надо и сбросить ошибку открытия UserBreak=0; } if (!m_Flags.Check(FFILEEDIT_NEW) || UserBreak) { if (UserBreak!=1) { if(OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotOpen), false) == operation::retry) continue; else SetExitCode(XC_OPEN_ERROR); } else { SetExitCode(XC_LOADING_INTERRUPTED); } // Ахтунг. Ниже комментарии оставлены в назидании потомкам (до тех пор, пока не измениться манагер) //WindowManager->DeleteWindow(this); // BugZ#546 - Editor валит фар! //Global->CtrlObject->Cp()->Redraw(); //AY: вроде как не надо, делает проблемы с прорисовкой если в редакторе из истории попытаться выбрать несуществующий файл // если прервали загрузку, то фреймы нужно проапдейтить, чтобы предыдущие месаги не оставались на экране if (!Global->Opt->Confirm.Esc && UserBreak && GetExitCode() == XC_LOADING_INTERRUPTED) Global->WindowManager->RefreshWindow(); return; } if (m_codepage==CP_DEFAULT || m_codepage == CP_REDETECT) m_codepage = GetDefaultCodePage(); m_editor->SetCodePage(m_codepage, nullptr, false); break; } if (GetExitCode() == XC_LOADING_INTERRUPTED || GetExitCode() == XC_OPEN_ERROR) return; InitKeyBar(); // Note: bottom - bottom m_windowKeyBar->SetPosition({ m_Where.left, m_Where.bottom, m_Where.right, m_Where.bottom }); if (IsKeyBarVisible()) { m_windowKeyBar->Show(); } else { m_windowKeyBar->Hide(); } SetMacroMode(MACROAREA_EDITOR); F4KeyOnly=true; bLoaded = true; if (m_Flags.Check(FFILEEDIT_ENABLEF6)) { if (Update) Global->WindowManager->ReplaceWindow(Update, shared_from_this()); else Global->WindowManager->InsertWindow(shared_from_this()); } else { if (Update) Global->WindowManager->DeleteWindow(Update); Global->WindowManager->ExecuteWindow(shared_from_this()); } Global->WindowManager->CallbackWindow([this](){ ReadEvent(); }); } void FileEditor::ReadEvent() { Global->CtrlObject->Plugins->ProcessEditorEvent(EE_READ, nullptr, m_editor.get()); bEE_READ_Sent = true; Global->WindowManager->RefreshWindow(); //в EE_READ поменялась позиция курсора или размер табуляции. } void FileEditor::InitKeyBar() { auto& Keybar = *m_windowKeyBar; Keybar.SetLabels(lng::MEditF1); if (Global->OnlyEditorViewerUsed) { Keybar[KBL_SHIFT][F4].clear(); Keybar[KBL_CTRL][F10].clear(); } if (!GetCanLoseFocus()) { Keybar[KBL_MAIN][F12].clear(); Keybar[KBL_ALT][F11].clear(); Keybar[KBL_SHIFT][F4].clear(); } if (m_Flags.Check(FFILEEDIT_SAVETOSAVEAS)) Keybar[KBL_MAIN][F2] = msg(lng::MEditShiftF2); if (!m_Flags.Check(FFILEEDIT_ENABLEF6)) Keybar[KBL_MAIN][F6].clear(); Keybar[KBL_MAIN][F8] = f8cps.NextCPname(m_codepage); Keybar.SetCustomLabels(KBA_EDITOR); } void FileEditor::SetNamesList(NamesList& Names) { EditNamesList = std::move(Names); } void FileEditor::Show() { if (m_Flags.Check(FFILEEDIT_FULLSCREEN)) { if (IsKeyBarVisible()) { m_windowKeyBar->SetPosition({ 0, ScrY, ScrX, ScrY }); } ScreenObjectWithShadow::SetPosition({ 0, 0, ScrX, ScrY }); } if (IsKeyBarVisible()) { m_windowKeyBar->Redraw(); } m_editor->SetPosition({ m_Where.left, m_Where.top + (IsTitleBarVisible()? 1 : 0), m_Where.right, m_Where.bottom - (IsKeyBarVisible()? 1 : 0) }); ScreenObjectWithShadow::Show(); } void FileEditor::DisplayObject() { if (!m_bClosing) { m_editor->Show(); } } long long FileEditor::VMProcess(int OpCode, void* vParam, long long iParam) { if (OpCode == MCODE_V_EDITORSTATE) { DWORD MacroEditState = 0; MacroEditState |= m_Flags.Check(FFILEEDIT_NEW)? 0_bit : 0; MacroEditState |= m_Flags.Check(FFILEEDIT_ENABLEF6)? 1_bit : 0; MacroEditState |= m_Flags.Check(FFILEEDIT_DELETEONCLOSE)? 2_bit : 0; MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)? 3_bit : 0; MacroEditState |= m_editor->IsStreamSelection()? 4_bit : 0; MacroEditState |= m_editor->IsVerticalSelection()? 5_bit : 0; MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_WASCHANGED)? 6_bit : 0; MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_OVERTYPE)? 7_bit : 0; MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_CURPOSCHANGEDBYPLUGIN)? 8_bit : 0; MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE)? 9_bit : 0; MacroEditState |= m_editor->EdOpt.PersistentBlocks? 10_bit : 0; MacroEditState |= !GetCanLoseFocus()? 11_bit : 0; MacroEditState |= Global->OnlyEditorViewerUsed ? 27_bit | 11_bit : 0; return MacroEditState; } if (OpCode == MCODE_V_EDITORCURPOS) return m_editor->m_it_CurLine->GetTabCurPos()+1; if (OpCode == MCODE_V_EDITORCURLINE) return m_editor->m_it_CurLine.Number() + 1; if (OpCode == MCODE_V_ITEMCOUNT || OpCode == MCODE_V_EDITORLINES) return m_editor->Lines.size(); if (OpCode == MCODE_F_KEYBAR_SHOW) { int PrevMode=IsKeyBarVisible()?2:1; switch (iParam) { case 0: break; case 1: Global->Opt->EdOpt.ShowKeyBar = true; m_windowKeyBar->Show(); Show(); break; case 2: Global->Opt->EdOpt.ShowKeyBar = false; m_windowKeyBar->Hide(); Show(); break; case 3: ProcessKey(Manager::Key(KEY_CTRLB)); break; default: PrevMode=0; break; } return PrevMode; } return m_editor->VMProcess(OpCode,vParam,iParam); } bool FileEditor::ProcessKey(const Manager::Key& Key) { return ReProcessKey(Key, false); } bool FileEditor::ReProcessKey(const Manager::Key& Key, bool CalledFromControl) { const auto LocalKey = Key(); if (none_of(LocalKey, KEY_F4, KEY_IDLE)) F4KeyOnly=false; if (m_Flags.Check(FFILEEDIT_REDRAWTITLE) && ((LocalKey & 0x00ffffff) < KEY_END_FKEY || IsInternalKeyReal(LocalKey & 0x00ffffff))) ShowConsoleTitle(); // Все остальные необработанные клавиши пустим далее /* $ 28.04.2001 DJ не передаем KEY_MACRO* плагину - поскольку ReadRec в этом случае никак не соответствует обрабатываемой клавише, возникают разномастные глюки */ if (in_closed_range(KEY_MACRO_BASE, LocalKey, KEY_MACRO_ENDBASE) || in_closed_range(KEY_OP_BASE, LocalKey, KEY_OP_ENDBASE)) // исключаем MACRO { // ; // } switch (LocalKey) { case KEY_F6: { if (m_Flags.Check(FFILEEDIT_ENABLEF6)) { int FirstSave=1; auto cp = m_codepage; // проверка на "а может это говно удалили уже?" // возможно здесь она и не нужна! // хотя, раз уж были изменения, то if (m_editor->IsFileChanged() && // в текущем сеансе были изменения? !os::fs::exists(strFullFileName)) { switch (Message(MSG_WARNING, msg(lng::MEditTitle), { msg(lng::MEditSavedChangedNonFile), msg(lng::MEditSavedChangedNonFile2) }, { lng::MHYes, lng::MHNo }, {}, &EditorSaveF6DeletedId)) { case 0: if (ProcessKey(Manager::Key(KEY_F2))) { FirstSave=0; break; } [[fallthrough]]; default: return false; } } if (!FirstSave || m_editor->IsFileChanged() || os::fs::exists(strFullFileName)) { const auto FilePos = m_editor->GetCurPos(true, m_bAddSignature); /* $ 01.02.2001 IS ! Открываем viewer с указанием длинного имени файла, а не короткого */ bool NeedQuestion = true; if (ProcessQuitKey(FirstSave,NeedQuestion,false)) { int delete_on_close = 0; if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE)) delete_on_close = 1; else if (m_Flags.Check(FFILEEDIT_DELETEONLYFILEONCLOSE)) delete_on_close = 2; SetDeleteOnClose(0); FileViewer::create( strFullFileName, GetCanLoseFocus(), m_Flags.Check(FFILEEDIT_DISABLEHISTORY), false, FilePos, {}, &EditNamesList, m_Flags.Check(FFILEEDIT_SAVETOSAVEAS), cp, strTitle, delete_on_close, shared_from_this()); } } return true; } break; // отдадим F6 плагинам, если есть запрет на переключение } /* $ 10.05.2001 DJ Alt-F11 - показать view/edit history */ case KEY_ALTF11: case KEY_RALTF11: { if (GetCanLoseFocus()) { Global->CtrlObject->CmdLine()->ShowViewEditHistory(); return true; } break; // отдадим Alt-F11 на растерзание плагинам, если редактор модальный } } bool ProcessedNext = true; _SVS(if (LocalKey=='n' || LocalKey=='m')) _SVS(SysLog(L"%d Key='%c'",__LINE__,LocalKey)); const auto MacroState = Global->CtrlObject->Macro.GetState(); if (!CalledFromControl && (MacroState == MACROSTATE_RECORDING_COMMON || MacroState == MACROSTATE_EXECUTING_COMMON || MacroState == MACROSTATE_NOMACRO)) { assert(Key.IsEvent()); if (Key.IsReal()) { ProcessedNext=!ProcessEditorInput(Key.Event()); } } if (ProcessedNext) { switch (LocalKey) { case KEY_F1: { help::show(L"Editor"sv); return true; } /* $ 25.04.2001 IS ctrl+f - вставить в строку полное имя редактируемого файла */ case KEY_CTRLF: case KEY_RCTRLF: { if (!m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE)) { m_editor->Pasting++; m_editor->TextChanged(true); if (!m_editor->EdOpt.PersistentBlocks && m_editor->IsAnySelection()) { m_editor->TurnOffMarkingBlock(); m_editor->DeleteBlock(); } m_editor->Paste(strFullFileName); //??? //if (!EdOpt.PersistentBlocks) m_editor->UnmarkBlock(); m_editor->Pasting--; m_editor->Show(); //??? } return true; } /* $ 24.08.2000 SVS + Добавляем реакцию показа бакграунда на клавишу CtrlAltShift */ case KEY_CTRLO: case KEY_RCTRLO: { m_editor->Hide(); // $ 27.09.2000 skv - To prevent redraw in macro with Ctrl-O if (Global->WindowManager->ShowBackground()) { SetCursorType(false, 0); WaitKey(); } Global->WindowManager->RefreshAll(); return true; } case KEY_F2: case KEY_SHIFTF2: { auto Done = false; while (!Done) // бьемся до упора { // проверим путь к файлу, может его уже снесли... // BUGBUG, похоже, не работает const auto pos = FindLastSlash(strFullFileName); if (pos != string::npos) { const auto Path = string_view(strFullFileName).substr(pos); // В корне? if(IsRootPath(Path)) { // а дальше? каталог существует? if (!os::fs::is_directory(Path) //|| LocalStricmp(OldCurDir,FullFileName) // <- это видимо лишнее. ) m_Flags.Set(FFILEEDIT_SAVETOSAVEAS); } } if (LocalKey == KEY_F2 && os::fs::is_file(strFullFileName)) { m_Flags.Clear(FFILEEDIT_SAVETOSAVEAS); } static eol SavedEol = eol::none; // none here means "do not change" uintptr_t codepage = m_codepage; const auto SaveAs = LocalKey==KEY_SHIFTF2 || m_Flags.Check(FFILEEDIT_SAVETOSAVEAS); string strFullSaveAsName = strFullFileName; if (SaveAs) { string strSaveAsName = m_Flags.Check(FFILEEDIT_SAVETOSAVEAS)?strFullFileName:strFileName; if (!dlgSaveFileAs(strSaveAsName, SavedEol, codepage, m_bAddSignature)) return false; strSaveAsName = unquote(os::env::expand(strSaveAsName)); const auto NameChanged = !equal_icase(strSaveAsName, m_Flags.Check(FFILEEDIT_SAVETOSAVEAS)? strFullFileName : strFileName); if (NameChanged) { if (!AskOverwrite(strSaveAsName)) { return true; } } strFullSaveAsName = ConvertNameToFull(strSaveAsName); //BUGBUG, не проверяем имя на правильность } error_state_ex ErrorState; int SaveResult=SaveFile(strFullSaveAsName, 0, SaveAs, ErrorState, SavedEol, codepage, m_bAddSignature); if (SaveResult==SAVEFILE_ERROR) { if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotSave), false) != operation::retry) { Done = true; break; } } else if (SaveResult==SAVEFILE_SUCCESS) { //здесь идет полная жопа, проверка на ошибки вообще пока отсутствует { bool bInPlace = /*(!IsUnicodeOrUtfCodePage(m_codepage) && !IsUnicodeOrUtfCodePage(codepage)) || */(m_codepage == codepage); if (!bInPlace) { m_editor->FreeAllocatedData(); m_editor->PushString({}); m_codepage = codepage; } SetFileName(strFullSaveAsName); if (!bInPlace) { //Message(MSG_WARNING, 1, L"WARNING!", L"Editor will be reopened with new file!", msg(lng::MOk)); int UserBreak; error_state_ex LoadErrorState; LoadFile(strFullSaveAsName, UserBreak, LoadErrorState); // BUGBUG check result // TODO: возможно подобный ниже код здесь нужен (copy/paste из FileEditor::Init()). оформить его нужно по иному //if(!Global->Opt->Confirm.Esc && UserBreak && GetExitCode()==XC_LOADING_INTERRUPTED && WindowManager) // WindowManager->RefreshWindow(); } // перерисовывать надо как минимум когда изменилась кодировка или имя файла ShowConsoleTitle(); Show();//!!! BUGBUG } Done = true; } else { Done = true; break; } } return true; } // $ 30.05.2003 SVS - Shift-F4 в редакторе/вьювере позволяет открывать другой редактор/вьювер (пока только редактор) case KEY_SHIFTF4: { if (!Global->OnlyEditorViewerUsed && GetCanLoseFocus()) { if (!m_Flags.Check(FFILEEDIT_DISABLESAVEPOS) && (m_editor->EdOpt.SavePos || m_editor->EdOpt.SaveShortPos)) // save position/codepage before reload SaveToCache(); Global->CtrlObject->Cp()->ActivePanel()->ProcessKey(Key); } return true; } // $ 21.07.2000 SKV + выход с позиционированием на редактируемом файле по CTRLF10 case KEY_CTRLF10: case KEY_RCTRLF10: { if (Global->WindowManager->InModal()) { return true; } string strFullFileNameTemp = strFullFileName; if (!os::fs::exists(strFullFileName)) // а сам файл то еще на месте? { if (!CheckShortcutFolder(strFullFileNameTemp, true, false)) return false; path::append(strFullFileNameTemp, L'.'); // для вваливания внутрь :-) } const auto ActivePanel = Global->CtrlObject->Cp()->ActivePanel(); if (m_Flags.Check(FFILEEDIT_NEW) || (ActivePanel && ActivePanel->FindFile(strFileName) == -1)) // Mantis#279 { UpdateFileList(); m_Flags.Clear(FFILEEDIT_NEW); } { SCOPED_ACTION(SaveScreen); Global->CtrlObject->Cp()->GoToFile(strFullFileNameTemp); m_Flags.Set(FFILEEDIT_REDRAWTITLE); } return true; } case KEY_CTRLB: case KEY_RCTRLB: { Global->Opt->EdOpt.ShowKeyBar=!Global->Opt->EdOpt.ShowKeyBar; if (IsKeyBarVisible()) m_windowKeyBar->Show(); else m_windowKeyBar->Hide(); Show(); return true; } case KEY_CTRLSHIFTB: case KEY_RCTRLSHIFTB: { Global->Opt->EdOpt.ShowTitleBar=!Global->Opt->EdOpt.ShowTitleBar; Show(); return true; } case KEY_SHIFTF10: if (!ProcessKey(Manager::Key(KEY_F2))) // учтем факт того, что могли отказаться от сохранения return false; [[fallthrough]]; case KEY_F4: if (F4KeyOnly) return true; [[fallthrough]]; case KEY_ESC: case KEY_F10: { bool FirstSave = true, NeedQuestion = true; if (LocalKey != KEY_SHIFTF10) // KEY_SHIFTF10 не учитываем! { const auto FilePlaced = !os::fs::exists(strFullFileName) && !m_Flags.Check(FFILEEDIT_NEW); if (m_editor->IsFileChanged() || // в текущем сеансе были изменения? FilePlaced) // а сам файл то еще на месте? { auto MsgLine1 = lng::MNewFileName; if (m_editor->IsFileChanged() && FilePlaced) MsgLine1 = lng::MEditSavedChangedNonFile; else if (!m_editor->IsFileChanged() && FilePlaced) MsgLine1 = lng::MEditSavedChangedNonFile1; if (MsgLine1 != lng::MNewFileName) { switch (Message(MSG_WARNING, msg(lng::MEditTitle), { msg(MsgLine1), msg(lng::MEditSavedChangedNonFile2) }, { lng::MHYes, lng::MHNo, lng::MHCancel }, {}, &EditorSaveExitDeletedId)) { case Message::first_button: if (!ProcessKey(Manager::Key(KEY_F2))) // попытка сначала сохранить NeedQuestion = false; FirstSave = false; break; case Message::second_button: NeedQuestion = false; FirstSave = false; break; default: return false; } } } else if (!m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)) //???? NeedQuestion = false; } return ProcessQuitKey(FirstSave, NeedQuestion); } case KEY_F8: { SetCodePageEx(f8cps.NextCP(m_codepage)); return true; } case KEY_SHIFTF8: { uintptr_t codepage = m_codepage; if (codepages::instance().SelectCodePage(codepage, false, true)) SetCodePageEx(codepage == CP_DEFAULT? CP_REDETECT : codepage); return true; } case KEY_ALTSHIFTF9: case KEY_RALTSHIFTF9: { // Работа с локальной копией EditorOptions Options::EditorOptions EdOpt; GetEditorOptions(EdOpt); Global->Opt->LocalEditorConfig(EdOpt); // $ 27.11.2001 DJ - Local в EditorConfig m_windowKeyBar->Show(); //???? Нужно ли???? SetEditorOptions(EdOpt); if (IsKeyBarVisible()) m_windowKeyBar->Show(); m_editor->Show(); return true; } default: { if (m_Flags.Check(FFILEEDIT_FULLSCREEN) && !Global->CtrlObject->Macro.IsExecuting()) if (IsKeyBarVisible()) m_windowKeyBar->Show(); if (!m_windowKeyBar->ProcessKey(Key)) return m_editor->ProcessKey(Key); } } } return true; } bool FileEditor::SetCodePageEx(uintptr_t cp) { if (cp == CP_DEFAULT) { EditorPosCache epc; if (!LoadFromCache(epc) || epc.CodePage <= 0 || epc.CodePage > 0xffff) return false; cp = epc.CodePage; } else if (cp == CP_REDETECT) { const os::fs::file EditFile(strFileName, FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING); const auto DefaultCodepage = GetDefaultCodePage(); cp = EditFile? GetFileCodepage(EditFile, DefaultCodepage) : DefaultCodepage; } if (cp == CP_DEFAULT || !codepages::IsCodePageSupported(cp)) { Message(MSG_WARNING, msg(lng::MEditTitle), { format(msg(lng::MEditorCPNotSupported), cp) }, { lng::MOk }); return false; } if (cp == m_codepage) return true; const auto CurrentCodepage = m_codepage; const auto need_reload = !m_Flags.Check(FFILEEDIT_NEW) // we can't reload non-existing file && (BadConversion || IsUnicodeCodePage(m_codepage) || IsUnicodeCodePage(cp)); if (need_reload) { if (IsFileModified()) { if (Message(MSG_WARNING, msg(lng::MEditTitle), { msg(lng::MEditorReloadCPWarnLost1), msg(lng::MEditorReloadCPWarnLost2) }, { lng::MOk, lng::MCancel }) != Message::first_button) { return false; } } // BUGBUG result check??? ReloadFile(cp); } else { SetCodePage(cp); } if (m_codepage == CurrentCodepage) return false; InitKeyBar(); return true; } bool FileEditor::ProcessQuitKey(int FirstSave, bool NeedQuestion, bool DeleteWindow) { for (;;) { int SaveCode=SAVEFILE_SUCCESS; error_state_ex ErrorState; if (NeedQuestion) { SaveCode=SaveFile(strFullFileName, FirstSave, false, ErrorState); } if (SaveCode==SAVEFILE_CANCEL) break; if (SaveCode==SAVEFILE_SUCCESS) { /* $ 09.02.2002 VVM + Обновить панели, если писали в текущий каталог */ if (NeedQuestion) { if (os::fs::exists(strFullFileName)) { UpdateFileList(); } } if (DeleteWindow) { Global->WindowManager->DeleteWindow(); } SetExitCode(XC_QUIT); break; } if (strFileName == msg(lng::MNewFileName)) { if (!ProcessKey(Manager::Key(KEY_SHIFTF2))) { return FALSE; } else break; } if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotSave), false) != operation::retry) break; FirstSave=0; } return GetExitCode() == XC_QUIT; } bool FileEditor::LoadFile(const string& Name,int &UserBreak, error_state_ex& ErrorState) { try { // TODO: indentation SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<Editor::EditorPreRedrawItem>()); SCOPED_ACTION(taskbar::indeterminate); SCOPED_ACTION(wakeful); EditorPosCache pc; UserBreak = 0; os::fs::file EditFile(Name, FILE_READ_DATA, FILE_SHARE_READ | (Global->Opt->EdOpt.EditOpenedForWrite? (FILE_SHARE_WRITE | FILE_SHARE_DELETE) : 0), nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN); if(!EditFile) { ErrorState = error_state::fetch(); if ((ErrorState.Win32Error != ERROR_FILE_NOT_FOUND) && (ErrorState.Win32Error != ERROR_PATH_NOT_FOUND)) { UserBreak = -1; m_Flags.Set(FFILEEDIT_OPENFAILED); } return false; } if (Global->Opt->EdOpt.FileSizeLimit) { unsigned long long FileSize = 0; if (EditFile.GetSize(FileSize)) { if (FileSize > static_cast<unsigned long long>(Global->Opt->EdOpt.FileSizeLimit)) { if (Message(MSG_WARNING, msg(lng::MEditTitle), { Name, // Ширина = 8 - это будет... в Kb и выше... format(msg(lng::MEditFileLong), trim(FileSizeToStr(FileSize, 8))), format(msg(lng::MEditFileLong2), trim(FileSizeToStr(Global->Opt->EdOpt.FileSizeLimit, 8))), msg(lng::MEditROOpen) }, { lng::MYes, lng::MNo }, {}, &EditorFileLongId) != Message::first_button) { EditFile.Close(); SetLastError(ERROR_OPEN_FAILED); //???? ErrorState = error_state::fetch(); UserBreak=1; m_Flags.Set(FFILEEDIT_OPENFAILED); return false; } } } else { if (Message(MSG_WARNING, msg(lng::MEditTitle), { Name, msg(lng::MEditFileGetSizeError), msg(lng::MEditROOpen) }, { lng::MYes, lng::MNo }, {}, &EditorFileGetSizeErrorId) != Message::first_button) { EditFile.Close(); SetLastError(ERROR_OPEN_FAILED); //???? ErrorState = error_state::fetch(); UserBreak=1; m_Flags.Set(FFILEEDIT_OPENFAILED); return false; } } } for (BitFlags f0 = m_editor->m_Flags; ; m_editor->m_Flags = f0) { m_editor->FreeAllocatedData(); const auto Cached = LoadFromCache(pc); const os::fs::file_status FileStatus(Name); if ((m_editor->EdOpt.ReadOnlyLock & 0_bit) && FileStatus.check(FILE_ATTRIBUTE_READONLY | (m_editor->EdOpt.ReadOnlyLock & 0b0110'0000) >> 4)) { m_editor->m_Flags.Invert(Editor::FEDITOR_LOCKMODE); } if (Cached && pc.CodePage && !codepages::IsCodePageSupported(pc.CodePage)) pc.CodePage = 0; bool testBOM = true; const auto Redetect = (m_codepage == CP_REDETECT); if (Redetect) m_codepage = CP_DEFAULT; if (m_codepage == CP_DEFAULT) { if (!Redetect && Cached && pc.CodePage) { m_codepage = pc.CodePage; } else { const auto Cp = GetFileCodepage(EditFile, GetDefaultCodePage(), &m_bAddSignature, Redetect || Global->Opt->EdOpt.AutoDetectCodePage); testBOM = false; if (codepages::IsCodePageSupported(Cp)) m_codepage = Cp; } if (m_codepage == CP_DEFAULT) m_codepage = GetDefaultCodePage(); } m_editor->SetCodePage(m_codepage, nullptr, false); //BUGBUG m_editor->GlobalEOL = eol::none; unsigned long long FileSize = 0; // BUGBUG check result (void)EditFile.GetSize(FileSize); const time_check TimeCheck; os::fs::filebuf StreamBuffer(EditFile, std::ios::in); std::istream Stream(&StreamBuffer); Stream.exceptions(Stream.badbit | Stream.failbit); enum_lines EnumFileLines(Stream, m_codepage); for (auto Str: EnumFileLines) { if (testBOM && IsUnicodeOrUtfCodePage(m_codepage)) { if (starts_with(Str.Str, encoding::bom_char)) { Str.Str.remove_prefix(1); m_bAddSignature = true; } } testBOM = false; if (TimeCheck) { if (CheckForEscSilent()) { if (ConfirmAbortOp()) { UserBreak = 1; EditFile.Close(); return false; } } SetCursorType(false, 0); const auto CurPos = EditFile.GetPointer(); auto Percent = CurPos * 100 / FileSize; // В случае если во время загрузки файл увеличивается размере, то количество // процентов может быть больше 100. Обрабатываем эту ситуацию. if (Percent > 100) { // BUGBUG check result (void)EditFile.GetSize(FileSize); Percent = std::min(CurPos * 100 / FileSize, 100ull); } Editor::EditorShowMsg(msg(lng::MEditTitle), msg(lng::MEditReading), Name, Percent); } if (m_editor->GlobalEOL == eol::none && Str.Eol != eol::none) { m_editor->GlobalEOL = Str.Eol; } m_editor->PushString(Str.Str); m_editor->LastLine()->SetEOL(Str.Eol); } BadConversion = EnumFileLines.conversion_error(); if (BadConversion) { uintptr_t cp = m_codepage; if (!dlgBadEditorCodepage(cp)) // cancel { EditFile.Close(); SetLastError(ERROR_OPEN_FAILED); //???? ErrorState = error_state::fetch(); UserBreak=1; m_Flags.Set(FFILEEDIT_OPENFAILED); return false; } else if (cp != m_codepage) { m_codepage = cp; EditFile.SetPointer(0, nullptr, FILE_BEGIN); continue; } // else -- codepage accepted } break; } if (m_editor->Lines.empty() || m_editor->Lines.back().GetEOL() != eol::none) m_editor->PushString({}); if (m_editor->GlobalEOL == eol::none) m_editor->GlobalEOL = Editor::GetDefaultEOL(); EditFile.Close(); m_editor->SetCacheParams(pc, m_bAddSignature); ErrorState = error_state::fetch(); // BUGBUG check result (void)os::fs::get_find_data(Name, FileInfo); EditorGetFileAttributes(Name); return true; } catch (const std::bad_alloc&) { // TODO: better diagnostics m_editor->FreeAllocatedData(); m_Flags.Set(FFILEEDIT_OPENFAILED); SetLastError(ERROR_NOT_ENOUGH_MEMORY); ErrorState = error_state::fetch(); return false; } catch (const std::exception&) { // A portion of file can be locked // TODO: better diagnostics m_editor->FreeAllocatedData(); m_Flags.Set(FFILEEDIT_OPENFAILED); ErrorState = error_state::fetch(); return false; } } bool FileEditor::ReloadFile(uintptr_t codepage) { const auto save_codepage(m_codepage); const auto save_bAddSignature(m_bAddSignature); const auto save_BadConversiom(BadConversion); const auto save_Flags(m_Flags), save_Flags1(m_editor->m_Flags); Editor saved(shared_from_this(), CP_DEFAULT); saved.fake_editor = true; m_editor->SwapState(saved); int user_break = 0; m_codepage = codepage; error_state_ex ErrorState; for (;;) { if (LoadFile(strFullFileName, user_break, ErrorState)) { m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED); m_editor->m_Flags.Clear(Editor::FEDITOR_MODIFIED); Show(); return true; } if (user_break != 1) { if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotOpen), false) == operation::retry) continue; } m_codepage = save_codepage; m_bAddSignature = save_bAddSignature; BadConversion = save_BadConversiom; m_Flags = save_Flags; m_editor->m_Flags = save_Flags1; m_editor->SwapState(saved); Show(); return false; } } //TextFormat и codepage используются ТОЛЬКО, если bSaveAs = true! int FileEditor::SaveFile(const string& Name,int Ask, bool bSaveAs, error_state_ex& ErrorState, eol Eol, uintptr_t Codepage, bool AddSignature) { if (!bSaveAs) { Eol = eol::none; Codepage=m_editor->GetCodePage(); } if (m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE) && !m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED) && !bSaveAs) return SAVEFILE_SUCCESS; SCOPED_ACTION(taskbar::indeterminate); SCOPED_ACTION(wakeful); if (Ask) { if (!m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)) return SAVEFILE_SUCCESS; std::vector Buttons{ lng::MHYes, lng::MHNo }; if (Global->AllowCancelExit) { Buttons.emplace_back(lng::MHCancel); } int Code = Message(MSG_WARNING, msg(lng::MEditTitle), { msg(lng::MEditAskSave) }, Buttons, {}, &EditAskSaveId); if(Code < 0 && !Global->AllowCancelExit) { Code = Message::second_button; // close == not save } switch (Code) { case Message::first_button: // Save break; case Message::second_button: // Not Save m_editor->TextChanged(false); return SAVEFILE_SUCCESS; default: return SAVEFILE_CANCEL; } } int NewFile=TRUE; const auto FileAttr = os::fs::get_file_attributes(Name); if (FileAttr != INVALID_FILE_ATTRIBUTES) { // Проверка времени модификации... if (!m_Flags.Check(FFILEEDIT_SAVEWQUESTIONS)) { os::fs::find_data FInfo; if (os::fs::get_find_data(Name, FInfo) && !FileInfo.FileName.empty()) { if (FileInfo.LastWriteTime != FInfo.LastWriteTime || FInfo.FileSize != FileInfo.FileSize) { switch (Message(MSG_WARNING, msg(lng::MEditTitle), { msg(lng::MEditAskSaveExt) }, { lng::MHYes, lng::MEditBtnSaveAs, lng::MHCancel }, L"WarnEditorSavedEx"sv, &EditAskSaveExtId)) { case Message::first_button: // Save break; case Message::second_button: // Save as return ProcessKey(Manager::Key(KEY_SHIFTF2))? SAVEFILE_SUCCESS : SAVEFILE_CANCEL; default: return SAVEFILE_CANCEL; } } } } m_Flags.Clear(FFILEEDIT_SAVEWQUESTIONS); NewFile=FALSE; if (FileAttr & FILE_ATTRIBUTE_READONLY) { //BUGBUG if (Message(MSG_WARNING, msg(lng::MEditTitle), { Name, msg(lng::MEditRO), msg(lng::MEditOvr) }, { lng::MYes, lng::MNo }, {}, &EditorSavedROId) != Message::first_button) return SAVEFILE_CANCEL; (void)os::fs::set_file_attributes(Name, FileAttr & ~FILE_ATTRIBUTE_READONLY); //BUGBUG } } else { // проверим путь к файлу, может его уже снесли... string strCreatedPath = Name; if (CutToParent(strCreatedPath)) { if (!os::fs::exists(strCreatedPath)) { // и попробуем создать. // Раз уж CreatePath(strCreatedPath); if (!os::fs::exists(strCreatedPath)) { ErrorState = error_state::fetch(); return SAVEFILE_ERROR; } } } } if (BadConversion) { if(Message(MSG_WARNING, msg(lng::MWarning), { msg(lng::MEditDataLostWarn), msg(lng::MEditorSaveNotRecommended) }, { lng::MEditorSave, lng::MCancel }) == Message::first_button) { BadConversion = false; } else { return SAVEFILE_CANCEL; } } int RetCode=SAVEFILE_SUCCESS; if (Eol != eol::none) { m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED); m_editor->GlobalEOL = Eol; } if (!os::fs::exists(Name)) m_Flags.Set(FFILEEDIT_NEW); //SaveScreen SaveScr; /* $ 11.10.2001 IS Если было произведено сохранение с любым результатом, то не удалять файл */ m_Flags.Clear(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE); //_D(SysLog(L"%08d EE_SAVE",__LINE__)); if (!IsUnicodeOrUtfCodePage(Codepage)) { int LineNumber=-1; encoding::error_position ErrorPosition; for(auto& Line: m_editor->Lines) { ++LineNumber; const auto& SaveStr = Line.GetString(); auto LineEol = Line.GetEOL(); (void)encoding::get_bytes_count(Codepage, SaveStr, &ErrorPosition); const auto ValidStr = !ErrorPosition; if (ValidStr) (void)encoding::get_bytes_count(Codepage, LineEol.str(), &ErrorPosition); if (ErrorPosition) { //SetMessageHelp(L"EditorDataLostWarning") const int Result = Message(MSG_WARNING, msg(lng::MWarning), { msg(lng::MEditorSaveCPWarn1), msg(lng::MEditorSaveCPWarn2), msg(lng::MEditorSaveNotRecommended) }, { lng::MCancel, lng::MEditorSaveCPWarnShow, lng::MEditorSave }); if (Result == Message::third_button) break; if(Result == Message::second_button) { m_editor->GoToLine(LineNumber); if(!ValidStr) { Line.SetCurPos(static_cast<int>(*ErrorPosition)); } else { Line.SetCurPos(Line.GetLength()); } Show(); } return SAVEFILE_CANCEL; } } } EditorSaveFile esf = {sizeof(esf), Name.c_str(), m_editor->GlobalEOL.str().data(), Codepage}; Global->CtrlObject->Plugins->ProcessEditorEvent(EE_SAVE, &esf, m_editor.get()); try { save_file_with_replace(Name, FileAttr, 0, Global->Opt->EdOpt.CreateBackups, [&](std::ostream& Stream) { m_editor->UndoSavePos = m_editor->UndoPos; m_editor->m_Flags.Clear(Editor::FEDITOR_UNDOSAVEPOSLOST); SetCursorType(false, 0); SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<Editor::EditorPreRedrawItem>()); if (!bSaveAs) AddSignature = m_bAddSignature; const time_check TimeCheck; encoding::writer Writer(Stream, Codepage, AddSignature); size_t LineNumber = -1; for (auto& Line : m_editor->Lines) { ++LineNumber; if (TimeCheck) { Editor::EditorShowMsg(msg(lng::MEditTitle), msg(lng::MEditSaving), Name, LineNumber * 100 / m_editor->Lines.size()); } const auto& SaveStr = Line.GetString(); auto LineEol = Line.GetEOL(); if (Eol != eol::none && LineEol != eol::none) { LineEol = m_editor->GlobalEOL; Line.SetEOL(LineEol); } Writer.write(SaveStr); Writer.write(LineEol.str()); } }); } catch (const far_exception& e) { RetCode = SAVEFILE_ERROR; ErrorState = e; } // BUGBUG check result (void)os::fs::get_find_data(Name, FileInfo); EditorGetFileAttributes(Name); if (m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED) || NewFile) m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED); /* Этот кусок раскомметировать в том случае, если народ решит, что для если файл был залочен и мы его переписали под други именем... ...то "лочка" должна быть снята. */ // if(SaveAs) // Flags.Clear(FEDITOR_LOCKMODE); /* 28.12.2001 VVM ! Проверить на успешную запись */ if (RetCode==SAVEFILE_SUCCESS) { m_editor->TextChanged(false); m_editor->m_Flags.Set(Editor::FEDITOR_NEWUNDO); } Show(); // ************************************ m_Flags.Clear(FFILEEDIT_NEW); return RetCode; } bool FileEditor::ProcessMouse(const MOUSE_EVENT_RECORD *MouseEvent) { F4KeyOnly = false; if (!m_windowKeyBar->ProcessMouse(MouseEvent)) { INPUT_RECORD mouse = { MOUSE_EVENT }; mouse.Event.MouseEvent=*MouseEvent; if (!ProcessEditorInput(mouse)) if (!m_editor->ProcessMouse(MouseEvent)) return false; } return true; } int FileEditor::GetTypeAndName(string &strType, string &strName) { strType = msg(lng::MScreensEdit); strName = strFullFileName; return windowtype_editor; } void FileEditor::ShowConsoleTitle() { string strEditorTitleFormat=Global->Opt->strEditorTitleFormat.Get(); replace_icase(strEditorTitleFormat, L"%Lng"sv, msg(lng::MInEditor)); replace_icase(strEditorTitleFormat, L"%File"sv, PointToName(strFileName)); ConsoleTitle::SetFarTitle(strEditorTitleFormat); m_Flags.Clear(FFILEEDIT_REDRAWTITLE); } void FileEditor::SetScreenPosition() { if (m_Flags.Check(FFILEEDIT_FULLSCREEN)) { SetPosition({ 0, 0, ScrX, ScrY }); } } void FileEditor::OnDestroy() { _OT(SysLog(L"[%p] FileEditor::OnDestroy()",this)); if (Global->CtrlObject && !m_Flags.Check(FFILEEDIT_DISABLEHISTORY) && !equal_icase(strFileName, msg(lng::MNewFileName))) Global->CtrlObject->ViewHistory->AddToHistory(strFullFileName, m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE) ? HR_EDITOR_RO : HR_EDITOR); //AY: флаг оповещающий закрытие редактора. m_bClosing = true; if (bEE_READ_Sent && Global->CtrlObject) { Global->CtrlObject->Plugins->ProcessEditorEvent(EE_CLOSE, nullptr, m_editor.get()); } if (!m_Flags.Check(FFILEEDIT_OPENFAILED) && !m_Flags.Check(FFILEEDIT_DISABLESAVEPOS) && (m_editor->EdOpt.SavePos || m_editor->EdOpt.SaveShortPos) && Global->CtrlObject) SaveToCache(); } bool FileEditor::GetCanLoseFocus(bool DynamicMode) const { if (DynamicMode && m_editor->IsFileModified()) { return false; } return window::GetCanLoseFocus(); } void FileEditor::SetLockEditor(bool LockMode) const { if (LockMode) m_editor->m_Flags.Set(Editor::FEDITOR_LOCKMODE); else m_editor->m_Flags.Clear(Editor::FEDITOR_LOCKMODE); } bool FileEditor::CanFastHide() const { return (Global->Opt->AllCtrlAltShiftRule & CASR_EDITOR) != 0; } int FileEditor::ProcessEditorInput(const INPUT_RECORD& Rec) { return Global->CtrlObject->Plugins->ProcessEditorInput(&Rec); } void FileEditor::SetPluginTitle(const string* PluginTitle) { if (!PluginTitle) strPluginTitle.clear(); else strPluginTitle = *PluginTitle; } bool FileEditor::SetFileName(const string_view NewFileName) { // BUGBUG This whole MNewFileName thing is madness. // TODO: Just support an empty name strFileName = NewFileName.empty()? msg(lng::MNewFileName) : NewFileName; if (strFileName != msg(lng::MNewFileName)) { strFullFileName = ConvertNameToFull(strFileName); string strFilePath=strFullFileName; if (CutToParent(strFilePath)) { if (equal_icase(strFilePath, os::fs::GetCurrentDirectory())) strFileName = PointToName(strFullFileName); } //Дабы избежать бардака, развернём слешики... ReplaceSlashToBackslash(strFullFileName); } else { strFullFileName = path::join(strStartDir, strFileName); } return true; } void FileEditor::SetTitle(const string* Title) { if (Title) strTitle = *Title; else strTitle.clear(); } string FileEditor::GetTitle() const { string strLocalTitle; if (!strPluginTitle.empty()) strLocalTitle = strPluginTitle; else { if (!strTitle.empty()) strLocalTitle = strTitle; else strLocalTitle = strFullFileName; } return strLocalTitle; } static std::pair<string, size_t> char_code(std::optional<wchar_t> const& Char, int const Codebase) { const auto process = [&](string_view const Format, string_view const Max) { return std::pair{ Char.has_value()? format(Format, unsigned(*Char)) : L""s, Max.size() }; }; switch (Codebase) { case 0: return process(L"0{0:o}"sv, L"0177777"sv); case 2: return process(L"{0:X}h"sv, L"FFFFh"sv); case 1: default: return process(L"{0}"sv, L"65535"sv); } } static std::pair<string, size_t> ansi_char_code(std::optional<wchar_t> const& Char, int const Codebase, uintptr_t const Codepage) { const auto process = [&](string_view const Format, string_view const Max) { std::optional<unsigned> CharCode; char Buffer; encoding::error_position ErrorPosition; if (Char.has_value() && encoding::get_bytes(Codepage, { &*Char, 1 }, { &Buffer, 1 }, &ErrorPosition) == 1 && !ErrorPosition) { const unsigned AnsiCode = Buffer; if (AnsiCode != *Char) { CharCode = AnsiCode; } } return std::pair{ CharCode.has_value()? format(Format, *CharCode) : L""s, Max.size() }; }; switch (Codebase) { case 0: return process(L"0{0:<3o}"sv, L"0377"sv); case 2: return process(L"{0:02X}h"sv, L"FFh"sv); case 1: default: return process(L"{0:<3}"sv, L"255"sv); } } void FileEditor::ShowStatus() const { if (!IsTitleBarVisible()) return; SetColor(COL_EDITORSTATUS); GotoXY(m_Where.left, m_Where.top); //?? const auto& Str = m_editor->m_it_CurLine->GetString(); const size_t CurPos = m_editor->m_it_CurLine->GetCurPos(); string CharCode; { std::optional<wchar_t> Char; if (CurPos < Str.size()) Char = Str[CurPos]; auto [UnicodeStr, UnicodeSize] = char_code(Char, m_editor->EdOpt.CharCodeBase); CharCode = std::move(UnicodeStr); if (!IsUnicodeOrUtfCodePage(m_codepage)) { const auto [AnsiStr, AnsiSize] = ansi_char_code(Char, m_editor->EdOpt.CharCodeBase, m_codepage); if (!CharCode.empty() && !AnsiStr.empty()) { append(CharCode, L'/', AnsiStr); } UnicodeSize += AnsiSize + 1; } if (Char.has_value()) inplace::pad_right(CharCode, UnicodeSize); else CharCode.assign(UnicodeSize, L' '); } //предварительный расчет const auto LinesFormat = FSTR(L"{0}/{1}"); const auto SizeLineStr = format(LinesFormat, m_editor->Lines.size(), m_editor->Lines.size()).size(); const auto strLineStr = format(LinesFormat, m_editor->m_it_CurLine.Number() + 1, m_editor->Lines.size()); const auto strAttr = *AttrStr? L"│"s + AttrStr : L""s; auto StatusLine = format(FSTR(L"│{0}{1}│{2:5.5}│{3:.3} {4:>{5}}│{6:.3} {7:<3}│{8:.3} {9:<3}{10}│{11}"), m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)?L'*':L' ', m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE)? L'-' : m_editor->m_Flags.Check(Editor::FEDITOR_PROCESSCTRLQ)? L'"' : L' ', ShortReadableCodepageName(m_codepage), msg(lng::MEditStatusLine), strLineStr, SizeLineStr, msg(lng::MEditStatusCol), m_editor->m_it_CurLine->GetTabCurPos() + 1, msg(lng::MEditStatusChar), m_editor->m_it_CurLine->GetCurPos() + 1, strAttr, CharCode); // Explicitly signed types - it's too easy to screw it up on small console sizes otherwise const int ClockSize = Global->Opt->ViewerEditorClock && m_Flags.Check(FFILEEDIT_FULLSCREEN)? static_cast<int>(Global->CurrentTime.size()) : 0; const int AvailableSpace = std::max(0, ObjWidth() - ClockSize - (ClockSize? 1 : 0)); inplace::cut_right(StatusLine, AvailableSpace); const int NameWidth = std::max(0, AvailableSpace - static_cast<int>(StatusLine.size())); Text(fit_to_left(truncate_path(GetTitle(), NameWidth), NameWidth)); Text(StatusLine); if (ClockSize) { Text(L'│'); // Separator before the clock ShowTime(); } } /* $ 13.02.2001 Узнаем атрибуты файла и заодно сформируем готовую строку атрибутов для статуса. */ os::fs::attributes FileEditor::EditorGetFileAttributes(string_view const Name) { m_FileAttributes = os::fs::get_file_attributes(Name); int ind=0; if (m_FileAttributes!=INVALID_FILE_ATTRIBUTES) { if (m_FileAttributes&FILE_ATTRIBUTE_READONLY) AttrStr[ind++]=L'R'; if (m_FileAttributes&FILE_ATTRIBUTE_SYSTEM) AttrStr[ind++]=L'S'; if (m_FileAttributes&FILE_ATTRIBUTE_HIDDEN) AttrStr[ind++]=L'H'; } AttrStr[ind]=0; return m_FileAttributes; } /* true - панель обновили */ bool FileEditor::UpdateFileList() const { const auto ActivePanel = Global->CtrlObject->Cp()->ActivePanel(); const auto FileName = PointToName(strFullFileName); string strFilePath(strFullFileName), strPanelPath(ActivePanel->GetCurDir()); strFilePath.resize(strFullFileName.size() - FileName.size()); AddEndSlash(strPanelPath); AddEndSlash(strFilePath); if (strPanelPath == strFilePath) { ActivePanel->Update(UPDATE_KEEP_SELECTION|UPDATE_DRAW_MESSAGE); return true; } return false; } void FileEditor::SetPluginData(const string* PluginData) { if (PluginData) strPluginData = *PluginData; else strPluginData.clear(); } /* $ 14.06.2002 IS DeleteOnClose стал int: 0 - не удалять ничего 1 - удалять файл и каталог 2 - удалять только файл */ void FileEditor::SetDeleteOnClose(int NewMode) { m_Flags.Clear(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE); if (NewMode==1) m_Flags.Set(FFILEEDIT_DELETEONCLOSE); else if (NewMode==2) m_Flags.Set(FFILEEDIT_DELETEONLYFILEONCLOSE); } void FileEditor::GetEditorOptions(Options::EditorOptions& EdOpt) const { EdOpt = m_editor->EdOpt; } void FileEditor::SetEditorOptions(const Options::EditorOptions& EdOpt) const { m_editor->SetOptions(EdOpt); } void FileEditor::OnChangeFocus(bool focus) { window::OnChangeFocus(focus); if (!m_bClosing) { Global->CtrlObject->Plugins->ProcessEditorEvent(focus? EE_GOTFOCUS : EE_KILLFOCUS, nullptr, m_editor.get()); } } intptr_t FileEditor::EditorControl(int Command, intptr_t Param1, void *Param2) { #if defined(SYSLOG_KEYMACRO) _KEYMACRO(CleverSysLog SL(L"FileEditor::EditorControl()")); if (Command == ECTL_READINPUT || Command == ECTL_PROCESSINPUT) { _KEYMACRO(SysLog(L"(Command=%s, Param2=[%d/0x%08X]) Macro.IsExecuting()=%d",_ECTL_ToName(Command),(int)((intptr_t)Param2),(int)((intptr_t)Param2),Global->CtrlObject->Macro.IsExecuting())); } #else _ECTLLOG(CleverSysLog SL(L"FileEditor::EditorControl()")); _ECTLLOG(SysLog(L"(Command=%s, Param2=[%d/0x%08X])",_ECTL_ToName(Command),(int)Param2,Param2)); #endif if(m_editor->EditorControlLocked()) return FALSE; if (m_bClosing && (Command != ECTL_GETINFO) && (Command != ECTL_GETBOOKMARKS) && (Command!=ECTL_GETFILENAME)) return FALSE; switch (Command) { case ECTL_GETFILENAME: { if (Param2 && static_cast<size_t>(Param1) > strFullFileName.size()) { *copy_string(strFullFileName, static_cast<wchar_t*>(Param2)) = {}; } return strFullFileName.size()+1; } case ECTL_GETBOOKMARKS: { const auto ebm = static_cast<EditorBookmarks*>(Param2); if (!m_Flags.Check(FFILEEDIT_OPENFAILED) && CheckNullOrStructSize(ebm)) { size_t size; if(Editor::InitSessionBookmarksForPlugin(ebm, m_editor->m_SavePos.size(), size)) { for (const auto& [i, index]: enumerate(m_editor->m_SavePos)) { if (ebm->Line) { ebm->Line[index] = i.Line; } if (ebm->Cursor) { ebm->Cursor[index] = i.LinePos; } if (ebm->ScreenLine) { ebm->ScreenLine[index] = i.ScreenLine; } if (ebm->LeftPos) { ebm->LeftPos[index] = i.LeftPos; } } } return size; } return 0; } case ECTL_ADDSESSIONBOOKMARK: { m_editor->AddSessionBookmark(); return TRUE; } case ECTL_PREVSESSIONBOOKMARK: { m_editor->TurnOffMarkingBlock(); return m_editor->PrevSessionBookmark(); } case ECTL_NEXTSESSIONBOOKMARK: { m_editor->TurnOffMarkingBlock(); return m_editor->NextSessionBookmark(); } case ECTL_CLEARSESSIONBOOKMARKS: { m_editor->ClearSessionBookmarks(); return TRUE; } case ECTL_DELETESESSIONBOOKMARK: { return m_editor->DeleteSessionBookmark(m_editor->PointerToSessionBookmark(static_cast<int>(reinterpret_cast<intptr_t>(Param2)))); } case ECTL_GETSESSIONBOOKMARKS: { return CheckNullOrStructSize(static_cast<const EditorBookmarks*>(Param2))? m_editor->GetSessionBookmarksForPlugin(static_cast<EditorBookmarks*>(Param2)) : 0; } case ECTL_GETTITLE: { const auto strLocalTitle = GetTitle(); if (Param2 && static_cast<size_t>(Param1) > strLocalTitle.size()) { *copy_string(strLocalTitle, static_cast<wchar_t*>(Param2)) = {}; } return strLocalTitle.size()+1; } case ECTL_SETTITLE: { strPluginTitle = NullToEmpty(static_cast<const wchar_t*>(Param2)); ShowStatus(); if (!m_editor->m_InEERedraw) Global->ScrBuf->Flush(); //??? return TRUE; } case ECTL_REDRAW: { Global->WindowManager->RefreshWindow(shared_from_this()); Global->WindowManager->PluginCommit(); Global->ScrBuf->Flush(); return TRUE; } /* Функция установки Keybar Labels Param2 = nullptr - восстановить, пред. значение Param2 = -1 - обновить полосу (перерисовать) Param2 = KeyBarTitles */ case ECTL_SETKEYBAR: { const auto Kbt = static_cast<const FarSetKeyBarTitles*>(Param2); if (!Kbt) //восстановить изначальное InitKeyBar(); else { if (reinterpret_cast<intptr_t>(Param2) != -1) // не только перерисовать? { if(CheckStructSize(Kbt)) m_windowKeyBar->Change(Kbt->Titles); else return FALSE; } m_windowKeyBar->Show(); } return TRUE; } case ECTL_SAVEFILE: { string strName = strFullFileName; auto Eol = eol::none; uintptr_t codepage=m_codepage; const auto esf = static_cast<const EditorSaveFile*>(Param2); if (CheckStructSize(esf)) { if (esf->FileName) strName=esf->FileName; if (esf->FileEOL) Eol = eol::parse(esf->FileEOL); if (esf->CodePage != CP_DEFAULT) codepage=esf->CodePage; } { const auto strOldFullFileName = strFullFileName; if (SetFileName(strName)) { if (!equal_icase(strFullFileName, strOldFullFileName)) { if (!AskOverwrite(strName)) { SetFileName(strOldFullFileName); return FALSE; } } m_Flags.Set(FFILEEDIT_SAVEWQUESTIONS); //всегда записываем в режиме save as - иначе не сменить кодировку и концы линий. error_state_ex ErrorState; return SaveFile(strName, FALSE, true, ErrorState, Eol, codepage, m_bAddSignature); } } return FALSE; } case ECTL_QUIT: { if (!bLoaded) // do not delete not created window { SetExitCode(XC_LOADING_INTERRUPTED); } else { Global->WindowManager->DeleteWindow(shared_from_this()); SetExitCode(XC_OPEN_ERROR); // что-то меня терзают смутные сомнения ...??? SAVEFILE_ERROR ??? Global->WindowManager->PluginCommit(); } return TRUE; } case ECTL_READINPUT: { const auto MacroState = Global->CtrlObject->Macro.GetState(); if (MacroState == MACROSTATE_RECORDING || MacroState == MACROSTATE_EXECUTING) { //return FALSE; } if (Param2) { const auto rec = static_cast<INPUT_RECORD*>(Param2); for (;;) { const auto Key = GetInputRecord(rec); if ((!rec->EventType || rec->EventType == KEY_EVENT) && ((Key >= KEY_MACRO_BASE && Key <= KEY_MACRO_ENDBASE) || (Key>=KEY_OP_BASE && Key <=KEY_OP_ENDBASE))) // исключаем MACRO ReProcessKey(Manager::Key(Key, *rec)); else break; } #if defined(SYSLOG_KEYMACRO) if (rec->EventType == KEY_EVENT) { SysLog(L"ECTL_READINPUT={KEY_EVENT,{%d,%d,Vk=0x%04X,0x%08X}}", rec->Event.KeyEvent.bKeyDown, rec->Event.KeyEvent.wRepeatCount, rec->Event.KeyEvent.wVirtualKeyCode, rec->Event.KeyEvent.dwControlKeyState); } #endif return TRUE; } return FALSE; } case ECTL_PROCESSINPUT: { if (Param2) { auto& rec = *static_cast<INPUT_RECORD*>(Param2); if (ProcessEditorInput(rec)) return TRUE; if (rec.EventType==MOUSE_EVENT) ProcessMouse(&rec.Event.MouseEvent); else { #if defined(SYSLOG_KEYMACRO) if (!rec.EventType || rec.EventType == KEY_EVENT) { SysLog(L"ECTL_PROCESSINPUT={%s,{%d,%d,Vk=0x%04X,0x%08X}}", (rec.EventType == KEY_EVENT?L"KEY_EVENT":L"(internal, macro)_KEY_EVENT"), rec.Event.KeyEvent.bKeyDown, rec.Event.KeyEvent.wRepeatCount, rec.Event.KeyEvent.wVirtualKeyCode, rec.Event.KeyEvent.dwControlKeyState); } #endif const auto Key = ShieldCalcKeyCode(&rec, false); ReProcessKey(Manager::Key(Key, rec)); } return TRUE; } return FALSE; } case ECTL_SETPARAM: { const auto espar = static_cast<const EditorSetParameter*>(Param2); if (CheckStructSize(espar)) { if (ESPT_SETBOM==espar->Type) { if(IsUnicodeOrUtfCodePage(m_codepage)) { m_bAddSignature=espar->iParam != 0; return TRUE; } return FALSE; } } break; } } const auto result = m_editor->EditorControl(Command, Param1, Param2); if (result&&ECTL_GETINFO==Command) { const auto Info=static_cast<EditorInfo*>(Param2); if (m_bAddSignature) Info->Options|=EOPT_BOM; if (Global->Opt->EdOpt.ShowTitleBar) Info->Options|=EOPT_SHOWTITLEBAR; if (Global->Opt->EdOpt.ShowKeyBar) Info->Options|=EOPT_SHOWKEYBAR; } return result; } bool FileEditor::LoadFromCache(EditorPosCache &pc) const { string strCacheName; const auto PluginData = GetPluginData(); if (!PluginData.empty()) { strCacheName = concat(PluginData, PointToName(strFullFileName)); } else { strCacheName = strFullFileName; ReplaceSlashToBackslash(strCacheName); } pc.Clear(); return FilePositionCache::GetPosition(strCacheName, pc); } void FileEditor::SaveToCache() const { EditorPosCache pc; m_editor->GetCacheParams(pc); if (!m_Flags.Check(FFILEEDIT_OPENFAILED)) //???? { pc.CodePage = BadConversion ? 0 : m_codepage; FilePositionCache::AddPosition(strPluginData.empty()? strFullFileName : strPluginData + PointToName(strFullFileName), pc); } } bool FileEditor::SetCodePage(uintptr_t codepage) { if (codepage == m_codepage || !m_editor) return false; uintptr_t ErrorCodepage; size_t ErrorLine, ErrorPos; if (!m_editor->TryCodePage(codepage, ErrorCodepage, ErrorLine, ErrorPos)) { const auto Info = codepages::GetInfo(ErrorCodepage); const int Result = Message(MSG_WARNING, msg(lng::MWarning), { msg(lng::MEditorSwitchCPWarn1), msg(lng::MEditorSwitchCPWarn2), format(FSTR(L"{0} - {1}"), codepage, Info? Info->Name : str(codepage)), msg(lng::MEditorSwitchCPConfirm) }, { lng::MCancel, lng::MEditorSaveCPWarnShow, lng::MOk }); switch (Result) { default: case Message::first_button: return false; case Message::second_button: m_editor->GoToLine(static_cast<int>(ErrorLine)); m_editor->m_it_CurLine->SetCurPos(static_cast<int>(ErrorPos)); Show(); return false; case Message::third_button: break; } } m_codepage = codepage; BadConversion = !m_editor->SetCodePage(m_codepage, &m_bAddSignature); return true; } bool FileEditor::AskOverwrite(const string& FileName) { bool result=true; if (os::fs::exists(FileName)) { if (Message(MSG_WARNING, msg(lng::MEditTitle), { FileName, msg(lng::MEditExists), msg(lng::MEditOvr) }, { lng::MYes, lng::MNo }, {}, &EditorAskOverwriteId) != Message::first_button) { result=false; } else { m_Flags.Set(FFILEEDIT_SAVEWQUESTIONS); } } return result; } uintptr_t FileEditor::GetDefaultCodePage() { intptr_t cp = Global->Opt->EdOpt.DefaultCodePage; if (cp < 0 || !codepages::IsCodePageSupported(cp)) cp = encoding::codepage::ansi(); return cp; } Editor* FileEditor::GetEditor() { return m_editor.get(); } bool FileEditor::IsKeyBarVisible() const { return Global->Opt->EdOpt.ShowKeyBar && ObjHeight() > 2; } bool FileEditor::IsTitleBarVisible() const { return Global->Opt->EdOpt.ShowTitleBar && ObjHeight() > 1; }
data-man/FarAS
far/fileedit.cpp
C++
bsd-3-clause
76,603
#!/bin/env python #Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__=""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """ import string, sys, os, re class Formatter: "Base formatter - simply applies python format strings" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - "$#,##0.00" is WAY easier than this.""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return "%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0)
nakagami/reportlab
src/reportlab/lib/formatters.py
Python
bsd-3-clause
3,887
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model backend\modules\masterdata\models\Countries */ $this->title = 'Create Countries'; $this->params['breadcrumbs'][] = ['label' => 'Countries', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="countries-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
ariandi/ktmavia
backend/modules/masterdata/views/countries/create.php
PHP
bsd-3-clause
446
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ package gov.nih.nci.calims2.domain.inventory.l10n; import java.util.ListResourceBundle; import gov.nih.nci.calims2.domain.inventory.enumeration.ContainerQuantity; /** * @author connollym@moxieinformatics.com * */ public class ContainerQuantityBundle extends ListResourceBundle { private static final Object[][] CONTENTS = { {ContainerQuantity.MAXIMUMCAPACITY.name(), "Maximum Capacity"}, {ContainerQuantity.CURRENTQUANTITY.name(), "Current Quantity"}, {ContainerQuantity.MINIMUMCAPACITY.name(), "Minimum Capacity"}}; /** * {@inheritDoc} */ protected Object[][] getContents() { return CONTENTS; } }
NCIP/calims
calims2-model/src/java/gov/nih/nci/calims2/domain/inventory/l10n/ContainerQuantityBundle.java
Java
bsd-3-clause
789
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\User */ $this->title = $model->id; $this->params['breadcrumbs'][] = ['label' => 'Users', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Users', ['index'], ['class' => 'btn btn-info']) ?> <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-success']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'username', 'auth_key', 'password_hash', 'password_reset_token', 'email:email', 'role', 'status', 'created_at', 'updated_at', ], ]) ?> </div>
OoWazowski/myApp
views/user/view.php
PHP
bsd-3-clause
1,167
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="id"> <context> <name>ColorDialog</name> <message> <location filename="../ColorDialog.ui" line="14"/> <source>Customize Colors</source> <translation>Atur Warna</translation> </message> <message> <location filename="../ColorDialog.ui" line="24"/> <source>Item Type</source> <translation>Item Tipe</translation> </message> <message> <location filename="../ColorDialog.ui" line="29"/> <source>Color</source> <translation>Warna</translation> </message> <message> <location filename="../ColorDialog.ui" line="34"/> <source>Sample</source> <translation>Contoh</translation> </message> <message> <location filename="../ColorDialog.ui" line="44"/> <location filename="../ColorDialog.cpp" line="55"/> <source>Select Color</source> <translation>Pilih Warna</translation> </message> <message> <location filename="../ColorDialog.ui" line="64"/> <source>Cancel</source> <translation>Batalkan</translation> </message> <message> <location filename="../ColorDialog.ui" line="71"/> <source>Apply</source> <translation>Terapkan</translation> </message> </context> <context> <name>DnDTabBar</name> <message> <location filename="../DnDTabBar.h" line="43"/> <source>Detach Tab</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainUI</name> <message> <location filename="../MainUI.ui" line="63"/> <source>Find the previous match</source> <translation>Cari kecocokan sebelumnya</translation> </message> <message> <location filename="../MainUI.ui" line="66"/> <location filename="../MainUI.ui" line="79"/> <location filename="../MainUI.ui" line="130"/> <location filename="../MainUI.ui" line="143"/> <location filename="../MainUI.ui" line="155"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../MainUI.ui" line="165"/> <source>Find:</source> <translation>Cari:</translation> </message> <message> <location filename="../MainUI.ui" line="76"/> <source>Find the next match</source> <translation>Cari kecocokan selanjutnya</translation> </message> <message> <location filename="../MainUI.ui" line="86"/> <source>Replace:</source> <translation>Ganti:</translation> </message> <message> <location filename="../MainUI.ui" line="105"/> <source>Match case</source> <translation>Kapitalisasi yang sama</translation> </message> <message> <location filename="../MainUI.ui" line="127"/> <source>Replace next match</source> <translation>Ganti pertandingan berikutnya</translation> </message> <message> <location filename="../MainUI.ui" line="140"/> <source>Replace all matches (to end of document)</source> <translation>Mengganti semua pertandingan (untuk akhir dokumen)</translation> </message> <message> <location filename="../MainUI.ui" line="152"/> <source>Hide the find/replace options</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="193"/> <source>File</source> <translation>Berkas</translation> </message> <message> <location filename="../MainUI.ui" line="207"/> <source>View</source> <translation>Tampilan</translation> </message> <message> <location filename="../MainUI.ui" line="211"/> <source>Syntax Highlighting</source> <translation>Penyorotan Sintaks</translation> </message> <message> <location filename="../MainUI.ui" line="218"/> <source>Tabs Location</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="235"/> <source>Edit</source> <translation>Sunting</translation> </message> <message> <location filename="../MainUI.ui" line="273"/> <source>Show Line Numbers</source> <translation>Tampilkan Nomor Baris</translation> </message> <message> <location filename="../MainUI.ui" line="278"/> <source>None</source> <translation>Nihil</translation> </message> <message> <location filename="../MainUI.ui" line="283"/> <location filename="../MainUI.cpp" line="192"/> <source>New File</source> <translation>Berkas Baru</translation> </message> <message> <location filename="../MainUI.ui" line="286"/> <source>Ctrl+N</source> <translation>Ctrl+N</translation> </message> <message> <location filename="../MainUI.ui" line="294"/> <source>Open File</source> <translation>Buka Berkas</translation> </message> <message> <location filename="../MainUI.ui" line="297"/> <source>Ctrl+O</source> <translation>Ctrl+O</translation> </message> <message> <location filename="../MainUI.ui" line="305"/> <source>Save File</source> <translation>Simpan File</translation> </message> <message> <location filename="../MainUI.ui" line="308"/> <source>Ctrl+S</source> <translation>Ctrl+S</translation> </message> <message> <location filename="../MainUI.ui" line="316"/> <source>Save File As</source> <translation>Simpan Berkas Sebagai</translation> </message> <message> <location filename="../MainUI.ui" line="321"/> <source>Close</source> <translation>Tutup</translation> </message> <message> <location filename="../MainUI.ui" line="324"/> <source>Ctrl+Q</source> <translation>Ctrl+Q</translation> </message> <message> <location filename="../MainUI.ui" line="332"/> <source>Close File</source> <translation>Tutup Berkas</translation> </message> <message> <location filename="../MainUI.ui" line="335"/> <source>Ctrl+W</source> <translation>Ctrl+W</translation> </message> <message> <location filename="../MainUI.ui" line="343"/> <source>Customize Colors</source> <translation>Warna Ubahan</translation> </message> <message> <location filename="../MainUI.ui" line="354"/> <source>Wrap Lines</source> <translation>Bungkus Garis</translation> </message> <message> <location filename="../MainUI.ui" line="359"/> <source>Find</source> <translation>Cari</translation> </message> <message> <location filename="../MainUI.ui" line="362"/> <source>Ctrl+F</source> <translation>Ctrl+F</translation> </message> <message> <location filename="../MainUI.ui" line="370"/> <source>Replace</source> <translation>Ganti</translation> </message> <message> <location filename="../MainUI.ui" line="373"/> <source>Ctrl+R</source> <translation>Ctrl+R</translation> </message> <message> <location filename="../MainUI.ui" line="387"/> <source>Show Popup Warnings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="390"/> <location filename="../MainUI.ui" line="393"/> <source>Show warnings about unsaved changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="404"/> <source>Top</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="412"/> <source>Bottom</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="420"/> <source>Left</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="428"/> <source>Right</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="433"/> <source>Print</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.ui" line="436"/> <source>Ctrl+P</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="64"/> <source>Text Editor</source> <translation>Editor Teks</translation> </message> <message> <location filename="../MainUI.cpp" line="199"/> <source>Open File(s)</source> <translation>Buka Berkas</translation> </message> <message> <location filename="../MainUI.cpp" line="199"/> <source>Text Files (*)</source> <translation>Berkas Teks (*)</translation> </message> <message> <location filename="../MainUI.cpp" line="252"/> <source>Print Content</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="383"/> <location filename="../MainUI.cpp" line="394"/> <location filename="../MainUI.cpp" line="502"/> <source>Lose Unsaved Changes?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="383"/> <location filename="../MainUI.cpp" line="394"/> <source>This file has unsaved changes. Do you want to close it anyway? %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../MainUI.cpp" line="502"/> <source>There are unsaved changes. Do you want to close the editor anyway? %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PlainTextEditor</name> <message> <location filename="../PlainTextEditor.cpp" line="110"/> <source>Save File</source> <translation>Simpan File</translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="110"/> <source>Text File (*)</source> <translation>Berkas Teks (*)</translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="318"/> <source>Row Number: %1, Column Number: %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="327"/> <source>The following file has been changed by some other utility. Do you want to re-load it?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="329"/> <source>(Note: You will lose all currently-unsaved changes)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PlainTextEditor.cpp" line="333"/> <source>File Modified</source> <translation type="unfinished"></translation> </message> </context> </TS>
sasongko26/lumina
src-qt5/desktop-utils/lumina-textedit/i18n/l-te_id.ts
TypeScript
bsd-3-clause
11,745
class OrderAudit < ActiveRecord::Migration def self.up add_column :orders, :admin_id , :integer end def self.down remove_column :orders, :admin_id end end
mehulsbhatt/spree-order-audit
db/migrate/20110122150723_order_audit.rb
Ruby
bsd-3-clause
172
import { IDataType } from 'phovea_core'; import * as d3 from 'd3'; export declare class D3Utils { static transform(x?: number, y?: number, rotate?: number, scaleX?: number, scaleY?: number): d3.Transform; /** * utility function to handle selections * @param data * @param $data * @param selector what type of object are the data bound ot * @returns {function(any, any): undefined} the click handler */ static selectionUtil(data: IDataType, $data: d3.Selection<any>, selector: string): (d: any, i: number) => void; /** * utility function to define a vis * @param name the name of the vis - will be used during toString * @param defaultOptions a function or an object containing the default options of this vis * @param initialSize a function or the size to compute the initial size of this vis * @param build the builder function * @param functions an object of additional functions to the vis * @returns a function class for this vis */ static defineVis(name: string, defaultOptions: any, initialSize: number[], build: ($parent: d3.Selection<any>, data: IDataType, size: number[]) => d3.Selection<any>, functions?: any): any; static defineVis(name: string, defaultOptions: (data: IDataType, options: any) => any, initialSize: number[], build: ($parent: d3.Selection<any>, data: IDataType, size: number[]) => d3.Selection<any>, functions?: any): any; static defineVis(name: string, defaultOptions: any, initialSize: (data: IDataType) => number[], build: ($parent: d3.Selection<any>, data: IDataType) => d3.Selection<any>, functions?: any): any; static defineVis(name: string, defaultOptions: (data: IDataType, options: any) => any, initialSize: (data: IDataType) => number[], build: ($parent: d3.Selection<any>, data: IDataType, size: number[]) => d3.Selection<any>, functions?: any): any; }
Caleydo/caleydo_d3
dist/d3utils/D3Utils.d.ts
TypeScript
bsd-3-clause
1,893
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * Copyright (c) 2014, Hunter Laux * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ package project; import java.io.IOException; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; // The Worker servlet should be mapped to the "/worker" URL. public class GetPCD extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ /* skip the first key / */ String keyStr =request.getPathInfo().substring(1); /* This allows /$key/filename.pcd where filename can be whatever */ keyStr = keyStr.split("/")[0]; DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key pclKey = KeyFactory.createKey("PointCloud2", keyStr); Query query = new Query(pclKey); try{ Entity pointCloud2 = datastore.prepare(query).asSingleEntity(); if(pointCloud2 == null) { ServletOutputStream out = response.getOutputStream(); out.print("Can't find point cloud "+ keyStr + "\n"); out.flush(); return; } PointCloud2 cloud = new PointCloud2(); cloud.width = Integer.valueOf(((Long) pointCloud2.getProperty("width")).intValue()); cloud.height = Integer.valueOf(((Long) pointCloud2.getProperty("height")).intValue()); cloud.is_bigendian = (Boolean) pointCloud2.getProperty("is_bigendian"); cloud.row_step = Integer.valueOf(((Long) pointCloud2.getProperty("row_step")).intValue()); cloud.is_dense = (Boolean) pointCloud2.getProperty("is_dense"); Filter filter = new FilterPredicate("cloud", FilterOperator.EQUAL, keyStr); Query fieldQuery = new Query("PointField").setFilter(filter); PreparedQuery fields = datastore.prepare(fieldQuery); List<Entity>lFields = fields.asList(FetchOptions.Builder.withDefaults()); cloud.fields = new PointField[lFields.size()]; int i; for(i = 0; i < lFields.size(); i++){ int idx = ((Long) lFields.get(i).getProperty("idx")).intValue(); cloud.fields[idx] = new PointField(); cloud.fields[idx].count = Integer.valueOf(((Long) lFields.get(i).getProperty("count")).intValue()); cloud.fields[idx].offset = Integer.valueOf(((Long) lFields.get(i).getProperty("offset")).intValue()); cloud.fields[idx].datatype = Byte.valueOf(((Long) lFields.get(i).getProperty("datatype")).byteValue()); cloud.fields[idx].name = (String) lFields.get(i).getProperty("name"); } BlobKey blobKey =(BlobKey) pointCloud2.getProperty("data"); ServletOutputStream out = response.getOutputStream(); out.print("# .PCD v0.7 - Point Cloud Data file format\n"); out.print("VERSION 0.7\n"); out.print(getFieldstr(cloud)+"\n"); out.print(getSizeStr(cloud)+"\n"); out.print(getTypeStr(cloud)+"\n"); out.print(getCountStr(cloud)+"\n"); out.print("WIDTH " + cloud.width+"\n" ); out.print("HEIGHT " + cloud.height+"\n"); out.print("VIEWPOINT 0 0 0 1 0 0 0\n"); out.print("POINTS " + cloud.width * cloud.height + "\n"); out.print("DATA binary\n"); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey); if( blobInfo == null ) return; if( blobInfo.getSize() > Integer.MAX_VALUE ) throw new RuntimeException("This method can only process blobs up to " + Integer.MAX_VALUE + " bytes"); int blobSize = (int)blobInfo.getSize(); int chunks = (int)Math.ceil(((double)blobSize / BlobstoreService.MAX_BLOB_FETCH_SIZE)); int startPointer = 0; int endPointer; for(i = 0; i < chunks; i++ ){ endPointer = Math.min(blobSize - 1, startPointer + BlobstoreService.MAX_BLOB_FETCH_SIZE - 1); byte[] bytes = blobstoreService.fetchData(blobKey, startPointer, endPointer); out.write(bytes); startPointer = endPointer + 1; } // out.write(cloud.data.getBytes()); out.flush(); } catch(IndexOutOfBoundsException e) { ServletOutputStream out = response.getOutputStream(); out.println("can't fetch pointcloud "+ keyStr); out.flush(); } } private String getTypeStr(PointCloud2 cloud) { String typeStr = new String("TYPE"); for(PointField field: cloud.fields){ switch(field.datatype){ case(1): case(3): case(5): typeStr = typeStr + " I"; break; case(2): case(4): case(6): typeStr = typeStr + " U"; break; case(7): case(8): typeStr = typeStr + " F"; break; } } return typeStr; } private String getCountStr(PointCloud2 cloud) { String countStr = new String("COUNT"); for(PointField field: cloud.fields){ countStr = countStr + " " + field.count; } return countStr; } private String getSizeStr(PointCloud2 cloud) { String typeStr = new String("SIZE"); for(PointField field: cloud.fields){ switch(field.datatype){ case(1): case(2): typeStr = typeStr + " 1"; break; case(3): case(4): typeStr = typeStr + " 2"; break; case(5): case(6): case(7): case(8): typeStr = typeStr + " 4"; break; } } return typeStr; } private String getFieldstr(PointCloud2 cloud) { String fieldStr = new String("FIELDS"); for(PointField field: cloud.fields){ fieldStr = fieldStr + " " + field.name; } return fieldStr; } }
jolting/cs263
project/src/main/java/project/GetPCD.java
Java
bsd-3-clause
8,756
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.modelaccess.impl.keys; import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess.LanguageOption; import edu.cornell.mannlib.vitro.webapp.utils.logging.ToString; /** * An immutable key for storing and retrieving OntModels. * * In addition to the usual options, it has a name, which adds to the * uniqueness. */ public final class OntModelKey extends ModelAccessKey { private final String name; private final int hashCode; public OntModelKey(String name, LanguageOption... options) { super(findLanguageOption(options)); this.name = name; this.hashCode = super.hashCode() ^ name.hashCode(); } public String getName() { return name; } @Override public LanguageOption getLanguageOption() { return super.getLanguageOption(); } @Override public boolean equals(Object obj) { return super.equals(obj) && ((OntModelKey) obj).name.equals(this.name); } @Override public int hashCode() { return hashCode; } @Override public String toString() { return super.toString() + " " + ToString.modelName(name); } }
vivo-project/Vitro
api/src/main/java/edu/cornell/mannlib/vitro/webapp/modelaccess/impl/keys/OntModelKey.java
Java
bsd-3-clause
1,164
/** * +--------------------------------------------------------------------+ * | This HTML_CodeSniffer file is Copyright (c) | * | Squiz Australia Pty Ltd ABN 53 131 581 247 | * +--------------------------------------------------------------------+ * | IMPORTANT: Your use of this Software is subject to the terms of | * | the Licence provided in the file licence.txt. If you cannot find | * | this file please contact Squiz (www.squiz.com.au) so we may | * | provide you a copy. | * +--------------------------------------------------------------------+ * */ /* Japanese translation by Yoshiki Kato @burnworks - v1.0.0 - 2016-03-01 */ var HTMLCS_Section508_Sniffs_C = { /** * Determines the elements to register for processing. * * Each element of the returned array can either be an element name, or "_top" * which is the top element of the tested code. * * @returns {Array} The list of elements. */ register: function() { return ['_top']; }, /** * Process the registered element. * * @param {DOMNode} element The element registered. * @param {DOMNode} top The top element of the tested code. */ process: function(element, top) { HTMLCS.addMessage(HTMLCS.NOTICE, top, '色が情報を伝える、あるいは視覚的な要素を判別するための唯一の視覚的手段になっていないことを確認してください。 Ensure that any information conveyed using colour alone is also available without colour, such as through context or markup.', 'Colour'); } };
burnworks/HTML_CodeSniffer-ja
Standards/Section508/Sniffs/C.js
JavaScript
bsd-3-clause
1,711
// +build freebsd linux darwin package disk import "syscall" func DiskUsage(path string) (*DiskUsageStat, error) { stat := syscall.Statfs_t{} err := syscall.Statfs(path, &stat) if err != nil { return nil, err } bsize := stat.Bsize ret := &DiskUsageStat{ Path: path, Total: (uint64(stat.Blocks) * uint64(bsize)), Free: (uint64(stat.Bfree) * uint64(bsize)), InodesTotal: (uint64(stat.Files)), InodesFree: (uint64(stat.Ffree)), } ret.InodesUsed = (ret.InodesTotal - ret.InodesFree) ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0 ret.Used = (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(bsize) ret.UsedPercent = (float64(ret.Used) / float64(ret.Total)) * 100.0 return ret, nil }
jmptrader/gopsutil
disk/disk_unix.go
GO
bsd-3-clause
771
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "../../source/BitstreamBuilder.h" #include "../../source/BitstreamParser.h" #include <assert.h> #include <stdio.h> #include <math.h> #include <tchar.h> #include <windows.h> uint32_t BitRateBPS(uint16_t x ) { return (x & 0x3fff) * uint32_t(pow(10.0f,(2 + (x >> 14)))); } uint16_t BitRateBPSInv(uint32_t x ) { // 16383 0x3fff // 1 638 300 exp 0 // 16 383 000 exp 1 // 163 830 000 exp 2 // 1 638 300 000 exp 3 const float exp = log10(float(x>>14)) - 2; if(exp < 0.0) { return uint16_t(x /100); }else if(exp < 1.0) { return 0x4000 + uint16_t(x /1000); }else if(exp < 2.0) { return 0x8000 + uint16_t(x /10000); }else if(exp < 3.0) { return 0xC000 + uint16_t(x /100000); } else { assert(false); return 0; } } int _tmain(int argc, _TCHAR* argv[]) { uint8_t dataBuffer[128]; BitstreamBuilder builder(dataBuffer, sizeof(dataBuffer)); // test 1 to 4 bits builder.Add1Bit(1); builder.Add1Bit(0); builder.Add1Bit(1); builder.Add2Bits(1); builder.Add2Bits(2); builder.Add2Bits(3); builder.Add3Bits(1); builder.Add3Bits(3); builder.Add3Bits(7); builder.Add4Bits(1); builder.Add4Bits(5); builder.Add4Bits(15); assert(4 == builder.Length()); BitstreamParser parser(dataBuffer, sizeof(dataBuffer)); assert(1 == parser.Get1Bit()); assert(0 == parser.Get1Bit()); assert(1 == parser.Get1Bit()); assert(1 == parser.Get2Bits()); assert(2 == parser.Get2Bits()); assert(3 == parser.Get2Bits()); assert(1 == parser.Get3Bits()); assert(3 == parser.Get3Bits()); assert(7 == parser.Get3Bits()); assert(1 == parser.Get4Bits()); assert(5 == parser.Get4Bits()); assert(15 == parser.Get4Bits()); printf("Test of 1 to 4 bits done\n"); // test 5 to 7 bits builder.Add5Bits(1); builder.Add5Bits(15); builder.Add5Bits(30); builder.Add6Bits(1); builder.Add6Bits(30); builder.Add6Bits(60); builder.Add7Bits(1); builder.Add7Bits(60); builder.Add7Bits(120); assert(1 == parser.Get5Bits()); assert(15 == parser.Get5Bits()); assert(30 == parser.Get5Bits()); assert(1 == parser.Get6Bits()); assert(30 == parser.Get6Bits()); assert(60 == parser.Get6Bits()); assert(1 == parser.Get7Bits()); assert(60 == parser.Get7Bits()); assert(120 == parser.Get7Bits()); printf("Test of 5 to 7 bits done\n"); builder.Add8Bits(1); builder.Add1Bit(1); builder.Add8Bits(255); builder.Add1Bit(0); builder.Add8Bits(127); builder.Add1Bit(1); builder.Add8Bits(60); builder.Add1Bit(0); builder.Add8Bits(30); builder.Add1Bit(1); builder.Add8Bits(120); builder.Add1Bit(0); builder.Add8Bits(160); builder.Add1Bit(1); builder.Add8Bits(180); assert(1 == parser.Get8Bits()); assert(1 == parser.Get1Bit()); assert(255 == parser.Get8Bits()); assert(0 == parser.Get1Bit()); assert(127 == parser.Get8Bits()); assert(1 == parser.Get1Bit()); assert(60 == parser.Get8Bits()); assert(0 == parser.Get1Bit()); assert(30 == parser.Get8Bits()); assert(1 == parser.Get1Bit()); assert(120 == parser.Get8Bits()); assert(0 == parser.Get1Bit()); assert(160 == parser.Get8Bits()); assert(1 == parser.Get1Bit()); assert(180 == parser.Get8Bits()); printf("Test of 8 bits done\n"); builder.Add16Bits(1); builder.Add1Bit(1); builder.Add16Bits(255); builder.Add1Bit(0); builder.Add16Bits(12756); builder.Add1Bit(1); builder.Add16Bits(60); builder.Add1Bit(0); builder.Add16Bits(30); builder.Add1Bit(1); builder.Add16Bits(30120); builder.Add1Bit(0); builder.Add16Bits(160); builder.Add1Bit(1); builder.Add16Bits(180); assert(1 == parser.Get16Bits()); assert(1 == parser.Get1Bit()); assert(255 == parser.Get16Bits()); assert(0 == parser.Get1Bit()); assert(12756 == parser.Get16Bits()); assert(1 == parser.Get1Bit()); assert(60 == parser.Get16Bits()); assert(0 == parser.Get1Bit()); assert(30 == parser.Get16Bits()); assert(1 == parser.Get1Bit()); assert(30120 == parser.Get16Bits()); assert(0 == parser.Get1Bit()); assert(160 == parser.Get16Bits()); assert(1 == parser.Get1Bit()); assert(180 == parser.Get16Bits()); printf("Test of 16 bits done\n"); builder.Add24Bits(1); builder.Add1Bit(1); builder.Add24Bits(255); builder.Add1Bit(0); builder.Add24Bits(12756); builder.Add1Bit(1); builder.Add24Bits(60); builder.Add1Bit(0); builder.Add24Bits(303333); builder.Add1Bit(1); builder.Add24Bits(30120); builder.Add1Bit(0); builder.Add24Bits(160); builder.Add1Bit(1); builder.Add24Bits(8018018); assert(1 == parser.Get24Bits()); assert(1 == parser.Get1Bit()); assert(255 == parser.Get24Bits()); assert(0 == parser.Get1Bit()); assert(12756 == parser.Get24Bits()); assert(1 == parser.Get1Bit()); assert(60 == parser.Get24Bits()); assert(0 == parser.Get1Bit()); assert(303333 == parser.Get24Bits()); assert(1 == parser.Get1Bit()); assert(30120 == parser.Get24Bits()); assert(0 == parser.Get1Bit()); assert(160 == parser.Get24Bits()); assert(1 == parser.Get1Bit()); assert(8018018 == parser.Get24Bits()); printf("Test of 24 bits done\n"); builder.Add32Bits(1); builder.Add1Bit(1); builder.Add32Bits(255); builder.Add1Bit(0); builder.Add32Bits(12756); builder.Add1Bit(1); builder.Add32Bits(60); builder.Add1Bit(0); builder.Add32Bits(303333); builder.Add1Bit(1); builder.Add32Bits(3012000012); builder.Add1Bit(0); builder.Add32Bits(1601601601); builder.Add1Bit(1); builder.Add32Bits(8018018); assert(1 == parser.Get32Bits()); assert(1 == parser.Get1Bit()); assert(255 == parser.Get32Bits()); assert(0 == parser.Get1Bit()); assert(12756 == parser.Get32Bits()); assert(1 == parser.Get1Bit()); assert(60 == parser.Get32Bits()); assert(0 == parser.Get1Bit()); assert(303333 == parser.Get32Bits()); assert(1 == parser.Get1Bit()); assert(3012000012 == parser.Get32Bits()); assert(0 == parser.Get1Bit()); assert(1601601601 == parser.Get32Bits()); assert(1 == parser.Get1Bit()); assert(8018018 == parser.Get32Bits()); printf("Test of 32 bits done\n"); builder.AddUE(1); builder.AddUE(4); builder.AddUE(9809706); builder.AddUE(2); builder.AddUE(15); builder.AddUE(16998); assert( 106 == builder.Length()); assert(1 == parser.GetUE()); assert(4 == parser.GetUE()); assert(9809706 == parser.GetUE()); assert(2 == parser.GetUE()); assert(15 == parser.GetUE()); assert(16998 == parser.GetUE()); printf("Test UE bits done\n"); BitstreamBuilder builderScalabilityInfo(dataBuffer, sizeof(dataBuffer)); BitstreamParser parserScalabilityInfo(dataBuffer, sizeof(dataBuffer)); const uint8_t numberOfLayers = 4; const uint8_t layerId[numberOfLayers] = {0,1,2,3}; const uint8_t priorityId[numberOfLayers] = {0,1,2,3}; const uint8_t discardableId[numberOfLayers] = {0,1,1,1}; const uint8_t dependencyId[numberOfLayers]= {0,1,1,1}; const uint8_t qualityId[numberOfLayers]= {0,0,0,1}; const uint8_t temporalId[numberOfLayers]= {0,0,1,1}; const uint16_t avgBitrate[numberOfLayers]= {BitRateBPSInv(100000), BitRateBPSInv(200000), BitRateBPSInv(400000), BitRateBPSInv(800000)}; // todo which one is the sum? const uint16_t maxBitrateLayer[numberOfLayers]= {BitRateBPSInv(150000), BitRateBPSInv(300000), BitRateBPSInv(500000), BitRateBPSInv(900000)}; const uint16_t maxBitrateLayerRepresentation[numberOfLayers] = {BitRateBPSInv(150000), BitRateBPSInv(450000), BitRateBPSInv(950000), BitRateBPSInv(1850000)}; assert( 16300 == BitRateBPS(BitRateBPSInv(16383))); assert( 163800 == BitRateBPS(BitRateBPSInv(163830))); assert( 1638300 == BitRateBPS(BitRateBPSInv(1638300))); assert( 1638000 == BitRateBPS(BitRateBPSInv(1638400))); assert( 18500 == BitRateBPS(BitRateBPSInv(18500))); assert( 185000 == BitRateBPS(BitRateBPSInv(185000))); assert( 1850000 == BitRateBPS(BitRateBPSInv(1850000))); assert( 18500000 == BitRateBPS(BitRateBPSInv(18500000))); assert( 185000000 == BitRateBPS(BitRateBPSInv(185000000))); const uint16_t maxBitrareCalcWindow[numberOfLayers] = {200, 200,200,200};// in 1/100 of second builderScalabilityInfo.Add1Bit(0); // temporal_id_nesting_flag builderScalabilityInfo.Add1Bit(0); // priority_layer_info_present_flag builderScalabilityInfo.Add1Bit(0); // priority_id_setting_flag builderScalabilityInfo.AddUE(numberOfLayers-1); for(int i = 0; i<= numberOfLayers-1; i++) { builderScalabilityInfo.AddUE(layerId[i]); builderScalabilityInfo.Add6Bits(priorityId[i]); builderScalabilityInfo.Add1Bit(discardableId[i]); builderScalabilityInfo.Add3Bits(dependencyId[i]); builderScalabilityInfo.Add4Bits(qualityId[i]); builderScalabilityInfo.Add3Bits(temporalId[i]); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(1); // bitrate_info_present_flag builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add1Bit(0); builderScalabilityInfo.Add16Bits(avgBitrate[i]); builderScalabilityInfo.Add16Bits(maxBitrateLayer[i]); builderScalabilityInfo.Add16Bits(maxBitrateLayerRepresentation[i]); builderScalabilityInfo.Add16Bits(maxBitrareCalcWindow[i]); builderScalabilityInfo.AddUE(0); // layer_dependency_info_src_layer_id_delta builderScalabilityInfo.AddUE(0); // parameter_sets_info_src_layer_id_delta } printf("Test builderScalabilityInfo done\n"); // Scalability Info parser parserScalabilityInfo.Get1Bit(); // not used in futher parsing const uint8_t priority_layer_info_present = parserScalabilityInfo.Get1Bit(); const uint8_t priority_id_setting_flag = parserScalabilityInfo.Get1Bit(); uint32_t numberOfLayersMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t j = 0; j<= numberOfLayersMinusOne; j++) { parserScalabilityInfo.GetUE(); parserScalabilityInfo.Get6Bits(); parserScalabilityInfo.Get1Bit(); parserScalabilityInfo.Get3Bits(); parserScalabilityInfo.Get4Bits(); parserScalabilityInfo.Get3Bits(); const uint8_t sub_pic_layer_flag = parserScalabilityInfo.Get1Bit(); const uint8_t sub_region_layer_flag = parserScalabilityInfo.Get1Bit(); const uint8_t iroi_division_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t profile_level_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t bitrate_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t frm_rate_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t frm_size_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t layer_dependency_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t parameter_sets_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t bitstream_restriction_info_present_flag = parserScalabilityInfo.Get1Bit(); const uint8_t exact_inter_layer_pred_flag = parserScalabilityInfo.Get1Bit(); // not used in futher parsing if(sub_pic_layer_flag || iroi_division_info_present_flag) { parserScalabilityInfo.Get1Bit(); } const uint8_t layer_conversion_flag = parserScalabilityInfo.Get1Bit(); const uint8_t layer_output_flag = parserScalabilityInfo.Get1Bit(); // not used in futher parsing if(profile_level_info_present_flag) { parserScalabilityInfo.Get24Bits(); } if(bitrate_info_present_flag) { // this is what we want assert(avgBitrate[j] == parserScalabilityInfo.Get16Bits()); assert(maxBitrateLayer[j] == parserScalabilityInfo.Get16Bits()); assert(maxBitrateLayerRepresentation[j] == parserScalabilityInfo.Get16Bits()); assert(maxBitrareCalcWindow[j] == parserScalabilityInfo.Get16Bits()); }else { assert(false); } if(frm_rate_info_present_flag) { parserScalabilityInfo.Get2Bits(); parserScalabilityInfo.Get16Bits(); } if(frm_size_info_present_flag || iroi_division_info_present_flag) { parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); } if(sub_region_layer_flag) { parserScalabilityInfo.GetUE(); if(parserScalabilityInfo.Get1Bit()) { parserScalabilityInfo.Get16Bits(); parserScalabilityInfo.Get16Bits(); parserScalabilityInfo.Get16Bits(); parserScalabilityInfo.Get16Bits(); } } if(sub_pic_layer_flag) { parserScalabilityInfo.GetUE(); } if(iroi_division_info_present_flag) { if(parserScalabilityInfo.Get1Bit()) { parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); }else { const uint32_t numRoisMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t k = 0; k <= numRoisMinusOne; k++) { parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); } } } if(layer_dependency_info_present_flag) { const uint32_t numDirectlyDependentLayers = parserScalabilityInfo.GetUE(); for(uint32_t k = 0; k < numDirectlyDependentLayers; k++) { parserScalabilityInfo.GetUE(); } } else { parserScalabilityInfo.GetUE(); } if(parameter_sets_info_present_flag) { const uint32_t numSeqParameterSetMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t k = 0; k <= numSeqParameterSetMinusOne; k++) { parserScalabilityInfo.GetUE(); } const uint32_t numSubsetSeqParameterSetMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t l = 0; l <= numSubsetSeqParameterSetMinusOne; l++) { parserScalabilityInfo.GetUE(); } const uint32_t numPicParameterSetMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t m = 0; m <= numPicParameterSetMinusOne; m++) { parserScalabilityInfo.GetUE(); } }else { parserScalabilityInfo.GetUE(); } if(bitstream_restriction_info_present_flag) { parserScalabilityInfo.Get1Bit(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); parserScalabilityInfo.GetUE(); } if(layer_conversion_flag) { parserScalabilityInfo.GetUE(); for(uint32_t k = 0; k <2;k++) { if(parserScalabilityInfo.Get1Bit()) { parserScalabilityInfo.Get24Bits(); parserScalabilityInfo.Get16Bits(); parserScalabilityInfo.Get16Bits(); } } } } if(priority_layer_info_present) { const uint32_t prNumDidMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t k = 0; k <= prNumDidMinusOne;k++) { parserScalabilityInfo.Get3Bits(); const uint32_t prNumMinusOne = parserScalabilityInfo.GetUE(); for(uint32_t l = 0; l <= prNumMinusOne; l++) { parserScalabilityInfo.GetUE(); parserScalabilityInfo.Get24Bits(); parserScalabilityInfo.Get16Bits(); parserScalabilityInfo.Get16Bits(); } } } if(priority_id_setting_flag) { uint8_t priorityIdSettingUri; uint32_t priorityIdSettingUriIdx = 0; do { priorityIdSettingUri = parserScalabilityInfo.Get8Bits(); } while (priorityIdSettingUri != 0); } printf("Test parserScalabilityInfo done\n"); printf("\nAPI test of parser for ScalabilityInfo done\n"); ::Sleep(5000); }
matsumoto-r/synciga
src/third_party/webrtc/modules/rtp_rtcp/test/bitstreamTest/bitstreamTest.cc
C++
bsd-3-clause
18,222
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/loader/resource_loader.h" #include "base/command_line.h" #include "base/message_loop.h" #include "base/time.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/loader/doomed_resource_handler.h" #include "content/browser/loader/resource_loader_delegate.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/ssl/ssl_client_auth_handler.h" #include "content/browser/ssl/ssl_manager.h" #include "content/common/ssl_status_serialization.h" #include "content/public/browser/cert_store.h" #include "content/public/browser/resource_dispatcher_host_login_delegate.h" #include "content/public/browser/site_instance.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/resource_response.h" #include "content/public/common/url_constants.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/ssl/client_cert_store.h" #include "net/ssl/client_cert_store_impl.h" #include "webkit/appcache/appcache_interceptor.h" using base::TimeDelta; using base::TimeTicks; namespace content { namespace { void PopulateResourceResponse(net::URLRequest* request, ResourceResponse* response) { response->head.error_code = request->status().error(); response->head.request_time = request->request_time(); response->head.response_time = request->response_time(); response->head.headers = request->response_headers(); request->GetCharset(&response->head.charset); response->head.content_length = request->GetExpectedContentSize(); request->GetMimeType(&response->head.mime_type); net::HttpResponseInfo response_info = request->response_info(); response->head.was_fetched_via_spdy = response_info.was_fetched_via_spdy; response->head.was_npn_negotiated = response_info.was_npn_negotiated; response->head.npn_negotiated_protocol = response_info.npn_negotiated_protocol; response->head.was_fetched_via_proxy = request->was_fetched_via_proxy(); response->head.socket_address = request->GetSocketAddress(); appcache::AppCacheInterceptor::GetExtraResponseInfo( request, &response->head.appcache_id, &response->head.appcache_manifest_url); } } // namespace ResourceLoader::ResourceLoader(scoped_ptr<net::URLRequest> request, scoped_ptr<ResourceHandler> handler, ResourceLoaderDelegate* delegate) : weak_ptr_factory_(this) { scoped_ptr<net::ClientCertStore> client_cert_store; #if !defined(USE_OPENSSL) client_cert_store.reset(new net::ClientCertStoreImpl()); #endif Init(request.Pass(), handler.Pass(), delegate, client_cert_store.Pass()); } ResourceLoader::~ResourceLoader() { if (login_delegate_) login_delegate_->OnRequestCancelled(); if (ssl_client_auth_handler_) ssl_client_auth_handler_->OnRequestCancelled(); // Run ResourceHandler destructor before we tear-down the rest of our state // as the ResourceHandler may want to inspect the URLRequest and other state. handler_.reset(); } void ResourceLoader::StartRequest() { if (delegate_->HandleExternalProtocol(this, request_->url())) { CancelAndIgnore(); return; } // Give the handler a chance to delay the URLRequest from being started. bool defer_start = false; if (!handler_->OnWillStart(GetRequestInfo()->GetRequestID(), request_->url(), &defer_start)) { Cancel(); return; } if (defer_start) { deferred_stage_ = DEFERRED_START; } else { StartRequestInternal(); } } void ResourceLoader::CancelRequest(bool from_renderer) { CancelRequestInternal(net::ERR_ABORTED, from_renderer); } void ResourceLoader::CancelAndIgnore() { ResourceRequestInfoImpl* info = GetRequestInfo(); info->set_was_ignored_by_handler(true); CancelRequest(false); } void ResourceLoader::CancelWithError(int error_code) { CancelRequestInternal(error_code, false); } void ResourceLoader::ReportUploadProgress() { ResourceRequestInfoImpl* info = GetRequestInfo(); if (waiting_for_upload_progress_ack_) return; // Send one progress event at a time. net::UploadProgress progress = request_->GetUploadProgress(); if (!progress.size()) return; // Nothing to upload. if (progress.position() == last_upload_position_) return; // No progress made since last time. const uint64 kHalfPercentIncrements = 200; const TimeDelta kOneSecond = TimeDelta::FromMilliseconds(1000); uint64 amt_since_last = progress.position() - last_upload_position_; TimeDelta time_since_last = TimeTicks::Now() - last_upload_ticks_; bool is_finished = (progress.size() == progress.position()); bool enough_new_progress = (amt_since_last > (progress.size() / kHalfPercentIncrements)); bool too_much_time_passed = time_since_last > kOneSecond; if (is_finished || enough_new_progress || too_much_time_passed) { if (request_->load_flags() & net::LOAD_ENABLE_UPLOAD_PROGRESS) { handler_->OnUploadProgress( info->GetRequestID(), progress.position(), progress.size()); waiting_for_upload_progress_ack_ = true; } last_upload_ticks_ = TimeTicks::Now(); last_upload_position_ = progress.position(); } } void ResourceLoader::MarkAsTransferring() { is_transferring_ = true; // When an URLRequest is transferred to a new RenderViewHost, its // ResourceHandler should not receive any notifications because it may depend // on the state of the old RVH. We set a ResourceHandler that only allows // canceling requests, because on shutdown of the RDH all pending requests // are canceled. The RVH of requests that are being transferred may be gone // by that time. In CompleteTransfer, the ResoureHandlers are substituted // again. handler_.reset(new DoomedResourceHandler(handler_.Pass())); } void ResourceLoader::WillCompleteTransfer() { handler_.reset(); } void ResourceLoader::CompleteTransfer(scoped_ptr<ResourceHandler> new_handler) { DCHECK_EQ(DEFERRED_REDIRECT, deferred_stage_); DCHECK(!handler_.get()); handler_ = new_handler.Pass(); handler_->SetController(this); is_transferring_ = false; Resume(); } ResourceRequestInfoImpl* ResourceLoader::GetRequestInfo() { return ResourceRequestInfoImpl::ForRequest(request_.get()); } void ResourceLoader::ClearLoginDelegate() { login_delegate_ = NULL; } void ResourceLoader::ClearSSLClientAuthHandler() { ssl_client_auth_handler_ = NULL; } void ResourceLoader::OnUploadProgressACK() { waiting_for_upload_progress_ack_ = false; } ResourceLoader::ResourceLoader( scoped_ptr<net::URLRequest> request, scoped_ptr<ResourceHandler> handler, ResourceLoaderDelegate* delegate, scoped_ptr<net::ClientCertStore> client_cert_store) : weak_ptr_factory_(this) { Init(request.Pass(), handler.Pass(), delegate, client_cert_store.Pass()); } void ResourceLoader::Init(scoped_ptr<net::URLRequest> request, scoped_ptr<ResourceHandler> handler, ResourceLoaderDelegate* delegate, scoped_ptr<net::ClientCertStore> client_cert_store) { deferred_stage_ = DEFERRED_NONE; request_ = request.Pass(); handler_ = handler.Pass(); delegate_ = delegate; last_upload_position_ = 0; waiting_for_upload_progress_ack_ = false; is_transferring_ = false; client_cert_store_ = client_cert_store.Pass(); request_->set_delegate(this); handler_->SetController(this); } void ResourceLoader::OnReceivedRedirect(net::URLRequest* unused, const GURL& new_url, bool* defer) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnReceivedRedirect: " << request_->url().spec(); DCHECK(request_->status().is_success()); ResourceRequestInfoImpl* info = GetRequestInfo(); if (info->process_type() != PROCESS_TYPE_PLUGIN && !ChildProcessSecurityPolicyImpl::GetInstance()-> CanRequestURL(info->GetChildID(), new_url)) { VLOG(1) << "Denied unauthorized request for " << new_url.possibly_invalid_spec(); // Tell the renderer that this request was disallowed. Cancel(); return; } delegate_->DidReceiveRedirect(this, new_url); if (delegate_->HandleExternalProtocol(this, new_url)) { // The request is complete so we can remove it. CancelAndIgnore(); return; } scoped_refptr<ResourceResponse> response(new ResourceResponse()); PopulateResourceResponse(request_.get(), response); if (!handler_->OnRequestRedirected(info->GetRequestID(), new_url, response, defer)) { Cancel(); } else if (*defer) { deferred_stage_ = DEFERRED_REDIRECT; // Follow redirect when resumed. } } void ResourceLoader::OnAuthRequired(net::URLRequest* unused, net::AuthChallengeInfo* auth_info) { DCHECK_EQ(request_.get(), unused); if (request_->load_flags() & net::LOAD_DO_NOT_PROMPT_FOR_LOGIN) { request_->CancelAuth(); return; } if (!delegate_->AcceptAuthRequest(this, auth_info)) { request_->CancelAuth(); return; } // Create a login dialog on the UI thread to get authentication data, or pull // from cache and continue on the IO thread. DCHECK(!login_delegate_) << "OnAuthRequired called with login_delegate pending"; login_delegate_ = delegate_->CreateLoginDelegate(this, auth_info); if (!login_delegate_) request_->CancelAuth(); } void ResourceLoader::OnCertificateRequested( net::URLRequest* unused, net::SSLCertRequestInfo* cert_info) { DCHECK_EQ(request_.get(), unused); if (!delegate_->AcceptSSLClientCertificateRequest(this, cert_info)) { request_->Cancel(); return; } #if !defined(USE_OPENSSL) client_cert_store_->GetClientCerts(*cert_info, &cert_info->client_certs); if (cert_info->client_certs.empty()) { // No need to query the user if there are no certs to choose from. request_->ContinueWithCertificate(NULL); return; } #endif DCHECK(!ssl_client_auth_handler_) << "OnCertificateRequested called with ssl_client_auth_handler pending"; ssl_client_auth_handler_ = new SSLClientAuthHandler(request_.get(), cert_info); ssl_client_auth_handler_->SelectCertificate(); } void ResourceLoader::OnSSLCertificateError(net::URLRequest* request, const net::SSLInfo& ssl_info, bool fatal) { ResourceRequestInfoImpl* info = GetRequestInfo(); int render_process_id; int render_view_id; if (!info->GetAssociatedRenderView(&render_process_id, &render_view_id)) NOTREACHED(); SSLManager::OnSSLCertificateError( weak_ptr_factory_.GetWeakPtr(), info->GetGlobalRequestID(), info->GetResourceType(), request_->url(), render_process_id, render_view_id, ssl_info, fatal); } void ResourceLoader::OnResponseStarted(net::URLRequest* unused) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnResponseStarted: " << request_->url().spec(); // The CanLoadPage check should take place after any server redirects have // finished, at the point in time that we know a page will commit in the // renderer process. ResourceRequestInfoImpl* info = GetRequestInfo(); ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (!policy->CanLoadPage(info->GetChildID(), request_->url(), info->GetResourceType())) { Cancel(); return; } if (!request_->status().is_success()) { ResponseCompleted(); return; } // We want to send a final upload progress message prior to sending the // response complete message even if we're waiting for an ack to to a // previous upload progress message. waiting_for_upload_progress_ack_ = false; ReportUploadProgress(); CompleteResponseStarted(); if (is_deferred()) return; if (request_->status().is_success()) { StartReading(false); // Read the first chunk. } else { ResponseCompleted(); } } void ResourceLoader::OnReadCompleted(net::URLRequest* unused, int bytes_read) { DCHECK_EQ(request_.get(), unused); VLOG(1) << "OnReadCompleted: \"" << request_->url().spec() << "\"" << " bytes_read = " << bytes_read; // bytes_read == -1 always implies an error. if (bytes_read == -1 || !request_->status().is_success()) { ResponseCompleted(); return; } CompleteRead(bytes_read); if (is_deferred()) return; if (request_->status().is_success() && bytes_read > 0) { StartReading(true); // Read the next chunk. } else { ResponseCompleted(); } } void ResourceLoader::CancelSSLRequest(const GlobalRequestID& id, int error, const net::SSLInfo* ssl_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // The request can be NULL if it was cancelled by the renderer (as the // request of the user navigating to a new page from the location bar). if (!request_->is_pending()) return; DVLOG(1) << "CancelSSLRequest() url: " << request_->url().spec(); if (ssl_info) { request_->CancelWithSSLError(error, *ssl_info); } else { request_->CancelWithError(error); } } void ResourceLoader::ContinueSSLRequest(const GlobalRequestID& id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << "ContinueSSLRequest() url: " << request_->url().spec(); request_->ContinueDespiteLastError(); } void ResourceLoader::Resume() { DCHECK(!is_transferring_); DeferredStage stage = deferred_stage_; deferred_stage_ = DEFERRED_NONE; switch (stage) { case DEFERRED_NONE: NOTREACHED(); break; case DEFERRED_START: StartRequestInternal(); break; case DEFERRED_REDIRECT: request_->FollowDeferredRedirect(); break; case DEFERRED_READ: MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::ResumeReading, weak_ptr_factory_.GetWeakPtr())); break; case DEFERRED_FINISH: // Delay self-destruction since we don't know how we were reached. MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::CallDidFinishLoading, weak_ptr_factory_.GetWeakPtr())); break; } } void ResourceLoader::Cancel() { CancelRequest(false); } void ResourceLoader::StartRequestInternal() { DCHECK(!request_->is_pending()); request_->Start(); delegate_->DidStartRequest(this); } void ResourceLoader::CancelRequestInternal(int error, bool from_renderer) { VLOG(1) << "CancelRequestInternal: " << request_->url().spec(); ResourceRequestInfoImpl* info = GetRequestInfo(); // WebKit will send us a cancel for downloads since it no longer handles // them. In this case, ignore the cancel since we handle downloads in the // browser. if (from_renderer && (info->is_download() || info->is_stream())) return; // TODO(darin): Perhaps we should really be looking to see if the status is // IO_PENDING? bool was_pending = request_->is_pending(); if (login_delegate_) { login_delegate_->OnRequestCancelled(); login_delegate_ = NULL; } if (ssl_client_auth_handler_) { ssl_client_auth_handler_->OnRequestCancelled(); ssl_client_auth_handler_ = NULL; } request_->CancelWithError(error); if (!was_pending) { // If the request isn't in flight, then we won't get an asynchronous // notification from the request, so we have to signal ourselves to finish // this request. MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::ResponseCompleted, weak_ptr_factory_.GetWeakPtr())); } } void ResourceLoader::CompleteResponseStarted() { ResourceRequestInfoImpl* info = GetRequestInfo(); scoped_refptr<ResourceResponse> response(new ResourceResponse()); PopulateResourceResponse(request_.get(), response); // The --site-per-process flag enables an out-of-process iframes // prototype. It works by changing the MIME type of cross-site subframe // responses to a Chrome specific one. This new type causes the subframe // to be replaced by a <webview> tag with the same URL, which results in // using a renderer in a different process. // // For prototyping purposes, we will use a small hack to ensure same site // iframes are not changed. We can compare the URL for the subframe // request with the referrer. If the two don't match, then it should be a // cross-site iframe. // Also, we don't do the MIME type change for chrome:// URLs, as those // require different privileges and are not allowed in regular renderers. // // The usage of SiteInstance::IsSameWebSite is safe on the IO thread, // if the browser_context parameter is NULL. This does not work for hosted // apps, but should be fine for prototyping. // TODO(nasko): Once the SiteInstance check is fixed, ensure we do the // right thing here. http://crbug.com/160576 const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kSitePerProcess) && GetRequestInfo()->GetResourceType() == ResourceType::SUB_FRAME && response->head.mime_type == "text/html" && !request_->url().SchemeIs(chrome::kChromeUIScheme) && !SiteInstance::IsSameWebSite(NULL, request_->url(), request_->GetSanitizedReferrer())) { response->head.mime_type = "application/browser-plugin"; } if (request_->ssl_info().cert) { int cert_id = CertStore::GetInstance()->StoreCert(request_->ssl_info().cert, info->GetChildID()); response->head.security_info = SerializeSecurityInfo( cert_id, request_->ssl_info().cert_status, request_->ssl_info().security_bits, request_->ssl_info().connection_status); } else { // We should not have any SSL state. DCHECK(!request_->ssl_info().cert_status && request_->ssl_info().security_bits == -1 && !request_->ssl_info().connection_status); } delegate_->DidReceiveResponse(this); bool defer = false; if (!handler_->OnResponseStarted(info->GetRequestID(), response, &defer)) { Cancel(); } else if (defer) { deferred_stage_ = DEFERRED_READ; // Read first chunk when resumed. } } void ResourceLoader::StartReading(bool is_continuation) { int bytes_read = 0; ReadMore(&bytes_read); // If IO is pending, wait for the URLRequest to call OnReadCompleted. if (request_->status().is_io_pending()) return; if (!is_continuation || bytes_read <= 0) { OnReadCompleted(request_.get(), bytes_read); } else { // Else, trigger OnReadCompleted asynchronously to avoid starving the IO // thread in case the URLRequest can provide data synchronously. MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceLoader::OnReadCompleted, weak_ptr_factory_.GetWeakPtr(), request_.get(), bytes_read)); } } void ResourceLoader::ResumeReading() { DCHECK(!is_deferred()); if (request_->status().is_success()) { StartReading(false); // Read the next chunk (OK to complete synchronously). } else { ResponseCompleted(); } } void ResourceLoader::ReadMore(int* bytes_read) { ResourceRequestInfoImpl* info = GetRequestInfo(); DCHECK(!is_deferred()); net::IOBuffer* buf; int buf_size; if (!handler_->OnWillRead(info->GetRequestID(), &buf, &buf_size, -1)) { Cancel(); return; } DCHECK(buf); DCHECK(buf_size > 0); request_->Read(buf, buf_size, bytes_read); // No need to check the return value here as we'll detect errors by // inspecting the URLRequest's status. } void ResourceLoader::CompleteRead(int bytes_read) { DCHECK(bytes_read >= 0); DCHECK(request_->status().is_success()); ResourceRequestInfoImpl* info = GetRequestInfo(); bool defer = false; if (!handler_->OnReadCompleted(info->GetRequestID(), bytes_read, &defer)) { Cancel(); } else if (defer) { deferred_stage_ = DEFERRED_READ; // Read next chunk when resumed. } } void ResourceLoader::ResponseCompleted() { VLOG(1) << "ResponseCompleted: " << request_->url().spec(); ResourceRequestInfoImpl* info = GetRequestInfo(); std::string security_info; const net::SSLInfo& ssl_info = request_->ssl_info(); if (ssl_info.cert != NULL) { int cert_id = CertStore::GetInstance()->StoreCert(ssl_info.cert, info->GetChildID()); security_info = SerializeSecurityInfo( cert_id, ssl_info.cert_status, ssl_info.security_bits, ssl_info.connection_status); } if (handler_->OnResponseCompleted(info->GetRequestID(), request_->status(), security_info)) { // This will result in our destruction. CallDidFinishLoading(); } else { // The handler is not ready to die yet. We will call DidFinishLoading when // we resume. deferred_stage_ = DEFERRED_FINISH; } } void ResourceLoader::CallDidFinishLoading() { delegate_->DidFinishLoading(this); } } // namespace content
timopulkkinen/BubbleFish
content/browser/loader/resource_loader.cc
C++
bsd-3-clause
21,725
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h" #include "base/lazy_instance.h" #include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api_helpers.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/sync_file_system/sync_event_observer.h" #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "chrome/browser/sync_file_system/sync_file_system_service_factory.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "chrome/common/extensions/api/sync_file_system.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" #include "webkit/browser/fileapi/file_system_url.h" #include "webkit/common/fileapi/file_system_util.h" using sync_file_system::SyncEventObserver; namespace extensions { static base::LazyInstance< BrowserContextKeyedAPIFactory<ExtensionSyncEventObserver> > g_factory = LAZY_INSTANCE_INITIALIZER; // static BrowserContextKeyedAPIFactory<ExtensionSyncEventObserver>* ExtensionSyncEventObserver::GetFactoryInstance() { return g_factory.Pointer(); } ExtensionSyncEventObserver::ExtensionSyncEventObserver( content::BrowserContext* context) : browser_context_(context), sync_service_(NULL) {} void ExtensionSyncEventObserver::InitializeForService( sync_file_system::SyncFileSystemService* sync_service) { DCHECK(sync_service); if (sync_service_ != NULL) { DCHECK_EQ(sync_service_, sync_service); return; } sync_service_ = sync_service; sync_service_->AddSyncEventObserver(this); } ExtensionSyncEventObserver::~ExtensionSyncEventObserver() {} void ExtensionSyncEventObserver::Shutdown() { if (sync_service_ != NULL) sync_service_->RemoveSyncEventObserver(this); } std::string ExtensionSyncEventObserver::GetExtensionId( const GURL& app_origin) { const Extension* app = ExtensionSystem::Get(browser_context_) ->extension_service() ->GetInstalledApp(app_origin); if (!app) { // The app is uninstalled or disabled. return std::string(); } return app->id(); } void ExtensionSyncEventObserver::OnSyncStateUpdated( const GURL& app_origin, sync_file_system::SyncServiceState state, const std::string& description) { // Convert state and description into SyncState Object. api::sync_file_system::ServiceInfo service_info; service_info.state = SyncServiceStateToExtensionEnum(state); service_info.description = description; scoped_ptr<base::ListValue> params( api::sync_file_system::OnServiceStatusChanged::Create(service_info)); BroadcastOrDispatchEvent( app_origin, api::sync_file_system::OnServiceStatusChanged::kEventName, params.Pass()); } void ExtensionSyncEventObserver::OnFileSynced( const fileapi::FileSystemURL& url, sync_file_system::SyncFileStatus status, sync_file_system::SyncAction action, sync_file_system::SyncDirection direction) { scoped_ptr<base::ListValue> params(new base::ListValue()); // For now we always assume events come only for files (not directories). params->Append(CreateDictionaryValueForFileSystemEntry( url, sync_file_system::SYNC_FILE_TYPE_FILE)); // Status, SyncAction and any optional notes to go here. api::sync_file_system::FileStatus status_enum = SyncFileStatusToExtensionEnum(status); api::sync_file_system::SyncAction action_enum = SyncActionToExtensionEnum(action); api::sync_file_system::SyncDirection direction_enum = SyncDirectionToExtensionEnum(direction); params->AppendString(api::sync_file_system::ToString(status_enum)); params->AppendString(api::sync_file_system::ToString(action_enum)); params->AppendString(api::sync_file_system::ToString(direction_enum)); BroadcastOrDispatchEvent( url.origin(), api::sync_file_system::OnFileStatusChanged::kEventName, params.Pass()); } void ExtensionSyncEventObserver::BroadcastOrDispatchEvent( const GURL& app_origin, const std::string& event_name, scoped_ptr<base::ListValue> values) { // Check to see whether the event should be broadcasted to all listening // extensions or sent to a specific extension ID. bool broadcast_mode = app_origin.is_empty(); EventRouter* event_router = ExtensionSystem::Get(browser_context_)->event_router(); DCHECK(event_router); scoped_ptr<Event> event(new Event(event_name, values.Pass())); event->restrict_to_browser_context = browser_context_; // No app_origin, broadcast to all listening extensions for this event name. if (broadcast_mode) { event_router->BroadcastEvent(event.Pass()); return; } // Dispatch to single extension ID. const std::string extension_id = GetExtensionId(app_origin); if (extension_id.empty()) return; event_router->DispatchEventToExtension(extension_id, event.Pass()); } template <> void BrowserContextKeyedAPIFactory< ExtensionSyncEventObserver>::DeclareFactoryDependencies() { DependsOn(sync_file_system::SyncFileSystemServiceFactory::GetInstance()); DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory()); } } // namespace extensions
patrickm/chromium.src
chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.cc
C++
bsd-3-clause
5,577
package ee.ut.math.tvt.salessystem.service; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import org.hibernate.Session; import ee.ut.math.tvt.salessystem.domain.data.Order; import ee.ut.math.tvt.salessystem.domain.data.SoldItem; import ee.ut.math.tvt.salessystem.domain.data.StockItem; import ee.ut.math.tvt.salessystem.util.HibernateUtil; @SuppressWarnings("unchecked") public class HibernateDataService { private static final Logger log = Logger .getLogger(HibernateDataService.class); private Session session = HibernateUtil.currentSession(); public List<SoldItem> getSoldItems() { List<SoldItem> result = new ArrayList<SoldItem>(); try { result = session.createQuery("from SOLDITEM").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } public List<StockItem> getStockItems() { List<StockItem> result = new ArrayList<StockItem>(); try { result = session.createQuery("from STOCKITEM").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } public List<Order> getOrders() { List<Order> result = new ArrayList<Order>(); try { result = session.createQuery("from ORDER").list(); } catch (Throwable ex) { log.error("No database connection!"); JOptionPane.showMessageDialog(null, "Unable to connect to the database!"); } return result; } }
pohh-mell/BeerHousePOS
src/ee/ut/math/tvt/salessystem/service/HibernateDataService.java
Java
bsd-3-clause
1,610
<?php class EventTest extends PHPUnit_Framework_TestCase { private $db; public function setUp () { $this->db = new \PDO('mysql:dbname=moa', 'travis'); $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->db->exec("TRUNCATE TABLE `datetime`"); $this->db->exec("TRUNCATE TABLE `duplicate`"); $this->db->exec("TRUNCATE TABLE `greedy`"); $this->db->exec("TRUNCATE TABLE `greedy_timestamp`"); $this->db->exec("TRUNCATE TABLE `number`"); $this->db->exec("TRUNCATE TABLE `string`"); } /** * @expectedException RuntimeException * @expectedExceptionCode 1 */ public function testAfterInsert () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'throw_after_insert'; $foo->save(); } public function testAfterInsertRecover () { $properties = ['name' => 'throw_after_insert']; $foo = new \Sandbox\Model\String($this->db); $foo->populate($properties); try { $foo->save(); } catch (\RuntimeException $e) { $this->assertSame($properties, $foo->getData()); } } /** * @expectedException RuntimeException * @expectedExceptionCode 2 */ public function testAfterUpdate () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'throw_after_update'; $foo->save(); $foo->save(); } public function testAfterUpdateRecover () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'throw_after_update'; $foo->save(); $properties = $foo->getData(); try { $foo->save(); } catch (\RuntimeException $e) { $this->assertSame($properties, $foo->getData()); } } /** * @expectedException RuntimeException * @expectedExceptionCode 3 */ public function testAfterDelete () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'throw_after_delete'; $foo->save(); $foo->delete(); } public function testAfterDeleteRecover () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'throw_after_delete'; $foo->save(); $properties = $foo->getData(); try { $foo->delete(); } catch (\RuntimeException $e) { $this->assertSame($properties, $foo->getData()); } } /** * @expectedException Gajus\MOA\Exception\LogicException * @expectedExceptionMessage Transaction was commited before the time. */ public function testAfterInsertCannotCommitTransaction () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'insert_commit_transaction'; $foo->save(); } /** * @expectedException Gajus\MOA\Exception\LogicException * @expectedExceptionMessage Transaction was commited before the time. */ public function testAfterUpdateCannotCommitTransaction () { $foo = new \Sandbox\Model\String($this->db); $foo->save(); $foo['name'] = 'update_commit_transaction'; $foo->save(); } /** * @todo Check if object's state is recovered. * * @expectedException Gajus\MOA\Exception\LogicException * @expectedExceptionMessage Transaction was commited before the time. */ public function testAfterDeleteCannotCommitTransaction () { $foo = new \Sandbox\Model\String($this->db); $foo['name'] = 'delete_commit_transaction'; $foo->save(); $foo->delete(); } }
gajus/moa
tests/EventTest.php
PHP
bsd-3-clause
3,683
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.application.query; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataService; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataValueType; import gov.nih.nci.caintegrator.application.arraydata.ArrayDataValues; import gov.nih.nci.caintegrator.application.arraydata.DataRetrievalRequest; import gov.nih.nci.caintegrator.common.HibernateUtil; import gov.nih.nci.caintegrator.common.QueryUtil; import gov.nih.nci.caintegrator.data.CaIntegrator2Dao; import gov.nih.nci.caintegrator.domain.application.EntityTypeEnum; import gov.nih.nci.caintegrator.domain.application.GenomicDataQueryResult; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultColumn; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultRow; import gov.nih.nci.caintegrator.domain.application.GenomicDataResultValue; import gov.nih.nci.caintegrator.domain.application.Query; import gov.nih.nci.caintegrator.domain.application.ResultRow; import gov.nih.nci.caintegrator.domain.application.ResultTypeEnum; import gov.nih.nci.caintegrator.domain.application.SegmentDataResultValue; import gov.nih.nci.caintegrator.domain.genomic.AbstractReporter; import gov.nih.nci.caintegrator.domain.genomic.ArrayData; import gov.nih.nci.caintegrator.domain.genomic.GenomeBuildVersionEnum; import gov.nih.nci.caintegrator.domain.genomic.Platform; import gov.nih.nci.caintegrator.domain.genomic.ReporterList; import gov.nih.nci.caintegrator.domain.genomic.ReporterTypeEnum; import gov.nih.nci.caintegrator.domain.genomic.SegmentData; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.common.collect.Maps; /** * Runs queries that return <code>GenomicDataQueryResults</code>. */ class GenomicQueryHandler { private static final float DECIMAL_100 = 100.0f; private final Query query; private final CaIntegrator2Dao dao; private final ArrayDataService arrayDataService; GenomicQueryHandler(Query query, CaIntegrator2Dao dao, ArrayDataService arrayDataService) { this.query = query; this.dao = dao; this.arrayDataService = arrayDataService; } GenomicDataQueryResult execute() throws InvalidCriterionException { if (ResultTypeEnum.COPY_NUMBER.equals(query.getResultType())) { return createCopyNumberResult(); } ArrayDataValues values = getDataValues(); return createGeneExpressionResult(values); } Collection<SegmentData> retrieveSegmentDataQuery() throws InvalidCriterionException { Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); return getMatchingSegmentDatas(arrayDatas); } private GenomicDataQueryResult createGeneExpressionResult(ArrayDataValues values) { GenomicDataQueryResult result = new GenomicDataQueryResult(); createGeneExpressionResultRows(result, values); Map<Long, GenomicDataResultRow> reporterIdToRowMap = createReporterIdToRowMap(result); for (ArrayData arrayData : values.getArrayDatas()) { addToGeneExpressionResult(values, result, reporterIdToRowMap, arrayData); } result.setQuery(query); return result; } private GenomicDataQueryResult createCopyNumberResult() throws InvalidCriterionException { GenomicDataQueryResult result = new GenomicDataQueryResult(); Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); Collection<SegmentData> segmentDatas = getMatchingSegmentDatas(arrayDatas); Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap = createCopyNumberResultRows(result, arrayDatas, segmentDatas); CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); result.setHasCriterionSpecifiedValues(criterionHandler.hasCriterionSpecifiedSegmentValues()); for (ArrayData arrayData : arrayDatas) { addToCopyNumberResult(result, segmentDataToRowMap, arrayData, criterionHandler); } result.setQuery(query); return result; } private void addToCopyNumberResult(GenomicDataQueryResult result, Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap, ArrayData arrayData, CompoundCriterionHandler criterionHandler) { GenomicDataResultColumn column = result.addColumn(); //Just take the 1st sample aquisition column.setSampleAcquisition(arrayData.getSample().getSampleAcquisitions().iterator().next()); for (SegmentData segmentData : segmentDataToRowMap.keySet()) { if (segmentData.getArrayData().equals(arrayData)) { GenomicDataResultRow row = segmentDataToRowMap.get(segmentData); GenomicDataResultValue value = new GenomicDataResultValue(); value.setColumn(column); value.setValue(twoDecimalPoint(segmentData.getSegmentValue())); value.setCallsValue(segmentData.getCallsValue()); value.setProbabilityAmplification(twoDecimalPoint(segmentData.getProbabilityAmplification())); value.setProbabilityGain(twoDecimalPoint(segmentData.getProbabilityGain())); value.setProbabilityLoss(twoDecimalPoint(segmentData.getProbabilityLoss())); value.setProbabilityNormal(twoDecimalPoint(segmentData.getProbabilityNormal())); checkMeetsCopyNumberCriterion(result, criterionHandler, row, value); row.getValues().add(value); } } } private float twoDecimalPoint(float floatValue) { return Math.round(floatValue * DECIMAL_100) / DECIMAL_100; } private Map<SegmentData, GenomicDataResultRow> createCopyNumberResultRows( GenomicDataQueryResult result, Collection<ArrayData> arrayDatas, Collection<SegmentData> segmentDatas) { Map<Integer, Map<Integer, GenomicDataResultRow>> startEndPositionResultRowMap = new HashMap<Integer, Map<Integer, GenomicDataResultRow>>(); Map<SegmentData, GenomicDataResultRow> segmentDataToRowMap = new HashMap<SegmentData, GenomicDataResultRow>(); GenomeBuildVersionEnum genomeVersion = query.getCopyNumberPlatform().getGenomeVersion(); boolean isGenomeVersionMapped = dao.isGenomeVersionMapped(genomeVersion); for (SegmentData segmentData : segmentDatas) { if (arrayDatas.contains(segmentData.getArrayData())) { int startPosition = segmentData.getLocation().getStartPosition(); int endPosition = segmentData.getLocation().getEndPosition(); if (!startEndPositionResultRowMap.containsKey(startPosition)) { startEndPositionResultRowMap.put(startPosition, new HashMap<Integer, GenomicDataResultRow>()); } if (!startEndPositionResultRowMap.get(startPosition).containsKey(endPosition)) { GenomicDataResultRow row = new GenomicDataResultRow(); addSegmentDataToRow(segmentData, row, isGenomeVersionMapped, genomeVersion); startEndPositionResultRowMap.get(startPosition).put(endPosition, row); result.getRowCollection().add(row); } segmentDataToRowMap.put(segmentData, startEndPositionResultRowMap.get(startPosition).get(endPosition)); } } return segmentDataToRowMap; } private void addSegmentDataToRow(SegmentData segmentData, GenomicDataResultRow row, boolean isGenomeVersionMapped, GenomeBuildVersionEnum genomeVersion) { row.setSegmentDataResultValue(new SegmentDataResultValue()); row.getSegmentDataResultValue().setChromosomalLocation(segmentData.getLocation()); if (isGenomeVersionMapped) { row.getSegmentDataResultValue().getGenes().addAll( dao.findGenesByLocation(segmentData.getLocation().getChromosome(), segmentData.getLocation() .getStartPosition(), segmentData.getLocation().getEndPosition(), genomeVersion)); } } private void addToGeneExpressionResult(ArrayDataValues values, GenomicDataQueryResult result, Map<Long, GenomicDataResultRow> reporterIdToRowMap, ArrayData arrayData) { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); result.setHasCriterionSpecifiedValues(criterionHandler.hasCriterionSpecifiedReporterValues()); GenomicDataResultColumn column = result.addColumn(); //Take the 1st sample acquisition column.setSampleAcquisition(arrayData.getSample().getSampleAcquisitions().iterator().next()); for (AbstractReporter reporter : values.getReporters()) { if (query.isNeedsGenomicHighlighting()) { HibernateUtil.loadCollection(reporter.getGenes()); HibernateUtil.loadCollection(reporter.getSamplesHighVariance()); } GenomicDataResultRow row = reporterIdToRowMap.get(reporter.getId()); GenomicDataResultValue value = new GenomicDataResultValue(); value.setColumn(column); float floatValue = values.getFloatValue(arrayData, reporter, ArrayDataValueType.EXPRESSION_SIGNAL); value.setValue(twoDecimalPoint(floatValue)); if (query.isNeedsGenomicHighlighting()) { checkMeetsGeneExpressionCriterion(result, criterionHandler, reporter, row, value); checkHighVariance(result, arrayData, reporter, value); } row.getValues().add(value); } } private void checkMeetsGeneExpressionCriterion(GenomicDataQueryResult result, CompoundCriterionHandler criterionHandler, AbstractReporter reporter, GenomicDataResultRow row, GenomicDataResultValue value) { if (result.isHasCriterionSpecifiedValues()) { value.setCriteriaMatchType(criterionHandler. getGenomicValueMatchCriterionType(reporter.getGenes(), value.getValue())); row.setHasMatchingValues(row.isHasMatchingValues() || value.isMeetsCriterion()); } } private void checkMeetsCopyNumberCriterion(GenomicDataQueryResult result, CompoundCriterionHandler criterionHandler, GenomicDataResultRow row, GenomicDataResultValue value) { if (result.isHasCriterionSpecifiedValues()) { if (criterionHandler.hasCriterionSpecifiedSegmentValues() && !criterionHandler.hasCriterionSpecifiedSegmentCallsValues()) { value.setCriteriaMatchType(criterionHandler.getSegmentValueMatchCriterionType(value.getValue())); } else { value.setCriteriaMatchType(criterionHandler. getSegmentCallsValueMatchCriterionType(value.getCallsValue())); } row.setHasMatchingValues(row.isHasMatchingValues() || value.isMeetsCriterion()); } } private void checkHighVariance(GenomicDataQueryResult result, ArrayData arrayData, AbstractReporter reporter, GenomicDataResultValue value) { if (reporter.getSamplesHighVariance().contains(arrayData.getSample())) { value.setHighVariance(true); result.setHasHighVarianceValues(true); } } private Map<Long, GenomicDataResultRow> createReporterIdToRowMap(GenomicDataQueryResult result) { Map<Long, GenomicDataResultRow> rowMap = Maps.newHashMapWithExpectedSize(result.getRowCollection().size()); for (GenomicDataResultRow row : result.getRowCollection()) { rowMap.put(row.getReporter().getId(), row); } return rowMap; } private void createGeneExpressionResultRows(GenomicDataQueryResult result, ArrayDataValues values) { for (AbstractReporter reporter : values.getReporters()) { GenomicDataResultRow row = new GenomicDataResultRow(); row.setReporter(reporter); result.getRowCollection().add(row); } } private ArrayDataValues getDataValues() throws InvalidCriterionException { Collection<ArrayData> arrayDatas = getMatchingArrayDatas(); Collection<AbstractReporter> reporters = getMatchingReporters(arrayDatas); return getDataValues(arrayDatas, reporters); } private ArrayDataValues getDataValues(Collection<ArrayData> arrayDatas, Collection<AbstractReporter> reporters) { DataRetrievalRequest request = new DataRetrievalRequest(); request.addReporters(reporters); request.addArrayDatas(arrayDatas); request.addType(ArrayDataValueType.EXPRESSION_SIGNAL); if (QueryUtil.isFoldChangeQuery(query) && !query.isAllGenomicDataQuery()) { return arrayDataService.getFoldChangeValues(request, query); } else { return arrayDataService.getData(request); } } private Collection<ArrayData> getMatchingArrayDatas() throws InvalidCriterionException { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); Set<EntityTypeEnum> samplesOnly = new HashSet<EntityTypeEnum>(); samplesOnly.add(EntityTypeEnum.SAMPLE); Set<ResultRow> rows = criterionHandler.getMatches(dao, arrayDataService, query, samplesOnly); return getArrayDatas(rows); } private void addMatchesFromArrayDatas(Set<ArrayData> matchingArrayDatas, Collection<ArrayData> candidateArrayDatas) { Platform platform = query.getGeneExpressionPlatform(); ReporterTypeEnum reporterTypeToUse = query.getReporterType(); if (ResultTypeEnum.COPY_NUMBER == query.getResultType()) { platform = query.getCopyNumberPlatform(); reporterTypeToUse = ReporterTypeEnum.DNA_ANALYSIS_REPORTER; } for (ArrayData arrayData : candidateArrayDatas) { for (ReporterList reporterList : arrayData.getReporterLists()) { if (isMatchingArrayData(platform, reporterTypeToUse, arrayData, reporterList)) { matchingArrayDatas.add(arrayData); } } } } private boolean isMatchingArrayData(Platform platform, ReporterTypeEnum reporterType, ArrayData arrayData, ReporterList reporterList) { return reporterType == reporterList.getReporterType() && platform.equals(arrayData.getArray().getPlatform()); } private Set<ArrayData> getArrayDatas(Set<ResultRow> rows) { Set<ArrayData> arrayDatas = new HashSet<ArrayData>(); for (ResultRow row : rows) { if (row.getSampleAcquisition() != null) { Collection<ArrayData> candidateArrayDatas = row.getSampleAcquisition().getSample().getArrayDataCollection(); addMatchesFromArrayDatas(arrayDatas, candidateArrayDatas); } } return arrayDatas; } private Collection<AbstractReporter> getMatchingReporters(Collection<ArrayData> arrayDatas) { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); if (arrayDatas.isEmpty()) { return Collections.emptySet(); } else if (criterionHandler.hasReporterCriterion() && !query.isAllGenomicDataQuery()) { return criterionHandler.getReporterMatches(dao, query.getSubscription().getStudy(), query.getReporterType(), query.getGeneExpressionPlatform()); } else { return getAllReporters(arrayDatas); } } private Collection<AbstractReporter> getAllReporters(Collection<ArrayData> arrayDatas) { HashSet<AbstractReporter> reporters = new HashSet<AbstractReporter>(); for (ArrayData arrayData : arrayDatas) { arrayData = dao.get(arrayData.getId(), ArrayData.class); reporters.addAll(arrayData.getReporters()); } return reporters; } private Collection<SegmentData> getMatchingSegmentDatas(Collection<ArrayData> arrayDatas) throws InvalidCriterionException { CompoundCriterionHandler criterionHandler = CompoundCriterionHandler.create( query.getCompoundCriterion(), query.getResultType()); if (arrayDatas.isEmpty()) { return Collections.emptySet(); } else if (criterionHandler.hasSegmentDataCriterion() && !query.isAllGenomicDataQuery()) { return criterionHandler.getSegmentDataMatches(dao, query.getSubscription().getStudy(), query.getCopyNumberPlatform()); } else { return getAllSegmentDatas(arrayDatas); } } private Collection<SegmentData> getAllSegmentDatas(Collection<ArrayData> arrayDatas) { HashSet<SegmentData> segmentDatas = new HashSet<SegmentData>(); for (ArrayData arrayData : arrayDatas) { arrayData = dao.get(arrayData.getId(), ArrayData.class); segmentDatas.addAll(arrayData.getSegmentDatas()); } return segmentDatas; } }
NCIP/caintegrator
caintegrator-war/src/gov/nih/nci/caintegrator/application/query/GenomicQueryHandler.java
Java
bsd-3-clause
17,653
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new GCore\Foundation\Application( realpath(__DIR__.'/../') ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $app->singleton( Illuminate\Contracts\Http\Kernel::class, GCore\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, GCore\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, GCore\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
garuda-cms/cms
bootstrap/app.php
PHP
bsd-3-clause
1,603
# orm/dependency.py # Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Bridge the ``PropertyLoader`` (i.e. a ``relation()``) and the ``UOWTransaction`` together to allow processing of relation()-based dependencies at flush time. """ from sqlalchemy.orm import sync from sqlalchemy import sql, util, exceptions from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOONE, MANYTOMANY def create_dependency_processor(prop): types = { ONETOMANY : OneToManyDP, MANYTOONE: ManyToOneDP, MANYTOMANY : ManyToManyDP, } if prop.association is not None: return AssociationDP(prop) else: return types[prop.direction](prop) class DependencyProcessor(object): no_dependencies = False def __init__(self, prop): self.prop = prop self.cascade = prop.cascade self.mapper = prop.mapper self.parent = prop.parent self.secondary = prop.secondary self.direction = prop.direction self.is_backref = prop.is_backref self.post_update = prop.post_update self.foreign_keys = prop.foreign_keys self.passive_deletes = prop.passive_deletes self.passive_updates = prop.passive_updates self.enable_typechecks = prop.enable_typechecks self.key = prop.key if not self.prop.synchronize_pairs: raise exceptions.ArgumentError("Can't build a DependencyProcessor for relation %s. No target attributes to populate between parent and child are present" % self.prop) def _get_instrumented_attribute(self): """Return the ``InstrumentedAttribute`` handled by this ``DependencyProecssor``. """ return getattr(self.parent.class_, self.key) def hasparent(self, state): """return True if the given object instance has a parent, according to the ``InstrumentedAttribute`` handled by this ``DependencyProcessor``.""" # TODO: use correct API for this return self._get_instrumented_attribute().impl.hasparent(state) def register_dependencies(self, uowcommit): """Tell a ``UOWTransaction`` what mappers are dependent on which, with regards to the two or three mappers handled by this ``PropertyLoader``. Also register itself as a *processor* for one of its mappers, which will be executed after that mapper's objects have been saved or before they've been deleted. The process operation manages attributes and dependent operations upon the objects of one of the involved mappers. """ raise NotImplementedError() def whose_dependent_on_who(self, state1, state2): """Given an object pair assuming `obj2` is a child of `obj1`, return a tuple with the dependent object second, or None if there is no dependency. """ if state1 is state2: return None elif self.direction == ONETOMANY: return (state1, state2) else: return (state2, state1) def process_dependencies(self, task, deplist, uowcommit, delete = False): """This method is called during a flush operation to synchronize data between a parent and child object. It is called within the context of the various mappers and sometimes individual objects sorted according to their insert/update/delete order (topological sort). """ raise NotImplementedError() def preprocess_dependencies(self, task, deplist, uowcommit, delete = False): """Used before the flushes' topological sort to traverse through related objects and ensure every instance which will require save/update/delete is properly added to the UOWTransaction. """ raise NotImplementedError() def _verify_canload(self, state): if not self.enable_typechecks: return if state is not None and not self.mapper._canload(state): raise exceptions.FlushError("Attempting to flush an item of type %s on collection '%s', which is handled by mapper '%s' and does not load items of that type. Did you mean to use a polymorphic mapper for this relationship ? Set 'enable_typechecks=False' on the relation() to disable this exception. Mismatched typeloading may cause bi-directional relationships (backrefs) to not function properly." % (state.class_, self.prop, self.mapper)) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): """Called during a flush to synchronize primary key identifier values between a parent/child object, as well as to an associationrow in the case of many-to-many. """ raise NotImplementedError() def _conditional_post_update(self, state, uowcommit, related): """Execute a post_update call. For relations that contain the post_update flag, an additional ``UPDATE`` statement may be associated after an ``INSERT`` or before a ``DELETE`` in order to resolve circular row dependencies. This method will check for the post_update flag being set on a particular relationship, and given a target object and list of one or more related objects, and execute the ``UPDATE`` if the given related object list contains ``INSERT``s or ``DELETE``s. """ if state is not None and self.post_update: for x in related: if x is not None: uowcommit.register_object(state, postupdate=True, post_update_cols=[r for l, r in self.prop.synchronize_pairs]) break def _pks_changed(self, uowcommit, state): raise NotImplementedError() def __str__(self): return "%s(%s)" % (self.__class__.__name__, str(self.prop)) class OneToManyDP(DependencyProcessor): def register_dependencies(self, uowcommit): if self.post_update: if not self.is_backref: stub = MapperStub(self.parent, self.mapper, self.key) uowcommit.register_dependency(self.mapper, stub) uowcommit.register_dependency(self.parent, stub) uowcommit.register_processor(stub, self, self.parent) else: uowcommit.register_dependency(self.parent, self.mapper) uowcommit.register_processor(self.parent, self, self.parent) def process_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " process_dep isdelete " + repr(delete) + " direction " + repr(self.direction) if delete: # head object is being deleted, and we manage its list of child objects # the child objects have to have their foreign key to the parent set to NULL # this phase can be called safely for any cascade but is unnecessary if delete cascade # is on. if self.post_update or not self.passive_deletes=='all': for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if unchanged or deleted: for child in deleted: if child is not None and self.hasparent(child) is False: self._synchronize(state, child, None, True, uowcommit) self._conditional_post_update(child, uowcommit, [state]) if self.post_update or not self.cascade.delete: for child in unchanged: if child is not None: self._synchronize(state, child, None, True, uowcommit) self._conditional_post_update(child, uowcommit, [state]) else: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key, passive=True) if added or deleted: for child in added: self._synchronize(state, child, None, False, uowcommit) if child is not None: self._conditional_post_update(child, uowcommit, [state]) for child in deleted: if not self.cascade.delete_orphan and not self.hasparent(child): self._synchronize(state, child, None, True, uowcommit) if self._pks_changed(uowcommit, state): if unchanged: for child in unchanged: self._synchronize(state, child, None, False, uowcommit) def preprocess_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " preprocess_dep isdelete " + repr(delete) + " direction " + repr(self.direction) if delete: # head object is being deleted, and we manage its list of child objects # the child objects have to have their foreign key to the parent set to NULL if not self.post_update: should_null_fks = not self.cascade.delete and not self.passive_deletes=='all' for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if unchanged or deleted: for child in deleted: if child is not None and self.hasparent(child) is False: if self.cascade.delete_orphan: uowcommit.register_object(child, isdelete=True) else: uowcommit.register_object(child) if should_null_fks: for child in unchanged: if child is not None: uowcommit.register_object(child) else: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=True) if added or deleted: for child in added: if child is not None: uowcommit.register_object(child) for child in deleted: if not self.cascade.delete_orphan: uowcommit.register_object(child, isdelete=False) elif self.hasparent(child) is False: uowcommit.register_object(child, isdelete=True) for c, m in self.mapper.cascade_iterator('delete', child): uowcommit.register_object(c._state, isdelete=True) if not self.passive_updates and self._pks_changed(uowcommit, state): if not unchanged: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key, passive=False) if unchanged: for child in unchanged: uowcommit.register_object(child) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): source = state dest = child if dest is None or (not self.post_update and uowcommit.is_deleted(dest)): return self._verify_canload(child) if clearkeys: sync.clear(dest, self.mapper, self.prop.synchronize_pairs) else: sync.populate(source, self.parent, dest, self.mapper, self.prop.synchronize_pairs) def _pks_changed(self, uowcommit, state): return sync.source_changes(uowcommit, state, self.parent, self.prop.synchronize_pairs) class DetectKeySwitch(DependencyProcessor): """a special DP that works for many-to-one relations, fires off for child items who have changed their referenced key.""" no_dependencies = True def register_dependencies(self, uowcommit): uowcommit.register_processor(self.parent, self, self.mapper) def preprocess_dependencies(self, task, deplist, uowcommit, delete=False): # for non-passive updates, register in the preprocess stage # so that mapper save_obj() gets a hold of changes if not delete and not self.passive_updates: self._process_key_switches(deplist, uowcommit) def process_dependencies(self, task, deplist, uowcommit, delete=False): # for passive updates, register objects in the process stage # so that we avoid ManyToOneDP's registering the object without # the listonly flag in its own preprocess stage (results in UPDATE) # statements being emitted if not delete and self.passive_updates: self._process_key_switches(deplist, uowcommit) def _process_key_switches(self, deplist, uowcommit): switchers = util.Set([s for s in deplist if self._pks_changed(uowcommit, s)]) if switchers: # yes, we're doing a linear search right now through the UOW. only # takes effect when primary key values have actually changed. # a possible optimization might be to enhance the "hasparents" capability of # attributes to actually store all parent references, but this introduces # more complicated attribute accounting. for s in [elem for elem in uowcommit.session.identity_map.all_states() if issubclass(elem.class_, self.parent.class_) and self.key in elem.dict and elem.dict[self.key]._state in switchers ]: uowcommit.register_object(s, listonly=self.passive_updates) sync.populate(s.dict[self.key]._state, self.mapper, s, self.parent, self.prop.synchronize_pairs) #self.syncrules.execute(s.dict[self.key]._state, s, None, None, False) def _pks_changed(self, uowcommit, state): return sync.source_changes(uowcommit, state, self.mapper, self.prop.synchronize_pairs) class ManyToOneDP(DependencyProcessor): def __init__(self, prop): DependencyProcessor.__init__(self, prop) self.mapper._dependency_processors.append(DetectKeySwitch(prop)) def register_dependencies(self, uowcommit): if self.post_update: if not self.is_backref: stub = MapperStub(self.parent, self.mapper, self.key) uowcommit.register_dependency(self.mapper, stub) uowcommit.register_dependency(self.parent, stub) uowcommit.register_processor(stub, self, self.parent) else: uowcommit.register_dependency(self.mapper, self.parent) uowcommit.register_processor(self.mapper, self, self.parent) def process_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " process_dep isdelete " + repr(delete) + " direction " + repr(self.direction) if delete: if self.post_update and not self.cascade.delete_orphan and not self.passive_deletes=='all': # post_update means we have to update our row to not reference the child object # before we can DELETE the row for state in deplist: self._synchronize(state, None, None, True, uowcommit) (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if added or unchanged or deleted: self._conditional_post_update(state, uowcommit, deleted + unchanged + added) else: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=True) if added or deleted or unchanged: for child in added: self._synchronize(state, child, None, False, uowcommit) self._conditional_post_update(state, uowcommit, deleted + unchanged + added) def preprocess_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " PRE process_dep isdelete " + repr(delete) + " direction " + repr(self.direction) if self.post_update: return if delete: if self.cascade.delete or self.cascade.delete_orphan: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if self.cascade.delete_orphan: todelete = added + unchanged + deleted else: todelete = added + unchanged for child in todelete: if child is None: continue uowcommit.register_object(child, isdelete=True) for c, m in self.mapper.cascade_iterator('delete', child): uowcommit.register_object(c._state, isdelete=True) else: for state in deplist: uowcommit.register_object(state) if self.cascade.delete_orphan: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if deleted: for child in deleted: if self.hasparent(child) is False: uowcommit.register_object(child, isdelete=True) for c, m in self.mapper.cascade_iterator('delete', child): uowcommit.register_object(c._state, isdelete=True) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): if state is None or (not self.post_update and uowcommit.is_deleted(state)): return if clearkeys or child is None: sync.clear(state, self.parent, self.prop.synchronize_pairs) else: self._verify_canload(child) sync.populate(child, self.mapper, state, self.parent, self.prop.synchronize_pairs) class ManyToManyDP(DependencyProcessor): def register_dependencies(self, uowcommit): # many-to-many. create a "Stub" mapper to represent the # "middle table" in the relationship. This stub mapper doesnt save # or delete any objects, but just marks a dependency on the two # related mappers. its dependency processor then populates the # association table. stub = MapperStub(self.parent, self.mapper, self.key) uowcommit.register_dependency(self.parent, stub) uowcommit.register_dependency(self.mapper, stub) uowcommit.register_processor(stub, self, self.parent) def process_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " process_dep isdelete " + repr(delete) + " direction " + repr(self.direction) connection = uowcommit.transaction.connection(self.mapper) secondary_delete = [] secondary_insert = [] secondary_update = [] if self.prop._reverse_property: reverse_dep = getattr(self.prop._reverse_property, '_dependency_processor', None) else: reverse_dep = None if delete: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=self.passive_deletes) if deleted or unchanged: for child in deleted + unchanged: if child is None or (reverse_dep and (reverse_dep, "manytomany", child, state) in uowcommit.attributes): continue associationrow = {} self._synchronize(state, child, associationrow, False, uowcommit) secondary_delete.append(associationrow) uowcommit.attributes[(self, "manytomany", state, child)] = True else: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key) if added or deleted: for child in added: if child is None or (reverse_dep and (reverse_dep, "manytomany", child, state) in uowcommit.attributes): continue associationrow = {} self._synchronize(state, child, associationrow, False, uowcommit) uowcommit.attributes[(self, "manytomany", state, child)] = True secondary_insert.append(associationrow) for child in deleted: if child is None or (reverse_dep and (reverse_dep, "manytomany", child, state) in uowcommit.attributes): continue associationrow = {} self._synchronize(state, child, associationrow, False, uowcommit) uowcommit.attributes[(self, "manytomany", state, child)] = True secondary_delete.append(associationrow) if not self.passive_updates and unchanged and self._pks_changed(uowcommit, state): for child in unchanged: associationrow = {} sync.update(state, self.parent, associationrow, "old_", self.prop.synchronize_pairs) sync.update(child, self.mapper, associationrow, "old_", self.prop.secondary_synchronize_pairs) #self.syncrules.update(associationrow, state, child, "old_") secondary_update.append(associationrow) if secondary_delete: secondary_delete.sort() # TODO: precompile the delete/insert queries? statement = self.secondary.delete(sql.and_(*[c == sql.bindparam(c.key, type_=c.type) for c in self.secondary.c if c.key in associationrow])) result = connection.execute(statement, secondary_delete) if result.supports_sane_multi_rowcount() and result.rowcount != len(secondary_delete): raise exceptions.ConcurrentModificationError("Deleted rowcount %d does not match number of secondary table rows deleted from table '%s': %d" % (result.rowcount, self.secondary.description, len(secondary_delete))) if secondary_update: statement = self.secondary.update(sql.and_(*[c == sql.bindparam("old_" + c.key, type_=c.type) for c in self.secondary.c if c.key in associationrow])) result = connection.execute(statement, secondary_update) if result.supports_sane_multi_rowcount() and result.rowcount != len(secondary_update): raise exceptions.ConcurrentModificationError("Updated rowcount %d does not match number of secondary table rows updated from table '%s': %d" % (result.rowcount, self.secondary.description, len(secondary_update))) if secondary_insert: statement = self.secondary.insert() connection.execute(statement, secondary_insert) def preprocess_dependencies(self, task, deplist, uowcommit, delete = False): #print self.mapper.mapped_table.name + " " + self.key + " " + repr(len(deplist)) + " preprocess_dep isdelete " + repr(delete) + " direction " + repr(self.direction) if not delete: for state in deplist: (added, unchanged, deleted) = uowcommit.get_attribute_history(state, self.key,passive=True) if deleted: for child in deleted: if self.cascade.delete_orphan and self.hasparent(child) is False: uowcommit.register_object(child, isdelete=True) for c, m in self.mapper.cascade_iterator('delete', child): uowcommit.register_object(c._state, isdelete=True) def _synchronize(self, state, child, associationrow, clearkeys, uowcommit): if associationrow is None: return self._verify_canload(child) sync.populate_dict(state, self.parent, associationrow, self.prop.synchronize_pairs) sync.populate_dict(child, self.mapper, associationrow, self.prop.secondary_synchronize_pairs) def _pks_changed(self, uowcommit, state): return sync.source_changes(uowcommit, state, self.parent, self.prop.synchronize_pairs) class AssociationDP(OneToManyDP): def __init__(self, *args, **kwargs): super(AssociationDP, self).__init__(*args, **kwargs) self.cascade.delete = True self.cascade.delete_orphan = True class MapperStub(object): """Pose as a Mapper representing the association table in a many-to-many join, when performing a ``flush()``. The ``Task`` objects in the objectstore module treat it just like any other ``Mapper``, but in fact it only serves as a dependency placeholder for the many-to-many update task. """ __metaclass__ = util.ArgSingleton def __init__(self, parent, mapper, key): self.mapper = mapper self.base_mapper = self self.class_ = mapper.class_ self._inheriting_mappers = [] def polymorphic_iterator(self): return iter([self]) def _register_dependencies(self, uowcommit): pass def _save_obj(self, *args, **kwargs): pass def _delete_obj(self, *args, **kwargs): pass def primary_mapper(self): return self
santisiri/popego
envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.5-py2.5.egg/sqlalchemy/orm/dependency.py
Python
bsd-3-clause
26,274
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MoonSharp.Interpreter { /// <summary> /// Exception thrown when a dynamic expression is invalid /// </summary> public class DynamicExpressionException : ScriptRuntimeException { /// <summary> /// Initializes a new instance of the <see cref="DynamicExpressionException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public DynamicExpressionException(string format, params object[] args) : base("<dynamic>: " + format, args) { } /// <summary> /// Initializes a new instance of the <see cref="DynamicExpressionException"/> class. /// </summary> /// <param name="message">The message.</param> public DynamicExpressionException(string message) : base("<dynamic>: " + message) { } } }
RainsSoft/moonsharp
src/MoonSharp.Interpreter/Errors/DynamicExpressionException.cs
C#
bsd-3-clause
892
using System; using System.Linq; using System.Reactive.Linq; namespace Excercise2 { class Program { static void Main(string[] args) { IObservable<int> source = Observable.Never<int>(); IDisposable subscription = source.Subscribe( x => Console.WriteLine("OnNext: {0}", x), ex => Console.WriteLine("OnError: {0}", ex.Message), () => Console.WriteLine("OnCompleted") ); Console.WriteLine("Press ENTER to unsubscribe..."); Console.ReadLine(); subscription.Dispose(); } } }
airbreather/RandomFireplace
External/Rx/Rx.NET/Samples/HOL/CS/Excercise2/Step08/Program.cs
C#
bsd-3-clause
646
package net.dougqh.jak; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; public final class TypeDescriptor { private final int flags; private final String name; private final TypeVariable<?>[] typeVars; private final Type parentType; private final Type[] interfaceTypes; TypeDescriptor( final int flags, final String name, final TypeVariable<?>[] typeVars, final Type parentType, final Type[] interfaceTypes ) { this.flags = flags; this.name = name; this.typeVars = typeVars; this.parentType = parentType; this.interfaceTypes = interfaceTypes; } public final JavaVersion version() { return JavaVersion.getDefault(); } public final int flags() { return this.flags; } public final String name() { return this.name; } public final Type parentType() { return this.parentType; } public final Type[] interfaceTypes() { return this.interfaceTypes; } public final TypeVariable<?>[] typeVars() { return this.typeVars; } public final TypeDescriptor qualify( final String packageName ) { return new TypeDescriptor( this.flags, packageName + '.' + this.name, this.typeVars, this.parentType, this.interfaceTypes ); } public final TypeDescriptor innerType( final String className, final int additionalFlags ) { return new TypeDescriptor( this.flags | additionalFlags, className + '$' + this.name, this.typeVars, this.parentType, this.interfaceTypes ); } }
dougqh/JAK
net.dougqh.jak.core/src/net/dougqh/jak/TypeDescriptor.java
Java
bsd-3-clause
1,479
require 'spec_helper' describe "admin_company_details/new" do before(:each) do assign(:company_detail, stub_model(Admin::CompanyDetail, :company_name => "MyString", :company_certificate => "" ).as_new_record) end it "renders new company_detail form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => admin_company_details_path, :method => "post" do assert_select "input#company_detail_company_name", :name => "company_detail[company_name]" assert_select "input#company_detail_company_certificate", :name => "company_detail[company_certificate]" end end end
samtreweek/spree_accounting
spec/views/admin/company_details/new.html.erb_spec.rb
Ruby
bsd-3-clause
693
package org.basex.query.util.pkg; import java.io.*; /** * Package component. * * @author BaseX Team 2005-20, BSD License * @author Rositsa Shadura */ final class PkgComponent { /** Namespace URI. */ String uri; /** Component file. */ String file; /** * Extracts the component file name from the component path. * @return name */ String name() { return file.substring(file.lastIndexOf(File.separator) + 1); } }
dimitarp/basex
basex-core/src/main/java/org/basex/query/util/pkg/PkgComponent.java
Java
bsd-3-clause
445
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/bookmarks/browser/bookmark_model.h" #include <algorithm> #include <functional> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/i18n/string_compare.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/profiler/scoped_tracker.h" #include "base/strings/string_util.h" #include "components/bookmarks/browser/bookmark_expanded_state_tracker.h" #include "components/bookmarks/browser/bookmark_index.h" #include "components/bookmarks/browser/bookmark_match.h" #include "components/bookmarks/browser/bookmark_model_observer.h" #include "components/bookmarks/browser/bookmark_node_data.h" #include "components/bookmarks/browser/bookmark_storage.h" #include "components/bookmarks/browser/bookmark_undo_delegate.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "components/favicon_base/favicon_types.h" #include "grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/favicon_size.h" using base::Time; namespace bookmarks { namespace { // Helper to get a mutable bookmark node. BookmarkNode* AsMutable(const BookmarkNode* node) { return const_cast<BookmarkNode*>(node); } // Helper to get a mutable permanent bookmark node. BookmarkPermanentNode* AsMutable(const BookmarkPermanentNode* node) { return const_cast<BookmarkPermanentNode*>(node); } // Comparator used when sorting permanent nodes. Nodes that are initially // visible are sorted before nodes that are initially hidden. class VisibilityComparator : public std::binary_function<const BookmarkPermanentNode*, const BookmarkPermanentNode*, bool> { public: explicit VisibilityComparator(BookmarkClient* client) : client_(client) {} // Returns true if |n1| preceeds |n2|. bool operator()(const BookmarkPermanentNode* n1, const BookmarkPermanentNode* n2) { bool n1_visible = client_->IsPermanentNodeVisible(n1); bool n2_visible = client_->IsPermanentNodeVisible(n2); return n1_visible != n2_visible && n1_visible; } private: BookmarkClient* client_; }; // Comparator used when sorting bookmarks. Folders are sorted first, then // bookmarks. class SortComparator : public std::binary_function<const BookmarkNode*, const BookmarkNode*, bool> { public: explicit SortComparator(icu::Collator* collator) : collator_(collator) {} // Returns true if |n1| preceeds |n2|. bool operator()(const BookmarkNode* n1, const BookmarkNode* n2) { if (n1->type() == n2->type()) { // Types are the same, compare the names. if (!collator_) return n1->GetTitle() < n2->GetTitle(); return base::i18n::CompareString16WithCollator( *collator_, n1->GetTitle(), n2->GetTitle()) == UCOL_LESS; } // Types differ, sort such that folders come first. return n1->is_folder(); } private: icu::Collator* collator_; }; // Delegate that does nothing. class EmptyUndoDelegate : public BookmarkUndoDelegate { public: EmptyUndoDelegate() {} ~EmptyUndoDelegate() override {} private: // BookmarkUndoDelegate: void SetUndoProvider(BookmarkUndoProvider* provider) override {} void OnBookmarkNodeRemoved(BookmarkModel* model, const BookmarkNode* parent, int index, scoped_ptr<BookmarkNode> node) override {} DISALLOW_COPY_AND_ASSIGN(EmptyUndoDelegate); }; } // namespace // BookmarkModel -------------------------------------------------------------- BookmarkModel::BookmarkModel(BookmarkClient* client) : client_(client), loaded_(false), root_(GURL()), bookmark_bar_node_(NULL), other_node_(NULL), mobile_node_(NULL), next_node_id_(1), observers_( base::ObserverList<BookmarkModelObserver>::NOTIFY_EXISTING_ONLY), loaded_signal_(true, false), extensive_changes_(0), undo_delegate_(nullptr), empty_undo_delegate_(new EmptyUndoDelegate) { DCHECK(client_); } BookmarkModel::~BookmarkModel() { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkModelBeingDeleted(this)); if (store_.get()) { // The store maintains a reference back to us. We need to tell it we're gone // so that it doesn't try and invoke a method back on us again. store_->BookmarkModelDeleted(); } } void BookmarkModel::Shutdown() { if (loaded_) return; // See comment in HistoryService::ShutdownOnUIThread where this is invoked for // details. It is also called when the BookmarkModel is deleted. loaded_signal_.Signal(); } void BookmarkModel::Load( PrefService* pref_service, const std::string& accept_languages, const base::FilePath& profile_path, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner, const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner) { if (store_.get()) { // If the store is non-null, it means Load was already invoked. Load should // only be invoked once. NOTREACHED(); return; } expanded_state_tracker_.reset( new BookmarkExpandedStateTracker(this, pref_service)); // Load the bookmarks. BookmarkStorage notifies us when done. store_.reset(new BookmarkStorage(this, profile_path, io_task_runner.get())); store_->LoadBookmarks(CreateLoadDetails(accept_languages), ui_task_runner); } const BookmarkNode* BookmarkModel::GetParentForNewNodes() { std::vector<const BookmarkNode*> nodes = GetMostRecentlyModifiedUserFolders(this, 1); DCHECK(!nodes.empty()); // This list is always padded with default folders. return nodes[0]; } void BookmarkModel::AddObserver(BookmarkModelObserver* observer) { observers_.AddObserver(observer); } void BookmarkModel::RemoveObserver(BookmarkModelObserver* observer) { observers_.RemoveObserver(observer); } void BookmarkModel::BeginExtensiveChanges() { if (++extensive_changes_ == 1) { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, ExtensiveBookmarkChangesBeginning(this)); } } void BookmarkModel::EndExtensiveChanges() { --extensive_changes_; DCHECK_GE(extensive_changes_, 0); if (extensive_changes_ == 0) { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, ExtensiveBookmarkChangesEnded(this)); } } void BookmarkModel::BeginGroupedChanges() { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, GroupedBookmarkChangesBeginning(this)); } void BookmarkModel::EndGroupedChanges() { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, GroupedBookmarkChangesEnded(this)); } void BookmarkModel::Remove(const BookmarkNode* node) { DCHECK(loaded_); DCHECK(node); DCHECK(!is_root_node(node)); RemoveAndDeleteNode(AsMutable(node)); } void BookmarkModel::RemoveAllUserBookmarks() { std::set<GURL> removed_urls; struct RemoveNodeData { RemoveNodeData(const BookmarkNode* parent, int index, BookmarkNode* node) : parent(parent), index(index), node(node) {} const BookmarkNode* parent; int index; BookmarkNode* node; }; std::vector<RemoveNodeData> removed_node_data_list; FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillRemoveAllUserBookmarks(this)); BeginExtensiveChanges(); // Skip deleting permanent nodes. Permanent bookmark nodes are the root and // its immediate children. For removing all non permanent nodes just remove // all children of non-root permanent nodes. { base::AutoLock url_lock(url_lock_); for (int i = 0; i < root_.child_count(); ++i) { const BookmarkNode* permanent_node = root_.GetChild(i); if (!client_->CanBeEditedByUser(permanent_node)) continue; for (int j = permanent_node->child_count() - 1; j >= 0; --j) { BookmarkNode* child_node = AsMutable(permanent_node->GetChild(j)); RemoveNodeAndGetRemovedUrls(child_node, &removed_urls); removed_node_data_list.push_back( RemoveNodeData(permanent_node, j, child_node)); } } } EndExtensiveChanges(); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkAllUserNodesRemoved(this, removed_urls)); BeginGroupedChanges(); for (const auto& removed_node_data : removed_node_data_list) { undo_delegate()->OnBookmarkNodeRemoved( this, removed_node_data.parent, removed_node_data.index, scoped_ptr<BookmarkNode>(removed_node_data.node)); } EndGroupedChanges(); } void BookmarkModel::Move(const BookmarkNode* node, const BookmarkNode* new_parent, int index) { if (!loaded_ || !node || !IsValidIndex(new_parent, index, true) || is_root_node(new_parent) || is_permanent_node(node)) { NOTREACHED(); return; } if (new_parent->HasAncestor(node)) { // Can't make an ancestor of the node be a child of the node. NOTREACHED(); return; } const BookmarkNode* old_parent = node->parent(); int old_index = old_parent->GetIndexOf(node); if (old_parent == new_parent && (index == old_index || index == old_index + 1)) { // Node is already in this position, nothing to do. return; } SetDateFolderModified(new_parent, Time::Now()); if (old_parent == new_parent && index > old_index) index--; BookmarkNode* mutable_new_parent = AsMutable(new_parent); mutable_new_parent->Add(AsMutable(node), index); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeMoved(this, old_parent, old_index, new_parent, index)); } void BookmarkModel::Copy(const BookmarkNode* node, const BookmarkNode* new_parent, int index) { if (!loaded_ || !node || !IsValidIndex(new_parent, index, true) || is_root_node(new_parent) || is_permanent_node(node)) { NOTREACHED(); return; } if (new_parent->HasAncestor(node)) { // Can't make an ancestor of the node be a child of the node. NOTREACHED(); return; } SetDateFolderModified(new_parent, Time::Now()); BookmarkNodeData drag_data(node); // CloneBookmarkNode will use BookmarkModel methods to do the job, so we // don't need to send notifications here. CloneBookmarkNode(this, drag_data.elements, new_parent, index, true); if (store_.get()) store_->ScheduleSave(); } const gfx::Image& BookmarkModel::GetFavicon(const BookmarkNode* node) { DCHECK(node); if (node->favicon_state() == BookmarkNode::INVALID_FAVICON) { BookmarkNode* mutable_node = AsMutable(node); LoadFavicon(mutable_node, client_->PreferTouchIcon() ? favicon_base::TOUCH_ICON : favicon_base::FAVICON); } return node->favicon(); } favicon_base::IconType BookmarkModel::GetFaviconType(const BookmarkNode* node) { DCHECK(node); return node->favicon_type(); } void BookmarkModel::SetTitle(const BookmarkNode* node, const base::string16& title) { DCHECK(node); if (node->GetTitle() == title) return; if (is_permanent_node(node) && !client_->CanSetPermanentNodeTitle(node)) { NOTREACHED(); return; } FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillChangeBookmarkNode(this, node)); // The title index doesn't support changing the title, instead we remove then // add it back. index_->Remove(node); AsMutable(node)->SetTitle(title); index_->Add(node); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeChanged(this, node)); } void BookmarkModel::SetURL(const BookmarkNode* node, const GURL& url) { DCHECK(node && !node->is_folder()); if (node->url() == url) return; BookmarkNode* mutable_node = AsMutable(node); mutable_node->InvalidateFavicon(); CancelPendingFaviconLoadRequests(mutable_node); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillChangeBookmarkNode(this, node)); { base::AutoLock url_lock(url_lock_); RemoveNodeFromInternalMaps(mutable_node); mutable_node->set_url(url); AddNodeToInternalMaps(mutable_node); } if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeChanged(this, node)); } void BookmarkModel::SetNodeMetaInfo(const BookmarkNode* node, const std::string& key, const std::string& value) { std::string old_value; if (node->GetMetaInfo(key, &old_value) && old_value == value) return; FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillChangeBookmarkMetaInfo(this, node)); if (AsMutable(node)->SetMetaInfo(key, value) && store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkMetaInfoChanged(this, node)); } void BookmarkModel::SetNodeMetaInfoMap( const BookmarkNode* node, const BookmarkNode::MetaInfoMap& meta_info_map) { const BookmarkNode::MetaInfoMap* old_meta_info_map = node->GetMetaInfoMap(); if ((!old_meta_info_map && meta_info_map.empty()) || (old_meta_info_map && meta_info_map == *old_meta_info_map)) return; FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillChangeBookmarkMetaInfo(this, node)); AsMutable(node)->SetMetaInfoMap(meta_info_map); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkMetaInfoChanged(this, node)); } void BookmarkModel::DeleteNodeMetaInfo(const BookmarkNode* node, const std::string& key) { const BookmarkNode::MetaInfoMap* meta_info_map = node->GetMetaInfoMap(); if (!meta_info_map || meta_info_map->find(key) == meta_info_map->end()) return; FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillChangeBookmarkMetaInfo(this, node)); if (AsMutable(node)->DeleteMetaInfo(key) && store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkMetaInfoChanged(this, node)); } void BookmarkModel::AddNonClonedKey(const std::string& key) { non_cloned_keys_.insert(key); } void BookmarkModel::SetNodeSyncTransactionVersion( const BookmarkNode* node, int64 sync_transaction_version) { DCHECK(client_->CanSyncNode(node)); if (sync_transaction_version == node->sync_transaction_version()) return; AsMutable(node)->set_sync_transaction_version(sync_transaction_version); if (store_.get()) store_->ScheduleSave(); } void BookmarkModel::OnFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url) { std::set<const BookmarkNode*> to_update; for (const GURL& page_url : page_urls) { std::vector<const BookmarkNode*> nodes; GetNodesByURL(page_url, &nodes); to_update.insert(nodes.begin(), nodes.end()); } if (!icon_url.is_empty()) { // Log Histogram to determine how often |icon_url| is non empty in // practice. // TODO(pkotwicz): Do something more efficient if |icon_url| is non-empty // many times a day for each user. UMA_HISTOGRAM_BOOLEAN("Bookmarks.OnFaviconsChangedIconURL", true); base::AutoLock url_lock(url_lock_); for (const BookmarkNode* node : nodes_ordered_by_url_set_) { if (icon_url == node->icon_url()) to_update.insert(node); } } for (const BookmarkNode* node : to_update) { // Rerequest the favicon. BookmarkNode* mutable_node = AsMutable(node); mutable_node->InvalidateFavicon(); CancelPendingFaviconLoadRequests(mutable_node); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeFaviconChanged(this, node)); } } void BookmarkModel::SetDateAdded(const BookmarkNode* node, Time date_added) { DCHECK(node && !is_permanent_node(node)); if (node->date_added() == date_added) return; AsMutable(node)->set_date_added(date_added); // Syncing might result in dates newer than the folder's last modified date. if (date_added > node->parent()->date_folder_modified()) { // Will trigger store_->ScheduleSave(). SetDateFolderModified(node->parent(), date_added); } else if (store_.get()) { store_->ScheduleSave(); } } void BookmarkModel::GetNodesByURL(const GURL& url, std::vector<const BookmarkNode*>* nodes) { base::AutoLock url_lock(url_lock_); BookmarkNode tmp_node(url); NodesOrderedByURLSet::iterator i = nodes_ordered_by_url_set_.find(&tmp_node); while (i != nodes_ordered_by_url_set_.end() && (*i)->url() == url) { nodes->push_back(*i); ++i; } } const BookmarkNode* BookmarkModel::GetMostRecentlyAddedUserNodeForURL( const GURL& url) { std::vector<const BookmarkNode*> nodes; GetNodesByURL(url, &nodes); std::sort(nodes.begin(), nodes.end(), &MoreRecentlyAdded); // Look for the first node that the user can edit. for (size_t i = 0; i < nodes.size(); ++i) { if (client_->CanBeEditedByUser(nodes[i])) return nodes[i]; } return NULL; } bool BookmarkModel::HasBookmarks() { base::AutoLock url_lock(url_lock_); return !nodes_ordered_by_url_set_.empty(); } bool BookmarkModel::IsBookmarked(const GURL& url) { base::AutoLock url_lock(url_lock_); return IsBookmarkedNoLock(url); } void BookmarkModel::GetBookmarks( std::vector<BookmarkModel::URLAndTitle>* bookmarks) { base::AutoLock url_lock(url_lock_); const GURL* last_url = NULL; for (NodesOrderedByURLSet::iterator i = nodes_ordered_by_url_set_.begin(); i != nodes_ordered_by_url_set_.end(); ++i) { const GURL* url = &((*i)->url()); // Only add unique URLs. if (!last_url || *url != *last_url) { BookmarkModel::URLAndTitle bookmark; bookmark.url = *url; bookmark.title = (*i)->GetTitle(); bookmarks->push_back(bookmark); } last_url = url; } } void BookmarkModel::BlockTillLoaded() { loaded_signal_.Wait(); } const BookmarkNode* BookmarkModel::AddFolder(const BookmarkNode* parent, int index, const base::string16& title) { return AddFolderWithMetaInfo(parent, index, title, NULL); } const BookmarkNode* BookmarkModel::AddFolderWithMetaInfo( const BookmarkNode* parent, int index, const base::string16& title, const BookmarkNode::MetaInfoMap* meta_info) { if (!loaded_ || is_root_node(parent) || !IsValidIndex(parent, index, true)) { // Can't add to the root. NOTREACHED(); return NULL; } BookmarkNode* new_node = new BookmarkNode(generate_next_node_id(), GURL()); new_node->set_date_folder_modified(Time::Now()); // Folders shouldn't have line breaks in their titles. new_node->SetTitle(title); new_node->set_type(BookmarkNode::FOLDER); if (meta_info) new_node->SetMetaInfoMap(*meta_info); return AddNode(AsMutable(parent), index, new_node); } const BookmarkNode* BookmarkModel::AddURL(const BookmarkNode* parent, int index, const base::string16& title, const GURL& url) { return AddURLWithCreationTimeAndMetaInfo( parent, index, title, url, Time::Now(), NULL); } const BookmarkNode* BookmarkModel::AddURLWithCreationTimeAndMetaInfo( const BookmarkNode* parent, int index, const base::string16& title, const GURL& url, const Time& creation_time, const BookmarkNode::MetaInfoMap* meta_info) { if (!loaded_ || !url.is_valid() || is_root_node(parent) || !IsValidIndex(parent, index, true)) { NOTREACHED(); return NULL; } // Syncing may result in dates newer than the last modified date. if (creation_time > parent->date_folder_modified()) SetDateFolderModified(parent, creation_time); BookmarkNode* new_node = new BookmarkNode(generate_next_node_id(), url); new_node->SetTitle(title); new_node->set_date_added(creation_time); new_node->set_type(BookmarkNode::URL); if (meta_info) new_node->SetMetaInfoMap(*meta_info); return AddNode(AsMutable(parent), index, new_node); } void BookmarkModel::SortChildren(const BookmarkNode* parent) { DCHECK(client_->CanBeEditedByUser(parent)); if (!parent || !parent->is_folder() || is_root_node(parent) || parent->child_count() <= 1) { return; } FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillReorderBookmarkNode(this, parent)); UErrorCode error = U_ZERO_ERROR; scoped_ptr<icu::Collator> collator(icu::Collator::createInstance(error)); if (U_FAILURE(error)) collator.reset(NULL); BookmarkNode* mutable_parent = AsMutable(parent); std::sort(mutable_parent->children().begin(), mutable_parent->children().end(), SortComparator(collator.get())); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeChildrenReordered(this, parent)); } void BookmarkModel::ReorderChildren( const BookmarkNode* parent, const std::vector<const BookmarkNode*>& ordered_nodes) { DCHECK(client_->CanBeEditedByUser(parent)); // Ensure that all children in |parent| are in |ordered_nodes|. DCHECK_EQ(static_cast<size_t>(parent->child_count()), ordered_nodes.size()); for (size_t i = 0; i < ordered_nodes.size(); ++i) DCHECK_EQ(parent, ordered_nodes[i]->parent()); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillReorderBookmarkNode(this, parent)); AsMutable(parent)->SetChildren( *(reinterpret_cast<const std::vector<BookmarkNode*>*>(&ordered_nodes))); if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeChildrenReordered(this, parent)); } void BookmarkModel::SetDateFolderModified(const BookmarkNode* parent, const Time time) { DCHECK(parent); AsMutable(parent)->set_date_folder_modified(time); if (store_.get()) store_->ScheduleSave(); } void BookmarkModel::ResetDateFolderModified(const BookmarkNode* node) { SetDateFolderModified(node, Time()); } void BookmarkModel::GetBookmarksMatching(const base::string16& text, size_t max_count, std::vector<BookmarkMatch>* matches) { GetBookmarksMatching(text, max_count, query_parser::MatchingAlgorithm::DEFAULT, matches); } void BookmarkModel::GetBookmarksMatching( const base::string16& text, size_t max_count, query_parser::MatchingAlgorithm matching_algorithm, std::vector<BookmarkMatch>* matches) { if (!loaded_) return; index_->GetBookmarksMatching(text, max_count, matching_algorithm, matches); } void BookmarkModel::ClearStore() { store_.reset(); } void BookmarkModel::SetPermanentNodeVisible(BookmarkNode::Type type, bool value) { BookmarkPermanentNode* node = AsMutable(PermanentNode(type)); node->set_visible(value || client_->IsPermanentNodeVisible(node)); } const BookmarkPermanentNode* BookmarkModel::PermanentNode( BookmarkNode::Type type) { DCHECK(loaded_); switch (type) { case BookmarkNode::BOOKMARK_BAR: return bookmark_bar_node_; case BookmarkNode::OTHER_NODE: return other_node_; case BookmarkNode::MOBILE: return mobile_node_; default: NOTREACHED(); return NULL; } } void BookmarkModel::RestoreRemovedNode(const BookmarkNode* parent, int index, scoped_ptr<BookmarkNode> scoped_node) { BookmarkNode* node = scoped_node.release(); AddNode(AsMutable(parent), index, node); // We might be restoring a folder node that have already contained a set of // child nodes. We need to notify all of them. NotifyNodeAddedForAllDescendents(node); } void BookmarkModel::NotifyNodeAddedForAllDescendents(const BookmarkNode* node) { for (int i = 0; i < node->child_count(); ++i) { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeAdded(this, node, i)); NotifyNodeAddedForAllDescendents(node->GetChild(i)); } } bool BookmarkModel::IsBookmarkedNoLock(const GURL& url) { BookmarkNode tmp_node(url); return (nodes_ordered_by_url_set_.find(&tmp_node) != nodes_ordered_by_url_set_.end()); } void BookmarkModel::RemoveNode(BookmarkNode* node, std::set<GURL>* removed_urls) { if (!loaded_ || !node || is_permanent_node(node)) { NOTREACHED(); return; } url_lock_.AssertAcquired(); if (node->is_url()) { RemoveNodeFromInternalMaps(node); removed_urls->insert(node->url()); } CancelPendingFaviconLoadRequests(node); // Recurse through children. for (int i = node->child_count() - 1; i >= 0; --i) RemoveNode(node->GetChild(i), removed_urls); } void BookmarkModel::DoneLoading(scoped_ptr<BookmarkLoadDetails> details) { DCHECK(details); if (loaded_) { // We should only ever be loaded once. NOTREACHED(); return; } // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile1( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading1")); next_node_id_ = details->max_id(); if (details->computed_checksum() != details->stored_checksum() || details->ids_reassigned()) { // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile2( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading2")); // If bookmarks file changed externally, the IDs may have changed // externally. In that case, the decoder may have reassigned IDs to make // them unique. So when the file has changed externally, we should save the // bookmarks file to persist new IDs. if (store_.get()) store_->ScheduleSave(); } bookmark_bar_node_ = details->release_bb_node(); other_node_ = details->release_other_folder_node(); mobile_node_ = details->release_mobile_folder_node(); index_.reset(details->release_index()); // Get any extra nodes and take ownership of them at the |root_|. std::vector<BookmarkPermanentNode*> extra_nodes; details->release_extra_nodes(&extra_nodes); // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile3( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading3")); // WARNING: order is important here, various places assume the order is // constant (but can vary between embedders with the initial visibility // of permanent nodes). std::vector<BookmarkPermanentNode*> root_children; root_children.push_back(bookmark_bar_node_); root_children.push_back(other_node_); root_children.push_back(mobile_node_); for (size_t i = 0; i < extra_nodes.size(); ++i) root_children.push_back(extra_nodes[i]); // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile4( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading4")); std::stable_sort(root_children.begin(), root_children.end(), VisibilityComparator(client_)); for (size_t i = 0; i < root_children.size(); ++i) root_.Add(root_children[i], static_cast<int>(i)); root_.SetMetaInfoMap(details->model_meta_info_map()); root_.set_sync_transaction_version(details->model_sync_transaction_version()); // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile5( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading5")); { base::AutoLock url_lock(url_lock_); // Update nodes_ordered_by_url_set_ from the nodes. PopulateNodesByURL(&root_); } loaded_ = true; loaded_signal_.Signal(); // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467179 // is fixed. tracked_objects::ScopedTracker tracking_profile6( FROM_HERE_WITH_EXPLICIT_FUNCTION("467179 BookmarkModel::DoneLoading6")); // Notify our direct observers. FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkModelLoaded(this, details->ids_reassigned())); } void BookmarkModel::RemoveAndDeleteNode(BookmarkNode* delete_me) { scoped_ptr<BookmarkNode> node(delete_me); const BookmarkNode* parent = node->parent(); DCHECK(parent); int index = parent->GetIndexOf(node.get()); DCHECK_NE(-1, index); FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, OnWillRemoveBookmarks(this, parent, index, node.get())); std::set<GURL> removed_urls; { base::AutoLock url_lock(url_lock_); RemoveNodeAndGetRemovedUrls(node.get(), &removed_urls); } if (store_.get()) store_->ScheduleSave(); FOR_EACH_OBSERVER( BookmarkModelObserver, observers_, BookmarkNodeRemoved(this, parent, index, node.get(), removed_urls)); undo_delegate()->OnBookmarkNodeRemoved(this, parent, index, node.Pass()); } void BookmarkModel::RemoveNodeFromInternalMaps(BookmarkNode* node) { index_->Remove(node); // NOTE: this is called in such a way that url_lock_ is already held. As // such, this doesn't explicitly grab the lock. url_lock_.AssertAcquired(); NodesOrderedByURLSet::iterator i = nodes_ordered_by_url_set_.find(node); DCHECK(i != nodes_ordered_by_url_set_.end()); // i points to the first node with the URL, advance until we find the // node we're removing. while (*i != node) ++i; nodes_ordered_by_url_set_.erase(i); } void BookmarkModel::RemoveNodeAndGetRemovedUrls(BookmarkNode* node, std::set<GURL>* removed_urls) { // NOTE: this method should be always called with |url_lock_| held. // This method does not explicitly acquires a lock. url_lock_.AssertAcquired(); DCHECK(removed_urls); BookmarkNode* parent = node->parent(); DCHECK(parent); parent->Remove(node); RemoveNode(node, removed_urls); // RemoveNode adds an entry to removed_urls for each node of type URL. As we // allow duplicates we need to remove any entries that are still bookmarked. for (std::set<GURL>::iterator i = removed_urls->begin(); i != removed_urls->end();) { if (IsBookmarkedNoLock(*i)) { // When we erase the iterator pointing at the erasee is // invalidated, so using i++ here within the "erase" call is // important as it advances the iterator before passing the // old value through to erase. removed_urls->erase(i++); } else { ++i; } } } BookmarkNode* BookmarkModel::AddNode(BookmarkNode* parent, int index, BookmarkNode* node) { parent->Add(node, index); if (store_.get()) store_->ScheduleSave(); { base::AutoLock url_lock(url_lock_); AddNodeToInternalMaps(node); } FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeAdded(this, parent, index)); return node; } void BookmarkModel::AddNodeToInternalMaps(BookmarkNode* node) { url_lock_.AssertAcquired(); if (node->is_url()) { index_->Add(node); nodes_ordered_by_url_set_.insert(node); } for (int i = 0; i < node->child_count(); ++i) AddNodeToInternalMaps(node->GetChild(i)); } bool BookmarkModel::IsValidIndex(const BookmarkNode* parent, int index, bool allow_end) { return (parent && parent->is_folder() && (index >= 0 && (index < parent->child_count() || (allow_end && index == parent->child_count())))); } BookmarkPermanentNode* BookmarkModel::CreatePermanentNode( BookmarkNode::Type type) { DCHECK(type == BookmarkNode::BOOKMARK_BAR || type == BookmarkNode::OTHER_NODE || type == BookmarkNode::MOBILE); BookmarkPermanentNode* node = new BookmarkPermanentNode(generate_next_node_id()); node->set_type(type); node->set_visible(client_->IsPermanentNodeVisible(node)); int title_id; switch (type) { case BookmarkNode::BOOKMARK_BAR: title_id = IDS_BOOKMARK_BAR_FOLDER_NAME; break; case BookmarkNode::OTHER_NODE: title_id = IDS_BOOKMARK_BAR_OTHER_FOLDER_NAME; break; case BookmarkNode::MOBILE: title_id = IDS_BOOKMARK_BAR_MOBILE_FOLDER_NAME; break; default: NOTREACHED(); title_id = IDS_BOOKMARK_BAR_FOLDER_NAME; break; } node->SetTitle(l10n_util::GetStringUTF16(title_id)); return node; } void BookmarkModel::OnFaviconDataAvailable( BookmarkNode* node, favicon_base::IconType icon_type, const favicon_base::FaviconImageResult& image_result) { DCHECK(node); node->set_favicon_load_task_id(base::CancelableTaskTracker::kBadTaskId); node->set_favicon_state(BookmarkNode::LOADED_FAVICON); if (!image_result.image.IsEmpty()) { node->set_favicon_type(icon_type); node->set_favicon(image_result.image); node->set_icon_url(image_result.icon_url); FaviconLoaded(node); } else if (icon_type == favicon_base::TOUCH_ICON) { // Couldn't load the touch icon, fallback to the regular favicon. DCHECK(client_->PreferTouchIcon()); LoadFavicon(node, favicon_base::FAVICON); } } void BookmarkModel::LoadFavicon(BookmarkNode* node, favicon_base::IconType icon_type) { if (node->is_folder()) return; DCHECK(node->url().is_valid()); node->set_favicon_state(BookmarkNode::LOADING_FAVICON); base::CancelableTaskTracker::TaskId taskId = client_->GetFaviconImageForPageURL( node->url(), icon_type, base::Bind( &BookmarkModel::OnFaviconDataAvailable, base::Unretained(this), node, icon_type), &cancelable_task_tracker_); if (taskId != base::CancelableTaskTracker::kBadTaskId) node->set_favicon_load_task_id(taskId); } void BookmarkModel::FaviconLoaded(const BookmarkNode* node) { FOR_EACH_OBSERVER(BookmarkModelObserver, observers_, BookmarkNodeFaviconChanged(this, node)); } void BookmarkModel::CancelPendingFaviconLoadRequests(BookmarkNode* node) { if (node->favicon_load_task_id() != base::CancelableTaskTracker::kBadTaskId) { cancelable_task_tracker_.TryCancel(node->favicon_load_task_id()); node->set_favicon_load_task_id(base::CancelableTaskTracker::kBadTaskId); } } void BookmarkModel::PopulateNodesByURL(BookmarkNode* node) { // NOTE: this is called with url_lock_ already held. As such, this doesn't // explicitly grab the lock. if (node->is_url()) nodes_ordered_by_url_set_.insert(node); for (int i = 0; i < node->child_count(); ++i) PopulateNodesByURL(node->GetChild(i)); } int64 BookmarkModel::generate_next_node_id() { return next_node_id_++; } scoped_ptr<BookmarkLoadDetails> BookmarkModel::CreateLoadDetails( const std::string& accept_languages) { BookmarkPermanentNode* bb_node = CreatePermanentNode(BookmarkNode::BOOKMARK_BAR); BookmarkPermanentNode* other_node = CreatePermanentNode(BookmarkNode::OTHER_NODE); BookmarkPermanentNode* mobile_node = CreatePermanentNode(BookmarkNode::MOBILE); return scoped_ptr<BookmarkLoadDetails>(new BookmarkLoadDetails( bb_node, other_node, mobile_node, client_->GetLoadExtraNodesCallback(), new BookmarkIndex(client_, accept_languages), next_node_id_)); } void BookmarkModel::SetUndoDelegate(BookmarkUndoDelegate* undo_delegate) { undo_delegate_ = undo_delegate; if (undo_delegate_) undo_delegate_->SetUndoProvider(this); } BookmarkUndoDelegate* BookmarkModel::undo_delegate() const { return undo_delegate_ ? undo_delegate_ : empty_undo_delegate_.get(); } } // namespace bookmarks
Workday/OpenFrame
components/bookmarks/browser/bookmark_model.cc
C++
bsd-3-clause
36,980
<?php /** * ModernWeb * * 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://www.modernweb.pl/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 kontakt@modernweb.pl so we can send you a copy immediately. * * @category Modern * @package Modern_Gdata * @package Maps * @author Rafał Gałka <rafal@modernweb.pl> * @copyright Copyright (c) 2007-2012 ModernWeb (http://www.modernweb.pl) * @license http://www.modernweb.pl/license/new-bsd New BSD License */ /** * @category Modern * @package Modern_Gdata * @package Maps * @author Rafał Gałka <rafal@modernweb.pl> * @copyright Copyright (c) 2007-2012 ModernWeb (http://www.modernweb.pl) */ class Modern_Gdata_Maps_LatLng { protected $_lat = 0; protected $_lng = 0; /** * @param float $lat * @param float $lng * @param boolean $noWrap * * @todo If the noWrap flag is true, then the numbers will be used * as passed, otherwise latitude will be clamped to lie between * -90 degrees and +90 degrees, and longitude will be wrapped * to lie between -180 degrees and +180 degrees. */ public function __construct($lat, $lng, $noWrap = false) { if ($noWrap) { $this->_lat = (float) $lat; $this->_lng = (float) $lng; } else { $this->_lat = (float) $lat; $this->_lng = (float) $lng; } } public function lat() { return $this->_lat; } public function lng() { return $this->_lng; } public function toUrlValue($precision = 6) { return sprintf("%.{$precision}f,%.{$precision}f", $this->_lat, $this->_lng); } public function toStrign($precision = null) { if (null === $precision) { $precision = 14; } return sprintf("(%s)", $this->toUrlValue($precision)); } public function __toString() { return $this->toStrign(); } }
Hagith/zf1-lib
library/Modern/Gdata/Maps/LatLng.php
PHP
bsd-3-clause
2,238
namespace NanoRpc { /// <summary> /// </summary> /// TODO: Should be renamed to IRpcObject public interface IRpcService { /// <summary> /// Parses the RPC call message, executes the method and returns the RPC message with result. /// </summary> /// <param name="rpcCall"> /// The RPC call message. /// </param> /// <returns> /// The RPC result message. /// </returns> RpcResult CallMethod(RpcCall rpcCall); } }
apkbox/nano-rpc
NanoRpc.Net/src/IRpcService.cs
C#
bsd-3-clause
519
import numpy as np import pandas as pd import gen_fns import math import re import csv import correlation_matrix as co # # reformat_raw_data # # Takes compiled data on historical proliferation contributers from xlsx # spreadsheet (final_hist_data.xlsx) and reformats. xlsx file has a single # row for each country with separate data for a 'pursue date' and an 'acquire # 'date'. These are split out so that each state has a unique row entry for # every year for which we have data. Nuclear Weapon states have an entry when # they began pursuing and another when they acquired. States that explored or # pursued have an entry for that year as well as an entry for 2015. States # that never pursued have only an entry for 2015. # A 'Status' column in output codes the action of the state in the given year # (Never/Explore/Pursue/Acquire). Coding details available inline. # # Input # File: tab-separated-file dropped straight from xlsx spreadsheet # (n_header): number of extra header lines to be skipped from spreadsheet # (outfile): name of desired output file, written to directory you're # running python from # Output # States: Array of states for each entry of the file database # Data: structured array of historical data for each state at time # indicated by 'Date' # def reformat_raw_data(file, n_header=1, outfile=None): from gen_fns import get_data from numpy.lib.recfunctions import append_fields countries, columns, raw_data = get_data(file, n_header, named_struct=True) pursue_names = [] acquire_names = [] clean_names = [] status = np.full(len(countries), 0) raw_data = append_fields(raw_data, 'Status', status) cols = raw_data.dtype.names order = range(0, len(cols) - 1) order.insert(2,len(cols) - 1) data = raw_data[[cols[i] for i in order]] cols = data.dtype.names for c in range(len(cols)): if ('Pursuit_' in cols[c]): pursue_names.append(cols[c]) new_str = re.sub('Pursuit_', '', cols[c]) clean_names.append(new_str) elif ('Acquire_' in cols[c]): acquire_names.append(cols[c]) else: pursue_names.append(cols[c]) acquire_names.append(cols[c]) clean_names.append(cols[c]) # all countries, data split into pursue-relevant or acquire-relevant pursue_array = data[pursue_names] acquire_array = data[acquire_names] no_acquire_mask = np.isnan(acquire_array['Acquire_Date']) conven_mask = np.isnan(pursue_array['Pursuit_Date']) explore_mask = (pursue_array['Pursuit_Date'] < 0) pursue_only_mask = (np.isnan(acquire_array['Acquire_Date'])) & (~(np.isnan(pursue_array['Pursuit_Date'])) & (pursue_array['Pursuit_Date'] > 0)) # states that pursued (_init_) and successfully acquired acquire_states = countries[~no_acquire_mask] acquire_final_array = acquire_array[~no_acquire_mask] acquire_init_array = pursue_array[~no_acquire_mask] # states that never pursued and have only conventional weapons conven_array = pursue_array[conven_mask] conven_states = countries[conven_mask] # states that explored NW but ultimately did not pursue explore_array = pursue_array[explore_mask] explore_present_array = acquire_array[explore_mask] explore_states = countries[explore_mask] # states that pursued but did not succeeed in acquiring pursue_only_array = pursue_array[pursue_only_mask] pursue_present_array = acquire_array[pursue_only_mask] pursue_states = countries[pursue_only_mask] # Status # -1 present data for a state that unsucessfully pursued # 0 present data for never-pursued (has only 'conventional weapons') # 1 historical data for explored # 2 historical data for pursued # 3 historical data for acquired acquire_init_array['Status'] = 2 acquire_final_array['Status'] = 3 conven_array['Status'] = 0 pursue_only_array['Status'] = 2 pursue_present_array['Status'] = -1 explore_array['Status'] = 1 explore_present_array['Status'] = 0 conven_array['Pursuit_Date'] = 2015 explore_array['Pursuit_Date'] = abs(explore_array['Pursuit_Date']) explore_present_array['Acquire_Date'] = 2015 pursue_present_array['Acquire_Date'] = 2015 acquire_final_array.dtype.names = clean_names acquire_final_array.mask.dtype.names = clean_names acquire_init_array.dtype.names = clean_names acquire_init_array.mask.dtype.names = clean_names conven_array.dtype.names = clean_names conven_array.mask.dtype.names = clean_names pursue_only_array.dtype.names = clean_names pursue_only_array.mask.dtype.names = clean_names pursue_present_array.dtype.names = clean_names pursue_present_array.mask.dtype.names = clean_names explore_array.dtype.names = clean_names explore_array.mask.dtype.names = clean_names explore_present_array.dtype.names = clean_names explore_present_array.mask.dtype.names = clean_names final_states = np.hstack((conven_states, explore_states, explore_states, pursue_states, acquire_states, acquire_states, pursue_states)) final_data = np.hstack((conven_array, explore_present_array, explore_array, pursue_only_array, acquire_init_array, acquire_final_array, pursue_present_array)) header ='Country' + '\t' + ('\t'.join(map(str,final_data.dtype.names))) if (outfile != None): with open(outfile, 'wb') as f: writer = csv.writer(f) writer.writerow([header]) i = 0 for comp in final_data.compressed(): cur_line = final_states[i] for c in range(len(comp)): val = comp[c] if (c <= 1): val = int(val) cur_line = cur_line + '\t' + str(val) writer.writerow([cur_line]) i+=1 return final_states,final_data # # calc_weights # # Given a tab separated input file with the following columns, use partial # component analysis to determine the relative importance of each factor # In: # filename: tab-separated input file with factor scores for each state # columns: Country, Date, Status, Factor1, Factor2, .... # mn_status: min value of nuclear weapons status for state to be considered # in analysis (-1 = gave up weapons program, 0 = never pursued, # 1 = explored, 2 = pursued, 3 = acquired) # mx_status: max value of weapons status to be considered # correl_min: weights below this number are rescaled to zero as they are # not significant (including negative correlations) # # Out: # weights: relative importance of each factor from the input file. Weights # sum to 1 and cannot be negative. # def calc_weights(filename, mn_status=0, mx_status=2, correl_min = 1e-6): data_file = open(filename, 'r') full_matrix = np.loadtxt(data_file, skiprows=1,usecols=(2,3,4,5,6,7,8,9,10)) relevant_mask = ((full_matrix[:,0] >= mn_status) & (full_matrix[:,0] <= mx_status)) matrix = full_matrix[relevant_mask] cor = co.Cor_matrix(matrix) factor_vals = np.array(cor[0,1:])[0] factor_vals[factor_vals < correl_min] = 0 f_tot = factor_vals.sum() weights = factor_vals/f_tot # normalize weights to sum to one return weights # # calc_pursuit # # Calculates 0-10 scale pursuit scores for historical data using factor # weighting from Baptiste's correlation analysis. # # In: # raw_data: np.array of value for each factor on a 0-10 scale # weights: np.array of factor weights (from correlation analysis) # Out: # final_vals: List of pursuit equation values in same order as input data # (order: Auth, Mil_Iso, Reactor, En_Repr, Sci_Net, Mil_Sp, # Conflict, U_Res) # def calc_pursuit(raw_data, weights): final_vals = [] weighted_factors = weights*raw_data for i in range(raw_data.shape[0]): val = weighted_factors[i].sum() final_vals.append(round(val,4)) return final_vals # Map of nuclear weapon states and their acquire date def get_nws(): nws = {} nws["China"] = 1964 nws["France"] = 1960 nws["India"] = 1974 # nws["India"] = 1988 # This was the Way coding but not first detonation nws["Israel"] = 1969 nws["N-Korea"] = 2006 nws["Pakist"] = 1987 nws["S-Afric"] = 1979 nws["UK"] = 1952 nws["US"] = 1945 nws["USSR"] = 1949 return nws # # time_to_acquire # # Returns a dictionary of countries that pursued and how long it took them to # succeed. Countries that never acquired are listed with a negative number that # indicates the time elapsed from beginning of pursuit to 2015 # # In: (none) # Out: # t2acq: Dictionary of how long it took state to acquire nuclear weapon # def time_to_acquire(): t2acq = {} t2acq["Argent"] = -37 t2acq["Austral"] = -54 t2acq["Brazil"] = -37 t2acq["China"] = 9 t2acq["Egypt"] = -50 t2acq["France"] = 6 t2acq["India"] = 10 t2acq["Iran"] = -30 t2acq["Iraq"] = -32 t2acq["Israel"] = 9 t2acq["Libya"] = -45 t2acq["N-Korea"] = 26 t2acq["S-Korea"] = -45 t2acq["Pakist"] = 15 t2acq["S-Afric"] = 5 t2acq["Syria"] = -15 t2acq["UK"] = 5 t2acq["US"] = 3 t2acq["USSR"] = 4 return t2acq # States that pursued and their pursuit date # (from google doc: Main Prolif Spreadsheet, Dec-5-2016) def get_pursue(): pursues = {} pursues["Argent"] = 1978 pursues["Austral"] = 1961 pursues["Brazil"] = 1978 pursues["China"] = 1955 pursues["Egypt"] = 1965 pursues["France"] = 1954 pursues["India"] = 1964 pursues["Iran"] = 1985 pursues["Iraq"] = 1983 pursues["Israel"] = 1960 pursues["Libya"] = 1970 pursues["N-Korea"] = 1980 pursues["S-Korea"] = 1970 pursues["Pakist"] = 1972 pursues["S-Afric"] = 1974 pursues["Syria"] = 2000 pursues["UK"] = 1947 pursues["US"] = 1939 pursues["USSR"] = 1945 return pursues # From a matched pair of numpy arrays containing countries and their pursuit # scores, make a new array of the pursuit scores for countries that succeeded def get_prolif_pe(countries, pes): prolif_pes = [] prolif_st = [] proliferants = get_prolif() for i in range(len(countries)): curr_state = countries[i] if curr_state in proliferants: prolif_pes.append(pes[i]) prolif_st.append(curr_state) return(prolif_st, prolif_pes) # From a matched pair of numpy arrays containing countries and their pursuit # scores, make a new array of the scores for the subset of countries that # actually chose to pursue and/or succeeded def get_pes(all_countries, pes, status): pursue_pes = [] pursue_st = [] if (status == "Pursue"): states = get_pursue() elif (status == "Prolif"): states = get_nws() else: return "DO YOU WANT PURSUIT OR PROLIFERANTS?" for i in range(len(all_countries)): curr_state = all_countries[i] if curr_state in states: pursue_pes.append(pes[i]) pursue_st.append(curr_state) return(pursue_st, pursue_pes) # # raw_to_factor_scores # # Read in the historical data for all states, output a tsv with the data # converted into 0-10 scores for each of the 8 factors # # In: # infile: tsv for historical data in clean format # (from reformat_raw_data) # (n_head): how many header lines to skip # (outfile): name of desired tab separated file for output, with row and # column headers # Out: (all structures preserve order across columns) # countries: array of state names that pairs with output data # dates: array of date for the row of factor scores # status: array with status for the row (never/explore/pursue/acquire) # (status coding described in README.md) # columns: list of column names for data # all_scores: np.array of 0-10 score for each factor # def raw_to_factor_scores(infile, n_head=1, outfile=None): from gen_fns import get_data countries, col_names, raw_data = get_data(infile, n_header = n_head, named_struct=True) factors = { "Reactor": [react2score, [raw_data['Reactors'], raw_data['Research_Reactors']]], "Mil_Iso": [alliance2iso_score, [raw_data['NonProlif_Alliance'], raw_data['Prolif_Alliance']]], "En_Repr": [enrich2score, raw_data['Enrichment']], "U_Res": [ures2score, raw_data['UReserves']], "Sci_Net": [network2score, raw_data['Scientific_Network']], # "Conflict": [upsala2conflict_score, [raw_data['Unique_Conflicts'], # raw_data['Conflict_Intensity']]], "Conflict": [relations2conflict_score, [raw_data['Weapon_Status_1'], raw_data['Conflict_Relation_1'], raw_data['Weapon_Status_2'], raw_data['Conflict_Relation_2'], raw_data['Weapon_Status_3'], raw_data['Conflict_Relation_3'], raw_data['Status']]], "Auth": [polity2auth_score, raw_data['Polity_Index']], "Mil_Sp": [mil_sp2score, raw_data['Military_GDP']] } score_columns = [] i = 0 for key in factors: score_columns.append(key) fn, inputs = factors[key] scores = fn(inputs) if (i == 0): all_scores = scores else: all_scores = np.column_stack((all_scores, scores)) i+=1 header ='Country' + '\t' + 'Date'+ '\t' + 'Status' + '\t'+ ( '\t'.join(map(str,score_columns))) if (outfile != None): with open(outfile, 'wb') as f: writer = csv.writer(f) writer.writerow([header]) for row in range(len(all_scores)): cur_line = countries[row]+ '\t'+ ( str(int(raw_data['Date'][row]))+ '\t') + ( str(raw_data['Status'][row]) + '\t') + ( ('\t'.join(map(str, all_scores[row])))) writer.writerow([cur_line]) return countries, raw_data['Date'], raw_data['Status'], score_columns, all_scores # Bilateral agreements converted to score # If only with non-nuclear states (npt), score is lower # If with nuclear states (nuclear umbrella), then only count these # # NOT CURRENTLY USED # def bilateral2score(npt, ws=None): stepA = 2 stepB = 4 stepC = 7 all_scores = np.ndarray(npt.size) for i in range(npt.size): score = -1 # if all agreements are with other non-nuclear states if (ws is None) or (ws[i] == 0) or (math.isnan(ws[i])): if (math.isnan(npt[i])): score = np.nan elif (npt[i] <= stepA): score = 1 elif (npt[i] <= stepB): score = 2 else: score = 3 else: if (ws[i] <= stepA): score = 6 elif (ws[i] <= stepB): score = 7 elif (ws[i] <= stepC): score = 8 else: score = 10 all_scores[i] = score return all_scores # # Global Peace Index # (includes both domestic and external stability) # Institute for Economics & Peace Global Peace Index # http://economicsandpeace.org/wp-content/uploads/2015/06/Global-Peace-Index-Report-2015_0.pdf # # NOT USED BECAUSE NO HISTORICAL DATA # def gpi2conflict_score(gpi_array): stepA = 1.5 stepB = 2 stepC = 2.5 stepD = 3.5 all_scores = np.ndarray(gpi_array.size) for i in range(gpi_array.size): gpi_val = gpi_array[i] score = -1 if (math.isnan(gpi_val)): score = np.nan elif (gpi_val < stepA): score = 2 elif (gpi_val < stepB): score = 4 elif (gpi_val < stepC): score = 6 elif (gpi_val < stepD): score = 8 else: score = 10 all_scores[i] = score return all_scores # # Fraction of GDP spent on military # World Bank http://data.worldbank.org/indicator/MS.MIL.XPND.GD.ZS # def mil_sp2score(mil_gdp): stepA = 1 stepB = 2 stepC = 3 stepD = 5 all_scores = np.ndarray(mil_gdp.size) for i in range(mil_gdp.size): score = -1 if (math.isnan(mil_gdp[i])): score = np.nan elif (mil_gdp[i] < stepA): score = 1 elif (mil_gdp[i] < stepB): score = 2 elif (mil_gdp[i] < stepC): score = 4 elif (mil_gdp[i] < stepD): score = 7 else: score = 10 all_scores[i] = score return all_scores # Convert number of reactors to a score # 'Reactors' is commercial, 'Research_Reactors' are in a separate column, # with negative number indicating they have only planned reactors. # Built reactors take precedence over planned # # REFERENCE??? # ** Correlation analysis demonstrated that reactors are protective against # proliferation (hypothesis that countries stable enough to run reactors # have other mitigating factors that reduce proliferation risk) # Therefore reactor score has been inverted so that the more reactors a country # has the lower their pursuit score. def react2score(all_reactors): step0 = 0.0 stepA = -4.0 stepB = -1.0 stepC = 3.0 stepD = 7.0 n_react = all_reactors[0] n_research = all_reactors[1] all_scores = np.ndarray(n_react.size) for i in range(n_react.size): score = 0 n_tot = 0 # if there are both planned (negative) and built reactors (positive) # between research and commercial, use the 'built' number if ((n_react[i] * n_research[i]) < 0): n_tot = max(n_research[i], n_react[i]) else: n_tot = n_research[i] + n_react[i] if (math.isnan(n_tot)): score = np.nan elif (n_tot == step0): score = 0 elif (n_tot <= stepA): score = 2 elif (n_tot <= stepB): score = 1 elif (n_tot <= stepC): score = 4 elif (n_tot <= stepD): score = 7 else: score = 10 all_scores[i] = 10 - abs(score) return all_scores # # upsala2conflict_score # # Uses number of unique conflicts * conflict intensity to determine total # conflict score. We have re-coded Iraq, Afghanistan, and Mali wars (2000s) # as coalition-wars, such that for individual countries the number of deaths # is the lower intensity coded as 1. # Max # of unique conflicts in historical data is 3 # Conflict = 5 for neutral relationships, increases with additional conflict. # # From Upsala # def upsala2conflict_score(all_conflict): neutral = 5 # for neutral relationships, score is 5 stepC = 4 n_conflicts = all_conflict[0] intensity = all_conflict[1] all_scores = np.ndarray(n_conflicts.size) for i in range(n_conflicts.size): score = 0 # If intensity is (-) then conflict is a coalition, downgrade intensity # to -1. If n_conflict is (-) then an additional non-armed (tense) # conflict has been added to the data (eg Korean Armistace), (but still # may be coded as zero intensity) if ((intensity[i] < 0) or (n_conflicts[i] < 0)): n_tot = abs(n_conflicts[i]) else: n_tot = n_conflicts[i] * intensity[i] if (math.isnan(n_tot)): score = np.nan elif (n_tot <= stepC): score = neutral + n_tot else: score = 10 all_scores[i] = score return all_scores # # relations2conflict_score # # Averages individual conflict scores with up to 3 pairs of countries that # have significant relationships (as determined by Hoffman and Buys). # Each country has a weapons status (0,2,3) and a defined # relationship with partner country (+1 = allies, 0 = neutral, -1 = enemies). # Scores are determined based on those 3 values using the score_matrix # dictionary in lookup_conflict_val (these dictionary values are also used # in mbmore::StateInst.cc (archetype for use with Cyclus). # # In: np.array of arrays - for each target country, weapons status and # relationship of each pair country, # and weapon status of target country # Out: np.array - for each target country, final conflict score (0-10 scale) # def relations2conflict_score(all_conflict): weapon_stat1 = all_conflict[0] conflict1= all_conflict[1] weapon_stat2 = all_conflict[2] conflict2= all_conflict[3] weapon_stat3 = all_conflict[4] conflict3= all_conflict[5] host_status = all_conflict[6] all_scores = np.ndarray(weapon_stat1.size) for i in range(all_scores.size): n_scores = 0 score = 0 if (np.isfinite(weapon_stat1[i])): n_scores+=1 score+= lookup_conflict_val(host_status[i], weapon_stat1[i], conflict1[i]) if (np.isfinite(weapon_stat2[i])): n_scores+=1 score+= lookup_conflict_val(host_status[i], weapon_stat2[i], conflict2[i]) if (np.isfinite(weapon_stat3[i])): n_scores+=1 score+= lookup_conflict_val(host_status[i], weapon_stat3[i], conflict3[i]) if (math.isnan(score) or (n_scores == 0)): avg_score = np.nan else: avg_score = score/n_scores all_scores[i] = avg_score return all_scores # # lookup_conflict_val # # Given the relationship between 2 countries (enemy, ally, neutral), and their # respective weapon status, look up the 0-10 score for that conflict level # 0-10 scores based on discussion with Andy Kydd and documented here: # https://docs.google.com/document/d/1c9YeFngXm3RCbuyFCEDWJjUK9Ovn072SpmlZU6j1qhg/edit?usp=sharing # Same defns are used in mbmore::StateInst.cc (archetype for use with Cyclus). # Historical countries with scores of -1 (gave up a weapons program) or # +1 (explored but did not pursue) have been reassigned a value of 0 (never # pursued). These gradations could be refined in future work. # # In: statusA - weapons status of country A (0, 2, 3) # statusB - weapons status of country B (0, 2, 3) # relation - relationship between country A and B (-1, 0, +1) # # Out: Conflict factor score for that pair (0-10) # def lookup_conflict_val(statusA, statusB, relation): score_matrix = { "ally_0_0": 2, "neut_0_0": 2, "enemy_0_0": 6, "ally_0_2": 3, "neut_0_2": 4, "enemy_0_2": 8, "ally_0_3": 1, "neut_0_3": 4, "enemy_0_3": 6, "ally_2_2": 3, "neut_2_2": 4, "enemy_2_2": 9, "ally_2_3": 3, "neut_2_3": 5, "enemy_2_3": 10, "ally_3_3": 1, "neut_3_3": 3, "enemy_3_3": 5 } # string is enemy if relation is -1 reln_str = "enemy_" if (relation == 1): reln_str = "ally_" elif (relation == 0): reln_str = "neut_" first_stat = statusA second_stat = statusB #Convention - list smaller number first if (statusA > statusB): first_stat = statusB second_stat = statusA # Recode any status that is not 0,2,3 # If a country has given up its weapon program (-1) or is only # 'exploring' (1) then treat them as 'never pursued' (0) for now. # Someday these status' could be given unique conflict values in the matrix if (first_stat == 1): first_stat = 0 if (first_stat == -1): first_stat = 0 if (second_stat == 1): second_stat = 0 if (second_stat == -1): second_stat = 0 reln_str += str(int(first_stat)) + "_" + str(int(second_stat)) return score_matrix[reln_str] # convert network (defined by intuition as small=1, medium=2, large=3) into # a factor score on 1-10 scale. # # Technology Achievement Index # # REFERENCE URL?? # def network2score(sci_val): stepA = 1 stepB = 2 stepC = 3 all_scores = np.ndarray(sci_val.size) for i in range(sci_val.size): score = -1 if (math.isnan(sci_val[i])): score = 1 elif (sci_val[i] < stepA): score = 2 elif (sci_val[i] < stepB): score = 4 elif (sci_val[i] < stepC): score = 7 else: score = 10 all_scores[i] = score return all_scores # # First assign a score of 0-3 based on number of alliances with non-nuclear # states. # Then add to that score a 5, 6, or 7 based on the number of alliances with # nuclear states (if none then add 0). # # Rice University Database http://atop.rice.edu/search # def alliance2iso_score(all_alliances): np_stepA = 2 np_stepB = 4 p_stepA = 1 p_stepB = 2 p_stepC = 3 non_prolif = all_alliances[0] prolif = all_alliances[1] all_scores = np.ndarray(non_prolif.size) for i in range(non_prolif.size): score = 0 if (math.isnan(prolif[i])) and (math.isnan(non_prolif[i])): score = np.nan elif (non_prolif[i] <= np_stepA): score = 1 elif (non_prolif[i] <= np_stepB): score = 2 else: score = 3 if (not math.isnan(prolif[i])): if (prolif[i] == p_stepA): score = score + 5 elif (prolif[i] == p_stepB): score = score + 6 elif (prolif[i] >= p_stepC): score = score + 7 # Isolation is the inverse of amount of alliances all_scores[i] = 10 - score return all_scores # # Center for Systemic Peace # Polity IV Series http://www.systemicpeace.org/inscrdata.html # def polity2auth_score(polity): scores = polity return scores # # Fuhrmman http://www.matthewfuhrmann.com/datasets.html # If any enrichment or reprocessing capability then 10, otherwise 0 # def enrich2score(enrich): scores = enrich*10.0 return scores # # If any U reserves than 10, otherwise 0 # OECD U report # https://www.oecd-nea.org/ndd/pubs/2014/7209-uranium-2014.pdf # def ures2score(ures): scores = ures*10.0 return scores
mbmcgarry/historical_prolif
hist_bench.py
Python
bsd-3-clause
27,370
from __future__ import division import abc import numpy as n import scipy.linalg as linalg import scipy.optimize as opt import scipy.spatial.distance as dist class Feature(object): ''' Abstract class that represents a feature to be used with :py:class:`pyransac.ransac.RansacFeature` ''' __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self): pass @abc.abstractproperty def min_points(self): '''int: Minimum number of points needed to define the feature.''' pass @abc.abstractmethod def points_distance(self,points): ''' This function implements a method to compute the distance of points from the feature. Args: points (numpy.ndarray): a numpy array of points the distance must be computed of. Returns: distances (numpy.ndarray): the computed distances of the points from the feature. ''' pass @abc.abstractmethod def print_feature(self,num_points): ''' This method returns an array of x,y coordinates for points that are in the feature. Args: num_points (numpy.ndarray): the number of points to be returned Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' class Circle(Feature): ''' Feature class for a Circle :math:`(x-x_c)^2 + (y-y_c)^2 - r = 0` ''' min_points = 3 '''int: Minimum number of points needed to define the circle (3).''' def __init__(self,points): self.radius,self.xc,self.yc = self.__gen(points) def __gen(self,points): ''' Compute the radius and the center coordinates of a circumference given three points Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: (tuple): A 3 elements tuple that contains the circumference radius and center coordinates [radius,xc,yc] Raises: RuntimeError: If the circle computation does not succeed a RuntimeError is raised. ''' # Linear system for (D,E,F) in circle # equations: D*xi + E*yi + F = -(xi**2 + yi**2) # where xi, yi are the coordinate of the i-th point. # Generating A matrix A = n.array([(x,y,1) for x,y in points]) # Generating rhs rhs = n.array([-(x**2+y**2) for x,y in points]) try: #Solving linear system D,E,F = linalg.lstsq(A,rhs)[0] except linalg.LinAlgError: raise RuntimeError('Circle calculation not successful. Please\ check the input data, probable collinear points') xc = -D/2 yc = -E/2 r = n.sqrt(xc**2+yc**2-F) return (r,xc,yc) def points_distance(self,points): r''' Compute the distance of the points from the feature :math:`d = \left| \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2} - r \right|` Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: d (numpy.ndarray): the computed distances of the points from the feature. ''' xa = n.array([self.xc,self.yc]).reshape((1,2)) d = n.abs(dist.cdist(points,xa) - self.radius) return d def print_feature(self, num_points): ''' This method returns an array of x,y coordinates for points that are in the feature. Args: num_points (numpy.ndarray): the number of points to be returned Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' theta = n.linspace(0,2*n.pi,num_points) x = self.xc + self.radius*n.cos(theta) y = self.yc + self.radius*n.sin(theta) return n.vstack((x,y)) class Exponential (Feature): ''' Feature Class for an exponential curve :math:`y=ax^{k} + b` ''' min_points = 3 def __init__(self,points): self.a,self.k,self.b = self.__gen(points) def __gen(self,points): ''' Compute the three parameters that univocally determine the exponential curve Args: points(numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: exp(numpy.ndarray): A (3,) numpy array that contains the a,n,b parameters [a,k,b] Raises: RuntimeError: If the circle computation does not succeed a RuntimeError is raised. ''' def exponential(x,points): ''' Non linear system function to use with :py:func:`scypy.optimize.root` ''' aa = x[0] nn = x[1] bb = x[2] f = n.zeros((3,)) f[0] = n.abs(aa)*n.power(points[0,0],nn)+bb - points[0,1] f[1] = n.abs(aa)*n.power(points[1,0],nn)+bb - points[1,1] f[2] = n.abs(aa)*n.power(points[2,0],nn)+bb - points[2,1] return f exp = opt.root(exponential,[1,1,1],points,method='lm')['x'] return exp def points_distance(self,points): r''' Compute the distance of the points from the feature :math:`d = \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2}` Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: d (numpy.ndarray): the computed distances of the points from the feature. ''' x = points[:,0] xa = n.array([x,self.a*n.power(x,self.k)+self.b]) xa = xa.T d = dist.cdist(points,xa) return n.diag(d) def print_feature(self, num_points, a,b): ''' This method returns an array of x,y coordinates for points that are in the feature in the interval [a,b]. Args: num_points (numpy.ndarray): the number of points to be returned a (float): left end of the interval b (float): right end of the interval Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' x = n.linspace(a,b,num_points) y = self.a*x**self.k + self.b return n.vstack((x,y))
rubendibattista/python-ransac-library
pyransac/features.py
Python
bsd-3-clause
6,919
<?php use yii\helpers\Html; ?> <section class="main-content"> <div class="row"> <div class="span12"> <div class="row"> <div class="span12"> <h4 class="title"> <span class="pull-left"><span class="text"><span class="line">Feature <strong>Products</strong></span></span></span> </h4> <div id="myCarousel" class="myCarousel carousel slide"> <div class="carousel-inner"> <div class="active item"> <ul class="thumbnails"> <?php foreach($model as $field){ ?> <li class="span3"> <div class="product-box"> <span class="sale_tag"></span> <p><?= Html::a("<img src=' $field->image ' />", ['detail', 'id' => $field->id]); ?></p> <a class="title"><?= $field->productname; ?></a><br/> <a class="category"><?= $field->description; ?></a> <p class="price">RM <?= number_format((float)$field->price, 2, '.', '');?></p> <p class="price"><strike>RM <?= number_format((float)$field->priceretail, 2, '.', '');?></strike></p> </div> </li> <?php } ?> </ul> </div> </div> </div> </div> </div> </div> </div> </section>
mat8392/yiihermo
frontend/views/product/index.php
PHP
bsd-3-clause
1,971
package yum import ( "bytes" "encoding/xml" "fmt" "io" "io/ioutil" "math" "os" "path/filepath" "time" "github.com/gonuts/logger" ) // List of packages to ignore for our case var IGNORED_PACKAGES = []string{ "rpmlib(CompressedFileNames)", "/bin/sh", "rpmlib(PayloadFilesHavePrefix)", "rpmlib(PartialHardlinkSets)", } // Repository represents a YUM repository with all associated metadata. type Repository struct { msg *logger.Logger Name string RepoUrl string RepoMdUrl string LocalRepoMdXml string CacheDir string Backends []string Backend Backend } // NewRepository create a new Repository with name and from url. func NewRepository(name, url, cachedir string, backends []string, setupBackend, checkForUpdates bool) (*Repository, error) { repo := Repository{ msg: logger.NewLogger("repo", logger.INFO, os.Stdout), Name: name, RepoUrl: url, RepoMdUrl: url + "/repodata/repomd.xml", LocalRepoMdXml: filepath.Join(cachedir, "repomd.xml"), CacheDir: cachedir, Backends: make([]string, len(backends)), } copy(repo.Backends, backends) err := os.MkdirAll(cachedir, 0644) if err != nil { return nil, err } // load appropriate backend if requested if setupBackend { if checkForUpdates { err = repo.setupBackendFromRemote() if err != nil { return nil, err } } else { err = repo.setupBackendFromLocal() if err != nil { return nil, err } } } return &repo, err } // Close cleans up after use func (repo *Repository) Close() error { return repo.Backend.Close() } // FindLatestMatchingName locats a package by name, returns the latest available version. func (repo *Repository) FindLatestMatchingName(name, version, release string) (*Package, error) { return repo.Backend.FindLatestMatchingName(name, version, release) } // FindLatestMatchingRequire locates a package providing a given functionality. func (repo *Repository) FindLatestMatchingRequire(requirement *Requires) (*Package, error) { return repo.Backend.FindLatestMatchingRequire(requirement) } // GetPackages returns all the packages known by a YUM repository func (repo *Repository) GetPackages() []*Package { return repo.Backend.GetPackages() } // setupBackendFromRemote checks which backend should be used and updates the DB files. func (repo *Repository) setupBackendFromRemote() error { repo.msg.Debugf("setupBackendFromRemote...\n") var err error var backend Backend // get repo metadata with list of available files remotedata, err := repo.remoteMetadata() if err != nil { return err } remotemd, err := repo.checkRepoMD(remotedata) if err != nil { return err } localdata, err := repo.localMetadata() if err != nil { return err } localmd, err := repo.checkRepoMD(localdata) if err != nil { return err } for _, bname := range repo.Backends { repo.msg.Debugf("checking availability of backend [%s]\n", bname) ba, err := NewBackend(bname, repo) if err != nil { ba.Close() continue } rrepomd, ok := remotemd[ba.YumDataType()] if !ok { repo.msg.Warnf("remote repository does not provide [%s] DB\n", bname) continue } // a priori a match backend = ba repo.Backend = backend lrepomd, ok := localmd[ba.YumDataType()] if !ok { // doesn't matter, we download the DB in any case } if !repo.Backend.HasDB() || rrepomd.Timestamp.After(lrepomd.Timestamp) { // we need to update the DB url := repo.RepoUrl + "/" + rrepomd.Location repo.msg.Debugf("updating the RPM database for %s\n", bname) err = repo.Backend.GetLatestDB(url) if err != nil { repo.msg.Warnf("problem updating RPM database for backend [%s]: %v\n", bname, err) err = nil backend = nil repo.Backend = nil continue } // save metadata to local repomd file err = ioutil.WriteFile(repo.LocalRepoMdXml, remotedata, 0644) if err != nil { repo.msg.Warnf("problem updating local repomd.xml file for backend [%s]: %v\n", bname, err) err = nil backend = nil repo.Backend = nil continue } } // load data necessary for the backend err = repo.Backend.LoadDB() if err != nil { repo.msg.Warnf("problem loading data for backend [%s]: %v\n", bname, err) err = nil backend = nil repo.Backend = nil continue } // stop at first one found break } if backend == nil { repo.msg.Errorf("No valid backend found\n") return fmt.Errorf("No valid backend found") } repo.msg.Debugf("repository [%s] - chosen backend [%T]\n", repo.Name, repo.Backend) return err } func (repo *Repository) setupBackendFromLocal() error { repo.msg.Debugf("setupBackendFromLocal...\n") var err error data, err := repo.localMetadata() if err != nil { return err } md, err := repo.checkRepoMD(data) if err != nil { return err } var backend Backend for _, bname := range repo.Backends { repo.msg.Debugf("checking availability of backend [%s]\n", bname) ba, err := NewBackend(bname, repo) if err != nil { continue } _ /*repomd*/, ok := md[ba.YumDataType()] if !ok { repo.msg.Warnf("local repository does not provide [%s] DB\n", bname) continue } // a priori a match backend = ba repo.Backend = backend // loading data necessary for the backend err = repo.Backend.LoadDB() if err != nil { repo.msg.Warnf("problem loading data for backend [%s]: %v\n", bname, err) err = nil backend = nil repo.Backend = nil continue } // stop at first one found. break } if backend == nil { repo.msg.Errorf("No valid backend found\n") return fmt.Errorf("No valid backend found") } repo.msg.Debugf("repository [%s] - chosen backend [%T]\n", repo.Name, repo.Backend) return err } // remoteMetadata retrieves the repo metadata file content func (repo *Repository) remoteMetadata() ([]byte, error) { r, err := getRemoteData(repo.RepoMdUrl) if err != nil { return nil, err } defer r.Close() buf := new(bytes.Buffer) _, err = io.Copy(buf, r) if err != nil && err != io.EOF { return nil, err } return buf.Bytes(), err } // localMetadata retrieves the repo metadata from the repomd file func (repo *Repository) localMetadata() ([]byte, error) { if !path_exists(repo.LocalRepoMdXml) { return nil, nil } f, err := os.Open(repo.LocalRepoMdXml) if err != nil { return nil, err } defer f.Close() buf := new(bytes.Buffer) _, err = io.Copy(buf, f) if err != nil && err != io.EOF { return nil, err } return buf.Bytes(), err } // checkRepoMD parses the Repository metadata XML content func (repo *Repository) checkRepoMD(data []byte) (map[string]RepoMD, error) { if len(data) <= 0 { repo.msg.Debugf("checkRepoMD: no data\n") return nil, nil } type xmlTree struct { XMLName xml.Name `xml:"repomd"` Data []struct { Type string `xml:"type,attr"` Checksum string `xml:"checksum"` Location struct { Href string `xml:"href,attr"` } `xml:"location"` Timestamp float64 `xml:"timestamp"` } `xml:"data"` } var tree xmlTree err := xml.Unmarshal(data, &tree) if err != nil { return nil, err } db := make(map[string]RepoMD) for _, data := range tree.Data { sec := int64(math.Floor(data.Timestamp)) nsec := int64((data.Timestamp - float64(sec)) * 1e9) db[data.Type] = RepoMD{ Checksum: data.Checksum, Timestamp: time.Unix(sec, nsec), Location: data.Location.Href, } } return db, err } type RepoMD struct { Checksum string Timestamp time.Time Location string } // EOF
lhcb-org/lbpkr
yum/repository.go
GO
bsd-3-clause
7,548
"""Klamp't visualization routines. See Python/demos/vistemplate.py for an example of how to run this module. The visualization module lets you draw most Klamp't objects in a 3D world using a simple interface. It also lets you customize the GUI using Qt widgets, OpenGL drawing, and keyboard/mouse intercept routines. Main features include: - Simple interface to modify the visualization - Simple interface to animate and render trajectories - Simple interface to edit certain Klamp't objects (configurations, points, transforms) - Simple interface to drawing text and text labels, and drawing plots - Multi-window, multi-viewport support - Unified interface to PyQt and GLUT (with loss of resource editing functionality under GLUT) - Automatic camera setup The resource editing functionality in the klampt.io.resource module (based on klampt.vis.editors) use this module as well. Due to weird OpenGL and Qt behavior in multi-threaded programs, you should only run visualizations using the methods in this module. There are two primary ways of setting up a visualization: - The first is by adding items to the visualization world and customizing them using the vis.X routines that mirror the methods in VisualizationPlugin (like add, setColor, animate, etc). See Python/demos/vistemplate.py for more information. - The second is by creating a subclass of GLPluginInterface and doing all the necessary drawing / interaction yourself inside its hooks. In the latter case, you will call vis.setPlugin(plugin) to override the default visualization behavior before creating your window. See Python/demos/visplugin.py for more information. A third way of setting up a visualization is a hybrid of the two, where you can add functionality on top of default the visualization world. You can either use vis.pushPlugin(plugin) in which case your plugin adds additional functionality, or you can subclass the vis.VisualizationPlugin class, and selectively augment / override the default functionality. Instructions: - To add things to the default visualization: Call the VisualizationPlugin aliases (add, animate, setColor, etc) - To show the visualization and quit when the user closes the window: vis.run() - To show the visualization and return when the user closes the window: vis.dialog() ... do stuff afterwards ... vis.kill() - To show the visualization and be able to run a script alongside it until the user closes the window: vis.show() while vis.shown(): vis.lock() ... do stuff ... [to exit the loop call show(False)] vis.unlock() time.sleep(dt) ... do stuff afterwards ... vis.kill() - To run a window with a custom plugin (GLPluginInterface) and terminate on closure: vis.run(plugin) - To show a dialog or parallel window vis.setPlugin(plugin) ... then call vis.dialog() ... or vis.show() ... do stuff afterwards ... vis.kill() - To add a GLPluginInterface that just customizes a few things on top of the default visualization: vis.pushPlugin(plugin) vis.dialog() vis.popPlugin() - To run plugins side-by-side in the same window: vis.setPlugin(plugin1) vis.addPlugin(plugin2) #this creates a new split-screen vis.dialog() ... or vis.show() ... do stuff afterwards ... vis.kill() - To run a custom dialog in a QtWindow vis.setPlugin([desired plugin or None for visualization]) vis.setParent(qt_window) vis.dialog() ... or vis.show() ... do stuff afterwards ... vis.kill() - To launch a second window after the first is closed: just call whatever you want again. Note: if show was previously called with a plugin and you wish to revert to the default visualization, you should call setPlugin(None) first to restore the default. - To create a separate window with a given plugin: w1 = vis.createWindow() #w1=0 show() w2 = vis.createWindow() #w2=1 vis.setPlugin(plugin) vis.dialog() #to restore commands to the original window vis.setWindow(w1) while vis.shown(): ... vis.kill() Note: when changing the data shown by the window (e.g., modifying the configurations of robots in a WorldModel) you must call vis.lock() before accessing the data and then call vis.unlock() afterwards. The main interface is as follows: def createWindow(title=None): creates a new visualization window and returns an integer identifier. def setWindow(id): sets the active window for all subsequent calls. ID 0 is the default visualization window. def getWindow(): gets the active window ID. def setWindowTitle(title): sets the title of the visualization window. def getWindowTitle(): returns the title of the visualization window def setPlugin(plugin=None): sets the current plugin (a GLPluginInterface instance). This plugin will now capture input from the visualization and can override any of the default behavior of the visualizer. Set plugin=None if you want to return to the default visualization. def addPlugin(plugin): adds a second OpenGL viewport governed by the given plugin (a GLPluginInterface instance). def run([plugin]): pops up a dialog and then kills the program afterwards. def kill(): kills all previously launched visualizations. Afterwards, you may not be able to start new windows. Call this to cleanly quit. def dialog(): pops up a dialog box (does not return to calling thread until closed). def show(hidden=False): shows/hides a visualization window run in parallel with the calling script. def spin(duration): shows the visualization window for the desired amount of time before returning, or until the user closes the window. def shown(): returns true if the window is shown. def lock(): locks the visualization world for editing. The visualization will be paused until unlock() is called. def unlock(): unlocks the visualization world. Must only be called once after every lock(). def customUI(make_func): launches a user-defined UI window by calling make_func(gl_backend) in the visualization thread. This can be used to build custom editors and windows that are compatible with other visualization functionality. Here gl_backend is an instance of _GLBackend instantiated for the current plugin. def getViewport(): Returns the currently active viewport. The following VisualizationPlugin methods are also added to the klampt.vis namespace and operate on the default plugin. If you are calling these methods from an external loop (as opposed to inside a plugin) be sure to lock/unlock the visualization before/after calling these methods. def add(name,item,keepAppearance=False): adds an item to the visualization. name is a unique identifier. If an item with the same name already exists, it will no longer be shown. If keepAppearance=True, then the prior item's appearance will be kept, if a prior item exists. def clear(): clears the visualization world. def listItems(): prints out all names of visualization objects def listItems(name): prints out all names of visualization objects under the given name def dirty(item_name='all'): marks the given item as dirty and recreates the OpenGL display lists. You may need to call this if you modify an item's geometry, for example. def remove(name): removes an item from the visualization. def setItemConfig(name,vector): sets the configuration of a named item. def getItemConfig(name): returns the configuration of a named item. def hide(name,hidden=True): hides/unhides an item. The item is not removed, it just becomes invisible. def edit(name,doedit=True): turns on/off visual editing of some item. Only points, transforms, coordinate.Point's, coordinate.Transform's, coordinate.Frame's, robots, and objects are currently accepted. def hideLabel(name,hidden=True): hides/unhides an item's text label. def setAppearance(name,appearance): changes the Appearance of an item. def revertAppearance(name): restores the Appearance of an item def setAttribute(name,attribute,value): sets an attribute of the appearance of an item. Typical attributes are 'color', 'size', 'length', 'width'... TODO: document all accepted attributes. def setColor(name,r,g,b,a=1.0): changes the color of an item. def setDrawFunc(name,func): sets a custom OpenGL drawing function for an item. func is a one-argument function that takes the item data as input. Set func to None to revert to default drawing. def animate(name,animation,speed=1.0,endBehavior='loop'): Sends an animation to the object. May be a Trajectory or a list of configurations. Works with points, so3 elements, se3 elements, rigid objects, or robots. - speed: a modulator on the animation speed. If the animation is a list of milestones, it is by default run at 1 milestone per second. - endBehavior: either 'loop' (animation repeats forever) or 'halt' (plays once). def pauseAnimation(paused=True): Turns on/off animation. def stepAnimation(amount): Moves forward the animation time by the given amount in seconds def animationTime(newtime=None): Gets/sets the current animation time If newtime == None (default), this gets the animation time. If newtime != None, this sets a new animation time. def addText(name,text,position=None): adds text. You need to give an identifier to all pieces of text, which will be used to access the text as any other vis object. If position is None, this is added as an on-screen display. If position is of length 2, it is the (x,y) position of the upper left corner of the text on the screen. Negative units anchor the text to the right or bottom of the window. If position is of length 3, the text is drawn in the world coordinates. You can then set the color, 'size' attribute, and 'position' attribute of the text using the identifier given in 'name'. def clearText(): clears all previously added text. def addPlot(name): creates a new empty plot. def addPlotItem(name,itemname): adds a visualization item to a plot. def logPlot(name,itemname,value): logs a custom visualization item to a plot def logPlotEvent(name,eventname,color=None): logs an event on the plot. def hidePlotItem(name,itemname,hidden=True): hides an item in the plot. To hide a particular channel of a given item pass a pair (itemname,channelindex). For example, to hide configurations 0-5 of 'robot', call hidePlotItem('plot',('robot',0)), ..., hidePlotItem('plot',('robot',5)). def setPlotDuration(name,time): sets the plot duration. def setPlotRange(name,vmin,vmax): sets the y range of a plot. def setPlotPosition(name,x,y): sets the upper left position of the plot on the screen. def setPlotSize(name,w,h): sets the width and height of the plot. def savePlot(name,fn): saves a plot to a CSV (extension .csv) or Trajectory (extension .traj) file. def autoFitCamera(scale=1.0): Automatically fits the camera to all objects in the visualization. A scale > 1 magnifies the camera zoom. Utility function: def autoFitViewport(viewport,objects): Automatically fits the viewport's camera to see all the given objects. NAMING CONVENTION: The world, if one exists, should be given the name 'world'. Configurations and paths are drawn with reference to the first robot in the world. All items that refer to a name (except add) can either be given a top level item name (a string) or a sub-item (a sequence of strings, given a path from the root to the leaf). For example, if you've added a RobotWorld under the name 'world' containing a robot called 'myRobot', then setColor(('world','myRobot'),0,1,0) will turn the robot green. If 'link5' is the robot's 5th link, then setColor(('world','myRobot','link5'),0,0,1) will turn the 5th link blue. """ from OpenGL.GL import * from threading import Thread,RLock from ..robotsim import * from ..math import vectorops,so3,se3 import gldraw from glinit import * from glinit import _GLBackend,_PyQtAvailable,_GLUTAvailable from glinterface import GLPluginInterface from glprogram import GLPluginProgram import glcommon import time import signal import weakref from ..model import types from ..model import config from ..model import coordinates from ..model.subrobot import SubRobotModel from ..model.trajectory import * from ..model.contact import ContactPoint,Hold class WindowInfo: """Mode can be hidden, shown, or dialog""" def __init__(self,name,frontend,vis,glwindow=None): self.name = name self.frontend = frontend self.vis = vis self.glwindow = glwindow self.mode = 'hidden' self.guidata = None self.custom_ui = None self.doRefresh = False self.doReload = False self.worlds = [] self.active_worlds = [] _globalLock = RLock() #the VisualizationPlugin instance of the currently active window _vis = None #the GLPluginProgram of the currently active window. Accepts _vis as plugin or other user-defined plugins as well _frontend = GLPluginProgram() #the window title for the next created window _window_title = "Klamp't visualizer" #a list of WorldModel's in the current window. A world cannot be used in multiple simultaneous #windows in GLUT. If a world is reused with a different window, its display lists will be refreshed. #Note: must be proxies to allow for deletion _current_worlds = [] #list of WindowInfo's _windows = [] #the index of the current window _current_window = None def createWindow(name): """Creates a new window (and sets it active).""" global _globalLock,_frontend,_vis,_window_title,_current_worlds,_windows,_current_window _globalLock.acquire() if len(_windows) == 0: #save the defaults in window 0 _windows.append(WindowInfo(_window_title,_frontend,_vis)) _windows[-1].worlds = _current_worlds _windows[-1].active_worlds = _current_worlds[:] #make a new window _window_title = name _frontend = GLPluginProgram() _vis = VisualizationPlugin() _frontend.setPlugin(_vis) _windows.append(WindowInfo(_window_title,_frontend,_vis)) _current_worlds = [] id = len(_windows)-1 _current_window = id _globalLock.release() return id def setWindow(id): """Sets currently active window.""" global _globalLock,_frontend,_vis,_window_title,_windows,_current_window,_current_worlds if id == _current_window: return _globalLock.acquire() if len(_windows) == 0: #save the defaults in window 0 _windows.append(WindowInfo(_window_title,_frontend,_vis)) _windows[-1].worlds = _current_worlds _windows[-1].active_worlds = _current_worlds[:] assert id >= 0 and id < len(_windows),"Invalid window id" _window_title,_frontend,_vis,_current_worlds = _windows[id].name,_windows[id].frontend,_windows[id].vis,_windows[id].worlds #print "vis.setWindow(",id,") the window has status",_windows[id].mode if not _PyQtAvailable: #PyQt interface allows sharing display lists but GLUT does not. #refresh all worlds' display lists that were once active. for w in _current_worlds: if w in _windows[_current_window].active_worlds: print "klampt.vis.setWindow(): world",w().index,"becoming active in the new window",id _refreshDisplayLists(w()) _windows[_current_window].active_worlds.remove(w) _windows[id].active_worlds = _current_worlds[:] _current_window = id _globalLock.release() def getWindow(): """Retrieves ID of currently active window or -1 if no window is active""" global _current_window if _current_window == None: return 0 return _current_window def setPlugin(plugin): """Lets the user capture input via a glinterface.GLPluginInterface class. Set plugin to None to disable plugins and return to the standard visualization""" global _globalLock,_frontend,_windows,_current_window _globalLock.acquire() if not isinstance(_frontend,GLPluginProgram): _frontend = GLPluginProgram() if _current_window != None: if _windows[_current_window].glwindow != None: _frontend.window = _windows[_current_window].glwindow if plugin == None: global _vis if _vis==None: raise RuntimeError("Visualization disabled") _frontend.setPlugin(_vis) else: _frontend.setPlugin(plugin) if hasattr(plugin,'world'): _checkWindowCurrent(plugin.world) _onFrontendChange() _globalLock.release() def pushPlugin(plugin): """Adds a new glinterface.GLPluginInterface plugin on top of the old one.""" global _globalLock,_frontend _globalLock.acquire() assert isinstance(_frontend,GLPluginProgram),"Can't push a plugin after addPlugin" if len(_frontend.plugins) == 0: global _vis if _vis==None: raise RuntimeError("Visualization disabled") _frontend.setPlugin(_vis) _frontend.pushPlugin(plugin) _onFrontendChange() _globalLock.release() def popPlugin(): """Reverses a prior pushPlugin() call""" global _frontend _globalLock.acquire() _frontend.popPlugin() _onFrontendChange() _globalLock.release() def addPlugin(plugin): """Adds a second OpenGL viewport in the same window, governed by the given plugin (a glinterface.GLPluginInterface instance).""" global _frontend _globalLock.acquire() #create a multi-view widget if isinstance(_frontend,glcommon.GLMultiViewportProgram): _frontend.addView(plugin) else: if len(_frontend.plugins) == 0: setPlugin(None) multiProgram = glcommon.GLMultiViewportProgram() multiProgram.window = None if _current_window != None: if _windows[_current_window].glwindow != None: multiProgram.window = _windows[_current_window].glwindow multiProgram.addView(_frontend) multiProgram.addView(plugin) multiProgram.name = _window_title _frontend = multiProgram _onFrontendChange() _globalLock.release() def run(plugin=None): """A blocking call to start a single window and then kill the visualization when closed. If plugin == None, the default visualization is used. Otherwise, plugin is a glinterface.GLPluginInterface object, and it is used.""" setPlugin(plugin) show() while shown(): time.sleep(0.1) setPlugin(None) kill() def dialog(): """A blocking call to start a single dialog window with the current plugin. It is closed by pressing OK or closing the window.""" _dialog() def setWindowTitle(title): global _window_title _window_title = title _onFrontendChange() def getWindowTitle(): global _window_title return _window_title def kill(): """This should be called at the end of the calling program to cleanly terminate the visualization thread""" global _vis,_globalLock if _vis==None: print "vis.kill() Visualization disabled" return _kill() def show(display=True): """Shows or hides the current window""" _globalLock.acquire() if display: _show() else: _hide() _globalLock.release() def spin(duration): """Spin-shows a window for a certain duration or until the window is closed.""" show() t = 0 while t < duration: if not shown(): break time.sleep(min(0.04,duration-t)) t += 0.04 show(False) return def lock(): """Begins a locked section. Needs to be called any time you modify a visualization item outside of the visualization thread. unlock() must be called to let the visualization thread proceed.""" global _globalLock _globalLock.acquire() def unlock(): """Ends a locked section acquired by lock().""" global _globalLock,_windows for w in _windows: if w.glwindow: w.doRefresh = True _globalLock.release() def shown(): """Returns true if a visualization window is currently shown.""" global _globalLock,_thread_running,_current_window _globalLock.acquire() res = (_thread_running and _current_window != None and _windows[_current_window].mode in ['shown','dialog'] or _windows[_current_window].guidata is not None) _globalLock.release() return res def customUI(func): """Tells the next created window/dialog to use a custom UI function. func is a 1-argument function that takes a QtWindow or GLUTWindow as its argument.""" global _globalLock _globalLock.acquire() _set_custom_ui(func) _globalLock.release() def getViewport(): """Returns the GLViewport of the current window (see klampt.vis.glprogram.GLViewport)""" return _frontend.get_view() def setViewport(viewport): """Sets the current window to use a given GLViewport (see klampt.vis.glprogram.GLViewport)""" _frontend.set_view(viewport) ######### CONVENIENCE ALIASES FOR VisualizationPlugin methods ########### def clear(): """Clears the visualization world.""" global _vis if _vis==None: return _vis.clear() def add(name,item,keepAppearance=False): """Adds an item to the visualization. name is a unique identifier. If an item with the same name already exists, it will no longer be shown. If keepAppearance=True, then the prior item's appearance will be kept, if a prior item exists.""" global _vis if _vis==None: print "Visualization disabled" return _globalLock.acquire() _checkWindowCurrent(item) _globalLock.release() _vis.add(name,item,keepAppearance) def listItems(name=None,indent=0): global _vis if _vis==None: print "Visualization disabled" return _vis.listItems(name,indent) def dirty(item_name='all'): """Marks the given item as dirty and recreates the OpenGL display lists. You may need to call this if you modify an item's geometry, for example. If things start disappearing from your world when you create a new window, you may need to call this too.""" global _vis if _vis==None: print "Visualization disabled" return _vis.dirty(item_name) def animate(name,animation,speed=1.0,endBehavior='loop'): """Sends an animation to the named object. Works with points, so3 elements, se3 elements, rigid objects, or robots, and may work with other objects as well. Parameters: - animation: may be a Trajectory or a list of configurations. - speed: a modulator on the animation speed. If the animation is a list of milestones, it is by default run at 1 milestone per second. - endBehavior: either 'loop' (animation repeats forever) or 'halt' (plays once). """ global _vis if _vis==None: print "Visualization disabled" return _vis.animate(name,animation,speed,endBehavior) def pauseAnimation(paused=True): global _vis if _vis==None: print "Visualization disabled" return _vis.pauseAnimation(paused) def stepAnimation(amount): global _vis if _vis==None: print "Visualization disabled" return _vis.stepAnimation(amount) def animationTime(newtime=None): """Gets/sets the current animation time If newtime == None (default), this gets the animation time. If newtime != None, this sets a new animation time. """ global _vis if _vis==None: print "Visualization disabled" return 0 return _vis.animationTime(newtime) def remove(name): global _vis if _vis==None: return return _vis.remove(name) def getItemConfig(name): global _vis if _vis==None: return None return _vis.getItemConfig(name) def setItemConfig(name,value): global _vis if _vis==None: return return _vis.setItemConfig(name,value) def hideLabel(name,hidden=True): global _vis if _vis==None: return return _vis.hideLabel(name,hidden) def hide(name,hidden=True): global _vis if _vis==None: return _vis.hide(name,hidden) def edit(name,doedit=True): """Turns on/off visual editing of some item. Only points, transforms, coordinate.Point's, coordinate.Transform's, coordinate.Frame's, robots, and objects are currently accepted.""" global _vis if _vis==None: return _vis.edit(name,doedit) def setAppearance(name,appearance): global _vis if _vis==None: return _vis.setAppearance(name,appearance) def setAttribute(name,attr,value): global _vis if _vis==None: return _vis.setAttribute(name,attr,value) def revertAppearance(name): global _vis if _vis==None: return _vis.revertAppearance(name) def setColor(name,r,g,b,a=1.0): global _vis if _vis==None: return _vis.setColor(name,r,g,b,a) def setDrawFunc(name,func): global _vis if _vis==None: return _vis.setDrawFunc(name,func) def _getOffsets(object): if isinstance(object,WorldModel): res = [] for i in range(object.numRobots()): res += _getOffsets(object.robot(i)) for i in range(object.numRigidObjects()): res += _getOffsets(object.rigidObject(i)) return res elif isinstance(object,RobotModel): q = object.getConfig() object.setConfig([0.0]*len(q)) worig = [object.link(i).getTransform()[1] for i in range(object.numLinks())] object.setConfig(q) wnew = [object.link(i).getTransform()[1] for i in range(object.numLinks())] return [vectorops.sub(b,a) for a,b in zip(worig,wnew)] elif isinstance(object,RigidObjectModel): return [object.getTransform()[1]] elif isinstance(object,Geometry3D): return object.getCurrentTransform()[1] elif isinstance(object,VisAppearance): res = _getOffsets(object.item) if len(res) != 0: return res if len(object.subAppearances) == 0: bb = object.getBounds() if bb != None and not aabb_empty(bb): return [vectorops.mul(vectorops.add(bb[0],bb[1]),0.5)] else: res = [] for a in object.subAppearances.itervalues(): res += _getOffsets(a) return res return [] def _getBounds(object): if isinstance(object,WorldModel): res = [] for i in range(object.numRobots()): res += _getBounds(object.robots(i)) for i in range(object.numRigidObjects()): res += _getBounds(object.rigidObject(i)) return res elif isinstance(object,RobotModel): return sum([object.link(i).geometry().getBB() for i in range(object.numLinks())],[]) elif isinstance(object,RigidObjectModel): return object.geometry().getAABB() elif isinstance(object,Geometry3D): return object.getAABB() elif isinstance(object,VisAppearance): if len(object.subAppearances) == 0: if isinstance(object.item,TerrainModel): return [] bb = object.getBounds() if bb != None and not aabb_empty(bb): return list(bb) else: res = [] for a in object.subAppearances.itervalues(): res += _getBounds(a) return res return [] def _fitPlane(pts): import numpy as np if len(pts) < 3: raise ValueError("Point set is degenerate") centroid = vectorops.div(vectorops.add(*pts),len(pts)) A = np.array([vectorops.sub(pt,centroid) for pt in pts]) U,S,V = np.linalg.svd(A,full_matrices=False) imin = 0 smin = S[0] zeros = [] for i in xrange(len(S)): if abs(S[i]) < 1e-6: zeros.append(i) if abs(S[i]) < smin: smin = S[i] imin = i if len(zeros) > 1: raise ValueError("Point set is degenerate") assert V.shape == (3,3) #normal is the corresponding row of U normal = V[imin,:] return centroid,normal.tolist() def autoFitViewport(viewport,objects): ofs = sum([_getOffsets(o) for o in objects],[]) pts = sum([_getBounds(o) for o in objects],[]) #print "Bounding box",bb,"center",center #raw_input() #reset viewport.camera.rot = [0.,0.,0.] viewport.camera.tgt = [0.,0.,0.] viewport.camera.dist = 6.0 viewport.clippingplanes = (0.2,20) if len(ofs) == 0: return bb = aabb_create(*pts) center = vectorops.mul(vectorops.add(bb[0],bb[1]),0.5) viewport.camera.tgt = center radius = max(vectorops.distance(bb[0],center),0.1) viewport.camera.dist = 1.2*radius / math.tan(math.radians(viewport.fov*0.5)) #default: oblique view viewport.camera.rot = [0,math.radians(30),math.radians(45)] #fit a plane to these points try: centroid,normal = _fitPlane(ofs) except Exception as e: try: centroid,normal = _fitPlane(pts) except Exception as e: print "Exception occurred during fitting to points" print ofs print pts raise return if normal[2] > 0: normal = vectorops.mul(normal,-1) z,x,y = so3.matrix(so3.inv(so3.canonical(normal))) #print z,x,y #raw_input() radius = max([abs(vectorops.dot(x,vectorops.sub(center,pt))) for pt in pts] + [abs(vectorops.dot(y,vectorops.sub(center,pt)))*viewport.w/viewport.h for pt in pts]) zmin = min([vectorops.dot(z,vectorops.sub(center,pt)) for pt in pts]) zmax = max([vectorops.dot(z,vectorops.sub(center,pt)) for pt in pts]) #print "Viewing direction",normal,"at point",center,"with scene size",radius #orient camera to point along normal direction viewport.camera.tgt = center viewport.camera.dist = 1.2*radius / math.tan(math.radians(viewport.fov*0.5)) near,far = viewport.clippingplanes if viewport.camera.dist + zmin < near: near = max((viewport.camera.dist + zmin)*0.5, radius*0.1) if viewport.camera.dist + zmax > far: far = max((viewport.camera.dist + zmax)*1.5, radius*3) viewport.clippingplanes = (near,far) roll = 0 yaw = math.atan2(normal[0],normal[1]) pitch = math.atan2(-normal[2],vectorops.norm(normal[0:2])) #print "Roll pitch and yaw",roll,pitch,yaw #print "Distance",viewport.camera.dist viewport.camera.rot = [roll,pitch,yaw] def addText(name,text,pos=None): """Adds text to the visualizer. You must give an identifier to all pieces of text, which will be used to access the text as any other vis object. Parameters: - name: the text's unique identifier. - text: the string to be drawn - pos: the position of the string. If pos=None, this is added to the on-screen "console" display. If pos has length 2, it is the (x,y) position of the upper left corner of the text on the screen. Negative units anchor the text to the right or bottom of the window. If pos has length 3, the text is drawn in the world coordinates. To customize the text appearance, you can set the color, 'size' attribute, and 'position' attribute of the text using the identifier given in 'name'. """ global _vis _vis.add(name,text,True) if pos is not None: _vis.setAttribute(name,'position',pos) def clearText(): """Clears all text in the visualization.""" global _vis if _vis==None: return _vis.clearText() def addPlot(name): add(name,VisPlot()) def addPlotItem(name,itemname): global _vis if _vis==None: return _vis.addPlotItem(name,itemname) def logPlot(name,itemname,value): """Logs a custom visualization item to a plot""" global _vis if _vis==None: return _vis.logPlot(name,itemname,value) def logPlotEvent(name,eventname,color=None): """Logs an event on the plot.""" global _vis if _vis==None: return _vis.logPlotEvent(name,eventname,color) def hidePlotItem(name,itemname,hidden=True): global _vis if _vis==None: return _vis.hidePlotItem(name,itemname,hidden) def setPlotDuration(name,time): setAttribute(name,'duration',time) def setPlotRange(name,vmin,vmax): setAttribute(name,'range',(vmin,vmax)) def setPlotPosition(name,x,y): setAttribute(name,'position',(x,y)) def setPlotSize(name,w,h): setAttribute(name,'size',(w,h)) def savePlot(name,fn): global _vis if _vis==None: return _vis.savePlot(name,fn) def autoFitCamera(scale=1): global _vis if _vis==None: return print "klampt.vis: auto-fitting camera to scene." _vis.autoFitCamera(scale) def objectToVisType(item,world): itypes = types.objectToTypes(item,world) if isinstance(itypes,(list,tuple)): #ambiguous, still need to figure out what to draw validtypes = [] for t in itypes: if t == 'Config': if world != None and len(item) == world.robot(0).numLinks(): validtypes.append(t) elif t=='Vector3': validtypes.append(t) elif t=='RigidTransform': validtypes.append(t) if len(validtypes) > 1: print "Unable to draw item of ambiguous types",validtypes return if len(validtypes) == 0: print "Unable to draw any of types",itypes return return validtypes[0] return itypes def aabb_create(*ptlist): if len(ptlist) == 0: return [float('inf')]*3,[float('-inf')]*3 else: bmin,bmax = list(ptlist[0]),list(ptlist[0]) for i in xrange(1,len(ptlist)): x = ptlist[i] bmin = [min(a,b) for (a,b) in zip(bmin,x)] bmax = [max(a,b) for (a,b) in zip(bmax,x)] return bmin,bmax def aabb_expand(bb,bb2): bmin = [min(a,b) for a,b in zip(bb[0],bb2[0])] bmax = [max(a,b) for a,b in zip(bb[1],bb2[1])] return (bmin,bmax) def aabb_empty(bb): return any((a > b) for (a,b) in zip(bb[0],bb[1])) _defaultCompressThreshold = 1e-2 class VisPlotItem: def __init__(self,itemname,linkitem): self.name = itemname self.itemnames = [] self.linkitem = linkitem self.traces = [] self.hidden = [] self.traceRanges = [] self.luminosity = [] self.compressThreshold = _defaultCompressThreshold if linkitem is not None: q = config.getConfig(linkitem.item) assert q is not None from collections import deque self.traces = [deque() for i in range(len(q))] self.itemnames = config.getConfigNames(linkitem.item) def customUpdate(self,item,t,v): for i,itemname in enumerate(self.itemnames): if item == itemname: self.updateTrace(i,t,v) self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v)) return else: from collections import deque self.itemnames.append(item) self.traces.append(deque()) i = len(self.itemnames)-1 self.updateTrace(i,t,v) self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v)) #raise ValueError("Invalid item specified: "+str(item)) def update(self,t): if self.linkitem is None: return q = config.getConfig(self.linkitem.item) assert len(self.traces) == len(q) for i,v in enumerate(q): self.updateTrace(i,t,v) self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v)) def discard(self,tstart): for t in self.traces: if len(t)<=1: return while len(t) >= 2: if t[1][0] < tstart: t.popleft() else: break def updateTrace(self,i,t,v): import random assert i < len(self.traces) assert i <= len(self.hidden) assert i <= len(self.luminosity) while i >= len(self.hidden): self.hidden.append(False) while i >= len(self.traceRanges): self.traceRanges.append((v,v)) if i >= len(self.luminosity): initialLuminosity = [0.5,0.25,0.75,1.0] while i >= len(self.luminosity): if len(self.luminosity)<len(initialLuminosity): self.luminosity.append(initialLuminosity[len(self.luminosity)]) else: self.luminosity.append(random.uniform(0,1)) trace = self.traces[i] if len(trace) > 0 and trace[-1][0] == t: trace[-1] = (t,v) return if self.compressThreshold is None: trace.append((t,v)) else: if len(trace) < 2: trace.append((t,v)) else: pprev = trace[-2] prev = trace[-1] assert prev > pprev,"Added two items with the same time?" assert t > prev[0] slope_old = (prev[1]-pprev[1])/(prev[0]-pprev[0]) slope_new = (v-prev[1])/(t-prev[0]) if (slope_old > 0 != slope_new > 0) or abs(slope_old-slope_new) > self.compressThreshold: trace.append((t,v)) else: #near-linear, just extend along straight line trace[-1] = (t,v) class VisPlot: def __init__(self): self.items = [] self.colors = [] self.events = dict() self.eventColors = dict() self.outfile = None self.outformat = None def __del__(self): self.endSave() def update(self,t,duration,compressThreshold): for i in self.items: i.compressThreshold = compressThreshold i.update(t) if self.outfile: self.dumpCurrent() self.discard(t-duration) else: self.discard(t-60.0) def discard(self,tmin): for i in self.items: i.discard(tmin) delevents = [] for e,times in self.events.iteritems(): while len(times) > 0 and times[0] < tmin: times.popleft() if len(times)==0: delevents.append(e) for e in delevents: del self.events[e] def addEvent(self,name,t,color=None): if name in self.events: self.events[name].append(t) else: from collections import deque self.events[name] = deque([t]) if color == None: import random color = (random.uniform(0.01,1),random.uniform(0.01,1),random.uniform(0.01,1)) color = vectorops.mul(color,1.0/max(color)) if color != None: self.eventColors[name] = color if len(color)==3: self.eventColors[name] += [1.0] def autoRange(self): vmin = float('inf') vmax = -float('inf') for i in self.items: for j in xrange(len(i.traceRanges)): if not i.hidden[j]: vmin = min(vmin,i.traceRanges[j][0]) vmax = max(vmax,i.traceRanges[j][1]) if math.isinf(vmin): return (0.,1.) if vmax == vmin: vmax += 1.0 return (float(vmin),float(vmax)) def render(self,window,x,y,w,h,duration,vmin=None,vmax=None): if vmin == None: vmin,vmax = self.autoRange() import random while len(self.colors) < len(self.items): c = (random.uniform(0.01,1),random.uniform(0.01,1),random.uniform(0.01,1)) c = vectorops.mul(c,1.0/max(c)) self.colors.append(c) glColor3f(0,0,0) glBegin(GL_LINE_LOOP) glVertex2f(x,y) glVertex2f(x+w,y) glVertex2f(x+w,y+h) glVertex2f(x,y+h) glEnd() window.draw_text((x-18,y+4),'%.2f'%(vmax,),9) window.draw_text((x-18,y+h+4),'%.2f'%(vmin,),9) tmax = 0 for i in self.items: for trace in i.traces: if len(trace)==0: continue tmax = max(tmax,trace[-1][0]) for i,item in enumerate(self.items): for j,trace in enumerate(item.traces): if len(trace)==0: continue labelheight = trace[-1][1] if len(item.name)==0: label = item.itemnames[j] else: label = str(item.name) + '.' + item.itemnames[j] labelheight = (labelheight - vmin)/(vmax-vmin) labelheight = y + h - h*labelheight glColor3fv(vectorops.mul(self.colors[i],item.luminosity[j])) window.draw_text((x+w+3,labelheight+4),label,9) glBegin(GL_LINE_STRIP) for k in xrange(len(trace)-1): if trace[k+1][0] > tmax-duration: u,v = trace[k] if trace[k][0] < tmax-duration: #interpolate so x is at tmax-duration u2,v2 = trace[k+1] #u + s(u2-u) = tmax-duration s = (tmax-duration-u)/(u2-u) v = v + s*(v2-v) u = (tmax-duration) u = (u-(tmax-duration))/duration v = (v-vmin)/(vmax-vmin) glVertex2f(x+w*u,y+(1-v)*h) u,v = trace[-1] u = (u-(tmax-duration))/duration v = (v-vmin)/(vmax-vmin) glVertex2f(x+w*u,y+(1-v)*h) glEnd() if len(self.events) > 0: for e,times in self.events.iteritems(): for t in times: if t < tmax-duration: continue labelx = (t - (tmax-duration))/duration labelx = x + w*labelx c = self.eventColors[e] glColor4f(c[0]*0.5,c[1]*0.5,c[2]*0.5,c[3]) window.draw_text((labelx,y+h+12),e,9) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) glBegin(GL_LINES) for e,times in self.events.iteritems(): for t in times: if t < tmax-duration: continue labelx = (t - (tmax-duration))/duration labelx = x + w*labelx glColor4f(c[0],c[1],c[2],c[3]*0.5) glVertex2f(labelx,y) glVertex2f(labelx,y+h) glEnd() glDisable(GL_BLEND) def beginSave(self,fn): import os ext = os.path.splitext(fn)[1] if ext == '.csv' or ext == '.traj': self.outformat = ext else: raise ValueError("Invalid extension for visualization plot, can only accept .csv or .traj") self.outfile = open(fn,'w') if self.outformat == '.csv': #output a header self.outfile.write("time") for i in self.items: self.outfile.write(",") fullitemnames = [] if len(i.name) != 0: name = None if isinstance(i.name,(list,tuple)): name = '.'.join(v for v in i.name) else: name = i.name fullitemnames = [name+'.'+itemname for itemname in i.itemnames] else: fullitemnames = i.itemnames self.outfile.write(",".join(fullitemnames)) self.outfile.write("\n") self.dumpAll() def endSave(self): if self.outfile is not None: self.outfile.close() def dumpAll(self): assert self.outfile is not None if len(self.items) == 0: return cols = [] mindt = float('inf') mint = float('inf') maxt = -float('inf') for i in self.items: if len(i.traces) == 0: continue for j,trace in enumerate(i.traces): times,vals = zip(*trace) if isinstance(vals[0],(int,float)): vals = [[v] for v in vals] traj = Trajectory(times,vals) cols.append(traj) mint = min(mint,traj.times[0]) maxt = max(maxt,traj.times[-1]) for k in xrange(len(traj.times)-1): mindt = min(mindt,traj.times[k+1] - traj.times[k]) assert mindt > 0, "For some reason, there is a duplicate time?" N = int((maxt - mint)/mindt) dt = (maxt - mint)/N times = [mint + i*(maxt-mint)/N for i in range(N+1)] for i in xrange(N+1): vals = [col.eval(times[i]) for col in cols] if self.outformat == '.csv': self.outfile.write(str(times[i])+',') self.outfile.write(','.join([str(v[0]) for v in vals])) self.outfile.write('\n') else: self.outfile.write(str(times[i])+'\t') self.outfile.write(str(len(vals))+' ') self.outfile.write(' '.join([str(v[0]) for v in vals])) self.outfile.write('\n') def dumpCurrent(self): if len(self.items) == 0: return assert len(self.items[0].trace) > 0, "Item has no channels?" assert len(self.items[0].trace[0]) > 0, "Item has no readings yet?" t = self.items[0].trace[0][-1] vals = [] for i in self.items: if len(i.trace) == 0: continue for j,trace in enumerate(i.trace): vals.append(trace[-1][1]) if self.outformat == '.csv': self.outfile.write(str(t)+',') self.outfile.write(','.join([str(v) for v in vals])) self.outfile.write('\n') else: self.outfile.write(str(t)+'\t') self.outfile.write(str(len(vals))+' ') self.outfile.write(' '.join([str(v) for v in vals])) self.outfile.write('\n') class VisAppearance: def __init__(self,item,name = None): self.name = name self.hidden = False self.useDefaultAppearance = True self.customAppearance = None self.customDrawFunc = None #For group items, this allows you to customize appearance of sub-items self.subAppearances = {} self.animation = None self.animationStartTime = 0 self.animationSpeed = 1.0 self.attributes = {} #used for Qt text rendering self.widget = None #used for visual editing of certain items self.editor = None #cached drawing self.displayCache = [glcommon.CachedGLObject()] self.displayCache[0].name = name #temporary configuration of the item self.drawConfig = None self.setItem(item) def setItem(self,item): self.item = item self.subAppearances = {} #Parse out sub-items which can have their own appearance changed if isinstance(item,WorldModel): for i in xrange(item.numRobots()): self.subAppearances[("Robot",i)] = VisAppearance(item.robot(i),item.robot(i).getName()) for i in xrange(item.numRigidObjects()): self.subAppearances[("RigidObject",i)] = VisAppearance(item.rigidObject(i),item.rigidObject(i).getName()) for i in xrange(item.numTerrains()): self.subAppearances[("Terrain",i)] = VisAppearance(item.terrain(i),item.terrain(i).getName()) elif isinstance(item,RobotModel): for i in xrange(item.numLinks()): self.subAppearances[("Link",i)] = VisAppearance(item.link(i),item.link(i).getName()) elif isinstance(item,coordinates.Group): for n,f in item.frames.iteritems(): self.subAppearances[("Frame",n)] = VisAppearance(f,n) for n,p in item.points.iteritems(): self.subAppearances[("Point",n)] = VisAppearance(p,n) for n,d in item.directions.iteritems(): self.subAppearances[("Direction",n)] = VisAppearance(d,n) for n,g in item.subgroups.iteritems(): self.subAppearances[("Subgroup",n)] = VisAppearance(g,n) elif isinstance(item,Hold): if item.ikConstraint is not None: self.subAppearances["ikConstraint"] = VisAppearance(item.ikConstraint,"ik") for n,c in enumerate(item.contacts): self.subAppearances[("contact",n)] = VisAppearance(c,n) for (k,a) in self.subAppearances.iteritems(): a.attributes = self.attributes def markChanged(self): for c in self.displayCache: c.markChanged() for (k,a) in self.subAppearances.iteritems(): a.markChanged() self.update_editor(True) self.doRefresh = True def destroy(self): for c in self.displayCache: c.destroy() for (k,a) in self.subAppearances.iteritems(): a.destroy() self.subAppearances = {} def drawText(self,text,point): """Draws the given text at the given point""" if self.attributes.get("text_hidden",False): return self.widget.addLabel(text,point[:],[0,0,0]) def updateAnimation(self,t): """Updates the configuration, if it's being animated""" if not self.animation: self.drawConfig = None else: u = self.animationSpeed*(t-self.animationStartTime) q = self.animation.eval(u,self.animationEndBehavior) self.drawConfig = q for n,app in self.subAppearances.iteritems(): app.updateAnimation(t) def updateTime(self,t): """Updates in real time""" if isinstance(self.item,VisPlot): compressThreshold = self.attributes.get('compress',_defaultCompressThreshold) duration = self.attributes.get('duration',5.) for items in self.item.items: if items.linkitem: items.linkitem.swapDrawConfig() self.item.update(t,duration,compressThreshold) for items in self.item.items: if items.linkitem: items.linkitem.swapDrawConfig() def swapDrawConfig(self): """Given self.drawConfig!=None, swaps out the item's curren configuration with self.drawConfig. Used for animations""" if self.drawConfig: try: newDrawConfig = config.getConfig(self.item) #self.item = config.setConfig(self.item,self.drawConfig) self.drawConfig = newDrawConfig except Exception as e: print "Warning, exception thrown during animation update. Probably have incorrect length of configuration" import traceback traceback.print_exc() pass for n,app in self.subAppearances.iteritems(): app.swapDrawConfig() def clearDisplayLists(self): if isinstance(self.item,WorldModel): for r in range(self.item.numRobots()): for link in range(self.item.robot(r).numLinks()): self.item.robot(r).link(link).appearance().refresh() for i in range(self.item.numRigidObjects()): self.item.rigidObject(i).appearance().refresh() for i in range(self.item.numTerrains()): self.item.terrain(i).appearance().refresh() elif hasattr(self.item,'appearance'): self.item.appearance().refresh() elif isinstance(self.item,RobotModel): for link in range(self.item.numLinks()): self.item.link(link).appearance().refresh() for n,o in self.subAppearances.iteritems(): o.clearDisplayLists() self.markChanged() def draw(self,world=None): """Draws the specified item in the specified world. If name is given and text_hidden != False, then the name of the item is shown.""" if self.hidden: return if self.customDrawFunc is not None: self.customDrawFunc(self.item) return item = self.item name = self.name #set appearance if not self.useDefaultAppearance and hasattr(item,'appearance'): if not hasattr(self,'oldAppearance'): self.oldAppearance = item.appearance().clone() if self.customAppearance != None: #print "Changing appearance of",name item.appearance().set(self.customAppearance) elif "color" in self.attributes: #print "Changing color of",name item.appearance().setColor(*self.attributes["color"]) if len(self.subAppearances)!=0: for n,app in self.subAppearances.iteritems(): app.widget = self.widget app.draw(world) elif hasattr(item,'drawGL'): item.drawGL() elif hasattr(item,'drawWorldGL'): item.drawWorldGL() elif isinstance(item,str): pos = self.attributes.get("position",None) if pos is not None and len(pos)==3: col = self.attributes.get("color",(0,0,0)) self.widget.addLabel(self.item,pos,col) elif isinstance(item,VisPlot): pass elif isinstance(item,Trajectory): doDraw = False centroid = None if isinstance(item,RobotTrajectory): ees = self.attributes.get("endeffectors",[-1]) if world: doDraw = (len(ees) > 0) robot = world.robot(0) for i,ee in enumerate(ees): if ee < 0: ees[i] = robot.numLinks()-1 if doDraw: robot.setConfig(item.milestones[0]) centroid = vectorops.div(vectorops.add(*[robot.link(ee).getTransform()[1] for ee in ees]),len(ees)) elif isinstance(item,SE3Trajectory): doDraw = True centroid = item.milestones[0][9:] else: if len(item.milestones[0]) == 3: #R3 trajectory doDraw = True centroid = item.milestones[0] elif len(item.milestones[0]) == 2: #R2 trajectory doDraw = True centroid = item.milestones[0]+[0.0] if doDraw: def drawRaw(): pointTrajectories = [] if isinstance(item,RobotTrajectory): robot = world.robot(0) ees = self.attributes.get("endeffectors",[-1]) for i,ee in enumerate(ees): if ee < 0: ees[i] = robot.numLinks()-1 if world: for ee in ees: pointTrajectories.append([]) for m in item.milestones: robot.setConfig(m) for ee,eetraj in zip(ees,pointTrajectories): eetraj.append(robot.link(ee).getTransform()[1]) elif isinstance(item,SE3Trajectory): pointTrajectories.append([]) for m in item.milestones: pointTrajectories[-1].append(m[9:]) else: if len(item.milestones[0]) == 3: #R3 trajectory pointTrajectories.append(item.milestones) elif len(item.milestones[0]) == 2: #R2 trajectory pointTrajectories.append([v + [0.0] for v in item.milestones]) glDisable(GL_LIGHTING) glLineWidth(self.attributes.get("width",3)) glColor4f(*self.attributes.get("color",[1,0.5,0,1])) for traj in pointTrajectories: if len(traj) == 1: glBegin(GL_POINTS) glVertex3f(*traj[0]) glEnd() if len(traj) >= 2: glBegin(GL_LINE_STRIP) for p in traj: glVertex3f(*p) glEnd() glLineWidth(1.0) self.displayCache[0].draw(drawRaw,se3.identity()) if name != None: self.drawText(name,centroid) elif isinstance(item,coordinates.Point): def drawRaw(): glDisable(GL_LIGHTING) glEnable(GL_POINT_SMOOTH) glPointSize(self.attributes.get("size",5.0)) glColor4f(*self.attributes.get("color",[0,0,0,1])) glBegin(GL_POINTS) glVertex3f(0,0,0) glEnd() #write name glDisable(GL_DEPTH_TEST) self.displayCache[0].draw(drawRaw,[so3.identity(),item.worldCoordinates()]) glEnable(GL_DEPTH_TEST) if name != None: self.drawText(name,item.worldCoordinates()) elif isinstance(item,coordinates.Direction): def drawRaw(): glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) L = self.attributes.get("length",0.15) source = [0,0,0] glColor4f(*self.attributes.get("color",[0,1,1,1])) glBegin(GL_LINES) glVertex3f(*source) glVertex3f(*vectorops.mul(item.localCoordinates(),L)) glEnd() glEnable(GL_DEPTH_TEST) #write name self.displayCache[0].draw(drawRaw,item.frame().worldCoordinates(),parameters = item.localCoordinates()) if name != None: self.drawText(name,vectorops.add(item.frame().worldCoordinates()[1],item.worldCoordinates())) elif isinstance(item,coordinates.Frame): t = item.worldCoordinates() if item.parent() != None: tp = item.parent().worldCoordinates() else: tp = se3.identity() tlocal = item.relativeCoordinates() def drawRaw(): glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glLineWidth(2.0) gldraw.xform_widget(tlocal,self.attributes.get("length",0.1),self.attributes.get("width",0.01)) glLineWidth(1.0) #draw curve between frame and parent if item.parent() != None: d = vectorops.norm(tlocal[1]) vlen = d*0.5 v1 = so3.apply(tlocal[0],[-vlen]*3) v2 = [vlen]*3 #glEnable(GL_BLEND) #glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) #glColor4f(1,1,0,0.5) glColor3f(1,1,0) gldraw.hermite_curve(tlocal[1],v1,[0,0,0],v2,0.03*max(0.1,vectorops.norm(tlocal[1]))) #glDisable(GL_BLEND) glEnable(GL_DEPTH_TEST) #For some reason, cached drawing is causing OpenGL problems #when the frame is rapidly changing self.displayCache[0].draw(drawRaw,transform=tp, parameters = tlocal) #glPushMatrix() #glMultMatrixf(sum(zip(*se3.homogeneous(tp)),())) #drawRaw() #glPopMatrix() #write name if name != None: self.drawText(name,t[1]) elif isinstance(item,coordinates.Transform): #draw curve between frames t1 = item.source().worldCoordinates() if item.destination() != None: t2 = item.destination().worldCoordinates() else: t2 = se3.identity() d = vectorops.distance(t1[1],t2[1]) vlen = d*0.5 v1 = so3.apply(t1[0],[-vlen]*3) v2 = so3.apply(t2[0],[vlen]*3) def drawRaw(): glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glColor3f(1,1,1) gldraw.hermite_curve(t1[1],v1,t2[1],v2,0.03) glEnable(GL_DEPTH_TEST) #write name at curve self.displayCache[0].draw(drawRaw,transform=None,parameters = (t1,t2)) if name != None: self.drawText(name,spline.hermite_eval(t1[1],v1,t2[1],v2,0.5)) elif isinstance(item,coordinates.Group): pass elif isinstance(item,ContactPoint): def drawRaw(): glDisable(GL_LIGHTING) glEnable(GL_POINT_SMOOTH) glPointSize(self.attributes.get("size",5.0)) l = self.attributes.get("length",0.05) glColor4f(*self.attributes.get("color",[1,0.5,0,1])) glBegin(GL_POINTS) glVertex3f(0,0,0) glEnd() glBegin(GL_LINES) glVertex3f(0,0,0) glVertex3f(l,0,0) glEnd() self.displayCache[0].draw(drawRaw,[so3.canonical(item.n),item.x]) elif isinstance(item,Hold): pass else: try: itypes = objectToVisType(item,world) except: print "visualization.py: Unsupported object type",item,"of type:",item.__class__.__name__ return if itypes == None: print "Unable to convert item",item,"to drawable" return elif itypes == 'Config': if world: robot = world.robot(0) if not self.useDefaultAppearance: oldAppearance = [robot.link(i).appearance().clone() for i in xrange(robot.numLinks())] for i in xrange(robot.numLinks()): if self.customAppearance is not None: robot.link(i).appearance().set(self.customAppearance) elif "color" in self.attributes: robot.link(i).appearance().setColor(*self.attributes["color"]) oldconfig = robot.getConfig() robot.setConfig(item) robot.drawGL() robot.setConfig(oldconfig) if not self.useDefaultAppearance: for (i,app) in enumerate(oldAppearance): robot.link(i).appearance().set(app) else: print "Unable to draw Config tiems without a world" elif itypes == 'Configs': if world: maxConfigs = self.attributes.get("maxConfigs",min(10,len(item))) robot = world.robot(0) if not self.useDefaultAppearance: oldAppearance = [robot.link(i).appearance().clone() for i in xrange(robot.numLinks())] for i in xrange(robot.numLinks()): if self.customAppearance is not None: robot.link(i).appearance().set(self.customAppearance) elif "color" in self.attributes: robot.link(i).appearance().setColor(*self.attributes["color"]) oldconfig = robot.getConfig() for i in xrange(maxConfigs): idx = int(i*len(item))/maxConfigs robot.setConfig(item[idx]) robot.drawGL() robot.setConfig(oldconfig) if not self.useDefaultAppearance: for (i,app) in enumerate(oldAppearance): robot.link(i).appearance().set(app) else: print "Unable to draw Configs items without a world" elif itypes == 'Vector3': def drawRaw(): glDisable(GL_LIGHTING) glEnable(GL_POINT_SMOOTH) glPointSize(self.attributes.get("size",5.0)) glColor4f(*self.attributes.get("color",[0,0,0,1])) glBegin(GL_POINTS) glVertex3f(0,0,0) glEnd() self.displayCache[0].draw(drawRaw,[so3.identity(),item]) if name != None: self.drawText(name,item) elif itypes == 'RigidTransform': def drawRaw(): fancy = self.attributes.get("fancy",False) if fancy: glEnable(GL_LIGHTING) else: glDisable(GL_LIGHTING) gldraw.xform_widget(se3.identity(),self.attributes.get("length",0.1),self.attributes.get("width",0.01),fancy=fancy) self.displayCache[0].draw(drawRaw,transform=item) if name != None: self.drawText(name,item[1]) elif itypes == 'IKGoal': if hasattr(item,'robot'): #need this to be built with a robot element. #Otherwise, can't determine the correct transforms robot = item.robot elif world: if world.numRobots() >= 1: robot = world.robot(0) else: robot = None else: robot = None if robot != None: link = robot.link(item.link()) dest = robot.link(item.destLink()) if item.destLink()>=0 else None while len(self.displayCache) < 3: self.displayCache.append(glcommon.CachedGLObject()) self.displayCache[1].name = self.name+" target position" self.displayCache[2].name = self.name+" curve" if item.numPosDims() != 0: lp,wp = item.getPosition() #set up parameters of connector p1 = se3.apply(link.getTransform(),lp) if dest != None: p2 = se3.apply(dest.getTransform(),wp) else: p2 = wp d = vectorops.distance(p1,p2) v1 = [0.0]*3 v2 = [0.0]*3 if item.numRotDims()==3: #full constraint R = item.getRotation() def drawRaw(): gldraw.xform_widget(se3.identity(),self.attributes.get("length",0.1),self.attributes.get("width",0.01)) t1 = se3.mul(link.getTransform(),(so3.identity(),lp)) t2 = (R,wp) if dest==None else se3.mul(dest.getTransform(),(R,wp)) self.displayCache[0].draw(drawRaw,transform=t1) self.displayCache[1].draw(drawRaw,transform=t2) vlen = d*0.1 v1 = so3.apply(t1[0],[-vlen]*3) v2 = so3.apply(t2[0],[vlen]*3) elif item.numRotDims()==0: #point constraint def drawRaw(): glDisable(GL_LIGHTING) glEnable(GL_POINT_SMOOTH) glPointSize(self.attributes.get("size",5.0)) glColor4f(*self.attributes.get("color",[0,0,0,1])) glBegin(GL_POINTS) glVertex3f(0,0,0) glEnd() self.displayCache[0].draw(drawRaw,transform=(so3.identity(),p1)) self.displayCache[1].draw(drawRaw,transform=(so3.identity(),p2)) #set up the connecting curve vlen = d*0.5 d = vectorops.sub(p2,p1) v1 = vectorops.mul(d,0.5) #curve in the destination v2 = vectorops.cross((0,0,0.5),d) else: #hinge constraint p = [0,0,0] d = [0,0,0] def drawRawLine(): glDisable(GL_LIGHTING) glEnable(GL_POINT_SMOOTH) glPointSize(self.attributes.get("size",5.0)) glColor4f(*self.attributes.get("color",[0,0,0,1])) glBegin(GL_POINTS) glVertex3f(*p) glEnd() glColor4f(*self.attributes.get("color",[0.5,0,0.5,1])) glLineWidth(self.attributes.get("width",3.0)) glBegin(GL_LINES) glVertex3f(*p) glVertex3f(*vectorops.madd(p,d,self.attributes.get("length",0.1))) glEnd() glLineWidth(1.0) ld,wd = item.getRotationAxis() p = lp d = ld self.displayCache[0].draw(drawRawLine,transform=link.getTransform(),parameters=(p,d)) p = wp d = wd self.displayCache[1].draw(drawRawLine,transform=dest.getTransform() if dest else se3.identity(),parameters=(p,d)) #set up the connecting curve d = vectorops.sub(p2,p1) v1 = vectorops.mul(d,0.5) #curve in the destination v2 = vectorops.cross((0,0,0.5),d) def drawConnection(): glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glColor3f(1,0.5,0) gldraw.hermite_curve(p1,v1,p2,v2,0.03*max(0.1,vectorops.distance(p1,p2))) #glBegin(GL_LINES) #glVertex3f(*p1) #glVertex3f(*p2) #glEnd() glEnable(GL_DEPTH_TEST) #TEMP for some reason the cached version sometimes gives a GL error self.displayCache[2].draw(drawConnection,transform=None,parameters = (p1,v1,p2,v2)) #drawConnection() if name != None: self.drawText(name,wp) else: wp = link.getTransform()[1] if item.numRotDims()==3: #full constraint R = item.getRotation() def drawRaw(): gldraw.xform_widget(se3.identity(),self.attributes.get("length",0.1),self.attributes.get("width",0.01)) self.displayCache[0].draw(drawRaw,transform=link.getTransform()) self.displayCache[1].draw(drawRaw,transform=se3.mul(link.getTransform(),(R,[0,0,0]))) elif item.numRotDims() > 0: #axis constraint d = [0,0,0] def drawRawLine(): glDisable(GL_LIGHTING) glColor4f(*self.attributes.get("color",[0.5,0,0.5,1])) glLineWidth(self.attributes.get("width",3.0)) glBegin(GL_LINES) glVertex3f(0,0,0) glVertex3f(*vectorops.mul(d,self.attributes.get("length",0.1))) glEnd() glLineWidth(1.0) ld,wd = item.getRotationAxis() d = ld self.displayCache[0].draw(drawRawLine,transform=link.getTransform(),parameters=d) d = wd self.displayCache[1].draw(drawRawLine,transform=(dest.getTransform()[0] if dest else so3.identity(),wp),parameters=d) else: #no drawing pass if name != None: self.drawText(name,wp) else: print "Unable to draw item of type",itypes #revert appearance if not self.useDefaultAppearance and hasattr(item,'appearance'): item.appearance().set(self.oldAppearance) def getBounds(self): """Returns a bounding box (bmin,bmax) or None if it can't be found""" if len(self.subAppearances)!=0: bb = aabb_create() for n,app in self.subAppearances.iteritems(): bb = aabb_expand(bb,app.getBounds()) return bb item = self.item if isinstance(item,coordinates.Point): return [item.worldCoordinates(),item.worldCoordinates()] elif isinstance(item,coordinates.Direction): T = item.frame().worldCoordinates() d = item.localCoordinates() L = self.attributes.get("length",0.1) return aabb_create(T[1],se3.apply(T,vectorops.mul(d,L))) elif isinstance(item,coordinates.Frame): T = item.worldCoordinates() L = self.attributes.get("length",0.1) return aabb_create(T[1],se3.apply(T,(L,0,0)),se3.apply(T,(0,L,0)),se3.apply(T,(0,0,L))) elif isinstance(item,ContactPoint): L = self.attributes.get("length",0.05) return aabb_create(item.x,vectorops.madd(item.x,item.n,L)) elif isinstance(item,WorldModel): pass elif hasattr(item,'geometry'): return item.geometry().getBB() elif isinstance(item,(str,VisPlot)): pass else: try: vtype = objectToVisType(item,None) if 'Vector3' == vtype: #assumed to be a point return (item,item) elif 'RigidTransform' == vtype: #assumed to be a rigid transform return (item[1],item[1]) except Exception: pass print "Empty bound for object",self.name,"type",self.item.__class__.__name__ return aabb_create() def getSubItem(self,path): if len(path) == 0: return self for k,v in self.subAppearances.iteritems(): if v.name == path[0]: try: return v.getSubItem(path[1:]) except ValueError,e: raise ValueError("Invalid sub-path specified "+str(path)+" at "+str(e)) raise ValueError("Invalid sub-item specified "+path[0]) def make_editor(self): if self.editor != None: return item = self.item if isinstance(item,coordinates.Point): res = PointPoser() res.set(self.item.worldCoordinates()) res.setAxes(self.item.frame().worldCoordinates()[0]) elif isinstance(item,coordinates.Direction): res = PointPoser() res.set(self.item.worldCoordinates()) res.setAxes(self.item.frame().worldCoordinates()[0]) elif isinstance(item,coordinates.Frame): res = TransformPoser() res.set(*self.item.worldCoordinates()) elif isinstance(self.item,RobotModel): res = RobotPoser(self.item) self.hidden = True elif isinstance(self.item,SubRobotModel): res = RobotPoser(self.item._robot) res.setActiveDofs(self.item.links); self.hidden = True elif isinstance(self.item,RigidObjectModel): res = ObjectPoser(self.item) elif isinstance(self.item,(list,tuple)): #determine if it's a rotation, transform, or point itype = objectToVisType(self.item,None) if itype == 'Vector3': res = PointPoser() res.set(self.item) elif itype == 'Matrix3': res = TransformPoser() res.enableRotation(True) res.enableTranslation(False) res.set(self.item) elif itype == 'RigidTransform': res = TransformPoser() res.enableRotation(True) res.enableTranslation(True) res.set(*self.item) else: print "VisAppearance.make_editor(): Warning, editor for object of type",itype,"not defined" return else: print "VisAppearance.make_editor(): Warning, editor for object of type",self.item.__class__.__name__,"not defined" return self.editor = res def update_editor(self,item_to_editor=False): for (name,item) in self.subAppearances.iteritems(): item.update_editor(item_to_editor) if self.editor == None: return item = self.item if item_to_editor: if isinstance(item,coordinates.Point): self.editor.set(self.item.worldCoordinates()) elif isinstance(item,coordinates.Direction): self.editor.set(self.item.worldCoordinates()) elif isinstance(item,coordinates.Frame): self.editor.set(*self.item.worldCoordinates()) elif isinstance(self.item,RobotModel): self.editor.set(self.item.getConfig()) elif isinstance(self.item,SubRobotModel): self.editor.set(self.item.tofull(self.item.getConfig())) elif isinstance(self.item,RigidObjectModel): self.editor.set(*self.item.getTransform()) elif isinstance(self.item,(list,tuple)): itype = objectToVisType(self.item,None) if itype in ('Vector3','Matrix3'): self.editor.set(self.item) elif itype == 'RigidTransform': self.editor.set(*self.item) else: raise RuntimeError("Uh... unsupported type with an editor?") else: if not self.editor.hasFocus(): return if isinstance(item,coordinates.Point): self.item._localCoordinates = se3.apply(se3.inv(self.item._frame.worldCoordinates()),self.editor.get()) elif isinstance(item,coordinates.Direction): self.item._localCoordinates = se3.apply(se3.inv(self.item._frame.worldCoordinates()),self.editor.get()) elif isinstance(item,coordinates.Frame): self.item._worldCoordinates = self.editor.get() self.item._relativeCoordinates = se3.mul(se3.inv(self.item.parent().worldCoordinates()),self.editor.get()) #TODO: updating downstream frames? elif isinstance(self.item,RobotModel): self.item.setConfig(self.editor.getConditioned(self.item.getConfig())) elif isinstance(self.item,SubRobotModel): self.item.setConfig(self.item.fromfull(self.editor.get())) elif isinstance(self.item,RigidObjectModel): self.item.setTransform(*self.editor.get()) elif isinstance(self.item,(tuple,list)): def setList(a,b): if isinstance(a,(list,tuple)) and isinstance(b,(list,tuple)): if len(a) == len(b): for i in xrange(len(a)): if not setList(a[i],b[i]): if isinstance(a,list): a[i] = b[i] else: return False return True return False v = self.editor.get() if not setList(self.item,v): self.item = v elif isinstance(self.item,tuple): print "Edited a tuple... maybe a point or an xform? can't actually edit" self.item = self.editor.get() else: raise RuntimeError("Uh... unsupported type with an editor?") def remove_editor(self): self.editor = None self.hidden = False class VisualizationPlugin(glcommon.GLWidgetPlugin): def __init__(self): glcommon.GLWidgetPlugin.__init__(self) self.items = {} self.labels = [] self.t = time.time() self.startTime = self.t self.animating = True self.currentAnimationTime = 0 self.doRefresh = False def initialize(self): #keep or refresh display lists? #self._clearDisplayLists() return glcommon.GLWidgetPlugin.initialize(self) def addLabel(self,text,point,color): self.labels.append((text,point,color)) def display(self): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.display(self) self.labels = [] world = self.items.get('world',None) if world != None: world=world.item for (k,v) in self.items.iteritems(): v.widget = self v.swapDrawConfig() v.draw(world) v.swapDrawConfig() v.widget = None #allows garbage collector to delete these objects #cluster label points pointTolerance = self.view.camera.dist*0.03 pointHash = {} for (text,point,color) in self.labels: index = tuple([int(x/pointTolerance) for x in point]) try: pointHash[index][1].append((text,color)) except KeyError: pointHash[index] = [point,[(text,color)]] for (p,items) in pointHash.itervalues(): self._drawLabelRaw(p,*zip(*items)) _globalLock.release() def display_screen(self): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.display_screen(self) cx = 20 cy = 20 glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) for (k,v) in self.items.iteritems(): if isinstance(v.item,VisPlot): pos = v.attributes.get('position',None) duration = v.attributes.get('duration',5.) vrange = v.attributes.get('range',(None,None)) w,h = v.attributes.get('size',(200,150)) if pos is None: v.item.render(self.window,cx,cy,w,h,duration,vrange[0],vrange[1]) cy += h+18 else: x = pos[0] y = pos[1] if x < 0: x = self.view.w + x if y < 0: y = self.view.h + y v.item.render(self.window,x,y,w,h,duration,vrange[0],vrange[1]) for (k,v) in self.items.iteritems(): if isinstance(v.item,str): pos = v.attributes.get('position',None) col = v.attributes.get('color',(0,0,0)) size = v.attributes.get('size',12) if pos is None: #draw at console self.window.draw_text((cx,cy+size),v.item,size,col) cy += (size*15)/10 elif len(pos)==2: x = pos[0] y = pos[1] if x < 0: x = self.view.w + x if y < 0: y = self.view.h + y self.window.draw_text((x,y+size),v.item,size,col) glEnable(GL_DEPTH_TEST) _globalLock.release() def reshapefunc(self,w,h): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.reshapefunc(self,w,h) _globalLock.release() def keyboardfunc(self,c,x,y): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.keyboardfunc(self,c,x,y) _globalLock.release() def keyboardupfunc(self,c,x,y): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.keyboardupfunc(self,c,x,y) _globalLock.release() def mousefunc(self,button,state,x,y): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.mousefunc(self,button,state,x,y) _globalLock.release() def motionfunc(self,x,y,dx,dy): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.motionfunc(self,x,y,dx,dy) _globalLock.release() def eventfunc(self,type,args=""): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.eventfunc(self,type,args) _globalLock.release() def closefunc(self): global _globalLock _globalLock.acquire() glcommon.GLWidgetPlugin.closefunc(self) _globalLock.release() def _drawLabelRaw(self,point,textList,colorList): #assert not self.makingDisplayList,"drawText must be called outside of display list" assert self.window != None for i,(text,c) in enumerate(zip(textList,colorList)): if i+1 < len(textList): text = text+"," projpt = self.view.project(point,clip=False) if projpt[2] > self.view.clippingplanes[0]: d = float(12)/float(self.view.w)*projpt[2]*0.7 point = vectorops.add(point,so3.apply(so3.inv(self.view.camera.matrix()[0]),(0,-d,0))) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glColor3f(*c) self.draw_text(point,text,size=12) glEnable(GL_DEPTH_TEST) def _clearDisplayLists(self): for i in self.items.itervalues(): i.clearDisplayLists() def idle(self): global _globalLock _globalLock.acquire() oldt = self.t self.t = time.time() if self.animating: self.currentAnimationTime += (self.t - oldt) for (k,v) in self.items.iteritems(): #do animation updates v.updateAnimation(self.currentAnimationTime) for (k,v) in self.items.iteritems(): #do other updates v.updateTime(self.t-self.startTime) _globalLock.release() return False def getItem(self,item_name): """Returns an VisAppearance according to the given name or path""" if isinstance(item_name,(list,tuple)): components = item_name if len(components)==1: return self.getItem(components[0]) if components[0] not in self.items: raise ValueError("Invalid top-level item specified: "+item_name) return self.items[components[0]].getSubItem(components[1:]) if item_name in self.items: return self.items[item_name] def dirty(self,item_name='all'): """Marks an item or everything as dirty, forcing a deep redraw.""" global _globalLock _globalLock.acquire() if item_name == 'all': if (name,itemvis) in self.items.iteritems(): itemvis.markChanged() else: self.getItem(item_name).markChanged() _globalLock.release() def clear(self): """Clears the visualization world""" global _globalLock _globalLock.acquire() for (name,itemvis) in self.items.iteritems(): itemvis.destroy() self.items = {} _globalLock.release() def clearText(self): """Clears all text in the visualization.""" global _globalLock _globalLock.acquire() del_items = [] for (name,itemvis) in self.items.iteritems(): if isinstance(itemvis.item,str): itemvis.destroy() del_items.append(name) for n in del_items: del self.items[n] _globalLock.release() def listItems(self,root=None,indent=0): """Prints out all items in the visualization world.""" if root == None: for name,value in self.items.iteritems(): self.listItems(value,indent) else: if isinstance(root,str): root = self.getItem(root) if indent > 0: print " "*(indent-1), print root.name for n,v in root.subAppearances.iteritems(): self.listItems(v,indent+2) def add(self,name,item,keepAppearance=False): """Adds a named item to the visualization world. If the item already exists, the appearance information will be reinitialized if keepAppearance=False (default) or be kept if keepAppearance=True.""" global _globalLock assert not isinstance(name,(list,tuple)),"Cannot add sub-path items" _globalLock.acquire() if keepAppearance and name in self.items: self.items[name].setItem(item) else: #need to erase prior item visualizer if name in self.items: self.items[name].destroy() app = VisAppearance(item,name) self.items[name] = app _globalLock.release() #self.refresh() def animate(self,name,animation,speed=1.0,endBehavior='loop'): global _globalLock _globalLock.acquire() if hasattr(animation,'__iter__'): #a list of milestones -- loop through them with 1s delay print "visualization.animate(): Making a Trajectory with unit durations between",len(animation),"milestones" animation = Trajectory(range(len(animation)),animation) if isinstance(animation,HermiteTrajectory): animation = animation.configTrajectory() item = self.getItem(name) item.animation = animation item.animationStartTime = self.currentAnimationTime item.animationSpeed = speed item.animationEndBehavior = endBehavior item.markChanged() _globalLock.release() def pauseAnimation(self,paused=True): global _globalLock _globalLock.acquire() self.animating = not paused _globalLock.release() def stepAnimation(self,amount): global _globalLock _globalLock.acquire() self.currentAnimationTime += amount self.doRefresh = True _globalLock.release() def animationTime(self,newtime=None): global _globalLock if self==None: print "Visualization disabled" return 0 if newtime != None: _globalLock.acquire() self.currentAnimationTime = newtime _globalLock.release() return self.currentAnimationTime def remove(self,name): global _globalLock _globalLock.acquire() assert name in self.items,"Can only remove top level objects from visualization, try hide() instead" item = self.getItem(name) item.destroy() del self.items[name] self.doRefresh = True _globalLock.release() def getItemConfig(self,name): global _globalLock _globalLock.acquire() res = config.getConfig(self.getItem(name).item) _globalLock.release() return res def setItemConfig(self,name,value): global _globalLock _globalLock.acquire() item = self.getItem(name) if isinstance(item.item,(list,tuple,str)): item.item = value else: config.setConfig(item.item,value) if item.editor: item.update_editor(item_to_editor = True) self.doRefresh = True _globalLock.release() def hideLabel(self,name,hidden=True): global _globalLock _globalLock.acquire() item = self.getItem(name) item.attributes["text_hidden"] = hidden item.markChanged() self.doRefresh = True _globalLock.release() def edit(self,name,doedit=True): global _globalLock _globalLock.acquire() obj = self.getItem(name) if obj == None: _globalLock.release() raise ValueError("Object "+name+" does not exist in visualization") if doedit: obj.make_editor() if obj.editor: self.klamptwidgetmaster.add(obj.editor) else: if obj.editor: self.klamptwidgetmaster.remove(obj.editor) obj.remove_editor() self.doRefresh = True _globalLock.release() def widgetchangefunc(self,edit): """Called by GLWidgetPlugin on any widget change""" for name,item in self.items.iteritems(): item.update_editor() def hide(self,name,hidden=True): global _globalLock _globalLock.acquire() self.getItem(name).hidden = hidden self.doRefresh = True _globalLock.release() def addPlotItem(self,plotname,itemname): global _globalLock _globalLock.acquire() plot = self.getItem(plotname) assert plot != None and isinstance(plot.item,VisPlot),(plotname+" is not a valid plot") plot = plot.item for i in plot.items: assert i.name != itemname,(str(itemname)+" is already in the plot "+plotname) item = self.getItem(itemname) assert item != None,(str(itemname)+" is not a valid item") plot.items.append(VisPlotItem(itemname,item)) _globalLock.release() def logPlot(self,plotname,itemname,value): global _globalLock _globalLock.acquire() customIndex = -1 plot = self.getItem(plotname) assert plot != None and isinstance(plot.item,VisPlot),(plotname+" is not a valid plot") compress = plot.attributes.get('compress',_defaultCompressThreshold) plot = plot.item for i,item in enumerate(plot.items): if len(item.name)==0: customIndex = i if customIndex < 0: customIndex = len(plot.items) plot.items.append(VisPlotItem('',None)) plot.items[customIndex].compressThreshold = compress plot.items[customIndex].customUpdate(itemname,self.t - self.startTime,value) _globalLock.release() def logPlotEvent(self,plotname,eventname,color): global _globalLock _globalLock.acquire() plot = self.getItem(plotname) assert plot != None and isinstance(plot.item,VisPlot),(plotname+" is not a valid plot") plot.item.addEvent(eventname,self.t-self.startTime,color) _globalLock.release() def hidePlotItem(self,plotname,itemname,hidden=True): global _globalLock _globalLock.acquire() plot = self.getItem(plotname) assert plot != None and isinstance(plot.item,VisPlot),plotname+" is not a valid plot" plot = plot.item identified = False if isinstance(itemname,(tuple,list)): for i in plot.items: if i.name == itemname[0]: assert itemname[1] < len(i.hidden),("Invalid component index of item "+str(itemname[0])) identified = True i.hidden[itemname] = hidden else: for i in plot.items: if i.name == itemname: for j in xrange(len(i.hidden)): i.hidden[j] = hidden assert identified,("Invalid item "+str(itemname)+" specified in plot "+plotname) self.doRefresh = True _globalLock.release() def savePlot(self,plotname,fn): global _globalLock _globalLock.acquire() plot = self.getItem(plotname) assert plot != None and isinstance(plot.item,VisPlot),plotname+" is not a valid plot" plot = plot.item if fn != None: plot.beginSave(fn) else: plot.endSave(fn) _globalLock.release() def setAppearance(self,name,appearance): global _globalLock _globalLock.acquire() item = self.getItem(name) item.useDefaultAppearance = False item.customAppearance = appearance item.markChanged() self.doRefresh = True _globalLock.release() def setAttribute(self,name,attr,value): global _globalLock _globalLock.acquire() item = self.getItem(name) item.attributes[attr] = value if value==None: del item.attributes[attr] item.markChanged() self.doRefresh = True _globalLock.release() def revertAppearance(self,name): global _globalLock _globalLock.acquire() item = self.getItem(name) item.useDefaultApperance = True item.markChanged() self.doRefresh = True _globalLock.release() def setColor(self,name,r,g,b,a=1.0): global _globalLock _globalLock.acquire() item = self.getItem(name) item.attributes["color"] = [r,g,b,a] item.useDefaultAppearance = False item.markChanged() self.doRefresh = True _globalLock.release() def setDrawFunc(self,name,func): global _globalLock _globalLock.acquire() item = self.getItem(name) item.customDrawFunc = func self.doRefresh = True _globalLock.release() def autoFitCamera(self,scale=1.0): vp = None if self.window == None: global _frontend vp = _frontend.get_view() else: vp = self.window.get_view() try: autoFitViewport(vp,self.items.values()) vp.camera.dist /= scale except Exception as e: print "Unable to auto-fit camera" print e _vis = VisualizationPlugin() _frontend.setPlugin(_vis) #signals to visualization thread _quit = False _thread_running = False if _PyQtAvailable: from PyQt4 import QtGui #Qt specific startup #need to set up a QDialog and an QApplication class _MyDialog(QDialog): def __init__(self,windowinfo): QDialog.__init__(self) self.windowinfo = windowinfo glwidget = windowinfo.glwindow glwidget.setMinimumSize(640,480) glwidget.setMaximumSize(4000,4000) glwidget.setSizePolicy(QSizePolicy(QSizePolicy.Maximum,QSizePolicy.Maximum)) self.description = QLabel("Press OK to continue") self.description.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Fixed)) self.layout = QVBoxLayout(self) self.layout.addWidget(glwidget) self.layout.addWidget(self.description) self.buttons = QDialogButtonBox(QDialogButtonBox.Ok,Qt.Horizontal, self) self.buttons.accepted.connect(self.accept) self.layout.addWidget(self.buttons) self.setWindowTitle(windowinfo.name) glwidget.name = windowinfo.name def accept(self): global _globalLock _globalLock.acquire() self.windowinfo.glwindow.hide() _globalLock.release() print "#########################################" print "klampt.vis: Dialog accept" print "#########################################" return QDialog.accept(self) def reject(self): global _globalLock _globalLock.acquire() self.windowinfo.glwindow.hide() print "#########################################" print "klampt.vis: Dialog reject" print "#########################################" _globalLock.release() return QDialog.reject(self) class _MyWindow(QMainWindow): def __init__(self,windowinfo): QMainWindow.__init__(self) self.windowinfo = windowinfo self.glwidget = windowinfo.glwindow self.glwidget.setMinimumSize(self.glwidget.width,self.glwidget.height) self.glwidget.setMaximumSize(4000,4000) self.glwidget.setSizePolicy(QSizePolicy(QSizePolicy.Maximum,QSizePolicy.Maximum)) self.setCentralWidget(self.glwidget) self.setWindowTitle(windowinfo.name) self.glwidget.name = windowinfo.name self.saving_movie = False self.movie_timer = QTimer(self) self.movie_timer.timeout.connect(self.movie_update) self.movie_frame = 0 self.movie_time_last = 0 self.saving_html = False self.html_saver = None self.html_start_time = 0 self.html_timer = QTimer(self) self.html_timer.timeout.connect(self.html_update) #TODO: for action-free programs, don't add this... but this has to be detected after initializeGL()? mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&Actions') self.glwidget.actionMenu = fileMenu visMenu = mainMenu.addMenu('&Visualization') a = QtGui.QAction('Save world...', self) a.setStatusTip('Saves world to xml file') a.triggered.connect(self.save_world) visMenu.addAction(a) a = QtGui.QAction('Add to world...', self) a.setStatusTip('Adds an item to the world') a.triggered.connect(self.add_to_world) visMenu.addAction(a) a = QtGui.QAction('Save camera...', self) a.setStatusTip('Saves camera settings') a.triggered.connect(self.save_camera) visMenu.addAction(a) a = QtGui.QAction('Load camera...', self) a.setStatusTip('Loads camera settings') a.triggered.connect(self.load_camera) visMenu.addAction(a) a = QtGui.QAction('Start/stop movie output', self) a.setShortcut('Ctrl+M') a.setStatusTip('Starts / stops saving movie frames') a.triggered.connect(self.toggle_movie_mode) visMenu.addAction(a) a = QtGui.QAction('Start/stop html output', self) a.setShortcut('Ctrl+H') a.setStatusTip('Starts / stops saving animation to HTML file') a.triggered.connect(self.toggle_html_mode) visMenu.addAction(a) def getWorld(self): if not hasattr(self.glwidget.program,'plugins'): return None for p in self.glwidget.program.plugins: if hasattr(p,'world'): return p.world elif isinstance(p,VisualizationPlugin): world = p.items.get('world',None) if world != None: return world.item return None def getSimulator(self): if not hasattr(self.glwidget.program,'plugins'): return None for p in self.glwidget.program.plugins: if hasattr(p,'sim'): return p.sim return None def save_camera(self): if not hasattr(self.glwidget.program,'get_view'): print "Program does not appear to have a camera" return v = self.glwidget.program.get_view() fn = QFileDialog.getSaveFileName(caption="Viewport file (*.txt)",filter="Viewport file (*.txt);;All files (*.*)") if fn is None: return f = open(str(fn),'w') f.write("VIEWPORT\n") f.write("FRAME %d %d %d %d\n"%(v.x,v.y,v.w,v.h)) f.write("PERSPECTIVE 1\n") aspect = float(v.w)/float(v.h) rfov = v.fov*math.pi/180.0 scale = 1.0/(2.0*math.tan(rfov*0.5/aspect)*aspect) f.write("SCALE %f\n"%(scale,)) f.write("NEARPLANE %f\n"%(v.clippingplanes[0],)) f.write("FARPLANE %f\n"%(v.clippingplanes[0],)) f.write("CAMTRANSFORM ") mat = se3.homogeneous(v.camera.matrix()) f.write(' '.join(str(v) for v in sum(mat,[]))) f.write('\n') f.write("ORBITDIST %f\n"%(v.camera.dist,)) f.close() def load_camera(self): print "TODO" def save_world(self): w = self.getWorld() if w is None: print "Program does not appear to have a world" fn = QFileDialog.getSaveFileName(caption="World file (elements will be saved to folder)",filter="World file (*.xml);;All files (*.*)") if fn != None: w.saveFile(str(fn)) print "Saved to",fn,"and elements were saved to a directory of the same name." def add_to_world(self): w = self.getWorld() if w is None: print "Program does not appear to have a world" fn = QFileDialog.getOpenFileName(caption="World element",filter="Robot file (*.rob *.urdf);;Object file (*.obj);;Terrain file (*.env *.off *.obj *.stl *.wrl);;All files (*.*)") if fn != None: w.loadElement(str(fn)) for p in self.glwidget.program.plugins: if isinstance(p,VisualizationPlugin): p.getItem('world').setItem(w) def toggle_movie_mode(self): self.saving_movie = not self.saving_movie if self.saving_movie: self.movie_timer.start(33) sim = self.getSimulator() if sim != None: self.movie_time_last = sim.getTime() else: self.movie_timer.stop() dlg = QtGui.QInputDialog(self) dlg.setInputMode( QtGui.QInputDialog.TextInput) dlg.setLabelText("Command") dlg.setTextValue('ffmpeg -y -f image2 -i image%04d.png klampt_record.mp4') dlg.resize(500,100) ok = dlg.exec_() cmd = dlg.textValue() #(cmd,ok) = QtGui.QInputDialog.getText(self,"Process with ffmpeg?","Command", text='ffmpeg -y -f image2 -i image%04d.png klampt_record.mp4') if ok: import os,glob os.system(str(cmd)) print "Removing temporary files" for fn in glob.glob('image*.png'): os.remove(fn) def movie_update(self): sim = self.getSimulator() if sim != None: while sim.getTime() >= self.movie_time_last + 1.0/30.0: self.glwidget.program.save_screen('image%04d.png'%(self.movie_frame)) self.movie_frame += 1 self.movie_time_last += 1.0/30.0 else: self.glwidget.program.save_screen('image%04d.png'%(self.movie_frame)) self.movie_frame += 1 def toggle_html_mode(self): self.saving_html = not self.saving_html if self.saving_html: world = self.getSimulator() if world is None: world = self.getWorld() if world is None: print "There is no world in the current plugin, can't save" self.saving_html = False return fn = QFileDialog.getSaveFileName(caption="Save path HTML file to...",filter="HTML file (*.html);;All files (*.*)") if fn is None: self.saving_html = False return from ..io import html self.html_start_time = time.time() self.html_saver = html.HTMLSharePath(fn) self.html_saver.dt = 0.033; self.html_saver.start(world) self.html_timer.start(33) else: self.html_saver.end() self.html_timer.stop() def html_update(self): t = None if self.html_saver.sim == None: #t = time.time()-self.html_start_time t = self.html_saver.last_t + 0.034 self.html_saver.animate(t) def closeEvent(self,event): global _globalLock _globalLock.acquire() self.windowinfo.glwindow.hide() self.windowinfo.mode = 'hidden' self.windowinfo.glwindow.idlesleep() self.windowinfo.glwindow.setParent(None) if self.saving_movie: self.toggle_movie_mode() if self.saving_html: self.toggle_html_mode() print "#########################################" print "klampt.vis: Window close" print "#########################################" _globalLock.release() def _run_app_thread(): global _thread_running,_vis,_widget,_window,_quit,_showdialog,_showwindow,_globalLock _thread_running = True _GLBackend.initialize("Klamp't visualization") res = None while not _quit: _globalLock.acquire() for i,w in enumerate(_windows): if w.glwindow == None and w.mode != 'hidden': print "vis: creating GL window" w.glwindow = _GLBackend.createWindow(w.name) w.glwindow.setProgram(w.frontend) w.glwindow.setParent(None) w.glwindow.refresh() if w.doRefresh: if w.mode != 'hidden': w.glwindow.updateGL() w.doRefresh = False if w.doReload and w.glwindow != None: w.glwindow.setProgram(w.frontend) if w.guidata: w.guidata.setWindowTitle(w.name) w.guidata.glwidget = w.glwindow w.guidata.setCentralWidget(w.glwindow) w.doReload = False if w.mode == 'dialog': print "#########################################" print "klampt.vis: Dialog on window",i print "#########################################" if w.custom_ui == None: dlg = _MyDialog(w) else: dlg = w.custom_ui(w.glwindow) #need to cache the bastards to avoid deleting the GL object. Not sure why it's being kept around. #alldlgs.append(dlg) #here's the crash -- above line deleted the old dialog, which for some reason kills the widget if dlg != None: w.glwindow.show() w.glwindow.idlesleep(0) w.glwindow.refresh() w.glwindow.refresh() _globalLock.release() res = dlg.exec_() _globalLock.acquire() print "#########################################" print "klampt.vis: Dialog done on window",i print "#########################################" w.glwindow.hide() w.glwindow.setParent(None) w.glwindow.idlesleep() w.mode = 'hidden' if w.mode == 'shown' and w.guidata == None: print "#########################################" print "klampt.vis: Making window",i print "#########################################" if w.custom_ui == None: w.guidata = _MyWindow(w) else: w.guidata = w.custom_ui(w.glwindow) w.glwindow.show() w.glwindow.idlesleep(0) if w.mode == 'shown' and not w.guidata.isVisible(): print "#########################################" print "klampt.vis: Showing window",i print "#########################################" w.glwindow.show() w.glwindow.setParent(w.guidata) w.glwindow.idlesleep(0) w.guidata.show() if w.mode == 'hidden' and w.guidata != None: if w.guidata.isVisible(): print "#########################################" print "klampt.vis: Hiding window",i print "#########################################" w.glwindow.setParent(None) w.glwindow.idlesleep() w.glwindow.hide() w.guidata.hide() #prevent deleting the GL window w.glwindow.setParent(None) w.guidata = None _globalLock.release() _GLBackend.app.processEvents() time.sleep(0.001) print "Visualization thread closing..." for w in _windows: w.vis.clear() if w.glwindow: w.glwindow.close() _thread_running = False return res elif _GLUTAvailable: print "klampt.visualization: QT is not available, falling back to poorer" print "GLUT interface. Returning to another GLUT thread will not work" print "properly." print "" class GLUTHijacker(GLPluginProgram): def __init__(self,windowinfo): GLPluginProgram.__init__(self) self.windowinfo = windowinfo self.name = windowinfo.name self.view = windowinfo.frontend.view self.clearColor = windowinfo.frontend.clearColor self.actions = windowinfo.frontend.actions self.frontend = windowinfo.frontend self.inDialog = False self.hidden = False def initialize(self): self.frontend.window = self.window if not self.frontend.initialize(): return False GLPluginProgram.initialize(self) return True def display(self): global _globalLock _globalLock.acquire() self.frontend.display() _globalLock.release() return True def display_screen(self): global _globalLock _globalLock.acquire() self.frontend.display_screen() glColor3f(1,1,1) glRasterPos(20,50) gldraw.glutBitmapString(GLUT_BITMAP_HELVETICA_18,"(Do not close this window except to quit)") if self.inDialog: glColor3f(1,1,0) glRasterPos(20,80) gldraw.glutBitmapString(GLUT_BITMAP_HELVETICA_18,"In Dialog mode. Press 'Esc' to return to normal mode") else: glColor3f(1,1,0) glRasterPos(20,80) gldraw.glutBitmapString(GLUT_BITMAP_HELVETICA_18,"In Window mode. Press 'Esc' to hide window") _globalLock.release() def keyboardfunc(self,c,x,y): if ord(c)==27: if self.inDialog: print "Esc pressed, hiding dialog" self.inDialog = False else: print "Esc pressed, hiding window" global _globalLock _globalLock.acquire() self.windowinfo.mode = 'hidden' self.hidden = True glutHideWindow() _globalLock.release() return True else: return self.frontend.keyboardfunc(c,x,y) def keyboardupfunc(self,c,x,y): return self.frontend.keyboardupfunc(c,x,y) def motionfunc(self,x,y,dx,dy): return self.frontend.motionfunc(x,y,dx,dy) def mousefunc(self,button,state,x,y): return self.frontend.mousefunc(button,state,x,y) def idlefunc(self): global _quit,_showdialog global _globalLock _globalLock.acquire() if _quit: if bool(glutLeaveMainLoop): glutLeaveMainLoop() else: print "Not compiled with freeglut, can't exit main loop safely. Press Ctrl+C instead" raw_input() if self.hidden: print "hidden, waiting...",self.windowinfo.mode if self.windowinfo.mode == 'shown': print "Showing window" glutSetWindow(self.window.glutWindowID) glutShowWindow() self.hidden = False elif self.windowinfo.mode == 'dialog': print "Showing window in dialog mode" self.inDialog = True glutSetWindow(self.window.glutWindowID) glutShowWindow() self.hidden = False _globalLock.release() return self.frontend.idlefunc() def _run_app_thread(): global _thread_running,_vis,_old_glut_window,_quit,_windows import weakref _thread_running = True _GLBackend.initialize("Klamp't visualization") w = _GLBackend.createWindow("Klamp't visualization") hijacker = GLUTHijacker(_windows[0]) _windows[0].guidata = weakref.proxy(hijacker) w.setProgram(hijacker) _GLBackend.run() print "Visualization thread closing..." for w in _windows: w.vis.clear() _thread_running = False return def _kill(): global _quit _quit = True while _thread_running: time.sleep(0.01) _quit = False if _PyQtAvailable: from PyQt4 import QtCore class MyQThread(QtCore.QThread): def __init__(self,func,*args): self.func = func self.args = args QtCore.QThread.__init__(self) def run(self): self.func(*self.args) def _show(): global _windows,_current_window,_thread_running if len(_windows)==0: _windows.append(WindowInfo(_window_title,_frontend,_vis)) _current_window = 0 _windows[_current_window].mode = 'shown' _windows[_current_window].worlds = _current_worlds _windows[_current_window].active_worlds = _current_worlds[:] if not _thread_running: signal.signal(signal.SIGINT, signal.SIG_DFL) if _PyQtAvailable and False: #for some reason, QThread doesn't allow for mouse events to be posted? thread = MyQThread(_run_app_thread) thread.start() else: thread = Thread(target=_run_app_thread) thread.setDaemon(True) thread.start() time.sleep(0.1) def _hide(): global _windows,_current_window,_thread_running if _current_window == None: return _windows[_current_window].mode = 'hidden' def _dialog(): global __windows,_current_window,_thread_running if len(_windows)==0: _windows.append(WindowInfo(_window_title,_frontend,_vis,None)) _current_window = 0 if not _thread_running: signal.signal(signal.SIGINT, signal.SIG_DFL) thread = Thread(target=_run_app_thread) thread.setDaemon(True) thread.start() #time.sleep(0.1) _globalLock.acquire() assert _windows[_current_window].mode == 'hidden',"dialog() called inside dialog?" _windows[_current_window].mode = 'dialog' _windows[_current_window].worlds = _current_worlds _windows[_current_window].active_worlds = _current_worlds[:] _globalLock.release() while _windows[_current_window].mode == 'dialog': time.sleep(0.1) return def _set_custom_ui(func): global _windows,_current_window,_thread_running if len(_windows)==0: _windows.append(WindowInfo(_window_title,_frontend,_vis,None)) _current_window = 0 _windows[_current_window].custom_ui = func return def _onFrontendChange(): global _windows,_frontend,_window_title,_current_window,_thread_running if _current_window == None: return w = _windows[_current_window] w.doReload = True w.name = _window_title w.frontend = _frontend if w.glwindow: w.glwindow.reshape(_frontend.view.w,_frontend.view.h) if w.guidata and not _PyQtAvailable: w.guidata.frontend = _frontend _frontend.window = w.guidata.window def _refreshDisplayLists(item): if isinstance(item,WorldModel): for i in xrange(item.numRobots()): _refreshDisplayLists(item.robot(i)) for i in xrange(item.numRigidObjects()): _refreshDisplayLists(item.rigidObject(i)) for i in xrange(item.numTerrains()): _refreshDisplayLists(item.terrain(i)) elif isinstance(item,RobotModel): for i in xrange(item.numLinks()): _refreshDisplayLists(item.link(i)) elif hasattr(item,'appearance'): item.appearance().refresh(False) def _checkWindowCurrent(item): global _windows,_current_window,_world_to_window,_current_worlds if isinstance(item,int): if not all(w.index != item for w in _current_worlds): print "klampt.vis: item appears to be in a new world, but doesn't have a full WorldModel instance" if isinstance(item,WorldModel): #print "Worlds active in current window",_current_window,":",[w().index for w in _current_worlds] if all(item != w() for w in _current_worlds): #PyQt interface allows sharing display lists but GLUT does not. #refresh all worlds' display lists that will be shifted to the current window. for i,win in enumerate(_windows): #print "Window",i,"active worlds",[w().index for w in win.active_worlds] if any(item == w() for w in win.active_worlds): if not _PyQtAvailable: print "klampt.vis: world",item.index,"was shown in a different window, now refreshing display lists" _refreshDisplayLists(item) win.active_worlds.remove(weakref.ref(item)) _current_worlds.append(weakref.ref(item)) #print "klampt.vis: world added to the visualization's world (items:",[w().index for w in _current_worlds],")" #else: # print "klampt.vis: world",item,"is already in the current window's world" elif hasattr(item,'world'): _checkWindowCurrent(item.world)
hpbader42/Klampt
Python/klampt/vis/visualization.py
Python
bsd-3-clause
123,948
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of # its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 501ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. '''visualize morphologies''' from matplotlib.collections import LineCollection, PolyCollection from matplotlib.patches import Circle from mpl_toolkits.mplot3d.art3d import \ Line3DCollection # pylint: disable=relative-import import numpy as np from neurom import NeuriteType, geom from neurom._compat import zip from neurom.core import iter_neurites, iter_segments from neurom.core._soma import SomaCylinders from neurom.core.dataformat import COLS from neurom.core.types import tree_type_checker from neurom.morphmath import segment_radius from neurom.view._dendrogram import Dendrogram from . import common _LINEWIDTH = 1.2 _ALPHA = 0.8 _DIAMETER_SCALE = 1.0 TREE_COLOR = {NeuriteType.basal_dendrite: 'red', NeuriteType.apical_dendrite: 'purple', NeuriteType.axon: 'blue', NeuriteType.soma: 'black', NeuriteType.undefined: 'green'} def _plane2col(plane): '''take a string like 'xy', and return the indices from COLS.*''' planes = ('xy', 'yx', 'xz', 'zx', 'yz', 'zy') assert plane in planes, 'No such plane found! Please select one of: ' + str(planes) return (getattr(COLS, plane[0].capitalize()), getattr(COLS, plane[1].capitalize()), ) def _get_linewidth(tree, linewidth, diameter_scale): '''calculate the desired linewidth based on tree contents If diameter_scale exists, it is used to scale the diameter of each of the segments in the tree If diameter_scale is None, the linewidth is used. ''' if diameter_scale is not None and tree: linewidth = [2 * segment_radius(s) * diameter_scale for s in iter_segments(tree)] return linewidth def _get_color(treecolor, tree_type): """if treecolor set, it's returned, otherwise tree_type is used to return set colors""" if treecolor is not None: return treecolor return TREE_COLOR.get(tree_type, 'green') def plot_tree(ax, tree, plane='xy', diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Plots a 2d figure of the tree's segments Args: ax(matplotlib axes): on what to plot tree(neurom.core.Tree or neurom.core.Neurite): plotted tree plane(str): Any pair of 'xyz' diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values Note: If the tree contains one single point the plot will be empty since no segments can be constructed. ''' plane0, plane1 = _plane2col(plane) segs = [((s[0][plane0], s[0][plane1]), (s[1][plane0], s[1][plane1])) for s in iter_segments(tree)] linewidth = _get_linewidth(tree, diameter_scale=diameter_scale, linewidth=linewidth) color = _get_color(color, tree.type) collection = LineCollection(segs, color=color, linewidth=linewidth, alpha=alpha) ax.add_collection(collection) def plot_soma(ax, soma, plane='xy', soma_outline=True, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Generates a 2d figure of the soma. Args: ax(matplotlib axes): on what to plot soma(neurom.core.Soma): plotted soma plane(str): Any pair of 'xyz' diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plane0, plane1 = _plane2col(plane) color = _get_color(color, tree_type=NeuriteType.soma) if isinstance(soma, SomaCylinders): plane0, plane1 = _plane2col(plane) for start, end in zip(soma.points, soma.points[1:]): common.project_cylinder_onto_2d(ax, (plane0, plane1), start=start[COLS.XYZ], end=end[COLS.XYZ], start_radius=start[COLS.R], end_radius=end[COLS.R], color=color, alpha=alpha) else: if soma_outline: ax.add_artist(Circle(soma.center, soma.radius, color=color, alpha=alpha)) else: plane0, plane1 = _plane2col(plane) points = [(p[plane0], p[plane1]) for p in soma.iter()] if points: points.append(points[0]) # close the loop ax.plot(points, color=color, alpha=alpha, linewidth=linewidth) ax.set_xlabel(plane[0]) ax.set_ylabel(plane[1]) bounding_box = geom.bounding_box(soma) ax.dataLim.update_from_data_xy(np.vstack(([bounding_box[0][plane0], bounding_box[0][plane1]], [bounding_box[1][plane0], bounding_box[1][plane1]])), ignore=False) # pylint: disable=too-many-arguments def plot_neuron(ax, nrn, neurite_type=NeuriteType.all, plane='xy', soma_outline=True, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Plots a 2D figure of the neuron, that contains a soma and the neurites Args: ax(matplotlib axes): on what to plot neurite_type(NeuriteType): an optional filter on the neurite type nrn(neuron): neuron to be plotted soma_outline(bool): should the soma be drawn as an outline plane(str): Any pair of 'xyz' diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plot_soma(ax, nrn.soma, plane=plane, soma_outline=soma_outline, linewidth=linewidth, color=color, alpha=alpha) for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)): plot_tree(ax, neurite, plane=plane, diameter_scale=diameter_scale, linewidth=linewidth, color=color, alpha=alpha) ax.set_title(nrn.name) ax.set_xlabel(plane[0]) ax.set_ylabel(plane[1]) def _update_3d_datalim(ax, obj): '''unlike w/ 2d Axes, the dataLim isn't set by collections, so it has to be updated manually''' min_bounding_box, max_bounding_box = geom.bounding_box(obj) xy_bounds = np.vstack((min_bounding_box[:COLS.Z], max_bounding_box[:COLS.Z])) ax.xy_dataLim.update_from_data_xy(xy_bounds, ignore=False) z_bounds = np.vstack(((min_bounding_box[COLS.Z], min_bounding_box[COLS.Z]), (max_bounding_box[COLS.Z], max_bounding_box[COLS.Z]))) ax.zz_dataLim.update_from_data_xy(z_bounds, ignore=False) def plot_tree3d(ax, tree, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Generates a figure of the tree in 3d. If the tree contains one single point the plot will be empty \ since no segments can be constructed. Args: ax(matplotlib axes): on what to plot tree(neurom.core.Tree or neurom.core.Neurite): plotted tree diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in iter_segments(tree)] linewidth = _get_linewidth(tree, diameter_scale=diameter_scale, linewidth=linewidth) color = _get_color(color, tree.type) collection = Line3DCollection(segs, color=color, linewidth=linewidth, alpha=alpha) ax.add_collection3d(collection) _update_3d_datalim(ax, tree) def plot_soma3d(ax, soma, color=None, alpha=_ALPHA): '''Generates a 3d figure of the soma. Args: ax(matplotlib axes): on what to plot soma(neurom.core.Soma): plotted soma color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' color = _get_color(color, tree_type=NeuriteType.soma) if isinstance(soma, SomaCylinders): for start, end in zip(soma.points, soma.points[1:]): common.plot_cylinder(ax, start=start[COLS.XYZ], end=end[COLS.XYZ], start_radius=start[COLS.R], end_radius=end[COLS.R], color=color, alpha=alpha) else: common.plot_sphere(ax, center=soma.center[COLS.XYZ], radius=soma.radius, color=color, alpha=alpha) # unlike w/ 2d Axes, the dataLim isn't set by collections, so it has to be updated manually _update_3d_datalim(ax, soma) def plot_neuron3d(ax, nrn, neurite_type=NeuriteType.all, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): ''' Generates a figure of the neuron, that contains a soma and a list of trees. Args: ax(matplotlib axes): on what to plot nrn(neuron): neuron to be plotted neurite_type(NeuriteType): an optional filter on the neurite type diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plot_soma3d(ax, nrn.soma, color=color, alpha=alpha) for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)): plot_tree3d(ax, neurite, diameter_scale=diameter_scale, linewidth=linewidth, color=color, alpha=alpha) ax.set_title(nrn.name) def _generate_collection(group, ax, ctype, colors): '''Render rectangle collection''' color = TREE_COLOR[ctype] # generate segment collection collection = PolyCollection(group, closed=False, antialiaseds=True, edgecolors='face', facecolors=color) # add it to the axes ax.add_collection(collection) # dummy plot for the legend if color not in colors: label = str(ctype).replace('NeuriteType.', '').replace('_', ' ').capitalize() ax.plot((0., 0.), (0., 0.), c=color, label=label) colors.add(color) def _render_dendrogram(dnd, ax, displacement): '''Renders dendrogram''' # set of unique colors that reflect the set of types of the neurites colors = set() for n, (indices, ctype) in enumerate(zip(dnd.groups, dnd.types)): # slice rectangles array for the current neurite group = dnd.data[indices[0]:indices[1]] if n > 0: # displace the neurites by half of their maximum x dimension # plus half of the previous neurite's maxmimum x dimension displacement += 0.5 * (dnd.dims[n - 1][0] + dnd.dims[n][0]) # arrange the trees without overlapping with each other group += (displacement, 0.) # create the polygonal collection of the dendrogram # segments _generate_collection(group, ax, ctype, colors) soma_square = dnd.soma if soma_square is not None: _generate_collection((soma_square + (displacement / 2., 0.),), ax, NeuriteType.soma, colors) ax.plot((displacement / 2., displacement), (0., 0.), color='k') ax.plot((0., displacement / 2.), (0., 0.), color='k') return displacement def plot_dendrogram(ax, obj, show_diameters=True): '''Dendrogram of `obj` Args: obj: Neuron or tree \ neurom.Neuron, neurom.Tree show_diameters : boolean \ Determines if node diameters will \ be show or not. ''' # create dendrogram and generate rectangle collection dnd = Dendrogram(obj, show_diameters=show_diameters) dnd.generate() # render dendrogram and take into account neurite displacement which # starts as zero. It is important to avoid overlapping of neurites # and to determine tha limits of the figure. _render_dendrogram(dnd, ax, 0.) ax.set_title('Morphology Dendrogram') ax.set_xlabel('micrometers (um)') ax.set_ylabel('micrometers (um)') ax.set_aspect('auto') ax.legend()
lidakanari/NeuroM
neurom/view/view.py
Python
bsd-3-clause
14,676
<?php // ##Reauthorization Sample // This sample code demonstrates how you can reauthorize a PayPal // account payment. // API used: v1/payments/authorization/{authorization_id}/reauthorize /** @var Authorization $authorization */ $authorization = require 'AuthorizePayment.php'; use PayPal\Api\Authorization; use PayPal\Api\Amount; // ### Reauthorization // Reauthorization is available only for PayPal account payments // and not for credit card payments. // You can reauthorize a payment only once 4 to 29 // days after the 3-day honor period for the original authorization // has expired. try { $amount = new Amount(); $amount->setCurrency("USD"); $amount->setTotal(1); // ### Reauthorize with amount being reauthorized $authorization->setAmount($amount); $reAuthorization = $authorization->reauthorize($apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printError("Reauthorize Payment", "Payment", null, null, $ex); exit(1); } // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printResult("Reauthorize Payment", "Payment", $authorization->getId(), null, $reAuthorization);
frankpaul142/aurasur
vendor/paypal/rest-api-sdk-php/sample/payments/Reauthorization.php
PHP
bsd-3-clause
1,260
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //var MODAL = $("#modalProducto"); var URL = Define.URL_BASE; window.onload=function(){ //toastr.error("Ingresaaaaaaaaa"); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'validar' }; httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; function redireccionar(url_direccionar){ setTimeout(function(){ location.href=url_direccionar; }, 5000); //tiempo expresado en milisegundos } $("#olvide").delegate('#semeolvido', 'click', function () {//buscar pedido en bd var usuario_a_buscar = $("#username").val(); var url_ajax = URL + Define.URL_OLVIDE; //le decimos a qué url tiene que mandar la información var data = { action: 'semeolvido', username: usuario_a_buscar }; if(!SOLICITUSEMEOLVIDO){ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.itemsCount != 0){ SOLICITUSEMEOLVIDO = true; url_direccionar = Define.URL_BASE + "cuenta/login" toastr.warning("Hola " + data.data[0].usuarioNombres + ", se te enviará la nueva contraseña al correo: " + data.data[0].usuarioEmail); redireccionar(url_direccionar); }else{ toastr.error("No existe una cuenta asociada a ese nombre de usuario."); } }); }else{ toastr.error("La solicitud ya fue enviada, revisa tu correo."); }; }); $("#login").delegate('#ingresoLogin', 'click', function () {//validar usuario var url_ajax = URL + Define.URL_LOGIN; //le decimos a qué url tiene que mandar la información var usuario_a_buscar = $("#name").val(); var passwd_user = $("#pswd").val(); var recordame_ve = false; if($('#recuerdame').is(':checked')){ recordame_ve = true; } alert(recordame_ve); var data = { action: 'ingresar', username: usuario_a_buscar, password_user: passwd_user, recuerdame: recordame_ve }; if(usuario_a_buscar == '' || passwd_user == ''){ toastr.error("Username y/o contraseña vacíos, por favor digite un valor"); }else{ httpPetition.ajxPost(url_ajax, data, function (data) { if(data.mensaje == "Ok"){ toastr.success("Bienvenido amante del cafe, esto es Coffee Market House"); redireccionar(Define.URL_BASE + "socialcoffee"); } }); }; });
jhonsfran/Coffee_market
public/js/Controllers/socialcoffee.js
JavaScript
bsd-3-clause
2,907
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/infobar_gtk.h" #include <gtk/gtk.h> #include "app/gfx/gtk_util.h" #include "base/string_util.h" #include "chrome/browser/gtk/custom_button.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/browser/gtk/infobar_container_gtk.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/common/gtk_util.h" #include "chrome/common/notification_service.h" namespace { const double kBackgroundColorTop[3] = {255.0 / 255.0, 242.0 / 255.0, 183.0 / 255.0}; const double kBackgroundColorBottom[3] = {250.0 / 255.0, 230.0 / 255.0, 145.0 / 255.0}; // The total height of the info bar. const int kInfoBarHeight = 37; // Pixels between infobar elements. const int kElementPadding = 5; // Extra padding on either end of info bar. const int kLeftPadding = 5; const int kRightPadding = 5; static gboolean OnBackgroundExpose(GtkWidget* widget, GdkEventExpose* event, gpointer unused) { const int height = widget->allocation.height; cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_pattern_t* pattern = cairo_pattern_create_linear(0, 0, 0, height); cairo_pattern_add_color_stop_rgb( pattern, 0.0, kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]); cairo_pattern_add_color_stop_rgb( pattern, 1.0, kBackgroundColorBottom[0], kBackgroundColorBottom[1], kBackgroundColorBottom[2]); cairo_set_source(cr, pattern); cairo_paint(cr); cairo_pattern_destroy(pattern); cairo_destroy(cr); return FALSE; } } // namespace InfoBar::InfoBar(InfoBarDelegate* delegate) : container_(NULL), delegate_(delegate), theme_provider_(NULL) { // Create |hbox_| and pad the sides. hbox_ = gtk_hbox_new(FALSE, kElementPadding); GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1); gtk_alignment_set_padding(GTK_ALIGNMENT(padding), 0, 0, kLeftPadding, kRightPadding); GtkWidget* bg_box = gtk_event_box_new(); gtk_widget_set_app_paintable(bg_box, TRUE); g_signal_connect(bg_box, "expose-event", G_CALLBACK(OnBackgroundExpose), NULL); gtk_container_add(GTK_CONTAINER(padding), hbox_); gtk_container_add(GTK_CONTAINER(bg_box), padding); // The -1 on the kInfoBarHeight is to account for the border. gtk_widget_set_size_request(bg_box, -1, kInfoBarHeight - 1); border_bin_.Own(gtk_util::CreateGtkBorderBin(bg_box, NULL, 0, 1, 0, 0)); // Add the icon on the left, if any. SkBitmap* icon = delegate->GetIcon(); if (icon) { GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon); GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf); g_object_unref(pixbuf); gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0); } // TODO(erg): GTK theme the info bar. close_button_.reset(CustomDrawButton::CloseButton(NULL)); gtk_util::CenterWidgetInHBox(hbox_, close_button_->widget(), true, 0); g_signal_connect(close_button_->widget(), "clicked", G_CALLBACK(OnCloseButton), this); slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(), SlideAnimatorGtk::DOWN, 0, true, true, this)); // We store a pointer back to |this| so we can refer to it from the infobar // container. g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this); } InfoBar::~InfoBar() { border_bin_.Destroy(); } GtkWidget* InfoBar::widget() { return slide_widget_->widget(); } void InfoBar::AnimateOpen() { slide_widget_->Open(); if (border_bin_->window) gdk_window_lower(border_bin_->window); } void InfoBar::Open() { slide_widget_->OpenWithoutAnimation(); if (border_bin_->window) gdk_window_lower(border_bin_->window); } void InfoBar::AnimateClose() { slide_widget_->Close(); } void InfoBar::Close() { if (delegate_) { delegate_->InfoBarClosed(); delegate_ = NULL; } delete this; } bool InfoBar::IsAnimating() { return slide_widget_->IsAnimating(); } void InfoBar::RemoveInfoBar() const { container_->RemoveDelegate(delegate_); } void InfoBar::Closed() { Close(); } void InfoBar::SetThemeProvider(GtkThemeProvider* theme_provider) { if (theme_provider_) { NOTREACHED(); return; } theme_provider_ = theme_provider; registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); UpdateBorderColor(); } void InfoBar::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { UpdateBorderColor(); } void InfoBar::UpdateBorderColor() { GdkColor border_color = theme_provider_->GetBorderColor(); gtk_widget_modify_bg(border_bin_.get(), GTK_STATE_NORMAL, &border_color); } // static void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) { if (info_bar->delegate_) info_bar->delegate_->InfoBarDismissed(); info_bar->RemoveInfoBar(); } // AlertInfoBar ---------------------------------------------------------------- class AlertInfoBar : public InfoBar { public: explicit AlertInfoBar(AlertInfoBarDelegate* delegate) : InfoBar(delegate) { std::wstring text = delegate->GetMessageText(); GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str()); // We want the label to be horizontally shrinkable, so that the Chrome // window can be resized freely even with a very long message. gtk_widget_set_size_request(label, 0, -1); gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack); gtk_box_pack_start(GTK_BOX(hbox_), label, TRUE, TRUE, 0); gtk_widget_show_all(border_bin_.get()); } }; // LinkInfoBar ----------------------------------------------------------------- class LinkInfoBar : public InfoBar { public: explicit LinkInfoBar(LinkInfoBarDelegate* delegate) : InfoBar(delegate) { size_t link_offset; std::wstring display_text = delegate->GetMessageTextWithOffset(&link_offset); std::wstring link_text = delegate->GetLinkText(); // Create the link button. GtkWidget* link_button = gtk_chrome_link_button_new(WideToUTF8(link_text).c_str()); gtk_chrome_link_button_set_use_gtk_theme( GTK_CHROME_LINK_BUTTON(link_button), FALSE); g_signal_connect(link_button, "clicked", G_CALLBACK(OnLinkClick), this); gtk_util::SetButtonTriggersNavigation(link_button); GtkWidget* hbox = gtk_hbox_new(FALSE, 0); // We want the link to be horizontally shrinkable, so that the Chrome // window can be resized freely even with a very long link. gtk_widget_set_size_request(hbox, 0, -1); gtk_box_pack_start(GTK_BOX(hbox_), hbox, TRUE, TRUE, 0); // If link_offset is npos, we right-align the link instead of embedding it // in the text. if (link_offset == std::wstring::npos) { gtk_box_pack_end(GTK_BOX(hbox), link_button, FALSE, FALSE, 0); GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str()); // In order to avoid the link_button and the label overlapping with each // other, we make the label shrinkable. gtk_widget_set_size_request(label, 0, -1); gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack); gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0); } else { GtkWidget* initial_label = gtk_label_new( WideToUTF8(display_text.substr(0, link_offset)).c_str()); GtkWidget* trailing_label = gtk_label_new( WideToUTF8(display_text.substr(link_offset)).c_str()); gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack); gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack); // We don't want any spacing between the elements, so we pack them into // this hbox that doesn't use kElementPadding. gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0); gtk_util::CenterWidgetInHBox(hbox, link_button, false, 0); gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0); } gtk_widget_show_all(border_bin_.get()); } private: static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) { const GdkEventButton* button_click_event = reinterpret_cast<GdkEventButton*>(gtk_get_current_event()); WindowOpenDisposition disposition = CURRENT_TAB; if (button_click_event) { disposition = event_utils::DispositionFromEventFlags( button_click_event->state); } if (link_info_bar->delegate_->AsLinkInfoBarDelegate()-> LinkClicked(disposition)) { link_info_bar->RemoveInfoBar(); } } }; // ConfirmInfoBar -------------------------------------------------------------- class ConfirmInfoBar : public AlertInfoBar { public: explicit ConfirmInfoBar(ConfirmInfoBarDelegate* delegate) : AlertInfoBar(delegate) { AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL); AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK); gtk_widget_show_all(border_bin_.get()); } private: // Adds a button to the info bar by type. It will do nothing if the delegate // doesn't specify a button of the given type. void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) { if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) { GtkWidget* button = gtk_button_new_with_label(WideToUTF8( delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str()); gtk_util::CenterWidgetInHBox(hbox_, button, true, 0); g_signal_connect(button, "clicked", G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ? OnOkButton : OnCancelButton), this); } } static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) { if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel()) info_bar->RemoveInfoBar(); } static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) { if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept()) info_bar->RemoveInfoBar(); } }; // AlertInfoBarDelegate, InfoBarDelegate overrides: ---------------------------- InfoBar* AlertInfoBarDelegate::CreateInfoBar() { return new AlertInfoBar(this); } // LinkInfoBarDelegate, InfoBarDelegate overrides: ----------------------------- InfoBar* LinkInfoBarDelegate::CreateInfoBar() { return new LinkInfoBar(this); } // ConfirmInfoBarDelegate, InfoBarDelegate overrides: -------------------------- InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() { return new ConfirmInfoBar(this); }
rwatson/chromium-capsicum
chrome/browser/gtk/infobar_gtk.cc
C++
bsd-3-clause
11,324
<?php class Printemps{ private static $colors=array( "balck" => "30", "red" => "31", "green" => "32", "yellow" => "33", "blue" => "34", "purple" => "35", "lblue" => "36", "gray" => "37", ); public static function Color($str,$color,$bg=0){ $code=self::$colors[$color]; return ($bg>0?"\033[$bg"."m":"")."\033[".$code."m $str \033[0m"; } }
face-orm/face-embryo
lib/Printemps.php
PHP
bsd-3-clause
468
# Copyright 2017 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. def CheckChangeOnCommit(input_api, output_api): tests = input_api.canned_checks.GetUnitTestsInDirectory( input_api, output_api, '.', files_to_check=['test_scripts.py$']) return input_api.RunTests(tests)
youtube/cobalt
third_party/v8/tools/release/PRESUBMIT.py
Python
bsd-3-clause
378
module Stupidedi module Editor # # Critiques (edits) interchanges (ISA/IEA) with version "00501", then # selects the appropriate editor, according to the config, and edits # each functional group (GS/GE) # class FiveOhOneEd < AbstractEd # @return [Config] attr_reader :config # @return [Time] attr_reader :received def initialize(config, received) @config, @received = config, received end # @return [ResultSet] def critique(isa, acc) # 000: No error # 002: This Standard as Noted in the Control Standards Identifier is Not Supported # Check for InvalidEnvelope # 003: This Version of the Controls is Not Supported # Check for InvalidEnvelope # 004: The Segment Terminator is Invalid # We couldn't have produced a parse tree, StreamReader#next_segment # would have returned an Either.failure<Result.failure> # 009: Unknown Interchange Receiver ID # This isn't for Stupidedi to decide # 016: Invalid Interchange Standards Identifier Value # Check for InvalidEnvelope # 022: Invalid Control Characters # What does this mean? TokenReader ignores control characters anyway, # so there will be no evidence of this in the parse tree # 025: Duplicate Interchange Control Numbers # Need to critique the parent, TransmissionVal # 028: Invalid Date in Deferred Delivery Request # 029: Invalid Time in Deferred Delivery Request # 030: Invalid Delivery Time Code in Deferred Delivery Request # 031: Invalid Grade of Service # It seems these elements should not be sent to a trading partner, # they are used internally to schedule a delivery. Not sure what to do # about validating them in a general way... acc.tap { critique_isa(isa, received, acc) } end private def critique_isa(isa, received, acc) # Authorization Information Qualifier edit(:ISA01) do isa.element(1).tap do |e| if e.node.blankness? acc.ta105(e, "R", "010", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "010", "is not an allowed value") end end end # Authorization Information edit(:ISA02) do isa.element(2).tap do |e| if e.node.blankness? acc.ta105(e, "R", "011", "must be present") elsif e.node.invalid? or not config.editor.an?(e.node) acc.ta105(e, "R", "011", "is not a valid string") end end end # Security Information Qualifier edit(:ISA03) do isa.element(3).tap do |e| if e.node.blankness? acc.ta105(e, "R", "012", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "012", "is not an allowed value") end end end # Security Information edit(:ISA04) do isa.element(4).tap do |e| if e.node.blankness? acc.ta105(e, "R", "013", "must be present") elsif e.node.invalid? or not config.editor.an?(e.node) acc.ta105(e, "R", "013", "is not a valid string") end end end # Interchange ID Qualifier edit(:ISA05) do isa.element(5).tap do |e| if e.node.blankness? acc.ta105(e, "R", "005", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "005", "is not an allowed value") end end end # Interchange Sender ID edit(:ISA06) do isa.element(6).tap do |e| if e.node.blankness? acc.ta105(e, "R", "006", "must be present") elsif e.node.invalid? or not config.editor.an?(e.node) acc.ta105(e, "R", "006", "is not a valid string") end end end # Interchange ID Qualifier edit(:ISA07) do isa.element(7).tap do |e| if e.node.blankness? acc.ta105(e, "R", "007", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "007", "is not an allowed value") end end end # Interchange Receiver ID edit(:ISA08) do isa.element(8).tap do |e| if e.node.blankness? acc.ta105(e, "R", "008", "must be present") end end end # Interchange Date edit(:ISA09) do isa.element(9).tap do |e| if e.node.blankness? acc.ta105(e, "R", "014", "must be present") elsif e.node.invalid? acc.ta105(e, "R", "014", "is not a valid date") else # Convert to a proper 4-digit year, by making the assumption # that the date is less than 30 years old. Note we have to use # Object#send to work around an incorrectly declared private # method that wasn't fixed until after Ruby 1.8 date = e.node.oldest(received.send(:to_date) << 12*30) if date > received.utc.send(:to_date) acc.ta105(e, "R", "014", "must not be a future date") end end end end # Interchange Time edit(:ISA10) do isa.element(10).tap do |e| if e.node.blankness? acc.ta105(e, "R", "015", "must be present") elsif e.node.invalid? acc.ta105(e, "R", "015", "is not a valid time") else isa.element(9).reject{|f| f.node.invalid? }.tap do |f| date = f.node.oldest(received.send(:to_date) << 12*30) if e.node.to_time(date) > received.utc acc.ta105(e, "R", "015", "must not be a future time") end end end end end # Repetition Separator edit(:ISA11) do isa.element(11).tap do |e| if e.node.blankness? acc.ta105(e, "R", "026", "must be present") end end end # Interchange Control Number edit(:ISA12) do isa.element(12).tap do |e| if e.node.blankness? acc.ta105(e, "R", "017", "must be present") end end end # Interchange Control Number edit(:ISA13) do isa.element(13).tap do |e| if e.node.blankness? acc.ta105(e, "R", "018", "must be present") elsif e.node.invalid? acc.ta105(e, "R", "018", "must be numeric") elsif e.node <= 0 acc.ta105(e, "R", "018", "must be positive") end end end # Acknowledgment Requested edit(:ISA14) do isa.element(14).tap do |e| if e.node.blankness? acc.ta105(e, "R", "019", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "019", "is not an allowed value") end end end # Interchange Usage Indicator edit(:ISA15) do isa.element(15).tap do |e| if e.node.blankness? acc.ta105(e, "R", "020", "must be present") elsif not e.node.allowed? acc.ta105(e, "R", "020", "is not an allowed value") end end end # Component Element Separator edit(:ISA16) do isa.element(16).tap do |e| if e.node.blankness? acc.ta105(e, "R", "027", "must be present") elsif e.node.invalid? or not config.editor.an?(e.node) acc.ta105(e, "R", "027", "is not a valid string") else isa.element(11).tap do |f| if e.node == f.node acc.ta105(e, "R", "027", "must be distinct from repetition separator") end end end end end m, gs06s = isa.find!(:GS), Hash.new{|h,k| h[k] = [] } # Collect all the GS06 elements within this interchange while m.defined? m = m.flatmap do |gs| edit_gs(gs, acc) gs.element(6).tap{|e| gs06s[e.node.to_s] << e } gs.find!(:GS) end end # Group Control Number edit(:GS06) do gs06s.each do |number, dupes| next if number.blankness? dupes.tail.each do |e| acc.ak905(e, "R", "19", "must be unique within interchange") end end end edit(:IEA) do isa.find(:IEA).tap do |iea| edit_iea(iea, isa, gs06s.length, acc) end.explain do isa.segment.tap{|s| acc.ta105(s, "R", "023", "missing IEA segment") } end end end def edit_iea(iea, isa, gs_count, acc) # @todo: acc.ta105(s, "024", "only one IEA segment is allowed") # Number of Included Functional Groups edit(:IEA01) do iea.element(1).tap do |e| if e.node.blankness? acc.ta105(e, "R", "021", "must be present") elsif e.node.invalid? acc.ta105(e, "R", "021", "must be numeric") elsif e.node != gs_count acc.ta105(e, "R", "021", "must equal the number of functional groups") end end end # Interchange Control Number edit(:IEA02) do iea.element(2).tap do |e| if e.node.blankness? acc.ta105(e, "R", "001", "must be present") else isa.element(13).reject{|f| e.node == f.node }.tap do acc.ta105(e, "R", "001", "must match interchange header control number") end end end end end # # @see FiftyTenEd#critique # def edit_gs(gs, acc) gs.segment.tap do |x| unless x.node.invalid? envelope_def = x.node.definition.parent.parent # Invoke the version-specific functional group editor if config.editor.defined_at?(envelope_def) editor = config.editor.at(envelope_def) editor.new(config, received).critique(gs, acc) end else # Probably "unknown interchange version '...'" acc.ak905(x, "R", "2", x.node.reason) end end end end end end
novuscommerce/stupidedi
lib/stupidedi/editor/00501.rb
Ruby
bsd-3-clause
10,787
##-*-coding: utf-8 -*- from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Usage(models.Model): ip = models.CharField(max_length=50) method = models.CharField(max_length=3) path = models.CharField(max_length=100) params = models.CharField(max_length=255) def __str__(self): return self.ip @python_2_unicode_compatible class Element(models.Model): name = models.CharField(max_length=10) code = models.CharField(max_length=10) def __str__(self): return self.name class Meta: verbose_name = "ธาตุ" verbose_name_plural = "ธาตุต่างๆ" db_table = 'element' @python_2_unicode_compatible class Disease(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, null=True) is_congenital = models.BooleanField(default=False) created_by = models.CharField(max_length=50, null=True) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = "เชื้อโรค" verbose_name_plural = "กลุ่มเชื้อโรค" db_table = 'disease' class Nutrient(models.Model): water = models.DecimalField(max_digits=14, decimal_places=4) protein = models.DecimalField(max_digits=14, decimal_places=4) fat = models.DecimalField(max_digits=14, decimal_places=4) carbohydrate = models.DecimalField(max_digits=14, decimal_places=4) dietary_fiber = models.DecimalField(max_digits=14, decimal_places=4) ash = models.DecimalField(max_digits=14, decimal_places=4) calcium = models.DecimalField(max_digits=14, decimal_places=4) phosphorus = models.DecimalField(max_digits=14, decimal_places=4) iron = models.DecimalField(max_digits=14, decimal_places=4) retinol = models.DecimalField(max_digits=14, decimal_places=4) beta_carotene = models.DecimalField(max_digits=14, decimal_places=4) vitamin_a = models.DecimalField(max_digits=14, decimal_places=4) vitamin_e = models.DecimalField(max_digits=14, decimal_places=4) thiamin = models.DecimalField(max_digits=14, decimal_places=4) riboflavin = models.DecimalField(max_digits=14, decimal_places=4) niacin = models.DecimalField(max_digits=14, decimal_places=4) vitamin_c = models.DecimalField(max_digits=14, decimal_places=4) def __str__(self): return 'id: ' + str(self._get_pk_val()) class Meta: verbose_name = "สารอาหาร" verbose_name_plural = "กลุ่มสารอาหาร" db_table = 'nutrient' @python_2_unicode_compatible class IngredientCategory(models.Model): name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = "หมวดหมู่วัตถุดิบ" verbose_name_plural = "กลุ่มหมวดหมู่วัตถุดิบ" db_table = 'ingredient_type' @python_2_unicode_compatible class FoodCategory(models.Model): name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = "หมวดหมู่อาหาร" verbose_name_plural = "กลุ่มหมวดหมู่อาหาร" db_table = 'food_type' @python_2_unicode_compatible class Ingredient(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True, null=True) calories = models.IntegerField(default=0) nutrient = models.ForeignKey(Nutrient, on_delete=models.SET_NULL, blank=True, null=True) element = models.ForeignKey(Element, on_delete=models.SET_NULL, blank=True, null=True) category = models.ManyToManyField(IngredientCategory, blank=True) healing = models.ManyToManyField(Disease, related_name="healing", blank=True) affect = models.ManyToManyField(Disease, related_name="affect", blank=True) code = models.IntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name = "วัตถุดิบ" verbose_name_plural = "กลุ่มวัตถุดิบ" db_table = 'ingredient' @python_2_unicode_compatible class Food(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True, null=True, default="") calories = models.IntegerField(default=0) nutrient = models.ForeignKey(Nutrient, on_delete=models.SET_NULL, blank=True, null=True) ingredients = models.ManyToManyField(Ingredient, through='Menu') category = models.ManyToManyField(FoodCategory) created_by = models.CharField(max_length=50, default="") created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) code = models.IntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name = "อาหาร" verbose_name_plural = "กลุ่มอาหาร" db_table = 'food' class Menu(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) weight = models.DecimalField(max_digits=14, decimal_places=4) name = models.CharField(max_length=100, blank=True, default="") class Meta: db_table = 'menu'
ohmini/thaifoodapi
thaifood/models.py
Python
bsd-3-clause
6,666
// Plugin for using a local directory as a Library. Generates the payload for // an AssetList REST endpoint consisting of asset models as well as pagination // helpers. var _ = require('underscore'), fs = require('fs'), url = require('url'), path = require('path'), querystring = require('querystring'), Step = require('step'); module.exports = function(app, options, callback) { // Recursive readdir. `callback(err, files)` is given a `files` array where // each file is an object with `filename` and `stat` properties. var lsR = function(basedir, callback) { var files = []; var ls = []; Step( function() { fs.readdir(basedir, this); }, function(err, data) { if (data.length === 0) return this(); var group = this.group(); ls = _.map(data, function(v) { return path.join(basedir, v); }); _.each(ls, function(v) { fs.stat(v, group()); }); }, function(err, stats) { if (ls.length === 0) return this(); var group = this.group(); _.each(ls, function(v, k) { var next = group(); if (stats[k].isDirectory()) { lsR(v, next); } else { files.push({ filename: v, stat: stats[k] }); next(); } }); }, function(err, sub) { _.each(sub, function(v) { v && (files = files.concat(v)); }); callback(err, files); } ); } // Filter an array of files where filenames match regex `re`. var lsFilter = function(files, re) { return _.filter(files, function(f) { return f.filename.match(re); }); }; // Convert a list of files into asset models. var toAssets = function(files, base_dir, port) { return _.map(files, function(f) { return { url: url.format({ host: 'localhost:' + port, protocol: 'http:', pathname: path.join( '/api/Library/' + options.id + '/files/' // Ensure only one trailing slash + querystring.escape(f.filename.replace( base_dir.replace(/(\/)$/, '') + '/', '')) ) }), bytes: (Math.ceil(parseInt(f.stat.size) / 1048576)) + ' MB', id: path.basename(f.filename) }; }); }; // Sort and slice to the specified page. var paginate = function(objects, page, limit) { return _.sortBy(objects, function(f) { return f.id; }).slice(page * limit, page * limit + limit); }; // Generate the AssetList payload object. lsR(options.directory_path, function(err, files) { var assets = toAssets( lsFilter(files, /\.(zip|json|geojson|vrt|tiff?)$/i), options.directory_path, require('settings').port ); callback({ models: paginate( assets, options.page, options.limit ), page: options.page, pageTotal: Math.ceil(assets.length / options.limit) }); }); };
makinacorpus/tilemill
server/library-directory.js
JavaScript
bsd-3-clause
3,711
"""A generic class to build line-oriented command interpreters. Interpreters constructed with this class obey the following conventions: 1. End of file on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. 4. Typing an empty line repeats the last command. (Actually, it calls the method `emptyline', which may be overridden in a subclass.) 5. There is a predefined `help' method. Given an argument `topic', it calls the command `help_topic'. With no arguments, it lists all topics with defined help_ functions, broken into up to three topics; documented commands, miscellaneous help topics, and undocumented commands. 6. The command '?' is a synonym for `help'. The command '!' is a synonym for `shell', if a do_shell method exists. 7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in. The `default' method may be overridden to intercept commands for which there is no do_ method. The `completedefault' method may be overridden to intercept completions for commands that have no complete_ method. The data member `self.ruler' sets the character used to draw separator lines in the help messages. If empty, no ruler line is drawn. It defaults to "=". If the value of `self.intro' is nonempty when the cmdloop method is called, it is printed out on interpreter startup. This value may be overridden via an optional argument to the cmdloop() method. The data members `self.doc_header', `self.misc_header', and `self.undoc_header' set the headers used for the help function's listings of documented functions, miscellaneous topics, and undocumented functions respectively. """ import string, sys __all__ = ["Cmd"] PROMPT = '(Cmd) ' IDENTCHARS = string.ascii_letters + string.digits + '_' class ElCmd: """A simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface. A Cmd instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate Cmd itself; rather, it's useful as a superclass of an interpreter class you define yourself in order to inherit Cmd's methods and encapsulate action methods. """ prompt = PROMPT identchars = IDENTCHARS ruler = '=' lastcmd = '' intro = None doc_leader = "" doc_header = "Documented commands (type help <topic>):" misc_header = "Miscellaneous help topics:" undoc_header = "Undocumented commands:" nohelp = "*** No help on %s" use_rawinput = False def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey if not self.use_rawinput and self.completekey: try: import editline self.editline = editline.editline("CMD", self.stdin, self.stdout, sys.stderr) self.editline.rl_completer = self.complete except ImportError: print("Failed to import editline") pass def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = input(self.prompt) except EOFError: line = 'EOF' else: self.editline.prompt = self.prompt line = self.editline.readline() if not len(line): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: pass def precmd(self, line): """Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued. """ return line def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop def preloop(self): """Hook method executed once when the cmdloop() method is called.""" pass def postloop(self): """Hook method executed once when the cmdloop() method is about to return. """ pass def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. """ cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if line == 'EOF' : print("") print("Bye") sys.exit(0) if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg) def emptyline(self): """Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """ if self.lastcmd: return self.onecmd(self.lastcmd) def default(self, line): """Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns. """ self.stdout.write('*** Unknown syntax: %s (%d)\n' % (line,len(line))) def completedefault(self, *ignored): """Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list. """ return [] def completenames(self, text, *ignored): dotext = 'do_'+text return [a[3:] for a in self.get_names() if a.startswith(dotext)] def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: origline = self.editline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = self.editline.get_begidx() - stripped endidx = self.editline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None def get_names(self): # This method used to pull in base class attributes # at a time dir() didn't do it yet. return dir(self.__class__) def complete_help(self, *args): commands = set(self.completenames(*args)) topics = set(a[5:] for a in self.get_names() if a.startswith('help_' + args[0])) return list(commands | topics) def do_help(self, arg): 'List available commands with "help" or detailed help with "help cmd".' if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, list(help.keys()),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80) def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: self.stdout.write("%s\n"%str(header)) if self.ruler: self.stdout.write("%s\n"%str(self.ruler * len(header))) self.columnize(cmds, maxcol-1) self.stdout.write("\n") def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). """ if not list: self.stdout.write("<empty>\n") return nonstrings = [i for i in range(len(list)) if not isinstance(list[i], str)] if nonstrings: raise TypeError("list[i] not a string for i in %s" % ", ".join(map(str, nonstrings))) size = len(list) if size == 1: self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards for nrows in range(1, len(list)): ncols = (size+nrows-1) // nrows colwidths = [] totwidth = -2 for col in range(ncols): colwidth = 0 for row in range(nrows): i = row + nrows*col if i >= size: break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += colwidth + 2 if totwidth > displaywidth: break if totwidth <= displaywidth: break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = row + nrows*col if i >= size: x = "" else: x = list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write("%s\n"%str(" ".join(texts))) class MyCmd(ElCmd,object): def do_bleep(self, s): print("bleep!") def do_blob(self, s): print("blob!") def do_bob(self, s): print("bob!") def do_mods(self, s): print(sys.modules.keys()) if __name__ == '__main__': mc = MyCmd() mc.cmdloop()
mark-nicholson/python-editline
examples/elCmd.py
Python
bsd-3-clause
15,015
from pymacy.db import get_db from bson.json_util import dumps db = get_db() results = [] count = 0 for i in db.benchmark.find({"element": "Ni"}): count += 1 if count > 100: break results.append(i) print(results[0]) with open("Ni.json", 'w') as f: file = dumps(results) f.write(file)
czhengsci/veidt
veidt/potential/tests/name/get_data.py
Python
bsd-3-clause
312
<?php /** * Template part for displaying page content in page.php. * * @link https://codex.wordpress.org/Template_Hierarchy * * @package devotion */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header> <div class="entry-content"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'devotion' ), 'after' => '</div>', ) ); ?> </div> <footer class="entry-footer"> <?php edit_post_link( esc_html__( 'Edit', 'devotion' ), '<span class="edit-link">', '</span>' ); ?> </footer> </article>
devotion-woocommerce/wp-devotion
template-parts/content-page.php
PHP
bsd-3-clause
698
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h" #include <memory> #include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/status_icons/status_icon_button_linux.h" #include "ui/message_center/public/cpp/notifier_id.h" #if defined(USE_DBUS) #include "chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h" #endif namespace { gfx::ImageSkia GetBestImageRep(const gfx::ImageSkia& image) { float best_scale = 0.0f; SkBitmap best_rep; for (const auto& rep : image.image_reps()) { if (rep.scale() > best_scale) { best_scale = rep.scale(); best_rep = rep.GetBitmap(); } } // All status icon implementations want the image in pixel coordinates, so use // a scale factor of 1. return gfx::ImageSkia::CreateFromBitmap(best_rep, 1.0f); } } // namespace StatusIconLinuxWrapper::StatusIconLinuxWrapper( views::StatusIconLinux* status_icon, StatusIconType status_icon_type, const gfx::ImageSkia& image, const std::u16string& tool_tip) : status_icon_(status_icon), status_icon_type_(status_icon_type), image_(GetBestImageRep(image)), tool_tip_(tool_tip) { status_icon_->SetDelegate(this); } #if defined(USE_DBUS) StatusIconLinuxWrapper::StatusIconLinuxWrapper( scoped_refptr<StatusIconLinuxDbus> status_icon, const gfx::ImageSkia& image, const std::u16string& tool_tip) : StatusIconLinuxWrapper(status_icon.get(), kTypeDbus, image, tool_tip) { status_icon_dbus_ = status_icon; } #endif StatusIconLinuxWrapper::StatusIconLinuxWrapper( std::unique_ptr<views::StatusIconLinux> status_icon, StatusIconType status_icon_type, const gfx::ImageSkia& image, const std::u16string& tool_tip) : StatusIconLinuxWrapper(status_icon.get(), status_icon_type, image, tool_tip) { status_icon_linux_ = std::move(status_icon); } StatusIconLinuxWrapper::~StatusIconLinuxWrapper() { } void StatusIconLinuxWrapper::SetImage(const gfx::ImageSkia& image) { image_ = GetBestImageRep(image); if (status_icon_) status_icon_->SetIcon(image_); } void StatusIconLinuxWrapper::SetToolTip(const std::u16string& tool_tip) { tool_tip_ = tool_tip; if (status_icon_) status_icon_->SetToolTip(tool_tip); } void StatusIconLinuxWrapper::DisplayBalloon( const gfx::ImageSkia& icon, const std::u16string& title, const std::u16string& contents, const message_center::NotifierId& notifier_id) { notification_.DisplayBalloon(icon, title, contents, notifier_id); } void StatusIconLinuxWrapper::OnClick() { DispatchClickEvent(); } bool StatusIconLinuxWrapper::HasClickAction() { return HasObservers(); } const gfx::ImageSkia& StatusIconLinuxWrapper::GetImage() const { return image_; } const std::u16string& StatusIconLinuxWrapper::GetToolTip() const { return tool_tip_; } ui::MenuModel* StatusIconLinuxWrapper::GetMenuModel() const { return menu_model_; } void StatusIconLinuxWrapper::OnImplInitializationFailed() { switch (status_icon_type_) { case kTypeDbus: #if defined(USE_DBUS) status_icon_dbus_.reset(); #endif status_icon_linux_ = std::make_unique<StatusIconButtonLinux>(); status_icon_ = status_icon_linux_.get(); status_icon_type_ = kTypeWindowed; status_icon_->SetDelegate(this); return; case kTypeWindowed: status_icon_linux_.reset(); status_icon_ = nullptr; status_icon_type_ = kTypeNone; if (menu_model_) menu_model_->RemoveObserver(this); menu_model_ = nullptr; return; case kTypeNone: NOTREACHED(); } } void StatusIconLinuxWrapper::OnMenuStateChanged() { if (status_icon_) status_icon_->RefreshPlatformContextMenu(); } std::unique_ptr<StatusIconLinuxWrapper> StatusIconLinuxWrapper::CreateWrappedStatusIcon( const gfx::ImageSkia& image, const std::u16string& tool_tip) { #if defined(USE_DBUS) return base::WrapUnique(new StatusIconLinuxWrapper( base::MakeRefCounted<StatusIconLinuxDbus>(), image, tool_tip)); #else return base::WrapUnique( new StatusIconLinuxWrapper(std::make_unique<StatusIconButtonLinux>(), kTypeWindowed, image, tool_tip)); #endif } void StatusIconLinuxWrapper::UpdatePlatformContextMenu( ui::MenuModel* model) { if (!status_icon_) return; status_icon_->UpdatePlatformContextMenu(model); }
nwjs/chromium.src
chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.cc
C++
bsd-3-clause
4,736
<?php /* @var $this SiteController */ /* */ /*echo CHtml::link('<i class="fa fa-question-circle fa-inverse"></i>', array('/site/help#SpelOverzicht'), array('target'=>'_blank')); */ ?> <div id="faq"> <h1>FAQ</h1> <?php echo CHtml::link('Waarom de Hike-app?', array('/site/help#waaromdehikeapp')); ?><br><?php echo CHtml::link('Hoe gaat het in zijn werk?', array('/site/help#hoewerkthet')); ?><br><?php echo CHtml::link('Wat zijn de benodigdheden?', array('/site/help#benodigdheden')); ?><br><?php echo CHtml::link('Hoe te beginnen?', array('/site/help#hoetebeginnen')); ?><br><?php echo CHtml::link('Kan ik zelf een hike aanmaken?', array('/site/help#kanikeenhkeaanmaken')); ?><br><?php echo CHtml::link('Moet ik nog een routeboekje maken?', array('/site/help#moetjenogeenrouteboekjemaken')); ?><br><?php echo CHtml::link('Hoe voeg je deelnemers toe?', array('/site/help#hoevoegikdeelnemerstoe')); ?><br><?php echo CHtml::link('Hoe start ik een hike', array('/site/help#hoestartikeenhike')); ?><br><?php echo CHtml::link('Hoe maak ik hike-vrienden?', array('/site/help#hoemaakikvrienden')); ?><br><?php echo CHtml::link('Wat betekent de hike status?', array('/site/help#watbetekenthikestatus')); ?><br><?php echo CHtml::link('Hoe start ik een hike?', array('/site/help#hoestartikeenhike')); ?><br><?php echo CHtml::link('Wat kunnen de deelenemers zien?', array('/site/help#watkunnendedeelnemerszien')); ?><br><?php ?> <!-- <div id="faq"> <h1>Uitleg</h1> --> <div id="faq"> <h1>FAQ</h1> <div id="waaromdehikeapp"> <p><h3>Waarom de Hike-app?</h3> Tijdens de hike kunnen de groepjes zien wat de actuele scores zijn van zichzelf en van de andere groepjes. Dit maakt de hike interactiever. Als je ziet dat je maar een paar punten achter ligt, dan loont het misschien wel om net een stapje harder te lopen om je directe concurrent in te halen. De hike wordt er dus spannender van voor de deelnemers. Voor de organisatie bied het extra comfort. Aan het eind van de hike hoeft er niet nog een punten-systeem uitgewerkt te worden, dat doet de app al voor je. Verder heb je tijdens de hike een aardig idee hoe goed de groepjes lopen. Verder hoeven posten pas bemand te worden als groepjes een bepaald punt hebben gepasseerd waardoor je de post-zit-tijd kunt verkorten. En groepjes die aan het dwalen zijn kunnen extra aangestuurd worden met hints. <div id="hoewerkthet"> <p><h3>Hoe gaat het in zijn werk?</h3> De basis van de hike blijft hetzelfde. Je hebt een route boekje, wat posten, eventueel wat controle-vragen. Tot zo ver niets nieuws. Daarnaast maak je de hike ook aan op de site. De volgende onderdelen kunnen aangemaakt worden: <h4>Posten</h4> Door posten aan te maken kun je met een paar klikken een groepje in- en uitchecken op een post. De groepjes krijgen dan automatisch punten bijgeschreven en de tijd wordt ook bijgehouden voor een eventuele tijdslimiet. <h4>Vragen</h4> Je kunt de vragen die je in je routeboekje hebt staan ook invoeren in de Hike-app. Je zet daarbij dan ook het goede antwoord en de score. Als een groepje tijdens de hike een vraag heeft beantwoord kun je in 1 oogopslag zien of dit goed is en met 1 klik kun je het goed of afkeuren. Bij goedkeuring krijgt het groepje automatisch de punten die bij de vraag horen. <h4>Stille posten</h4> Dit zijn qr-codes die je van te voren aanmaakt en uitprint. Deze kun je ophangen op de route. Een groepje dat de qr-code vindt en scant krijgt automatisch punten bij geschreven. <h4>Hints</h4> je kunt hints maken, in een hint kunnen tips staan over hoe je een bepaald route onderdeel kunt oplossen, de oplossing geven voor een bepaald routeonderdeel of zelfs de coördinaten van een bepaald routeonderdeel. Tijdens de hike kunnen groepjes de hint openen als ze er niet uitkomen. Uiteraard krijgen ze hier dan wel strafpunten voor. <h4>Bonuspunten</h4> Je kunt een groepje bonuspunten of strafpunten geven voor alles dat je belangrijk vind. <div id="benodigdheden"> <p><h3>Wat zijn de benodigdheden?</h3> Alle groepjes moeten tenminste één smartphone hebben met daarop een qr scanner app geïnstalleerd en een databundel. De hike-app zelf is een web-based applicatie wat betekent dat je hem niet op je telefoon installeert, maar dat je hem kan gebruiken door met je browser naar www.hike-app.nl te gaan. Wat je wel moet installeren is een qr-code scanner, maar daar zijn er heel veel van. <br> De databundel hoeft niet groot te zijn. Je hoeft namelijk alleen contact met het internet te hebben als je een vraag wilt beantwoorden, een stille post wilt inchecken (qr-code) of een hint wilt bekijken. Verder is de app redelijk klein waardoor je voor een lang hike weekend niet meer dan 50mb per groepje gebruikt. Uit ervaring is gebleken dat als het bereik matig is dan is de app nog steeds prima te gebruiken. Als je helemaal geen bereik hebt, kun je het beantwoorden van vragen en het inchecken van stille posten ook doen op een later moment dat je wel bereik hebt. De accu van de smartphones zijn veel meer een issue, een groepje moet efficiënt gebruik maken van de telefoons om te voorkomen dat ze zonder stroom komen te zitten. Groepjes kunnen dus niet eindeloos op google maps gaan zitten zoeken. De ervaring leert dat dit juist een leuk extra spelelement is. <div id="hoetebeginnen"> <p><h3>Hoe te beginnen?</h3> Als je gebruik wil maken van de Hike-app dan moet je een account maken op www.hike-app.nl Je kunt dan al direct een hike aanmaken. Aan je hike kun je vervolgens posten, vragen, hints en stille posten toevoegen. Je kunt deelnemers toevoegen aan je hike, maar alleen als je hike-vrienden met ze bent. Dus de deelnemers moeten zich ook aanmelden en je moet hike-vrienden worden met de deelnemers. De gegevens die je invoert worden alleen gebruikt voor de hike-app. Zolang de hike niet is gestart kunnen de deelnemers niets van de hike zien, pas als de hike start dan kunnen de deelnemers de onderdelen zien die bij die dag horen. <div id="kanikeenhkeaanmaken"> <p><h3>Kan ik zelf een hike aanmaken?</h3> Ja, als je ingelogd bent en je gaat naar de home pagina (het huisje), dan staat er in het menu rechts, of onderaan de optie 'Nieuwe hike beginnen'. Als je daarop klikt kun je een hike aanmaken. Klik vervolgens op het metertje in het menu bovenaan (Hike uitzetten), vanaf daar kun je de verschillende hike onderdelen aanmaken. <div id="moetjenogeenrouteboekjemaken"> <p><h3>Moet ik nog een routeboekje maken?</h3> Jazeker, de Hike-app is er alleen ter ondersteuning voor het bijhouden van de scores en de tijdslimiet. De route en puzzels moeten de deelnemers uit een routeboekje halen. Het best is dan ook om eerste de route en het routeboekje te maken en als dat (bijna) klaar is, de hike aanmaken op de Hike-app. <div id="hoevoegikdeelnemerstoe"> <p><h3>Hoe voeg je deelnemers toe?</h3> Als je een hike hebt aangemaakt, dan ben je automatisch toegevoegd aan die hike als organisatie. Je kunt anderen toevoegen aan je hike, je kunt anderen toevoegen als oa organisatie of als deelnemer. Maar let op, je kunt alleen hike-vrienden toevoegen aan je hike. Als je op de pagina 'Hike uitzetten'bent, dan staat er in het menu rechts (mits de status van de hike is 'opstart') de optie 'Deelnemers toevoegen'. Als je daarop klikt kom je op de pagina deelnemers toevoegen. In het eerste veld kun je beginnen met het typen van de naam van een hike-vriend die je wilt toevoegen. Het is een autocomplete veld, dus na 2 a 3 letters komen er suggesties. Komt er niets, dan heb je geen hike-vrienden met die letter combinatie. Kies vervolgens een rol, indien de rol 'deelnemer' is, dan moet je ook een groep selecteren. De groep moet je dus al aangemaakt hebben. Druk op de submit knop als je klaar bent. <div id="hoemaakikvriengen"> <p><h3>Hoe maak ik hike-vrienden?</h3> Als je mensen aan je hike wilt toevoegen dan moet je vrienden met ze zijn. Maar ook als je aan een hike toegevoegd wilt worden moet je vrienden zijn met de op zijn mist 1 persoon van de organisatie. Als je vrienden wilt maken/zoeken, ga dan naar de thuis pagina als je bent ingelogd. Rechts in het menu staat de optie 'Vrienden Zoeken' als je daarop klikt zie je een lijst met mensen die zich aangemeld hebben bij de hike-app. Als je iemand gevonden hebt, klik je op het vinkje rechts bij zijn naam. Je hebt dan een uitnodiging gestuurd en je moet wachten tot diegene de uitnodiging accepteert. Als je iemand niet in de lijst ziet staan, maar je weet zeker dat hij/zij zich wel aangemeld heeft op de site, dan kan iemand jou al een vriendschapsverzoek gestuurd hebben. Om een vriendschapsverzoek te accepteren, ga naar de homepage en klik op het tabblad 'Verzoeken', daar zie je mensen staan die jou een verzoek hebben gedaan. Klik het vinkje om het verzoek te accepteren. Als je het vezoek wilt weigeren dan klik je op het rondje met de streep erdoor. Let op, als je iemands verzoek weigert, dan kan je die persoon ook niet meer zoeken. <div id="watbetekenthikestatus"> <p><h3>Wat betekent de hike status?</h3> Als je een hike hebt aangemaakt, dan is de hike status automatisch 'Opstart'. Deze status betekent dat je als organisatie de hike en deelnemers in kan voeren. Zolang de status 'Opstart' is kunnen de deelnemers ook niets zien van de hike. Pas als je de status veranderd naar 'Introductie' of 'Gestart' dan kunnen de deelnemers pas de hike zien. De status 'Introductie' kun je gebruiken voor de voorpret, je kunt al wat vragen maken die de deelenemers voor de hike moeten maken. En je kunt ook stille posten maken die de deelenemers tijdens de introductie (dus voor de hike) kunnen scannen om punten te halen. Groot voordeel van het gebruik van een introductie is dat de deelenemers al in de dagen voor de hike, de app al een keer bekeken en gebruikt hebben. Voorbeeld van het gebruik van de stille post tijdens de introductie is bijvoorbeeld, de stille post ergens op de site van de groep zetten. <div id="hoestartikeenhike"> <p><h3>Hoe start ik een hike? </h3> Als je een hike gemaakt hebt, je hebt alle vragen ingevoerd, de (stille) posten gemaakt, de hints ingevoerd en de deelenemers toegevoegd, dan kun je de hike starten door de status te veranderen. Als je de status op 'Introductie' zet dan kunnen de deelnemers de vragen beantwoorden die bij de introductie hoort. Ook kunnen ze de stillen posten voor de introductie scannen. Let op! De introductie kan geen hints of gewone posten hebben. Als de hike echt begint, dan zet je de hike status op 'Gestart' tevens selecteer je welke dag het is en geef je aan hoeveel looptijd de deelnemers hebben. De looptijd is de tijd die deelnemers tussen de posten hebben. Als die voorbij is dan kunnen ze geen vragen meer beantwoorden of punten krijgen voor (stille) posten. Wil je niet met een tijdslimiet lopen, zet de tijdlimiet dan op 24 uur. Vanaf het moment dat de hike gestart is kunnen de deelnemers de onderdelen zien die bij die dag hoort. De onderdelen die bij een andere dag hoort, kunnen de deelnemers niet zien. <div id="watkunnendedeelnemerszien"> <p><h3>Wat kunnen de deelenemers zien? </h3> Wat de deelnemers kunnen zien hangt af van de status van de hike. <p><h4>Opstart</h4> Deelnemers kunnen niets zien van de hike. De organisatie kan dus tijdens deze status rustig dingen toevoegen, verwijderen of wijzigen. <p><h4>Introductie</h4> Tijdens deze status kunnen de groepjes de vragen zien die bij de introductie hoort. Ze kunnen de vraag beantwoorden en als de organisatie de vraag heeft gecontroleerd dan kunnen ze ook zien of de vraag goed of fout is. De groepjes kunnen niet van elkaar zien welke vragen zij beantwoord hebben en of het goed of fout is. De groepjes kunnen niet zien of en hoeveel stille posten er zijn tijdens de introductie. Maar als ze een stille post hebben gevonden en gescand, dan zien ze die wel in hun eigen overzicht terug met de score die erbij hoort. In het spel overzicht kan iedereen zien hoeveel punten elke groep heeft op welk onderdelen. Maar de groepjes kunnen niet bij elkaar zien welke vragen of stille posten een ander groepje al heeft gehad. Tijdens de introductie zijn er geen hints of posten. <p><h4>Gestart</h4> Vragen en stille posten zijn hetzelfde als tijdens de introductie. De gewone posten kunnen de deelenemers niet zien. Ze weten dus niet wanneer en hoeveel posten er zijn. Pas als ze een post gepasseerd zijn en in gecheckt zijn, dan zien ze de post (met de score) terug in hun groepsoverzicht. De deelnemers zien voor een dag alle beschikbare hints. De hints hebben een titel waaraan de deelenemers kunnen afleiden op welk punt in de route de hint betrekking heeft. Als de deelnemers de hint openmaken kunnen ze het veld 'coordinaten' en het veld 'opmerkingen' zien. Ook hier geld dat de groepen wel de totaal scores van elkaar kunnen zien, maar niet precies zien voor welke posten of hint een andere groep (straf)punten heeft gekregen. <br> <br> <br> <br> <h1>Help</h1> <div id="iconen"> <p><h3>Iconen</h3> <ul> <li><b> <td colspan="4" style="text-align:center; font-size:220%"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-1x fa-green fa-15x"></i> <i class="fa fa-home fa-stack-1x"></i> </span> </td></b> De beginpagina van de site. Als je ingelogd bent heb je hier de mogelijkheid om je wachtwoord te wijzigen. </li> <li><b> <td colspan="4" style="text-align:center; font-size:220%"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-1x fa-green fa-15x"></i> <i class="fa fa-compass fa-stack-1x"></i> </span> </td></b> Hier staat een overzicht van de standen van de verschillende groepjes. Bij elke groepsnaam staat een plusje, als je bij die groep hoort, dan kan je via dat plusje naar je groepsgegevens.</li> <li><b> <td colspan="4" style="text-align:center; font-size:220%"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-1x fa-green fa-15x"></i> <i class="fa fa-bar-chart-o fa-stack-1x"></i> </span> </td></b> De score in een fancysmancy grafiekje. </li> <li><b> <td colspan="4" style="text-align:center; font-size:220%"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-1x fa-green fa-15x"></i> <i class="fa fa-tachometer fa-stack-1x"></i> </span> </td></b> Hier kan de organisatie een hike invoeren.</li> <li><b> <td colspan="4" style="text-align:center; font-size:220%"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-1x fa-green fa-15x"></i> <i class="fa fa-envelope-o fa-stack-1x"></i> </span> </td></b> Hier kan je een berichtje sturen naar de beheerder van de site. </li> </ul> </br> <div id="HikeOverzicht"> <p><h3>Hike Overzicht</h3> Het is een overzicht van alle hiken waarvoor je ingeschreven bent.</p> <p>Als je bent ingeschreven voor 1 hike of als er 1 hike de status introdctie of gestart heeft, dan krijg je dit scherm niet te zien. </p> </br> </br> <div id="SpelOverzicht"> <p><h3>Spel Overzicht</h3> Het is een overzicht van alle groepen die meedoen met de hike. <ul> <li><b>Group Name:</b> Dit is de naam van de groep </li> <li><b>Post:</b> Dit is de post die deze groep als laatst is gepasseerd. </li> <li><b>Tijd Laatste Post:</b> Dit is het tijdstip van de laatste binnenkomst op een post</li> <li><b>Score Posten:</b> Totaal score voor het passeren van de posten. </li> <li><b>Score Vragen:</b> Totaal score voor het beantwoorden van de vragen.</li> <li><b>Score Stille Posten:</b> Totaal score voor het scannen van stille posten. </li> <li><b>Score Bonuspunten:</b> Totaal score voor bonuspunten.</li> <li><b>Strafpunten Hints:</b> Totaal aantal strafpunten voor het openen van hint.</li> <li><b>Total score:</b> Totaal score. </li> <li><b> <td colspan="4" style="text-align:center; font-size:220%""> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x fa-gold"></i> <i class="fa fa-trophy fa-stack-1x fa-inverse"></i> <i class="fa fa-stack-30p fa-blue fa-05x"> 1 </i> </span> </td> </b> De ranking voor deze groep. </li> </ul> </br> <div id="menuopties"> <h3>Menu opties</h3> <h4>Antwoorden Controleren</h4> Hier kan de organisatie de vragen beoordelen. <ul> <li><b>Goed (figuur):</b> Antwoord is fout. </li> <li><b>Four (figuur):</b> Antwoord is goed en groep krijgt de punten voor deze vraag.</li> </ul> </p> </br> </br> <div id="Vragen"> <h4>Alle Vragen</h4> Hier staat een overzicht van alle vragen die een groep kan beantwoorden. <ul> </ul> </p> </br> </br> <div id="BeantwoordeVragen"> <h4>Beantwoorde Vragen</h4> Hier staat een overzicht van alle vragen die een groep heeft beantwoorden. <ul> </ul> </p> </br> </br> <div id="TeControlerenVragen"> <h4>Te Controleren Vragen</h4> Hier staan vragen die nog gecontroleerd moeten worden. Zolang de vragen nog niet gecontroleerd zijn, kunnen de antwoorden nog aangepast worden. <ul> </ul> </p> </br> </br> <div id="BonuspuntenToekennen"> <h4>Bonuspunten Toekennen</h4> Hier kan de organisatie de bonuspunten geven aan een groep. Dit kunnen ook strafpunten zijn (negetieve getallen). <ul> </ul> </p> </br> </br> <div id="Hints"> <h4>Hints</h4> Dit is een overzicht van alle hints die beschikbaar zijn en die een groep kan openen. LET OP! Bij het openen van een hint krijgt je groep strafpunten. <ul> </ul> </p> </br> </br> <div id="BeantwoordeVragen"> <h4>Beantwoorde Vragen</h4> Dit is een overzicht van vragen die een groep beantwoord heeft. <ul> </ul> </p> </br> </br> <div id="GeopendeHints"> <h4>Geopende Hints</h4> Dit is een overzicht van hints die een groep geopend heeft. <ul> </ul> </p> </br> </br> <div id="Bonuspunten"> <h4>Bonuspunten Overzicht</h4> Dit is een overzicht van alle bonuspunten die toegekend zijn. Tijdens een hike kan alleen de organisatie dit overzicht bekijken. Als een hike beeindigd is, dan kunnen alle deelnemers dit overzicht ook bekijken en hun scores vergelijken. <ul> </ul> </p> </br> </br> <div id="PostPassages"> <h4>Gepasseerde Posten</h4> Dit is een overzicht van alle Posten die gepasseerd zijn. Tijdens een hike kan alleen de organisatie dit overzicht bekijken. Als een hike beeindigd is, dan kunnen alle deelnemers dit overzicht ook bekijken en hun scores vergelijken. <ul> </ul> </p> </br> </br> <div id="BinnenkomstPost"> <h4>Binnenkomst Posten Registreren</h4> Hier kan de organisatie of iemand van de post de binnenkomst van een groep registreren. <ul> </ul> </p> </br> </br> <div id="StillePosten"> <h4>Stille Posten</h4> Dit is een overzicht van alle stille posten die gepasseerd zijn. Tijdens een hike kan alleen de organisatie dit overzicht bekijken. Als een hike beeindigd is, dan kunnen alle deelnemers dit overzicht ook bekijken en hun scores vergelijken. <ul> </ul> </p> </br> </br> </br> </br>
dasscheman/hike_development
hike_development/protected/views/site/help.php
PHP
bsd-3-clause
19,057
// Copyright 2008, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 file contains the implementation of the File methods specific to // the win32 platform. // TODO: likely there are better ways to accomplish Delete and // CreateNewTempFile. #ifdef _WIN32 #include "kml/base/file.h" #include <windows.h> #include <tchar.h> #include <xstring> #include <algorithm> namespace kmlbase { // Internal to the win32 file class. We need a conversion from string to // LPCWSTR. static std::wstring Str2Wstr(const string& str) { std::wstring wstr(str.length(), L''); std::copy(str.begin(), str.end(), wstr.begin()); return wstr; } // Internal to the win32 file class. We need a conversion from std::wstring to // string. string Wstr2Str(const std::wstring& wstr) { size_t s = wstr.size(); string str(static_cast<int>(s+1), 0); WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), static_cast<int>(s), &str[0], static_cast<int>(s), NULL, NULL); return str; } bool File::Exists(const string& full_path) { if (full_path.empty()) { return false; } std::wstring wstr = Str2Wstr(full_path); DWORD attrs = ::GetFileAttributes(wstr.c_str()); return (attrs != INVALID_FILE_ATTRIBUTES) && ((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0); } bool File::Delete(const string& filepath) { if (filepath.empty()) { return false; } std::wstring wstr = Str2Wstr(filepath); return ::DeleteFile(wstr.c_str()) ? true : false; } static const unsigned int BUFSIZE = 1024; DWORD dwBufSize = BUFSIZE; DWORD dwRetVal; TCHAR lpPathBuffer[BUFSIZE]; UINT uRetVal; TCHAR szTempName[BUFSIZE]; // http://msdn.microsoft.com/en-us/library/aa363875(VS.85).aspx bool File::CreateNewTempFile(string* path) { if (!path) { return false; } // Get the temp path. dwRetVal = ::GetTempPath(dwBufSize, lpPathBuffer); if (dwRetVal > dwBufSize || (dwRetVal == 0)) { return false; } // Create a temporary file. uRetVal = ::GetTempFileName(lpPathBuffer, TEXT("libkml"), 0, szTempName); if (uRetVal == 0) { return false; } string str = Wstr2Str(szTempName); path->assign(str.c_str(), strlen(str.c_str())); return true; } } // end namespace kmlbase #endif
sebastic/libkml
src/kml/base/file_win32.cc
C++
bsd-3-clause
3,643
package main import ( "encoding/json" "encoding/xml" "errors" "fmt" "io" "io/ioutil" "net" "os" "path" "path/filepath" "strconv" "strings" "sync" "syscall" "time" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/alexzorin/libvirt-go" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/daemon/networkdriver/ipallocator" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/pkg/term" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/libcontainer/netlink" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/miekg/dns" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/natefinch/lumberjack" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/technoweenie/grohl" "github.com/flynn/flynn/host/containerinit" lt "github.com/flynn/flynn/host/libvirt" "github.com/flynn/flynn/host/logbuf" "github.com/flynn/flynn/host/logmux" "github.com/flynn/flynn/host/resource" "github.com/flynn/flynn/host/types" "github.com/flynn/flynn/host/volume/manager" "github.com/flynn/flynn/pinkerton" "github.com/flynn/flynn/pinkerton/layer" "github.com/flynn/flynn/pkg/attempt" "github.com/flynn/flynn/pkg/cluster" "github.com/flynn/flynn/pkg/iptables" "github.com/flynn/flynn/pkg/random" ) const ( libvirtNetName = "flynn" bridgeName = "flynnbr0" imageRoot = "/var/lib/docker" ) func NewLibvirtLXCBackend(state *State, vman *volumemanager.Manager, volPath, logPath, initPath string, mux *logmux.LogMux) (Backend, error) { libvirtc, err := libvirt.NewVirConnection("lxc:///") if err != nil { return nil, err } pinkertonCtx, err := pinkerton.BuildContext("aufs", imageRoot) if err != nil { return nil, err } return &LibvirtLXCBackend{ LogPath: logPath, VolPath: volPath, InitPath: initPath, libvirt: libvirtc, state: state, vman: vman, pinkerton: pinkertonCtx, logs: make(map[string]*logbuf.Log), containers: make(map[string]*libvirtContainer), defaultEnv: make(map[string]string), resolvConf: "/etc/resolv.conf", mux: mux, ipalloc: ipallocator.New(), discoverdConfigured: make(chan struct{}), networkConfigured: make(chan struct{}), }, nil } type LibvirtLXCBackend struct { LogPath string InitPath string VolPath string libvirt libvirt.VirConnection state *State vman *volumemanager.Manager pinkerton *pinkerton.Context ipalloc *ipallocator.IPAllocator ifaceMTU int bridgeAddr net.IP bridgeNet *net.IPNet resolvConf string logsMtx sync.Mutex logs map[string]*logbuf.Log mux *logmux.LogMux containersMtx sync.RWMutex containers map[string]*libvirtContainer envMtx sync.RWMutex defaultEnv map[string]string discoverdConfigured chan struct{} networkConfigured chan struct{} } type libvirtContainer struct { RootPath string IP net.IP job *host.Job l *LibvirtLXCBackend done chan struct{} *containerinit.Client } type dockerImageConfig struct { User string Env []string Cmd []string Entrypoint []string WorkingDir string Volumes map[string]struct{} } func writeContainerConfig(path string, c *containerinit.Config, envs ...map[string]string) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() c.Env = make(map[string]string) for _, e := range envs { for k, v := range e { c.Env[k] = v } } return json.NewEncoder(f).Encode(c) } func writeHostname(path, hostname string) error { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() pos, err := f.Seek(0, os.SEEK_END) if err != nil { return err } if pos > 0 { if _, err := f.Write([]byte("\n")); err != nil { return err } } _, err = fmt.Fprintf(f, "127.0.0.1 %s\n", hostname) return err } func readDockerImageConfig(id string) (*dockerImageConfig, error) { res := &struct{ Config dockerImageConfig }{} f, err := os.Open(filepath.Join(imageRoot, "graph", id, "json")) if err != nil { return nil, err } defer f.Close() if err := json.NewDecoder(f).Decode(res); err != nil { return nil, err } return &res.Config, nil } var networkConfigAttempts = attempt.Strategy{ Total: 10 * time.Minute, Delay: 200 * time.Millisecond, } // ConfigureNetworking is called once during host startup and passed the // strategy and identifier of the networking coordinatior job. Currently the // only strategy implemented uses flannel. func (l *LibvirtLXCBackend) ConfigureNetworking(config *host.NetworkConfig) error { var err error l.bridgeAddr, l.bridgeNet, err = net.ParseCIDR(config.Subnet) if err != nil { return err } l.ipalloc.RequestIP(l.bridgeNet, l.bridgeAddr) err = netlink.CreateBridge(bridgeName, false) bridgeExists := os.IsExist(err) if err != nil && !bridgeExists { return err } bridge, err := net.InterfaceByName(bridgeName) if err != nil { return err } if !bridgeExists { // We need to explicitly assign the MAC address to avoid it changing to a lower value // See: https://github.com/flynn/flynn/issues/223 b := random.Bytes(5) bridgeMAC := fmt.Sprintf("fe:%02x:%02x:%02x:%02x:%02x", b[0], b[1], b[2], b[3], b[4]) if err := netlink.NetworkSetMacAddress(bridge, bridgeMAC); err != nil { return err } } currAddrs, err := bridge.Addrs() if err != nil { return err } setIP := true for _, addr := range currAddrs { ip, net, _ := net.ParseCIDR(addr.String()) if ip.Equal(l.bridgeAddr) && net.String() == l.bridgeNet.String() { setIP = false } else { if err := netlink.NetworkLinkDelIp(bridge, ip, net); err != nil { return err } } } if setIP { if err := netlink.NetworkLinkAddIp(bridge, l.bridgeAddr, l.bridgeNet); err != nil { return err } } if err := netlink.NetworkLinkUp(bridge); err != nil { return err } network, err := l.libvirt.LookupNetworkByName(libvirtNetName) if err != nil { // network doesn't exist networkConfig := &lt.Network{ Name: libvirtNetName, Bridge: lt.Bridge{Name: bridgeName}, Forward: lt.Forward{Mode: "bridge"}, } network, err = l.libvirt.NetworkDefineXML(string(networkConfig.XML())) if err != nil { return err } } active, err := network.IsActive() if err != nil { return err } if !active { if err := network.Create(); err != nil { return err } } if defaultNet, err := l.libvirt.LookupNetworkByName("default"); err == nil { // The default network causes dnsmasq to run and bind to all interfaces, // including ours. This prevents discoverd from binding its DNS server. // We don't use it, so destroy it if it exists. defaultNet.Destroy() } // enable IP forwarding if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1\n"), 0644); err != nil { return err } // Set up iptables for outbound traffic masquerading from containers to the // rest of the network. if err := iptables.EnableOutboundNAT(bridgeName, l.bridgeNet.String()); err != nil { return err } // Read DNS config, discoverd uses the nameservers dnsConf, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err != nil { return err } config.Resolvers = dnsConf.Servers // Write a resolv.conf to be bind-mounted into containers pointing at the // future discoverd DNS listener if err := os.MkdirAll("/etc/flynn", 0755); err != nil { return err } var resolvSearch string if len(dnsConf.Search) > 0 { resolvSearch = fmt.Sprintf("search %s\n", strings.Join(dnsConf.Search, " ")) } if err := ioutil.WriteFile("/etc/flynn/resolv.conf", []byte(fmt.Sprintf("%snameserver %s\n", resolvSearch, l.bridgeAddr.String())), 0644); err != nil { return err } l.resolvConf = "/etc/flynn/resolv.conf" // Allocate IPs for running jobs for i, container := range l.containers { if !container.job.Config.HostNetwork { var err error l.containers[i].IP, err = l.ipalloc.RequestIP(l.bridgeNet, container.IP) if err != nil { grohl.Log(grohl.Data{"fn": "ConfigureNetworking", "at": "request_ip", "status": "error", "err": err}) } } } close(l.networkConfigured) return nil } var libvirtAttempts = attempt.Strategy{ Total: 10 * time.Second, Delay: 200 * time.Millisecond, } func (l *LibvirtLXCBackend) withConnRetries(f func() error) error { return libvirtAttempts.Run(func() error { err := f() if err != nil { if alive, err := l.libvirt.IsAlive(); err != nil || !alive { conn, connErr := libvirt.NewVirConnection("lxc:///") if connErr != nil { return connErr } l.libvirt = conn } } return err }) } func (l *LibvirtLXCBackend) SetDefaultEnv(k, v string) { l.envMtx.Lock() l.defaultEnv[k] = v l.envMtx.Unlock() if k == "DISCOVERD" { close(l.discoverdConfigured) } } func (l *LibvirtLXCBackend) Run(job *host.Job, runConfig *RunConfig) (err error) { g := grohl.NewContext(grohl.Data{"backend": "libvirt-lxc", "fn": "run", "job.id": job.ID}) g.Log(grohl.Data{"at": "start", "job.artifact.uri": job.Artifact.URI, "job.cmd": job.Config.Cmd}) if !job.Config.HostNetwork { <-l.networkConfigured } if _, ok := job.Config.Env["DISCOVERD"]; !ok { <-l.discoverdConfigured } if runConfig == nil { runConfig = &RunConfig{} } container := &libvirtContainer{ l: l, job: job, done: make(chan struct{}), } if !job.Config.HostNetwork { container.IP, err = l.ipalloc.RequestIP(l.bridgeNet, runConfig.IP) if err != nil { g.Log(grohl.Data{"at": "request_ip", "status": "error", "err": err}) return err } } defer func() { if err != nil { go container.cleanup() } }() g.Log(grohl.Data{"at": "pull_image"}) layers, err := l.pinkertonPull(job.Artifact.URI) if err != nil { g.Log(grohl.Data{"at": "pull_image", "status": "error", "err": err}) return err } imageID, err := pinkerton.ImageID(job.Artifact.URI) if err == pinkerton.ErrNoImageID && len(layers) > 0 { imageID = layers[len(layers)-1].ID } else if err != nil { g.Log(grohl.Data{"at": "image_id", "status": "error", "err": err}) return err } g.Log(grohl.Data{"at": "read_config"}) imageConfig, err := readDockerImageConfig(imageID) if err != nil { g.Log(grohl.Data{"at": "read_config", "status": "error", "err": err}) return err } g.Log(grohl.Data{"at": "checkout"}) rootPath, err := l.pinkerton.Checkout(job.ID, imageID) if err != nil { g.Log(grohl.Data{"at": "checkout", "status": "error", "err": err}) return err } container.RootPath = rootPath g.Log(grohl.Data{"at": "mount"}) if err := bindMount(l.InitPath, filepath.Join(rootPath, ".containerinit"), false, true); err != nil { g.Log(grohl.Data{"at": "mount", "file": ".containerinit", "status": "error", "err": err}) return err } if err := os.MkdirAll(filepath.Join(rootPath, "etc"), 0755); err != nil { g.Log(grohl.Data{"at": "mkdir", "dir": "etc", "status": "error", "err": err}) return err } if err := bindMount(l.resolvConf, filepath.Join(rootPath, "etc/resolv.conf"), false, true); err != nil { g.Log(grohl.Data{"at": "mount", "file": "resolv.conf", "status": "error", "err": err}) return err } if err := writeHostname(filepath.Join(rootPath, "etc/hosts"), job.ID); err != nil { g.Log(grohl.Data{"at": "write_hosts", "status": "error", "err": err}) return err } if err := os.MkdirAll(filepath.Join(rootPath, ".container-shared"), 0700); err != nil { g.Log(grohl.Data{"at": "mkdir", "dir": ".container-shared", "status": "error", "err": err}) return err } for i, m := range job.Config.Mounts { if err := os.MkdirAll(filepath.Join(rootPath, m.Location), 0755); err != nil { g.Log(grohl.Data{"at": "mkdir_mount", "dir": m.Location, "status": "error", "err": err}) return err } if m.Target == "" { m.Target = filepath.Join(l.VolPath, cluster.RandomJobID("")) job.Config.Mounts[i].Target = m.Target if err := os.MkdirAll(m.Target, 0755); err != nil { g.Log(grohl.Data{"at": "mkdir_vol", "dir": m.Target, "status": "error", "err": err}) return err } } if err := bindMount(m.Target, filepath.Join(rootPath, m.Location), m.Writeable, true); err != nil { g.Log(grohl.Data{"at": "mount", "target": m.Target, "location": m.Location, "status": "error", "err": err}) return err } } // apply volumes for _, v := range job.Config.Volumes { vol := l.vman.GetVolume(v.VolumeID) if vol == nil { err := fmt.Errorf("job %s required volume %s, but that volume does not exist", job.ID, v.VolumeID) g.Log(grohl.Data{"at": "volume", "volumeID": v.VolumeID, "status": "error", "err": err}) return err } if err := os.MkdirAll(filepath.Join(rootPath, v.Target), 0755); err != nil { g.Log(grohl.Data{"at": "volume_mkdir", "dir": v.Target, "status": "error", "err": err}) return err } if err != nil { g.Log(grohl.Data{"at": "volume_mount", "target": v.Target, "volumeID": v.VolumeID, "status": "error", "err": err}) return err } if err := bindMount(vol.Location(), filepath.Join(rootPath, v.Target), v.Writeable, true); err != nil { g.Log(grohl.Data{"at": "volume_mount2", "target": v.Target, "volumeID": v.VolumeID, "status": "error", "err": err}) return err } } if job.Config.Env == nil { job.Config.Env = make(map[string]string) } for i, p := range job.Config.Ports { if p.Proto != "tcp" && p.Proto != "udp" { return fmt.Errorf("unknown port proto %q", p.Proto) } if p.Port == 0 { job.Config.Ports[i].Port = 5000 + i } if i == 0 { job.Config.Env["PORT"] = strconv.Itoa(job.Config.Ports[i].Port) } job.Config.Env[fmt.Sprintf("PORT_%d", i)] = strconv.Itoa(job.Config.Ports[i].Port) } if !job.Config.HostNetwork { job.Config.Env["EXTERNAL_IP"] = container.IP.String() } config := &containerinit.Config{ TTY: job.Config.TTY, OpenStdin: job.Config.Stdin, WorkDir: job.Config.WorkingDir, Resources: job.Resources, } if !job.Config.HostNetwork { config.IP = container.IP.String() + "/24" config.Gateway = l.bridgeAddr.String() } if config.WorkDir == "" { config.WorkDir = imageConfig.WorkingDir } if job.Config.Uid > 0 { config.User = strconv.Itoa(job.Config.Uid) } else if imageConfig.User != "" { // TODO: check and lookup user from image config } if len(job.Config.Entrypoint) > 0 { config.Args = job.Config.Entrypoint config.Args = append(config.Args, job.Config.Cmd...) } else { config.Args = imageConfig.Entrypoint if len(job.Config.Cmd) > 0 { config.Args = append(config.Args, job.Config.Cmd...) } else { config.Args = append(config.Args, imageConfig.Cmd...) } } for _, port := range job.Config.Ports { config.Ports = append(config.Ports, port) } g.Log(grohl.Data{"at": "write_config"}) l.envMtx.RLock() err = writeContainerConfig(filepath.Join(rootPath, ".containerconfig"), config, map[string]string{ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "TERM": "xterm", "HOME": "/", }, l.defaultEnv, job.Config.Env, map[string]string{ "HOSTNAME": job.ID, }, ) l.envMtx.RUnlock() if err != nil { g.Log(grohl.Data{"at": "write_config", "status": "error", "err": err}) return err } l.state.AddJob(job, container.IP) domain := &lt.Domain{ Type: "lxc", Name: job.ID, Memory: lt.UnitInt{Value: 1, Unit: "GiB"}, OS: lt.OS{ Type: lt.OSType{Value: "exe"}, Init: "/.containerinit", }, Devices: lt.Devices{ Filesystems: []lt.Filesystem{{ Type: "mount", Source: lt.FSRef{Dir: rootPath}, Target: lt.FSRef{Dir: "/"}, }}, Consoles: []lt.Console{{Type: "pty"}}, }, OnPoweroff: "preserve", OnCrash: "preserve", } if spec, ok := job.Resources[resource.TypeMemory]; ok && spec.Limit != nil { domain.Memory = lt.UnitInt{Value: *spec.Limit, Unit: "bytes"} } if !job.Config.HostNetwork { domain.Devices.Interfaces = []lt.Interface{{ Type: "network", Source: lt.InterfaceSrc{Network: libvirtNetName}, }} } // attempt to run libvirt commands multiple times in case the libvirt daemon is // temporarily unavailable (e.g. it has restarted, which sometimes happens in CI) g.Log(grohl.Data{"at": "define_domain"}) var vd libvirt.VirDomain if err := l.withConnRetries(func() (err error) { vd, err = l.libvirt.DomainDefineXML(string(domain.XML())) return }); err != nil { g.Log(grohl.Data{"at": "define_domain", "status": "error", "err": err}) return err } g.Log(grohl.Data{"at": "create_domain"}) if err := l.withConnRetries(vd.Create); err != nil { g.Log(grohl.Data{"at": "create_domain", "status": "error", "err": err}) return err } uuid, err := vd.GetUUIDString() if err != nil { g.Log(grohl.Data{"at": "get_domain_uuid", "status": "error", "err": err}) return err } g.Log(grohl.Data{"at": "get_uuid", "uuid": uuid}) l.state.SetContainerID(job.ID, uuid) domainXML, err := vd.GetXMLDesc(0) if err != nil { g.Log(grohl.Data{"at": "get_domain_xml", "status": "error", "err": err}) return err } domain = &lt.Domain{} if err := xml.Unmarshal([]byte(domainXML), domain); err != nil { g.Log(grohl.Data{"at": "unmarshal_domain_xml", "status": "error", "err": err}) return err } go container.watch(nil) g.Log(grohl.Data{"at": "finish"}) return nil } func (l *LibvirtLXCBackend) openLog(id string) *logbuf.Log { l.logsMtx.Lock() defer l.logsMtx.Unlock() if _, ok := l.logs[id]; !ok { // TODO: configure retention and log size l.logs[id] = logbuf.NewLog(&lumberjack.Logger{Filename: filepath.Join(l.LogPath, id, id+".log")}) } // TODO: do reference counting and remove logs that are not in use from memory return l.logs[id] } func (c *libvirtContainer) watch(ready chan<- error) error { g := grohl.NewContext(grohl.Data{"backend": "libvirt-lxc", "fn": "watch_container", "job.id": c.job.ID}) g.Log(grohl.Data{"at": "start"}) defer func() { // TODO: kill containerinit/domain if it is still running c.l.containersMtx.Lock() delete(c.l.containers, c.job.ID) c.l.containersMtx.Unlock() c.cleanup() close(c.done) }() var symlinked bool var err error symlink := "/tmp/containerinit-rpc." + c.job.ID socketPath := path.Join(c.RootPath, containerinit.SocketPath) for startTime := time.Now(); time.Since(startTime) < 10*time.Second; time.Sleep(time.Millisecond) { if !symlinked { // We can't connect to the socket file directly because // the path to it is longer than 108 characters (UNIX_PATH_MAX). // Create a temporary symlink to connect to. if err = os.Symlink(socketPath, symlink); err != nil && !os.IsExist(err) { g.Log(grohl.Data{"at": "symlink_socket", "status": "error", "err": err, "source": socketPath, "target": symlink}) continue } defer os.Remove(symlink) symlinked = true } c.Client, err = containerinit.NewClient(symlink) if err == nil { break } } if ready != nil { ready <- err } if err != nil { g.Log(grohl.Data{"at": "connect", "status": "error", "err": err.Error()}) c.l.state.SetStatusFailed(c.job.ID, errors.New("failed to connect to container")) d, e := c.l.libvirt.LookupDomainByName(c.job.ID) if e != nil { return e } if err := d.Destroy(); err != nil { g.Log(grohl.Data{"at": "destroy", "status": "error", "err": err.Error()}) } return err } defer c.Client.Close() c.l.containersMtx.Lock() c.l.containers[c.job.ID] = c c.l.containersMtx.Unlock() if !c.job.Config.DisableLog && !c.job.Config.TTY { g.Log(grohl.Data{"at": "get_stdout"}) stdout, stderr, initLog, err := c.Client.GetStreams() if err != nil { g.Log(grohl.Data{"at": "get_streams", "status": "error", "err": err.Error()}) return err } log := c.l.openLog(c.job.ID) defer log.Close() muxConfig := logmux.Config{ AppID: c.job.Metadata["flynn-controller.app"], HostID: c.l.state.id, JobType: c.job.Metadata["flynn-controller.type"], JobID: c.job.ID, } // TODO(benburkert): remove file logging once attach proto uses logaggregator streams := []io.Reader{stdout, stderr} for i, stream := range streams { bufr, bufw := io.Pipe() muxr, muxw := io.Pipe() go func(r io.Reader, pw1, pw2 *io.PipeWriter) { mw := io.MultiWriter(pw1, pw2) _, err := io.Copy(mw, r) pw1.CloseWithError(err) pw2.CloseWithError(err) }(stream, bufw, muxw) fd := i + 1 go log.Follow(fd, bufr) go c.l.mux.Follow(muxr, fd, muxConfig) } go log.Follow(3, initLog) } g.Log(grohl.Data{"at": "watch_changes"}) for change := range c.Client.StreamState() { g.Log(grohl.Data{"at": "change", "state": change.State.String()}) if change.Error != "" { err := errors.New(change.Error) g.Log(grohl.Data{"at": "change", "status": "error", "err": err}) c.Client.Resume() c.l.state.SetStatusFailed(c.job.ID, err) return err } switch change.State { case containerinit.StateInitial: g.Log(grohl.Data{"at": "wait_attach"}) c.l.state.WaitAttach(c.job.ID) g.Log(grohl.Data{"at": "resume"}) c.Client.Resume() case containerinit.StateRunning: g.Log(grohl.Data{"at": "running"}) c.l.state.SetStatusRunning(c.job.ID) // if the job was stopped before it started, exit if c.l.state.GetJob(c.job.ID).ForceStop { c.Stop() } case containerinit.StateExited: g.Log(grohl.Data{"at": "exited", "status": change.ExitStatus}) c.Client.Resume() c.l.state.SetStatusDone(c.job.ID, change.ExitStatus) return nil case containerinit.StateFailed: g.Log(grohl.Data{"at": "failed"}) c.Client.Resume() c.l.state.SetStatusFailed(c.job.ID, errors.New("container failed to start")) return nil } } g.Log(grohl.Data{"at": "unknown_failure"}) c.l.state.SetStatusFailed(c.job.ID, errors.New("unknown failure")) return nil } func (c *libvirtContainer) cleanup() error { g := grohl.NewContext(grohl.Data{"backend": "libvirt-lxc", "fn": "cleanup", "job.id": c.job.ID}) g.Log(grohl.Data{"at": "start"}) if err := syscall.Unmount(filepath.Join(c.RootPath, ".containerinit"), 0); err != nil { g.Log(grohl.Data{"at": "unmount", "file": ".containerinit", "status": "error", "err": err}) } if err := syscall.Unmount(filepath.Join(c.RootPath, "etc/resolv.conf"), 0); err != nil { g.Log(grohl.Data{"at": "unmount", "file": "resolv.conf", "status": "error", "err": err}) } if err := c.l.pinkerton.Cleanup(c.job.ID); err != nil { g.Log(grohl.Data{"at": "pinkerton", "status": "error", "err": err}) } for _, m := range c.job.Config.Mounts { if err := syscall.Unmount(filepath.Join(c.RootPath, m.Location), 0); err != nil { g.Log(grohl.Data{"at": "unmount", "location": m.Location, "status": "error", "err": err}) } } for _, v := range c.job.Config.Volumes { if err := syscall.Unmount(filepath.Join(c.RootPath, v.Target), 0); err != nil { g.Log(grohl.Data{"at": "unmount", "target": v.Target, "volumeID": v.VolumeID, "status": "error", "err": err}) } } if !c.job.Config.HostNetwork && c.l.bridgeNet != nil { c.l.ipalloc.ReleaseIP(c.l.bridgeNet, c.IP) } g.Log(grohl.Data{"at": "finish"}) return nil } func (c *libvirtContainer) WaitStop(timeout time.Duration) error { job := c.l.state.GetJob(c.job.ID) if job.Status == host.StatusDone || job.Status == host.StatusFailed { return nil } select { case <-c.done: return nil case <-time.After(timeout): return fmt.Errorf("Timed out: %v", timeout) } } func (c *libvirtContainer) Stop() error { if err := c.Signal(int(syscall.SIGTERM)); err != nil { return err } if err := c.WaitStop(10 * time.Second); err != nil { return c.Signal(int(syscall.SIGKILL)) } return nil } func (l *LibvirtLXCBackend) Stop(id string) error { c, err := l.getContainer(id) if err != nil { return err } return c.Stop() } func (l *LibvirtLXCBackend) getContainer(id string) (*libvirtContainer, error) { l.containersMtx.RLock() defer l.containersMtx.RUnlock() c := l.containers[id] if c == nil { return nil, errors.New("libvirt: unknown container") } return c, nil } func (l *LibvirtLXCBackend) ResizeTTY(id string, height, width uint16) error { container, err := l.getContainer(id) if err != nil { return err } if !container.job.Config.TTY { return errors.New("job doesn't have a TTY") } pty, err := container.GetPtyMaster() if err != nil { return err } return term.SetWinsize(pty.Fd(), &term.Winsize{Height: height, Width: width}) } func (l *LibvirtLXCBackend) Signal(id string, sig int) error { container, err := l.getContainer(id) if err != nil { return err } return container.Signal(sig) } func (l *LibvirtLXCBackend) Attach(req *AttachRequest) (err error) { client, err := l.getContainer(req.Job.Job.ID) if err != nil && (req.Job.Job.Config.TTY || req.Stdin != nil) { return err } defer func() { if client != nil && (req.Job.Job.Config.TTY || req.Stream) && err == io.EOF { <-client.done job := l.state.GetJob(req.Job.Job.ID) if job.Status == host.StatusDone || job.Status == host.StatusCrashed { err = ExitError(job.ExitStatus) return } err = errors.New(*job.Error) } }() if req.Job.Job.Config.TTY { pty, err := client.GetPtyMaster() if err != nil { return err } if err := term.SetWinsize(pty.Fd(), &term.Winsize{Height: req.Height, Width: req.Width}); err != nil { return err } if req.Attached != nil { req.Attached <- struct{}{} } if req.Stdin != nil && req.Stdout != nil { go io.Copy(pty, req.Stdin) } else if req.Stdin != nil { io.Copy(pty, req.Stdin) } if req.Stdout != nil { io.Copy(req.Stdout, pty) } pty.Close() return io.EOF } if req.Stdin != nil { stdinPipe, err := client.GetStdin() if err != nil { return err } go func() { io.Copy(stdinPipe, req.Stdin) stdinPipe.Close() }() } if req.Job.Job.Config.DisableLog { stdout, stderr, initLog, err := client.GetStreams() if err != nil { return err } if req.Attached != nil { req.Attached <- struct{}{} } var wg sync.WaitGroup cp := func(w io.Writer, r io.Reader) { if w == nil { w = ioutil.Discard } wg.Add(1) go func() { io.Copy(w, r) wg.Done() }() } cp(req.InitLog, initLog) cp(req.Stdout, stdout) cp(req.Stderr, stderr) wg.Wait() return io.EOF } if req.Attached != nil { req.Attached <- struct{}{} } lines := -1 if !req.Logs { lines = 0 } log := l.openLog(req.Job.Job.ID) ch := make(chan logbuf.Data) done := make(chan struct{}) go log.Read(lines, req.Stream, ch, done) defer close(done) for data := range ch { var w io.Writer switch data.Stream { case 1: w = req.Stdout case 2: w = req.Stderr case 3: w = req.InitLog } if w == nil { continue } if _, err := w.Write([]byte(data.Message)); err != nil { return nil } } return io.EOF } func (l *LibvirtLXCBackend) Cleanup() error { g := grohl.NewContext(grohl.Data{"backend": "libvirt-lxc", "fn": "Cleanup"}) l.containersMtx.Lock() ids := make([]string, 0, len(l.containers)) for id := range l.containers { ids = append(ids, id) } l.containersMtx.Unlock() g.Log(grohl.Data{"at": "start", "count": len(ids)}) errs := make(chan error) for _, id := range ids { go func(id string) { g.Log(grohl.Data{"at": "stop", "job.id": id}) err := l.Stop(id) if err != nil { g.Log(grohl.Data{"at": "error", "job.id": id, "err": err.Error()}) } errs <- err }(id) } var err error for i := 0; i < len(ids); i++ { stopErr := <-errs if stopErr != nil { err = stopErr } } g.Log(grohl.Data{"at": "finish"}) return err } /* Loads a series of jobs, and reconstructs whatever additional backend state was saved. This may include reconnecting rpc systems and communicating with containers (thus this may take a significant moment; it's not just deserializing). */ func (l *LibvirtLXCBackend) UnmarshalState(jobs map[string]*host.ActiveJob, jobBackendStates map[string][]byte, backendGlobalState []byte) error { containers := make(map[string]*libvirtContainer) for k, v := range jobBackendStates { container := &libvirtContainer{} if err := json.Unmarshal(v, container); err != nil { return fmt.Errorf("failed to deserialize backed container state: %s", err) } containers[k] = container } readySignals := make(map[string]chan error) // for every job with a matching container, attempt to restablish a connection for _, j := range jobs { container, ok := containers[j.Job.ID] if !ok { continue } container.l = l container.job = j.Job container.done = make(chan struct{}) readySignals[j.Job.ID] = make(chan error) go container.watch(readySignals[j.Job.ID]) } // gather connection attempts and finish reconstruction if success. failures will time out. for _, j := range jobs { container, ok := containers[j.Job.ID] if !ok { continue } if err := <-readySignals[j.Job.ID]; err != nil { // log error l.state.RemoveJob(j.Job.ID) container.cleanup() continue } l.containers[j.Job.ID] = container } return nil } func (l *LibvirtLXCBackend) MarshalJobState(jobID string) ([]byte, error) { l.containersMtx.RLock() defer l.containersMtx.RUnlock() if associatedState, exists := l.containers[jobID]; exists { return json.Marshal(associatedState) } return nil, nil } func (l *LibvirtLXCBackend) pinkertonPull(url string) ([]layer.PullInfo, error) { var layers []layer.PullInfo info := make(chan layer.PullInfo) done := make(chan struct{}) go func() { for l := range info { layers = append(layers, l) } close(done) }() if err := l.pinkerton.PullDocker(url, info); err != nil { return nil, err } <-done return layers, nil } func bindMount(src, dest string, writeable, private bool) error { srcStat, err := os.Stat(src) if err != nil { return err } if _, err := os.Stat(dest); os.IsNotExist(err) { if srcStat.IsDir() { if err := os.MkdirAll(dest, 0755); err != nil { return err } } else { if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } f, err := os.OpenFile(dest, os.O_CREATE, 0755) if err != nil { return err } f.Close() } } else if err != nil { return err } flags := syscall.MS_BIND | syscall.MS_REC if !writeable { flags |= syscall.MS_RDONLY } if err := syscall.Mount(src, dest, "bind", uintptr(flags), ""); err != nil { return err } if private { if err := syscall.Mount("", dest, "none", uintptr(syscall.MS_PRIVATE), ""); err != nil { return err } } return nil }
technosophos/flynn
host/libvirt_lxc_backend.go
GO
bsd-3-clause
30,467
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.core.view.opengl.picking; /** * Provides a label that depends on a {@link Pick}. * * @author Christian Partl * */ public interface IPickingLabelProvider { /** * Returns a label depending on the provided {@link Pick}. * * @param pick * @return */ public String getLabel(Pick pick); }
Caleydo/caleydo
org.caleydo.ui/src/org/caleydo/core/view/opengl/picking/IPickingLabelProvider.java
Java
bsd-3-clause
691
package proxy import ( "fmt" "github.com/hashicorp/serf/command" "github.com/mitchellh/cli" "math/rand" "strings" ) // Service contains all the addresses for a current service. // The Service current supports random retrieval of available services. type Service struct { // name of service name string // ip and port that host service Addresses []string } // NewService creates a Service instance func NewService(name string) *Service { return &Service{name: name} } // addAddress adds a provided node to the Service func (s *Service) addAddress(addr string) error { s.Addresses = append(s.Addresses, addr) return nil } // getAddress returns a random node that implements the Service func (s *Service) getAddress() (address string, err error) { err = nil address = "" if len(s.Addresses) > 0 { address = s.Addresses[rand.Intn(len(s.Addresses))] } else { err = fmt.Errorf("Address does not exist for service: %s", s.name) } return address, err } // MembersWrite handles serf output (implements Writer interface) type MembersWrite struct { bytes []byte } // Write implements the Writer interface and handles serf output func (w *MembersWrite) Write(p []byte) (n int, err error) { n = len(p) w.bytes = append(w.bytes, p...) err = nil return n, err } // GetString retrieves the string in MembersWrite func (w *MembersWrite) GetString() string { return string(w.bytes[:]) } // Registry contains the mapping of service names to Service objects type Registry struct { services map[string]*Service } // UpdateRegistry computes attached services from serf network func (r *Registry) UpdateRegistry() error { // retrieve members that are alive writer := new(MembersWrite) ui := &cli.BasicUi{Writer: writer} mc := &command.MembersCommand{Ui: ui} var dargs []string dargs = append(dargs, "-status=alive") dargs = append(dargs, "-rpc-addr="+rpcAddr) mc.Run(dargs) mem_str := writer.GetString() mems := strings.Split(strings.Trim(mem_str, "\n"), "\n") r.services = make(map[string]*Service) // parse members from serf output for _, member := range mems { fields := strings.Fields(member) serviceport := strings.Split(fields[0], "#") // there should be no hash marks int the name service_name := serviceport[0] if service_name == "proxy" { continue } if len(serviceport) != 2 { fmt.Errorf("service name incorrectly formatted: %s ", serviceport) continue } complete_address_name := serviceport[1] // service_address := strings.Split(complete_address_name, ":") if len(fields) != 3 { fmt.Errorf("incorrect number of fields for service") continue } // TODO: should make sure that the IP address of serf agent // and the encoded service name are the same // address_fields := strings.Split(fields[1], ":") // serf_address := address_fields[0] // if serf_address != service_address[0] { // fmt.Errorf("Service address does not match serf agent address: %s\n", service_name) // continue // } _, ok := r.services[service_name] var service *Service if ok { service = r.services[service_name] } else { service = NewService(service_name) r.services[service_name] = service } // add new node address to service service.addAddress(complete_address_name) } return nil } // GetActiveNodes returns all nodes associates with a Service func (r *Registry) GetActiveNodes() []string { var nodes []string unique_nodes := make(map[string]bool) for _, service := range r.services { for _, val := range service.Addresses { addr := strings.Split(val, ":")[0] unique_nodes[addr] = true } } for node, _ := range unique_nodes { nodes = append(nodes, node) } return nodes } // GetServicesSlice returns all services associated with the Registry func (r *Registry) GetServicesSlice() []string { var services []string for key, _ := range r.services { services = append(services, key) } return services } // GetServiceAddrs returns nodes for a given service (if it exists) func (r *Registry) GetServiceAddrs(service string) ([]string, error) { var err error _, ok := r.services[service] var addrs []string if ok { serviceInfo := r.services[service] addrs = serviceInfo.Addresses } else { err = fmt.Errorf("Service not in registry: " + service) } return addrs, err } // GetServiceAddr returns node for a given service (if it exists) func (r *Registry) GetServiceAddr(service string) (string, error) { var err error _, ok := r.services[service] addr := "" if ok { serviceInfo := r.services[service] addr, err = serviceInfo.getAddress() } else { err = fmt.Errorf("Service not in registry: " + service) } return addr, err }
janelia-flyem/serviceproxy
proxy/registry.go
GO
bsd-3-clause
4,689
""" Generic, configurable scatterplot """ import collections import warnings import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd import seaborn as sns class PlottingAttribute(object): __slots__ = 'groupby', 'title', 'palette', 'group_to_attribute' def __init__(self, groupby, title, palette, order): """An attribute that you want to visualize with a specific visual cue Parameters ---------- groupby : mappable A series or dict or list to groupby on the rows of the data title : str Title of this part of the legend palette : list-like What to plot for each group """ self.groupby = groupby self.title = title self.palette = palette if order is not None: # there's more than one attribute self.group_to_attribute = dict(zip(order, palette)) else: # There's only one attribute self.group_to_attribute = {None: palette[0]} def __getitem__(self, item): return self.group_to_attribute[item] class PlotterMixin(object): """ Must be mixed with something that creates the ``self.plot_data`` attribute Attributes ---------- color : """ # Markers that can be filled, in a reasonable order so things that can be # confused with each other (e.g. triangles pointing to the left or right) are # not next to each other filled_markers = (u'o', u'v', u's', u'*', u'h', u'<', u'H', u'x', u'8', u'>', u'D', u'd', u'^') linewidth_min, linewidth_max = 0.1, 5 alpha_min, alpha_max = 0.1, 1 size_min, size_max = 3, 30 legend_order = 'color', 'symbol', 'linewidth', 'edgecolor', 'alpha', 'size' def establish_colors(self, color, hue, hue_order, palette): """Get a list of colors for the main component of the plots.""" n_colors = None current_palette = sns.utils.get_color_cycle() color_labels = None color_title = None if color is not None and palette is not None: error = 'Cannot interpret colors to plot when both "color" and ' \ '"palette" are specified' raise ValueError(error) # Force "hue" to be a mappable if hue is not None: try: # Check if "hue" is a column in the data color_title = str(hue) hue = self.data[hue] except (ValueError, KeyError): # Hue is already a mappable if isinstance(hue, pd.Series): color_title = hue.name else: color_title = None # This will give the proper number of categories even if there are # more categories in "hue_order" than represented in "hue" hue_order = sns.utils.categorical_order(hue, hue_order) color_labels = hue_order hue = pd.Categorical(hue, hue_order) n_colors = len(self.plot_data.groupby(hue)) else: if hue_order is not None: # Check if "hue_order" specifies rows in the data samples_to_plot = self.plot_data.index.intersection(hue_order) n_colors = len(samples_to_plot) if n_colors > 0: # Different color for every sample (row name) hue = pd.Series(self.plot_data.index, index=self.plot_data.index) else: error = "When 'hue=None' and 'hue_order' is specified, " \ "'hue_order' must overlap with the data row " \ "names (index)" raise ValueError(error) else: # Same color for everything hue = pd.Series('hue', index=self.plot_data.index) n_colors = 1 if palette is not None: colors = sns.color_palette(palette, n_colors=n_colors) elif color is not None: colors = sns.light_palette(color, n_colors=n_colors) else: colors = sns.light_palette(current_palette[0], n_colors=n_colors) self.color = PlottingAttribute(hue, color_title, colors, hue_order) def _maybe_make_grouper(self, attribute, palette_maker, order=None, func=None, default=None): """Create a Series from a single attribute, else make categorical Checks if the attribute is in the data provided, or is an external mapper Parameters ---------- attribute : object Either a single item to create into a series, or a series mapping each sample to an attribute (e.g. the plotting symbol 'o' or linewidth 1) palette_maker : function Function which takes an integer and creates the appropriate palette for the attribute, e.g. shades of grey for edgecolor or linearly spaced sizes order : list The order to create the attributes into func : function A function which returns true if the attribute is a single valid instance, e.g. "black" for color or 0.1 for linewidth. Otherwise, we assume that "attribute" is a mappable Returns ------- grouper : pandas.Series A mapping of the high dimensional data samples to the attribute """ title = None if func is None or func(attribute): # Use this single attribute for everything return PlottingAttribute(pd.Series(None, index=self.samples), title, (attribute,), order) else: try: # Check if this is a column in the data attribute = self.data[attribute] except (ValueError, KeyError): pass if isinstance(attribute, pd.Series): title = attribute.name order = sns.utils.categorical_order(attribute, order) palette = palette_maker(len(order)) attribute = pd.Categorical(attribute, categories=order, ordered=True) return PlottingAttribute(pd.Series(attribute, index=self.samples), title, palette, order) def establish_symbols(self, marker, marker_order, text, text_order): """Figure out what symbol put on the axes for each data point""" symbol_title = None if isinstance(text, bool): # Option 1: Text is a boolean if text: # 1a: text=True, so use the sample names of data as the # plotting symbol symbol_title = 'Samples' symbols = [str(x) for x in self.samples] symbol = pd.Series(self.samples, index=self.samples) else: # 1b: text=False, so use the specified marker for each sample symbol = self._maybe_make_grouper(marker, marker_order, str) if marker is not None: try: symbol_title = marker symbol = self.data[marker] symbols = sns.categorical_order(symbol, marker_order) except (ValueError, KeyError): # Marker is a single marker, or already a groupable if marker in self.filled_markers: # Single marker so make a tuple so it's indexable symbols = (marker,) else: # already a groupable object if isinstance(marker, pd.Series): symbol_title = marker.name n_symbols = len(self.plot_data.groupby(symbol)) if n_symbols > len(self.filled_markers): # If there's too many categories, then # auto-expand the existing list of filled # markers multiplier = np.ceil( n_symbols/float(len(self.filled_markers))) filled_markers = list(self.filled_markers) \ * multiplier symbols = filled_markers[:n_symbols] else: symbols = self.filled_markers[:n_symbols] symbol = PlottingAttribute(symbol, symbol_title, symbols, marker_order) else: # Assume "text" is a mapping from row names (sample ids) of the # data to text labels text_order = sns.utils.categorical_order(text, text_order) symbols = text_order symbol = pd.Series(pd.Categorical(text, categories=text_order, ordered=True), index=self.samples) symbol = PlottingAttribute(symbol, symbol_title, symbols, text_order) if marker is not None: warnings.warn('Overriding plotting symbol from "marker" with ' 'values in "text"') # Turn text into a boolean text = True self.symbol = symbol self.text = text def establish_symbol_attributes(self,linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order): self.edgecolor = self._maybe_make_grouper( edgecolor, self._edgecolor_palette, edgecolor_order, mpl.colors.is_color_like) self.linewidth = self._maybe_make_grouper( linewidth, self._linewidth_palette, linewidth_order, np.isfinite) self.alpha = self._maybe_make_grouper( alpha, self._alpha_palette, alpha_order, np.isfinite) self.size = self._maybe_make_grouper( size, self._size_palette, size_order, np.isfinite) @staticmethod def _edgecolor_palette(self, n_groups): return sns.color_palette('Greys', n_colors=n_groups) def _linewidth_palette(self, n_groups): return np.linspace(self.linewidth_min, self.linewidth_max, n_groups) def _alpha_palette(self, n_groups): return np.linspace(self.alpha_min, self.alpha_max, n_groups) def _size_palette(self, n_groups): return np.linspace(self.size_min, self.size_max, n_groups) def symbolplotter(self, xs, ys, ax, symbol, linewidth, edgecolor, **kwargs): """Plots either a matplotlib marker or a string at each data position Wraps plt.text and plt.plot Parameters ---------- xs : array-like List of x positions for data ys : array-like List of y-positions for data symbol : str What to plot at each (x, y) data position text : bool If true, then "symboL" is assumed to be a string and iterates over each data point individually, using plt.text to position the text. Otherwise, "symbol" is a matplotlib marker and uses plt.plot for plotting kwargs Any other keyword arguments to plt.text or plt.plot """ # If both the x- and y- positions don't have data, don't do anything if xs.empty and ys.empty: return if self.text: # Add dummy plot to make the axes in the right window ax.plot(xs, ys, color=None) # Plot each (x, y) position as text for x, y in zip(xs, ys): ax.text(x, y, symbol, **kwargs) else: # use plt.plot instead of plt.scatter for speed, since plotting all # the same marker shape and color and linestyle ax.plot(xs, ys, 'o', marker=symbol, markeredgewidth=linewidth, markeredgecolor=edgecolor, **kwargs) def annotate_axes(self, ax): """Add descriptive labels to an Axes object.""" if self.xlabel is not None: ax.set_xlabel(self.xlabel) if self.ylabel is not None: ax.set_ylabel(self.ylabel) def establish_legend_data(self): self.legend_data = pd.DataFrame(dict(color=self.color.groupby, symbol=self.symbol.groupby, size=self.size.groupby, linewidth=self.linewidth.groupby, edgecolor=self.edgecolor.groupby, alpha=self.alpha.groupby), index=self.samples) self.legend_data = self.legend_data.reindex(columns=self.legend_order) def draw_symbols(self, ax, plot_kws): """Plot each sample in the data""" plot_kws = {} if plot_kws is None else plot_kws for labels, df in self.legend_data.groupby(self.legend_order): # Get the attributes in order, using the group label to get the # attribute for name, label in zip(self.legend_order, labels): plot_kws[name] = getattr(self, name)[label] self.symbolplotter(df.iloc[:, 0], df.iloc[:, 1], **plot_kws) # Iterate over all the possible modifications of the points # TODO: add alpha and size # for i, (color_label, df1) in enumerate(self.plot_data.groupby(self.color.groupby)): # color = self.color.palette[i] # for j, (marker_label, df2) in enumerate(df1.groupby(self.symbol.groupby)): # symbol = self.symbol.palette[j] # for k, (lw_label, df3) in enumerate(df2.groupby(self.linewidth.groupby)): # linewidth = self.linewidth.palette[k] # for l, (ec_label, df4) in df3.groupby(self.edgecolor): # edgecolor = self.edgecolor.palette[l] # # and finally ... actually plot the data! # for m # self.symbolplotter(df4.iloc[:, 0], df4.iloc[:, 1], # symbol=symbol, color=color, # ax=ax, linewidth=linewidth, # edgecolor=edgecolor, **plot_kws) # class ScatterPlotter(PlotterMixin): def __init__(self, data, x, y, color, hue, hue_order, palette, marker, marker_order, text, text_order, linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order): self.establish_data(data, x, y) self.establish_symbols(marker, marker_order, text, text_order) self.establish_symbol_attributes(linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order) self.establish_colors(color, hue, hue_order, palette) self.establish_legend_data() # import pdb; pdb.set_trace() def establish_data(self, data, x, y): if isinstance(data, pd.DataFrame): xlabel = data.columns[x] ylabel = data.columns[y] else: data = pd.DataFrame(data) xlabel = None ylabel = None self.data = data self.plot_data = self.data.iloc[:, [x, y]] self.xlabel = xlabel self.ylabel = ylabel self.samples = self.plot_data.index self.features = self.plot_data.columns self.n_samples = len(self.samples) self.n_features = len(self.features) def plot(self, ax, kwargs): self.draw_symbols(ax, kwargs) self.annotate_axes(ax) def scatterplot(data, x=0, y=1, color=None, hue=None, hue_order=None, palette=None, marker='o', marker_order=None, text=False, text_order=None, linewidth=1, linewidth_order=None, edgecolor='k', edgecolor_order=None, alpha=1, alpha_order=None, size=7, size_order=None, ax=None, **kwargs): plotter = ScatterPlotter(data, x, y, color, hue, hue_order, palette, marker, marker_order, text, text_order, linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order) if ax is None: ax = plt.gca() plotter.plot(ax, kwargs) return ax
olgabot/cupcake
cupcake/scatter.py
Python
bsd-3-clause
16,979
<?php namespace app\admin\models; use Yii; use yii\base\Model; use app\admin\models\Admin as User; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } else { return false; } } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); } return $this->_user; } }
froyot/mdBlog
admin/models/LoginForm.php
PHP
bsd-3-clause
1,954
import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ImproperlyConfigured from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand): help = 'Clean filebased cache' def handle(self, **options): os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)
dpetzold/django-cacheops
cacheops/management/commands/cleanfilecache.py
Python
bsd-3-clause
407
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/callback_helpers.h" #include "base/gtest_prod_util.h" #include "base/message_loop.h" #include "base/stl_util.h" #include "base/stringprintf.h" #include "media/base/audio_timestamp_helper.h" #include "media/base/data_buffer.h" #include "media/base/gmock_callback_support.h" #include "media/base/mock_audio_renderer_sink.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" #include "media/filters/audio_renderer_impl.h" #include "testing/gtest/include/gtest/gtest.h" using ::base::Time; using ::base::TimeDelta; using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::Return; using ::testing::ReturnRef; using ::testing::NiceMock; using ::testing::StrictMock; namespace media { // Constants for distinguishing between muted audio and playing audio when using // ConsumeBufferedData(). static uint8 kMutedAudio = 0x00; static uint8 kPlayingAudio = 0x99; class AudioRendererImplTest : public ::testing::Test { public: // Give the decoder some non-garbage media properties. AudioRendererImplTest() : renderer_(new AudioRendererImpl( message_loop_.message_loop_proxy(), new NiceMock<MockAudioRendererSink>(), SetDecryptorReadyCB())), demuxer_stream_(new MockDemuxerStream()), decoder_(new MockAudioDecoder()), audio_config_(kCodecVorbis, kSampleFormatPlanarF32, CHANNEL_LAYOUT_STEREO, 44100, NULL, 0, false) { EXPECT_CALL(*demuxer_stream_, type()) .WillRepeatedly(Return(DemuxerStream::AUDIO)); EXPECT_CALL(*demuxer_stream_, audio_decoder_config()) .WillRepeatedly(ReturnRef(audio_config_)); // Stub out time. renderer_->set_now_cb_for_testing(base::Bind( &AudioRendererImplTest::GetTime, base::Unretained(this))); // Used to save callbacks and run them at a later time. EXPECT_CALL(*decoder_, Read(_)) .WillRepeatedly(Invoke(this, &AudioRendererImplTest::ReadDecoder)); // Set up audio properties. EXPECT_CALL(*decoder_, bits_per_channel()) .WillRepeatedly(Return(audio_config_.bits_per_channel())); EXPECT_CALL(*decoder_, channel_layout()) .WillRepeatedly(Return(CHANNEL_LAYOUT_MONO)); EXPECT_CALL(*decoder_, samples_per_second()) .WillRepeatedly(Return(audio_config_.samples_per_second())); } virtual ~AudioRendererImplTest() { SCOPED_TRACE("~AudioRendererImplTest()"); WaitableMessageLoopEvent event; renderer_->Stop(event.GetClosure()); event.RunAndWait(); } void ExpectUnsupportedAudioDecoder() { EXPECT_CALL(*decoder_, Initialize(_, _, _)) .WillOnce(RunCallback<1>(DECODER_ERROR_NOT_SUPPORTED)); } void ExpectUnsupportedAudioDecoderConfig() { EXPECT_CALL(*decoder_, bits_per_channel()) .WillRepeatedly(Return(3)); EXPECT_CALL(*decoder_, channel_layout()) .WillRepeatedly(Return(CHANNEL_LAYOUT_UNSUPPORTED)); EXPECT_CALL(*decoder_, samples_per_second()) .WillRepeatedly(Return(0)); EXPECT_CALL(*decoder_, Initialize(_, _, _)) .WillOnce(RunCallback<1>(PIPELINE_OK)); } MOCK_METHOD1(OnStatistics, void(const PipelineStatistics&)); MOCK_METHOD0(OnUnderflow, void()); MOCK_METHOD0(OnDisabled, void()); MOCK_METHOD1(OnError, void(PipelineStatus)); void OnAudioTimeCallback(TimeDelta current_time, TimeDelta max_time) { CHECK(current_time <= max_time); } void Initialize() { EXPECT_CALL(*decoder_, Initialize(_, _, _)) .WillOnce(RunCallback<1>(PIPELINE_OK)); InitializeWithStatus(PIPELINE_OK); int channels = ChannelLayoutToChannelCount(decoder_->channel_layout()); int bytes_per_frame = decoder_->bits_per_channel() * channels / 8; next_timestamp_.reset(new AudioTimestampHelper( bytes_per_frame, decoder_->samples_per_second())); } void InitializeWithStatus(PipelineStatus expected) { SCOPED_TRACE(base::StringPrintf("InitializeWithStatus(%d)", expected)); AudioRendererImpl::AudioDecoderList decoders; decoders.push_back(decoder_); WaitableMessageLoopEvent event; renderer_->Initialize( demuxer_stream_, decoders, event.GetPipelineStatusCB(), base::Bind(&AudioRendererImplTest::OnStatistics, base::Unretained(this)), base::Bind(&AudioRendererImplTest::OnUnderflow, base::Unretained(this)), base::Bind(&AudioRendererImplTest::OnAudioTimeCallback, base::Unretained(this)), ended_event_.GetClosure(), base::Bind(&AudioRendererImplTest::OnDisabled, base::Unretained(this)), base::Bind(&AudioRendererImplTest::OnError, base::Unretained(this))); event.RunAndWaitForStatus(expected); // We should have no reads. EXPECT_TRUE(read_cb_.is_null()); } void Preroll() { Preroll(0, PIPELINE_OK); } void Preroll(int timestamp_ms, PipelineStatus expected) { SCOPED_TRACE(base::StringPrintf("Preroll(%d, %d)", timestamp_ms, expected)); TimeDelta timestamp = TimeDelta::FromMilliseconds(timestamp_ms); next_timestamp_->SetBaseTimestamp(timestamp); // Fill entire buffer to complete prerolling. WaitableMessageLoopEvent event; renderer_->Preroll(timestamp, event.GetPipelineStatusCB()); WaitForPendingRead(); DeliverRemainingAudio(); event.RunAndWaitForStatus(PIPELINE_OK); // We should have no reads. EXPECT_TRUE(read_cb_.is_null()); } void Play() { SCOPED_TRACE("Play()"); WaitableMessageLoopEvent event; renderer_->Play(event.GetClosure()); renderer_->SetPlaybackRate(1.0f); event.RunAndWait(); } void WaitForEnded() { SCOPED_TRACE("WaitForEnded()"); ended_event_.RunAndWait(); } void WaitForPendingRead() { SCOPED_TRACE("WaitForPendingRead()"); if (!read_cb_.is_null()) return; DCHECK(wait_for_pending_read_cb_.is_null()); WaitableMessageLoopEvent event; wait_for_pending_read_cb_ = event.GetClosure(); event.RunAndWait(); DCHECK(!read_cb_.is_null()); DCHECK(wait_for_pending_read_cb_.is_null()); } // Delivers |size| bytes with value kPlayingAudio to |renderer_|. void SatisfyPendingRead(size_t size) { CHECK(!read_cb_.is_null()); scoped_refptr<DataBuffer> buffer = new DataBuffer(size); buffer->SetDataSize(size); memset(buffer->GetWritableData(), kPlayingAudio, buffer->GetDataSize()); buffer->SetTimestamp(next_timestamp_->GetTimestamp()); buffer->SetDuration(next_timestamp_->GetDuration(buffer->GetDataSize())); next_timestamp_->AddBytes(buffer->GetDataSize()); DeliverBuffer(AudioDecoder::kOk, buffer); } void AbortPendingRead() { DeliverBuffer(AudioDecoder::kAborted, NULL); } void DeliverEndOfStream() { DeliverBuffer(AudioDecoder::kOk, DataBuffer::CreateEOSBuffer()); } // Delivers bytes until |renderer_|'s internal buffer is full and no longer // has pending reads. void DeliverRemainingAudio() { SatisfyPendingRead(bytes_remaining_in_buffer()); } // Attempts to consume |size| bytes from |renderer_|'s internal buffer, // returning true if all |size| bytes were consumed, false if less than // |size| bytes were consumed. // // |muted| is optional and if passed will get set if the byte value of // the consumed data is muted audio. bool ConsumeBufferedData(uint32 size, bool* muted) { scoped_array<uint8> buffer(new uint8[size]); uint32 bytes_per_frame = (decoder_->bits_per_channel() / 8) * ChannelLayoutToChannelCount(decoder_->channel_layout()); uint32 requested_frames = size / bytes_per_frame; uint32 frames_read = renderer_->FillBuffer( buffer.get(), requested_frames, 0); if (frames_read > 0 && muted) { *muted = (buffer[0] == kMutedAudio); } return (frames_read == requested_frames); } // Attempts to consume all data available from the renderer. Returns the // number of frames read. Since time is frozen, the audio delay will increase // as frames come in. int ConsumeAllBufferedData() { renderer_->DisableUnderflowForTesting(); int frames_read = 0; int total_frames_read = 0; const int kRequestFrames = 1024; const uint32 bytes_per_frame = (decoder_->bits_per_channel() / 8) * ChannelLayoutToChannelCount(decoder_->channel_layout()); scoped_array<uint8> buffer(new uint8[kRequestFrames * bytes_per_frame]); do { TimeDelta audio_delay = TimeDelta::FromMicroseconds( total_frames_read * Time::kMicrosecondsPerSecond / static_cast<float>(decoder_->samples_per_second())); frames_read = renderer_->FillBuffer( buffer.get(), kRequestFrames, audio_delay.InMilliseconds()); total_frames_read += frames_read; } while (frames_read > 0); return total_frames_read * bytes_per_frame; } uint32 bytes_buffered() { return renderer_->algorithm_->bytes_buffered(); } uint32 buffer_capacity() { return renderer_->algorithm_->QueueCapacity(); } uint32 bytes_remaining_in_buffer() { // This can happen if too much data was delivered, in which case the buffer // will accept the data but not increase capacity. if (bytes_buffered() > buffer_capacity()) { return 0; } return buffer_capacity() - bytes_buffered(); } void CallResumeAfterUnderflow() { renderer_->ResumeAfterUnderflow(false); } TimeDelta CalculatePlayTime(int bytes_filled) { return TimeDelta::FromMicroseconds( bytes_filled * Time::kMicrosecondsPerSecond / renderer_->audio_parameters_.GetBytesPerSecond()); } void EndOfStreamTest(float playback_rate) { Initialize(); Preroll(); Play(); renderer_->SetPlaybackRate(playback_rate); // Drain internal buffer, we should have a pending read. int total_bytes = bytes_buffered(); int bytes_filled = ConsumeAllBufferedData(); WaitForPendingRead(); // Due to how the cross-fade algorithm works we won't get an exact match // between the ideal and expected number of bytes consumed. In the faster // than normal playback case, more bytes are created than should exist and // vice versa in the slower than normal playback case. const float kEpsilon = 0.10 * (total_bytes / playback_rate); EXPECT_NEAR(bytes_filled, total_bytes / playback_rate, kEpsilon); // Figure out how long until the ended event should fire. TimeDelta audio_play_time = CalculatePlayTime(bytes_filled); // Fulfill the read with an end-of-stream packet. We shouldn't report ended // nor have a read until we drain the internal buffer. DeliverEndOfStream(); // Advance time half way without an ended expectation. AdvanceTime(audio_play_time / 2); ConsumeBufferedData(bytes_buffered(), NULL); // Advance time by other half and expect the ended event. AdvanceTime(audio_play_time / 2); ConsumeBufferedData(bytes_buffered(), NULL); WaitForEnded(); } void AdvanceTime(TimeDelta time) { base::AutoLock auto_lock(lock_); time_ += time; } // Fixture members. MessageLoop message_loop_; scoped_refptr<AudioRendererImpl> renderer_; private: Time GetTime() { base::AutoLock auto_lock(lock_); return time_; } void ReadDecoder(const AudioDecoder::ReadCB& read_cb) { // TODO(scherkus): Make this a DCHECK after threading semantics are fixed. if (MessageLoop::current() != &message_loop_) { message_loop_.PostTask(FROM_HERE, base::Bind( &AudioRendererImplTest::ReadDecoder, base::Unretained(this), read_cb)); return; } CHECK(read_cb_.is_null()) << "Overlapping reads are not permitted"; read_cb_ = read_cb; // Wake up WaitForPendingRead() if needed. if (!wait_for_pending_read_cb_.is_null()) base::ResetAndReturn(&wait_for_pending_read_cb_).Run(); } void DeliverBuffer(AudioDecoder::Status status, const scoped_refptr<DataBuffer>& buffer) { CHECK(!read_cb_.is_null()); base::ResetAndReturn(&read_cb_).Run(status, buffer); } scoped_refptr<MockDemuxerStream> demuxer_stream_; scoped_refptr<MockAudioDecoder> decoder_; // Used for stubbing out time in the audio callback thread. base::Lock lock_; Time time_; // Used for satisfying reads. AudioDecoder::ReadCB read_cb_; scoped_ptr<AudioTimestampHelper> next_timestamp_; AudioDecoderConfig audio_config_; WaitableMessageLoopEvent ended_event_; // Run during ReadDecoder() to unblock WaitForPendingRead(). base::Closure wait_for_pending_read_cb_; DISALLOW_COPY_AND_ASSIGN(AudioRendererImplTest); }; TEST_F(AudioRendererImplTest, Initialize_Failed) { ExpectUnsupportedAudioDecoderConfig(); InitializeWithStatus(PIPELINE_ERROR_INITIALIZATION_FAILED); } TEST_F(AudioRendererImplTest, Initialize_Successful) { Initialize(); } TEST_F(AudioRendererImplTest, Initialize_DecoderInitFailure) { ExpectUnsupportedAudioDecoder(); InitializeWithStatus(DECODER_ERROR_NOT_SUPPORTED); } TEST_F(AudioRendererImplTest, Preroll) { Initialize(); Preroll(); } TEST_F(AudioRendererImplTest, Play) { Initialize(); Preroll(); Play(); // Drain internal buffer, we should have a pending read. EXPECT_TRUE(ConsumeBufferedData(bytes_buffered(), NULL)); WaitForPendingRead(); } TEST_F(AudioRendererImplTest, EndOfStream) { EndOfStreamTest(1.0); } TEST_F(AudioRendererImplTest, EndOfStream_FasterPlaybackSpeed) { EndOfStreamTest(2.0); } TEST_F(AudioRendererImplTest, EndOfStream_SlowerPlaybackSpeed) { EndOfStreamTest(0.5); } TEST_F(AudioRendererImplTest, Underflow) { Initialize(); Preroll(); Play(); // Drain internal buffer, we should have a pending read. EXPECT_TRUE(ConsumeBufferedData(bytes_buffered(), NULL)); WaitForPendingRead(); // Verify the next FillBuffer() call triggers the underflow callback // since the decoder hasn't delivered any data after it was drained. const size_t kDataSize = 1024; EXPECT_CALL(*this, OnUnderflow()); EXPECT_FALSE(ConsumeBufferedData(kDataSize, NULL)); renderer_->ResumeAfterUnderflow(false); // Verify after resuming that we're still not getting data. // // NOTE: FillBuffer() satisfies the read but returns muted audio, which // is crazy http://crbug.com/106600 bool muted = false; EXPECT_EQ(0u, bytes_buffered()); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_TRUE(muted); // Deliver data, we should get non-muted audio. DeliverRemainingAudio(); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_FALSE(muted); } TEST_F(AudioRendererImplTest, Underflow_EndOfStream) { Initialize(); Preroll(); Play(); // Figure out how long until the ended event should fire. Since // ConsumeBufferedData() doesn't provide audio delay information, the time // until the ended event fires is equivalent to the longest buffered section, // which is the initial bytes_buffered() read. TimeDelta time_until_ended = CalculatePlayTime(bytes_buffered()); // Drain internal buffer, we should have a pending read. EXPECT_TRUE(ConsumeBufferedData(bytes_buffered(), NULL)); WaitForPendingRead(); // Verify the next FillBuffer() call triggers the underflow callback // since the decoder hasn't delivered any data after it was drained. const size_t kDataSize = 1024; EXPECT_CALL(*this, OnUnderflow()); EXPECT_FALSE(ConsumeBufferedData(kDataSize, NULL)); // Deliver a little bit of data. SatisfyPendingRead(kDataSize); WaitForPendingRead(); // Verify we're getting muted audio during underflow. // // NOTE: FillBuffer() satisfies the read but returns muted audio, which // is crazy http://crbug.com/106600 bool muted = false; EXPECT_EQ(kDataSize, bytes_buffered()); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_TRUE(muted); // Now deliver end of stream, we should get our little bit of data back. DeliverEndOfStream(); EXPECT_EQ(kDataSize, bytes_buffered()); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_FALSE(muted); // Deliver another end of stream buffer and attempt to read to make sure // we're truly at the end of stream. // // TODO(scherkus): fix AudioRendererImpl and AudioRendererAlgorithmBase to // stop reading after receiving an end of stream buffer. It should have also // fired the ended callback http://crbug.com/106641 WaitForPendingRead(); DeliverEndOfStream(); AdvanceTime(time_until_ended); EXPECT_FALSE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_FALSE(muted); WaitForEnded(); } TEST_F(AudioRendererImplTest, Underflow_ResumeFromCallback) { Initialize(); Preroll(); Play(); // Drain internal buffer, we should have a pending read. EXPECT_TRUE(ConsumeBufferedData(bytes_buffered(), NULL)); WaitForPendingRead(); // Verify the next FillBuffer() call triggers the underflow callback // since the decoder hasn't delivered any data after it was drained. const size_t kDataSize = 1024; EXPECT_CALL(*this, OnUnderflow()) .WillOnce(Invoke(this, &AudioRendererImplTest::CallResumeAfterUnderflow)); EXPECT_FALSE(ConsumeBufferedData(kDataSize, NULL)); // Verify after resuming that we're still not getting data. bool muted = false; EXPECT_EQ(0u, bytes_buffered()); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_TRUE(muted); // Deliver data, we should get non-muted audio. DeliverRemainingAudio(); EXPECT_TRUE(ConsumeBufferedData(kDataSize, &muted)); EXPECT_FALSE(muted); } TEST_F(AudioRendererImplTest, AbortPendingRead_Preroll) { Initialize(); // Start prerolling and wait for a read. WaitableMessageLoopEvent event; renderer_->Preroll(TimeDelta(), event.GetPipelineStatusCB()); WaitForPendingRead(); // Simulate the decoder aborting the pending read. AbortPendingRead(); event.RunAndWaitForStatus(PIPELINE_OK); // Preroll again to a different timestamp and verify it completed normally. Preroll(1000, PIPELINE_OK); } TEST_F(AudioRendererImplTest, AbortPendingRead_Pause) { Initialize(); Preroll(); Play(); // Partially drain internal buffer so we get a pending read. EXPECT_TRUE(ConsumeBufferedData(bytes_buffered() / 2, NULL)); WaitForPendingRead(); // Start pausing. WaitableMessageLoopEvent event; renderer_->Pause(event.GetClosure()); // Simulate the decoder aborting the pending read. AbortPendingRead(); event.RunAndWait(); // Preroll again to a different timestamp and verify it completed normally. Preroll(1000, PIPELINE_OK); } } // namespace media
nacl-webkit/chrome_deps
media/filters/audio_renderer_impl_unittest.cc
C++
bsd-3-clause
18,806
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package org.cagrid.tests.data.styles.cacore42.story; import gov.nih.nci.cagrid.common.Utils; import java.io.File; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SDK42DataServiceSystemTests { private static Log LOG = LogFactory.getLog(SDK42DataServiceSystemTests.class); private static File tempApplicationDir; @BeforeClass public static void setUp() throws Throwable { // create a temporary directory for the SDK application to package things in tempApplicationDir = File.createTempFile("SdkExample", "temp"); tempApplicationDir.delete(); tempApplicationDir.mkdirs(); LOG.debug("Created temp application base dir: " + tempApplicationDir.getAbsolutePath()); // throw out the ivy cache dirs used by the SDK LOG.debug("Destroying SDK ivy cache"); NukeIvyCacheStory nukeStory = new NukeIvyCacheStory(); nukeStory.runBare(); // create the caCORE SDK example project LOG.debug("Running caCORE SDK example project creation story"); CreateExampleProjectStory createExampleStory = new CreateExampleProjectStory(tempApplicationDir, false); createExampleStory.runBare(); } @Test public void localSDKApiTests() throws Throwable { // create and run a caGrid Data Service using the SDK's local API LOG.debug("Running data service using local API story"); SDK42StyleLocalApiStory localApiStory = new SDK42StyleLocalApiStory(false, false); localApiStory.runBare(); } @Test public void secureLocalSDKApiTests() throws Throwable { // create and run a secure caGrid Data Service using the SDK's local API LOG.debug("Running secure data service using local API story"); SDK42StyleLocalApiStory secureLocalApiStory = new SDK42StyleLocalApiStory(true, false); secureLocalApiStory.runBare(); } @Test public void remoteSDKApiTests() throws Throwable { // create and run a caGrid Data Service using the SDK's remote API LOG.debug("Running data service using remote API story"); SDK42StyleRemoteApiStory remoteApiStory = new SDK42StyleRemoteApiStory(false); remoteApiStory.runBare(); } @Test public void secureRemoteSDKApiTests() throws Throwable { // create and run a secure caGrid Data Service using the SDK's remote API LOG.debug("Running secure data service using remote API story"); SDK42StyleRemoteApiStory secureRemoteApiStory = new SDK42StyleRemoteApiStory(true); secureRemoteApiStory.runBare(); } @Test public void localSDKApiWithCsmTests() throws Throwable { LOG.debug("Running caCORE SDK example project with CSM creation story"); CreateExampleProjectStory createExampleWithCsmStory = new CreateExampleProjectStory(tempApplicationDir, true); createExampleWithCsmStory.runBare(); // create and run a caGrid Data Service using the SDK's local API LOG.debug("Running secure data service using local API and CSM story"); SDK42StyleLocalApiStory localApiWithCsmStory = new SDK42StyleLocalApiStory(true, true); localApiWithCsmStory.runBare(); } @AfterClass public static void cleanUp() { LOG.debug("Cleaning up after tests"); // throw away the temp sdk dir LOG.debug("Deleting temp application base dir: " + tempApplicationDir.getAbsolutePath()); Utils.deleteDir(tempApplicationDir); } public static void main(String[] args) { TestRunner runner = new TestRunner(); TestResult result = runner.doRun(new TestSuite(SDK42DataServiceSystemTests.class)); System.exit(result.errorCount() + result.failureCount()); } }
NCIP/cagrid-core
integration-tests/projects/sdk42StyleTests/src/org/cagrid/tests/data/styles/cacore42/story/SDK42DataServiceSystemTests.java
Java
bsd-3-clause
4,639
<?php /** * @todo Compose PHP doc */ class TeacherController extends Controller { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'accessControl', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view'), 'users' =>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update'), 'users' =>array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'), 'users' =>array('admin'), ), array('deny', // deny all users 'users' =>array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new Teacher; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Teacher'])) { $model->attributes=$_POST['Teacher']; if($model->save()) $this->redirect(array('view','id'=>$model->TID)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Teacher'])) { $model->attributes=$_POST['Teacher']; if($model->save()) $this->redirect(array('view','id'=>$model->TID)); } $this->render('update',array( 'model'=>$model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Lists all models. */ public function actionIndex() { $model=new Teacher('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Teacher'])) $model->attributes=$_GET['Teacher']; $dataProvider=new CActiveDataProvider('Teacher'); $this->render('index',array( 'model'=>$model, 'dataProvider'=>$dataProvider, )); } /** * Manages all models. */ public function actionAdmin() { $model=new Teacher('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Teacher'])) $model->attributes=$_GET['Teacher']; $this->render('admin',array( 'model'=>$model, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model=Teacher::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='teacher-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } } ?>
wrensly/SegTDD
protected/controllers/TeacherController.php
PHP
bsd-3-clause
4,510
<?php use yii\db\Schema; use yii\db\Migration; class m151130_085523_insert_category_table extends Migration { public function up() { $this->insert('{{%category}}', [ 'id' => 1, 'category_name' => 'Books', ]); $this->insert('{{%category}}', [ 'id' => 2, 'category_name' => 'Commerce', ]); $this->insert('{{%category}}', [ 'id' => 3, 'category_name' => 'Entertainment', ]); $this->insert('{{%category}}', [ 'id' => 4, 'category_name' => 'Fashion', ]); $this->insert('{{%category}}', [ 'id' => 5, 'category_name' => 'Film', ]); $this->insert('{{%category}}', [ 'id' => 6, 'category_name' => 'Health', ]); $this->insert('{{%category}}', [ 'id' => 7, 'category_name' => 'Science', ]); $this->insert('{{%category}}', [ 'id' => 8, 'category_name' => 'Technology', ]); $this->insert('{{%category}}', [ 'id' => 9, 'category_name' => 'History', ]); $this->insert('{{%category}}', [ 'id' => 10, 'category_name' => 'Sport', ]); } public function down() { $this->delete('{{%category}}', ['id' => 1]); $this->delete('{{%category}}', ['id' => 2]); $this->delete('{{%category}}', ['id' => 3]); $this->delete('{{%category}}', ['id' => 4]); $this->delete('{{%category}}', ['id' => 5]); $this->delete('{{%category}}', ['id' => 6]); $this->delete('{{%category}}', ['id' => 7]); $this->delete('{{%category}}', ['id' => 8]); $this->delete('{{%category}}', ['id' => 9]); $this->delete('{{%category}}', ['id' => 10]); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
BorisMatonickin/yiicms
console/migrations/m151130_085523_insert_category_table.php
PHP
bsd-3-clause
2,075
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Network drop-down implementation. */ cr.define('cr.ui', function() { /** * Creates a new container for the drop down menu items. * @constructor * @extends {HTMLDivElement} */ var DropDownContainer = cr.ui.define('div'); DropDownContainer.prototype = { __proto__: HTMLDivElement.prototype, /** @override */ decorate: function() { this.classList.add('dropdown-container'); // Selected item in the menu list. this.selectedItem = null; // First item which could be selected. this.firstItem = null; this.setAttribute('role', 'menu'); // Whether scroll has just happened. this.scrollJustHappened = false; }, /** * Gets scroll action to be done for the item. * @param {!Object} item Menu item. * @return {integer} -1 for scroll up; 0 for no action; 1 for scroll down. */ scrollAction: function(item) { var thisTop = this.scrollTop; var thisBottom = thisTop + this.offsetHeight; var itemTop = item.offsetTop; var itemBottom = itemTop + item.offsetHeight; if (itemTop <= thisTop) return -1; if (itemBottom >= thisBottom) return 1; return 0; }, /** * Selects new item. * @param {!Object} selectedItem Item to be selected. * @param {boolean} mouseOver Is mouseover event triggered? */ selectItem: function(selectedItem, mouseOver) { if (mouseOver && this.scrollJustHappened) { this.scrollJustHappened = false; return; } if (this.selectedItem) this.selectedItem.classList.remove('hover'); selectedItem.classList.add('hover'); this.selectedItem = selectedItem; if (!this.hidden) { this.previousSibling.setAttribute( 'aria-activedescendant', selectedItem.id); } var action = this.scrollAction(selectedItem); if (action != 0) { selectedItem.scrollIntoView(action < 0); this.scrollJustHappened = true; } } }; /** * Creates a new DropDown div. * @constructor * @extends {HTMLDivElement} */ var DropDown = cr.ui.define('div'); DropDown.ITEM_DIVIDER_ID = -2; DropDown.KEYCODE_DOWN = 40; DropDown.KEYCODE_ENTER = 13; DropDown.KEYCODE_ESC = 27; DropDown.KEYCODE_SPACE = 32; DropDown.KEYCODE_TAB = 9; DropDown.KEYCODE_UP = 38; DropDown.prototype = { __proto__: HTMLDivElement.prototype, /** @override */ decorate: function() { this.appendChild(this.createOverlay_()); this.appendChild(this.title_ = this.createTitle_()); var container = new DropDownContainer(); container.id = this.id + '-dropdown-container'; this.appendChild(container); this.addEventListener('keydown', this.keyDownHandler_); this.title_.id = this.id + '-dropdown'; this.title_.setAttribute('role', 'button'); this.title_.setAttribute('aria-haspopup', 'true'); this.title_.setAttribute('aria-owns', container.id); }, /** * Returns true if dropdown menu is shown. * @type {bool} Whether menu element is shown. */ get isShown() { return !this.container.hidden; }, /** * Sets dropdown menu visibility. * @param {bool} show New visibility state for dropdown menu. */ set isShown(show) { this.firstElementChild.hidden = !show; this.container.hidden = !show; if (show) { this.container.selectItem(this.container.firstItem, false); } else { this.title_.removeAttribute('aria-activedescendant'); } }, /** * Returns container of the menu items. */ get container() { return this.lastElementChild; }, /** * Sets title and icon. * @param {string} title Text on dropdown. * @param {string} icon Icon in dataURL format. */ setTitle: function(title, icon) { this.title_.firstElementChild.src = icon; this.title_.lastElementChild.textContent = title; }, /** * Sets dropdown items. * @param {Array} items Dropdown items array. */ setItems: function(items) { this.container.innerHTML = ''; this.container.firstItem = null; this.container.selectedItem = null; for (var i = 0; i < items.length; ++i) { var item = items[i]; if ('sub' in item) { // Workaround for submenus, add items on top level. // TODO(altimofeev): support submenus. for (var j = 0; j < item.sub.length; ++j) this.createItem_(this.container, item.sub[j]); continue; } this.createItem_(this.container, item); } this.container.selectItem(this.container.firstItem, false); }, /** * Id of the active drop-down element. * @private */ activeElementId_: '', /** * Creates dropdown item element and adds into container. * @param {HTMLElement} container Container where item is added. * @param {!Object} item Item to be added. * @private */ createItem_: function(container, item) { var itemContentElement; var className = 'dropdown-item'; if (item.id == DropDown.ITEM_DIVIDER_ID) { className = 'dropdown-divider'; itemContentElement = this.ownerDocument.createElement('hr'); } else { var span = this.ownerDocument.createElement('span'); itemContentElement = span; span.textContent = item.label; if ('bold' in item && item.bold) span.classList.add('bold'); var image = this.ownerDocument.createElement('img'); image.alt = ''; image.classList.add('dropdown-image'); if (item.icon) image.src = item.icon; } var itemElement = this.ownerDocument.createElement('div'); itemElement.classList.add(className); itemElement.appendChild(itemContentElement); itemElement.iid = item.id; itemElement.controller = this; var enabled = 'enabled' in item && item.enabled; if (!enabled) itemElement.classList.add('disabled-item'); if (item.id > 0) { var wrapperDiv = this.ownerDocument.createElement('div'); wrapperDiv.setAttribute('role', 'menuitem'); wrapperDiv.id = this.id + item.id; if (!enabled) wrapperDiv.setAttribute('aria-disabled', 'true'); wrapperDiv.classList.add('dropdown-item-container'); var imageDiv = this.ownerDocument.createElement('div'); imageDiv.appendChild(image); wrapperDiv.appendChild(imageDiv); wrapperDiv.appendChild(itemElement); wrapperDiv.addEventListener('click', function f(e) { var item = this.lastElementChild; if (item.iid < -1 || item.classList.contains('disabled-item')) return; item.controller.isShown = false; if (item.iid >= 0) chrome.send('networkItemChosen', [item.iid]); this.parentNode.parentNode.title_.focus(); }); wrapperDiv.addEventListener('mouseover', function f(e) { this.parentNode.selectItem(this, true); }); itemElement = wrapperDiv; } container.appendChild(itemElement); if (!container.firstItem && item.id >= 0) { container.firstItem = itemElement; } }, /** * Creates dropdown overlay element, which catches outside clicks. * @type {HTMLElement} * @private */ createOverlay_: function() { var overlay = this.ownerDocument.createElement('div'); overlay.classList.add('dropdown-overlay'); overlay.addEventListener('click', function() { this.parentNode.title_.focus(); this.parentNode.isShown = false; }); return overlay; }, /** * Creates dropdown title element. * @type {HTMLElement} * @private */ createTitle_: function() { var image = this.ownerDocument.createElement('img'); image.alt = ''; image.classList.add('dropdown-image'); var text = this.ownerDocument.createElement('div'); var el = this.ownerDocument.createElement('div'); el.appendChild(image); el.appendChild(text); el.tabIndex = 0; el.classList.add('dropdown-title'); el.iid = -1; el.controller = this; el.inFocus = false; el.opening = false; el.addEventListener('click', function f(e) { this.controller.isShown = !this.controller.isShown; }); el.addEventListener('focus', function(e) { this.inFocus = true; }); el.addEventListener('blur', function(e) { this.inFocus = false; }); el.addEventListener('keydown', function f(e) { if (this.inFocus && !this.controller.isShown && (e.keyCode == DropDown.KEYCODE_ENTER || e.keyCode == DropDown.KEYCODE_SPACE || e.keyCode == DropDown.KEYCODE_UP || e.keyCode == DropDown.KEYCODE_DOWN)) { this.opening = true; this.controller.isShown = true; e.stopPropagation(); e.preventDefault(); } }); return el; }, /** * Handles keydown event from the keyboard. * @private * @param {!Event} e Keydown event. */ keyDownHandler_: function(e) { if (!this.isShown) return; var selected = this.container.selectedItem; var handled = false; switch (e.keyCode) { case DropDown.KEYCODE_UP: { do { selected = selected.previousSibling; if (!selected) selected = this.container.lastElementChild; } while (selected.iid < 0); this.container.selectItem(selected, false); handled = true; break; } case DropDown.KEYCODE_DOWN: { do { selected = selected.nextSibling; if (!selected) selected = this.container.firstItem; } while (selected.iid < 0); this.container.selectItem(selected, false); handled = true; break; } case DropDown.KEYCODE_ESC: { this.isShown = false; handled = true; break; } case DropDown.KEYCODE_TAB: { this.isShown = false; handled = true; break; } case DropDown.KEYCODE_ENTER: { if (!this.title_.opening) { this.title_.focus(); this.isShown = false; var item = this.title_.controller.container.selectedItem.lastElementChild; if (item.iid >= 0 && !item.classList.contains('disabled-item')) chrome.send('networkItemChosen', [item.iid]); } handled = true; break; } } if (handled) { e.stopPropagation(); e.preventDefault(); } this.title_.opening = false; } }; /** * Updates networks list with the new data. * @param {!Object} data Networks list. */ DropDown.updateNetworks = function(data) { if (DropDown.activeElementId_) $(DropDown.activeElementId_).setItems(data); }; /** * Updates network title, which is shown by the drop-down. * @param {string} title Title to be displayed. * @param {!Object} icon Icon to be displayed. */ DropDown.updateNetworkTitle = function(title, icon) { if (DropDown.activeElementId_) $(DropDown.activeElementId_).setTitle(title, icon); }; /** * Activates network drop-down. Only one network drop-down * can be active at the same time. So activating new drop-down deactivates * the previous one. * @param {string} elementId Id of network drop-down element. * @param {boolean} isOobe Whether drop-down is used by an Oobe screen. * @param {integer} lastNetworkType Last active network type. Pass -1 if it * isn't known. */ DropDown.show = function(elementId, isOobe, lastNetworkType) { $(elementId).isShown = false; if (DropDown.activeElementId_ != elementId) { DropDown.activeElementId_ = elementId; chrome.send('networkDropdownShow', [elementId, isOobe, lastNetworkType]); } }; /** * Deactivates network drop-down. Deactivating inactive drop-down does * nothing. * @param {string} elementId Id of network drop-down element. */ DropDown.hide = function(elementId) { if (DropDown.activeElementId_ == elementId) { DropDown.activeElementId_ = ''; chrome.send('networkDropdownHide'); } }; /** * Refreshes network drop-down. Should be called on language change. */ DropDown.refresh = function() { chrome.send('networkDropdownRefresh'); }; return { DropDown: DropDown }; });
loopCM/chromium
chrome/browser/resources/chromeos/login/network_dropdown.js
JavaScript
bsd-3-clause
12,950
/* * Copyright (c) 2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements Primary Backbone Router service management in the Thread Network. */ #include "bbr_leader.hpp" #if (OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2) #include "common/instance.hpp" #include "common/locator-getters.hpp" #include "common/logging.hpp" namespace ot { namespace BackboneRouter { Leader::Leader(Instance &aInstance) : InstanceLocator(aInstance) { Reset(); } void Leader::Reset(void) { // Invalid server short address indicates no available Backbone Router service in the Thread Network. mConfig.mServer16 = Mac::kShortAddrInvalid; // Domain Prefix Length 0 indicates no available Domain Prefix in the Thread network. mDomainPrefix.SetLength(0); } otError Leader::GetConfig(BackboneRouterConfig &aConfig) const { otError error = OT_ERROR_NONE; VerifyOrExit(HasPrimary(), error = OT_ERROR_NOT_FOUND); aConfig = mConfig; exit: return error; } otError Leader::GetServiceId(uint8_t &aServiceId) const { otError error = OT_ERROR_NONE; uint8_t serviceData = NetworkData::ServiceTlv::kServiceDataBackboneRouter; VerifyOrExit(HasPrimary(), error = OT_ERROR_NOT_FOUND); error = Get<NetworkData::Leader>().GetServiceId(NetworkData::ServiceTlv::kThreadEnterpriseNumber, &serviceData, sizeof(serviceData), true, aServiceId); exit: return error; } #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1) void Leader::LogBackboneRouterPrimary(State aState, const BackboneRouterConfig &aConfig) const { OT_UNUSED_VARIABLE(aConfig); otLogInfoBbr("PBBR state: %s", StateToString(aState)); if (aState != kStateRemoved && aState != kStateNone) { otLogInfoBbr("Rloc16: 0x%4X, seqno: %d, delay: %d, timeout %d", aConfig.mServer16, aConfig.mSequenceNumber, aConfig.mReregistrationDelay, aConfig.mMlrTimeout); } } void Leader::LogDomainPrefix(DomainPrefixState aState, const Ip6::Prefix &aPrefix) const { otLogInfoBbr("Domain Prefix: %s, state: %s", aPrefix.ToString().AsCString(), DomainPrefixStateToString(aState)); } const char *Leader::StateToString(State aState) { const char *logString = "Unknown"; switch (aState) { case kStateNone: logString = "None"; break; case kStateAdded: logString = "Added"; break; case kStateRemoved: logString = "Removed"; break; case kStateToTriggerRereg: logString = "Rereg triggered"; break; case kStateRefreshed: logString = "Refreshed"; break; case kStateUnchanged: logString = "Unchanged"; break; default: break; } return logString; } const char *Leader::DomainPrefixStateToString(DomainPrefixState aState) { const char *logString = "Unknown"; switch (aState) { case kDomainPrefixNone: logString = "None"; break; case kDomainPrefixAdded: logString = "Added"; break; case kDomainPrefixRemoved: logString = "Removed"; break; case kDomainPrefixRefreshed: logString = "Refreshed"; break; case kDomainPrefixUnchanged: logString = "Unchanged"; break; } return logString; } #endif void Leader::Update(void) { UpdateBackboneRouterPrimary(); UpdateDomainPrefixConfig(); } void Leader::UpdateBackboneRouterPrimary(void) { BackboneRouterConfig config; State state; uint32_t origMlrTimeout; IgnoreError(Get<NetworkData::Leader>().GetBackboneRouterPrimary(config)); if (config.mServer16 != mConfig.mServer16) { if (config.mServer16 == Mac::kShortAddrInvalid) { state = kStateRemoved; } else if (mConfig.mServer16 == Mac::kShortAddrInvalid) { state = kStateAdded; } else { // Short Address of PBBR changes. state = kStateToTriggerRereg; } } else if (config.mServer16 == Mac::kShortAddrInvalid) { // If no Primary all the time. state = kStateNone; } else if (config.mSequenceNumber != mConfig.mSequenceNumber) { state = kStateToTriggerRereg; } else if (config.mReregistrationDelay != mConfig.mReregistrationDelay || config.mMlrTimeout != mConfig.mMlrTimeout) { state = kStateRefreshed; } else { state = kStateUnchanged; } // Restrain the range of MLR timeout to be always valid if (config.mServer16 != Mac::kShortAddrInvalid) { origMlrTimeout = config.mMlrTimeout; config.mMlrTimeout = config.mMlrTimeout < static_cast<uint32_t>(Mle::kMlrTimeoutMin) ? static_cast<uint32_t>(Mle::kMlrTimeoutMin) : config.mMlrTimeout; config.mMlrTimeout = config.mMlrTimeout > static_cast<uint32_t>(Mle::kMlrTimeoutMax) ? static_cast<uint32_t>(Mle::kMlrTimeoutMax) : config.mMlrTimeout; if (config.mMlrTimeout != origMlrTimeout) { otLogNoteBbr("Leader MLR Timeout is normalized from %u to %u", origMlrTimeout, config.mMlrTimeout); } } mConfig = config; LogBackboneRouterPrimary(state, mConfig); #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE Get<BackboneRouter::Local>().HandleBackboneRouterPrimaryUpdate(state, mConfig); #endif #if OPENTHREAD_CONFIG_MLR_ENABLE || OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE Get<MlrManager>().HandleBackboneRouterPrimaryUpdate(state, mConfig); #endif #if OPENTHREAD_CONFIG_DUA_ENABLE || OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE Get<DuaManager>().HandleBackboneRouterPrimaryUpdate(state, mConfig); #endif } void Leader::UpdateDomainPrefixConfig(void) { NetworkData::Iterator iterator = NetworkData::kIteratorInit; NetworkData::OnMeshPrefixConfig config; DomainPrefixState state; bool found = false; while (Get<NetworkData::Leader>().GetNextOnMeshPrefix(iterator, config) == OT_ERROR_NONE) { if (config.mDp) { found = true; break; } } if (!found) { if (mDomainPrefix.GetLength() != 0) { // Domain Prefix does not exist any more. mDomainPrefix.SetLength(0); state = kDomainPrefixRemoved; } else { state = kDomainPrefixNone; } } else if (config.GetPrefix() == mDomainPrefix) { state = kDomainPrefixUnchanged; } else { if (mDomainPrefix.mLength == 0) { state = kDomainPrefixAdded; } else { state = kDomainPrefixRefreshed; } mDomainPrefix = config.GetPrefix(); } LogDomainPrefix(state, mDomainPrefix); #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE Get<Local>().HandleDomainPrefixUpdate(state); Get<NdProxyTable>().HandleDomainPrefixUpdate(state); #endif #if OPENTHREAD_CONFIG_DUA_ENABLE || OPENTHREAD_CONFIG_TMF_PROXY_DUA_ENABLE Get<DuaManager>().HandleDomainPrefixUpdate(state); #endif } bool Leader::IsDomainUnicast(const Ip6::Address &aAddress) const { return HasDomainPrefix() && aAddress.MatchesPrefix(mDomainPrefix); } } // namespace BackboneRouter } // namespace ot #endif // (OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2)
chshu/openthread
src/core/backbone_router/bbr_leader.cpp
C++
bsd-3-clause
9,252