repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
markogresak/DefinitelyTyped
types/carbon__icons-react/es/arrows--vertical/20.d.ts
54
export { ArrowsVertical20 as default } from "../../";
mit
vastcharade/godot
scene/gui/video_player.cpp
7355
/*************************************************************************/ /* video_player.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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. */ /*************************************************************************/ #include "video_player.h" void VideoPlayer::_notification(int p_notification) { switch (p_notification) { case NOTIFICATION_ENTER_TREE: { //set_idle_process(false); //don't annoy if (stream.is_valid() && autoplay && !get_tree()->is_editor_hint()) play(); } break; case NOTIFICATION_PROCESS: { if (stream.is_null()) return; if (paused) return; if (!stream->is_playing()) return; stream->update(get_tree()->get_idle_process_time()); int prev_width = texture->get_width(); stream->pop_frame(texture); if (prev_width == 0) { update(); minimum_size_changed(); }; } break; case NOTIFICATION_DRAW: { if (texture.is_null()) return; if (texture->get_width() == 0) return; Size2 s=expand?get_size():texture->get_size(); RID ci = get_canvas_item(); printf("drawing with size %f, %f\n", s.x, s.y); draw_texture_rect(texture,Rect2(Point2(),s),false); } break; }; }; Size2 VideoPlayer::get_minimum_size() const { if (!expand && !texture.is_null()) return texture->get_size(); else return Size2(); } void VideoPlayer::set_expand(bool p_expand) { expand=p_expand; update(); minimum_size_changed(); } bool VideoPlayer::has_expand() const { return expand; } void VideoPlayer::set_stream(const Ref<VideoStream> &p_stream) { stop(); texture = Ref<ImageTexture>(memnew(ImageTexture)); stream=p_stream; if (!stream.is_null()) { stream->set_loop(loops); stream->set_paused(paused); } }; Ref<VideoStream> VideoPlayer::get_stream() const { return stream; }; void VideoPlayer::play() { ERR_FAIL_COND(!is_inside_tree()); if (stream.is_null()) return; stream->play(); set_process(true); }; void VideoPlayer::stop() { if (!is_inside_tree()) return; if (stream.is_null()) return; stream->stop(); set_process(false); }; bool VideoPlayer::is_playing() const { if (stream.is_null()) return false; return stream->is_playing(); }; void VideoPlayer::set_paused(bool p_paused) { paused=p_paused; if (stream.is_valid()) { stream->set_paused(p_paused); set_process(!p_paused); }; }; bool VideoPlayer::is_paused() const { return paused; }; void VideoPlayer::set_volume(float p_vol) { volume=p_vol; }; float VideoPlayer::get_volume() const { return volume; }; void VideoPlayer::set_volume_db(float p_db) { if (p_db<-79) set_volume(0); else set_volume(Math::db2linear(p_db)); }; float VideoPlayer::get_volume_db() const { if (volume==0) return -80; else return Math::linear2db(volume); }; String VideoPlayer::get_stream_name() const { if (stream.is_null()) return "<No Stream>"; return stream->get_name(); }; float VideoPlayer::get_stream_pos() const { if (stream.is_null()) return 0; return stream->get_pos(); }; void VideoPlayer::set_autoplay(bool p_enable) { autoplay=p_enable; }; bool VideoPlayer::has_autoplay() const { return autoplay; }; void VideoPlayer::_bind_methods() { ObjectTypeDB::bind_method(_MD("set_stream","stream:Stream"),&VideoPlayer::set_stream); ObjectTypeDB::bind_method(_MD("get_stream:Stream"),&VideoPlayer::get_stream); ObjectTypeDB::bind_method(_MD("play"),&VideoPlayer::play); ObjectTypeDB::bind_method(_MD("stop"),&VideoPlayer::stop); ObjectTypeDB::bind_method(_MD("is_playing"),&VideoPlayer::is_playing); ObjectTypeDB::bind_method(_MD("set_paused","paused"),&VideoPlayer::set_paused); ObjectTypeDB::bind_method(_MD("is_paused"),&VideoPlayer::is_paused); ObjectTypeDB::bind_method(_MD("set_volume","volume"),&VideoPlayer::set_volume); ObjectTypeDB::bind_method(_MD("get_volume"),&VideoPlayer::get_volume); ObjectTypeDB::bind_method(_MD("set_volume_db","db"),&VideoPlayer::set_volume_db); ObjectTypeDB::bind_method(_MD("get_volume_db"),&VideoPlayer::get_volume_db); ObjectTypeDB::bind_method(_MD("get_stream_name"),&VideoPlayer::get_stream_name); ObjectTypeDB::bind_method(_MD("get_stream_pos"),&VideoPlayer::get_stream_pos); ObjectTypeDB::bind_method(_MD("set_autoplay","enabled"),&VideoPlayer::set_autoplay); ObjectTypeDB::bind_method(_MD("has_autoplay"),&VideoPlayer::has_autoplay); ObjectTypeDB::bind_method(_MD("set_expand","enable"), &VideoPlayer::set_expand ); ObjectTypeDB::bind_method(_MD("has_expand"), &VideoPlayer::has_expand ); ADD_PROPERTY( PropertyInfo(Variant::OBJECT, "stream/stream", PROPERTY_HINT_RESOURCE_TYPE,"VideoStream"), _SCS("set_stream"), _SCS("get_stream") ); // ADD_PROPERTY( PropertyInfo(Variant::BOOL, "stream/loop"), _SCS("set_loop"), _SCS("has_loop") ); ADD_PROPERTY( PropertyInfo(Variant::REAL, "stream/volume_db", PROPERTY_HINT_RANGE,"-80,24,0.01"), _SCS("set_volume_db"), _SCS("get_volume_db") ); ADD_PROPERTY( PropertyInfo(Variant::BOOL, "stream/autoplay"), _SCS("set_autoplay"), _SCS("has_autoplay") ); ADD_PROPERTY( PropertyInfo(Variant::BOOL, "stream/paused"), _SCS("set_paused"), _SCS("is_paused") ); ADD_PROPERTY( PropertyInfo( Variant::BOOL, "expand" ), _SCS("set_expand"),_SCS("has_expand") ); } VideoPlayer::VideoPlayer() { volume=1; loops = false; paused = false; autoplay = false; expand = true; loops = false; }; VideoPlayer::~VideoPlayer() { if (stream_rid.is_valid()) AudioServer::get_singleton()->free(stream_rid); };
mit
wp-e-commerce/Gold-Cart
merchants/wpec_auth_net/classes/anet_php_sdk/lib/net/authorize/api/contract/v1/ImpersonationAuthenticationType.php
1306
<?php namespace net\authorize\api\contract\v1; /** * Class representing ImpersonationAuthenticationType * * * XSD Type: impersonationAuthenticationType */ class ImpersonationAuthenticationType { /** * @property string $partnerLoginId */ private $partnerLoginId = null; /** * @property string $partnerTransactionKey */ private $partnerTransactionKey = null; /** * Gets as partnerLoginId * * @return string */ public function getPartnerLoginId() { return $this->partnerLoginId; } /** * Sets a new partnerLoginId * * @param string $partnerLoginId * @return self */ public function setPartnerLoginId($partnerLoginId) { $this->partnerLoginId = $partnerLoginId; return $this; } /** * Gets as partnerTransactionKey * * @return string */ public function getPartnerTransactionKey() { return $this->partnerTransactionKey; } /** * Sets a new partnerTransactionKey * * @param string $partnerTransactionKey * @return self */ public function setPartnerTransactionKey($partnerTransactionKey) { $this->partnerTransactionKey = $partnerTransactionKey; return $this; } }
gpl-2.0
naaatasha/pr-bny-projekt
wp-content/plugins/wp-e-commerce/wpsc-components/merchant-core-v3/gateways/php-merchant/tests/gateways/paypal-express-checkout.php
24698
<?php require_once( PHP_MERCHANT_PATH . '/gateways/paypal-express-checkout.php' ); class PHP_Merchant_Paypal_Express_Checkout_Test extends UnitTestCase { private $bogus; private $options; private $amount; private $token; private $setup_purchase_options; private $purchase_options; public function __construct() { parent::__construct( 'PHP_Merchant_Paypal_Express_Checkout test cases' ); $this->token = 'EC-6L77249383950130E'; // options to pass to the merchant class $this->setup_purchase_options = $this->purchase_options = array( // API info 'return_url' => 'http://example.com/return', 'cancel_url' => 'http://example.com/cancel', 'address_override' => true, // Shipping details 'shipping_address' => array( 'name' => 'Gary Cao', 'street' => '1 Infinite Loop', 'street2' => 'Apple Headquarter', 'city' => 'Cupertino', 'state' => 'CA', 'country' => 'USA', 'zip' => '95014', 'phone' => '(877) 412-7753', ), // Payment info 'currency' => 'JPY', 'amount' => 15337, 'subtotal' => 13700, 'shipping' => 1500, 'tax' => 137, 'description' => 'Order for example.com', 'invoice' => 'E84A90G94', 'notify_url' => 'http://example.com/ipn', // Items 'items' => array( array( 'name' => 'Gold Cart Plugin', 'description' => 'Gold Cart extends your WP eCommerce store by enabling additional features and functionality, including views, galleries, store search and payment gateways.', 'amount' => 4000, 'quantity' => 1, 'tax' => 40, 'url' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/gold-cart-plugin/', ), array( 'name' => 'Member Access Plugin', 'description' => 'Create pay to view subscription sites', 'amount' => 5000, 'quantity' => 1, 'tax' => 50, 'url' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/member-access-plugin/', ), array( 'name' => 'Amazon S3', 'description' => 'This Plugin allows downloadable products that you have for sale on your WP eCommerce site to be hosted within Amazon S3.', 'amount' => 4700, 'quantity' => 1, 'tax' => 47, 'url' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/amazon-s3-plugin/', ), ), ); $this->purchase_options += array( 'token' => 'EC-2JJ0893331633543K', 'payer_id' => 'BC798KQ2QU22W', ); } public function setUp() { $this->bogus = new PHP_Merchant_Paypal_Express_Checkout_Bogus( array( 'api_username' => 'sdk-three_api1.sdk.com', 'api_password' => 'QFZCWN5HZM8VBG7Q', 'api_signature' => 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', ) ); } public function tearDown() { } public function test_correct_parameters_are_sent_to_paypal_when_set_express_checkout() { // set up expectations for mock objects $url = 'https://api-3t.paypal.com/nvp'; // how the request parameters should look like $args = array( // API info 'USER' => 'sdk-three_api1.sdk.com', 'PWD' => 'QFZCWN5HZM8VBG7Q', 'VERSION' => '114.0', 'SIGNATURE' => 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', 'METHOD' => 'SetExpressCheckout', 'RETURNURL' => 'http://example.com/return', 'CANCELURL' => 'http://example.com/cancel', 'AMT' => 15337, 'ADDROVERRIDE' => 1, 'INVOICEID' => 'E84A90G94', // Shipping details 'PAYMENTREQUEST_0_SHIPTONAME' => 'Gary Cao', 'PAYMENTREQUEST_0_SHIPTOSTREET' => '1 Infinite Loop', 'PAYMENTREQUEST_0_SHIPTOSTREET2' => 'Apple Headquarter', 'PAYMENTREQUEST_0_SHIPTOCITY' => 'Cupertino', 'PAYMENTREQUEST_0_SHIPTOSTATE' => 'CA', 'PAYMENTREQUEST_0_SHIPTOZIP' => '95014', 'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => 'USA', 'PAYMENTREQUEST_0_SHIPTOPHONENUM' => '(877) 412-7753', // Payment info 'PAYMENTREQUEST_0_AMT' => '15,337', 'PAYMENTREQUEST_0_CURRENCYCODE' => 'JPY', 'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale', 'PAYMENTREQUEST_0_ALLOWEDPAYMENTMETHOD' => 'InstantPaymentOnly', 'PAYMENTREQUEST_0_ITEMAMT' => '13,700', 'PAYMENTREQUEST_0_SHIPPINGAMT' => '1,500', 'PAYMENTREQUEST_0_TAXAMT' => '137', 'PAYMENTREQUEST_0_DESC' => 'Order for example.com', 'PAYMENTREQUEST_0_INVNUM' => 'E84A90G94', 'PAYMENTREQUEST_0_NOTIFYURL' => 'http://example.com/ipn', // Items 'L_PAYMENTREQUEST_0_NAME0' => 'Gold Cart Plugin', 'L_PAYMENTREQUEST_0_AMT0' => '4,000', 'L_PAYMENTREQUEST_0_QTY0' => 1, 'L_PAYMENTREQUEST_0_DESC0' => 'Gold Cart extends your WP eCommerce store by enabling additional features and functionality, including views, galleries, store search and payment gateways.', 'L_PAYMENTREQUEST_0_TAXAMT0' => '40', 'L_PAYMENTREQUEST_0_ITEMURL0' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/gold-cart-plugin/', 'L_PAYMENTREQUEST_0_NAME1' => 'Member Access Plugin', 'L_PAYMENTREQUEST_0_AMT1' => '5,000', 'L_PAYMENTREQUEST_0_QTY1' => 1, 'L_PAYMENTREQUEST_0_DESC1' => 'Create pay to view subscription sites', 'L_PAYMENTREQUEST_0_TAXAMT1' => '50', 'L_PAYMENTREQUEST_0_ITEMURL1' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/member-access-plugin/', 'L_PAYMENTREQUEST_0_NAME2' => 'Amazon S3', 'L_PAYMENTREQUEST_0_AMT2' => '4,700', 'L_PAYMENTREQUEST_0_QTY2' => 1, 'L_PAYMENTREQUEST_0_DESC2' => 'This Plugin allows downloadable products that you have for sale on your WP eCommerce site to be hosted within Amazon S3.', 'L_PAYMENTREQUEST_0_TAXAMT2' => '47', 'L_PAYMENTREQUEST_0_ITEMURL2' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/amazon-s3-plugin/', ); $this->bogus->http->expectOnce( 'post', array( $url, $args ) ); try { $this->bogus->setup_purchase( $this->setup_purchase_options ); } catch ( PHP_Merchant_Exception $e ) { } } public function test_correct_parameters_are_sent_when_do_express_checkout_payment() { // set up expectations for mock objects $url = 'https://api-3t.paypal.com/nvp'; // how the request parameters should look like $args = array( // API info 'USER' => 'sdk-three_api1.sdk.com', 'PWD' => 'QFZCWN5HZM8VBG7Q', 'VERSION' => '114.0', 'SIGNATURE' => 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', 'METHOD' => 'DoExpressCheckoutPayment', 'RETURNURL' => 'http://example.com/return', 'CANCELURL' => 'http://example.com/cancel', 'AMT' => 15337, 'ADDROVERRIDE' => 1, // Payer ID 'TOKEN' => 'EC-2JJ0893331633543K', 'PAYERID' => 'BC798KQ2QU22W', 'INVOICEID' => 'E84A90G94', // Shipping details 'PAYMENTREQUEST_0_SHIPTONAME' => 'Gary Cao', 'PAYMENTREQUEST_0_SHIPTOSTREET' => '1 Infinite Loop', 'PAYMENTREQUEST_0_SHIPTOSTREET2' => 'Apple Headquarter', 'PAYMENTREQUEST_0_SHIPTOCITY' => 'Cupertino', 'PAYMENTREQUEST_0_SHIPTOSTATE' => 'CA', 'PAYMENTREQUEST_0_SHIPTOZIP' => '95014', 'PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE' => 'USA', 'PAYMENTREQUEST_0_SHIPTOPHONENUM' => '(877) 412-7753', // Payment info 'PAYMENTREQUEST_0_AMT' => '15,337', 'PAYMENTREQUEST_0_CURRENCYCODE' => 'JPY', 'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale', 'PAYMENTREQUEST_0_ALLOWEDPAYMENTMETHOD' => 'InstantPaymentOnly', 'PAYMENTREQUEST_0_ITEMAMT' => '13,700', 'PAYMENTREQUEST_0_SHIPPINGAMT' => '1,500', 'PAYMENTREQUEST_0_TAXAMT' => '137', 'PAYMENTREQUEST_0_DESC' => 'Order for example.com', 'PAYMENTREQUEST_0_INVNUM' => 'E84A90G94', 'PAYMENTREQUEST_0_NOTIFYURL' => 'http://example.com/ipn', // Items 'L_PAYMENTREQUEST_0_NAME0' => 'Gold Cart Plugin', 'L_PAYMENTREQUEST_0_AMT0' => '4,000', 'L_PAYMENTREQUEST_0_QTY0' => 1, 'L_PAYMENTREQUEST_0_DESC0' => 'Gold Cart extends your WP eCommerce store by enabling additional features and functionality, including views, galleries, store search and payment gateways.', 'L_PAYMENTREQUEST_0_TAXAMT0' => '40', 'L_PAYMENTREQUEST_0_ITEMURL0' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/gold-cart-plugin/', 'L_PAYMENTREQUEST_0_NAME1' => 'Member Access Plugin', 'L_PAYMENTREQUEST_0_AMT1' => '5,000', 'L_PAYMENTREQUEST_0_QTY1' => 1, 'L_PAYMENTREQUEST_0_DESC1' => 'Create pay to view subscription sites', 'L_PAYMENTREQUEST_0_TAXAMT1' => '50', 'L_PAYMENTREQUEST_0_ITEMURL1' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/member-access-plugin/', 'L_PAYMENTREQUEST_0_NAME2' => 'Amazon S3', 'L_PAYMENTREQUEST_0_AMT2' => '4,700', 'L_PAYMENTREQUEST_0_QTY2' => 1, 'L_PAYMENTREQUEST_0_DESC2' => 'This Plugin allows downloadable products that you have for sale on your WP eCommerce site to be hosted within Amazon S3.', 'L_PAYMENTREQUEST_0_TAXAMT2' => '47', 'L_PAYMENTREQUEST_0_ITEMURL2' => 'http://getshopped.org/extend/premium-upgrades/premium-upgrades/amazon-s3-plugin/', ); $this->bogus->http->expectOnce( 'post', array( $url, $args ) ); try { $this->bogus->purchase( $this->purchase_options ); } catch ( PHP_Merchant_Exception $e ) { } } public function test_correct_parameters_are_sent_when_get_express_checkout_details() { $url = 'https://api-3t.paypal.com/nvp'; $args = array( // API info 'USER' => 'sdk-three_api1.sdk.com', 'PWD' => 'QFZCWN5HZM8VBG7Q', 'VERSION' => '114.0', 'SIGNATURE' => 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', 'METHOD' => 'GetExpressCheckoutDetails', 'TOKEN' => $this->token, ); $this->bogus->http->expectOnce( 'post', array( $url, $args ) ); try { $this->bogus->get_details_for( $this->token ); } catch ( PHP_Merchant_Exception $e ) { } } public function test_correct_response_is_returned_when_set_express_checkout_is_successful() { $mock_response = 'ACK=Success&CORRELATIONID=224f0e4a32d14&TIMESTAMP=2011%2d07%2d05T13%253A23%253A52Z&VERSION=2%2e30000&BUILD=1%2e0006&TOKEN=EC%2d1OIN4UJGFOK54YFV'; $this->bogus->http->returnsByValue( 'post', $mock_response ); $response = $this->bogus->setup_purchase( $this->setup_purchase_options ); $this->assertTrue( $response->is_successful() ); $this->assertFalse( $response->has_errors() ); $this->assertEqual( $response->get( 'token' ), 'EC-1OIN4UJGFOK54YFV' ); $this->assertEqual( $response->get( 'timestamp' ), 1309872232 ); $this->assertEqual( $response->get( 'datetime' ), '2011-07-05T13:23:52Z' ); $this->assertEqual( $response->get( 'correlation_id' ), '224f0e4a32d14' ); $this->assertEqual( $response->get( 'version' ), '2.30000' ); $this->assertEqual( $response->get( 'build' ), '1.0006' ); } public function test_correct_response_is_returned_when_get_express_checkout_details_is_successful() { $mock_response = 'TOKEN=EC%2d6EC97401PF4449255'. // API Info '&CHECKOUTSTATUS=PaymentActionNotInitiated'. '&TIMESTAMP=2011%2d08%2d25T08%3a04%3a26Z'. '&CORRELATIONID=b5ae9bd5c735f'. '&ACK=Success'. '&VERSION=114%2e0'. '&BUILD=2085867'. // Payer info '&EMAIL=visa_1304648966_per%40garyc40%2ecom'. '&PAYERID=BC798KQ2QU22W'. '&PAYERSTATUS=verified'. '&FIRSTNAME=Test'. '&LASTNAME=User'. '&COUNTRYCODE=US'. '&SHIPTONAME=Gary%20Cao'. '&SHIPTOSTREET=1%20Infinite%20Loop'. '&SHIPTOSTREET2=Apple%20Headquarter'. '&SHIPTOCITY=Cupertino'. '&SHIPTOSTATE=CA'. '&SHIPTOZIP=95014'. '&SHIPTOCOUNTRYCODE=US'. '&SHIPTOPHONENUM=%28877%29%20412%2d7753'. '&SHIPTOCOUNTRYNAME=United%20States'. '&ADDRESSSTATUS=Unconfirmed'. // Legacy parameters (old API) '&CURRENCYCODE=JPY'. '&AMT=15337'. '&ITEMAMT=13700'. '&SHIPPINGAMT=1500'. '&HANDLINGAMT=0'. '&TAXAMT=137'. '&DESC=Order%20for%20example%2ecom'. '&INVNUM=E84A90G94'. '&NOTIFYURL=http%3a%2f%2fexample%2ecom%2fipn'. '&INSURANCEAMT=0'. '&SHIPDISCAMT=0'. // Legacy parameters (old API) '&L_NAME0=Gold%20Cart%20Plugin'. '&L_NAME1=Member%20Access%20Plugin'. '&L_NAME2=Amazon%20S3'. '&L_QTY0=1'. '&L_QTY1=1'. '&L_QTY2=1'. '&L_TAXAMT0=40'. '&L_TAXAMT1=50'. '&L_TAXAMT2=47'. '&L_AMT0=4000'. '&L_AMT1=5000'. '&L_AMT2=4700'. '&L_DESC0=Gold%20Cart%20extends%20your%20WP%20e%2dCommerce%20store%20by%20enabling%20additional%20features%20and%20functionality%2e'. '&L_DESC1=Create%20pay%20to%20view%20subscription%20sites'. '&L_DESC2=This%20Plugin%20allows%20downloadable%20products%20on%20your%20WP%20e%2dCommerce%20site%20to%20be%20hosted%20on%20Amazon%20S3%2e'. '&L_ITEMWEIGHTVALUE0=%20%20%200%2e00000'. '&L_ITEMWEIGHTVALUE1=%20%20%200%2e00000'. '&L_ITEMWEIGHTVALUE2=%20%20%200%2e00000'. '&L_ITEMLENGTHVALUE0=%20%20%200%2e00000'. '&L_ITEMLENGTHVALUE1=%20%20%200%2e00000'. '&L_ITEMLENGTHVALUE2=%20%20%200%2e00000'. '&L_ITEMWIDTHVALUE0=%20%20%200%2e00000'. '&L_ITEMWIDTHVALUE1=%20%20%200%2e00000'. '&L_ITEMWIDTHVALUE2=%20%20%200%2e00000'. '&L_ITEMHEIGHTVALUE0=%20%20%200%2e00000'. '&L_ITEMHEIGHTVALUE1=%20%20%200%2e00000'. '&L_ITEMHEIGHTVALUE2=%20%20%200%2e00000'. // Payment Information '&PAYMENTREQUEST_0_CURRENCYCODE=JPY'. '&PAYMENTREQUEST_0_AMT=15337'. '&PAYMENTREQUEST_0_ITEMAMT=13700'. '&PAYMENTREQUEST_0_SHIPPINGAMT=1500'. '&PAYMENTREQUEST_0_HANDLINGAMT=0'. '&PAYMENTREQUEST_0_TAXAMT=137'. '&PAYMENTREQUEST_0_DESC=Order%20for%20example%2ecom'. '&PAYMENTREQUEST_0_INVNUM=E84A90G94'. '&PAYMENTREQUEST_0_NOTIFYURL=http%3a%2f%2fexample%2ecom%2fipn'. '&PAYMENTREQUEST_0_INSURANCEAMT=0'. '&PAYMENTREQUEST_0_SHIPDISCAMT=0'. '&PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED=false'. // Item Information '&L_PAYMENTREQUEST_0_NAME0=Gold%20Cart%20Plugin'. '&L_PAYMENTREQUEST_0_NAME1=Member%20Access%20Plugin'. '&L_PAYMENTREQUEST_0_NAME2=Amazon%20S3'. '&L_PAYMENTREQUEST_0_QTY0=1'. '&L_PAYMENTREQUEST_0_QTY1=1'. '&L_PAYMENTREQUEST_0_QTY2=1'. '&L_PAYMENTREQUEST_0_TAXAMT0=40'. '&L_PAYMENTREQUEST_0_TAXAMT1=50'. '&L_PAYMENTREQUEST_0_TAXAMT2=47'. '&L_PAYMENTREQUEST_0_AMT0=4000'. '&L_PAYMENTREQUEST_0_AMT1=5000'. '&L_PAYMENTREQUEST_0_AMT2=4700'. '&L_PAYMENTREQUEST_0_DESC0=Gold%20Cart%20extends%20your%20WP%20e%2dCommerce%20store%20by%20enabling%20additional%20features%20and%20functionality%2e'. '&L_PAYMENTREQUEST_0_DESC1=Create%20pay%20to%20view%20subscription%20sites'. '&L_PAYMENTREQUEST_0_DESC2=This%20Plugin%20allows%20downloadable%20products%20on%20your%20WP%20e%2dCommerce%20site%20to%20be%20hosted%20on%20Amazon%20S3%2e'. '&L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE0=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE1=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE2=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMLENGTHVALUE0=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMLENGTHVALUE1=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMLENGTHVALUE2=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMWIDTHVALUE0=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMWIDTHVALUE1=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMWIDTHVALUE2=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE0=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE1=%20%20%200%2e00000'. '&L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE2=%20%20%200%2e00000'. // Errors '&PAYMENTREQUESTINFO_0_ERRORCODE=0'; $this->bogus->http->returnsByValue( 'post', $mock_response ); $response = $this->bogus->get_details_for( $this->token ); $this->assertTrue( $response->is_successful() ); $this->assertFalse( $response->has_errors() ); // API Info $this->assertTrue( $response->is_checkout_not_initiated() ); $this->assertFalse( $response->is_checkout_failed() ); $this->assertFalse( $response->is_checkout_in_progress() ); $this->assertFalse( $response->is_checkout_completed() ); $this->assertEqual( $response->get( 'checkout_status' ), 'Not-Initiated' ); $this->assertEqual( $response->get( 'token' ), 'EC-6EC97401PF4449255' ); $this->assertEqual( $response->get( 'timestamp' ), 1314259466 ); $this->assertEqual( $response->get( 'datetime' ), '2011-08-25T08:04:26Z' ); $this->assertEqual( $response->get( 'correlation_id' ), 'b5ae9bd5c735f' ); $this->assertEqual( $response->get( 'version' ), '114.0' ); $this->assertEqual( $response->get( 'build' ), '2085867' ); // Payer Information $mock_payer = (Object) array( 'email' => 'visa_1304648966_per@garyc40.com', 'id' => 'BC798KQ2QU22W', 'status' => 'verified', 'shipping_status' => 'Unconfirmed', 'first_name' => 'Test', 'last_name' => 'User', 'country' => 'US', ); $this->assertEqual( $response->get( 'payer' ), $mock_payer ); // Shipping Address $mock_shipping_address = array( 'name' => 'Gary Cao', 'street' => '1 Infinite Loop', 'street2' => 'Apple Headquarter', 'city' => 'Cupertino', 'state' => 'CA', 'zip' => '95014', 'country_code' => 'US', 'country' => 'United States', 'phone' => '(877) 412-7753', ); $this->assertEqual( $response->get( 'shipping_address' ), $mock_shipping_address ); // Payment Information $this->assertEqual( $response->get( 'currency' ), 'JPY' ); $this->assertEqual( $response->get( 'amount' ), 15337 ); $this->assertEqual( $response->get( 'subtotal' ), 13700 ); $this->assertEqual( $response->get( 'shipping' ), 1500 ); $this->assertEqual( $response->get( 'handling' ), 0 ); $this->assertEqual( $response->get( 'tax' ), 137 ); $this->assertEqual( $response->get( 'invoice' ), 'E84A90G94' ); $this->assertEqual( $response->get( 'notify_url' ), 'http://example.com/ipn' ); $this->assertEqual( $response->get( 'shipping_discount' ), 0 ); // Item Information $items = $response->get( 'items' ); $mock_items = array(); $mock_items[0] = new stdClass(); $mock_items[0]->name = 'Gold Cart Plugin'; $mock_items[0]->description = 'Gold Cart extends your WP eCommerce store by enabling additional features and functionality.'; $mock_items[0]->amount = 4000; $mock_items[0]->quantity = 1; $mock_items[0]->tax = 40; $mock_items[1] = new stdClass(); $mock_items[1]->name = 'Member Access Plugin'; $mock_items[1]->description = 'Create pay to view subscription sites'; $mock_items[1]->amount = 5000; $mock_items[1]->quantity = 1; $mock_items[1]->tax = 50; $mock_items[2] = new stdClass(); $mock_items[2]->name = 'Amazon S3'; $mock_items[2]->description = 'This Plugin allows downloadable products on your WP eCommerce site to be hosted on Amazon S3.'; $mock_items[2]->amount = 4700; $mock_items[2]->quantity = 1; $mock_items[2]->tax = 47; $this->assertEqual( $items, $mock_items ); } public function test_correct_response_is_returned_when_set_express_checkout_fails() { $mock_response = 'ACK=Failure&CORRELATIONID=224f0e4a32d14&TIMESTAMP=2011%2d07%2d05T13%253A23%253A52Z&VERSION=2%2e30000&BUILD=1%2e0006&TOKEN=EC%2d1OIN4UJGFOK54YFV&L_ERRORCODE0=10412&L_SHORTMESSAGE0=Duplicate%20invoice&L_LONGMESSAGE0=Payment%20has%20already%20been%20made%20for%20this%20InvoiceID.&L_SEVERITYCODE0=3&L_ERRORCODE1=10010&L_SHORTMESSAGE1=Invalid%20Invoice&L_LONGMESSAGE1=Non-ASCII%20invoice%20id%20is%20not%20supported.&L_SEVERITYCODE1=3'; $this->bogus->http->returnsByValue( 'post', $mock_response ); $response = $this->bogus->setup_purchase( $this->setup_purchase_options ); $this->assertFalse( $response->is_successful() ); $this->assertTrue( $response->has_errors() ); $this->assertEqual( $response->get( 'timestamp' ), 1309872232 ); $this->assertEqual( $response->get( 'datetime' ), '2011-07-05T13:23:52Z' ); $this->assertEqual( $response->get( 'correlation_id' ), '224f0e4a32d14' ); $this->assertEqual( $response->get( 'version' ), '2.30000' ); $this->assertEqual( $response->get( 'build' ), '1.0006' ); $expected_errors = array( array( 'code' => 10412, 'message' => 'Duplicate invoice', 'details' => 'Payment has already been made for this InvoiceID.', ), array( 'code' => 10010, 'message' => 'Invalid Invoice', 'details' => 'Non-ASCII invoice id is not supported.', ), ); $actual_errors = $response->get_errors(); $this->assertEqual( $actual_errors, $expected_errors ); } public function test_correct_response_is_returned_when_set_express_checkout_is_successful_with_warning() { $mock_response = 'ACK=SuccessWithWarning&CORRELATIONID=224f0e4a32d14&TIMESTAMP=2011%2d07%2d05T13%253A23%253A52Z&VERSION=2%2e30000&BUILD=1%2e0006&TOKEN=EC%2d1OIN4UJGFOK54YFV&L_ERRORCODE0=10412&L_SHORTMESSAGE0=Duplicate%20invoice&L_LONGMESSAGE0=Payment%20has%20already%20been%20made%20for%20this%20InvoiceID.&L_SEVERITYCODE0=3&L_ERRORCODE1=10010&L_SHORTMESSAGE1=Invalid%20Invoice&L_LONGMESSAGE1=Non-ASCII%20invoice%20id%20is%20not%20supported.&L_SEVERITYCODE1=3'; $this->bogus->http->returnsByValue( 'post', $mock_response ); $response = $this->bogus->setup_purchase( $this->setup_purchase_options ); $this->assertTrue( $response->is_successful() ); $this->assertTrue( $response->has_errors() ); $this->assertEqual( $response->get( 'token' ), 'EC-1OIN4UJGFOK54YFV' ); $this->assertEqual( $response->get( 'timestamp' ), 1309872232 ); $this->assertEqual( $response->get( 'datetime' ), '2011-07-05T13:23:52Z' ); $this->assertEqual( $response->get( 'correlation_id' ), '224f0e4a32d14' ); $this->assertEqual( $response->get( 'version' ), '2.30000' ); $this->assertEqual( $response->get( 'build' ), '1.0006' ); $expected_errors = array( array( 'code' => 10412, 'message' => 'Duplicate invoice', 'details' => 'Payment has already been made for this InvoiceID.', ), array( 'code' => 10010, 'message' => 'Invalid Invoice', 'details' => 'Non-ASCII invoice id is not supported.', ), ); $actual_errors = $response->get_errors(); $this->assertEqual( $actual_errors, $expected_errors ); } } require_once( PHP_MERCHANT_PATH . '/common/http-curl.php' ); Mock::generate( 'PHP_Merchant_HTTP_CURL' ); class PHP_Merchant_Paypal_Express_Checkout_Bogus extends PHP_Merchant_Paypal_Express_Checkout { public $http; public function __construct( $options = array() ) { $options['http_client'] = new MockPHP_Merchant_HTTP_CURL(); parent::__construct( $options ); } }
gpl-2.0
HladikBox/Console
plugins/ace-builds/src/mode-sql.js
3094
define("ace/mode/sql_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SqlHighlightRules = function() { var keywords = ( "select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" + "when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|primary|key|if|" + "foreign|not|references|default|null|inner|cross|natural|database|drop|grant" ); var builtinConstants = ( "true|false" ); var builtinFunctions = ( "avg|count|first|last|max|min|sum|ucase|lcase|mid|len|round|rank|now|format|" + "coalesce|ifnull|isnull|nvl" ); var dataTypes = ( "int|numeric|decimal|date|varchar|char|bigint|float|double|bit|binary|text|set|timestamp|" + "money|real|number|integer" ); var keywordMapper = this.createKeywordMapper({ "support.function": builtinFunctions, "keyword": keywords, "constant.language": builtinConstants, "storage.type": dataTypes }, "identifier", true); this.$rules = { "start" : [ { token : "comment", regex : "--.*$" }, { token : "comment", start : "/\\*", end : "\\*/" }, { token : "string", // " string regex : '".*?"' }, { token : "string", // ' string regex : "'.*?'" }, { token : "string", // ` string (apache drill) regex : "`.*?`" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\(]" }, { token : "paren.rparen", regex : "[\\)]" }, { token : "text", regex : "\\s+" } ] }; this.normalizeRules(); }; oop.inherits(SqlHighlightRules, TextHighlightRules); exports.SqlHighlightRules = SqlHighlightRules; }); define("ace/mode/sql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sql_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules; var Mode = function() { this.HighlightRules = SqlHighlightRules; this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "--"; this.$id = "ace/mode/sql"; }).call(Mode.prototype); exports.Mode = Mode; });
apache-2.0
drsquidop/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/DelegationSet.java
11844
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.route53.model; import java.io.Serializable; /** * <p> * A complex type that contains name server information. * </p> */ public class DelegationSet implements Serializable, Cloneable { private String id; private String callerReference; /** * A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> */ private com.amazonaws.internal.ListWithAutoConstructFlag<String> nameServers; /** * Default constructor for a new DelegationSet object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public DelegationSet() {} /** * Constructs a new DelegationSet object. * Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param nameServers A complex type that contains the authoritative name * servers for the hosted zone. Use the method provided by your domain * registrar to add an NS record to your domain for each * <code>NameServer</code> that is assigned to your hosted zone. */ public DelegationSet(java.util.List<String> nameServers) { setNameServers(nameServers); } /** * Returns the value of the Id property for this object. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 32<br/> * * @return The value of the Id property for this object. */ public String getId() { return id; } /** * Sets the value of the Id property for this object. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 32<br/> * * @param id The new value for the Id property for this object. */ public void setId(String id) { this.id = id; } /** * Sets the value of the Id property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 32<br/> * * @param id The new value for the Id property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public DelegationSet withId(String id) { this.id = id; return this; } /** * Returns the value of the CallerReference property for this object. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * * @return The value of the CallerReference property for this object. */ public String getCallerReference() { return callerReference; } /** * Sets the value of the CallerReference property for this object. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * * @param callerReference The new value for the CallerReference property for this object. */ public void setCallerReference(String callerReference) { this.callerReference = callerReference; } /** * Sets the value of the CallerReference property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * * @param callerReference The new value for the CallerReference property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public DelegationSet withCallerReference(String callerReference) { this.callerReference = callerReference; return this; } /** * A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @return A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. */ public java.util.List<String> getNameServers() { if (nameServers == null) { nameServers = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(); nameServers.setAutoConstruct(true); } return nameServers; } /** * A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param nameServers A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. */ public void setNameServers(java.util.Collection<String> nameServers) { if (nameServers == null) { this.nameServers = null; return; } com.amazonaws.internal.ListWithAutoConstructFlag<String> nameServersCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(nameServers.size()); nameServersCopy.addAll(nameServers); this.nameServers = nameServersCopy; } /** * A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setNameServers(java.util.Collection)} or {@link * #withNameServers(java.util.Collection)} if you want to override the * existing values. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param nameServers A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * * @return A reference to this updated object so that method calls can be chained * together. */ public DelegationSet withNameServers(String... nameServers) { if (getNameServers() == null) setNameServers(new java.util.ArrayList<String>(nameServers.length)); for (String value : nameServers) { getNameServers().add(value); } return this; } /** * A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param nameServers A complex type that contains the authoritative name servers for the * hosted zone. Use the method provided by your domain registrar to add * an NS record to your domain for each <code>NameServer</code> that is * assigned to your hosted zone. * * @return A reference to this updated object so that method calls can be chained * together. */ public DelegationSet withNameServers(java.util.Collection<String> nameServers) { if (nameServers == null) { this.nameServers = null; } else { com.amazonaws.internal.ListWithAutoConstructFlag<String> nameServersCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(nameServers.size()); nameServersCopy.addAll(nameServers); this.nameServers = nameServersCopy; } return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: " + getId() + ","); if (getCallerReference() != null) sb.append("CallerReference: " + getCallerReference() + ","); if (getNameServers() != null) sb.append("NameServers: " + getNameServers() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getCallerReference() == null) ? 0 : getCallerReference().hashCode()); hashCode = prime * hashCode + ((getNameServers() == null) ? 0 : getNameServers().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DelegationSet == false) return false; DelegationSet other = (DelegationSet)obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getCallerReference() == null ^ this.getCallerReference() == null) return false; if (other.getCallerReference() != null && other.getCallerReference().equals(this.getCallerReference()) == false) return false; if (other.getNameServers() == null ^ this.getNameServers() == null) return false; if (other.getNameServers() != null && other.getNameServers().equals(this.getNameServers()) == false) return false; return true; } @Override public DelegationSet clone() { try { return (DelegationSet) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
soldiermoth/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/GetIdentityNotificationAttributesResult.java
5829
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleemail.model; import java.io.Serializable; /** * <p> * Describes whether an identity has Amazon Simple Notification Service * (Amazon SNS) topics set for bounce, complaint, and/or delivery * notifications, and specifies whether feedback forwarding is enabled * for bounce and complaint notifications. * </p> */ public class GetIdentityNotificationAttributesResult implements Serializable, Cloneable { /** * A map of Identity to IdentityNotificationAttributes. */ private java.util.Map<String,IdentityNotificationAttributes> notificationAttributes; /** * A map of Identity to IdentityNotificationAttributes. * * @return A map of Identity to IdentityNotificationAttributes. */ public java.util.Map<String,IdentityNotificationAttributes> getNotificationAttributes() { if (notificationAttributes == null) { notificationAttributes = new java.util.HashMap<String,IdentityNotificationAttributes>(); } return notificationAttributes; } /** * A map of Identity to IdentityNotificationAttributes. * * @param notificationAttributes A map of Identity to IdentityNotificationAttributes. */ public void setNotificationAttributes(java.util.Map<String,IdentityNotificationAttributes> notificationAttributes) { this.notificationAttributes = notificationAttributes; } /** * A map of Identity to IdentityNotificationAttributes. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param notificationAttributes A map of Identity to IdentityNotificationAttributes. * * @return A reference to this updated object so that method calls can be chained * together. */ public GetIdentityNotificationAttributesResult withNotificationAttributes(java.util.Map<String,IdentityNotificationAttributes> notificationAttributes) { setNotificationAttributes(notificationAttributes); return this; } /** * A map of Identity to IdentityNotificationAttributes. * <p> * The method adds a new key-value pair into NotificationAttributes * parameter, and returns a reference to this object so that method calls * can be chained together. * * @param key The key of the entry to be added into NotificationAttributes. * @param value The corresponding value of the entry to be added into NotificationAttributes. */ public GetIdentityNotificationAttributesResult addNotificationAttributesEntry(String key, IdentityNotificationAttributes value) { if (null == this.notificationAttributes) { this.notificationAttributes = new java.util.HashMap<String,IdentityNotificationAttributes>(); } if (this.notificationAttributes.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.notificationAttributes.put(key, value); return this; } /** * Removes all the entries added into NotificationAttributes. * <p> * Returns a reference to this object so that method calls can be chained together. */ public GetIdentityNotificationAttributesResult clearNotificationAttributesEntries() { this.notificationAttributes = null; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getNotificationAttributes() != null) sb.append("NotificationAttributes: " + getNotificationAttributes() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNotificationAttributes() == null) ? 0 : getNotificationAttributes().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetIdentityNotificationAttributesResult == false) return false; GetIdentityNotificationAttributesResult other = (GetIdentityNotificationAttributesResult)obj; if (other.getNotificationAttributes() == null ^ this.getNotificationAttributes() == null) return false; if (other.getNotificationAttributes() != null && other.getNotificationAttributes().equals(this.getNotificationAttributes()) == false) return false; return true; } @Override public GetIdentityNotificationAttributesResult clone() { try { return (GetIdentityNotificationAttributesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
drsquidop/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/transform/ApplyPendingMaintenanceActionRequestMarshaller.java
2539
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.rds.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.internal.ListWithAutoConstructFlag; import com.amazonaws.services.rds.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Apply Pending Maintenance Action Request Marshaller */ public class ApplyPendingMaintenanceActionRequestMarshaller implements Marshaller<Request<ApplyPendingMaintenanceActionRequest>, ApplyPendingMaintenanceActionRequest> { public Request<ApplyPendingMaintenanceActionRequest> marshall(ApplyPendingMaintenanceActionRequest applyPendingMaintenanceActionRequest) { if (applyPendingMaintenanceActionRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<ApplyPendingMaintenanceActionRequest> request = new DefaultRequest<ApplyPendingMaintenanceActionRequest>(applyPendingMaintenanceActionRequest, "AmazonRDS"); request.addParameter("Action", "ApplyPendingMaintenanceAction"); request.addParameter("Version", "2014-10-31"); if (applyPendingMaintenanceActionRequest.getResourceIdentifier() != null) { request.addParameter("ResourceIdentifier", StringUtils.fromString(applyPendingMaintenanceActionRequest.getResourceIdentifier())); } if (applyPendingMaintenanceActionRequest.getApplyAction() != null) { request.addParameter("ApplyAction", StringUtils.fromString(applyPendingMaintenanceActionRequest.getApplyAction())); } if (applyPendingMaintenanceActionRequest.getOptInType() != null) { request.addParameter("OptInType", StringUtils.fromString(applyPendingMaintenanceActionRequest.getOptInType())); } return request; } }
apache-2.0
cgvarela/chef
spec/unit/provider/service/redhat_spec.rb
12114
# # Author:: AJ Christensen (<aj@hjksolutions.com>) # Copyright:: Copyright (c) 2008 HJK Solutions, LLC # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", "spec_helper")) require 'ostruct' shared_examples_for "define_resource_requirements_common" do it "should raise an error if /sbin/chkconfig does not exist" do allow(File).to receive(:exists?).with("/sbin/chkconfig").and_return(false) allow(@provider).to receive(:shell_out).with("/sbin/service chef status").and_raise(Errno::ENOENT) allow(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_raise(Errno::ENOENT) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end it "should not raise an error if the service exists but is not added to any runlevels" do status = double("Status", :exitstatus => 0, :stdout => "" , :stderr => "") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "", :stderr => "service chef supports chkconfig, but is not referenced in any runlevel (run 'chkconfig --add chef')") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.not_to raise_error end end describe "Chef::Provider::Service::Redhat" do before(:each) do @node = Chef::Node.new @node.automatic_attrs[:command] = {:ps => 'foo'} @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::Service.new("chef") @current_resource = Chef::Resource::Service.new("chef") @provider = Chef::Provider::Service::Redhat.new(@new_resource, @run_context) @provider.action = :start allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource) allow(File).to receive(:exists?).with("/sbin/chkconfig").and_return(true) end describe "while not in why run mode" do before(:each) do Chef::Config[:why_run] = false end describe "load current resource" do before do status = double("Status", :exitstatus => 0, :stdout => "" , :stderr => "") allow(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) end it "sets supports[:status] to true by default" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@provider.supports[:status]).to be true end it "lets the user override supports[:status] in the new_resource" do @new_resource.supports( { status: false } ) @new_resource.pattern "myservice" chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) foo_out = double("ps_command", :exitstatus => 0, :stdout => "a line that matches myservice", :stderr => "") expect(@provider).to receive(:shell_out!).with("foo").and_return(foo_out) expect(@provider.service_missing).to be false expect(@provider).not_to receive(:shell_out).with("/sbin/service chef status") @provider.load_current_resource expect(@provider.supports[:status]).to be false end it "sets the current enabled status to true if the service is enabled for any run level" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:on 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be true end it "sets the current enabled status to false if the regex does not match" do chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:off 2:off 3:off 4:off 5:off 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false expect(@provider.load_current_resource).to eql(@current_resource) expect(@current_resource.enabled).to be false end it "sets the current enabled status to true if the service is enabled at specified run levels" do @new_resource.run_levels([1, 2]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:on 3:off 4:off 5:off 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be true expect(@provider.current_run_levels).to eql([1, 2]) end it "sets the current enabled status to false if the service is enabled at a run level it should not" do @new_resource.run_levels([1, 2]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:on 3:on 4:off 5:off 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be false expect(@provider.current_run_levels).to eql([1, 2, 3]) end it "sets the current enabled status to false if the service is not enabled at specified run levels" do @new_resource.run_levels([ 2 ]) chkconfig = double("Chkconfig", :exitstatus => 0, :stdout => "chef 0:off 1:on 2:off 3:off 4:off 5:off 6:off", :stderr => "") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) expect(@provider.service_missing).to be false @provider.load_current_resource expect(@current_resource.enabled).to be false expect(@provider.current_run_levels).to eql([1]) end end describe "define resource requirements" do it_should_behave_like "define_resource_requirements_common" context "when the service does not exist" do before do status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :existatus=> 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements end [ "start", "reload", "restart", "enable" ].each do |action| it "should raise an error when the action is #{action}" do @provider.action = action expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::Service) end end [ "stop", "disable" ].each do |action| it "should not raise an error when the action is #{action}" do @provider.action = action expect { @provider.process_resource_requirements }.not_to raise_error end end end end end describe "while in why run mode" do before(:each) do Chef::Config[:why_run] = true end after do Chef::Config[:why_run] = false end describe "define resource requirements" do it_should_behave_like "define_resource_requirements_common" it "should not raise an error if the service does not exist" do status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service") expect(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status) chkconfig = double("Chkconfig", :existatus=> 1, :stdout => "", :stderr => "error reading information on service chef: No such file or directory") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --list chef", :returns => [0,1]).and_return(chkconfig) @provider.load_current_resource @provider.define_resource_requirements expect { @provider.process_resource_requirements }.not_to raise_error end end end describe "enable_service" do it "should call chkconfig to add 'service_name'" do expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig #{@new_resource.service_name} on") @provider.enable_service end it "should call chkconfig to add 'service_name' at specified run_levels" do allow(@provider).to receive(:run_levels).and_return([1, 2]) expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 12 #{@new_resource.service_name} on") @provider.enable_service end it "should call chkconfig to add 'service_name' at specified run_levels when run_levels do not match" do allow(@provider).to receive(:run_levels).and_return([1, 2]) allow(@provider).to receive(:current_run_levels).and_return([1, 3]) expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 12 #{@new_resource.service_name} on") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 3 #{@new_resource.service_name} off") @provider.enable_service end it "should call chkconfig to add 'service_name' at specified run_levels if there is an extra run_level" do allow(@provider).to receive(:run_levels).and_return([1, 2]) allow(@provider).to receive(:current_run_levels).and_return([1, 2, 3]) expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 12 #{@new_resource.service_name} on") expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 3 #{@new_resource.service_name} off") @provider.enable_service end end describe "disable_service" do it "should call chkconfig to del 'service_name'" do expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig #{@new_resource.service_name} off") @provider.disable_service end it "should call chkconfig to del 'service_name' at specified run_levels" do allow(@provider).to receive(:run_levels).and_return([1, 2]) expect(@provider).to receive(:shell_out!).with("/sbin/chkconfig --level 12 #{@new_resource.service_name} off") @provider.disable_service end end end
apache-2.0
hpmtissera/product-is
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/utils/WorkflowConstants.java
1875
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.identity.integration.test.utils; public class WorkflowConstants { private WorkflowConstants(){ } public static final String IMMEDIATE_DENY_TEMPLATE_IMPL_NAME = "Default"; public static final String IMMEDIATE_DENY_TEMPLATE_ID = "ImmediateDeny"; public static final String ADD_USER_EVENT = "ADD_USER"; public static final String ADD_ROLE_EVENT = "ADD_ROLE"; public static final String DELETE_USER_EVENT = "DELETE_USER"; public static final String DELETE_ROLE_EVENT = "DELETE_ROLE"; public static final String UPDATE_ROLE_NAME_EVENT = "UPDATE_ROLE_NAME"; public static final String CHANGE_USER_CREDENTIAL_EVENT = "CHANGE_CREDENTIAL"; public static final String SET_USER_CLAIM_EVENT = "SET_USER_CLAIM"; public static final String DELETE_USER_CLAIM_EVENT = "DELETE_MULTIPLE_USER_CLAIMS"; public static final String SET_MULTIPLE_USER_CLAIMS_EVENT = "SET_MULTIPLE_USER_CLAIMS"; public static final String DELETE_MULTIPLE_USER_CLAIMS_EVENT = "DELETE_MULTIPLE_USER_CLAIMS"; public static final String UPDATE_USER_ROLES_EVENT = "UPDATE_USER_ROLES"; public static final String UPDATE_ROLE_USERS_EVENT = "UPDATE_ROLE_USERS"; }
apache-2.0
GeoinformationSystems/Time4Maps
WebContent/js/dojo-release-1.9.0/dojox/editor/plugins/nls/Breadcrumb.js
632
//>>built define("dojox/editor/plugins/nls/Breadcrumb",{root:({"nodeActions":"${nodeName} Actions","selectContents":"Select contents","selectElement":"Select element","deleteElement":"Delete element","deleteContents":"Delete contents","moveStart":"Move cursor to start","moveEnd":"Move cursor to end"}),"zh":true,"zh-tw":true,"uk":true,"tr":true,"th":true,"sv":true,"sl":true,"sk":true,"ru":true,"ro":true,"pt":true,"pt-pt":true,"pl":true,"nl":true,"nb":true,"ko":true,"kk":true,"ja":true,"it":true,"hu":true,"hr":true,"he":true,"fr":true,"fi":true,"es":true,"el":true,"de":true,"da":true,"cs":true,"ca":true,"bg":true,"ar":true});
apache-2.0
jgcaaprom/android_external_chromium_org
net/quic/quic_server_test.cc
1908
// 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 "net/quic/quic_server.h" #include "net/quic/crypto/quic_random.h" #include "net/quic/quic_utils.h" #include "net/quic/test_tools/mock_quic_dispatcher.h" #include "net/quic/test_tools/quic_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; namespace net { namespace test { namespace { // TODO(dmz) Remove "Chrome" part of name once net/tools/quic is deleted. class QuicChromeServerDispatchPacketTest : public ::testing::Test { public: QuicChromeServerDispatchPacketTest() : crypto_config_("blah", QuicRandom::GetInstance()), dispatcher_(config_, crypto_config_, new QuicDispatcher::DefaultPacketWriterFactory(), &helper_) { dispatcher_.Initialize(NULL); } void DispatchPacket(const QuicEncryptedPacket& packet) { IPEndPoint client_addr, server_addr; dispatcher_.ProcessPacket(server_addr, client_addr, packet); } protected: QuicConfig config_; QuicCryptoServerConfig crypto_config_; MockHelper helper_; MockQuicDispatcher dispatcher_; }; TEST_F(QuicChromeServerDispatchPacketTest, DispatchPacket) { unsigned char valid_packet[] = { // public flags (8 byte connection_id) 0x3C, // connection_id 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, // packet sequence number 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, // private flags 0x00 }; QuicEncryptedPacket encrypted_valid_packet(QuicUtils::AsChars(valid_packet), arraysize(valid_packet), false); EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1); DispatchPacket(encrypted_valid_packet); } } // namespace } // namespace test } // namespace net
bsd-3-clause
brettonw/Jane
site/js-lib/d3/examples/splom/splom.js
3532
d3.json("flowers.json", function(flower) { // Size parameters. var size = 150, padding = 19.5, n = flower.traits.length; // Position scales. var x = {}, y = {}; flower.traits.forEach(function(trait) { var value = function(d) { return d[trait]; }, domain = [d3.min(flower.values, value), d3.max(flower.values, value)], range = [padding / 2, size - padding / 2]; x[trait] = d3.scale.linear() .domain(domain) .range(range); y[trait] = d3.scale.linear() .domain(domain) .range(range.slice().reverse()); }); // Axes. var axis = d3.svg.axis() .ticks(5) .tickSize(size * n); // Brush. var brush = d3.svg.brush() .on("brushstart", brushstart) .on("brush", brush) .on("brushend", brushend); // Root panel. var svg = d3.select("#chart").append("svg") .attr("width", size * n + padding) .attr("height", size * n + padding); // X-axis. svg.selectAll("g.x.axis") .data(flower.traits) .enter().append("g") .attr("class", "x axis") .attr("transform", function(d, i) { return "translate(" + i * size + ",0)"; }) .each(function(d) { d3.select(this).call(axis.scale(x[d]).orient("bottom")); }); // Y-axis. svg.selectAll("g.y.axis") .data(flower.traits) .enter().append("g") .attr("class", "y axis") .attr("transform", function(d, i) { return "translate(0," + i * size + ")"; }) .each(function(d) { d3.select(this).call(axis.scale(y[d]).orient("right")); }); // Cell and plot. var cell = svg.selectAll("g.cell") .data(cross(flower.traits, flower.traits)) .enter().append("g") .attr("class", "cell") .attr("transform", function(d) { return "translate(" + d.i * size + "," + d.j * size + ")"; }) .each(plot); // Titles for the diagonal. cell.filter(function(d) { return d.i == d.j; }).append("text") .attr("x", padding) .attr("y", padding) .attr("dy", ".71em") .text(function(d) { return d.x; }); function plot(p) { var cell = d3.select(this); // Plot frame. cell.append("rect") .attr("class", "frame") .attr("x", padding / 2) .attr("y", padding / 2) .attr("width", size - padding) .attr("height", size - padding); // Plot dots. cell.selectAll("circle") .data(flower.values) .enter().append("circle") .attr("class", function(d) { return d.species; }) .attr("cx", function(d) { return x[p.x](d[p.x]); }) .attr("cy", function(d) { return y[p.y](d[p.y]); }) .attr("r", 3); // Plot brush. cell.call(brush.x(x[p.x]).y(y[p.y])); } // Clear the previously-active brush, if any. function brushstart(p) { if (brush.data !== p) { cell.call(brush.clear()); brush.x(x[p.x]).y(y[p.y]).data = p; } } // Highlight the selected circles. function brush(p) { var e = brush.extent(); svg.selectAll("circle").attr("class", function(d) { return e[0][0] <= d[p.x] && d[p.x] <= e[1][0] && e[0][1] <= d[p.y] && d[p.y] <= e[1][1] ? d.species : null; }); } // If the brush is empty, select all circles. function brushend() { if (brush.empty()) svg.selectAll("circle").attr("class", function(d) { return d.species; }); } function cross(a, b) { var c = [], n = a.length, m = b.length, i, j; for (i = -1; ++i < n;) for (j = -1; ++j < m;) c.push({x: a[i], i: i, y: b[j], j: j}); return c; } });
mit
toaicntt/base
assets/vendor/ckfinder/core/connector/php/vendor/league/flysystem-cached-adapter/src/CachedAdapter.php
6534
<?php namespace League\Flysystem\Cached; use League\Flysystem\AdapterInterface; use League\Flysystem\Config; class CachedAdapter implements AdapterInterface { /** * @var AdapterInterface */ private $adapter; /** * @var CacheInterface */ private $cache; /** * Constructor. * * @param AdapterInterface $adapter * @param CacheInterface $cache */ public function __construct(AdapterInterface $adapter, CacheInterface $cache) { $this->adapter = $adapter; $this->cache = $cache; $this->cache->load(); } /** * {@inheritdoc} */ public function getAdapter() { return $this->adapter; } /** * {@inheritdoc} */ public function write($path, $contents, Config $config) { $result = $this->adapter->write($path, $contents, $config); if ($result !== false) { $this->cache->updateObject($path, $result + compact('path', 'contents'), true); } return $result; } /** * {@inheritdoc} */ public function writeStream($path, $resource, Config $config) { $result = $this->adapter->writeStream($path, $resource, $config); if ($result !== false) { $contents = false; $this->cache->updateObject($path, $result + compact('path', 'contents'), true); } return $result; } /** * {@inheritdoc} */ public function update($path, $contents, Config $config) { $result = $this->adapter->update($path, $contents, $config); if ($result !== false) { $this->cache->updateObject($path, $result + compact('path', 'contents'), true); } return $result; } /** * {@inheritdoc} */ public function updateStream($path, $resource, Config $config) { $result = $this->adapter->updateStream($path, $resource, $config); if ($result !== false) { $contents = false; $this->cache->updateObject($path, $result + compact('path', 'contents'), true); } return $result; } /** * {@inheritdoc} */ public function rename($path, $newPath) { $result = $this->adapter->rename($path, $newPath); if ($result !== false) { $this->cache->rename($path, $newPath); } return $result; } /** * {@inheritdoc} */ public function copy($path, $newpath) { $result = $this->adapter->copy($path, $newpath); if ($result !== false) { $this->cache->copy($path, $newpath); } return $result; } /** * {@inheritdoc} */ public function delete($path) { $result = $this->adapter->delete($path); if ($result !== false) { $this->cache->delete($path); } return $result; } /** * {@inheritdoc} */ public function deleteDir($dirname) { $result = $this->adapter->deleteDir($dirname); if ($result !== false) { $this->cache->deleteDir($dirname); } return $result; } /** * {@inheritdoc} */ public function createDir($dirname, Config $config) { $result = $this->adapter->createDir($dirname, $config); if ($result !== false) { $type = 'dir'; $path = $dirname; $this->cache->updateObject($dirname, compact('path', 'type'), true); } return $result; } /** * {@inheritdoc} */ public function setVisibility($path, $visibility) { $result = $this->adapter->setVisibility($path, $visibility); if ($result !== false) { $this->cache->updateObject($path, compact('path', 'visibility'), true); } return $result; } /** * {@inheritdoc} */ public function has($path) { $cacheHas = $this->cache->has($path); if ($cacheHas !== null) { return $cacheHas; } $adapterResponse = $this->adapter->has($path); if (! $adapterResponse) { $this->cache->storeMiss($path); } else { $cacheEntry = is_array($adapterResponse) ? $adapterResponse : compact('path'); $this->cache->updateObject($path, $cacheEntry, true); } return $adapterResponse; } /** * {@inheritdoc} */ public function read($path) { return $this->callWithFallback('read', $path); } /** * {@inheritdoc} */ public function readStream($path) { return $this->adapter->readStream($path); } /** * {@inheritdoc} */ public function listContents($directory = '', $recursive = false) { if ($this->cache->isComplete($directory, $recursive)) { return $this->cache->listContents($directory, $recursive); } $result = $this->adapter->listContents($directory, $recursive); if ($result) { $this->cache->storeContents($directory, $result, $recursive); } return $result; } /** * {@inheritdoc} */ public function getMetadata($path) { return $this->callWithFallback('getMetadata', $path); } /** * {@inheritdoc} */ public function getSize($path) { return $this->callWithFallback('getSize', $path); } /** * {@inheritdoc} */ public function getMimetype($path) { return $this->callWithFallback('getMimetype', $path); } /** * {@inheritdoc} */ public function getTimestamp($path) { return $this->callWithFallback('getTimestamp', $path); } /** * {@inheritdoc} */ public function getVisibility($path) { return $this->callWithFallback('getVisibility', $path); } /** * Call a method and cache the response. * * @param string $method * @param string $path * * @return mixed */ protected function callWithFallback($method, $path) { $result = $this->cache->{$method}($path); if ($result !== false) { return $result; } $result = $this->adapter->{$method}($path); if ($result) { $object = $result + compact('path'); $this->cache->updateObject($path, $object, true); } return $result; } }
mit
gippy/nahladine
wp-content/plugins/sitepress-multilingual-cms/inc/upgrade-functions/upgrade-2.0.0.php
12425
<?php function icl_upgrade_2_0_0_steps($step, $stepper){ global $wpdb, $sitepress, $wp_post_types, $sitepress_settings; if(!isset($sitepress)) $sitepress = new SitePress; $TranslationManagement = new TranslationManagement; define('ICL_TM_DISABLE_ALL_NOTIFICATIONS', true); // make sure no notifications are being sent //if(defined('icl_upgrade_2_0_0_runonce')){ // return; //} //define('icl_upgrade_2_0_0_runonce', true); // fix source_language_code // assume that the lowest element_id is the source language ini_set('max_execution_time', 300); $post_types = array_keys($wp_post_types); foreach($post_types as $pt){ $types[] = 'post_' . $pt; } $temp_upgrade_data = get_option('icl_temp_upgrade_data', array('step' => 0, 'offset' => 0)); switch($step) { case 1: // if the tables are missing, call the plugin activation routine $table_name = $wpdb->prefix.'icl_translation_status'; if($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name){ icl_sitepress_activate(); } $wpdb->query("ALTER TABLE `{$wpdb->prefix}icl_translations` CHANGE `element_type` `element_type` VARCHAR( 32 ) NOT NULL DEFAULT 'post_post'"); $wpdb->query("ALTER TABLE `{$wpdb->prefix}icl_translations` CHANGE `element_id` `element_id` BIGINT( 20 ) NULL DEFAULT NULL "); // fix source_language_code // all source documents must have null $wpdb->query($wpdb->prepare("UPDATE {$wpdb->prefix}icl_translations SET source_language_code = NULL WHERE element_type IN('".join("','", $types)."') AND source_language_code = '' AND language_code='%s'", $sitepress->get_default_language())); // get translated documents with missing source language $res = $wpdb->get_results($wpdb->prepare(" SELECT translation_id, trid, language_code FROM {$wpdb->prefix}icl_translations WHERE (source_language_code = '' OR source_language_code IS NULL) AND element_type IN('".join("','", $types)."') AND language_code <> %s ", $sitepress->get_default_language() )); foreach($res as $row){ $wpdb->query($wpdb->prepare("UPDATE {$wpdb->prefix}icl_translations SET source_language_code = '%s' WHERE translation_id=%d", $sitepress->get_default_language(), $row->translation_id)); } $temp_upgrade_data['step'] = 2; update_option('icl_temp_upgrade_data', $temp_upgrade_data); return array('message' => __('Processing translations...', 'sitepress')); break; case 2: $limit = 100; $offset = $temp_upgrade_data['offset']; $processing = FALSE; //loop existing translations $res = mysql_query("SELECT * FROM {$wpdb->prefix}icl_translations WHERE element_type IN('".join("','", $types)."') AND source_language_code IS NULL LIMIT " . $limit . " OFFSET " . $offset); while($row = mysql_fetch_object($res)){ $processing = TRUE; // grab translations $translations = $sitepress->get_element_translations($row->trid, $row->element_type); $md5 = 0; $table_name = $wpdb->prefix.'icl_node'; if($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") == $table_name){ list($md5, $links_fixed) = $wpdb->get_row($wpdb->prepare(" SELECT md5, links_fixed FROM {$wpdb->prefix}icl_node WHERE nid = %d ", $row->element_id), ARRAY_N); } if(!$md5){ $md5 = $TranslationManagement->post_md5($row->element_id); } $translation_package = $TranslationManagement->create_translation_package($row->element_id); foreach($translations as $lang => $t){ if(!$t->original){ // determine service and status $service = 'local'; $status = 10; $needs_update = 0; list($rid, $status, $current_md5) = $wpdb->get_row($wpdb->prepare(" SELECT c.rid, n.status , c.md5 FROM {$wpdb->prefix}icl_content_status c JOIN {$wpdb->prefix}icl_core_status n ON c.rid = n.rid WHERE c.nid = %d AND target = %s ORDER BY rid DESC LIMIT 1 ", $row->element_id, $lang), ARRAY_N); if($rid){ if($current_md5 != $md5){ $needs_update = 1; } if($status == 3){ $status = 10; }else{ $status = 2; } $service = 'icanlocalize'; foreach($sitepress_settings['icl_lang_status'] as $lpair){ if($lpair['from'] == $row->language_code && $lpair['to'] == $lang && isset($lpair['translators'][0]['id'])){ $translator_id = $lpair['translators'][0]['id']; break; } } }else{ $status = 10; $translator_id = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM {$wpdb->posts} WHERE ID=%d", $t->element_id)); $tlp = get_user_meta($translator_id, $wpdb->prefix.'language_pairs', true); $tlp[$row->language_code][$lang] = 1; $TranslationManagement->edit_translator($translator_id, $tlp); } // add translation_status record list($newrid, $update) = $TranslationManagement->update_translation_status(array( 'translation_id' => $t->translation_id, 'status' => $status, 'translator_id' => $translator_id, 'needs_update' => $needs_update, 'md5' => $md5, 'translation_service' => $service, 'translation_package' => serialize($translation_package), 'links_fixed' => intval($links_fixed) )); $job_id = $TranslationManagement->add_translation_job($newrid, $translator_id , $translation_package); if($status == 10){ $post = get_post($t->element_id); $TranslationManagement->save_job_fields_from_post($job_id, $post); } } } } if ($processing) { update_option('icl_temp_upgrade_data', array('step' => 2, 'offset' => intval($offset+100))); $stepper->setNextStep(2); } else { update_option('icl_temp_upgrade_data', array('step' => 3, 'offset' => 99999999999999999999)); } $message = $processing ? __('Processing translations...', 'sitepress') : __('Finalizing upgrade...', 'sitepress'); return array('message' => $message); break; case 3: // removing the plugins text table; importing data into a Sitepress setting $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}icl_plugins_texts"); if(!empty($results)){ foreach($results as $row){ $cft[$row->attribute_name] = $row->translate + 1; } $iclsettings['translation-management']['custom_fields_translation'] = $cft; $sitepress->save_settings($iclsettings); mysql_query("DROP TABLE {$wpdb->prefix}icl_plugins_texts"); } $iclsettings['language_selector_initialized'] = 1; if(get_option('_force_mp_post_http')){ $iclsettings['troubleshooting_options']['http_communication'] = intval(get_option('_force_mp_post_http')); delete_option('_force_mp_post_http'); } // set default translators if (isset($sitepress_settings['icl_lang_status'])) { foreach($sitepress_settings['icl_lang_status'] as $lpair){ if(!empty($lpair['translators'])){ $iclsettings['default_translators'][$lpair['from']][$lpair['to']] = array('id'=>$lpair['translators'][0]['id'], 'type'=>'icanlocalize'); } } } $sitepress->save_settings($iclsettings); $iclsettings['migrated_2_0_0'] = 1; $sitepress->save_settings($iclsettings); delete_option('icl_temp_upgrade_data'); return array('message' => __('Done', 'sitepress'), 'completed' => 1); break; default: return array('error' => __('Missing step', 'sitepress'), 'stop' => 1); } } // $iclsettings defined in upgrade.php if(empty($iclsettings['migrated_2_0_0'])){ wp_enqueue_script('icl-stepper', ICL_PLUGIN_URL . '/inc/upgrade-functions/2.0.0/stepper.js', array('jquery')); add_filter('admin_notices', 'icl_migrate_2_0_0'); add_action('icl_ajx_custom_call', 'icl_ajx_upgrade_2_0_0', 1, 2); } function icl_migrate_2_0_0() { $txt = get_option('icl_temp_upgrade_data', FALSE) ? __('Resume Upgrade Process', 'sitepress') : __('Run Upgrade Process', 'sitepress'); echo '<div class="message error" id="icl-migrate"><p><strong>'.__('WPML requires database upgrade', 'sitepress').'</strong></p>' .'<p>' . __('This normally takes a few seconds, but may last up to several minutes of very large databases.', 'sitepress') . '</p>' . '<p><a href="index.php?icl_ajx_action=wpml_upgrade_2_0_0" style="" id="icl-migrate-start">' . $txt . '</a></p>' . '<div id="icl-migrate-progress" style="display:none; margin: 10px 0 20px 0;">' . '</div></div>'; } function icl_ajx_upgrade_2_0_0($call, $request){ if($call == 'wpml_upgrade_2_0_0'){ $error = 0; $completed = 0; $stop = 0; $message = __('Starting the upgrade process...', 'sitepress'); include_once ICL_PLUGIN_PATH . '/inc/upgrade-functions/2.0.0/stepper.php'; include_once ICL_PLUGIN_PATH . '/inc/upgrade-functions/upgrade-2.0.0.php'; $temp_upgrade_data = get_option('icl_temp_upgrade_data', array('step' => 0, 'offset' => 0)); $step = isset($request['step']) ? $request['step'] : $temp_upgrade_data['step']; $migration = new Icl_Stepper($step); $migration->registerSteps( 'icl_upgrade_2_0_0_steps', 'icl_upgrade_2_0_0_steps', 'icl_upgrade_2_0_0_steps'); if (isset($request['init'])) { echo json_encode(array( 'error' => $error, 'output' => $migration->render(), 'step' => $migration->getNextStep(), 'message' => __('Creating new tables...', 'sitepress'), 'stop' => $stop, )); exit; } $data = $migration->init(); @extract($data, EXTR_OVERWRITE); echo json_encode(array( 'error' => $error, 'completed' => $completed, 'message' => $message, 'step' => $migration->getNextStep(), 'barWidth' => $migration->barWidth(), 'stop' => $stop, )); } } ?>
gpl-2.0
heqiaoliu/Viral-Dark-Matter
tmp/install_4f20918762d32/components/com_content/views/featured/view.feed.php
2641
<?php /** * @version $Id: view.feed.php 21589 2011-06-20 17:38:33Z chdemko $ * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; jimport('joomla.application.component.view'); /** * Frontpage View class * * @package Joomla.Site * @subpackage com_content * @since 1.5 */ class ContentViewFeatured extends JView { function display($tpl = null) { // parameters $app = JFactory::getApplication(); $db = JFactory::getDbo(); $document = JFactory::getDocument(); $params = $app->getParams(); $feedEmail = (@$app->getCfg('feed_email')) ? $app->getCfg('feed_email') : 'author'; $siteEmail = $app->getCfg('mailfrom'); $document->link = JRoute::_('index.php?option=com_content&view=featured'); // Get some data from the model JRequest::setVar('limit', $app->getCfg('feed_limit')); $categories = JCategories::getInstance('Content'); $rows = $this->get('Items'); foreach ($rows as $row) { // strip html from feed item title $title = $this->escape($row->title); $title = html_entity_decode($title, ENT_COMPAT, 'UTF-8'); // Compute the article slug $row->slug = $row->alias ? ($row->id . ':' . $row->alias) : $row->id; // url link to article $link = JRoute::_(ContentHelperRoute::getArticleRoute($row->slug, $row->catid)); // strip html from feed item description text // TODO: Only pull fulltext if necessary (actually, just get the necessary fields). $description = ($params->get('feed_summary', 0) ? $row->introtext/*.$row->fulltext*/ : $row->introtext); $author = $row->created_by_alias ? $row->created_by_alias : $row->author; // load individual item creator class $item = new JFeedItem(); $item->title = $title; $item->link = $link; $item->description = $description; $item->date = $row->created; $item_category = $categories->get($row->catid); $item->category = array(); $item->category[] = JText::_('JFEATURED'); // All featured articles are categorized as "Featured" for ($item_category = $categories->get($row->catid); $item_category !== null; $item_category = $item_category->getParent()) { if ($item_category->id > 1) { // Only add non-root categories $item->category[] = $item_category->title; } } $item->author = $author; if ($feedEmail == 'site') { $item->authorEmail = $siteEmail; } else { $item->authorEmail = $row->author_email; } // loads item info into rss array $document->addItem($item); } } } ?>
gpl-2.0
rrevanth/shooter-player
Thirdparty/boost/boost/local_function/detail/preprocessor/void_list.hpp
5557
// Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #ifndef BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HPP_ #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HPP_ #include <boost/local_function/detail/preprocessor/keyword/void.hpp> #include <boost/config.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/comparison/equal.hpp> #include <boost/preprocessor/tuple/to_list.hpp> #include <boost/preprocessor/seq/size.hpp> #include <boost/preprocessor/seq/to_tuple.hpp> // PRIVATE // // Argument: (token1)... #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_FROM_SEQ_(unused, seq) \ BOOST_PP_TUPLE_TO_LIST(BOOST_PP_SEQ_SIZE(seq), BOOST_PP_SEQ_TO_TUPLE(seq)) // Token: void | token1 #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HANDLE_VOID_( \ is_void_macro, token) \ BOOST_PP_IIF(is_void_macro(token), \ BOOST_PP_NIL \ , \ (token, BOOST_PP_NIL) \ ) // Token: (a)(b)... | empty | void | token #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HANDLE_SEQ_( \ is_void_macro, token) \ BOOST_PP_IIF(BOOST_PP_IS_UNARY(token), /* unary paren (a)... */ \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_FROM_SEQ_ \ , \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HANDLE_VOID_ \ )(is_void_macro, token) #ifdef BOOST_NO_VARIADIC_MACROS #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_(is_void_macro, seq) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HANDLE_SEQ_(is_void_macro, seq) #else // VARIADICS // FUTURE: Replace this with BOOST_PP_VARIADIC_SIZE when and if // BOOST_PP_VARIAIDCS detection will match !BOOST_NO_VARIADIC_MACROS (for now // Boost.Preprocessor and Boost.Config disagree on detecting compiler variadic // support while this VARIADIC_SIZE works on compilers not detected by PP). #if BOOST_MSVC # define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_(...) \ BOOST_PP_CAT(BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_I_(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,),) #else // MSVC # define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_(...) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_I_(__VA_ARGS__, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,) #endif // MSVC #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_I_(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, size, ...) size // Argument: token1, ... #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_FROM_VARIADIC_(unused, ...) \ BOOST_PP_TUPLE_TO_LIST( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_( \ __VA_ARGS__), (__VA_ARGS__)) #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_(is_void_macro, ...) \ BOOST_PP_IIF(BOOST_PP_EQUAL( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_VARIADIC_SIZE_( \ __VA_ARGS__), 1), \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_HANDLE_SEQ_ \ , \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_FROM_VARIADIC_ \ )(is_void_macro, __VA_ARGS__) #endif // VARIADICS #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_NEVER_(tokens) \ 0 /* void check always returns false */ // PUBLIC // // NOTE: Empty list must always be represented is void (which is also a way to // specify no function parameter) and it can never be empty because (1) // IS_EMPTY(&var) fails (because of the leading non alphanumeric symbol) and // (2) some compilers (MSVC) fail to correctly pass empty macro parameters // even if they support variadic macros. Therefore, always using void to // represent is more portable. #ifdef BOOST_NO_VARIADIC_MACROS // Expand `void | (a)(b)...` to pp-list `NIL | (a, (b, NIL))`. #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST(sign) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_KEYWORD_IS_VOID_BACK, sign) // Expand `(a)(b)...` to pp-list `(a, (b, NIL))`. #define BOOST_LOCAL_FUNCTION_DETAIL_PP_NON_VOID_LIST(seq) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_NEVER_, seq) #else // VARIADICS // Expand `void | (a)(b)... | a, b, ...` to pp-list `NIL | (a, (b, NIL))`. #define BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST(...) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_KEYWORD_IS_VOID_BACK, __VA_ARGS__) // Expand `(a)(b)... | a, b, ...` to pp-list `(a, (b, NIL))`. #define BOOST_LOCAL_FUNCTION_DETAIL_PP_NON_VOID_LIST(...) \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_( \ BOOST_LOCAL_FUNCTION_DETAIL_PP_VOID_LIST_NEVER_, __VA_ARGS__) #endif // VARIADICS #endif // #include guard
gpl-2.0
gombadi/aws-tools
vendor/github.com/aws/aws-sdk-go/service/firehose/examples_test.go
7404
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. package firehose_test import ( "bytes" "fmt" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/firehose" ) var _ time.Duration var _ bytes.Buffer func ExampleFirehose_CreateDeliveryStream() { svc := firehose.New(session.New()) params := &firehose.CreateDeliveryStreamInput{ DeliveryStreamName: aws.String("DeliveryStreamName"), // Required RedshiftDestinationConfiguration: &firehose.RedshiftDestinationConfiguration{ ClusterJDBCURL: aws.String("ClusterJDBCURL"), // Required CopyCommand: &firehose.CopyCommand{ // Required DataTableName: aws.String("DataTableName"), // Required CopyOptions: aws.String("CopyOptions"), DataTableColumns: aws.String("DataTableColumns"), }, Password: aws.String("Password"), // Required RoleARN: aws.String("RoleARN"), // Required S3Configuration: &firehose.S3DestinationConfiguration{ // Required BucketARN: aws.String("BucketARN"), // Required RoleARN: aws.String("RoleARN"), // Required BufferingHints: &firehose.BufferingHints{ IntervalInSeconds: aws.Int64(1), SizeInMBs: aws.Int64(1), }, CompressionFormat: aws.String("CompressionFormat"), EncryptionConfiguration: &firehose.EncryptionConfiguration{ KMSEncryptionConfig: &firehose.KMSEncryptionConfig{ AWSKMSKeyARN: aws.String("AWSKMSKeyARN"), // Required }, NoEncryptionConfig: aws.String("NoEncryptionConfig"), }, Prefix: aws.String("Prefix"), }, Username: aws.String("Username"), // Required }, S3DestinationConfiguration: &firehose.S3DestinationConfiguration{ BucketARN: aws.String("BucketARN"), // Required RoleARN: aws.String("RoleARN"), // Required BufferingHints: &firehose.BufferingHints{ IntervalInSeconds: aws.Int64(1), SizeInMBs: aws.Int64(1), }, CompressionFormat: aws.String("CompressionFormat"), EncryptionConfiguration: &firehose.EncryptionConfiguration{ KMSEncryptionConfig: &firehose.KMSEncryptionConfig{ AWSKMSKeyARN: aws.String("AWSKMSKeyARN"), // Required }, NoEncryptionConfig: aws.String("NoEncryptionConfig"), }, Prefix: aws.String("Prefix"), }, } resp, err := svc.CreateDeliveryStream(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_DeleteDeliveryStream() { svc := firehose.New(session.New()) params := &firehose.DeleteDeliveryStreamInput{ DeliveryStreamName: aws.String("DeliveryStreamName"), // Required } resp, err := svc.DeleteDeliveryStream(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_DescribeDeliveryStream() { svc := firehose.New(session.New()) params := &firehose.DescribeDeliveryStreamInput{ DeliveryStreamName: aws.String("DeliveryStreamName"), // Required ExclusiveStartDestinationId: aws.String("DestinationId"), Limit: aws.Int64(1), } resp, err := svc.DescribeDeliveryStream(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_ListDeliveryStreams() { svc := firehose.New(session.New()) params := &firehose.ListDeliveryStreamsInput{ ExclusiveStartDeliveryStreamName: aws.String("DeliveryStreamName"), Limit: aws.Int64(1), } resp, err := svc.ListDeliveryStreams(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_PutRecord() { svc := firehose.New(session.New()) params := &firehose.PutRecordInput{ DeliveryStreamName: aws.String("DeliveryStreamName"), // Required Record: &firehose.Record{ // Required Data: []byte("PAYLOAD"), // Required }, } resp, err := svc.PutRecord(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_PutRecordBatch() { svc := firehose.New(session.New()) params := &firehose.PutRecordBatchInput{ DeliveryStreamName: aws.String("DeliveryStreamName"), // Required Records: []*firehose.Record{ // Required { // Required Data: []byte("PAYLOAD"), // Required }, // More values... }, } resp, err := svc.PutRecordBatch(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) } func ExampleFirehose_UpdateDestination() { svc := firehose.New(session.New()) params := &firehose.UpdateDestinationInput{ CurrentDeliveryStreamVersionId: aws.String("DeliveryStreamVersionId"), // Required DeliveryStreamName: aws.String("DeliveryStreamName"), // Required DestinationId: aws.String("DestinationId"), // Required RedshiftDestinationUpdate: &firehose.RedshiftDestinationUpdate{ ClusterJDBCURL: aws.String("ClusterJDBCURL"), CopyCommand: &firehose.CopyCommand{ DataTableName: aws.String("DataTableName"), // Required CopyOptions: aws.String("CopyOptions"), DataTableColumns: aws.String("DataTableColumns"), }, Password: aws.String("Password"), RoleARN: aws.String("RoleARN"), S3Update: &firehose.S3DestinationUpdate{ BucketARN: aws.String("BucketARN"), BufferingHints: &firehose.BufferingHints{ IntervalInSeconds: aws.Int64(1), SizeInMBs: aws.Int64(1), }, CompressionFormat: aws.String("CompressionFormat"), EncryptionConfiguration: &firehose.EncryptionConfiguration{ KMSEncryptionConfig: &firehose.KMSEncryptionConfig{ AWSKMSKeyARN: aws.String("AWSKMSKeyARN"), // Required }, NoEncryptionConfig: aws.String("NoEncryptionConfig"), }, Prefix: aws.String("Prefix"), RoleARN: aws.String("RoleARN"), }, Username: aws.String("Username"), }, S3DestinationUpdate: &firehose.S3DestinationUpdate{ BucketARN: aws.String("BucketARN"), BufferingHints: &firehose.BufferingHints{ IntervalInSeconds: aws.Int64(1), SizeInMBs: aws.Int64(1), }, CompressionFormat: aws.String("CompressionFormat"), EncryptionConfiguration: &firehose.EncryptionConfiguration{ KMSEncryptionConfig: &firehose.KMSEncryptionConfig{ AWSKMSKeyARN: aws.String("AWSKMSKeyARN"), // Required }, NoEncryptionConfig: aws.String("NoEncryptionConfig"), }, Prefix: aws.String("Prefix"), RoleARN: aws.String("RoleARN"), }, } resp, err := svc.UpdateDestination(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
apache-2.0
ROMFactory/android_external_chromium_org
chrome/test/chromedriver/chrome/status.cc
2862
// 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/test/chromedriver/chrome/status.h" #include "base/strings/stringprintf.h" namespace { // Returns the string equivalent of the given |ErrorCode|. const char* DefaultMessageForStatusCode(StatusCode code) { switch (code) { case kOk: return "ok"; case kNoSuchSession: return "no such session"; case kNoSuchElement: return "no such element"; case kNoSuchFrame: return "no such frame"; case kUnknownCommand: return "unknown command"; case kStaleElementReference: return "stale element reference"; case kElementNotVisible: return "element not visible"; case kInvalidElementState: return "invalid element state"; case kUnknownError: return "unknown error"; case kJavaScriptError: return "javascript error"; case kXPathLookupError: return "xpath lookup error"; case kTimeout: return "timeout"; case kNoSuchWindow: return "no such window"; case kInvalidCookieDomain: return "invalid cookie domain"; case kUnexpectedAlertOpen: return "unexpected alert open"; case kNoAlertOpen: return "no alert open"; case kScriptTimeout: return "asynchronous script timeout"; case kInvalidSelector: return "invalid selector"; case kSessionNotCreatedException: return "session not created exception"; case kNoSuchExecutionContext: return "no such execution context"; case kChromeNotReachable: return "chrome not reachable"; case kDisconnected: return "disconnected"; default: return "<unknown>"; } } } // namespace Status::Status(StatusCode code) : code_(code), msg_(DefaultMessageForStatusCode(code)) {} Status::Status(StatusCode code, const std::string& details) : code_(code), msg_(DefaultMessageForStatusCode(code) + std::string(": ") + details) { } Status::Status(StatusCode code, const Status& cause) : code_(code), msg_(DefaultMessageForStatusCode(code) + std::string("\nfrom ") + cause.message()) {} Status::Status(StatusCode code, const std::string& details, const Status& cause) : code_(code), msg_(DefaultMessageForStatusCode(code) + std::string(": ") + details + "\nfrom " + cause.message()) { } Status::~Status() {} void Status::AddDetails(const std::string& details) { msg_ += base::StringPrintf("\n (%s)", details.c_str()); } bool Status::IsOk() const { return code_ == kOk; } bool Status::IsError() const { return code_ != kOk; } StatusCode Status::code() const { return code_; } const std::string& Status::message() const { return msg_; }
bsd-3-clause
mbroadst/aurelia-plunker
jspm_packages/npm/aurelia-history@1.0.0-beta.1/aurelia-history.d.ts
1301
declare module 'aurelia-history' { /** * The options that can be specified as part of a history navigation request. */ export interface NavigationOptions { /** * Replace the existing route. */ replace?: boolean; /** * Trigger the router. */ trigger?: boolean; } /** * An abstract base class for implementors of the basic history api. */ export class History { /** * Activates the history object. * * @param options The set of options to activate history with. */ activate(options: Object): boolean; /** * Deactivates the history object. */ deactivate(): void; /** * Causes a history navigation to occur. * * @param fragment The history fragment to navigate to. * @param options The set of options that specify how the navigation should occur. * @return True if navigation occurred/false otherwise. */ navigate(fragment: string, options?: NavigationOptions): boolean; /** * Causes the history state to navigate back. */ navigateBack(): void; /** * Updates the title associated with the current location. */ setTitle(title: string): void; } }
mit
sin3fu3/inkjet-conveni
data/module/Compat/tests/function/array_key_exists.phpt
407
--TEST-- Function -- array_key_exists --SKIPIF-- <?php if (function_exists('array_key_exists')) { echo 'skip'; } ?> --FILE-- <?php require_once 'PHP/Compat.php'; PHP_Compat::loadFunction('array_key_exists'); $search_array = array("first" => 1, "second" => 4); if (array_key_exists("first", $search_array)) { echo "The 'first' element is in the array"; } ?> --EXPECT-- The 'first' element is in the array
gpl-2.0
frohoff/jdk8u-jdk
src/share/classes/sun/net/www/content/image/gif.java
2101
/* * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.net.www.content.image; import java.net.*; import sun.awt.image.*; import java.io.IOException; import java.awt.Image; import java.awt.Toolkit; public class gif extends ContentHandler { public Object getContent(URLConnection urlc) throws java.io.IOException { return new URLImageSource(urlc); } @SuppressWarnings("rawtypes") public Object getContent(URLConnection urlc, Class[] classes) throws IOException { Class<?>[] cls = classes; for (int i = 0; i < cls.length; i++) { if (cls[i].isAssignableFrom(URLImageSource.class)) { return new URLImageSource(urlc); } if (cls[i].isAssignableFrom(Image.class)) { Toolkit tk = Toolkit.getDefaultToolkit(); return tk.createImage(new URLImageSource(urlc)); } } return null; } }
gpl-2.0
markllama/origin
vendor/github.com/openshift/client-go/servicecertsigner/informers/externalversions/servicecertsigner/interface.go
1107
// Code generated by informer-gen. DO NOT EDIT. package servicecertsigner import ( internalinterfaces "github.com/openshift/client-go/servicecertsigner/informers/externalversions/internalinterfaces" v1alpha1 "github.com/openshift/client-go/servicecertsigner/informers/externalversions/servicecertsigner/v1alpha1" ) // Interface provides access to each of this group's versions. type Interface interface { // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface } type group struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // V1alpha1 returns a new v1alpha1.Interface. func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) }
apache-2.0
yumingjuan/selenium
py/selenium/webdriver/remote/errorhandler.py
6364
# Copyright 2010 WebDriver committers # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from selenium.common.exceptions import ElementNotSelectableException from selenium.common.exceptions import ElementNotVisibleException from selenium.common.exceptions import InvalidCookieDomainException from selenium.common.exceptions import InvalidElementStateException from selenium.common.exceptions import InvalidSelectorException from selenium.common.exceptions import ImeNotAvailableException from selenium.common.exceptions import ImeActivationFailedException from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException from selenium.common.exceptions import NoSuchWindowException from selenium.common.exceptions import StaleElementReferenceException from selenium.common.exceptions import UnableToSetCookieException from selenium.common.exceptions import NoAlertPresentException from selenium.common.exceptions import ErrorInResponseException from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import MoveTargetOutOfBoundsException class ErrorCode(object): """ Error codes defined in the WebDriver wire protocol. """ # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = 7 NO_SUCH_FRAME = 8 UNKNOWN_COMMAND = 9 STALE_ELEMENT_REFERENCE = 10 ELEMENT_NOT_VISIBLE = 11 INVALID_ELEMENT_STATE = 12 UNKNOWN_ERROR = 13 ELEMENT_IS_NOT_SELECTABLE = 15 JAVASCRIPT_ERROR = 17 XPATH_LOOKUP_ERROR = 19 TIMEOUT = 21 NO_SUCH_WINDOW = 23 INVALID_COOKIE_DOMAIN = 24 UNABLE_TO_SET_COOKIE = 25 UNEXPECTED_ALERT_OPEN = 26 NO_ALERT_OPEN = 27 SCRIPT_TIMEOUT = 28 INVALID_ELEMENT_COORDINATES = 29 IME_NOT_AVAILABLE = 30; IME_ENGINE_ACTIVATION_FAILED = 31 INVALID_SELECTOR = 32 MOVE_TARGET_OUT_OF_BOUNDS = 34 INVALID_XPATH_SELECTOR = 51 INVALID_XPATH_SELECTOR_RETURN_TYPER = 52 METHOD_NOT_ALLOWED = 405 class ErrorHandler(object): """ Handles errors returned by the WebDriver server. """ def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ status = response['status'] if status == ErrorCode.SUCCESS: return exception_class = ErrorInResponseException if status == ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status == ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status == ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status == ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status == ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status == ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif status == ErrorCode.INVALID_SELECTOR \ or status == ErrorCode.INVALID_XPATH_SELECTOR \ or status == ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER: exception_class = InvalidSelectorException elif status == ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status == ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = WebDriverException elif status == ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = WebDriverException elif status == ErrorCode.TIMEOUT: exception_class = TimeoutException elif status == ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status == ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status == ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status == ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status == ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status == ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException else: exception_class = WebDriverException value = response['value'] if type(value) is str: if exception_class == ErrorInResponseException: raise exception_class(response, value) raise exception_class(value) message = '' if 'message' in value: message = value['message'] screen = None if 'screen' in value: screen = value['screen'] stacktrace = None if 'stackTrace' in value and value['stackTrace']: zeroeth = '' try: zeroeth = value['stackTrace'][0] except: pass if zeroeth.has_key('methodName'): stacktrace = "Method %s threw an error in %s" % \ (zeroeth['methodName'], self._value_or_default(zeroeth, 'fileName', '[No file name]')) if exception_class == ErrorInResponseException: raise exception_class(response, message) raise exception_class(message, screen, stacktrace) def _value_or_default(self, obj, key, default): return obj[key] if obj.has_key(key) else default
apache-2.0
vinay-qa/vinayit-android-server-apk
java/client/src/org/openqa/selenium/remote/AugmenterProvider.java
1192
/* Copyright 2007-2010 Selenium committers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.remote; /** * Describes and provides an implementation for a particular interface for use with the * {@link org.openqa.selenium.remote.Augmenter}. Think of this as a simulacrum of mixins. */ public interface AugmenterProvider { /** * @return The interface that this augmentor describes. */ Class<?> getDescribedInterface(); /** * For the interface that this provider describes, return an implementation. * * @param value The value from the capability map * @return An interface implementation */ InterfaceImplementation getImplementation(Object value); }
apache-2.0
jiajiechen/mxnet
tools/caffe_translator/src/main/java/io/mxnet/caffetranslator/Utils.java
1446
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file Utils.java * \brief General util functions */ package io.mxnet.caffetranslator; import java.util.Collections; public class Utils { public static String indent(String str, int level, boolean useSpaces, int numSpaces) { String prefix; if (!useSpaces) { prefix = String.join("", Collections.nCopies(level, "\t")); } else { String spaces = String.join("", Collections.nCopies(numSpaces, " ")); prefix = String.join("", Collections.nCopies(level, spaces)); } String indented = str.replaceAll("(?m)^", prefix); return indented; } }
apache-2.0
tomerf/kubernetes
staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go
7279
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package describe import ( "fmt" "strings" "github.com/spf13/cobra" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/resource" cmdutil "k8s.io/kubectl/pkg/cmd/util" "k8s.io/kubectl/pkg/describe" "k8s.io/kubectl/pkg/util/i18n" "k8s.io/kubectl/pkg/util/templates" ) var ( describeLong = templates.LongDesc(` Show details of a specific resource or group of resources Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example: $ kubectl describe TYPE NAME_PREFIX will first check for an exact match on TYPE and NAME_PREFIX. If no such resource exists, it will output details for every resource that has a name prefixed with NAME_PREFIX.`) describeExample = templates.Examples(i18n.T(` # Describe a node kubectl describe nodes kubernetes-node-emt8.c.myproject.internal # Describe a pod kubectl describe pods/nginx # Describe a pod identified by type and name in "pod.json" kubectl describe -f pod.json # Describe all pods kubectl describe pods # Describe pods by label name=myLabel kubectl describe po -l name=myLabel # Describe all pods managed by the 'frontend' replication controller (rc-created pods # get the name of the rc as a prefix in the pod the name). kubectl describe pods frontend`)) ) type DescribeOptions struct { CmdParent string Selector string Namespace string Describer func(*meta.RESTMapping) (describe.ResourceDescriber, error) NewBuilder func() *resource.Builder BuilderArgs []string EnforceNamespace bool AllNamespaces bool DescriberSettings *describe.DescriberSettings FilenameOptions *resource.FilenameOptions genericclioptions.IOStreams } func NewCmdDescribe(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command { o := &DescribeOptions{ FilenameOptions: &resource.FilenameOptions{}, DescriberSettings: &describe.DescriberSettings{ ShowEvents: true, }, CmdParent: parent, IOStreams: streams, } cmd := &cobra.Command{ Use: "describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)", DisableFlagsInUseLine: true, Short: i18n.T("Show details of a specific resource or group of resources"), Long: describeLong + "\n\n" + cmdutil.SuggestAPIResources(parent), Example: describeExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Run()) }, } usage := "containing the resource to describe" cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, usage) cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.") cmd.Flags().BoolVar(&o.DescriberSettings.ShowEvents, "show-events", o.DescriberSettings.ShowEvents, "If true, display events related to the described object.") return cmd } func (o *DescribeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var err error o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return err } if o.AllNamespaces { o.EnforceNamespace = false } if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) { return fmt.Errorf("You must specify the type of resource to describe. %s\n", cmdutil.SuggestAPIResources(o.CmdParent)) } o.BuilderArgs = args o.Describer = func(mapping *meta.RESTMapping) (describe.ResourceDescriber, error) { return describe.DescriberFn(f, mapping) } o.NewBuilder = f.NewBuilder return nil } func (o *DescribeOptions) Validate(args []string) error { return nil } func (o *DescribeOptions) Run() error { r := o.NewBuilder(). Unstructured(). ContinueOnError(). NamespaceParam(o.Namespace).DefaultNamespace().AllNamespaces(o.AllNamespaces). FilenameParam(o.EnforceNamespace, o.FilenameOptions). LabelSelectorParam(o.Selector). ResourceTypeOrNameArgs(true, o.BuilderArgs...). Flatten(). Do() err := r.Err() if err != nil { return err } allErrs := []error{} infos, err := r.Infos() if err != nil { if apierrors.IsNotFound(err) && len(o.BuilderArgs) == 2 { return o.DescribeMatchingResources(err, o.BuilderArgs[0], o.BuilderArgs[1]) } allErrs = append(allErrs, err) } errs := sets.NewString() first := true for _, info := range infos { mapping := info.ResourceMapping() describer, err := o.Describer(mapping) if err != nil { if errs.Has(err.Error()) { continue } allErrs = append(allErrs, err) errs.Insert(err.Error()) continue } s, err := describer.Describe(info.Namespace, info.Name, *o.DescriberSettings) if err != nil { if errs.Has(err.Error()) { continue } allErrs = append(allErrs, err) errs.Insert(err.Error()) continue } if first { first = false fmt.Fprint(o.Out, s) } else { fmt.Fprintf(o.Out, "\n\n%s", s) } } if len(infos) == 0 && len(allErrs) == 0 { // if we wrote no output, and had no errors, be sure we output something. if o.AllNamespaces { fmt.Fprintln(o.ErrOut, "No resources found") } else { fmt.Fprintf(o.ErrOut, "No resources found in %s namespace.\n", o.Namespace) } } return utilerrors.NewAggregate(allErrs) } func (o *DescribeOptions) DescribeMatchingResources(originalError error, resource, prefix string) error { r := o.NewBuilder(). Unstructured(). NamespaceParam(o.Namespace).DefaultNamespace(). ResourceTypeOrNameArgs(true, resource). SingleResourceType(). Flatten(). Do() mapping, err := r.ResourceMapping() if err != nil { return err } describer, err := o.Describer(mapping) if err != nil { return err } infos, err := r.Infos() if err != nil { return err } isFound := false for ix := range infos { info := infos[ix] if strings.HasPrefix(info.Name, prefix) { isFound = true s, err := describer.Describe(info.Namespace, info.Name, *o.DescriberSettings) if err != nil { return err } fmt.Fprintf(o.Out, "%s\n", s) } } if !isFound { return originalError } return nil }
apache-2.0
hambroperks/j2objc
jre_emul/stub_classes/java/lang/reflect/Method.java
2534
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.lang.reflect; import java.lang.annotation.Annotation; /** * Stub implementation of Method. The actual implementation * is in Method.h and Method.m, so the declared methods in this * class should match the actual methods implemented in order * to catch unsupported API references. * * @see Object */ public class Method extends AccessibleObject implements GenericDeclaration, Member { public String getName() { return null; } public int getModifiers() { return 0; } public Class getReturnType() { return null; } public Type getGenericReturnType() { return null; } public Class<?> getDeclaringClass() { return null; } public Class<?>[] getParameterTypes() { return null; } public Type[] getGenericParameterTypes() { return null; } public Object invoke(Object o, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { return null; } public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { return null; } public Annotation[] getDeclaredAnnotations() { return null; } public Annotation[][] getParameterAnnotations() { return null; } public TypeVariable<Method>[] getTypeParameters() { return null; } public boolean isSynthetic() { return false; } public Class[] getExceptionTypes() { return null; } public Type[] getGenericExceptionTypes() { return null; } public String toGenericString() { return null; } public boolean isBridge() { return false; } public boolean isVarArgs() { return false; } public Object getDefaultValue() { return null; } }
apache-2.0
cuheguevara/zendframework2
library/Zend/Feed/Reader/Extension/DublinCore/Feed.php
7137
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Feed */ namespace Zend\Feed\Reader\Extension\DublinCore; use DateTime; use Zend\Feed\Reader; use Zend\Feed\Reader\Collection; use Zend\Feed\Reader\Extension; /** * @category Zend * @package Zend_Feed_Reader */ class Feed extends Extension\AbstractFeed { /** * Get a single author * * @param int $index * @return string|null */ public function getAuthor($index = 0) { $authors = $this->getAuthors(); if (isset($authors[$index])) { return $authors[$index]; } return null; } /** * Get an array with feed authors * * @return array */ public function getAuthors() { if (array_key_exists('authors', $this->data)) { return $this->data['authors']; } $authors = array(); $list = $this->xpath->query('//dc11:creator'); if (!$list->length) { $list = $this->xpath->query('//dc10:creator'); } if (!$list->length) { $list = $this->xpath->query('//dc11:publisher'); if (!$list->length) { $list = $this->xpath->query('//dc10:publisher'); } } if ($list->length) { foreach ($list as $author) { $authors[] = array( 'name' => $author->nodeValue ); } $authors = new Collection\Author( Reader\Reader::arrayUnique($authors) ); } else { $authors = null; } $this->data['authors'] = $authors; return $this->data['authors']; } /** * Get the copyright entry * * @return string|null */ public function getCopyright() { if (array_key_exists('copyright', $this->data)) { return $this->data['copyright']; } $copyright = null; $copyright = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:rights)'); if (!$copyright) { $copyright = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:rights)'); } if (!$copyright) { $copyright = null; } $this->data['copyright'] = $copyright; return $this->data['copyright']; } /** * Get the feed description * * @return string|null */ public function getDescription() { if (array_key_exists('description', $this->data)) { return $this->data['description']; } $description = null; $description = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:description)'); if (!$description) { $description = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:description)'); } if (!$description) { $description = null; } $this->data['description'] = $description; return $this->data['description']; } /** * Get the feed ID * * @return string|null */ public function getId() { if (array_key_exists('id', $this->data)) { return $this->data['id']; } $id = null; $id = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:identifier)'); if (!$id) { $id = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:identifier)'); } $this->data['id'] = $id; return $this->data['id']; } /** * Get the feed language * * @return string|null */ public function getLanguage() { if (array_key_exists('language', $this->data)) { return $this->data['language']; } $language = null; $language = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:language)'); if (!$language) { $language = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:language)'); } if (!$language) { $language = null; } $this->data['language'] = $language; return $this->data['language']; } /** * Get the feed title * * @return string|null */ public function getTitle() { if (array_key_exists('title', $this->data)) { return $this->data['title']; } $title = null; $title = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:title)'); if (!$title) { $title = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:title)'); } if (!$title) { $title = null; } $this->data['title'] = $title; return $this->data['title']; } /** * * * @return DateTime|null */ public function getDate() { if (array_key_exists('date', $this->data)) { return $this->data['date']; } $d = null; $date = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc11:date)'); if (!$date) { $date = $this->xpath->evaluate('string(' . $this->getXpathPrefix() . '/dc10:date)'); } if ($date) { $d = DateTime::createFromFormat(DateTime::ISO8601, $date); } $this->data['date'] = $d; return $this->data['date']; } /** * Get categories (subjects under DC) * * @return Collection\Category */ public function getCategories() { if (array_key_exists('categories', $this->data)) { return $this->data['categories']; } $list = $this->xpath->evaluate($this->getXpathPrefix() . '//dc11:subject'); if (!$list->length) { $list = $this->xpath->evaluate($this->getXpathPrefix() . '//dc10:subject'); } if ($list->length) { $categoryCollection = new Collection\Category; foreach ($list as $category) { $categoryCollection[] = array( 'term' => $category->nodeValue, 'scheme' => null, 'label' => $category->nodeValue, ); } } else { $categoryCollection = new Collection\Category; } $this->data['categories'] = $categoryCollection; return $this->data['categories']; } /** * Register the default namespaces for the current feed format * * @return void */ protected function registerNamespaces() { $this->xpath->registerNamespace('dc10', 'http://purl.org/dc/elements/1.0/'); $this->xpath->registerNamespace('dc11', 'http://purl.org/dc/elements/1.1/'); } }
bsd-3-clause
davewalker/Symfony-Exploration
vendor/symfony/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/Bundles/Vendor/AnnotationsBundle/Entity/Test.php
301
<?php /* * This file is part of the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Fixtures\Bundles\Vendor\AnnotationsBundle\Entity; class Test { }
mit
fengnovo/webpack-react
react-redux-demo/todomvc/src/components/TodoTextInput.js
1169
import React, { Component, PropTypes } from 'react' import classnames from 'classnames' export default class TodoTextInput extends Component { static propTypes = { onSave: PropTypes.func.isRequired, text: PropTypes.string, placeholder: PropTypes.string, editing: PropTypes.bool, newTodo: PropTypes.bool } state = { text: this.props.text || '' } handleSubmit = e => { const text = e.target.value.trim() if (e.which === 13) { this.props.onSave(text) if (this.props.newTodo) { this.setState({ text: '' }) } } } handleChange = e => { this.setState({ text: e.target.value }) } handleBlur = e => { if (!this.props.newTodo) { this.props.onSave(e.target.value) } } render() { return ( <input className={ classnames({ edit: this.props.editing, 'new-todo': this.props.newTodo })} type="text" placeholder={this.props.placeholder} autoFocus="true" value={this.state.text} onBlur={this.handleBlur} onChange={this.handleChange} onKeyDown={this.handleSubmit} /> ) } }
mit
sperling/coreclr
src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
10775
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: ComEventHelpers APIs allow binding ** managed delegates to COM's connection point based events. ** **/ namespace System.Runtime.InteropServices { // // #ComEventsFeature // // code:#ComEventsFeature defines two public methods allowing to add/remove .NET delegates handling // events from COM objects. Those methods are defined as part of code:ComEventsHelper static class // * code:ComEventsHelper.Combine - will create/reuse-an-existing COM event sink and register the // specified delegate to be raised when corresponding COM event is raised // * code:ComEventsHelper.Remove // // // To bind an event handler to the COM object you need to provide the following data: // * rcw - the instance of the COM object you want to bind to // * iid - Guid of the source interface you want the sink to implement // * dispid - dispatch identifier of the event on the source interface you are interested in // * d - delegate to invoked when corresponding COM event is raised. // // #ComEventsArchitecture: // In COM world, events are handled by so-called event sinks. What these are? COM-based Object Models // (OMs) define "source" interfaces that need to be implemented by the COM clients to receive events. So, // event sinks are COM objects implementing a source interfaces. Once an event sink is passed to the COM // server (through a mechanism known as 'binding/advising to connection point'), COM server will be // calling source interface methods to "fire events" (advising, connection points, firing events etc. - // is all COM jargon). // // There are few interesting obervations about source interfaces. Usually source interfaces are defined // as 'dispinterface' - meaning that only late-bound invocations on this interface are allowed. Even // though it is not illegal to use early bound invocations on source interfaces - the practice is // discouraged because of versioning concerns. // // Notice also that each COM server object might define multiple source interfaces and hence have // multiple connection points (each CP handles exactly one source interface). COM objects that want to // fire events are required to implement IConnectionPointContainer interface which is used by the COM // clients to discovery connection poitns - objects implementing IConnectionPoint interface. Once // connection point is found - clients can bind to it using IConnectionPoint::Advise (see // code:ComEventsSink.Advise). // // The idea behind code:#ComEventsFeature is to write a "universal event sink" COM component that is // generic enough to handle all late-bound event firings and invoke corresponding COM delegates (through // reflection). // // When delegate is registered (using code:ComEventsHelper.Combine) we will verify we have corresponding // event sink created and bound. // // But what happens when COM events are fired? code:ComEventsSink.Invoke implements IDispatch::Invoke method // and this is the entry point that is called. Once our event sink is invoked, we need to find the // corresponding delegate to invoke . We need to match the dispid of the call that is coming in to a // dispid of .NET delegate that has been registered for this object. Once this is found we do call the // delegates using reflection (code:ComEventsMethod.Invoke). // // #ComEventsArgsMarshalling // Notice, that we may not have a delegate registered against every method on the source interface. If we // were to marshal all the input parameters for methods that do not reach user code - we would end up // generatic RCWs that are not reachable for user code (the inconvenience it might create is there will // be RCWs that users can not call Marshal.ReleaseComObject on to explicitly manage the lifetime of these // COM objects). The above behavior was one of the shortcoimings of legacy TLBIMP's implementation of COM // event sinking. In our code we will not marshal any data if there is no delegate registered to handle // the event. (code:ComEventsMethod.Invoke) // // #ComEventsFinalization: // Additional area of interest is when COM sink should be unadvised from the connection point. Legacy // TLBIMP's implementation of COM event sinks will unadvises the sink when corresponding RCW is GCed. // This is achieved by rooting the event sinks in a finalizable object stored in RCW's property bag // (using Marshal.SetComObjectData). Hence, once RCW is no longer reachable - the finalizer is called and // it would unadvise all the event sinks. We are employing the same strategy here. See storing an // instance in the RCW at code:ComEventsInfo.FromObject and undadvsing the sinks at // code:ComEventsInfo.~ComEventsInfo // // Classes of interest: // * code:ComEventsHelpers - defines public methods but there are also a number of internal classes that // implement the actual COM event sink: // * code:ComEventsInfo - represents a finalizable container for all event sinks for a particular RCW. // Lifetime of this instance corresponds to the lifetime of the RCW object // * code:ComEventsSink - represents a single event sink. Maintains an internal pointer to the next // instance (in a singly linked list). A collection of code:ComEventsSink is stored at // code:ComEventsInfo._sinks // * code:ComEventsMethod - represents a single method from the source interface which has .NET delegates // attached to it. Maintains an internal pointer to the next instance (in a singly linked list). A // collection of code:ComEventMethod is stored at code:ComEventsSink._methods // // #ComEventsRetValIssue: // Issue: normally, COM events would not return any value. However, it may happen as described in // http://support.microsoft.com/kb/810228. Such design might represent a problem for us - e.g. what is // the return value of a chain of delegates - is it the value of the last call in the chain or the the // first one? As the above KB article indicates, in cases where OM has events returning values, it is // suggested that people implement their event sink by explicitly implementing the source interface. This // means that the problem is already quite complex and we should not be dealing with it - see // code:ComEventsMethod.Invoke using System; using System.Runtime.Remoting; /// <summary> /// The static methods provided in ComEventsHelper allow using .NET delegates to subscribe to events /// raised COM objects. /// </summary> public static class ComEventsHelper { /// <summary> /// Adds a delegate to the invocation list of events originating from the COM object. /// </summary> /// <param name="rcw">COM object firing the events the caller would like to respond to</param> /// <param name="iid">identifier of the source interface used by COM object to fire events</param> /// <param name="dispid">dispatch identifier of the method on the source interface</param> /// <param name="d">delegate to invoke when specifed COM event is fired</param> [System.Security.SecurityCritical] public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) { rcw = UnwrapIfTransparentProxy(rcw); lock (rcw) { ComEventsInfo eventsInfo = ComEventsInfo.FromObject(rcw); ComEventsSink sink = eventsInfo.FindSink(ref iid); if (sink == null) { sink = eventsInfo.AddSink(ref iid); } ComEventsMethod method = sink.FindMethod(dispid); if (method == null) { method = sink.AddMethod(dispid); } method.AddDelegate(d); } } /// <summary> /// Removes a delegate from the invocation list of events originating from the COM object. /// </summary> /// <param name="rcw">COM object the delegate is attached to</param> /// <param name="iid">identifier of the source interface used by COM object to fire events</param> /// <param name="dispid">dispatch identifier of the method on the source interface</param> /// <param name="d">delegate to remove from the invocation list</param> /// <returns></returns> [System.Security.SecurityCritical] public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) { rcw = UnwrapIfTransparentProxy(rcw); lock (rcw) { ComEventsInfo eventsInfo = ComEventsInfo.Find(rcw); if (eventsInfo == null) return null; ComEventsSink sink = eventsInfo.FindSink(ref iid); if (sink == null) return null; ComEventsMethod method = sink.FindMethod(dispid); if (method == null) return null; method.RemoveDelegate(d); if (method.Empty) { // removed the last event handler for this dispid - need to remove dispid handler method = sink.RemoveMethod(method); } if (method == null) { // removed last dispid handler for this sink - need to remove the sink sink = eventsInfo.RemoveSink(sink); } if (sink == null) { // removed last sink for this rcw - need to remove all traces of event info Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), null); GC.SuppressFinalize(eventsInfo); } return d; } } [System.Security.SecurityCritical] internal static object UnwrapIfTransparentProxy(object rcw) { #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(rcw)) { IntPtr punk = Marshal.GetIUnknownForObject(rcw); try { rcw = Marshal.GetObjectForIUnknown(punk); } finally { Marshal.Release(punk); } } #endif return rcw; } } }
mit
vegantriathlete/mastering-drupal-8-development
core/modules/migrate/tests/src/Unit/process/DedupeEntityTest.php
7622
<?php namespace Drupal\Tests\migrate\Unit\process; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\Query\QueryInterface; use Drupal\migrate\Plugin\migrate\process\DedupeEntity; use Drupal\Component\Utility\Unicode; /** * @coversDefaultClass \Drupal\migrate\Plugin\migrate\process\DedupeEntity * @group migrate */ class DedupeEntityTest extends MigrateProcessTestCase { /** * The mock entity query. * * @var \Drupal\Core\Entity\Query\QueryInterface * @var \Drupal\Core\Entity\Query\QueryFactory */ protected $entityQuery; /** * The mocked entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $entityTypeManager; /** * The migration configuration, initialized to set the ID to test. * * @var array */ protected $migrationConfiguration = [ 'id' => 'test', ]; /** * {@inheritdoc} */ protected function setUp() { $this->entityQuery = $this->getMockBuilder('Drupal\Core\Entity\Query\QueryInterface') ->disableOriginalConstructor() ->getMock(); $this->entityTypeManager = $this->getMock(EntityTypeManagerInterface::class); $storage = $this->getMock(EntityStorageInterface::class); $storage->expects($this->any()) ->method('getQuery') ->willReturn($this->entityQuery); $this->entityTypeManager->expects($this->any()) ->method('getStorage') ->with('test_entity_type') ->willReturn($storage); parent::setUp(); } /** * Tests entity based deduplication based on providerTestDedupe() values. * * @dataProvider providerTestDedupe */ public function testDedupe($count, $postfix = '', $start = NULL, $length = NULL) { $configuration = [ 'entity_type' => 'test_entity_type', 'field' => 'test_field', ]; if ($postfix) { $configuration['postfix'] = $postfix; } $configuration['start'] = isset($start) ? $start : NULL; $configuration['length'] = isset($length) ? $length : NULL; $plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager); $this->entityQueryExpects($count); $value = $this->randomMachineName(32); $actual = $plugin->transform($value, $this->migrateExecutable, $this->row, 'testproperty'); $expected = Unicode::substr($value, $start, $length); $expected .= $count ? $postfix . $count : ''; $this->assertSame($expected, $actual); } /** * Tests that invalid start position throws an exception. */ public function testDedupeEntityInvalidStart() { $configuration = [ 'entity_type' => 'test_entity_type', 'field' => 'test_field', 'start' => 'foobar', ]; $plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager); $this->setExpectedException('Drupal\migrate\MigrateException', 'The start position configuration key should be an integer. Omit this key to capture from the beginning of the string.'); $plugin->transform('test_start', $this->migrateExecutable, $this->row, 'testproperty'); } /** * Tests that invalid length option throws an exception. */ public function testDedupeEntityInvalidLength() { $configuration = [ 'entity_type' => 'test_entity_type', 'field' => 'test_field', 'length' => 'foobar', ]; $plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager); $this->setExpectedException('Drupal\migrate\MigrateException', 'The character length configuration key should be an integer. Omit this key to capture the entire string.'); $plugin->transform('test_length', $this->migrateExecutable, $this->row, 'testproperty'); } /** * Data provider for testDedupe(). */ public function providerTestDedupe() { return [ // Tests no duplication. [0], // Tests no duplication and start position. [0, NULL, 10], // Tests no duplication, start position, and length. [0, NULL, 5, 10], // Tests no duplication and length. [0, NULL, NULL, 10], // Tests duplication. [3], // Tests duplication and start position. [3, NULL, 10], // Tests duplication, start position, and length. [3, NULL, 5, 10], // Tests duplication and length. [3, NULL, NULL, 10], // Tests no duplication and postfix. [0, '_'], // Tests no duplication, postfix, and start position. [0, '_', 5], // Tests no duplication, postfix, start position, and length. [0, '_', 5, 10], // Tests no duplication, postfix, and length. [0, '_', NULL, 10], // Tests duplication and postfix. [2, '_'], // Tests duplication, postfix, and start position. [2, '_', 5], // Tests duplication, postfix, start position, and length. [2, '_', 5, 10], // Tests duplication, postfix, and length. [2, '_', NULL, 10], ]; } /** * Helper function to add expectations to the mock entity query object. * * @param int $count * The number of deduplications to be set up. */ protected function entityQueryExpects($count) { $this->entityQuery->expects($this->exactly($count + 1)) ->method('condition') ->will($this->returnValue($this->entityQuery)); $this->entityQuery->expects($this->exactly($count + 1)) ->method('count') ->will($this->returnValue($this->entityQuery)); $this->entityQuery->expects($this->exactly($count + 1)) ->method('execute') ->will($this->returnCallback(function () use (&$count) { return $count--;})); } /** * Test deduplicating only migrated entities. */ public function testDedupeMigrated() { $configuration = [ 'entity_type' => 'test_entity_type', 'field' => 'test_field', 'migrated' => TRUE, ]; $plugin = new DedupeEntity($configuration, 'dedupe_entity', [], $this->getMigration(), $this->entityTypeManager); // Setup the entityQuery used in DedupeEntity::exists. The map, $map, is // an array consisting of the four input parameters to the query condition // method and then the query to return. Both 'forum' and // 'test_vocab' are existing entities. There is no 'test_vocab1'. $map = []; foreach (['forums', 'test_vocab', 'test_vocab1'] as $id) { $query = $this->prophesize(QueryInterface::class); $query->willBeConstructedWith([]); $query->execute()->willReturn($id === 'test_vocab1' ? [] : [$id]); $map[] = ['test_field', $id, NULL, NULL, $query->reveal()]; } $this->entityQuery ->method('condition') ->will($this->returnValueMap($map)); // Entity 'forums' is pre-existing, entity 'test_vocab' was migrated. $this->idMap ->method('lookupSourceID') ->will($this->returnValueMap([ [['test_field' => 'forums'], FALSE], [['test_field' => 'test_vocab'], ['source_id' => 42]], ])); // Existing entity 'forums' was not migrated, it should not be deduplicated. $actual = $plugin->transform('forums', $this->migrateExecutable, $this->row, 'testproperty'); $this->assertEquals('forums', $actual, 'Pre-existing name is re-used'); // Entity 'test_vocab' was migrated, should be deduplicated. $actual = $plugin->transform('test_vocab', $this->migrateExecutable, $this->row, 'testproperty'); $this->assertEquals('test_vocab1', $actual, 'Migrated name is deduplicated'); } }
gpl-2.0
Mileto/NiuShard
Scripts/Services/Virtues/VirtueGump.cs
6066
using System; using System.Collections; using Server.Gumps; using Server.Network; namespace Server { public delegate void OnVirtueUsed(Mobile from); public class VirtueGump : Gump { private static readonly Hashtable m_Callbacks = new Hashtable(); private static readonly int[] m_Table = new int[24] { 0x0481, 0x0963, 0x0965, 0x060A, 0x060F, 0x002A, 0x08A4, 0x08A7, 0x0034, 0x0965, 0x08FD, 0x0480, 0x00EA, 0x0845, 0x0020, 0x0011, 0x0269, 0x013D, 0x08A1, 0x08A3, 0x0042, 0x0543, 0x0547, 0x0061 }; private readonly Mobile m_Beholder; private readonly Mobile m_Beheld; public VirtueGump(Mobile beholder, Mobile beheld) : base(0, 0) { this.m_Beholder = beholder; this.m_Beheld = beheld; this.Serial = beheld.Serial; this.AddPage(0); this.AddImage(30, 40, 104); this.AddPage(1); this.Add(new InternalEntry(61, 71, 108, this.GetHueFor(0))); // Humility this.Add(new InternalEntry(123, 46, 112, this.GetHueFor(4))); // Valor this.Add(new InternalEntry(187, 70, 107, this.GetHueFor(5))); // Honor this.Add(new InternalEntry(35, 135, 110, this.GetHueFor(1))); // Sacrifice this.Add(new InternalEntry(211, 133, 105, this.GetHueFor(2))); // Compassion this.Add(new InternalEntry(61, 195, 111, this.GetHueFor(3))); // Spiritulaity this.Add(new InternalEntry(186, 195, 109, this.GetHueFor(6))); // Justice this.Add(new InternalEntry(121, 221, 106, this.GetHueFor(7))); // Honesty if (this.m_Beholder == this.m_Beheld) { this.AddButton(57, 269, 2027, 2027, 1, GumpButtonType.Reply, 0); this.AddButton(186, 269, 2071, 2071, 2, GumpButtonType.Reply, 0); } } public static void Initialize() { EventSink.VirtueGumpRequest += new VirtueGumpRequestEventHandler(EventSink_VirtueGumpRequest); EventSink.VirtueItemRequest += new VirtueItemRequestEventHandler(EventSink_VirtueItemRequest); EventSink.VirtueMacroRequest += new VirtueMacroRequestEventHandler(EventSink_VirtueMacroRequest); } public static void Register(int gumpID, OnVirtueUsed callback) { m_Callbacks[gumpID] = callback; } public override void OnResponse(NetState state, RelayInfo info) { if (info.ButtonID == 1 && this.m_Beholder == this.m_Beheld) this.m_Beholder.SendGump(new VirtueStatusGump(this.m_Beholder)); } private static void EventSink_VirtueItemRequest(VirtueItemRequestEventArgs e) { if (e.Beholder != e.Beheld) return; e.Beholder.CloseGump(typeof(VirtueGump)); if (e.Beholder.Kills >= 5) { e.Beholder.SendLocalizedMessage(1049609); // Murderers cannot invoke this virtue. return; } OnVirtueUsed callback = (OnVirtueUsed)m_Callbacks[e.GumpID]; if (callback != null) callback(e.Beholder); else e.Beholder.SendLocalizedMessage(1052066); // That virtue is not active yet. } private static void EventSink_VirtueMacroRequest(VirtueMacroRequestEventArgs e) { int virtueID = 0; switch ( e.VirtueID ) { case 0: // Honor virtueID = 107; break; case 1: // Sacrifice virtueID = 110; break; case 2: // Valor; virtueID = 112; break; } EventSink_VirtueItemRequest(new VirtueItemRequestEventArgs(e.Mobile, e.Mobile, virtueID)); } private static void EventSink_VirtueGumpRequest(VirtueGumpRequestEventArgs e) { Mobile beholder = e.Beholder; Mobile beheld = e.Beheld; if (beholder == beheld && beholder.Kills >= 5) { beholder.SendLocalizedMessage(1049609); // Murderers cannot invoke this virtue. } else if (beholder.Map == beheld.Map && beholder.InRange(beheld, 12)) { beholder.CloseGump(typeof(VirtueGump)); beholder.SendGump(new VirtueGump(beholder, beheld)); } } private int GetHueFor(int index) { if (this.m_Beheld.Virtues.GetValue(index) == 0) return 2402; int value = this.m_Beheld.Virtues.GetValue(index); if (value < 4000) return 2402; if (value >= 30000) value = 20000; //Sanity int vl; if (value < 10000) vl = 0; else if (value >= 20000 && index == 5) vl = 2; else if (value >= 21000 && index != 1) vl = 2; else if (value >= 22000 && index == 1) vl = 2; else vl = 1; return m_Table[(index * 3) + (int)vl]; } private class InternalEntry : GumpImage { private static readonly byte[] m_Class = Gump.StringToBuffer(" class=VirtueGumpItem"); public InternalEntry(int x, int y, int gumpID, int hue) : base(x, y, gumpID, hue) { } public override string Compile() { return String.Format("{{ gumppic {0} {1} {2} hue={3} class=VirtueGumpItem }}", this.X, this.Y, this.GumpID, this.Hue); } public override void AppendTo(IGumpWriter disp) { base.AppendTo(disp); disp.AppendLayout(m_Class); } } } }
gpl-2.0
aakb/replicator
sites/all/modules/contrib/jquery_ui/jquery.ui/tests/unit/datepicker/datepicker_tickets.js
464
/* * datepicker_tickets.js */ (function($) { module("datepicker: tickets"); test('#4055: onclick events contain references to "jQuery"', function() { // no assertions, if the test fails, there will be an error var _jQuery = jQuery; jQuery = null; $('<div/>').appendTo('body').datepicker() // the third weekend day always exists .find('tbody .ui-datepicker-week-end:eq(3)').click().end() .datepicker('destroy'); jQuery = _jQuery; }); })(jQuery);
gpl-2.0
skywalker00/sabermod_rom_toolchain
libstdc++-v3/testsuite/26_numerics/random/subtract_with_carry_engine/operators/equal.cc
1380
// { dg-options "-std=c++0x" } // { dg-require-cstdint "" } // // 2008-11-24 Edward M. Smith-Rowland <3dw4rd@verizon.net> // // Copyright (C) 2008-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 26.4.3.3 Class template subtract_with_carry_engine [rand.eng.sub] // 26.4.2.2 Concept RandomNumberEngine [rand.concept.eng] #include <random> #include <testsuite_hooks.h> void test01() { bool test __attribute__((unused)) = true; std::subtract_with_carry_engine<unsigned long, 24, 10, 24> u; std::subtract_with_carry_engine<unsigned long, 24, 10, 24> v; VERIFY( u == v ); u.discard(100); v.discard(100); VERIFY( u == v ); } int main() { test01(); return 0; }
gpl-2.0
JennyCumming/blog
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint/AllowedValuesConstraintValidator.php
3859
<?php namespace Drupal\Core\Validation\Plugin\Validation\Constraint; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\TypedData\OptionsProviderInterface; use Drupal\Core\TypedData\ComplexDataInterface; use Drupal\Core\TypedData\PrimitiveInterface; use Drupal\Core\TypedData\Validation\TypedDataAwareValidatorTrait; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\ChoiceValidator; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; /** * Validates the AllowedValues constraint. */ class AllowedValuesConstraintValidator extends ChoiceValidator implements ContainerInjectionInterface { use TypedDataAwareValidatorTrait; /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $currentUser; /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static($container->get('current_user')); } /** * Constructs a new AllowedValuesConstraintValidator. * * @param \Drupal\Core\Session\AccountInterface $current_user * The current user. */ public function __construct(AccountInterface $current_user) { $this->currentUser = $current_user; } /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { $typed_data = $this->getTypedData(); if ($typed_data instanceof OptionsProviderInterface) { $allowed_values = $typed_data->getSettableValues($this->currentUser); $constraint->choices = $allowed_values; // If the data is complex, we have to validate its main property. if ($typed_data instanceof ComplexDataInterface) { $name = $typed_data->getDataDefinition()->getMainPropertyName(); if (!isset($name)) { throw new \LogicException('Cannot validate allowed values for complex data without a main property.'); } $typed_data = $typed_data->get($name); $value = $typed_data->getValue(); } } // The parent implementation ignores values that are not set, but makes // sure some choices are available firstly. However, we want to support // empty choices for undefined values; for instance, if a term reference // field points to an empty vocabulary. if (!isset($value)) { return; } // Get the value with the proper datatype in order to make strict // comparisons using in_array(). if (!($typed_data instanceof PrimitiveInterface)) { throw new \LogicException('The data type must be a PrimitiveInterface at this point.'); } $value = $typed_data->getCastedValue(); // In a better world where typed data just returns typed values, we could // set a constraint callback to use the OptionsProviderInterface. // This is not possible right now though because we do the typecasting // further down. if ($constraint->callback) { if (!\is_callable($choices = [$this->context->getObject(), $constraint->callback]) && !\is_callable($choices = [$this->context->getClassName(), $constraint->callback]) && !\is_callable($choices = $constraint->callback) ) { throw new ConstraintDefinitionException('The AllowedValuesConstraint constraint expects a valid callback'); } $allowed_values = \call_user_func($choices); $constraint->choices = $allowed_values; // parent::validate() does not need to invoke the callback again. $constraint->callback = NULL; } // Force the choices to be the same type as the value. $type = gettype($value); foreach ($constraint->choices as &$choice) { settype($choice, $type); } parent::validate($value, $constraint); } }
gpl-2.0
greasydeal/darkstar
src/common/zlib.cpp
3485
#include "../common/zlib.h" #include "../common/showmsg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> uint32 zlib_compress_table[512]; uintptr zlib_decompress_table[2556]; int32 zlib_init() { memset(zlib_compress_table, 0, sizeof(zlib_compress_table)); memset(zlib_decompress_table, 0, sizeof(zlib_decompress_table)); auto fp = fopen("compress.dat", "rb"); if (fp == NULL) ShowFatalError("zlib_init: can't open file <compress.dat> \n"); fread(zlib_compress_table, sizeof(uint32), 512, fp); fclose(fp); uint32 temp_decompress_table[2556]; fp = fopen("decompress.dat", "rb"); if (fp == NULL) ShowFatalError("zlib_init: can't open file <decompress.dat> \n"); fseek(fp, 0, SEEK_END); auto size = ftell(fp); fseek(fp, 0, SEEK_SET); fread(temp_decompress_table, sizeof(char), size, fp); fclose(fp); // Align the jump table with our internal table.. for (auto x = 0; x < size / 4; x++) { if (temp_decompress_table[x] > 0xff) zlib_decompress_table[x] = (uintptr)((uintptr*)zlib_decompress_table + ((temp_decompress_table[x] - 0x15b3aaa0) / 4)); else zlib_decompress_table[x] = temp_decompress_table[x]; } return 0; } int32 zlib_compress_sub(char * output, uint32 var1, uint32 cume, char * lookup1, uint32 var2, uint32 var3, uint32 lookup2) { if ((cume + lookup2 + 7) / 8 > var1) return -1; var1 = lookup2 + var3; if ((var1 + 7) / 8 > var2) { return -1; } else if (var3 < var1) { lookup2 = cume - var3; for (; var3 < var1; var3++) output[(lookup2 + var3) / 8] = ((~(1 << ((lookup2 + var3) & 7)))&output[(lookup2 + var3) / 8]) + (((lookup1[var3 / 8] >> (var3 & 7)) & 1) << ((lookup2 + var3) & 7)); } return 0; } int32 zlib_compress(char * input, uint32 var1, char * output, uint32 var2, uint32 * lookup) { uint32 i, cume = 0, tmp; uint32 * ptr; tmp = (var2 - 1) * 8; for (i = 0; i < var1 && var1; i++) { if (lookup[input[i] + 384] + cume < tmp) { ptr = lookup + input[i] + 128; zlib_compress_sub(output + 1, var2 - 1, cume, (char *)ptr, 4, 0, lookup[input[i] + 384]); cume += lookup[input[i] + 384]; } else if (var1 + 1 >= var2) { memset(output, 0, (var2 / 4) + (var2 & 3)); memset(output + 1, var1, var1 / 4); memset(output + 1 + var1 / 4, (var1 + 1) * 8, var1 & 3); return var1; } else return -1; } output[0] = 1; return (cume + 8); } uint32 zlib_decompress(char *in, uint32 inSize, char *out, uint32 outSize, uintptr *table) { uintptr* follow = (uintptr*)table[0]; uint32 i, j = 0; if (in[0] != 1) return -1; in++; for (i = 0; i < inSize; i++) { if ((in[i / 8] >> (i & 7)) & 1) follow = (uintptr*)follow[1]; else follow = (uintptr*)follow[0]; if (follow[0] == 0) { if (follow[1] == 0) { void *ptr = (void*)follow[3]; out[j] = (uintptr)(ptr)& 255; if (++j >= outSize) return -1; follow = (uintptr*)table[0]; } } } return j; }
gpl-3.0
heqichen/ardublock
src/main/java/com/ardublock/translator/block/WireIsReadBlock.java
479
package com.ardublock.translator.block; import com.ardublock.translator.Translator; public class WireIsReadBlock extends TranslatorBlock { public WireIsReadBlock(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) { super(blockId, translator, codePrefix, codeSuffix, label); } @Override public String toCode() { WireReadBlock.setupWireEnvironment(translator); return codePrefix + " __ardublockIsI2cReadOk " + codeSuffix; } }
gpl-3.0
purplecabbage/cordova-lib
spec/cordova/fixtures/projWithHooks/.cordova/hooks/before_build/hookScriptDot1.js
165
#!/usr/bin/env node var path = require('path'); var orderLogger = require(path.join(process.argv.slice(2)[0], 'scripts', 'orderLogger')); orderLogger.logOrder('02');
apache-2.0
abaranau/hbase
src/main/java/org/apache/hadoop/hbase/util/HBaseConfTool.java
1409
/* * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.util; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; /** * Tool that prints out a configuration. * Pass the configuration key on the command-line. */ public class HBaseConfTool { public static void main(String args[]) { if (args.length < 1) { System.err.println("Usage: HBaseConfTool <CONFIGURATION_KEY>"); System.exit(1); return; } Configuration conf = HBaseConfiguration.create(); System.out.println(conf.get(args[0])); } }
apache-2.0
pranavraman/elasticsearch
core/src/test/java/org/elasticsearch/transport/NettySizeHeaderFrameDecoderTests.java
4577
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.transport; import java.nio.charset.StandardCharsets; import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.node.settings.NodeSettingsService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.common.util.MockBigArrays; import org.elasticsearch.cache.recycler.MockPageCacheRecycler; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.netty.NettyTransport; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.Socket; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.Matchers.is; /** * This test checks, if a HTTP look-alike request (starting with a HTTP method and a space) * actually returns text response instead of just dropping the connection */ public class NettySizeHeaderFrameDecoderTests extends ESTestCase { private final Settings settings = settingsBuilder().put("name", "foo").put("transport.host", "127.0.0.1").build(); private ThreadPool threadPool; private NettyTransport nettyTransport; private int port; private InetAddress host; @Before public void startThreadPool() { threadPool = new ThreadPool(settings); threadPool.setNodeSettingsService(new NodeSettingsService(settings)); NetworkService networkService = new NetworkService(settings); BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(settings, threadPool), new NoneCircuitBreakerService()); nettyTransport = new NettyTransport(settings, threadPool, networkService, bigArrays, Version.CURRENT, new NamedWriteableRegistry()); nettyTransport.start(); TransportService transportService = new TransportService(nettyTransport, threadPool); nettyTransport.transportServiceAdapter(transportService.createAdapter()); InetSocketTransportAddress transportAddress = (InetSocketTransportAddress) nettyTransport.boundAddress().boundAddress(); port = transportAddress.address().getPort(); host = transportAddress.address().getAddress(); } @After public void terminateThreadPool() throws InterruptedException { nettyTransport.stop(); terminate(threadPool); } @Test public void testThatTextMessageIsReturnedOnHTTPLikeRequest() throws Exception { String randomMethod = randomFrom("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"); String data = randomMethod + " / HTTP/1.1"; try (Socket socket = new Socket(host, port)) { socket.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) { assertThat(reader.readLine(), is("This is not a HTTP port")); } } } @Test public void testThatNothingIsReturnedForOtherInvalidPackets() throws Exception { try (Socket socket = new Socket(host, port)) { socket.getOutputStream().write("FOOBAR".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); // end of stream assertThat(socket.getInputStream().read(), is(-1)); } } }
apache-2.0
ern/elasticsearch
server/src/test/java/org/elasticsearch/bootstrap/JNANativesTests.java
1179
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.bootstrap; import org.apache.lucene.util.Constants; import org.elasticsearch.test.ESTestCase; import static org.hamcrest.Matchers.equalTo; public class JNANativesTests extends ESTestCase { public void testMlockall() { if (Constants.MAC_OS_X) { assertFalse("Memory locking is not available on OS X platforms", JNANatives.LOCAL_MLOCKALL); } } public void testConsoleCtrlHandler() { if (Constants.WINDOWS) { assertNotNull(JNAKernel32Library.getInstance()); assertThat(JNAKernel32Library.getInstance().getCallbacks().size(), equalTo(1)); } else { assertNotNull(JNAKernel32Library.getInstance()); assertThat(JNAKernel32Library.getInstance().getCallbacks().size(), equalTo(0)); } } }
apache-2.0
lan666as/LineBotTemplate
vendor/github.com/line/line-bot-sdk-go/linebot/template.go
6615
// Copyright 2016 LINE Corporation // // LINE Corporation licenses this file to you under the Apache License, // version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package linebot import ( "encoding/json" ) // TemplateType type type TemplateType string // TemplateType constants const ( TemplateTypeButtons TemplateType = "buttons" TemplateTypeConfirm TemplateType = "confirm" TemplateTypeCarousel TemplateType = "carousel" ) // TemplateActionType type type TemplateActionType string // TemplateActionType constants const ( TemplateActionTypeURI TemplateActionType = "uri" TemplateActionTypeMessage TemplateActionType = "message" TemplateActionTypePostback TemplateActionType = "postback" ) // Template interface type Template interface { json.Marshaler template() } // ButtonsTemplate type type ButtonsTemplate struct { ThumbnailImageURL string Title string Text string Actions []TemplateAction } // MarshalJSON method of ButtonsTemplate func (t *ButtonsTemplate) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateType `json:"type"` ThumbnailImageURL string `json:"thumbnailImageUrl,omitempty"` Title string `json:"title,omitempty"` Text string `json:"text"` Actions []TemplateAction `json:"actions"` }{ Type: TemplateTypeButtons, ThumbnailImageURL: t.ThumbnailImageURL, Title: t.Title, Text: t.Text, Actions: t.Actions, }) } // ConfirmTemplate type type ConfirmTemplate struct { Text string Actions []TemplateAction } // MarshalJSON method of ConfirmTemplate func (t *ConfirmTemplate) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateType `json:"type"` Text string `json:"text"` Actions []TemplateAction `json:"actions"` }{ Type: TemplateTypeConfirm, Text: t.Text, Actions: t.Actions, }) } // CarouselTemplate type type CarouselTemplate struct { Columns []*CarouselColumn } // CarouselColumn type type CarouselColumn struct { ThumbnailImageURL string `json:"thumbnailImageUrl,omitempty"` Title string `json:"title,omitempty"` Text string `json:"text"` Actions []TemplateAction `json:"actions"` } // MarshalJSON method of CarouselTemplate func (t *CarouselTemplate) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateType `json:"type"` Columns []*CarouselColumn `json:"columns"` }{ Type: TemplateTypeCarousel, Columns: t.Columns, }) } // implements Template interface func (*ConfirmTemplate) template() {} func (*ButtonsTemplate) template() {} func (*CarouselTemplate) template() {} // NewConfirmTemplate function func NewConfirmTemplate(text string, left, right TemplateAction) *ConfirmTemplate { return &ConfirmTemplate{ Text: text, Actions: []TemplateAction{left, right}, } } // NewButtonsTemplate function // `thumbnailImageURL` and `title` are optional. they can be empty. func NewButtonsTemplate(thumbnailImageURL, title, text string, actions ...TemplateAction) *ButtonsTemplate { return &ButtonsTemplate{ ThumbnailImageURL: thumbnailImageURL, Title: title, Text: text, Actions: actions, } } // NewCarouselTemplate function func NewCarouselTemplate(columns ...*CarouselColumn) *CarouselTemplate { return &CarouselTemplate{ Columns: columns, } } // NewCarouselColumn function // `thumbnailImageURL` and `title` are optional. they can be empty. func NewCarouselColumn(thumbnailImageURL, title, text string, actions ...TemplateAction) *CarouselColumn { return &CarouselColumn{ ThumbnailImageURL: thumbnailImageURL, Title: title, Text: text, Actions: actions, } } // TemplateAction interface type TemplateAction interface { json.Marshaler templateAction() } // URITemplateAction type type URITemplateAction struct { Label string URI string } // MarshalJSON method of URITemplateAction func (a *URITemplateAction) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateActionType `json:"type"` Label string `json:"label"` URI string `json:"uri"` }{ Type: TemplateActionTypeURI, Label: a.Label, URI: a.URI, }) } // MessageTemplateAction type type MessageTemplateAction struct { Label string Text string } // MarshalJSON method of MessageTemplateAction func (a *MessageTemplateAction) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateActionType `json:"type"` Label string `json:"label"` Text string `json:"text"` }{ Type: TemplateActionTypeMessage, Label: a.Label, Text: a.Text, }) } // PostbackTemplateAction type type PostbackTemplateAction struct { Label string Data string Text string } // MarshalJSON method of PostbackTemplateAction func (a *PostbackTemplateAction) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Type TemplateActionType `json:"type"` Label string `json:"label"` Data string `json:"data"` Text string `json:"text,omitempty"` }{ Type: TemplateActionTypePostback, Label: a.Label, Data: a.Data, Text: a.Text, }) } // implements TemplateAction interface func (*URITemplateAction) templateAction() {} func (*MessageTemplateAction) templateAction() {} func (*PostbackTemplateAction) templateAction() {} // NewURITemplateAction function func NewURITemplateAction(label, uri string) *URITemplateAction { return &URITemplateAction{ Label: label, URI: uri, } } // NewMessageTemplateAction function func NewMessageTemplateAction(label, text string) *MessageTemplateAction { return &MessageTemplateAction{ Label: label, Text: text, } } // NewPostbackTemplateAction function func NewPostbackTemplateAction(label, data, text string) *PostbackTemplateAction { return &PostbackTemplateAction{ Label: label, Data: data, Text: text, } }
apache-2.0
pagekit/pagekit
app/modules/kernel/src/Event/ResponseListener.php
1025
<?php namespace Pagekit\Kernel\Event; use Pagekit\Event\EventSubscriberInterface; /** * @author Fabien Potencier <fabien@symfony.com> * @copyright Copyright (c) 2004-2015 Fabien Potencier */ class ResponseListener implements EventSubscriberInterface { /** * @var string */ protected $charset; /** * Constructor. * * @param string $charset */ public function __construct($charset = 'UTF-8') { $this->charset = $charset; } /** * Filters the Response. * * @param $event * @param $request * @param $response */ public function onResponse($event, $request, $response) { if (!$event->isMasterRequest()) { return; } if ($response->getCharset() === null) { $response->setCharset($this->charset); } $response->prepare($request); } public function subscribe() { return [ 'response' => ['onResponse', -10] ]; } }
mit
Jascen/UOSmart
Scripts/Services/XmlSpawner/XMLSpawner Extras/XmlCustomAttacks/TestCustomWeapon.cs
1548
using System; using Server; using Server.Engines.XmlSpawner2; namespace Server.Items { public class TestCustomWeapon : Katana { [Constructable] public TestCustomWeapon() { Name = "Test weapon"; switch(Utility.Random(3)) { case 0: // add a custom attack attachment with 3 random attacks XmlAttach.AttachTo(this, new XmlCustomAttacks( "random", 3)); break; case 1: // add a named custom attack attachment XmlAttach.AttachTo(this, new XmlCustomAttacks( "tartan")); break; case 2: // add a specific list of custom attacks like this XmlAttach.AttachTo(this, new XmlCustomAttacks( new XmlCustomAttacks.SpecialAttacks [] { XmlCustomAttacks.SpecialAttacks.MindDrain, XmlCustomAttacks.SpecialAttacks.StamDrain } ) ); break; } } public TestCustomWeapon( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
gpl-2.0
naderman/pflow
lib/ezc/trunk/ConsoleTools/docs/tutorial_example_08_statusbar.php
656
<?php require_once 'tutorial_autoload.php'; $output = new ezcConsoleOutput(); $output->formats->success->color = 'green'; $output->formats->failure->color = 'red'; $options = array( 'successChar' => $output->formatText( '+', 'success' ), 'failureChar' => $output->formatText( '-', 'failure' ), ); $status = new ezcConsoleStatusbar( $output, $options ); for ( $i = 0; $i < 120; $i++ ) { $nextStatus = ( bool )mt_rand( 0,1 ); $status->add( $nextStatus ); usleep( mt_rand( 200, 2000 ) ); } $output->outputLine(); $output->outputLine( 'Successes: ' . $status->getSuccessCount() . ', Failures: ' . $status->getFailureCount() ); ?>
gpl-3.0
BackupGGCode/propgcc
gcc/gcc/testsuite/go.test/test/fixedbugs/bug239.go
414
// $G $D/$F.go || echo BUG: bug239 // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Test case for issue 475. This file should compile. package main import . "unsafe" func main() { var x int println(Sizeof(x)) } /* bug239.go:11: imported and not used: unsafe bug239.go:15: undefined: Sizeof */
gpl-3.0
shidao-fm/canvas-lms
app/controllers/course_audit_api_controller.rb
7542
# # Copyright (C) 2014 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # # @API Course Audit log # # Query audit log of course events. # # Only available if the server has configured audit logs; will return 404 Not # Found response otherwise. # # For each endpoint, a compound document is returned. The primary collection of # event objects is paginated, ordered by date descending. Secondary collections # of courses, users and page_views related to the returned events # are also included. # # The event data for `ConcludedEventData`, `UnconcludedEventData`, `PublishedEventData`, # `UnpublishedEventData`, `DeletedEventData`, `RestoredEventData`, `ResetFromEventData`, # `ResetToEventData`, `CopiedFromEventData`, and `CopiedToEventData` objects will # return a empty objects as these do not have any additional log data associated. # # @model CourseEventLink # { # "id": "CourseEventLink", # "description": "", # "properties": { # "course": { # "description": "ID of the course for the event.", # "example": 12345, # "type": "integer" # }, # "user": { # "description": "ID of the user for the event (who made the change).", # "example": 12345, # "type": "integer" # }, # "page_view": { # "description": "ID of the page view during the event if it exists.", # "example": "e2b76430-27a5-0131-3ca1-48e0eb13f29b", # "type": "string" # }, # "copied_from": { # "description": "ID of the course that this course was copied from. This is only included if the event_type is copied_from.", # "example": 12345, # "type": "integer" # }, # "copied_to": { # "description": "ID of the course that this course was copied to. This is only included if the event_type is copied_to.", # "example": 12345, # "type": "integer" # }, # "sis_batch": { # "description": "ID of the SIS batch that triggered the event.", # "example": 12345, # "type": "integer" # } # } # } # # @model CourseEvent # { # "id": "CourseEvent", # "description": "", # "properties": { # "id": { # "description": "ID of the event.", # "example": "e2b76430-27a5-0131-3ca1-48e0eb13f29b", # "type": "string" # }, # "created_at": { # "description": "timestamp of the event", # "example": "2012-07-19T15:00:00-06:00", # "type": "datetime" # }, # "event_type": { # "description": "Course event type The event type defines the type and schema of the event_data object.", # "example": "updated", # "type": "string" # }, # "event_data": { # "description": "Course event data depending on the event type. This will return an object containing the relevant event data. An updated event type will return an UpdatedEventData object.", # "example": "{}", # "type": "string" # }, # "event_source": { # "description": "Course event source depending on the event type. This will return a string containing the source of the event.", # "example": "manual|sis|api", # "type": "string" # }, # "links": { # "description": "Jsonapi.org links", # "example": "{\"course\"=>\"12345\", \"user\"=>\"12345\", \"page_view\"=>\"e2b76430-27a5-0131-3ca1-48e0eb13f29b\"}", # "$ref": "CourseEventLink" # } # } # } # # @model CreatedEventData # { # "id": "CreatedEventData", # "description": "The created event data object returns all the fields that were set in the format of the following example. If a field does not exist it was not set. The value of each field changed is in the format of [:old_value, :new_value]. The created event type also includes a created_source field to specify what triggered the creation of the course.", # "properties": { # "name": { # "example": "[nil, \"Course 1\"]", # "type": "array", # "items": { "type": "string" } # }, # "start_at": { # "example": "[nil, \"2012-01-19T15:00:00-06:00\"]", # "type": "array", # "items": { "type": "datetime" } # }, # "conclude_at": { # "example": "[nil, \"2012-01-19T15:00:00-08:00\"]", # "type": "array", # "items": { "type": "datetime" } # }, # "is_public": { # "example": "[nil, false]", # "type": "array", # "items": { "type": "boolean" } # }, # "created_source": "manual|sis|api" # } # } # # @model UpdatedEventData # { # "id": "UpdatedEventData", # "description": "The updated event data object returns all the fields that have changed in the format of the following example. If a field does not exist it was not changed. The value is an array that contains the before and after values for the change as in [:old_value, :new_value].", # "properties": { # "name": { # "example": "[\"Course 1\", \"Course 2\"]", # "type": "array", # "items": { "type": "string" } # }, # "start_at": { # "example": "[\"2012-01-19T15:00:00-06:00\", \"2012-07-19T15:00:00-06:00\"]", # "type": "array", # "items": { "type": "datetime" } # }, # "conclude_at": { # "example": "[\"2012-01-19T15:00:00-08:00\", \"2012-07-19T15:00:00-08:00\"]", # "type": "array", # "items": { "type": "datetime" } # }, # "is_public": { # "example": "[true, false]", # "type": "array", # "items": { "type": "boolean" } # } # } # } # class CourseAuditApiController < AuditorApiController include Api::V1::CourseEvent # @API Query by course. # # List course change events for a given course. # # @argument start_time [DateTime] # The beginning of the time range from which you want events. # # @argument end_time [Datetime] # The end of the time range from which you want events. # # @returns [CourseEvent] # def for_course @course = @domain_root_account.all_courses.find(params[:course_id]) if authorize events = Auditors::Course.for_course(@course, query_options) render_events(events, api_v1_audit_course_for_course_url(@course)) else render_unauthorized_action end end private def authorize @domain_root_account.grants_right?(@current_user, session, :view_course_changes) end def render_events(events, route) events = Api.paginate(events, self, route) render :json => course_events_compound_json(events, @current_user, session) end end
agpl-3.0
reneploetz/keycloak
adapters/saml/as7-eap6/subsystem/src/main/java/org/keycloak/subsystem/saml/as7/SingleSignOnDefinition.java
3516
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.subsystem.saml.as7; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelType; import java.util.HashMap; /** * @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a> */ abstract class SingleSignOnDefinition { static final SimpleAttributeDefinition SIGN_REQUEST = new SimpleAttributeDefinitionBuilder(Constants.Model.SIGN_REQUEST, ModelType.BOOLEAN, true) .setXmlName(Constants.XML.SIGN_REQUEST) .build(); static final SimpleAttributeDefinition VALIDATE_RESPONSE_SIGNATURE = new SimpleAttributeDefinitionBuilder(Constants.Model.VALIDATE_RESPONSE_SIGNATURE, ModelType.BOOLEAN, true) .setXmlName(Constants.XML.VALIDATE_RESPONSE_SIGNATURE) .build(); static final SimpleAttributeDefinition VALIDATE_ASSERTION_SIGNATURE = new SimpleAttributeDefinitionBuilder(Constants.Model.VALIDATE_ASSERTION_SIGNATURE, ModelType.BOOLEAN, true) .setXmlName(Constants.XML.VALIDATE_ASSERTION_SIGNATURE) .build(); static final SimpleAttributeDefinition REQUEST_BINDING = new SimpleAttributeDefinitionBuilder(Constants.Model.REQUEST_BINDING, ModelType.STRING, true) .setXmlName(Constants.XML.REQUEST_BINDING) .build(); static final SimpleAttributeDefinition RESPONSE_BINDING = new SimpleAttributeDefinitionBuilder(Constants.Model.RESPONSE_BINDING, ModelType.STRING, true) .setXmlName(Constants.XML.RESPONSE_BINDING) .build(); static final SimpleAttributeDefinition BINDING_URL = new SimpleAttributeDefinitionBuilder(Constants.Model.BINDING_URL, ModelType.STRING, true) .setXmlName(Constants.XML.BINDING_URL) .build(); static final SimpleAttributeDefinition ASSERTION_CONSUMER_SERVICE_URL = new SimpleAttributeDefinitionBuilder(Constants.Model.ASSERTION_CONSUMER_SERVICE_URL, ModelType.STRING, true) .setXmlName(Constants.XML.ASSERTION_CONSUMER_SERVICE_URL) .build(); static final SimpleAttributeDefinition[] ATTRIBUTES = {SIGN_REQUEST, VALIDATE_RESPONSE_SIGNATURE, VALIDATE_ASSERTION_SIGNATURE, REQUEST_BINDING, RESPONSE_BINDING, BINDING_URL, ASSERTION_CONSUMER_SERVICE_URL}; static final HashMap<String, SimpleAttributeDefinition> ATTRIBUTE_MAP = new HashMap<>(); static { for (SimpleAttributeDefinition def : ATTRIBUTES) { ATTRIBUTE_MAP.put(def.getXmlName(), def); } } static SimpleAttributeDefinition lookup(String xmlName) { return ATTRIBUTE_MAP.get(xmlName); } }
apache-2.0
sudosurootdev/external_chromium_org
chrome/browser/ui/libgtk2ui/PRESUBMIT.py
548
#!/usr/bin/python # 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. """Chromium presubmit script for src/chrome/browser/ui/libgtk2ui. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built into gcl. """ def GetPreferredTryMasters(project, change): return { 'tryserver.chromium.linux': { 'linux_chromium_rel_swarming': set(['defaulttests']), } }
bsd-3-clause
CyanogenMod/android_external_chromium_org_third_party_webrtc
base/winfirewall.cc
4408
/* * Copyright 2004 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 "webrtc/base/winfirewall.h" #include "webrtc/base/win32.h" #include <comdef.h> #include <netfw.h> #define RELEASE(lpUnk) do { \ if ((lpUnk) != NULL) { \ (lpUnk)->Release(); \ (lpUnk) = NULL; \ } \ } while (0) namespace rtc { ////////////////////////////////////////////////////////////////////// // WinFirewall ////////////////////////////////////////////////////////////////////// WinFirewall::WinFirewall() : mgr_(NULL), policy_(NULL), profile_(NULL) { } WinFirewall::~WinFirewall() { Shutdown(); } bool WinFirewall::Initialize(HRESULT* result) { if (mgr_) { if (result) { *result = S_OK; } return true; } HRESULT hr = CoCreateInstance(__uuidof(NetFwMgr), 0, CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr), reinterpret_cast<void **>(&mgr_)); if (SUCCEEDED(hr) && (mgr_ != NULL)) hr = mgr_->get_LocalPolicy(&policy_); if (SUCCEEDED(hr) && (policy_ != NULL)) hr = policy_->get_CurrentProfile(&profile_); if (result) *result = hr; return SUCCEEDED(hr) && (profile_ != NULL); } void WinFirewall::Shutdown() { RELEASE(profile_); RELEASE(policy_); RELEASE(mgr_); } bool WinFirewall::Enabled() const { if (!profile_) return false; VARIANT_BOOL fwEnabled = VARIANT_FALSE; profile_->get_FirewallEnabled(&fwEnabled); return (fwEnabled != VARIANT_FALSE); } bool WinFirewall::QueryAuthorized(const char* filename, bool* authorized) const { return QueryAuthorizedW(ToUtf16(filename).c_str(), authorized); } bool WinFirewall::QueryAuthorizedW(const wchar_t* filename, bool* authorized) const { *authorized = false; bool success = false; if (!profile_) return false; _bstr_t bfilename = filename; INetFwAuthorizedApplications* apps = NULL; HRESULT hr = profile_->get_AuthorizedApplications(&apps); if (SUCCEEDED(hr) && (apps != NULL)) { INetFwAuthorizedApplication* app = NULL; hr = apps->Item(bfilename, &app); if (SUCCEEDED(hr) && (app != NULL)) { VARIANT_BOOL fwEnabled = VARIANT_FALSE; hr = app->get_Enabled(&fwEnabled); app->Release(); if (SUCCEEDED(hr)) { success = true; *authorized = (fwEnabled != VARIANT_FALSE); } } else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) { // No entry in list of authorized apps success = true; } else { // Unexpected error } apps->Release(); } return success; } bool WinFirewall::AddApplication(const char* filename, const char* friendly_name, bool authorized, HRESULT* result) { return AddApplicationW(ToUtf16(filename).c_str(), ToUtf16(friendly_name).c_str(), authorized, result); } bool WinFirewall::AddApplicationW(const wchar_t* filename, const wchar_t* friendly_name, bool authorized, HRESULT* result) { INetFwAuthorizedApplications* apps = NULL; HRESULT hr = profile_->get_AuthorizedApplications(&apps); if (SUCCEEDED(hr) && (apps != NULL)) { INetFwAuthorizedApplication* app = NULL; hr = CoCreateInstance(__uuidof(NetFwAuthorizedApplication), 0, CLSCTX_INPROC_SERVER, __uuidof(INetFwAuthorizedApplication), reinterpret_cast<void **>(&app)); if (SUCCEEDED(hr) && (app != NULL)) { _bstr_t bstr = filename; hr = app->put_ProcessImageFileName(bstr); bstr = friendly_name; if (SUCCEEDED(hr)) hr = app->put_Name(bstr); if (SUCCEEDED(hr)) hr = app->put_Enabled(authorized ? VARIANT_TRUE : VARIANT_FALSE); if (SUCCEEDED(hr)) hr = apps->Add(app); app->Release(); } apps->Release(); } if (result) *result = hr; return SUCCEEDED(hr); } } // namespace rtc
bsd-3-clause
andrewvc/email-spec
examples/rails3_root/lib/notifier_job.rb
149
class NotifierJob < Struct.new(:notifier_method,:username,:name) def perform UserMailer.send(notifier_method,username, name).deliver end end
mit
gusortiz/code_challenges
node_modules/rimraf/bin.js
1878
#!/usr/bin/env node const rimraf = require('./') const path = require('path') const isRoot = arg => /^(\/|[a-zA-Z]:\\)$/.test(path.resolve(arg)) const filterOutRoot = arg => { const ok = preserveRoot === false || !isRoot(arg) if (!ok) { console.error(`refusing to remove ${arg}`) console.error('Set --no-preserve-root to allow this') } return ok } let help = false let dashdash = false let noglob = false let preserveRoot = true const args = process.argv.slice(2).filter(arg => { if (dashdash) return !!arg else if (arg === '--') dashdash = true else if (arg === '--no-glob' || arg === '-G') noglob = true else if (arg === '--glob' || arg === '-g') noglob = false else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/)) help = true else if (arg === '--preserve-root') preserveRoot = true else if (arg === '--no-preserve-root') preserveRoot = false else return !!arg }).filter(arg => !preserveRoot || filterOutRoot(arg)) const go = n => { if (n >= args.length) return const options = noglob ? { glob: false } : {} rimraf(args[n], options, er => { if (er) throw er go(n+1) }) } if (help || args.length === 0) { // If they didn't ask for help, then this is not a "success" const log = help ? console.log : console.error log('Usage: rimraf <path> [<path> ...]') log('') log(' Deletes all files and folders at "path" recursively.') log('') log('Options:') log('') log(' -h, --help Display this usage info') log(' -G, --no-glob Do not expand glob patterns in arguments') log(' -g, --glob Expand glob patterns in arguments (default)') log(' --preserve-root Do not remove \'/\' (default)') log(' --no-preserve-root Do not treat \'/\' specially') log(' -- Stop parsing flags') process.exit(help ? 0 : 1) } else go(0)
mit
falcontersama/chatbot
node_modules/webpack/node_modules/source-list-map/lib/fromStringWithSourceMap.js
3020
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var base64VLQ = require("./base64-vlq"); var SourceNode = require("./SourceNode"); var CodeNode = require("./CodeNode"); var SourceListMap = require("./SourceListMap"); module.exports = function fromStringWithSourceMap(code, map) { var sources = map.sources; var sourcesContent = map.sourcesContent; var mappings = map.mappings.split(";"); var lines = code.split("\n"); var nodes = []; var currentNode = null; var currentLine = 1; var currentSourceIdx = 0; var currentSourceNodeLine; mappings.forEach(function(mapping, idx) { var line = lines[idx]; if(typeof line === 'undefined') return; if(idx !== lines.length - 1) line += "\n"; if(!mapping) return addCode(line); mapping = { value: 0, rest: mapping }; var lineAdded = false; while(mapping.rest) lineAdded = processMapping(mapping, line, lineAdded) || lineAdded; if(!lineAdded) addCode(line); }); if(mappings.length < lines.length) { var idx = mappings.length; while(!lines[idx].trim() && idx < lines.length-1) { addCode(lines[idx] + "\n"); idx++; } addCode(lines.slice(idx).join("\n")); } return new SourceListMap(nodes); function processMapping(mapping, line, ignore) { if(mapping.rest && mapping.rest[0] !== ",") { base64VLQ.decode(mapping.rest, mapping); } if(!mapping.rest) return false; if(mapping.rest[0] === ",") { mapping.rest = mapping.rest.substr(1); return false; } base64VLQ.decode(mapping.rest, mapping); var sourceIdx = mapping.value + currentSourceIdx; currentSourceIdx = sourceIdx; if(mapping.rest && mapping.rest[0] !== ",") { base64VLQ.decode(mapping.rest, mapping); var linePosition = mapping.value + currentLine; currentLine = linePosition; } else { var linePosition = currentLine; } if(mapping.rest) { var next = mapping.rest.indexOf(","); mapping.rest = next === -1 ? "" : mapping.rest.substr(next); } if(!ignore) { addSource(line, sources ? sources[sourceIdx] : null, sourcesContent ? sourcesContent[sourceIdx] : null, linePosition) return true; } } function addCode(generatedCode) { if(currentNode && currentNode instanceof CodeNode) { currentNode.addGeneratedCode(generatedCode); } else if(currentNode && currentNode instanceof SourceNode && !generatedCode.trim()) { currentNode.addGeneratedCode(generatedCode); currentSourceNodeLine++; } else { currentNode = new CodeNode(generatedCode); nodes.push(currentNode); } } function addSource(generatedCode, source, originalSource, linePosition) { if(currentNode && currentNode instanceof SourceNode && currentNode.source === source && currentSourceNodeLine === linePosition ) { currentNode.addGeneratedCode(generatedCode); currentSourceNodeLine++; } else { currentNode = new SourceNode(generatedCode, source, originalSource, linePosition); currentSourceNodeLine = linePosition + 1; nodes.push(currentNode); } } };
mit
mollstam/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/reportlab-3.2.0/src/reportlab/lib/pygments2xpre.py
2578
"""Helps you output colourised code snippets in ReportLab documents. Platypus has an 'XPreformatted' flowable for handling preformatted text, with variations in fonts and colors. If Pygments is installed, calling 'pygments2xpre' will return content suitable for display in an XPreformatted object. If it's not installed, you won't get colours. For a list of available lexers see http://pygments.org/docs/ """ __all__ = ('pygments2xpre',) from reportlab.lib.utils import isPy3, asBytes, getBytesIO, getStringIO, asUnicode, isUnicode def _2xpre(s,styles): "Helper to transform Pygments HTML output to ReportLab markup" s = s.replace('<div class="highlight">','') s = s.replace('</div>','') s = s.replace('<pre>','') s = s.replace('</pre>','') for k,c in styles+[('p','#000000'),('n','#000000'),('err','#000000')]: s = s.replace('<span class="%s">' % k,'<span color="%s">' % c) return s def pygments2xpre(s, language="python"): "Return markup suitable for XPreformatted" try: from pygments import highlight from pygments.formatters import HtmlFormatter except ImportError: return s from pygments.lexers import get_lexer_by_name rconv = lambda x: x if isPy3: out = getStringIO() else: if isUnicode(s): s = asBytes(s) rconv = asUnicode out = getBytesIO() l = get_lexer_by_name(language) h = HtmlFormatter() highlight(s,l,h,out) styles = [(cls, style.split(';')[0].split(':')[1].strip()) for cls, (style, ttype, level) in h.class2style.items() if cls and style and style.startswith('color:')] return rconv(_2xpre(out.getvalue(),styles)) def convertSourceFiles(filenames): "Helper function - makes minimal PDF document" from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted from reportlab.lib.styles import getSampleStyleSheet styT=getSampleStyleSheet()["Title"] styC=getSampleStyleSheet()["Code"] doc = SimpleDocTemplate("pygments2xpre.pdf") S = [].append for filename in filenames: S(Paragraph(filename,style=styT)) src = open(filename, 'r').read() fmt = pygments2xpre(src) S(XPreformatted(fmt, style=styC)) doc.build(S.__self__) print('saved pygments2xpre.pdf') if __name__=='__main__': import sys filenames = sys.argv[1:] if not filenames: print('usage: pygments2xpre.py file1.py [file2.py] [...]') sys.exit(0) convertSourceFiles(filenames)
mit
sullenor/about-css-modules
bower_components/prismjs/plugins/file-highlight/prism-file-highlight.min.js
769
(function(){if(!self.Prism||!self.document||!document.querySelector)return;var e={js:"javascript",html:"markup",svg:"markup"};Array.prototype.slice.call(document.querySelectorAll("pre[data-src]")).forEach(function(t){var n=t.getAttribute("data-src"),r=(n.match(/\.(\w+)$/)||[,""])[1],i=e[r]||r,s=document.createElement("code");s.className="language-"+i;t.textContent="";s.textContent="Loading…";t.appendChild(s);var o=new XMLHttpRequest;o.open("GET",n,!0);o.onreadystatechange=function(){if(o.readyState==4)if(o.status<400&&o.responseText){s.textContent=o.responseText;Prism.highlightElement(s)}else o.status>=400?s.textContent="✖ Error "+o.status+" while fetching file: "+o.statusText:s.textContent="✖ Error: File does not exist or is empty"};o.send(null)})})();
mit
hodobaj/Pandaren5.3.0-master
src/server/game/Spells/SpellScript.cpp
41679
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include "Spell.h" #include "SpellAuras.h" #include "SpellScript.h" #include "SpellMgr.h" bool _SpellScript::_Validate(SpellInfo const* entry) { if (!Validate(entry)) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` did not pass Validate() function of script `%s` - script will be not added to the spell", entry->Id, m_scriptName->c_str()); return false; } return true; } void _SpellScript::_Register() { m_currentScriptState = SPELL_SCRIPT_STATE_REGISTRATION; Register(); m_currentScriptState = SPELL_SCRIPT_STATE_NONE; } void _SpellScript::_Unload() { m_currentScriptState = SPELL_SCRIPT_STATE_UNLOADING; Unload(); m_currentScriptState = SPELL_SCRIPT_STATE_NONE; } void _SpellScript::_Init(std::string const* scriptname, uint32 spellId) { m_currentScriptState = SPELL_SCRIPT_STATE_NONE; m_scriptName = scriptname; m_scriptSpellId = spellId; } std::string const* _SpellScript::_GetScriptName() const { return m_scriptName; } _SpellScript::EffectHook::EffectHook(uint8 _effIndex) { // effect index must be in range <0;2>, allow use of special effindexes ASSERT(_effIndex == EFFECT_ALL || _effIndex == EFFECT_FIRST_FOUND || _effIndex < MAX_SPELL_EFFECTS); effIndex = _effIndex; } uint8 _SpellScript::EffectHook::GetAffectedEffectsMask(SpellInfo const* spellEntry) { uint8 mask = 0; if ((effIndex == EFFECT_ALL) || (effIndex == EFFECT_FIRST_FOUND)) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((effIndex == EFFECT_FIRST_FOUND) && mask) return mask; if (CheckEffect(spellEntry, i)) mask |= (uint8)1<<i; } } else { if (CheckEffect(spellEntry, effIndex)) mask |= (uint8)1<<effIndex; } return mask; } bool _SpellScript::EffectHook::IsEffectAffected(SpellInfo const* spellEntry, uint8 effIndex) { return GetAffectedEffectsMask(spellEntry) & 1<<effIndex; } std::string _SpellScript::EffectHook::EffIndexToString() { switch (effIndex) { case EFFECT_ALL: return "EFFECT_ALL"; case EFFECT_FIRST_FOUND: return "EFFECT_FIRST_FOUND"; case EFFECT_0: return "EFFECT_0"; case EFFECT_1: return "EFFECT_1"; case EFFECT_2: return "EFFECT_2"; } return "Invalid Value"; } bool _SpellScript::EffectNameCheck::Check(SpellInfo const* spellEntry, uint8 effIndex) { if (!spellEntry->Effects[effIndex].Effect && !effName) return true; if (!spellEntry->Effects[effIndex].Effect) return false; return (effName == SPELL_EFFECT_ANY) || (spellEntry->Effects[effIndex].Effect == effName); } std::string _SpellScript::EffectNameCheck::ToString() { switch (effName) { case SPELL_EFFECT_ANY: return "SPELL_EFFECT_ANY"; default: char num[10]; sprintf (num, "%u", effName); return num; } } bool _SpellScript::EffectAuraNameCheck::Check(SpellInfo const* spellEntry, uint8 effIndex) { if (!spellEntry->Effects[effIndex].ApplyAuraName && !effAurName) return true; if (!spellEntry->Effects[effIndex].ApplyAuraName) return false; return (effAurName == SPELL_EFFECT_ANY) || (spellEntry->Effects[effIndex].ApplyAuraName == effAurName); } std::string _SpellScript::EffectAuraNameCheck::ToString() { switch (effAurName) { case SPELL_AURA_ANY: return "SPELL_AURA_ANY"; default: char num[10]; sprintf (num, "%u", effAurName); return num; } } SpellScript::CastHandler::CastHandler(SpellCastFnType _pCastHandlerScript) { pCastHandlerScript = _pCastHandlerScript; } void SpellScript::CastHandler::Call(SpellScript* spellScript) { (spellScript->*pCastHandlerScript)(); } SpellScript::CheckCastHandler::CheckCastHandler(SpellCheckCastFnType checkCastHandlerScript) { _checkCastHandlerScript = checkCastHandlerScript; } SpellCastResult SpellScript::CheckCastHandler::Call(SpellScript* spellScript) { return (spellScript->*_checkCastHandlerScript)(); } SpellScript::EffectHandler::EffectHandler(SpellEffectFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : _SpellScript::EffectNameCheck(_effName), _SpellScript::EffectHook(_effIndex) { pEffectHandlerScript = _pEffectHandlerScript; } std::string SpellScript::EffectHandler::ToString() { return "Index: " + EffIndexToString() + " Name: " +_SpellScript::EffectNameCheck::ToString(); } bool SpellScript::EffectHandler::CheckEffect(SpellInfo const* spellEntry, uint8 effIndex) { return _SpellScript::EffectNameCheck::Check(spellEntry, effIndex); } void SpellScript::EffectHandler::Call(SpellScript* spellScript, SpellEffIndex effIndex) { (spellScript->*pEffectHandlerScript)(effIndex); } SpellScript::HitHandler::HitHandler(SpellHitFnType _pHitHandlerScript) { pHitHandlerScript = _pHitHandlerScript; } void SpellScript::HitHandler::Call(SpellScript* spellScript) { (spellScript->*pHitHandlerScript)(); } SpellScript::TargetHook::TargetHook(uint8 _effectIndex, uint16 _targetType, bool _area) : _SpellScript::EffectHook(_effectIndex), targetType(_targetType), area(_area) { } std::string SpellScript::TargetHook::ToString() { std::ostringstream oss; oss << "Index: " << EffIndexToString() << " Target: " << targetType; return oss.str(); } bool SpellScript::TargetHook::CheckEffect(SpellInfo const* spellEntry, uint8 effIndex) { if (!targetType) return false; if (spellEntry->Effects[effIndex].TargetA.GetTarget() != targetType && spellEntry->Effects[effIndex].TargetB.GetTarget() != targetType) return false; SpellImplicitTargetInfo targetInfo(targetType); switch (targetInfo.GetSelectionCategory()) { case TARGET_SELECT_CATEGORY_CHANNEL: // SINGLE return !area; case TARGET_SELECT_CATEGORY_NEARBY: // BOTH return true; case TARGET_SELECT_CATEGORY_CONE: // AREA case TARGET_SELECT_CATEGORY_AREA: // AREA return area; case TARGET_SELECT_CATEGORY_DEFAULT: switch (targetInfo.GetObjectType()) { case TARGET_OBJECT_TYPE_SRC: // EMPTY case TARGET_OBJECT_TYPE_DEST: // EMPTY return false; default: switch (targetInfo.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: // SINGLE return !area; case TARGET_REFERENCE_TYPE_TARGET: // BOTH return true; default: break; } break; } break; default: break; } return false; } SpellScript::ObjectAreaTargetSelectHandler::ObjectAreaTargetSelectHandler(SpellObjectAreaTargetSelectFnType _pObjectAreaTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType) : TargetHook(_effIndex, _targetType, true) { pObjectAreaTargetSelectHandlerScript = _pObjectAreaTargetSelectHandlerScript; } void SpellScript::ObjectAreaTargetSelectHandler::Call(SpellScript* spellScript, std::list<WorldObject*>& targets) { (spellScript->*pObjectAreaTargetSelectHandlerScript)(targets); } SpellScript::ObjectTargetSelectHandler::ObjectTargetSelectHandler(SpellObjectTargetSelectFnType _pObjectTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType) : TargetHook(_effIndex, _targetType, false) { pObjectTargetSelectHandlerScript = _pObjectTargetSelectHandlerScript; } void SpellScript::ObjectTargetSelectHandler::Call(SpellScript* spellScript, WorldObject*& target) { (spellScript->*pObjectTargetSelectHandlerScript)(target); } bool SpellScript::_Validate(SpellInfo const* entry) { for (std::list<EffectHandler>::iterator itr = OnEffectLaunch.begin(); itr != OnEffectLaunch.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectLaunch` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectHandler>::iterator itr = OnEffectLaunchTarget.begin(); itr != OnEffectLaunchTarget.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectLaunchTarget` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectHandler>::iterator itr = OnEffectHit.begin(); itr != OnEffectHit.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectHit` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectHandler>::iterator itr = OnEffectHitTarget.begin(); itr != OnEffectHitTarget.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectHitTarget` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<ObjectAreaTargetSelectHandler>::iterator itr = OnObjectAreaTargetSelect.begin(); itr != OnObjectAreaTargetSelect.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnObjectAreaTargetSelect` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<ObjectTargetSelectHandler>::iterator itr = OnObjectTargetSelect.begin(); itr != OnObjectTargetSelect.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnObjectTargetSelect` of SpellScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); return _SpellScript::_Validate(entry); } bool SpellScript::_Load(Spell* spell) { m_spell = spell; _PrepareScriptCall((SpellScriptHookType)SPELL_SCRIPT_STATE_LOADING); bool load = Load(); _FinishScriptCall(); return load; } void SpellScript::_InitHit() { m_hitPreventEffectMask = 0; m_hitPreventDefaultEffectMask = 0; } void SpellScript::_PrepareScriptCall(SpellScriptHookType hookType) { m_currentScriptState = hookType; } void SpellScript::_FinishScriptCall() { m_currentScriptState = SPELL_SCRIPT_STATE_NONE; } bool SpellScript::IsInCheckCastHook() const { return m_currentScriptState == SPELL_SCRIPT_HOOK_CHECK_CAST; } bool SpellScript::IsInTargetHook() const { switch (m_currentScriptState) { case SPELL_SCRIPT_HOOK_EFFECT_LAUNCH_TARGET: case SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET: case SPELL_SCRIPT_HOOK_BEFORE_HIT: case SPELL_SCRIPT_HOOK_HIT: case SPELL_SCRIPT_HOOK_AFTER_HIT: return true; } return false; } bool SpellScript::IsInHitPhase() const { return (m_currentScriptState >= HOOK_SPELL_HIT_START && m_currentScriptState < HOOK_SPELL_HIT_END); } bool SpellScript::IsInEffectHook() const { return (m_currentScriptState >= SPELL_SCRIPT_HOOK_EFFECT_LAUNCH && m_currentScriptState <= SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET); } Unit* SpellScript::GetCaster() { return m_spell->GetCaster(); } Unit* SpellScript::GetOriginalCaster() { return m_spell->GetOriginalCaster(); } SpellInfo const* SpellScript::GetSpellInfo() { return m_spell->GetSpellInfo(); } WorldLocation const* SpellScript::GetExplTargetDest() { if (m_spell->m_targets.HasDst()) return m_spell->m_targets.GetDstPos(); return NULL; } void SpellScript::SetExplTargetDest(WorldLocation& loc) { m_spell->m_targets.SetDst(loc); } WorldObject* SpellScript::GetExplTargetWorldObject() { return m_spell->m_targets.GetObjectTarget(); } Unit* SpellScript::GetExplTargetUnit() { return m_spell->m_targets.GetUnitTarget(); } GameObject* SpellScript::GetExplTargetGObj() { return m_spell->m_targets.GetGOTarget(); } Item* SpellScript::GetExplTargetItem() { return m_spell->m_targets.GetItemTarget(); } Unit* SpellScript::GetHitUnit() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitUnit was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } return m_spell->unitTarget; } Creature* SpellScript::GetHitCreature() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitCreature was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } if (m_spell->unitTarget) return m_spell->unitTarget->ToCreature(); else return NULL; } Player* SpellScript::GetHitPlayer() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitPlayer was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } if (m_spell->unitTarget) return m_spell->unitTarget->ToPlayer(); else return NULL; } Item* SpellScript::GetHitItem() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitItem was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } return m_spell->itemTarget; } GameObject* SpellScript::GetHitGObj() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitGObj was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } return m_spell->gameObjTarget; } WorldLocation* SpellScript::GetHitDest() { if (!IsInEffectHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitDest was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } return m_spell->destTarget; } int32 SpellScript::GetHitDamage() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitDamage was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return 0; } return m_spell->m_damage; } void SpellScript::SetHitDamage(int32 damage) { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::SetHitDamage was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return; } m_spell->m_damage = damage; } int32 SpellScript::GetHitHeal() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitHeal was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return 0; } return m_spell->m_healing; } void SpellScript::SetHitHeal(int32 heal) { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::SetHitHeal was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return; } m_spell->m_healing = heal; } Aura* SpellScript::GetHitAura() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::GetHitAura was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return NULL; } if (!m_spell->m_spellAura) return NULL; if (m_spell->m_spellAura->IsRemoved()) return NULL; return m_spell->m_spellAura; } void SpellScript::PreventHitAura() { if (!IsInTargetHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::PreventHitAura was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return; } if (m_spell->m_spellAura) m_spell->m_spellAura->Remove(); } void SpellScript::PreventHitEffect(SpellEffIndex effIndex) { if (!IsInHitPhase() && !IsInEffectHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::PreventHitEffect was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return; } m_hitPreventEffectMask |= 1 << effIndex; PreventHitDefaultEffect(effIndex); } void SpellScript::PreventHitDefaultEffect(SpellEffIndex effIndex) { if (!IsInHitPhase() && !IsInEffectHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::PreventHitDefaultEffect was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return; } m_hitPreventDefaultEffectMask |= 1 << effIndex; } int32 SpellScript::GetEffectValue() { if (!IsInEffectHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::PreventHitDefaultEffect was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); return 0; } return m_spell->damage; } Item* SpellScript::GetCastItem() { return m_spell->m_CastItem; } void SpellScript::CreateItem(uint32 effIndex, uint32 itemId) { m_spell->DoCreateItem(effIndex, itemId); } SpellInfo const* SpellScript::GetTriggeringSpell() { return m_spell->m_triggeredByAuraSpell; } void SpellScript::FinishCast(SpellCastResult result) { m_spell->SendCastResult(result); m_spell->finish(result == SPELL_CAST_OK); } void SpellScript::SetCustomCastResultMessage(SpellCustomErrors result) { if (!IsInCheckCastHook()) { TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u`: function SpellScript::SetCustomCastResultMessage was called while spell not in check cast phase!", m_scriptName->c_str(), m_scriptSpellId); return; } m_spell->m_customError = result; } SpellValue const* SpellScript::GetSpellValue() { return m_spell->m_spellValue; } bool AuraScript::_Validate(SpellInfo const* entry) { for (std::list<CheckAreaTargetHandler>::iterator itr = DoCheckAreaTarget.begin(); itr != DoCheckAreaTarget.end(); ++itr) if (!entry->HasAreaAuraEffect() && !entry->HasEffect(SPELL_EFFECT_PERSISTENT_AREA_AURA)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have area aura effect - handler bound to hook `DoCheckAreaTarget` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<AuraDispelHandler>::iterator itr = OnDispel.begin(); itr != OnDispel.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `OnDispel` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<AuraDispelHandler>::iterator itr = AfterDispel.begin(); itr != AfterDispel.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `AfterDispel` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<EffectApplyHandler>::iterator itr = OnEffectApply.begin(); itr != OnEffectApply.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectApply` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectApplyHandler>::iterator itr = OnEffectRemove.begin(); itr != OnEffectRemove.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectRemove` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectApplyHandler>::iterator itr = AfterEffectApply.begin(); itr != AfterEffectApply.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `AfterEffectApply` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectApplyHandler>::iterator itr = AfterEffectRemove.begin(); itr != AfterEffectRemove.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `AfterEffectRemove` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectPeriodicHandler>::iterator itr = OnEffectPeriodic.begin(); itr != OnEffectPeriodic.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectPeriodic` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectUpdatePeriodicHandler>::iterator itr = OnEffectUpdatePeriodic.begin(); itr != OnEffectUpdatePeriodic.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectUpdatePeriodic` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectCalcAmountHandler>::iterator itr = DoEffectCalcAmount.begin(); itr != DoEffectCalcAmount.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `DoEffectCalcAmount` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectCalcPeriodicHandler>::iterator itr = DoEffectCalcPeriodic.begin(); itr != DoEffectCalcPeriodic.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `DoEffectCalcPeriodic` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectCalcSpellModHandler>::iterator itr = DoEffectCalcSpellMod.begin(); itr != DoEffectCalcSpellMod.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `DoEffectCalcSpellMod` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectAbsorbHandler>::iterator itr = OnEffectAbsorb.begin(); itr != OnEffectAbsorb.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectAbsorb` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectAbsorbHandler>::iterator itr = AfterEffectAbsorb.begin(); itr != AfterEffectAbsorb.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `AfterEffectAbsorb` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectManaShieldHandler>::iterator itr = OnEffectManaShield.begin(); itr != OnEffectManaShield.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectManaShield` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectManaShieldHandler>::iterator itr = AfterEffectManaShield.begin(); itr != AfterEffectManaShield.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `AfterEffectManaShield` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectSplitHandler>::iterator itr = OnEffectSplit.begin(); itr != OnEffectSplit.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectSplit` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<CheckProcHandler>::iterator itr = DoCheckProc.begin(); itr != DoCheckProc.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `DoCheckProc` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<AuraProcHandler>::iterator itr = DoPrepareProc.begin(); itr != DoPrepareProc.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `DoPrepareProc` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<AuraProcHandler>::iterator itr = OnProc.begin(); itr != OnProc.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `OnProc` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<AuraProcHandler>::iterator itr = AfterProc.begin(); itr != AfterProc.end(); ++itr) if (!entry->HasEffect(SPELL_EFFECT_APPLY_AURA) && !entry->HasAreaAuraEffect()) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` of script `%s` does not have apply aura effect - handler bound to hook `AfterProc` of AuraScript won't be executed", entry->Id, m_scriptName->c_str()); for (std::list<EffectProcHandler>::iterator itr = OnEffectProc.begin(); itr != OnEffectProc.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `OnEffectProc` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); for (std::list<EffectProcHandler>::iterator itr = AfterEffectProc.begin(); itr != AfterEffectProc.end(); ++itr) if (!(*itr).GetAffectedEffectsMask(entry)) TC_LOG_ERROR(LOG_FILTER_TSCR, "Spell `%u` Effect `%s` of script `%s` did not match dbc effect data - handler bound to hook `AfterEffectProc` of AuraScript won't be executed", entry->Id, (*itr).ToString().c_str(), m_scriptName->c_str()); return _SpellScript::_Validate(entry); } AuraScript::CheckAreaTargetHandler::CheckAreaTargetHandler(AuraCheckAreaTargetFnType _pHandlerScript) { pHandlerScript = _pHandlerScript; } bool AuraScript::CheckAreaTargetHandler::Call(AuraScript* auraScript, Unit* _target) { return (auraScript->*pHandlerScript)(_target); } AuraScript::AuraDispelHandler::AuraDispelHandler(AuraDispelFnType _pHandlerScript) { pHandlerScript = _pHandlerScript; } void AuraScript::AuraDispelHandler::Call(AuraScript* auraScript, DispelInfo* _dispelInfo) { (auraScript->*pHandlerScript)(_dispelInfo); } AuraScript::EffectBase::EffectBase(uint8 _effIndex, uint16 _effName) : _SpellScript::EffectAuraNameCheck(_effName), _SpellScript::EffectHook(_effIndex) { } bool AuraScript::EffectBase::CheckEffect(SpellInfo const* spellEntry, uint8 effIndex) { return _SpellScript::EffectAuraNameCheck::Check(spellEntry, effIndex); } std::string AuraScript::EffectBase::ToString() { return "Index: " + EffIndexToString() + " AuraName: " +_SpellScript::EffectAuraNameCheck::ToString(); } AuraScript::EffectPeriodicHandler::EffectPeriodicHandler(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectPeriodicHandler::Call(AuraScript* auraScript, AuraEffect const* _aurEff) { (auraScript->*pEffectHandlerScript)(_aurEff); } AuraScript::EffectUpdatePeriodicHandler::EffectUpdatePeriodicHandler(AuraEffectUpdatePeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectUpdatePeriodicHandler::Call(AuraScript* auraScript, AuraEffect* aurEff) { (auraScript->*pEffectHandlerScript)(aurEff); } AuraScript::EffectCalcAmountHandler::EffectCalcAmountHandler(AuraEffectCalcAmountFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectCalcAmountHandler::Call(AuraScript* auraScript, AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) { (auraScript->*pEffectHandlerScript)(aurEff, amount, canBeRecalculated); } AuraScript::EffectCalcPeriodicHandler::EffectCalcPeriodicHandler(AuraEffectCalcPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectCalcPeriodicHandler::Call(AuraScript* auraScript, AuraEffect const* aurEff, bool& isPeriodic, int32& periodicTimer) { (auraScript->*pEffectHandlerScript)(aurEff, isPeriodic, periodicTimer); } AuraScript::EffectCalcSpellModHandler::EffectCalcSpellModHandler(AuraEffectCalcSpellModFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectCalcSpellModHandler::Call(AuraScript* auraScript, AuraEffect const* aurEff, SpellModifier*& spellMod) { (auraScript->*pEffectHandlerScript)(aurEff, spellMod); } AuraScript::EffectApplyHandler::EffectApplyHandler(AuraEffectApplicationModeFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName, AuraEffectHandleModes _mode) : AuraScript::EffectBase(_effIndex, _effName) { pEffectHandlerScript = _pEffectHandlerScript; mode = _mode; } void AuraScript::EffectApplyHandler::Call(AuraScript* auraScript, AuraEffect const* _aurEff, AuraEffectHandleModes _mode) { if (_mode & mode) (auraScript->*pEffectHandlerScript)(_aurEff, _mode); } AuraScript::EffectAbsorbHandler::EffectAbsorbHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex) : AuraScript::EffectBase(_effIndex, SPELL_AURA_SCHOOL_ABSORB) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectAbsorbHandler::Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount) { (auraScript->*pEffectHandlerScript)(aurEff, dmgInfo, absorbAmount); } AuraScript::EffectManaShieldHandler::EffectManaShieldHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex) : AuraScript::EffectBase(_effIndex, SPELL_AURA_MANA_SHIELD) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectManaShieldHandler::Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount) { (auraScript->*pEffectHandlerScript)(aurEff, dmgInfo, absorbAmount); } AuraScript::EffectSplitHandler::EffectSplitHandler(AuraEffectSplitFnType _pEffectHandlerScript, uint8 _effIndex) : AuraScript::EffectBase(_effIndex, SPELL_AURA_SPLIT_DAMAGE_PCT) { pEffectHandlerScript = _pEffectHandlerScript; } void AuraScript::EffectSplitHandler::Call(AuraScript* auraScript, AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& splitAmount) { (auraScript->*pEffectHandlerScript)(aurEff, dmgInfo, splitAmount); } AuraScript::CheckProcHandler::CheckProcHandler(AuraCheckProcFnType handlerScript) { _HandlerScript = handlerScript; } bool AuraScript::CheckProcHandler::Call(AuraScript* auraScript, ProcEventInfo& eventInfo) { return (auraScript->*_HandlerScript)(eventInfo); } AuraScript::AuraProcHandler::AuraProcHandler(AuraProcFnType handlerScript) { _HandlerScript = handlerScript; } void AuraScript::AuraProcHandler::Call(AuraScript* auraScript, ProcEventInfo& eventInfo) { (auraScript->*_HandlerScript)(eventInfo); } AuraScript::EffectProcHandler::EffectProcHandler(AuraEffectProcFnType effectHandlerScript, uint8 effIndex, uint16 effName) : AuraScript::EffectBase(effIndex, effName) { _EffectHandlerScript = effectHandlerScript; } void AuraScript::EffectProcHandler::Call(AuraScript* auraScript, AuraEffect const* aurEff, ProcEventInfo& eventInfo) { (auraScript->*_EffectHandlerScript)(aurEff, eventInfo); } bool AuraScript::_Load(Aura* aura) { m_aura = aura; _PrepareScriptCall((AuraScriptHookType)SPELL_SCRIPT_STATE_LOADING, NULL); bool load = Load(); _FinishScriptCall(); return load; } void AuraScript::_PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp) { m_scriptStates.push(ScriptStateStore(m_currentScriptState, m_auraApplication, m_defaultActionPrevented)); m_currentScriptState = hookType; m_defaultActionPrevented = false; m_auraApplication = aurApp; } void AuraScript::_FinishScriptCall() { ScriptStateStore stateStore = m_scriptStates.top(); m_currentScriptState = stateStore._currentScriptState; m_auraApplication = stateStore._auraApplication; m_defaultActionPrevented = stateStore._defaultActionPrevented; m_scriptStates.pop(); } bool AuraScript::_IsDefaultActionPrevented() { switch (m_currentScriptState) { case AURA_SCRIPT_HOOK_EFFECT_APPLY: case AURA_SCRIPT_HOOK_EFFECT_REMOVE: case AURA_SCRIPT_HOOK_EFFECT_PERIODIC: case AURA_SCRIPT_HOOK_EFFECT_ABSORB: case AURA_SCRIPT_HOOK_EFFECT_SPLIT: case AURA_SCRIPT_HOOK_PREPARE_PROC: case AURA_SCRIPT_HOOK_EFFECT_PROC: return m_defaultActionPrevented; default: ASSERT(false && "AuraScript::_IsDefaultActionPrevented is called in a wrong place"); return false; } } void AuraScript::PreventDefaultAction() { switch (m_currentScriptState) { case AURA_SCRIPT_HOOK_EFFECT_APPLY: case AURA_SCRIPT_HOOK_EFFECT_REMOVE: case AURA_SCRIPT_HOOK_EFFECT_PERIODIC: case AURA_SCRIPT_HOOK_EFFECT_ABSORB: case AURA_SCRIPT_HOOK_EFFECT_SPLIT: case AURA_SCRIPT_HOOK_PREPARE_PROC: case AURA_SCRIPT_HOOK_EFFECT_PROC: m_defaultActionPrevented = true; break; default: TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u` AuraScript::PreventDefaultAction called in a hook in which the call won't have effect!", m_scriptName->c_str(), m_scriptSpellId); break; } } SpellInfo const* AuraScript::GetSpellInfo() const { return m_aura->GetSpellInfo(); } uint32 AuraScript::GetId() const { return m_aura->GetId(); } uint64 AuraScript::GetCasterGUID() const { return m_aura->GetCasterGUID(); } Unit* AuraScript::GetCaster() const { return m_aura->GetCaster(); } WorldObject* AuraScript::GetOwner() const { return m_aura->GetOwner(); } Unit* AuraScript::GetUnitOwner() const { return m_aura->GetUnitOwner(); } DynamicObject* AuraScript::GetDynobjOwner() const { return m_aura->GetDynobjOwner(); } void AuraScript::Remove(uint32 removeMode) { m_aura->Remove((AuraRemoveMode)removeMode); } Aura* AuraScript::GetAura() const { return m_aura; } AuraObjectType AuraScript::GetType() const { return m_aura->GetType(); } int32 AuraScript::GetDuration() const { return m_aura->GetDuration(); } void AuraScript::SetDuration(int32 duration, bool withMods) { m_aura->SetDuration(duration, withMods); } void AuraScript::RefreshDuration() { m_aura->RefreshDuration(); } time_t AuraScript::GetApplyTime() const { return m_aura->GetApplyTime(); } int32 AuraScript::GetMaxDuration() const { return m_aura->GetMaxDuration(); } void AuraScript::SetMaxDuration(int32 duration) { m_aura->SetMaxDuration(duration); } int32 AuraScript::CalcMaxDuration() const { return m_aura->CalcMaxDuration(); } bool AuraScript::IsExpired() const { return m_aura->IsExpired(); } bool AuraScript::IsPermanent() const { return m_aura->IsPermanent(); } uint8 AuraScript::GetCharges() const { return m_aura->GetCharges(); } void AuraScript::SetCharges(uint8 charges) { m_aura->SetCharges(charges); } uint8 AuraScript::CalcMaxCharges() const { return m_aura->CalcMaxCharges(); } bool AuraScript::ModCharges(int8 num, AuraRemoveMode removeMode /*= AURA_REMOVE_BY_DEFAULT*/) { return m_aura->ModCharges(num, removeMode); } bool AuraScript::DropCharge(AuraRemoveMode removeMode) { return m_aura->DropCharge(removeMode); } uint8 AuraScript::GetStackAmount() const { return m_aura->GetStackAmount(); } void AuraScript::SetStackAmount(uint8 num) { m_aura->SetStackAmount(num); } bool AuraScript::ModStackAmount(int32 num, AuraRemoveMode removeMode) { return m_aura->ModStackAmount(num, removeMode); } bool AuraScript::IsPassive() const { return m_aura->IsPassive(); } bool AuraScript::IsDeathPersistent() const { return m_aura->IsDeathPersistent(); } bool AuraScript::HasEffect(uint8 effIndex) const { return m_aura->HasEffect(effIndex); } AuraEffect* AuraScript::GetEffect(uint8 effIndex) const { return m_aura->GetEffect(effIndex); } bool AuraScript::HasEffectType(AuraType type) const { return m_aura->HasEffectType(type); } Unit* AuraScript::GetTarget() const { switch (m_currentScriptState) { case AURA_SCRIPT_HOOK_EFFECT_APPLY: case AURA_SCRIPT_HOOK_EFFECT_REMOVE: case AURA_SCRIPT_HOOK_EFFECT_AFTER_APPLY: case AURA_SCRIPT_HOOK_EFFECT_AFTER_REMOVE: case AURA_SCRIPT_HOOK_EFFECT_PERIODIC: case AURA_SCRIPT_HOOK_EFFECT_ABSORB: case AURA_SCRIPT_HOOK_EFFECT_AFTER_ABSORB: case AURA_SCRIPT_HOOK_EFFECT_MANASHIELD: case AURA_SCRIPT_HOOK_EFFECT_AFTER_MANASHIELD: case AURA_SCRIPT_HOOK_EFFECT_SPLIT: case AURA_SCRIPT_HOOK_CHECK_PROC: case AURA_SCRIPT_HOOK_PREPARE_PROC: case AURA_SCRIPT_HOOK_PROC: case AURA_SCRIPT_HOOK_AFTER_PROC: case AURA_SCRIPT_HOOK_EFFECT_PROC: case AURA_SCRIPT_HOOK_EFFECT_AFTER_PROC: return m_auraApplication->GetTarget(); default: TC_LOG_ERROR(LOG_FILTER_TSCR, "Script: `%s` Spell: `%u` AuraScript::GetTarget called in a hook in which the call won't have effect!", m_scriptName->c_str(), m_scriptSpellId); } return NULL; } AuraApplication const* AuraScript::GetTargetApplication() const { return m_auraApplication; }
gpl-2.0
haris-raheem/SuiteCRM
modules/ACLRoles/vardefs.php
6154
<?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2016 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ $dictionary['ACLRole'] = array('table' => 'acl_roles', 'comment' => 'ACL Role definition' , 'fields' => array( 'id' => array( 'name' => 'id', 'vname' => 'LBL_ID', 'required' => true, 'type' => 'id', 'reportable' => false, 'comment' => 'Unique identifier' ), 'date_entered' => array( 'name' => 'date_entered', 'vname' => 'LBL_DATE_ENTERED', 'type' => 'datetime', 'required' => true, 'comment' => 'Date record created' ), 'date_modified' => array( 'name' => 'date_modified', 'vname' => 'LBL_DATE_MODIFIED', 'type' => 'datetime', 'required' => true, 'comment' => 'Date record last modified' ), 'modified_user_id' => array( 'name' => 'modified_user_id', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_MODIFIED', 'type' => 'assigned_user_name', 'table' => 'modified_user_id_users', 'isnull' => 'false', 'dbType' => 'id', 'required' => false, 'len' => 36, 'reportable' => true, 'comment' => 'User who last modified record' ), 'created_by' => array( 'name' => 'created_by', 'rname' => 'user_name', 'id_name' => 'created_by', 'vname' => 'LBL_CREATED', 'type' => 'assigned_user_name', 'table' => 'created_by_users', 'isnull' => 'false', 'dbType' => 'id', 'len' => 36, 'comment' => 'User who created record' ), 'name' => array( 'name' => 'name', 'type' => 'varchar', 'vname' => 'LBL_NAME', 'len' => 150, 'comment' => 'The role name' ), 'description' => array( 'name' => 'description', 'vname' => 'LBL_DESCRIPTION', 'type' => 'text', 'comment' => 'The role description' ), 'deleted' => array( 'name' => 'deleted', 'vname' => 'LBL_DELETED', 'type' => 'bool', 'reportable' => false, 'comment' => 'Record deletion indicator' ), 'users' => array( 'name' => 'users', 'type' => 'link', 'relationship' => 'acl_roles_users', 'source' => 'non-db', 'vname' => 'LBL_USERS', ), 'actions' => array( 'name' => 'actions', 'type' => 'link', 'relationship' => 'acl_roles_actions', 'source' => 'non-db', 'vname' => 'LBL_USERS', ), 'SecurityGroups' => array( 'name' => 'SecurityGroups', 'type' => 'link', 'relationship' => 'securitygroups_acl_roles', 'module' => 'SecurityGroups', 'bean_name' => 'SecurityGroup', 'source' => 'non-db', 'vname' => 'LBL_SECURITYGROUPS', ), ) , 'indices' => array( array('name' => 'aclrolespk', 'type' => 'primary', 'fields' => array('id')), array('name' => 'idx_aclrole_id_del', 'type' => 'index', 'fields' => array('id', 'deleted')), ) ); ?>
agpl-3.0
HashEngineering/dimecoinj
core/src/main/java/com/google/bitcoin/wallet/DefaultCoinSelector.java
5121
package com.google.bitcoin.wallet; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.TransactionConfidence; import com.google.bitcoin.core.TransactionOutput; import com.google.bitcoin.params.RegTestParams; import com.google.common.annotations.VisibleForTesting; import java.math.BigInteger; import java.util.*; /** * This class implements a {@link com.google.bitcoin.wallet.CoinSelector} which attempts to get the highest priority * possible. This means that the transaction is the most likely to get confirmed. Note that this means we may end up * "spending" more priority than would be required to get the transaction we are creating confirmed. */ public class DefaultCoinSelector implements CoinSelector { public CoinSelection select(BigInteger biTarget, LinkedList<TransactionOutput> candidates) { long target = biTarget.longValue(); HashSet<TransactionOutput> selected = new HashSet<TransactionOutput>(); // Sort the inputs by age*value so we get the highest "coindays" spent. // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered. ArrayList<TransactionOutput> sortedOutputs = new ArrayList<TransactionOutput>(candidates); // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting // them in order to improve performance. if (!biTarget.equals(NetworkParameters.MAX_MONEY)) { sortOutputs(sortedOutputs); } // Now iterate over the sorted outputs until we have got as close to the target as possible or a little // bit over (excessive value will be change). long total = 0; for (TransactionOutput output : sortedOutputs) { if (total >= target) break; // Only pick chain-included transactions, or transactions that are ours and pending. if (!shouldSelect(output.getParentTransaction())) continue; selected.add(output); total += output.getValue().longValue(); } // Total may be lower than target here, if the given candidates were insufficient to create to requested // transaction. return new CoinSelection(BigInteger.valueOf(total), selected); } @VisibleForTesting static void sortOutputs(ArrayList<TransactionOutput> outputs) { Collections.sort(outputs, new Comparator<TransactionOutput>() { public int compare(TransactionOutput a, TransactionOutput b) { int depth1 = 0; int depth2 = 0; TransactionConfidence conf1 = a.getParentTransaction().getConfidence(); TransactionConfidence conf2 = b.getParentTransaction().getConfidence(); if (conf1.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) depth1 = conf1.getDepthInBlocks(); if (conf2.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) depth2 = conf2.getDepthInBlocks(); BigInteger aValue = a.getValue(); BigInteger bValue = b.getValue(); BigInteger aCoinDepth = aValue.multiply(BigInteger.valueOf(depth1)); BigInteger bCoinDepth = bValue.multiply(BigInteger.valueOf(depth2)); int c1 = bCoinDepth.compareTo(aCoinDepth); if (c1 != 0) return c1; // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size. int c2 = bValue.compareTo(aValue); if (c2 != 0) return c2; // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering. BigInteger aHash = a.getParentTransaction().getHash().toBigInteger(); BigInteger bHash = b.getParentTransaction().getHash().toBigInteger(); return aHash.compareTo(bHash); } }); } /** Sub-classes can override this to just customize whether transactions are usable, but keep age sorting. */ protected boolean shouldSelect(Transaction tx) { return isSelectable(tx); } public static boolean isSelectable(Transaction tx) { // Only pick chain-included transactions, or transactions that are ours and pending. TransactionConfidence confidence = tx.getConfidence(); TransactionConfidence.ConfidenceType type = confidence.getConfidenceType(); return type.equals(TransactionConfidence.ConfidenceType.BUILDING) || type.equals(TransactionConfidence.ConfidenceType.PENDING) && confidence.getSource().equals(TransactionConfidence.Source.SELF) && // In regtest mode we expect to have only one peer, so we won't see transactions propagate. // TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0 (confidence.numBroadcastPeers() > 1 || tx.getParams() == RegTestParams.get()); } }
apache-2.0
aaron-goshine/angular
modules/angular2/src/core/zone/ng_zone.ts
12021
import {ListWrapper, StringMapWrapper} from 'angular2/src/core/facade/collection'; import {normalizeBlank, isPresent, global} from 'angular2/src/core/facade/lang'; import {wtfLeave, wtfCreateScope, WtfScopeFn} from '../profile/profile'; export interface NgZoneZone extends Zone { _innerZone: boolean; } /** * An injectable service for executing work inside or outside of the Angular zone. * * The most common use of this service is to optimize performance when starting a work consisting of * one or more asynchronous tasks that don't require UI updates or error handling to be handled by * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks * can reenter the Angular zone via {@link #run}. * * <!-- TODO: add/fix links to: * - docs explaining zones and the use of zones in Angular and change-detection * - link to runOutsideAngular/run (throughout this file!) * --> * * ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview)) * ``` * import {Component, View, NgIf, NgZone} from 'angular2/angular2'; * * @Component({ * selector: 'ng-zone-demo' * }) * @View({ * template: ` * <h2>Demo: NgZone</h2> * * <p>Progress: {{progress}}%</p> * <p *ng-if="progress >= 100">Done processing {{label}} of Angular zone!</p> * * <button (click)="processWithinAngularZone()">Process within Angular zone</button> * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button> * `, * directives: [NgIf] * }) * export class NgZoneDemo { * progress: number = 0; * label: string; * * constructor(private _ngZone: NgZone) {} * * // Loop inside the Angular zone * // so the UI DOES refresh after each setTimeout cycle * processWithinAngularZone() { * this.label = 'inside'; * this.progress = 0; * this._increaseProgress(() => console.log('Inside Done!')); * } * * // Loop outside of the Angular zone * // so the UI DOES NOT refresh after each setTimeout cycle * processOutsideOfAngularZone() { * this.label = 'outside'; * this.progress = 0; * this._ngZone.runOutsideAngular(() => { * this._increaseProgress(() => { * // reenter the Angular zone and display done * this._ngZone.run(() => {console.log('Outside Done!') }); * }})); * } * * * _increaseProgress(doneCallback: () => void) { * this.progress += 1; * console.log(`Current progress: ${this.progress}%`); * * if (this.progress < 100) { * window.setTimeout(() => this._increaseProgress(doneCallback)), 10) * } else { * doneCallback(); * } * } * } * ``` */ export class NgZone { _runScope: WtfScopeFn = wtfCreateScope(`NgZone#run()`); _microtaskScope: WtfScopeFn = wtfCreateScope(`NgZone#microtask()`); // Code executed in _mountZone does not trigger the onTurnDone. _mountZone; // _innerZone is the child of _mountZone. Any code executed in this zone will trigger the // onTurnDone hook at the end of the current VM turn. _innerZone; _onTurnStart: () => void; _onTurnDone: () => void; _onEventDone: () => void; _onErrorHandler: (error, stack) => void; // Number of microtasks pending from _innerZone (& descendants) _pendingMicrotasks: number; // Whether some code has been executed in the _innerZone (& descendants) in the current turn _hasExecutedCodeInInnerZone: boolean; // run() call depth in _mountZone. 0 at the end of a macrotask // zone.run(() => { // top-level call // zone.run(() => {}); // nested call -> in-turn // }); _nestedRun: number; // TODO(vicb): implement this class properly for node.js environment // This disabled flag is only here to please cjs tests _disabled: boolean; _inVmTurnDone: boolean = false; _pendingTimeouts: number[] = []; /** * @private * @param {bool} enableLongStackTrace whether to enable long stack trace. They should only be * enabled in development mode as they significantly impact perf. */ constructor({enableLongStackTrace}) { this._onTurnStart = null; this._onTurnDone = null; this._onEventDone = null; this._onErrorHandler = null; this._pendingMicrotasks = 0; this._hasExecutedCodeInInnerZone = false; this._nestedRun = 0; if (global.zone) { this._disabled = false; this._mountZone = global.zone; this._innerZone = this._createInnerZone(this._mountZone, enableLongStackTrace); } else { this._disabled = true; this._mountZone = null; } } /** * @private <!-- TODO: refactor to make TS private --> * * Sets the zone hook that is called just before a browser task that is handled by Angular * executes. * * The hook is called once per browser task that is handled by Angular. * * Setting the hook overrides any previously set hook. */ overrideOnTurnStart(onTurnStartHook: Function): void { this._onTurnStart = normalizeBlank(onTurnStartHook); } /** * @private <!-- TODO: refactor to make TS private --> * * Sets the zone hook that is called immediately after Angular zone is done processing the current * task and any microtasks scheduled from that task. * * This is where we typically do change-detection. * * The hook is called once per browser task that is handled by Angular. * * Setting the hook overrides any previously set hook. */ overrideOnTurnDone(onTurnDoneHook: Function): void { this._onTurnDone = normalizeBlank(onTurnDoneHook); } /** * @private <!-- TODO: refactor to make TS private --> * * Sets the zone hook that is called immediately after the `onTurnDone` callback is called and any * microstasks scheduled from within that callback are drained. * * `onEventDoneFn` is executed outside Angular zone, which means that we will no longer attempt to * sync the UI with any model changes that occur within this callback. * * This hook is useful for validating application state (e.g. in a test). * * Setting the hook overrides any previously set hook. */ overrideOnEventDone(onEventDoneFn: Function, opt_waitForAsync: boolean = false): void { var normalizedOnEventDone = normalizeBlank(onEventDoneFn); if (opt_waitForAsync) { this._onEventDone = () => { if (!this._pendingTimeouts.length) { normalizedOnEventDone(); } }; } else { this._onEventDone = normalizedOnEventDone; } } /** * @private <!-- TODO: refactor to make TS private --> * * Sets the zone hook that is called when an error is thrown in the Angular zone. * * Setting the hook overrides any previously set hook. */ overrideOnErrorHandler(errorHandler: (error: Error, stack: string) => void) { this._onErrorHandler = normalizeBlank(errorHandler); } /** * Executes the `fn` function synchronously within the Angular zone and returns value returned by * the function. * * Running functions via `run` allows you to reenter Angular zone from a task that was executed * outside of the Angular zone (typically started via {@link #runOutsideAngular}). * * Any future tasks or microtasks scheduled from within this function will continue executing from * within the Angular zone. */ run(fn: () => any): any { if (this._disabled) { return fn(); } else { var s = this._runScope(); try { return this._innerZone.run(fn); } finally { wtfLeave(s); } } } /** * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by * the function. * * Running functions via `runOutsideAngular` allows you to escape Angular's zone and do work that * doesn't trigger Angular change-detection or is subject to Angular's error handling. * * Any future tasks or microtasks scheduled from within this function will continue executing from * outside of the Angular zone. * * Use {@link #run} to reenter the Angular zone and do work that updates the application model. */ runOutsideAngular(fn: () => any): any { if (this._disabled) { return fn(); } else { return this._mountZone.run(fn); } } _createInnerZone(zone, enableLongStackTrace) { var microtaskScope = this._microtaskScope; var ngZone = this; var errorHandling; if (enableLongStackTrace) { errorHandling = StringMapWrapper.merge(Zone.longStackTraceZone, {onError: function(e) { ngZone._onError(this, e); }}); } else { errorHandling = {onError: function(e) { ngZone._onError(this, e); }}; } return zone.fork(errorHandling) .fork({ '$run': function(parentRun) { return function() { try { ngZone._nestedRun++; if (!ngZone._hasExecutedCodeInInnerZone) { ngZone._hasExecutedCodeInInnerZone = true; if (ngZone._onTurnStart) { parentRun.call(ngZone._innerZone, ngZone._onTurnStart); } } return parentRun.apply(this, arguments); } finally { ngZone._nestedRun--; // If there are no more pending microtasks, we are at the end of a VM turn (or in // onTurnStart) // _nestedRun will be 0 at the end of a macrotasks (it could be > 0 when there are // nested calls // to run()). if (ngZone._pendingMicrotasks == 0 && ngZone._nestedRun == 0 && !this._inVmTurnDone) { if (ngZone._onTurnDone && ngZone._hasExecutedCodeInInnerZone) { try { this._inVmTurnDone = true; parentRun.call(ngZone._innerZone, ngZone._onTurnDone); } finally { this._inVmTurnDone = false; ngZone._hasExecutedCodeInInnerZone = false; } } if (ngZone._pendingMicrotasks === 0 && isPresent(ngZone._onEventDone)) { ngZone.runOutsideAngular(ngZone._onEventDone); } } } }; }, '$scheduleMicrotask': function(parentScheduleMicrotask) { return function(fn) { ngZone._pendingMicrotasks++; var microtask = function() { var s = microtaskScope(); try { fn(); } finally { ngZone._pendingMicrotasks--; wtfLeave(s); } }; parentScheduleMicrotask.call(this, microtask); }; }, '$setTimeout': function(parentSetTimeout) { return function(fn: Function, delay: number, ...args) { var id; var cb = function() { fn(); ListWrapper.remove(ngZone._pendingTimeouts, id); }; id = parentSetTimeout(cb, delay, args); ngZone._pendingTimeouts.push(id); return id; }; }, '$clearTimeout': function(parentClearTimeout) { return function(id: number) { parentClearTimeout(id); ListWrapper.remove(ngZone._pendingTimeouts, id); }; }, _innerZone: true }); } _onError(zone, e): void { if (isPresent(this._onErrorHandler)) { var trace = [normalizeBlank(e.stack)]; while (zone && zone.constructedAtException) { trace.push(zone.constructedAtException.get()); zone = zone.parent; } this._onErrorHandler(e, trace); } else { console.log('## _onError ##'); console.log(e.stack); throw e; } } }
apache-2.0
emretiryaki/Orchard
src/Orchard.Web/Modules/Orchard.MediaLibrary/Scripts/media-library-picker.js
5393
(function($) { $(".media-library-picker-field").each(function() { var element = $(this); var multiple = element.data("multiple"); var removeText = element.data("remove-text"); var removePrompt = element.data("remove-prompt"); var removeAllPrompt = element.data("remove-all-prompt"); var editText = element.data("edit-text"); var dirtyText = element.data("dirty-text"); var pipe = element.data("pipe"); var returnUrl = element.data("return-url"); var addUrl = element.data("add-url"); var promptOnNavigate = element.data("prompt-on-navigate"); var showSaveWarning = element.data("show-save-warning"); var addButton = element.find(".button.add"); var removeAllButton = element.find(".button.remove"); var template = '<li><div data-id="{contentItemId}" class="media-library-picker-item"><div class="thumbnail">{thumbnail}<div class="overlay"><h3>{title}</h3></div></div></div><a href="#" data-id="{contentItemId}" class="media-library-picker-remove">' + removeText + '</a>' + pipe + '<a href="{editLink}?ReturnUrl=' + returnUrl + '">' + editText + '</a></li>'; var refreshIds = function() { var id = element.find('.selected-ids'); id.val(''); element.find(".media-library-picker-item").each(function() { id.val(id.val() + "," + $(this).attr("data-id")); }); var itemsCount = element.find(".media-library-picker-item").length; if(!multiple && itemsCount > 0) { addButton.hide(); } else { addButton.show(); } if(itemsCount > 1) { removeAllButton.show(); } else { removeAllButton.hide(); } }; var showSaveMsg = function () { if (!showSaveWarning) return; element.find('.media-library-picker-message').show(); window.mediaLibraryDirty = true; }; window.mediaLibraryDirty = false; if (promptOnNavigate) { if (!window.mediaLibraryNavigateAway) { $(window).on("beforeunload", window.mediaLibraryNavigateAway = function() { if (window.mediaLibraryDirty) { return dirtyText; } }); element.closest("form").on("submit", function() { window.mediaLibraryDirty = false; }); } } refreshIds(); addButton.click(function () { var url = addUrl; $.colorbox({ href: url, iframe: true, reposition: true, width: "100%", height: "100%", onLoad: function() { // hide the scrollbars from the main window $('html, body').css('overflow', 'hidden'); $('#cboxClose').remove(); element.trigger("opened"); }, onClosed: function() { $('html, body').css('overflow', ''); var selectedData = $.colorbox.selectedData; if (selectedData == null) { // Dialog cancelled, do nothing element.trigger("closed"); return; } var selectionLength = multiple ? selectedData.length : Math.min(selectedData.length, 1); for (var i = 0; i < selectionLength ; i++) { var tmpl = template .replace(/\{contentItemId\}/g, selectedData[i].id) .replace(/\{thumbnail\}/g, selectedData[i].thumbnail) .replace(/\{title\}/g, selectedData[i].title) .replace(/\{editLink\}/g, selectedData[i].editLink); var content = $(tmpl); element.find('.media-library-picker.items ul').append(content); } refreshIds(); if (selectedData.length) { showSaveMsg(); } element.trigger("closed"); } }); }); removeAllButton.click(function (e) { e.preventDefault(); if (!confirm(removeAllPrompt)) return false; element.find('.media-library-picker.items ul').children('li').remove(); refreshIds(); showSaveMsg(); return false; }); element.on("click",'.media-library-picker-remove', function(e) { e.preventDefault(); if (!confirm(removePrompt)) return false; $(this).closest('li').remove(); refreshIds(); showSaveMsg(); return false; }); element.find(".media-library-picker.items ul").sortable({ handle: '.thumbnail', stop: function() { refreshIds(); showSaveMsg(); } }).disableSelection(); }); })(jQuery);
bsd-3-clause
soltanmm/grpc
src/csharp/Grpc.Auth/Properties/AssemblyInfo.cs
375
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("Grpc.Auth")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Google Inc. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
bsd-3-clause
dakshshah96/cdnjs
ajax/libs/ag-grid/7.1.0/lib/rendering/cellEditorFactory.js
5132
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v7.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var context_1 = require("../context/context"); var utils_1 = require('../utils'); var textCellEditor_1 = require("./cellEditors/textCellEditor"); var selectCellEditor_1 = require("./cellEditors/selectCellEditor"); var popupEditorWrapper_1 = require("./cellEditors/popupEditorWrapper"); var popupTextCellEditor_1 = require("./cellEditors/popupTextCellEditor"); var popupSelectCellEditor_1 = require("./cellEditors/popupSelectCellEditor"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var largeTextCellEditor_1 = require("./cellEditors/largeTextCellEditor"); var CellEditorFactory = (function () { function CellEditorFactory() { this.cellEditorMap = {}; } CellEditorFactory.prototype.init = function () { this.cellEditorMap[CellEditorFactory.TEXT] = textCellEditor_1.TextCellEditor; this.cellEditorMap[CellEditorFactory.SELECT] = selectCellEditor_1.SelectCellEditor; this.cellEditorMap[CellEditorFactory.POPUP_TEXT] = popupTextCellEditor_1.PopupTextCellEditor; this.cellEditorMap[CellEditorFactory.POPUP_SELECT] = popupSelectCellEditor_1.PopupSelectCellEditor; this.cellEditorMap[CellEditorFactory.LARGE_TEXT] = largeTextCellEditor_1.LargeTextCellEditor; }; CellEditorFactory.prototype.addCellEditor = function (key, cellEditor) { this.cellEditorMap[key] = cellEditor; }; // private registerEditorsFromGridOptions(): void { // var userProvidedCellEditors = this.gridOptionsWrapper.getCellEditors(); // _.iterateObject(userProvidedCellEditors, (key: string, cellEditor: {new(): ICellEditor})=> { // this.addCellEditor(key, cellEditor); // }); // } CellEditorFactory.prototype.createCellEditor = function (key, params) { var CellEditorClass; if (utils_1.Utils.missing(key)) { CellEditorClass = this.cellEditorMap[CellEditorFactory.TEXT]; } else if (typeof key === 'string') { CellEditorClass = this.cellEditorMap[key]; if (utils_1.Utils.missing(CellEditorClass)) { console.warn('ag-Grid: unable to find cellEditor for key ' + key); CellEditorClass = this.cellEditorMap[CellEditorFactory.TEXT]; } } else { CellEditorClass = key; } var cellEditor = new CellEditorClass(); this.context.wireBean(cellEditor); // we have to call init first, otherwise when using the frameworks, the wrapper // classes won't be set up if (cellEditor.init) { cellEditor.init(params); } if (cellEditor.isPopup && cellEditor.isPopup()) { if (this.gridOptionsWrapper.isFullRowEdit()) { console.warn('ag-Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both ' + '- either turn off fullRowEdit, or stop using popup editors.'); } cellEditor = new popupEditorWrapper_1.PopupEditorWrapper(cellEditor); cellEditor.init(params); } return cellEditor; }; CellEditorFactory.TEXT = 'text'; CellEditorFactory.SELECT = 'select'; CellEditorFactory.POPUP_TEXT = 'popupText'; CellEditorFactory.POPUP_SELECT = 'popupSelect'; CellEditorFactory.LARGE_TEXT = 'largeText'; __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], CellEditorFactory.prototype, "context", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], CellEditorFactory.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], CellEditorFactory.prototype, "init", null); CellEditorFactory = __decorate([ context_1.Bean('cellEditorFactory'), __metadata('design:paramtypes', []) ], CellEditorFactory); return CellEditorFactory; }()); exports.CellEditorFactory = CellEditorFactory;
mit
shimingsg/corefx
src/System.Collections.Specialized/tests/HybridDictionary/HybridDictionary.CtorTests.cs
2327
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.Specialized.Tests { public class HybridDictionaryCtorTests { [Fact] public void Ctor_Empty() { HybridDictionary hybridDictionary = new HybridDictionary(); VerifyCtor(hybridDictionary, caseInsensitive: false); } [Theory] [InlineData(-1)] [InlineData(0)] [InlineData(5)] [InlineData(50)] public void Ctor_Int(int initialSize) { HybridDictionary hybridDictionary = new HybridDictionary(initialSize); VerifyCtor(hybridDictionary, caseInsensitive: false); Ctor_Int_Bool(initialSize, true); Ctor_Int_Bool(initialSize, false); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Bool(bool caseInsensitive) { HybridDictionary hybridDictionary = new HybridDictionary(caseInsensitive); VerifyCtor(hybridDictionary, caseInsensitive: caseInsensitive); } private static void Ctor_Int_Bool(int initialSize, bool caseInsensitive) { HybridDictionary hybridDictionary = new HybridDictionary(initialSize, caseInsensitive); VerifyCtor(hybridDictionary, caseInsensitive: caseInsensitive); } private static void VerifyCtor(HybridDictionary hybridDictionary, bool caseInsensitive) { Assert.Equal(0, hybridDictionary.Count); Assert.Equal(0, hybridDictionary.Keys.Count); Assert.Equal(0, hybridDictionary.Values.Count); Assert.False(hybridDictionary.IsFixedSize); Assert.False(hybridDictionary.IsReadOnly); Assert.False(hybridDictionary.IsSynchronized); if (caseInsensitive) { hybridDictionary["key"] = "value"; Assert.Equal("value", hybridDictionary["KEY"]); } else { hybridDictionary["key"] = "value"; Assert.Null(hybridDictionary["KEY"]); } } } }
mit
sethpollack/kubernetes
staging/src/k8s.io/code-generator/_examples/crd/clientset/versioned/typed/example/v1/fake/fake_testtype.go
5378
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( "context" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" examplev1 "k8s.io/code-generator/_examples/crd/apis/example/v1" ) // FakeTestTypes implements TestTypeInterface type FakeTestTypes struct { Fake *FakeExampleV1 ns string } var testtypesResource = schema.GroupVersionResource{Group: "example.crd.code-generator.k8s.io", Version: "v1", Resource: "testtypes"} var testtypesKind = schema.GroupVersionKind{Group: "example.crd.code-generator.k8s.io", Version: "v1", Kind: "TestType"} // Get takes name of the testType, and returns the corresponding testType object, and an error if there is any. func (c *FakeTestTypes) Get(ctx context.Context, name string, options v1.GetOptions) (result *examplev1.TestType, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(testtypesResource, c.ns, name), &examplev1.TestType{}) if obj == nil { return nil, err } return obj.(*examplev1.TestType), err } // List takes label and field selectors, and returns the list of TestTypes that match those selectors. func (c *FakeTestTypes) List(ctx context.Context, opts v1.ListOptions) (result *examplev1.TestTypeList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(testtypesResource, testtypesKind, c.ns, opts), &examplev1.TestTypeList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &examplev1.TestTypeList{ListMeta: obj.(*examplev1.TestTypeList).ListMeta} for _, item := range obj.(*examplev1.TestTypeList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested testTypes. func (c *FakeTestTypes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(testtypesResource, c.ns, opts)) } // Create takes the representation of a testType and creates it. Returns the server's representation of the testType, and an error, if there is any. func (c *FakeTestTypes) Create(ctx context.Context, testType *examplev1.TestType, opts v1.CreateOptions) (result *examplev1.TestType, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(testtypesResource, c.ns, testType), &examplev1.TestType{}) if obj == nil { return nil, err } return obj.(*examplev1.TestType), err } // Update takes the representation of a testType and updates it. Returns the server's representation of the testType, and an error, if there is any. func (c *FakeTestTypes) Update(ctx context.Context, testType *examplev1.TestType, opts v1.UpdateOptions) (result *examplev1.TestType, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(testtypesResource, c.ns, testType), &examplev1.TestType{}) if obj == nil { return nil, err } return obj.(*examplev1.TestType), err } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *FakeTestTypes) UpdateStatus(ctx context.Context, testType *examplev1.TestType, opts v1.UpdateOptions) (*examplev1.TestType, error) { obj, err := c.Fake. Invokes(testing.NewUpdateSubresourceAction(testtypesResource, "status", c.ns, testType), &examplev1.TestType{}) if obj == nil { return nil, err } return obj.(*examplev1.TestType), err } // Delete takes name of the testType and deletes it. Returns an error if one occurs. func (c *FakeTestTypes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(testtypesResource, c.ns, name), &examplev1.TestType{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeTestTypes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { action := testing.NewDeleteCollectionAction(testtypesResource, c.ns, listOpts) _, err := c.Fake.Invokes(action, &examplev1.TestTypeList{}) return err } // Patch applies the patch and returns the patched testType. func (c *FakeTestTypes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *examplev1.TestType, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(testtypesResource, c.ns, name, pt, data, subresources...), &examplev1.TestType{}) if obj == nil { return nil, err } return obj.(*examplev1.TestType), err }
apache-2.0
nawawi/docker
vendor/github.com/coreos/go-systemd/v22/activation/files_windows.go
676
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package activation import "os" func Files(unsetEnv bool) []*os.File { return nil }
apache-2.0
microhackathon-test/marketing-offer-generator-lodz
src/main/groovy/com/ofg/twitter/config/Versions.java
570
package com.ofg.twitter.config; public final class Versions { private Versions() { throw new UnsupportedOperationException("Can't instantiate a utility class"); } public static final String APP_NAME = "com.ofg.twitter-places-analyzer"; public static final String VND_PREFIX = "application/vnd"; public static final String JSON_TYPE_SUFFIX = "+json"; public static final String VERSION_1 = "v1"; public static final String TWITTER_PLACES_ANALYZER_JSON_VERSION_1 = VND_PREFIX + "." + APP_NAME + "." + VERSION_1 + JSON_TYPE_SUFFIX; }
apache-2.0
BrainlessLabs/bun
include/third_party/msgpack/msgpack/preprocessor/debug/error.hpp
1640
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef MSGPACK_PREPROCESSOR_DEBUG_ERROR_HPP # define MSGPACK_PREPROCESSOR_DEBUG_ERROR_HPP # # include <msgpack/preprocessor/cat.hpp> # include <msgpack/preprocessor/config/config.hpp> # # /* MSGPACK_PP_ERROR */ # # if MSGPACK_PP_CONFIG_ERRORS # define MSGPACK_PP_ERROR(code) MSGPACK_PP_CAT(MSGPACK_PP_ERROR_, code) # endif # # define MSGPACK_PP_ERROR_0x0000 MSGPACK_PP_ERROR(0x0000, MSGPACK_PP_INDEX_OUT_OF_BOUNDS) # define MSGPACK_PP_ERROR_0x0001 MSGPACK_PP_ERROR(0x0001, MSGPACK_PP_WHILE_OVERFLOW) # define MSGPACK_PP_ERROR_0x0002 MSGPACK_PP_ERROR(0x0002, MSGPACK_PP_FOR_OVERFLOW) # define MSGPACK_PP_ERROR_0x0003 MSGPACK_PP_ERROR(0x0003, MSGPACK_PP_REPEAT_OVERFLOW) # define MSGPACK_PP_ERROR_0x0004 MSGPACK_PP_ERROR(0x0004, MSGPACK_PP_LIST_FOLD_OVERFLOW) # define MSGPACK_PP_ERROR_0x0005 MSGPACK_PP_ERROR(0x0005, MSGPACK_PP_SEQ_FOLD_OVERFLOW) # define MSGPACK_PP_ERROR_0x0006 MSGPACK_PP_ERROR(0x0006, MSGPACK_PP_ARITHMETIC_OVERFLOW) # define MSGPACK_PP_ERROR_0x0007 MSGPACK_PP_ERROR(0x0007, MSGPACK_PP_DIVISION_BY_ZERO) # # endif
bsd-3-clause
wolfzero1314/ReactDemo
node_modules/acorn/dist/walk.es.js
13610
// AST walker module for Mozilla Parser API compatible trees // A simple walk is one where you simply specify callbacks to be // called on specific nodes. The last two arguments are optional. A // simple use would be // // walk.simple(myTree, { // Expression: function(node) { ... } // }); // // to do something with all expressions. All Parser API node types // can be used to identify node types, as well as Expression, // Statement, and ScopeBody, which denote categories of nodes. // // The base argument can be used to pass a custom (recursive) // walker, and state can be used to give this walked an initial // state. function simple(node, visitors, base, state, override) { if (!base) { base = exports.base ; }(function c(node, st, override) { var type = override || node.type, found = visitors[type]; base[type](node, st, c); if (found) { found(node, st); } })(node, state, override); } // An ancestor walk keeps an array of ancestor nodes (including the // current node) and passes them to the callback as third parameter // (and also as state parameter when no other state is present). function ancestor(node, visitors, base, state) { if (!base) { base = exports.base; } var ancestors = [];(function c(node, st, override) { var type = override || node.type, found = visitors[type]; var isNew = node != ancestors[ancestors.length - 1]; if (isNew) { ancestors.push(node); } base[type](node, st, c); if (found) { found(node, st || ancestors, ancestors); } if (isNew) { ancestors.pop(); } })(node, state); } // A recursive walk is one where your functions override the default // walkers. They can modify and replace the state parameter that's // threaded through the walk, and can opt how and whether to walk // their child nodes (by calling their third argument on these // nodes). function recursive(node, state, funcs, base, override) { var visitor = funcs ? exports.make(funcs, base) : base;(function c(node, st, override) { visitor[override || node.type](node, st, c); })(node, state, override); } function makeTest(test) { if (typeof test == "string") { return function (type) { return type == test; } } else if (!test) { return function () { return true; } } else { return test } } var Found = function Found(node, state) { this.node = node; this.state = state; }; // A full walk triggers the callback on each node function full(node, callback, base, state, override) { if (!base) { base = exports.base ; }(function c(node, st, override) { var type = override || node.type; base[type](node, st, c); callback(node, st, type); })(node, state, override); } // An fullAncestor walk is like an ancestor walk, but triggers // the callback on each node function fullAncestor(node, callback, base, state) { if (!base) { base = exports.base; } var ancestors = [];(function c(node, st, override) { var type = override || node.type; var isNew = node != ancestors[ancestors.length - 1]; if (isNew) { ancestors.push(node); } base[type](node, st, c); callback(node, st || ancestors, ancestors, type); if (isNew) { ancestors.pop(); } })(node, state); } // Find a node with a given start, end, and type (all are optional, // null can be used as wildcard). Returns a {node, state} object, or // undefined when it doesn't find a matching node. function findNodeAt(node, start, end, test, base, state) { test = makeTest(test); if (!base) { base = exports.base; } try { (function c(node, st, override) { var type = override || node.type; if ((start == null || node.start <= start) && (end == null || node.end >= end)) { base[type](node, st, c); } if ((start == null || node.start == start) && (end == null || node.end == end) && test(type, node)) { throw new Found(node, st) } })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the innermost node of a given type that contains the given // position. Interface similar to findNodeAt. function findNodeAround(node, pos, test, base, state) { test = makeTest(test); if (!base) { base = exports.base; } try { (function c(node, st, override) { var type = override || node.type; if (node.start > pos || node.end < pos) { return } base[type](node, st, c); if (test(type, node)) { throw new Found(node, st) } })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the outermost matching node after a given position. function findNodeAfter(node, pos, test, base, state) { test = makeTest(test); if (!base) { base = exports.base; } try { (function c(node, st, override) { if (node.end < pos) { return } var type = override || node.type; if (node.start >= pos && test(type, node)) { throw new Found(node, st) } base[type](node, st, c); })(node, state); } catch (e) { if (e instanceof Found) { return e } throw e } } // Find the outermost matching node before a given position. function findNodeBefore(node, pos, test, base, state) { test = makeTest(test); if (!base) { base = exports.base; } var max;(function c(node, st, override) { if (node.start > pos) { return } var type = override || node.type; if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) { max = new Found(node, st); } base[type](node, st, c); })(node, state); return max } // Fallback to an Object.create polyfill for older environments. var create = Object.create || function(proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor }; // Used to create a custom walker. Will fill in all missing node // type properties with the defaults. function make(funcs, base) { if (!base) { base = exports.base; } var visitor = create(base); for (var type in funcs) { visitor[type] = funcs[type]; } return visitor } function skipThrough(node, st, c) { c(node, st); } function ignore(_node, _st, _c) {} // Node walkers. var base = {}; base.Program = base.BlockStatement = function (node, st, c) { for (var i = 0, list = node.body; i < list.length; i += 1) { var stmt = list[i]; c(stmt, st, "Statement"); } }; base.Statement = skipThrough; base.EmptyStatement = ignore; base.ExpressionStatement = base.ParenthesizedExpression = function (node, st, c) { return c(node.expression, st, "Expression"); }; base.IfStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Statement"); if (node.alternate) { c(node.alternate, st, "Statement"); } }; base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; base.BreakStatement = base.ContinueStatement = ignore; base.WithStatement = function (node, st, c) { c(node.object, st, "Expression"); c(node.body, st, "Statement"); }; base.SwitchStatement = function (node, st, c) { c(node.discriminant, st, "Expression"); for (var i = 0, list = node.cases; i < list.length; i += 1) { var cs = list[i]; if (cs.test) { c(cs.test, st, "Expression"); } for (var i$1 = 0, list$1 = cs.consequent; i$1 < list$1.length; i$1 += 1) { var cons = list$1[i$1]; c(cons, st, "Statement"); } } }; base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { if (node.argument) { c(node.argument, st, "Expression"); } }; base.ThrowStatement = base.SpreadElement = function (node, st, c) { return c(node.argument, st, "Expression"); }; base.TryStatement = function (node, st, c) { c(node.block, st, "Statement"); if (node.handler) { c(node.handler, st); } if (node.finalizer) { c(node.finalizer, st, "Statement"); } }; base.CatchClause = function (node, st, c) { c(node.param, st, "Pattern"); c(node.body, st, "ScopeBody"); }; base.WhileStatement = base.DoWhileStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.body, st, "Statement"); }; base.ForStatement = function (node, st, c) { if (node.init) { c(node.init, st, "ForInit"); } if (node.test) { c(node.test, st, "Expression"); } if (node.update) { c(node.update, st, "Expression"); } c(node.body, st, "Statement"); }; base.ForInStatement = base.ForOfStatement = function (node, st, c) { c(node.left, st, "ForInit"); c(node.right, st, "Expression"); c(node.body, st, "Statement"); }; base.ForInit = function (node, st, c) { if (node.type == "VariableDeclaration") { c(node, st); } else { c(node, st, "Expression"); } }; base.DebuggerStatement = ignore; base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; base.VariableDeclaration = function (node, st, c) { for (var i = 0, list = node.declarations; i < list.length; i += 1) { var decl = list[i]; c(decl, st); } }; base.VariableDeclarator = function (node, st, c) { c(node.id, st, "Pattern"); if (node.init) { c(node.init, st, "Expression"); } }; base.Function = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; c(param, st, "Pattern"); } c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody"); }; // FIXME drop these node types in next major version // (They are awkward, and in ES6 every block can be a scope.) base.ScopeBody = function (node, st, c) { return c(node, st, "Statement"); }; base.ScopeExpression = function (node, st, c) { return c(node, st, "Expression"); }; base.Pattern = function (node, st, c) { if (node.type == "Identifier") { c(node, st, "VariablePattern"); } else if (node.type == "MemberExpression") { c(node, st, "MemberPattern"); } else { c(node, st); } }; base.VariablePattern = ignore; base.MemberPattern = skipThrough; base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; base.ArrayPattern = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Pattern"); } } }; base.ObjectPattern = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; c(prop.value, st, "Pattern"); } }; base.Expression = skipThrough; base.ThisExpression = base.Super = base.MetaProperty = ignore; base.ArrayExpression = function (node, st, c) { for (var i = 0, list = node.elements; i < list.length; i += 1) { var elt = list[i]; if (elt) { c(elt, st, "Expression"); } } }; base.ObjectExpression = function (node, st, c) { for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; c(prop, st); } }; base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; base.SequenceExpression = base.TemplateLiteral = function (node, st, c) { for (var i = 0, list = node.expressions; i < list.length; i += 1) { var expr = list[i]; c(expr, st, "Expression"); } }; base.UnaryExpression = base.UpdateExpression = function (node, st, c) { c(node.argument, st, "Expression"); }; base.BinaryExpression = base.LogicalExpression = function (node, st, c) { c(node.left, st, "Expression"); c(node.right, st, "Expression"); }; base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { c(node.left, st, "Pattern"); c(node.right, st, "Expression"); }; base.ConditionalExpression = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Expression"); c(node.alternate, st, "Expression"); }; base.NewExpression = base.CallExpression = function (node, st, c) { c(node.callee, st, "Expression"); if (node.arguments) { for (var i = 0, list = node.arguments; i < list.length; i += 1) { var arg = list[i]; c(arg, st, "Expression"); } } }; base.MemberExpression = function (node, st, c) { c(node.object, st, "Expression"); if (node.computed) { c(node.property, st, "Expression"); } }; base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { if (node.declaration) { c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } if (node.source) { c(node.source, st, "Expression"); } }; base.ExportAllDeclaration = function (node, st, c) { c(node.source, st, "Expression"); }; base.ImportDeclaration = function (node, st, c) { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { var spec = list[i]; c(spec, st); } c(node.source, st, "Expression"); }; base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore; base.TaggedTemplateExpression = function (node, st, c) { c(node.tag, st, "Expression"); c(node.quasi, st); }; base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; base.Class = function (node, st, c) { if (node.id) { c(node.id, st, "Pattern"); } if (node.superClass) { c(node.superClass, st, "Expression"); } for (var i = 0, list = node.body.body; i < list.length; i += 1) { var item = list[i]; c(item, st); } }; base.MethodDefinition = base.Property = function (node, st, c) { if (node.computed) { c(node.key, st, "Expression"); } c(node.value, st, "Expression"); }; export { simple, ancestor, recursive, full, fullAncestor, findNodeAt, findNodeAround, findNodeAfter, findNodeBefore, make, base };
apache-2.0
gordoney/gzsito
libraries/legacy/table/menu.php
7316
<?php /** * @package Joomla.Legacy * @subpackage Table * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; use Joomla\Registry\Registry; /** * Menu table * * @since 11.1 */ class JTableMenu extends JTableNested { /** * Constructor * * @param JDatabaseDriver $db Database driver object. * * @since 11.1 */ public function __construct(JDatabaseDriver $db) { parent::__construct('#__menu', 'id', $db); // Set the default access level. $this->access = (int) JFactory::getConfig()->get('access'); } /** * Overloaded bind function * * @param array $array Named array * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. * * @return mixed Null if operation was satisfactory, otherwise returns an error * * @see JTable::bind() * @since 11.1 */ public function bind($array, $ignore = '') { // Verify that the default home menu is not unset if ($this->home == '1' && $this->language == '*' && ($array['home'] == '0')) { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_CANNOT_UNSET_DEFAULT_DEFAULT')); return false; } // Verify that the default home menu set to "all" languages" is not unset if ($this->home == '1' && $this->language == '*' && ($array['language'] != '*')) { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_CANNOT_UNSET_DEFAULT')); return false; } // Verify that the default home menu is not unpublished if ($this->home == '1' && $this->language == '*' && $array['published'] != '1') { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_UNPUBLISH_DEFAULT_HOME')); return false; } if (isset($array['params']) && is_array($array['params'])) { $registry = new Registry; $registry->loadArray($array['params']); $array['params'] = (string) $registry; } return parent::bind($array, $ignore); } /** * Overloaded check function * * @return boolean True on success * * @see JTable::check() * @since 11.1 */ public function check() { // Check for a title. if (trim($this->title) == '') { $this->setError(JText::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_MENUITEM')); return false; } // Set correct component id to ensure proper 404 messages with separator items if ($this->type == "separator") { $this->component_id = 0; } // Check for a path. if (trim($this->path) == '') { $this->path = $this->alias; } // Check for params. if (trim($this->params) == '') { $this->params = '{}'; } // Check for img. if (trim($this->img) == '') { $this->img = ' '; } // Cast the home property to an int for checking. $this->home = (int) $this->home; // Verify that a first level menu item alias is not 'component'. if ($this->parent_id == 1 && $this->alias == 'component') { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_ROOT_ALIAS_COMPONENT')); return false; } // Verify that a first level menu item alias is not the name of a folder. jimport('joomla.filesystem.folder'); if ($this->parent_id == 1 && in_array($this->alias, JFolder::folders(JPATH_ROOT))) { $this->setError(JText::sprintf('JLIB_DATABASE_ERROR_MENU_ROOT_ALIAS_FOLDER', $this->alias, $this->alias)); return false; } // Verify that the home item a component. if ($this->home && $this->type != 'component') { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_HOME_NOT_COMPONENT')); return false; } return true; } /** * Overloaded store function * * @param boolean $updateNulls True to update fields even if they are null. * * @return mixed False on failure, positive integer on success. * * @see JTable::store() * @since 11.1 */ public function store($updateNulls = false) { $db = JFactory::getDbo(); // Verify that the alias is unique $table = JTable::getInstance('Menu', 'JTable', array('dbo' => $this->getDbo())); $originalAlias = trim($this->alias); $this->alias = !$originalAlias ? $this->title : $originalAlias; $this->alias = JApplicationHelper::stringURLSafe(trim($this->alias), $this->language); // If alias still empty (for instance, new menu item with chinese characters with no unicode alias setting). if (empty($this->alias)) { $this->alias = JFactory::getDate()->format('Y-m-d-H-i-s'); } else { $itemSearch = array('alias' => $this->alias, 'parent_id' => $this->parent_id, 'client_id' => (int) $this->client_id); $errorType = ''; // Check if the alias already exists. For multilingual site. if (JLanguageMultilang::isEnabled()) { // If not exists a menu item at the same level with the same alias (in the All or the same language). if (($table->load(array_replace($itemSearch, array('language' => '*'))) && ($table->id != $this->id || $this->id == 0)) || ($table->load(array_replace($itemSearch, array('language' => $this->language))) && ($table->id != $this->id || $this->id == 0)) || ($this->language == '*' && $table->load($itemSearch) && ($table->id != $this->id || $this->id == 0))) { $errorType = 'MULTILINGUAL'; } } // Check if the alias already exists. For monolingual site. else { // If not exists a menu item at the same level with the same alias (in any language). if ($table->load($itemSearch) && ($table->id != $this->id || $this->id == 0)) { $errorType = 'MONOLINGUAL'; } } // The alias already exists. Send an error message. if ($errorType) { $message = JText::_('JLIB_DATABASE_ERROR_MENU_UNIQUE_ALIAS' . ($this->menutype != $table->menutype ? '_ROOT' : '')); $this->setError($message); return false; } } if ($this->home == '1') { // Verify that the home page for this menu is unique. if ($table->load( array( 'menutype' => $this->menutype, 'client_id' => (int) $this->client_id, 'home' => '1' ) ) && ($table->language != $this->language)) { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_HOME_NOT_UNIQUE_IN_MENU')); return false; } // Verify that the home page for this language is unique if ($table->load(array('home' => '1', 'language' => $this->language))) { if ($table->checked_out && $table->checked_out != $this->checked_out) { $this->setError(JText::_('JLIB_DATABASE_ERROR_MENU_DEFAULT_CHECKIN_USER_MISMATCH')); return false; } $table->home = 0; $table->checked_out = 0; $table->checked_out_time = $db->getNullDate(); $table->store(); } } if (!parent::store($updateNulls)) { return false; } // Get the new path in case the node was moved $pathNodes = $this->getPath(); $segments = array(); foreach ($pathNodes as $node) { // Don't include root in path if ($node->alias != 'root') { $segments[] = $node->alias; } } $newPath = trim(implode('/', $segments), ' /\\'); // Use new path for partial rebuild of table // Rebuild will return positive integer on success, false on failure return ($this->rebuild($this->{$this->_tbl_key}, $this->lft, $this->level, $newPath) > 0); } }
gpl-2.0
infobip/infobip-open-jdk-8
nashorn/docs/source/RunnableImpl.java
2590
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. 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 Oracle 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. */ import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; @SuppressWarnings("javadoc") public class RunnableImpl { public static void main(final String[] args) throws Exception { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByName("nashorn"); // JavaScript code in a String final String script = "function run() { print('run called'); }"; // evaluate script engine.eval(script); final Invocable inv = (Invocable) engine; // get Runnable interface object from engine. This interface methods // are implemented by script functions with the matching name. final Runnable r = inv.getInterface(Runnable.class); // start a new thread that runs the script implemented // runnable interface final Thread th = new Thread(r); th.start(); th.join(); } }
gpl-2.0
lluisanunez/goodmood
mod/workshop/exassessment.php
8578
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Assess an example submission * * @package mod * @subpackage workshop * @copyright 2009 David Mudrak <david.mudrak@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); require_once(dirname(__FILE__).'/locallib.php'); $asid = required_param('asid', PARAM_INT); // assessment id $assessment = $DB->get_record('workshop_assessments', array('id' => $asid), '*', MUST_EXIST); $example = $DB->get_record('workshop_submissions', array('id' => $assessment->submissionid, 'example' => 1), '*', MUST_EXIST); $workshop = $DB->get_record('workshop', array('id' => $example->workshopid), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $workshop->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('workshop', $workshop->id, $course->id, false, MUST_EXIST); require_login($course, false, $cm); if (isguestuser()) { print_error('guestsarenotallowed'); } $workshop = new workshop($workshop, $cm, $course); $PAGE->set_url($workshop->exassess_url($assessment->id)); $PAGE->set_title($workshop->name); $PAGE->set_heading($course->fullname); $PAGE->navbar->add(get_string('assessingexample', 'workshop')); $currenttab = 'assessment'; $canmanage = has_capability('mod/workshop:manageexamples', $workshop->context); $isreviewer = ($USER->id == $assessment->reviewerid); if ($isreviewer or $canmanage) { // such a user can continue } else { print_error('nopermissions', 'error', $workshop->view_url(), 'assess example submission'); } // only the reviewer is allowed to modify the assessment if (($canmanage and $assessment->weight == 1) or ($isreviewer and $workshop->assessing_examples_allowed())) { $assessmenteditable = true; } else { $assessmenteditable = false; } // load the grading strategy logic $strategy = $workshop->grading_strategy_instance(); // load the assessment form and process the submitted data eventually $mform = $strategy->get_assessment_form($PAGE->url, 'assessment', $assessment, $assessmenteditable); // Set data managed by the workshop core, subplugins set their own data themselves. $currentdata = (object)array( 'feedbackauthor' => $assessment->feedbackauthor, 'feedbackauthorformat' => $assessment->feedbackauthorformat, ); if ($assessmenteditable and $workshop->overallfeedbackmode) { $currentdata = file_prepare_standard_editor($currentdata, 'feedbackauthor', $workshop->overall_feedback_content_options(), $workshop->context, 'mod_workshop', 'overallfeedback_content', $assessment->id); if ($workshop->overallfeedbackfiles) { $currentdata = file_prepare_standard_filemanager($currentdata, 'feedbackauthorattachment', $workshop->overall_feedback_attachment_options(), $workshop->context, 'mod_workshop', 'overallfeedback_attachment', $assessment->id); } } $mform->set_data($currentdata); if ($mform->is_cancelled()) { redirect($workshop->view_url()); } elseif ($assessmenteditable and ($data = $mform->get_data())) { if ($canmanage) { if (is_null($assessment->grade)) { $workshop->log('add reference assessment', $workshop->exassess_url($assessment->id), $assessment->submissionid); } else { $workshop->log('update reference assessment', $workshop->exassess_url($assessment->id), $assessment->submissionid); } } else { if (is_null($assessment->grade)) { $workshop->log('add example assessment', $workshop->exassess_url($assessment->id), $assessment->submissionid); } else { $workshop->log('update example assessment', $workshop->exassess_url($assessment->id), $assessment->submissionid); } } // Let the grading strategy subplugin save its data. $rawgrade = $strategy->save_assessment($assessment, $data); // Store the data managed by the workshop core. $coredata = (object)array('id' => $assessment->id); if (isset($data->feedbackauthor_editor)) { $coredata->feedbackauthor_editor = $data->feedbackauthor_editor; $coredata = file_postupdate_standard_editor($coredata, 'feedbackauthor', $workshop->overall_feedback_content_options(), $workshop->context, 'mod_workshop', 'overallfeedback_content', $assessment->id); unset($coredata->feedbackauthor_editor); } if (isset($data->feedbackauthorattachment_filemanager)) { $coredata->feedbackauthorattachment_filemanager = $data->feedbackauthorattachment_filemanager; $coredata = file_postupdate_standard_filemanager($coredata, 'feedbackauthorattachment', $workshop->overall_feedback_attachment_options(), $workshop->context, 'mod_workshop', 'overallfeedback_attachment', $assessment->id); unset($coredata->feedbackauthorattachment_filemanager); if (empty($coredata->feedbackauthorattachment)) { $coredata->feedbackauthorattachment = 0; } } if ($canmanage) { // Remember the last one who edited the reference assessment. $coredata->reviewerid = $USER->id; } $DB->update_record('workshop_assessments', $coredata); if (!is_null($rawgrade) and isset($data->saveandclose)) { if ($canmanage) { redirect($workshop->view_url()); } else { redirect($workshop->excompare_url($example->id, $assessment->id)); } } else { // either it is not possible to calculate the $rawgrade // or the reviewer has chosen "Save and continue" redirect($PAGE->url); } } // output starts here $output = $PAGE->get_renderer('mod_workshop'); // workshop renderer echo $output->header(); echo $output->heading(get_string('assessedexample', 'workshop'), 2); $example = $workshop->get_example_by_id($example->id); // reload so can be passed to the renderer echo $output->render($workshop->prepare_example_submission(($example))); // show instructions for assessing as thay may contain important information // for evaluating the assessment if (trim($workshop->instructreviewers)) { $instructions = file_rewrite_pluginfile_urls($workshop->instructreviewers, 'pluginfile.php', $PAGE->context->id, 'mod_workshop', 'instructreviewers', 0, workshop::instruction_editors_options($PAGE->context)); print_collapsible_region_start('', 'workshop-viewlet-instructreviewers', get_string('instructreviewers', 'workshop')); echo $output->box(format_text($instructions, $workshop->instructreviewersformat, array('overflowdiv'=>true)), array('generalbox', 'instructions')); print_collapsible_region_end(); } // extend the current assessment record with user details $assessment = $workshop->get_assessment_by_id($assessment->id); if ($canmanage and $assessment->weight == 1) { $options = array( 'showreviewer' => false, 'showauthor' => false, 'showform' => true, ); $assessment = $workshop->prepare_example_reference_assessment($assessment, $mform, $options); $assessment->title = get_string('assessmentreference', 'workshop'); echo $output->render($assessment); } else if ($isreviewer) { $options = array( 'showreviewer' => true, 'showauthor' => false, 'showform' => true, ); $assessment = $workshop->prepare_example_assessment($assessment, $mform, $options); $assessment->title = get_string('assessmentbyyourself', 'workshop'); echo $output->render($assessment); } else if ($canmanage) { $options = array( 'showreviewer' => true, 'showauthor' => false, 'showform' => true, 'showweight' => false, ); $assessment = $workshop->prepare_example_assessment($assessment, $mform, $options); echo $output->render($assessment); } echo $output->footer();
gpl-3.0
nasomi/darkstar
scripts/globals/items/boiled_crayfish.lua
1248
----------------------------------------- -- ID: 4535 -- Item: Boiled Crayfish -- Food Effect: 30Min, All Races ----------------------------------------- -- defense % 30 -- defense % 25 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4535); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_DEFP, 30); target:addMod(MOD_FOOD_DEF_CAP, 25); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_DEFP, 30); target:delMod(MOD_FOOD_DEF_CAP, 25); end;
gpl-3.0
eripahle/framework
Samples/Neuro/Classification (ANN)/AboutBox.cs
3339
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Reflection; using System.Windows.Forms; namespace SampleApp { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; this.textBoxDescription.Text = AssemblyDescription; } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion } }
lgpl-2.1
nkubala/container-diff
vendor/github.com/google/go-github/github/issues_events.go
4746
// Copyright 2014 The go-github AUTHORS. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package github import ( "context" "fmt" "time" ) // IssueEvent represents an event that occurred around an Issue or Pull Request. type IssueEvent struct { ID *int64 `json:"id,omitempty"` URL *string `json:"url,omitempty"` // The User that generated this event. Actor *User `json:"actor,omitempty"` // Event identifies the actual type of Event that occurred. Possible // values are: // // closed // The Actor closed the issue. // If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit. // // merged // The Actor merged into master a branch containing a commit mentioning the issue. // CommitID holds the SHA1 of the merge commit. // // referenced // The Actor committed to master a commit mentioning the issue in its commit message. // CommitID holds the SHA1 of the commit. // // reopened, unlocked // The Actor did that to the issue. // // locked // The Actor locked the issue. // LockReason holds the reason of locking the issue (if provided while locking). // // renamed // The Actor changed the issue title from Rename.From to Rename.To. // // mentioned // Someone unspecified @mentioned the Actor [sic] in an issue comment body. // // assigned, unassigned // The Assigner assigned the issue to or removed the assignment from the Assignee. // // labeled, unlabeled // The Actor added or removed the Label from the issue. // // milestoned, demilestoned // The Actor added or removed the issue from the Milestone. // // subscribed, unsubscribed // The Actor subscribed to or unsubscribed from notifications for an issue. // // head_ref_deleted, head_ref_restored // The pull request’s branch was deleted or restored. // Event *string `json:"event,omitempty"` CreatedAt *time.Time `json:"created_at,omitempty"` Issue *Issue `json:"issue,omitempty"` // Only present on certain events; see above. Assignee *User `json:"assignee,omitempty"` Assigner *User `json:"assigner,omitempty"` CommitID *string `json:"commit_id,omitempty"` Milestone *Milestone `json:"milestone,omitempty"` Label *Label `json:"label,omitempty"` Rename *Rename `json:"rename,omitempty"` LockReason *string `json:"lock_reason,omitempty"` } // ListIssueEvents lists events for the specified issue. // // GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%v/events", owner, repo, number) u, err := addOptions(u, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } req.Header.Set("Accept", mediaTypeLockReasonPreview) var events []*IssueEvent resp, err := s.client.Do(ctx, req, &events) if err != nil { return nil, resp, err } return events, resp, nil } // ListRepositoryEvents lists events for the specified repository. // // GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) u, err := addOptions(u, opt) if err != nil { return nil, nil, err } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } var events []*IssueEvent resp, err := s.client.Do(ctx, req, &events) if err != nil { return nil, resp, err } return events, resp, nil } // GetEvent returns the specified issue event. // // GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event func (s *IssuesService) GetEvent(ctx context.Context, owner, repo string, id int64) (*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/events/%v", owner, repo, id) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } event := new(IssueEvent) resp, err := s.client.Do(ctx, req, event) if err != nil { return nil, resp, err } return event, resp, nil } // Rename contains details for 'renamed' events. type Rename struct { From *string `json:"from,omitempty"` To *string `json:"to,omitempty"` } func (r Rename) String() string { return Stringify(r) }
apache-2.0
txominpelu/airflow
tests/__init__.py
59
from __future__ import absolute_import from .core import *
apache-2.0
yynil/elasticsearch
plugins/store-smb/src/test/java/org/elasticsearch/index/store/AbstractAzureFsTestCase.java
1747
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.store; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.plugin.store.smb.SMBStorePlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import java.util.Collection; import static org.hamcrest.Matchers.is; abstract public class AbstractAzureFsTestCase extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return pluginList(SMBStorePlugin.class); } public void testAzureFs() { // Create an index and index some documents createIndex("test"); long nbDocs = randomIntBetween(10, 1000); for (long i = 0; i < nbDocs; i++) { index("test", "doc", "" + i, "foo", "bar"); } refresh(); SearchResponse response = client().prepareSearch("test").get(); assertThat(response.getHits().totalHits(), is(nbDocs)); } }
apache-2.0
makhdumi/azure-sdk-for-net
src/ServiceManagement/HDInsight/Microsoft.WindowsAzure.Management.HDInsight/HDInsightClient.cs
43792
// Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. namespace Microsoft.WindowsAzure.Management.HDInsight { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Hadoop.Client; using Microsoft.Hadoop.Client.WebHCatRest; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.ClusterManager; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.LocationFinder; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.IaasClusters; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.PocoClient.PaasClusters; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.ResourceTypeFinder; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.RestClient; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.VersionFinder; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.WebRequest; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Retries; using Microsoft.WindowsAzure.Management.HDInsight.Framework.ServiceLocation; using Microsoft.WindowsAzure.Management.HDInsight.Logging; /// <inheritdoc /> [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "DisposableObject implements IDisposable correctly, the implementation of IDisposable in the interfaces is necessary for the design.")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This complexity is needed to handle all the operations.")] public sealed class HDInsightClient : ClientBase, IHDInsightClient { private readonly Lazy<bool> canUseClustersContract; private Lazy<List<string>> capabilities; /// <summary> /// Default HDInsight version. /// </summary> internal const string DEFAULTHDINSIGHTVERSION = "default"; internal const string ClustersContractCapabilityVersion1 = "CAPABILITY_FEATURE_CLUSTERS_CONTRACT_1_SDK"; internal static string ClustersContractCapabilityVersion2 = "CAPABILITY_FEATURE_CLUSTERS_CONTRACT_2_SDK"; internal static string IaasClustersCapability = "CAPABILITY_FEATURE_IAAS_DEPLOYMENTS"; internal const string ClusterAlreadyExistsError = "The condition specified by the ETag is not satisfied."; private IHDInsightSubscriptionCredentials credentials; private ClusterDetails currentDetails; private const string DefaultSchemaVersion = "1.0"; private TimeSpan defaultResizeTimeout = TimeSpan.FromHours(1); /// <summary> /// Gets the connection credential. /// </summary> public IHDInsightSubscriptionCredentials Credentials { get { return this.credentials; } } /// <inheritdoc /> public TimeSpan PollingInterval { get; set; } /// <inheritdoc /> internal static TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(30); /// <summary> /// Initializes a new instance of the HDInsightClient class. /// </summary> /// <param name="credentials">The credential to use when operating against the service.</param> /// <param name="httpOperationTimeout">The HTTP operation timeout.</param> /// <param name="policy">The retry policy.</param> /// <exception cref="System.InvalidOperationException">Unable to connect to the HDInsight subscription with the supplied type of credential.</exception> internal HDInsightClient(IHDInsightSubscriptionCredentials credentials, TimeSpan? httpOperationTimeout = null, IRetryPolicy policy = null) : base(httpOperationTimeout, policy) { var asCertificateCredentials = credentials; if (asCertificateCredentials.IsNull()) { throw new InvalidOperationException("Unable to connect to the HDInsight subscription with the supplied type of credential"); } this.credentials = ServiceLocator.Instance.Locate<IHDInsightSubscriptionCredentialsFactory>().Create(asCertificateCredentials); this.capabilities = new Lazy<List<string>>(this.GetCapabilities); this.canUseClustersContract = new Lazy<bool>(this.CanUseClustersContract); this.PollingInterval = DefaultPollingInterval; } /// <summary> /// Connects to an HDInsight subscription. /// </summary> /// <param name="credentials"> /// The credential used to connect to the subscription. /// </param> /// <returns> /// A new HDInsight client. /// </returns> public static IHDInsightClient Connect(IHDInsightSubscriptionCredentials credentials) { return ServiceLocator.Instance.Locate<IHDInsightClientFactory>().Create(credentials); } /// <summary> /// Connects the specified credentials. /// </summary> /// <param name="credentials">The credential used to connect to the subscription.</param> /// <param name="httpOperationTimeout">The HTTP operation timeout.</param> /// <param name="policy">The retry policy to use for operations on this client.</param> /// <returns> /// A new HDInsight client. /// </returns> public static IHDInsightClient Connect(IHDInsightSubscriptionCredentials credentials, TimeSpan httpOperationTimeout, IRetryPolicy policy) { return ServiceLocator.Instance.Locate<IHDInsightClientFactory>().Create(credentials, httpOperationTimeout, policy); } /// <inheritdoc /> public event EventHandler<ClusterProvisioningStatusEventArgs> ClusterProvisioning; /// <inheritdoc /> public async Task<Collection<string>> ListAvailableLocationsAsync() { return await ListAvailableLocationsAsync(OSType.Windows); } /// <inheritdoc /> public async Task<Collection<string>> ListAvailableLocationsAsync(OSType osType) { var client = ServiceLocator.Instance.Locate<ILocationFinderClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); switch (osType) { case OSType.Windows: return await client.ListAvailableLocations(); case OSType.Linux: return await client.ListAvailableIaasLocations(); default: throw new InvalidProgramException(String.Format("Encountered unhandled value for OSType: {0}", osType)); } } /// <inheritdoc /> public async Task<IEnumerable<KeyValuePair<string, string>>> ListResourceProviderPropertiesAsync() { var client = ServiceLocator.Instance.Locate<IRdfeServiceRestClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); return await client.GetResourceProviderProperties(); } /// <inheritdoc /> public async Task<Collection<HDInsightVersion>> ListAvailableVersionsAsync() { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); return await overrideHandlers.VersionFinder.ListAvailableVersions(); } /// <inheritdoc /> public async Task<ICollection<ClusterDetails>> ListClustersAsync() { ICollection<ClusterDetails> allClusters; // List all clusters using the containers client using (var client = this.CreateContainersPocoClient()) { allClusters = await client.ListContainers(); } // List all clusters using the clusters client if (this.canUseClustersContract.Value) { using (var client = this.CreateClustersPocoClient(this.capabilities.Value)) { var clusters = await client.ListContainers(); allClusters = clusters.Concat(allClusters).ToList(); } } // List all clusters using the iaas clusters client if (this.HasIaasCapability()) { using (var client = this.CreateIaasClustersPocoClient(this.capabilities.Value)) { var iaasClusters = await client.ListContainers(); allClusters = iaasClusters.Concat(allClusters).ToList(); } } return allClusters; } /// <inheritdoc /> public async Task<ClusterDetails> GetClusterAsync(string name) { if (name == null) { throw new ArgumentNullException("name"); } try { using (var client = this.CreatePocoClientForDnsName(name)) { return await client.ListContainer(name); } } catch (HDInsightClusterDoesNotExistException) { //The semantics of this method is that if a cluster doesn't exist we return null return null; } } /// <inheritdoc /> public async Task<ClusterDetails> GetClusterAsync(string name, string location) { if (name == null) { throw new ArgumentNullException("name"); } if (location == null) { throw new ArgumentNullException("location"); } try { using (var client = this.CreatePocoClientForDnsName(name)) { return await client.ListContainer(name, location); } } catch (HDInsightClusterDoesNotExistException) { //The semantics of this method is that if a cluster doesn't exist we return null return null; } } public async Task<ClusterDetails> CreateClusterAsync(ClusterCreateParameters clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } var createParamsV2 = new ClusterCreateParametersV2(clusterCreateParameters); return await CreateClusterAsync(createParamsV2); } /// <inheritdoc /> public async Task<ClusterDetails> CreateClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters.OSType == OSType.Linux) { return await this.CreateIaasClusterAsync(clusterCreateParameters); } else { return await this.CreatePaasClusterAsync(clusterCreateParameters); } } private async Task<ClusterDetails> CreatePaasClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } IHDInsightManagementPocoClient client = null; if (!this.canUseClustersContract.Value) { client = this.CreateContainersPocoClient(); } else { client = this.CreateClustersPocoClient(this.capabilities.Value); } this.LogMessage("Validating Cluster Versions", Severity.Informational, Verbosity.Detailed); await this.ValidateClusterVersion(clusterCreateParameters); // listen to cluster provisioning events on the POCO client. client.ClusterProvisioning += this.RaiseClusterProvisioningEvent; Exception requestException = null; // Creates a cluster and waits for it to complete try { this.LogMessage("Sending Cluster Create Request", Severity.Informational, Verbosity.Detailed); await client.CreateContainer(clusterCreateParameters); } catch (Exception ex) { ex = ex.GetFirstException(); var hlex = ex as HttpLayerException; var httpEx = ex as HttpRequestException; var webex = ex as WebException; if (hlex.IsNotNull() || httpEx.IsNotNull() || webex.IsNotNull()) { requestException = ex; if (hlex.IsNotNull()) { HandleCreateHttpLayerException(clusterCreateParameters, hlex); } } else { throw; } } await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, clusterCreateParameters.Name, clusterCreateParameters.Location, clusterCreateParameters.CreateTimeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); // Validates that cluster didn't get on error state var result = this.currentDetails; if (result == null) { if (requestException != null) { throw requestException; } throw new HDInsightClusterCreateException("Attempting to return the newly created cluster returned no cluster. The cluster could not be found."); } if (result.Error != null) { throw new HDInsightClusterCreateException(result); } return result; } private async Task<ClusterDetails> CreateIaasClusterAsync(ClusterCreateParametersV2 clusterCreateParameters) { if (clusterCreateParameters == null) { throw new ArgumentNullException("clusterCreateParameters"); } // Validate cluster creation parameters clusterCreateParameters.ValidateClusterCreateParameters(); this.LogMessage("Validating Cluster Versions", Severity.Informational, Verbosity.Detailed); await this.ValidateClusterVersion(clusterCreateParameters); IHDInsightManagementPocoClient client = this.CreateIaasClustersPocoClient(this.capabilities.Value); // listen to cluster provisioning events on the POCO client. client.ClusterProvisioning += this.RaiseClusterProvisioningEvent; Exception requestException = null; // Creates a cluster and waits for it to complete try { this.LogMessage("Sending Cluster Create Request", Severity.Informational, Verbosity.Detailed); await client.CreateContainer(clusterCreateParameters); } catch (Exception ex) { ex = ex.GetFirstException(); var hlex = ex as HttpLayerException; var httpEx = ex as HttpRequestException; var webex = ex as WebException; if (hlex.IsNotNull() || httpEx.IsNotNull() || webex.IsNotNull()) { requestException = ex; if (hlex.IsNotNull()) { HandleCreateHttpLayerException(clusterCreateParameters, hlex); } } else { throw; } } await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, clusterCreateParameters.Name, clusterCreateParameters.Location, clusterCreateParameters.CreateTimeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); // Validates that cluster didn't get on error state var result = this.currentDetails; if (result == null) { if (requestException != null) { throw requestException; } throw new HDInsightClusterCreateException("Attempting to return the newly created cluster returned no cluster. The cluster could not be found."); } if (result.Error != null) { throw new HDInsightClusterCreateException(result); } return result; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private bool CanUseClustersContract() { string clustersCapability; SchemaVersionUtils.SupportedSchemaVersions.TryGetValue(1, out clustersCapability); bool retval = this.capabilities.Value.Contains(clustersCapability); this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Clusters resource type is enabled '{0}'", retval), Severity.Critical, Verbosity.Detailed); return retval; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private bool HasIaasCapability() { bool retval = this.capabilities.Value.Contains(IaasClustersCapability); this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Iaas Clusters resource type is enabled '{0}'", retval), Severity.Critical, Verbosity.Detailed); return retval; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "They are not", MessageId = "Microsoft.WindowsAzure.Management.HDInsight.Logging.LogProviderExtensions.LogMessage(Microsoft.WindowsAzure.Management.HDInsight.Logging.ILogProvider,System.String,Microsoft.WindowsAzure.Management.HDInsight.Logging.Severity,Microsoft.WindowsAzure.Management.HDInsight.Logging.Verbosity)")] private List<string> GetCapabilities() { this.LogMessage(string.Format(CultureInfo.InvariantCulture, "Fetching resource provider properties for subscription '{0}'.", this.credentials.SubscriptionId), Severity.Critical, Verbosity.Detailed); List<KeyValuePair<string, string>> props = this.ListResourceProviderProperties().ToList(); return props.Select(p => p.Key).ToList(); } private IHDInsightManagementPocoClient CreateClustersPocoClient(List<string> capabilities) { return new PaasClustersPocoClient(this.credentials, this.IgnoreSslErrors, this.Context, capabilities); } private IHDInsightManagementPocoClient CreateIaasClustersPocoClient(List<string> capabilities) { return new IaasClustersPocoClient(this.credentials, this.IgnoreSslErrors, this.Context, capabilities); } private IHDInsightManagementPocoClient CreateContainersPocoClient() { return ServiceLocator.Instance.Locate<IHDInsightManagementPocoClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); } private IHDInsightManagementPocoClient CreatePocoClientForDnsName(string dnsName) { if (this.canUseClustersContract.Value) { var rdfeResourceTypeFinder = ServiceLocator.Instance.Locate<IRdfeResourceTypeFinderFactory>() .Create(this.credentials, this.Context, this.IgnoreSslErrors, DefaultSchemaVersion); var rdfeResourceType = rdfeResourceTypeFinder.GetResourceTypeForCluster(dnsName).Result; switch (rdfeResourceType) { case RdfeResourceType.Clusters: return this.CreateClustersPocoClient(this.capabilities.Value); case RdfeResourceType.Containers: return this.CreateContainersPocoClient(); case RdfeResourceType.IaasClusters: return this.CreateIaasClustersPocoClient(this.capabilities.Value); default: throw new HDInsightClusterDoesNotExistException(dnsName); } } return this.CreateContainersPocoClient(); } private static void HandleCreateHttpLayerException(ClusterCreateParametersV2 clusterCreateParameters, HttpLayerException e) { if (e.RequestContent.Contains(ClusterAlreadyExistsError) && e.RequestStatusCode == HttpStatusCode.BadRequest) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cluster {0} already exists.", clusterCreateParameters.Name)); } } /// <summary> /// Raises the cluster provisioning event. /// </summary> /// <param name="sender">The IHDInsightManagementPocoClient instance.</param> /// <param name="e">EventArgs for the event.</param> public void RaiseClusterProvisioningEvent(object sender, ClusterProvisioningStatusEventArgs e) { var handler = this.ClusterProvisioning; if (handler.IsNotNull()) { handler(sender, e); } } /// <summary> /// Used to handle the notification events during waiting. /// </summary> /// <param name="cluster"> /// The cluster in its current state. /// </param> public void HandleClusterWaitNotifyEvent(ClusterDetails cluster) { if (cluster.IsNotNull()) { this.currentDetails = cluster; this.RaiseClusterProvisioningEvent(this, new ClusterProvisioningStatusEventArgs(cluster, cluster.State)); } } /// <inheritdoc /> public async Task DeleteClusterAsync(string name) { if (name == null) { throw new ArgumentNullException("name"); } var client = this.CreatePocoClientForDnsName(name); await client.DeleteContainer(name); await client.WaitForClusterNull(name, TimeSpan.FromMinutes(30), this.PollingInterval, this.Context.CancellationToken); } /// <inheritdoc /> public async Task DeleteClusterAsync(string name, string location) { if (name == null) { throw new ArgumentNullException("name"); } if (location == null) { throw new ArgumentNullException("location"); } var client = this.CreatePocoClientForDnsName(name); await client.DeleteContainer(name, location); await client.WaitForClusterNull(name, location, TimeSpan.FromMinutes(30), this.Context.CancellationToken); } /// <inheritdoc /> public async Task EnableHttpAsync(string dnsName, string location, string httpUserName, string httpPassword) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); httpUserName.ArgumentNotNullOrEmpty("httpUserName"); httpPassword.ArgumentNotNullOrEmpty("httpPassword"); using (var client = this.CreatePocoClientForDnsName(dnsName)) { await this.AssertClusterVersionSupported(dnsName); var operationId = await client.EnableHttp(dnsName, location, httpUserName, httpPassword); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, this.PollingInterval, TimeSpan.FromHours(1), this.Context.CancellationToken); } } /// <inheritdoc /> public void DisableHttp(string dnsName, string location) { this.DisableHttpAsync(dnsName, location).WaitForResult(); } public void EnableRdp(string dnsName, string location, string rdpUserName, string rdpPassword, DateTime expiry) { this.EnableRdpAsync(dnsName, location, rdpUserName, rdpPassword, expiry).WaitForResult(); } public void DisableRdp(string dnsName, string location) { this.DisableRdpAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public void EnableHttp(string dnsName, string location, string httpUserName, string httpPassword) { this.EnableHttpAsync(dnsName, location, httpUserName, httpPassword).WaitForResult(); } /// <inheritdoc /> public async Task DisableHttpAsync(string dnsName, string location) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); using (var client = this.CreatePocoClientForDnsName(dnsName)) { await this.AssertClusterVersionSupported(dnsName); var operationId = await client.DisableHttp(dnsName, location); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, this.PollingInterval, TimeSpan.FromHours(1), this.Context.CancellationToken); } } public async Task EnableRdpAsync(string dnsName, string location, string rdpUserName, string rdpPassword, DateTime expiry) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); rdpUserName.ArgumentNotNullOrEmpty("rdpUserName"); rdpPassword.ArgumentNotNullOrEmpty("rdpPassword"); if (expiry <= DateTime.Now) { throw new ArgumentOutOfRangeException("expiry",string.Format("DateTime expiry needs to be sometime in future. Given expiry: {0}",expiry.ToString())); } using (var client = this.CreatePocoClientForDnsName(dnsName)) { var operationId = await client.EnableRdp(dnsName, location, rdpUserName, rdpPassword, expiry); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, this.PollingInterval, TimeSpan.FromMinutes(10), this.Context.CancellationToken); } } public async Task DisableRdpAsync(string dnsName, string location) { dnsName.ArgumentNotNullOrEmpty("dnsName"); location.ArgumentNotNullOrEmpty("location"); using (var client = this.CreatePocoClientForDnsName(dnsName)) { var operationId = await client.DisableRdp(dnsName, location); await client.WaitForOperationCompleteOrError(dnsName, location, operationId, this.PollingInterval, TimeSpan.FromMinutes(10), this.Context.CancellationToken); } } /// <inheritdoc /> public Collection<string> ListAvailableLocations() { return this.ListAvailableLocationsAsync().WaitForResult(); } /// <inheritdoc /> public Collection<string> ListAvailableLocations(OSType osType) { return this.ListAvailableLocationsAsync(osType).WaitForResult(); } /// <inheritdoc /> public IEnumerable<KeyValuePair<string, string>> ListResourceProviderProperties() { var client = ServiceLocator.Instance.Locate<IRdfeServiceRestClientFactory>().Create(this.credentials, this.Context, this.IgnoreSslErrors); return client.GetResourceProviderProperties().WaitForResult(); } /// <inheritdoc /> public Collection<HDInsightVersion> ListAvailableVersions() { return this.ListAvailableVersionsAsync().WaitForResult(); } /// <inheritdoc /> public ICollection<ClusterDetails> ListClusters() { return this.ListClustersAsync().WaitForResult(); } /// <inheritdoc /> public ClusterDetails GetCluster(string dnsName) { return this.GetClusterAsync(dnsName).WaitForResult(); } /// <inheritdoc /> public ClusterDetails GetCluster(string dnsName, string location) { return this.GetClusterAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public ClusterDetails CreateCluster(ClusterCreateParameters cluster) { return this.CreateClusterAsync(new ClusterCreateParametersV2(cluster)).WaitForResult(); } /// <inheritdoc /> public ClusterDetails CreateCluster(ClusterCreateParameters cluster, TimeSpan timeout) { return this.CreateClusterAsync(new ClusterCreateParametersV2(cluster)).WaitForResult(timeout); } public ClusterDetails CreateCluster(ClusterCreateParametersV2 cluster) { return this.CreateClusterAsync(cluster).WaitForResult(); } public ClusterDetails CreateCluster(ClusterCreateParametersV2 cluster, TimeSpan timeout) { return this.CreateClusterAsync(cluster).WaitForResult(timeout); } /// <inheritdoc /> public ClusterDetails ChangeClusterSize(string dnsName, string location, int newSize) { return this.ChangeClusterSizeAsync(dnsName, location, newSize).WaitForResult(); } /// <inheritdoc /> public ClusterDetails ChangeClusterSize(string dnsName, string location, int newSize, TimeSpan timeout) { return this.ChangeClusterSizeAsync(dnsName, location, newSize, timeout).ConfigureAwait(false).GetAwaiter().GetResult(); } /// <inheritdoc /> public async Task<ClusterDetails> ChangeClusterSizeAsync(string dnsName, string location, int newSize) { return await ChangeClusterSizeAsync(dnsName, location, newSize, this.defaultResizeTimeout); } /// <inheritdoc /> public async Task<ClusterDetails> ChangeClusterSizeAsync(string dnsName, string location, int newSize, TimeSpan timeout) { dnsName.ArgumentNotNullOrEmpty("dnsName"); newSize.ArgumentNotNull("newSize"); location.ArgumentNotNull("location"); SchemaVersionUtils.EnsureSchemaVersionSupportsResize(this.capabilities.Value); var client = this.CreateClustersPocoClient(this.capabilities.Value); var operationId = Guid.Empty; try { this.LogMessage("Sending Change Cluster Size request.", Severity.Informational, Verbosity.Detailed); operationId = await client.ChangeClusterSize(dnsName, location, newSize); } catch (Exception ex) { this.LogMessage(ex.GetFirstException().Message, Severity.Error, Verbosity.Detailed); throw ex.GetFirstException(); } if (operationId == Guid.Empty) { return await client.ListContainer(dnsName); } await client.WaitForOperationCompleteOrError(dnsName, location, operationId, this.PollingInterval, timeout, this.Context.CancellationToken); await client.WaitForClusterInConditionOrError(this.HandleClusterWaitNotifyEvent, dnsName, location, timeout, this.PollingInterval, this.Context, ClusterState.Operational, ClusterState.Running); this.LogMessage("Validating that the cluster didn't go into an error state.", Severity.Informational, Verbosity.Detailed); var result = await client.ListContainer(dnsName); if (result == null) { throw new Exception(string.Format("Cluster {0} could not be found.", dnsName)); } if (result.Error != null) { this.LogMessage(result.Error.Message, Severity.Informational, Verbosity.Detailed); throw new Exception(result.Error.Message); } return result; } /// <inheritdoc /> public void DeleteCluster(string dnsName) { this.DeleteClusterAsync(dnsName).WaitForResult(); } /// <inheritdoc /> public void DeleteCluster(string dnsName, TimeSpan timeout) { this.DeleteClusterAsync(dnsName).WaitForResult(timeout); } /// <inheritdoc /> public void DeleteCluster(string dnsName, string location) { this.DeleteClusterAsync(dnsName, location).WaitForResult(); } /// <inheritdoc /> public void DeleteCluster(string dnsName, string location, TimeSpan timeout) { this.DeleteClusterAsync(dnsName, location).WaitForResult(timeout); } /// <summary> /// Encrypt payload string into a base 64-encoded string using the certificate. /// This is suitable for encrypting storage account keys for later use as a job argument. /// </summary> /// <param name="cert"> /// Certificate used to encrypt the payload. /// </param> /// <param name="payload"> /// Value to encrypt. /// </param> /// <returns> /// Encrypted payload. /// </returns> public static string EncryptAsBase64String(X509Certificate2 cert, string payload) { var ci = new ContentInfo(Encoding.UTF8.GetBytes(payload)); var env = new EnvelopedCms(ci); env.Encrypt(new CmsRecipient(cert)); return Convert.ToBase64String(env.Encode()); } // This method is used by the NonPublic SDK. Be aware of breaking changes to that project when you alter it. private async Task AssertClusterVersionSupported(string dnsName) { var cluster = await this.GetClusterAsync(dnsName); if (cluster == null) { throw new HDInsightClusterDoesNotExistException(dnsName); } if (cluster.State == ClusterState.Error) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cluster '{0}' is an error state. Performing operations other than delete are not possible.", dnsName)); } this.AssertSupportedVersion(cluster.VersionNumber); } private async Task ValidateClusterVersion(ClusterCreateParametersV2 cluster) { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); // Validates the version for cluster creation if (!string.IsNullOrEmpty(cluster.Version) && !string.Equals(cluster.Version, DEFAULTHDINSIGHTVERSION, StringComparison.OrdinalIgnoreCase)) { this.AssertSupportedVersion(overrideHandlers.PayloadConverter.ConvertStringToVersion(ClusterVersionUtils.TryGetVersionNumber(cluster.Version))); var availableVersions = await overrideHandlers.VersionFinder.ListAvailableVersions(); if (availableVersions.All(hdinsightVersion => hdinsightVersion.Version != ClusterVersionUtils.TryGetVersionNumber(cluster.Version))) { throw new InvalidOperationException( string.Format( "Cannot create a cluster with version '{0}'. Available Versions for your subscription are: {1}", cluster.Version, string.Join(",", availableVersions))); } // Clusters with OSType.Linux only supported from version 3.2 onwards var version = new Version(ClusterVersionUtils.TryGetVersionNumber(cluster.Version)); if (cluster.OSType == OSType.Linux && version.CompareTo(new Version("3.2")) < 0) { throw new NotSupportedException(string.Format("Clusters with OSType {0} are only supported from version 3.2", cluster.OSType)); } // HBase cluster only supported after version 3.0 if (version.CompareTo(new Version("3.0")) < 0 && cluster.ClusterType == ClusterType.HBase) { throw new InvalidOperationException( string.Format("Cannot create a HBase cluster with version '{0}'. HBase cluster only supported after version 3.0", cluster.Version)); } // Cluster customization only supported after version 3.0 if (version.CompareTo(new Version("3.0")) < 0 && cluster.ConfigActions != null && cluster.ConfigActions.Count > 0) { throw new InvalidOperationException( string.Format("Cannot create a customized cluster with version '{0}'. Customized clusters only supported after version 3.0", cluster.Version)); } // Various VM sizes only supported starting with version 3.1 if (version.CompareTo(new Version("3.1")) < 0 && createHasNewVMSizesSpecified(cluster)) { throw new InvalidOperationException( string.Format( "Cannot use various VM sizes with cluster version '{0}'. Custom VM sizes are only supported for cluster versions 3.1 and above.", cluster.Version)); } // Spark cluster only supported after version 3.2 if (version.CompareTo(new Version("3.2")) < 0 && cluster.ClusterType == ClusterType.Spark) { throw new InvalidOperationException( string.Format("Cannot create a Spark cluster with version '{0}'. Spark cluster only supported after version 3.2", cluster.Version)); } } else { cluster.Version = DEFAULTHDINSIGHTVERSION; } } private void AssertSupportedVersion(Version hdinsightClusterVersion) { var overrideHandlers = ServiceLocator.Instance.Locate<IHDInsightClusterOverrideManager>().GetHandlers(this.credentials, this.Context, this.IgnoreSslErrors); switch (overrideHandlers.VersionFinder.GetVersionStatus(hdinsightClusterVersion)) { case VersionStatus.Obsolete: throw new NotSupportedException( string.Format( CultureInfo.CurrentCulture, HDInsightConstants.ClusterVersionTooLowForClusterOperations, hdinsightClusterVersion.ToString(), HDInsightSDKSupportedVersions.MinVersion, HDInsightSDKSupportedVersions.MaxVersion)); case VersionStatus.ToolsUpgradeRequired: throw new NotSupportedException( string.Format( CultureInfo.CurrentCulture, HDInsightConstants.ClusterVersionTooHighForClusterOperations, hdinsightClusterVersion.ToString(), HDInsightSDKSupportedVersions.MinVersion, HDInsightSDKSupportedVersions.MaxVersion)); } } private bool createHasNewVMSizesSpecified(ClusterCreateParametersV2 clusterCreateParameters) { const string ExtraLarge = "ExtraLarge"; const string Large = "Large"; if (!new[] {Large, ExtraLarge}.Contains(clusterCreateParameters.HeadNodeSize, StringComparer.OrdinalIgnoreCase)) { return true; } if (!clusterCreateParameters.DataNodeSize.Equals(Large)) { return true; } return clusterCreateParameters.ZookeeperNodeSize != null; } } }
apache-2.0
xissburg/XDefrac
boost/algorithm/string/concept.hpp
2427
// Boost string_algo library concept.hpp header file ---------------------------// // Copyright Pavol Droba 2002-2003. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/ for updates, documentation, and revision history. #ifndef BOOST_STRING_CONCEPT_HPP #define BOOST_STRING_CONCEPT_HPP #include <boost/concept_check.hpp> #include <boost/range/iterator_range_core.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> /*! \file Defines concepts used in string_algo library */ namespace boost { namespace algorithm { //! Finder concept /*! Defines the Finder concept. Finder is a functor which selects an arbitrary part of a string. Search is performed on the range specified by starting and ending iterators. Result of the find operation must be convertible to iterator_range. */ template<typename FinderT, typename IteratorT> struct FinderConcept { private: typedef iterator_range<IteratorT> range; public: void constraints() { // Operation r=(*pF)(i,i); } private: range r; IteratorT i; FinderT* pF; }; // Finder_concept //! Formatter concept /*! Defines the Formatter concept. Formatter is a functor, which takes a result from a finder operation and transforms it in a specific way. Result must be a container supported by container_traits, or a reference to it. */ template<typename FormatterT, typename FinderT, typename IteratorT> struct FormatterConcept { public: void constraints() { // Operation ::boost::begin((*pFo)( (*pF)(i,i) )); ::boost::end((*pFo)( (*pF)(i,i) )); } private: IteratorT i; FinderT* pF; FormatterT *pFo; }; // FormatterConcept; } // namespace algorithm } // namespace boost #endif // BOOST_STRING_CONCEPT_HPP
mit
ghetolay/angular
packages/compiler/test/pipe_resolver_spec.ts
1538
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {PipeResolver} from '@angular/compiler/src/pipe_resolver'; import {ɵstringify as stringify} from '@angular/core'; import {Pipe} from '@angular/core/src/metadata'; import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_reflector'; @Pipe({name: 'somePipe', pure: true}) class SomePipe { } class SimpleClass {} { describe('PipeResolver', () => { let resolver: PipeResolver; beforeEach(() => { resolver = new PipeResolver(new JitReflector()); }); it('should read out the metadata from the class', () => { const moduleMetadata = resolver.resolve(SomePipe); expect(moduleMetadata).toEqual(new Pipe({name: 'somePipe', pure: true})); }); it('should throw when simple class has no pipe decorator', () => { expect(() => resolver.resolve(SimpleClass)) .toThrowError(`No Pipe decorator found on ${stringify(SimpleClass)}`); }); it('should support inheriting the metadata', function() { @Pipe({name: 'p'}) class Parent { } class ChildNoDecorator extends Parent {} @Pipe({name: 'c'}) class ChildWithDecorator extends Parent { } expect(resolver.resolve(ChildNoDecorator)).toEqual(new Pipe({name: 'p'})); expect(resolver.resolve(ChildWithDecorator)).toEqual(new Pipe({name: 'c'})); }); }); }
mit
holmari/robolectric
robolectric-resources/src/main/java/org/robolectric/res/XpathResourceXmlLoader.java
4180
package org.robolectric.res; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.VTDNav; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; import org.jetbrains.annotations.NotNull; import javax.xml.xpath.XPathExpressionException; public abstract class XpathResourceXmlLoader extends XmlLoader { private final String expression; public XpathResourceXmlLoader(String expression) { this.expression = expression; } @Override protected void processResourceXml(FsFile xmlFile, XmlNode xmlNode, XmlContext xmlContext) throws Exception { for (XmlNode node : xmlNode.selectByXpath(expression)) { String name = node.getAttrValue("name"); processNode(name, node, xmlContext); } } protected abstract void processNode(String name, XmlNode xmlNode, XmlContext xmlContext) throws XPathExpressionException; public static class XmlNode { private final VTDNav vtdNav; public XmlNode(VTDNav vtdNav) { this.vtdNav = vtdNav; } public String getElementName() { try { return vtdNav.toString(vtdNav.getCurrentIndex()); } catch (NavException e) { throw new RuntimeException(e); } } public XmlNode getFirstChild() { try { VTDNav cloneVtdNav = vtdNav.cloneNav(); if (!cloneVtdNav.toElement(VTDNav.FIRST_CHILD)) return null; return new XmlNode(cloneVtdNav); } catch (NavException e) { throw new RuntimeException(e); } } public String getTextContent() { try { return vtdNav.getXPathStringVal(); } catch (NavException e) { throw new RuntimeException(e); } } public Iterable<XmlNode> selectByXpath(String expr) throws XPathParseException { VTDNav cloneVtdNav = vtdNav.cloneNav(); final AutoPilot ap = new AutoPilot(cloneVtdNav); ap.selectXPath(expr); return returnIterable(new Iterator(ap, cloneVtdNav) { @Override boolean doHasNext() throws XPathEvalException, NavException { int result = ap.evalXPath(); if (result == -1) { ap.resetXPath(); } return result != -1; } }); } public Iterable<XmlNode> selectElements(String name) { VTDNav cloneVtdNav = vtdNav.cloneNav(); final AutoPilot ap = new AutoPilot(cloneVtdNav); ap.selectElement(name); return returnIterable(new Iterator(ap, cloneVtdNav) { @Override boolean doHasNext() throws XPathEvalException, NavException { return ap.iterate(); } }); } private Iterable<XmlNode> returnIterable(final Iterator iterator) { return new Iterable<XmlNode>() { @NotNull @Override public java.util.Iterator<XmlNode> iterator() { return iterator; } }; } public String getAttrValue(String attrName) { try { int nameIndex = vtdNav.getAttrVal(attrName); return nameIndex == -1 ? null : vtdNav.toNormalizedString(nameIndex); } catch (NavException e) { throw new RuntimeException(e); } } public void pushLocation() { vtdNav.push(); } public void popLocation() { vtdNav.pop(); } public boolean moveToParent() { try { return vtdNav.toElement(VTDNav.PARENT); } catch (NavException e) { throw new RuntimeException(e); } } private abstract class Iterator implements java.util.Iterator<XmlNode> { private final AutoPilot ap; private final VTDNav vtdNav; public Iterator(AutoPilot ap, VTDNav vtdNav) { this.ap = ap; this.vtdNav = vtdNav; } @Override public boolean hasNext() { try { return doHasNext(); } catch (XPathEvalException | NavException e) { throw new RuntimeException(e); } } abstract boolean doHasNext() throws XPathEvalException, NavException; @Override public XmlNode next() { return new XmlNode(vtdNav); } @Override public void remove() { throw new UnsupportedOperationException(); } } } }
mit
Kogser/bitcoin
db-4.8.30.NC/examples_java/src/collections/ship/entity/Weight.java
990
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2009 Oracle. All rights reserved. * * $Id$ */ package collections.ship.entity; import java.io.Serializable; /** * Weight represents a weight amount and unit of measure. * * <p> In this sample, Weight is embedded in part data values which are stored * as Serial serialized objects; therefore Weight must be Serializable. </p> * * @author Mark Hayes */ public class Weight implements Serializable { public final static String GRAMS = "grams"; public final static String OUNCES = "ounces"; private double amount; private String units; public Weight(double amount, String units) { this.amount = amount; this.units = units; } public final double getAmount() { return amount; } public final String getUnits() { return units; } public String toString() { return "[" + amount + ' ' + units + ']'; } }
mit
kreynen/civicrm-starterkit-drops-7
profiles/civicrm_starterkit/modules/contrib/wysiwyg/wysiwyg.api.php
15516
<?php /** * @file * API documentation for Wysiwyg module. * * To implement a "Drupal plugin" button, you need to write a Wysiwyg plugin: * - Implement hook_wysiwyg_include_directory() to register the directory * containing plugin definitions. * - In each plugin definition file, implement hook_INCLUDE_plugin(). * - For each plugin button, implement a JavaScript integration and an icon for * the button. * * @todo Icon: Recommended size and type of image. * * For example implementations you may want to look at * - Image Assist (img_assist) * - Teaser break plugin (plugins/break; part of WYSIWYG) * - IMCE (imce_wysiwyg) */ /** * Return an array of native editor plugins. * * Only to be used for native (internal) editor plugins. * * @see hook_wysiwyg_include_directory() * * @param $editor * The internal name of the currently processed editor. * @param $version * The version of the currently processed editor. * * @return * An associative array having internal plugin names as keys and an array of * plugin meta-information as values. */ function hook_wysiwyg_plugin($editor, $version) { switch ($editor) { case 'tinymce': if ($version > 3) { return array( 'myplugin' => array( // A URL to the plugin's homepage. 'url' => 'http://drupal.org/project/img_assist', // The full path to the native editor plugin, no trailing slash. // Ignored when 'internal' is set to TRUE below. 'path' => drupal_get_path('module', 'img_assist') . '/drupalimage', // The name of the plugin's main JavaScript file. // Ignored when 'internal' is set to TRUE below. // Default value depends on which editor the plugin is for. 'filename' => 'editor_plugin.js', // A list of buttons provided by this native plugin. The key has to // match the corresponding JavaScript implementation. The value is // is displayed on the editor configuration form only. // CKEditor-specific note: The internal button name/key is // capitalized, i.e. Img_assist. 'buttons' => array( 'img_assist' => t('Image Assist'), ), // A list of editor extensions provided by this native plugin. // Extensions are not displayed as buttons and touch the editor's // internals, so you should know what you are doing. 'extensions' => array( 'imce' => t('IMCE'), ), // A list of global, native editor configuration settings to // override. To be used rarely and only when required. 'options' => array( 'file_browser_callback' => 'imceImageBrowser', 'inline_styles' => TRUE, ), // Boolean whether the editor needs to load this plugin. When TRUE, // the editor will automatically load the plugin based on the 'path' // variable provided. If FALSE, the plugin either does not need to // be loaded or is already loaded by something else on the page. // Most plugins should define TRUE here. 'load' => TRUE, // Boolean whether this plugin is a native plugin, i.e. shipped with // the editor. Definition must be omitted for plugins provided by // other modules. TRUE means 'path' and 'filename' above are ignored // and the plugin is instead loaded from the editor's plugin folder. 'internal' => TRUE, // TinyMCE-specific: Additional HTML elements to allow in the markup. 'extended_valid_elements' => array( 'img[class|src|border=0|alt|title|width|height|align|name|style]', ), ), ); } break; } } /** * Register a directory containing Wysiwyg plugins. * * @param $type * The type of objects being collected: either 'plugins' or 'editors'. * @return * A sub-directory of the implementing module that contains the corresponding * plugin files. This directory must only contain integration files for * Wysiwyg module. */ function hook_wysiwyg_include_directory($type) { switch ($type) { case 'plugins': // You can just return $type, if you place your Wysiwyg plugins into a // sub-directory named 'plugins'. return $type; } } /** * Define a Wysiwyg plugin. * * Supposed to be used for "Drupal plugins" (cross-editor plugins) only. * * @see hook_wysiwyg_plugin() * * Each plugin file in the specified plugin directory of a module needs to * define meta information about the particular plugin provided. * The plugin's hook implementation function name is built out of the following: * - 'hook': The name of the module providing the plugin. * - 'INCLUDE': The basename of the file containing the plugin definition. * - 'plugin': Static. * * For example, if your module's name is 'mymodule' and * mymodule_wysiwyg_include_directory() returned 'plugins' as plugin directory, * and this directory contains an "awesome" plugin file named 'awesome.inc', i.e. * sites/all/modules/mymodule/plugins/awesome.inc * then the corresponding plugin hook function name is: * mymodule_awesome_plugin() * * @see hook_wysiwyg_include_directory() * * @return * Meta information about the buttons provided by this plugin. */ function hook_INCLUDE_plugin() { $plugins['awesome'] = array( // The plugin's title; defaulting to its internal name ('awesome'). 'title' => t('Awesome plugin'), // The (vendor) homepage of this plugin; defaults to ''. 'vendor url' => 'http://drupal.org/project/wysiwyg', // The path to the button's icon; defaults to // '/[path-to-module]/[plugins-directory]/[plugin-name]/images'. 'icon path' => 'path to icon', // The button image filename; defaults to '[plugin-name].png'. 'icon file' => 'name of the icon file with extension', // The button title to display on hover. 'icon title' => t('Do something'), // An alternative path to the integration JavaScript; defaults to // '[path-to-module]/[plugins-directory]/[plugin-name]'. 'js path' => drupal_get_path('module', 'mymodule') . '/awesomeness', // An alternative filename of the integration JavaScript; defaults to // '[plugin-name].js'. 'js file' => 'awesome.js', // An alternative path to the integration stylesheet; defaults to // '[path-to-module]/[plugins-directory]/[plugin-name]'. 'css path' => drupal_get_path('module', 'mymodule') . '/awesomeness', // An alternative filename of the integration stylesheet; defaults to // '[plugin-name].css'. 'css file' => 'awesome.css', // An array of settings for this button. Required, but API is still in flux. 'settings' => array( ), // TinyMCE-specific: Additional HTML elements to allow in the markup. 'extended_valid_elements' => array( 'tag1[attribute1|attribute2]', 'tag2[attribute3|attribute4]', ), ); return $plugins; } /** * Alter plugin definitions before loading and further processing. * * @param array $info * The plugin definitions to alter. * @param string $hook * The plugin type being loaded. Can be 'editor' or 'plugin'. */ function hook_wysiwyg_load_includes_alter(&$info, $hook) { if ($hook == 'editor' && isset($info['ckeditor'])) { $info['ckeditor']['version callback'] = 'my_own_version_callback'; } elseif ($hook == 'plugin' && isset($info['break'])) { $info['break']['title'] = t('Summary delimiter'); } } /** * Define a Wysiwyg editor library. * * @todo Complete this documentation. */ function hook_INCLUDE_editor() { $editor['ckeditor'] = array( // The official, human-readable label of the editor library. 'title' => 'CKEditor', // The URL to the library's homepage. 'vendor url' => 'http://ckeditor.com', // The URL to the library's download page. 'download url' => 'http://ckeditor.com/download', // A definition of available variants for the editor library. // The first defined is used by default. 'libraries' => array( '' => array( 'title' => 'Default', 'files' => array( 'ckeditor.js' => array('preprocess' => FALSE), ), ), 'src' => array( 'title' => 'Source', 'files' => array( 'ckeditor_source.js' => array('preprocess' => FALSE), ), ), ), // (optional) A callback to invoke to return additional notes for installing // the editor library in the administrative list/overview. 'install note callback' => 'wysiwyg_ckeditor_install_note', // The minimum and maximum versions the implementation has been tested with. // Users will be notified if installing a version not within this range. 'verified version range' => array('1.2.3', '3.4.5'), // (optional) A callback to perform migrations of the settings stored in a // profile when a library change has been detected. Takes a reference to a // settings object, the processed editor definition, the profile version and // the installed library version. Migrations should be performed in the // order changes were introduced by library versions, and the last version // migrated to should be returned, or FALSE if no migration was possible. // The returned version should be less than or equal to the highest version // ( and >= the lowest version) defined in 'verified version range' and // be as close as possible to, without passing, the installed version. 'migrate settings callback' => 'wysiwyg_ckeditor_migrate_settings', // A callback to determine the library's version. 'version callback' => 'wysiwyg_ckeditor_version', // A callback to return available themes/skins for the editor library. 'themes callback' => 'wysiwyg_ckeditor_themes', // (optional) A callback to perform editor-specific adjustments or // enhancements for the administrative editor profile settings form. 'settings form callback' => 'wysiwyg_ckeditor_settings_form', // (optional) A callback to return an initialization JavaScript snippet for // this editor library, loaded before the actual library files. The returned // JavaScript is executed as inline script in a primitive environment, // before the DOM is loaded; typically used to prime a base path and other // global window variables for the editor library before it is loaded. // All implementations should verbosely document what they are doing and // why that is required. 'init callback' => 'wysiwyg_ckeditor_init', // A callback to convert administrative profile/editor settings into // JavaScript settings. 'settings callback' => 'wysiwyg_ckeditor_settings', // A callback to supply definitions of available editor plugins. 'plugin callback' => 'wysiwyg_ckeditor_plugins', // A callback to supply global metadata for a single native external plugin. 'plugin meta callback' => 'wysiwyg_ckeditor_plugin_meta', // A callback to convert administrative plugin settings for an editor // profile into JavaScript settings per profile. 'plugin settings callback' => 'wysiwyg_ckeditor_plugin_settings', // (optional) Defines the proxy plugin that handles plugins provided by // Drupal modules, which work in all editors that support proxy plugins. 'proxy plugin' => array( 'drupal' => array( 'load' => TRUE, 'proxy' => TRUE, ), ), // (optional) A callback to convert proxy plugin settings into JavaScript // settings. 'proxy plugin settings callback' => 'wysiwyg_ckeditor_proxy_plugin_settings', // Defines the list of supported (minimum) versions of the editor library, // and the respective Drupal integration files to load. 'versions' => array( '3.0.0.3665' => array( 'js files' => array('ckeditor-3.0.js'), ), ), ); return $editor; } /** * Alter editor definitions defined by other modules. * * @param array $editors * The Editors to alter. */ function hook_wysiwyg_editor_alter(&$editors) { $editors['editor']['version callback'] = 'my_own_version_callback'; } /** * Act on editor profile settings. * * This hook is invoked from wysiwyg_get_editor_config() after the JavaScript * settings have been generated for an editor profile and before the settings * are added to the page. The settings may be customized or enhanced; typically * with options that cannot be controlled through Wysiwyg module's * administrative UI currently. * * Modules implementing this hook to enforce settings that can also be * controlled through the UI should also implement * hook_form_wysiwyg_profile_form_alter() to adjust or at least indicate on the * editor profile configuration form that certain/affected settings cannot be * changed. * * @param $settings * An associative array of JavaScript settings to pass to the editor. * @param $context * An associative array containing additional context information: * - editor: The plugin definition array of the editor. * - profile: The editor profile object, as loaded from the database. * - theme: The name of the editor theme/skin. */ function hook_wysiwyg_editor_settings_alter(&$settings, $context) { // Each editor has its own collection of native settings that may be extended // or overridden. Please consult the respective official vendor documentation // for details. if ($context['profile']->editor == 'tinymce') { // Supported values to JSON data types. $settings['cleanup_on_startup'] = TRUE; // Function references (callbacks) need special care. // @see wysiwyg_wrap_js_callback() $settings['file_browser_callback'] = wysiwyg_wrap_js_callback('myFileBrowserCallback'); // Regular Expressions need special care. // @see wysiwyg_wrap_js_regexp() $settings['stylesheetParser_skipSelectors'] = wysiwyg_wrap_js_regexp('(^body\.|^caption\.|\.high|^\.)', 'i'); } } /** * Act on stylesheets used in WYSIWYG mode. * * This hook acts like a pre-render callback to the style element normally * output in the document header. It is invoked before Core has * sorted/grouped/aggregated stylesheets and changes made here will only have * an effect on the stylesheets used in an editor's WYSIWYG mode. * Wysiwyg will only keep items if their type is 'file' or 'inline' and only if * they are in the group CSS_THEME. * * This hook may be invoked several times in a row with slightly different or * altered stylesheets if something like Color module is used by a theme. * Wysiwyg will cache the final list of stylesheets so this hook will only be * called while the cache is being rebuilt. * * Messages set in this hook will not be displayed because the processing is * done in an internal HTTP request and the page output is ignored. * * @param $elements * The style element which will be rendered. Added stylesheets are found in * $element['#items']['path/to/stylesheet.css']. * @param $context * An array with the following keys: * - theme: The name of the theme which was used when the list of stylesheets * was generated. */ function hook_wysiwyg_editor_styles_alter(&$element, $context) { if ($context['theme'] == 'alpha') { unset($element['#items']['sites/all/themes/omega/alpha/css/alpha-debug.css']); } }
gpl-2.0
SayenkoDesign/gogo-racing.com
wp-content/plugins/wordpress-seo/admin/taxonomy/class-taxonomy.php
10889
<?php /** * @package WPSEO\Admin */ /** * Class that handles the edit boxes on taxonomy edit pages. */ class WPSEO_Taxonomy { /** * The current active taxonomy * * @var string */ private $taxonomy = ''; /** * Class constructor */ public function __construct() { $this->taxonomy = $this->get_taxonomy(); if ( is_admin() && $this->taxonomy !== '' && $this->show_metabox( ) ) { add_action( sanitize_text_field( $this->taxonomy ) . '_edit_form', array( $this, 'term_metabox' ), 90, 1 ); } add_action( 'edit_term', array( $this, 'update_term' ), 99, 3 ); add_action( 'init', array( $this, 'custom_category_descriptions_allow_html' ) ); add_filter( 'category_description', array( $this, 'custom_category_descriptions_add_shortcode_support' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); } /** * Show the SEO inputs for term. * * @param stdClass|WP_Term $term Term to show the edit boxes for. */ public function term_metabox( $term ) { $metabox = new WPSEO_Taxonomy_Metabox( $this->taxonomy, $term ); $metabox->display(); } /** * Translate options text strings for use in the select fields * * @internal IMPORTANT: if you want to add a new string (option) somewhere, make sure you add * that array key to the main options definition array in the class WPSEO_Taxonomy_Meta() as well!!!! */ public function translate_meta_options() { $this->no_index_options = WPSEO_Taxonomy_Meta::$no_index_options; $this->sitemap_include_options = WPSEO_Taxonomy_Meta::$sitemap_include_options; $this->no_index_options['default'] = __( 'Use %s default (Currently: %s)', 'wordpress-seo' ); $this->no_index_options['index'] = __( 'Always index', 'wordpress-seo' ); $this->no_index_options['noindex'] = __( 'Always noindex', 'wordpress-seo' ); $this->sitemap_include_options['-'] = __( 'Auto detect', 'wordpress-seo' ); $this->sitemap_include_options['always'] = __( 'Always include', 'wordpress-seo' ); $this->sitemap_include_options['never'] = __( 'Never include', 'wordpress-seo' ); } /** * Test whether we are on a public taxonomy - no metabox actions needed if we are not * Unfortunately we have to hook most everything in before the point where all taxonomies are registered and * we know which taxonomy is being requested, so we need to use this check in nearly every hooked in function. * * @since 1.5.0 */ public function admin_enqueue_scripts() { if ( $GLOBALS['pagenow'] === 'edit-tags.php' && filter_input( INPUT_GET, 'action' ) === 'edit' ) { wp_enqueue_media(); // Enqueue files needed for upload functionality. wp_enqueue_style( 'yoast-seo', plugins_url( 'css/dist/yoast-seo/yoast-seo-' . '305' . '.min.css', WPSEO_FILE ), array(), WPSEO_VERSION ); wp_enqueue_style( 'yoast-metabox-css', plugins_url( 'css/metabox-' . '302' . WPSEO_CSSJS_SUFFIX . '.css', WPSEO_FILE ), array(), WPSEO_VERSION ); wp_enqueue_style( 'snippet', plugins_url( 'css/snippet-' . '302' . WPSEO_CSSJS_SUFFIX . '.css', WPSEO_FILE ), array(), WPSEO_VERSION ); wp_enqueue_style( 'seo_score', plugins_url( 'css/yst_seo_score-' . '302' . WPSEO_CSSJS_SUFFIX . '.css', WPSEO_FILE ), array(), WPSEO_VERSION ); wp_editor( '', 'description' ); wp_enqueue_script( 'wp-seo-metabox', plugins_url( 'js/wp-seo-metabox-' . '302' . WPSEO_CSSJS_SUFFIX . '.js', WPSEO_FILE ), array( 'jquery', 'jquery-ui-core', 'jquery-ui-autocomplete', ), WPSEO_VERSION, true ); wp_enqueue_script( 'yoast-seo', plugins_url( 'js/dist/yoast-seo/yoast-seo-' . '305' . '.min.js', WPSEO_FILE ), null, WPSEO_VERSION, true ); wp_enqueue_script( 'wp-seo-term-scraper', plugins_url( 'js/wp-seo-term-scraper-' . '305' . WPSEO_CSSJS_SUFFIX . '.js', WPSEO_FILE ), array( 'yoast-seo' ), WPSEO_VERSION, true ); wp_enqueue_script( 'wp-seo-replacevar-plugin', plugins_url( 'js/wp-seo-replacevar-plugin-' . '302' . WPSEO_CSSJS_SUFFIX . '.js', WPSEO_FILE ), array( 'yoast-seo', 'wp-seo-term-scraper' ), WPSEO_VERSION, true ); wp_localize_script( 'wp-seo-term-scraper', 'wpseoTermScraperL10n', $this->localize_term_scraper_script() ); wp_localize_script( 'wp-seo-replacevar-plugin', 'wpseoReplaceVarsL10n', $this->localize_replace_vars_script() ); // Always enqueue minified as it's not our code. wp_enqueue_style( 'jquery-qtip.js', plugins_url( 'css/jquery.qtip' . WPSEO_CSSJS_SUFFIX . '.css', WPSEO_FILE ), array(), '2.2.1' ); wp_enqueue_script( 'jquery-qtip', plugins_url( 'js/jquery.qtip.min.js', WPSEO_FILE ), array( 'jquery' ), '2.2.1', true ); wp_enqueue_script( 'wpseo-admin-media', plugins_url( 'js/wp-seo-admin-media-' . '302' . WPSEO_CSSJS_SUFFIX . '.js', WPSEO_FILE ), array( 'jquery', 'jquery-ui-core', ), WPSEO_VERSION, true ); wp_localize_script( 'wpseo-admin-media', 'wpseoMediaL10n', array( 'choose_image' => __( 'Use Image', 'wordpress-seo' ), ) ); } } /** * Update the taxonomy meta data on save. * * @param int $term_id ID of the term to save data for. * @param int $tt_id The taxonomy_term_id for the term. * @param string $taxonomy The taxonomy the term belongs to. */ public function update_term( $term_id, $tt_id, $taxonomy ) { /* Create post array with only our values */ $new_meta_data = array(); foreach ( WPSEO_Taxonomy_Meta::$defaults_per_term as $key => $default ) { if ( $posted_value = filter_input( INPUT_POST, $key ) ) { $new_meta_data[ $key ] = $posted_value; } } unset( $key, $default ); // Saving the values. WPSEO_Taxonomy_Meta::set_values( $term_id, $taxonomy, $new_meta_data ); } /** * Allows HTML in descriptions */ public function custom_category_descriptions_allow_html() { $filters = array( 'pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description', ); foreach ( $filters as $filter ) { remove_filter( $filter, 'wp_filter_kses' ); } remove_filter( 'term_description', 'wp_kses_data' ); } /** * Adds shortcode support to category descriptions. * * @param string $desc String to add shortcodes in. * * @return string */ public function custom_category_descriptions_add_shortcode_support( $desc ) { // Wrap in output buffering to prevent shortcodes that echo stuff instead of return from breaking things. ob_start(); $desc = do_shortcode( $desc ); ob_end_clean(); return $desc; } /** * Check if metabox for current taxonomy should be displayed. * * @return bool */ private function show_metabox() { $options = WPSEO_Options::get_all(); $option_key = 'hideeditbox-tax-' . $this->taxonomy; return ( empty( $options[ $option_key ] ) ); } /** * Getting the taxonomy from the URL * * @return string */ private function get_taxonomy() { return filter_input( INPUT_GET, 'taxonomy', FILTER_DEFAULT, array( 'options' => array( 'default' => '' ) ) ); } /** * Pass variables to js for use with the term-scraper * * @return array */ public function localize_term_scraper_script() { $translations = $this->get_scraper_translations(); $term_id = filter_input( INPUT_GET, 'tag_ID' ); $term = get_term_by( 'id', $term_id, $this->get_taxonomy() ); $focuskw = WPSEO_Taxonomy_Meta::get_term_meta( $term, $term->taxonomy, 'focuskw' ); $taxonomy = get_taxonomy( $term->taxonomy ); $options = WPSEO_Options::get_all(); $base_url = home_url( '/', null ); if ( ! $options['stripcategorybase'] ) { $base_url = trailingslashit( $base_url . $taxonomy->rewrite['slug'] ); } return array( 'translations' => $translations, 'base_url' => $base_url, 'taxonomy' => $term->taxonomy, 'keyword_usage' => WPSEO_Taxonomy_Meta::get_keyword_usage( $focuskw, $term->term_id, $term->taxonomy ), // Todo: a column needs to be added on the termpages to add a filter for the keyword, so this can be used in the focus kw doubles. 'search_url' => admin_url( 'edit-tags.php?taxonomy=' . $term->taxonomy . '&seo_kw_filter={keyword}' ), 'post_edit_url' => admin_url( 'edit-tags.php?action=edit&taxonomy=' . $term->taxonomy . '&tag_ID={id}' ), 'title_template' => WPSEO_Taxonomy::get_title_template( $term ), 'metadesc_template' => WPSEO_Taxonomy::get_metadesc_template( $term ), 'contentTab' => __( 'Content:', 'wordpress-seo' ), 'locale' => get_locale(), ); } /** * Retrieves the title template. * * @param object $term taxonomy term. * * @return string */ public static function get_title_template( $term ) { $options = get_option( 'wpseo_titles' ); $title_template = ''; if ( is_object( $term ) && property_exists( $term, 'taxonomy' ) ) { $needed_option = 'title-tax-' . $term->taxonomy; if ( isset( $options[ $needed_option ] ) && $options[ $needed_option ] !== '' ) { $title_template = $options[ $needed_option ]; } } return $title_template; } /** * Retrieves the metadesc template. * * @param object $term taxonomy term. * * @return string */ public static function get_metadesc_template( $term ) { $options = get_option( 'wpseo_titles' ); $metadesc_template = ''; if ( is_object( $term ) && property_exists( $term, 'taxonomy' ) ) { $needed_option = 'metadesc-tax-' . $term->taxonomy; if ( isset( $options[ $needed_option ] ) && $options[ $needed_option ] !== '' ) { $metadesc_template = $options[ $needed_option ]; } } return $metadesc_template; } /** * Pass some variables to js for replacing variables. */ public function localize_replace_vars_script() { return array( 'no_parent_text' => __( '(no parent)', 'wordpress-seo' ), 'replace_vars' => $this->get_replace_vars(), ); } /** * Prepares the replace vars for localization. * * @return array replace vars. */ private function get_replace_vars() { $term_id = filter_input( INPUT_GET, 'tag_ID' ); $term = get_term_by( 'id', $term_id, $this->get_taxonomy() ); $cached_replacement_vars = array(); $vars_to_cache = array( 'date', 'id', 'sitename', 'sitedesc', 'sep', 'page', 'currenttime', 'currentdate', 'currentday', 'currentmonth', 'currentyear', 'term_title', 'term_description', 'category_description', 'tag_description', 'searchphrase', ); foreach ( $vars_to_cache as $var ) { $cached_replacement_vars[ $var ] = wpseo_replace_vars( '%%' . $var . '%%', $term ); } return $cached_replacement_vars; } /** * Returns Jed compatible YoastSEO.js translations. * * @return array */ private function get_scraper_translations() { $file = plugin_dir_path( WPSEO_FILE ) . 'languages/wordpress-seo-' . get_locale() . '.json'; if ( file_exists( $file ) && $file = file_get_contents( $file ) ) { return json_decode( $file, true ); } return array(); } } /* End of class */
gpl-2.0
lehung151292/bestilblomster
wp-content/plugins/w3-total-cache/pub/js/lightbox.js
18494
var W3tc_Lightbox = { window: jQuery(window), container: null, options: null, create: function() { var me = this; this.container = jQuery('<div class="lightbox lightbox-loading"><div class="lightbox-close">Close window</div><div class="lightbox-content"></div></div>').css({ top: 0, left: 0, width: 0, height: 0, position: 'fixed', 'z-index': 9991, display: 'none' }); jQuery('#w3tc').append(this.container); me.resize(); this.window.resize(function() { me.resize(); }); this.window.scroll(function() { me.resize(); }); this.container.find('.lightbox-close').click(function() { me.close(); }); jQuery(document).keyup(function(e) { if (e.keyCode == 27) { me.close(); } // esc }); }, open: function(options) { this.options = jQuery.extend({ width: 0, height: 0, maxWidth: 0, maxHeight: 0, minWidth: 0, minHeight: 0, widthPercent: 0.6, heightPercent: 0.8, content: null, url: null, callback: null }, options); this.create(); this.resize(); if (this.options.content) { this.content(this.options.content); } else if (this.options.url) { this.load(this.options.url, this.options.callback); } W3tc_Overlay.show(); this.container.show(); }, close: function() { this.container.remove(); W3tc_Overlay.hide(); }, resize: function() { var width = (this.options.width ? this.options.width : this.window.width() * this.options.widthPercent); var height = (this.options.height ? this.options.height : this.window.height() * this.options.heightPercent); if (this.options.maxWidth && width > this.options.maxWidth) { width = this.options.maxWidth; } else if (width < this.options.minWidth) { width = this.options.minWidth; } if (this.options.maxHeight && height > this.options.maxHeight) { height = this.options.maxHeight; } else if (height < this.options.minHeight) { height = this.options.minHeight; } this.container.css({ top: (this.window.height() / 2 - this.container.outerHeight() / 2)>=0 ? this.window.height() / 2 - this.container.outerHeight() / 2 : 0, left: (this.window.width() / 2 - this.container.outerWidth() / 2)>=0 ? this.window.width() / 2 - this.container.outerWidth() / 2 : 0 }); this.container.css({ width: width, height: height }); jQuery('.lightbox-content', this.container).css({ width: width, height: height }); }, load: function(url, callback) { this.content(''); this.loading(true); var me = this; jQuery.get(url, {}, function(content) { me.loading(false); me.content(content); if (callback) { callback.call(this, me); } }); }, content: function(content) { return this.container.find('.lightbox-content').html(content); }, width: function(width) { if (width === undefined) { return this.container.width(); } else { this.container.css('width', width); return this.resize(); } }, height: function(height) { if (height === undefined) { return this.container.height(); } else { this.container.css('height', height); return this.resize(); } }, loading: function(loading) { return (loading === undefined ? this.container.hasClass('lightbox-loader') : (loading ? this.container.addClass('lightbox-loader') : this.container.removeClass('lightbox-loader'))); } }; var W3tc_Overlay = { window: jQuery(window), container: null, create: function() { var me = this; this.container = jQuery('<div id="overlay" />').css({ top: 0, left: 0, width: 0, height: 0, position: 'fixed', 'z-index': 9990, display: 'none', opacity: 0.6 }); jQuery('#w3tc').append(this.container); this.window.resize(function() { me.resize(); }); this.window.scroll(function() { me.resize(); }); }, show: function() { this.create(); this.resize(); this.container.show(); }, hide: function() { this.container.remove(); }, resize: function() { this.container.css({ width: this.window.width(), height: this.window.height() }); } }; function w3tc_lightbox_support_us(nonce) { W3tc_Lightbox.open({ width: 500, height: 200, url: 'admin.php?page=w3tc_dashboard&w3tc_support_us&_wpnonce=' + nonce }); } var w3tc_minify_recommendations_checked = {}; function w3tc_lightbox_minify_recommendations(nonce) { W3tc_Lightbox.open({ width: 1000, url: 'admin.php?page=w3tc_minify&w3tc_test_minify_recommendations&_wpnonce=' + nonce, callback: function(lightbox) { var theme = jQuery('#recom_theme').val(); if (jQuery.ui && jQuery.ui.sortable) { jQuery("#recom_js_files,#recom_css_files").sortable({ axis: 'y', stop: function() { jQuery(this).find('li').each(function(index) { jQuery(this).find('td:eq(1)').html((index + 1) + '.'); }); } }); } if (w3tc_minify_recommendations_checked[theme] !== undefined) { jQuery('#recom_js_files :text,#recom_css_files :text').each(function() { var hash = jQuery(this).parents('li').find('[name=recom_js_template]').val() + ':' + jQuery(this).val(); if (w3tc_minify_recommendations_checked[theme][hash] !== undefined) { var checkbox = jQuery(this).parents('li').find(':checkbox'); if (w3tc_minify_recommendations_checked[theme][hash]) { checkbox.attr('checked', 'checked'); } else { checkbox.removeAttr('checked'); } } }); } jQuery('#recom_theme').change(function() { jQuery('#recom_js_files :checkbox,#recom_css_files :checkbox').each(function() { var li = jQuery(this).parents('li'); var hash = li.find('[name=recom_js_template]').val() + ':' + li.find(':text').val(); if (w3tc_minify_recommendations_checked[theme] === undefined) { w3tc_minify_recommendations_checked[theme] = {}; } w3tc_minify_recommendations_checked[theme][hash] = jQuery(this).is(':checked'); }); lightbox.load('admin.php?page=w3tc_minify&w3tc_test_minify_recommendations&theme_key=' + jQuery(this).val() + '&_wpnonce=' + nonce, lightbox.options.callback); }); jQuery('#recom_js_check').click(function() { if (jQuery('#recom_js_files :checkbox:checked').size()) { jQuery('#recom_js_files :checkbox').removeAttr('checked'); } else { jQuery('#recom_js_files :checkbox').attr('checked', 'checked'); } return false; }); jQuery('#recom_css_check').click(function() { if (jQuery('#recom_css_files :checkbox:checked').size()) { jQuery('#recom_css_files :checkbox').removeAttr('checked'); } else { jQuery('#recom_css_files :checkbox').attr('checked', 'checked'); } return false; }); jQuery('.recom_apply', lightbox.container).click(function() { var theme = jQuery('#recom_theme').val(); jQuery('#js_files li').each(function() { if (jQuery(this).find(':text').attr('name').indexOf('js_files[' + theme + ']') != -1) { jQuery(this).remove(); } }); jQuery('#css_files li').each(function() { if (jQuery(this).find(':text').attr('name').indexOf('css_files[' + theme + ']') != -1) { jQuery(this).remove(); } }); jQuery('#recom_js_files li').each(function() { if (jQuery(this).find(':checkbox:checked').size()) { w3tc_minify_js_file_add(theme, jQuery(this).find('[name=recom_js_template]').val(), jQuery(this).find('[name=recom_js_location]').val(), jQuery(this).find('[name=recom_js_file]').val()); } }); jQuery('#recom_css_files li').each(function() { if (jQuery(this).find(':checkbox:checked').size()) { w3tc_minify_css_file_add(theme, jQuery(this).find('[name=recom_css_template]').val(), jQuery(this).find('[name=recom_css_file]').val()); } }); w3tc_minify_js_theme(theme); w3tc_minify_css_theme(theme); w3tc_input_enable('.js_enabled', jQuery('#minify_js_enable:checked').size()); w3tc_input_enable('.css_enabled', jQuery('#minify_css_enable:checked').size()); lightbox.close(); }); } }); } function w3tc_lightbox_self_test(nonce) { W3tc_Lightbox.open({ width: 800, minHeight: 300, url: 'admin.php?page=w3tc_dashboard&w3tc_test_self&_wpnonce=' + nonce, callback: function(lightbox) { jQuery('.button-primary', lightbox.container).click(function() { lightbox.close(); }); } }); } function w3tc_lightbox_buy_plugin(nonce) { W3tc_Lightbox.open({ width: 800, minHeight: 450, url: 'admin.php?page=w3tc_dashboard&w3tc_licensing_buy_plugin&_wpnonce=' + nonce, callback: function(lightbox) { var w3tc_license_listener = function(event) { if (event.origin !== "http://www.w3-edge.com") return; if (event.data.substr(0, 7) != 'license') return; lightbox.close(); jQuery('#plugin_license_key').val(event.data.substr(8)); jQuery('#w3tc_save_options_licensing').click(); } if (window.addEventListener) { addEventListener("message", w3tc_license_listener, false) } else if (attachEvent) { attachEvent("onmessage", w3tc_license_listener); } jQuery('.button-primary', lightbox.container).click(function() { lightbox.close(); }); } }); } function w3tc_lightbox_cdn_s3_bucket_location(type, nonce) { W3tc_Lightbox.open({ width: 500, height: 130, url: 'admin.php?page=w3tc_dashboard&w3tc_cdn_s3_bucket_location&type=' + type + '&_wpnonce=' + nonce, callback: function(lightbox) { jQuery('.button', lightbox.container).click(function() { lightbox.close(); }); } }); } function w3tc_lightbox_netdna_maxcdn_pull_zone(type, nonce) { W3tc_Lightbox.open({ width: 500, height: 400, url: 'admin.php?page=w3tc_dashboard&w3tc_cdn_create_netdna_maxcdn_pull_zone_form&type=' + type + '&_wpnonce=' + nonce, callback: function(lightbox) { jQuery('#create_pull_zone', lightbox.container).click(function() { var loader = jQuery('#pull-zone-loading'); loader.addClass('w3tc-loading'); var pull_button = jQuery(this); pull_button.attr("disabled", "disabled"); jQuery('.create-error').text(''); var name_val = jQuery('#name', lightbox.container).val(); var name_filter = /^[a-zA-Z\d\-]*$/; if (name_val == '') { jQuery('#name', lightbox.container).addClass('w3tc-error'); jQuery('.name_message', lightbox.container).text('Cannot be empty.'); } else if(name_val.length < 3) { jQuery('#name', lightbox.container).addClass('w3tc-error'); jQuery('.name_message', lightbox.container).text('Too short.'); } else if (name_val.length > 32) { jQuery('#name', lightbox.container).addClass('w3tc-error'); jQuery('.name_message', lightbox.container).text('Too long.'); } else if (!name_filter.test(name_val)) { jQuery('#name', lightbox.container).addClass('w3tc-error'); jQuery('.name_message', lightbox.container).text('Cannot use unsupported characters.'); } else { jQuery('#name', lightbox.container).removeClass('w3tc-error'); jQuery('.name_message', lightbox.container).text(''); } var label_val = jQuery('#label', lightbox.container).val(); if (label_val == '') { jQuery('#label', lightbox.container).addClass('w3tc-error'); jQuery('.label_message', lightbox.container).text('Cannot be empty.'); } else if(label_val.length < 1) { jQuery('#label', lightbox.container).addClass('w3tc-error'); jQuery('.label_message', lightbox.container).text('Too short.'); } else if (label_val.length > 255) { jQuery('#label', lightbox.container).addClass('w3tc-error'); jQuery('.label_message', lightbox.container).text('Too long.'); } else { jQuery('#label', lightbox.container).removeClass('w3tc-error'); jQuery('.label_message', lightbox.container).text(''); } if (!jQuery('#label').hasClass('w3tc-error') && !jQuery('#name').hasClass('w3tc-error')) { jQuery.post('admin.php?page=w3tc_dashboard&w3tc_cdn_create_netdna_maxcdn_pull_zone', {name:name_val, label: label_val, nonce: jQuery('#_wp_nonce').val(), type: type},function(data) { loader.removeClass('w3tc-loading'); if (data['status'] == 'error') { jQuery('.create-error').show(); jQuery('.create-error').html('<p>Something is wrong:<br />' + data['message'] + '</p>'); pull_button.removeAttr("disabled"); } else { if (jQuery('#cdn_cnames > :first-child > :first-child').val() == '') { jQuery('#cdn_cnames > :first-child > :first-child').val(data['temporary_url']); jQuery('.netdna-maxcdn-form').html('<p>Pull zone was successfully created. Following url was added as default "Replace site\'s hostname with:" ' + data['temporary_url'] + '</p>'); } else { jQuery('.netdna-maxcdn-form').html('<p>Pull zone was successfully created. cnames were already set so "Replace site\'s hostname with:" were not replaced with ' + data['temporary_url'] + '</p>'); } } }, 'json'); } else { loader.removeClass('w3tc-loading'); pull_button.removeAttr("disabled"); } }); jQuery('.button', lightbox.container).click(function() { lightbox.close(); }); } }); } jQuery(function() { jQuery('.button-minify-recommendations').click(function() { var nonce = jQuery(this).metadata().nonce; w3tc_lightbox_minify_recommendations(nonce); return false; }); jQuery('.button-self-test').click(function() { var nonce = jQuery(this).metadata().nonce; w3tc_lightbox_self_test(nonce); return false; }); jQuery('.button-buy-plugin').click(function() { var nonce = jQuery(this).metadata().nonce; w3tc_lightbox_buy_plugin(nonce); var left = (screen.width/2)-(500/2); var top = (screen.height/2)-(600/2); jQuery('#w3tc-license-instruction').show(); return false; }); jQuery('.button-cdn-s3-bucket-location,.button-cdn-cf-bucket-location').click(function() { var type = ''; var nonce = jQuery(this).metadata().nonce; if (jQuery(this).hasClass('cdn_s3')) { type = 's3'; } else if (jQuery(this).hasClass('cdn_cf')) { type = 'cf'; } w3tc_lightbox_cdn_s3_bucket_location(type, nonce); return false; }); jQuery('#netdna-maxcdn-create-pull-zone').click(function() { var type = jQuery(this).metadata().type; var nonce = jQuery(this).metadata().nonce; w3tc_lightbox_netdna_maxcdn_pull_zone(type, nonce); return false; }); });
gpl-2.0
koutheir/incinerator-hotspot
nashorn/test/script/trusted/NASHORN-653.js
2862
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * NASHORN-653 : Various problems with isTerminal and dead code generation from ASM * * @test * @run */ var script = " \ function a() { \ return true; \ } \ \ function b() { \ while (x) { \ return true; \ } \ } \ \ function c() { \ while (true) { \ return true; \ } \ } \ \ function d() { \ do { \ return true; \ } while (x); \ } \ \ function f() { \ for (;;) { \ return true; \ } \ } \ \ function e() { \ for (;;) { \ return true; \ } \ } \ \ function g() { \ for(;;) { \ print('goes on and on and on ... '); \ } \ print('x'); \ } \ "; function runScriptEngine(opts, code) { var imports = new JavaImporter( Packages.jdk.nashorn.api.scripting, java.io, java.lang, java.util); with(imports) { var fac = new NashornScriptEngineFactory(); // get current System.err var oldErr = System.err; var baos = new ByteArrayOutputStream(); var newErr = new PrintStream(baos); try { // set new standard err System.setErr(newErr); var engine = fac.getScriptEngine(Java.to(opts, "java.lang.String[]")); engine.eval(code); newErr.flush(); return new java.lang.String(baos.toByteArray()); } finally { // restore System.err to old value System.setErr(oldErr); } } } var result = runScriptEngine([ "--print-code" ], script); if (result.indexOf("NOP") != -1) { fail("ASM genenerates NOP*/ATHROW sequences - dead code is still in the script"); }
gpl-2.0
signed/intellij-community
plugins/javaFX/testData/rename/NestedControllerIdFromJava_after.java
189
import javafx.fxml.FXML; import javafx.scene.layout.VBox; class NestedControllerIdFromJava { @FXML private VBox newName; @FXML NestedControllerIdFromJavaInternal newNameController; }
apache-2.0
neo1973/xbmc
xbmc/addons/binary/interfaces/api1/AudioEngine/AddonCallbacksAudioEngine.cpp
12949
/* * Copyright (C) 2014 Team KODI * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KODI; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "system.h" #include "AddonCallbacksAudioEngine.h" #include "addons/kodi-addon-dev-kit/include/kodi/kodi_audioengine_types.h" #include "cores/AudioEngine/AEFactory.h" #include "cores/AudioEngine/Interfaces/AEStream.h" #include "cores/AudioEngine/Utils/AEChannelData.h" #include "utils/log.h" using namespace ADDON; namespace V1 { namespace KodiAPI { namespace AudioEngine { CAddonCallbacksAudioEngine::CAddonCallbacksAudioEngine(CAddon* addon) : ADDON::IAddonInterface(addon, 1, KODI_AUDIOENGINE_API_VERSION), m_callbacks(new CB_AudioEngineLib) { // write KODI audio DSP specific add-on function addresses to callback table m_callbacks->MakeStream = AudioEngine_MakeStream; m_callbacks->FreeStream = AudioEngine_FreeStream; m_callbacks->GetCurrentSinkFormat = AudioEngine_GetCurrentSinkFormat; // AEStream add-on function callback table m_callbacks->AEStream_GetSpace = AEStream_GetSpace; m_callbacks->AEStream_AddData = AEStream_AddData; m_callbacks->AEStream_GetDelay = AEStream_GetDelay; m_callbacks->AEStream_IsBuffering = AEStream_IsBuffering; m_callbacks->AEStream_GetCacheTime = AEStream_GetCacheTime; m_callbacks->AEStream_GetCacheTotal = AEStream_GetCacheTotal; m_callbacks->AEStream_Pause = AEStream_Pause; m_callbacks->AEStream_Resume = AEStream_Resume; m_callbacks->AEStream_Drain = AEStream_Drain; m_callbacks->AEStream_IsDraining = AEStream_IsDraining; m_callbacks->AEStream_IsDrained = AEStream_IsDrained; m_callbacks->AEStream_Flush = AEStream_Flush; m_callbacks->AEStream_GetVolume = AEStream_GetVolume; m_callbacks->AEStream_SetVolume = AEStream_SetVolume; m_callbacks->AEStream_GetAmplification = AEStream_GetAmplification; m_callbacks->AEStream_SetAmplification = AEStream_SetAmplification; m_callbacks->AEStream_GetFrameSize = AEStream_GetFrameSize; m_callbacks->AEStream_GetChannelCount = AEStream_GetChannelCount; m_callbacks->AEStream_GetSampleRate = AEStream_GetSampleRate; m_callbacks->AEStream_GetDataFormat = AEStream_GetDataFormat; m_callbacks->AEStream_GetResampleRatio = AEStream_GetResampleRatio; m_callbacks->AEStream_SetResampleRatio = AEStream_SetResampleRatio; } AEStreamHandle* CAddonCallbacksAudioEngine::AudioEngine_MakeStream(AudioEngineFormat StreamFormat, unsigned int Options) { AEAudioFormat format; format.m_dataFormat = StreamFormat.m_dataFormat; format.m_sampleRate = StreamFormat.m_sampleRate; format.m_channelLayout = StreamFormat.m_channels; return CAEFactory::MakeStream(format, Options); } void CAddonCallbacksAudioEngine::AudioEngine_FreeStream(AEStreamHandle *StreamHandle) { if (!StreamHandle) { CLog::Log(LOGERROR, "CAddonCallbacksAudioEngine - %s - invalid stream data", __FUNCTION__); return; } CAEFactory::FreeStream((IAEStream*)StreamHandle); } bool CAddonCallbacksAudioEngine::AudioEngine_GetCurrentSinkFormat(void *AddonData, AudioEngineFormat *SinkFormat) { if (!AddonData || !SinkFormat) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid input data!", __FUNCTION__); return false; } AEAudioFormat AESinkFormat; if (!CAEFactory::GetEngine() || !CAEFactory::GetEngine()->GetCurrentSinkFormat(AESinkFormat)) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - failed to get current sink format from AE!", __FUNCTION__); return false; } SinkFormat->m_channelCount = AESinkFormat.m_channelLayout.Count(); for (unsigned int ch = 0; ch < SinkFormat->m_channelCount; ch++) { SinkFormat->m_channels[ch] = AESinkFormat.m_channelLayout[ch]; } SinkFormat->m_dataFormat = AESinkFormat.m_dataFormat; SinkFormat->m_sampleRate = AESinkFormat.m_sampleRate; SinkFormat->m_frames = AESinkFormat.m_frames; SinkFormat->m_frameSize = AESinkFormat.m_frameSize; return true; } CAddonCallbacksAudioEngine::~CAddonCallbacksAudioEngine() { /* delete the callback table */ delete m_callbacks; } unsigned int CAddonCallbacksAudioEngine::AEStream_GetSpace(void *AddonData, AEStreamHandle *StreamHandle) { if (!AddonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return 0; } return ((IAEStream*)StreamHandle)->GetSpace(); } unsigned int CAddonCallbacksAudioEngine::AEStream_AddData(void *AddonData, AEStreamHandle *StreamHandle, uint8_t* const *Data, unsigned int Offset, unsigned int Frames) { if (!AddonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return 0; } return ((IAEStream*)StreamHandle)->AddData(Data, Offset, Frames); } double CAddonCallbacksAudioEngine::AEStream_GetDelay(void *AddonData, AEStreamHandle *StreamHandle) { if (!AddonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0; } return ((IAEStream*)StreamHandle)->GetDelay(); } bool CAddonCallbacksAudioEngine::AEStream_IsBuffering(void *AddonData, AEStreamHandle *StreamHandle) { if (!AddonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return false; } return ((IAEStream*)StreamHandle)->IsBuffering(); } double CAddonCallbacksAudioEngine::AEStream_GetCacheTime(void *AddonData, AEStreamHandle *StreamHandle) { if (!AddonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0; } return ((IAEStream*)StreamHandle)->GetCacheTime(); } double CAddonCallbacksAudioEngine::AEStream_GetCacheTotal(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0; } return ((IAEStream*)StreamHandle)->GetCacheTotal(); } void CAddonCallbacksAudioEngine::AEStream_Pause(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->Pause(); } void CAddonCallbacksAudioEngine::AEStream_Resume(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->Resume(); } void CAddonCallbacksAudioEngine::AEStream_Drain(void *AddonData, AEStreamHandle *StreamHandle, bool Wait) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->Drain(Wait); } bool CAddonCallbacksAudioEngine::AEStream_IsDraining(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return false; } return ((IAEStream*)StreamHandle)->IsDraining(); } bool CAddonCallbacksAudioEngine::AEStream_IsDrained(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return false; } return ((IAEStream*)StreamHandle)->IsDrained(); } void CAddonCallbacksAudioEngine::AEStream_Flush(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->Flush(); } float CAddonCallbacksAudioEngine::AEStream_GetVolume(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0f; } return ((IAEStream*)StreamHandle)->GetVolume(); } void CAddonCallbacksAudioEngine::AEStream_SetVolume(void *AddonData, AEStreamHandle *StreamHandle, float Volume) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->SetVolume(Volume); } float CAddonCallbacksAudioEngine::AEStream_GetAmplification(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0f; } return ((IAEStream*)StreamHandle)->GetAmplification(); } void CAddonCallbacksAudioEngine::AEStream_SetAmplification(void *AddonData, AEStreamHandle *StreamHandle, float Amplify) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->SetAmplification(Amplify); } const unsigned int CAddonCallbacksAudioEngine::AEStream_GetFrameSize(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return 0; } return ((IAEStream*)StreamHandle)->GetFrameSize(); } const unsigned int CAddonCallbacksAudioEngine::AEStream_GetChannelCount(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return 0; } return ((IAEStream*)StreamHandle)->GetChannelCount(); } const unsigned int CAddonCallbacksAudioEngine::AEStream_GetSampleRate(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return 0; } return ((IAEStream*)StreamHandle)->GetSampleRate(); } const AEDataFormat CAddonCallbacksAudioEngine::AEStream_GetDataFormat(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return AE_FMT_INVALID; } return ((IAEStream*)StreamHandle)->GetDataFormat(); } double CAddonCallbacksAudioEngine::AEStream_GetResampleRatio(void *AddonData, AEStreamHandle *StreamHandle) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return -1.0f; } return ((IAEStream*)StreamHandle)->GetResampleRatio(); } void CAddonCallbacksAudioEngine::AEStream_SetResampleRatio(void *AddonData, AEStreamHandle *StreamHandle, double Ratio) { // prevent compiler warnings void *addonData = AddonData; if (!addonData || !StreamHandle) { CLog::Log(LOGERROR, "libKODI_audioengine - %s - invalid stream data", __FUNCTION__); return; } ((IAEStream*)StreamHandle)->SetResampleRatio(Ratio); } } /* namespace AudioEngine */ } /* namespace KodiAPI */ } /* namespace V1 */
gpl-2.0
dockerizedrupal/dockerizedrupal.com
core/modules/views/src/Tests/Plugin/MenuLinkTest.php
2751
<?php namespace Drupal\views\Tests\Plugin; use Drupal\menu_link_content\Entity\MenuLinkContent; use Drupal\views\Tests\ViewTestBase; /** * Tests the menu links created in views. * * @group views */ class MenuLinkTest extends ViewTestBase { /** * Views used by this test. * * @var array */ public static $testViews = ['test_menu_link']; /** * Modules to enable. * * @var array */ public static $modules = ['views', 'views_ui', 'user', 'node', 'menu_ui', 'block']; /** * A user with permission to administer views, menus and view content. * * @var \Drupal\user\UserInterface */ protected $adminUser; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->enableViewsTestModule(); $this->adminUser = $this->drupalCreateUser(['administer views', 'administer menu']); $this->drupalPlaceBlock('system_menu_block:main'); $this->drupalCreateContentType(['type' => 'page']); } /** * Test that menu links using menu_link_content as parent are visible. */ public function testHierarchicalMenuLinkVisibility() { $this->drupalLogin($this->adminUser); $node = $this->drupalCreateNode(['type' => 'page']); // Create a primary level menu link to the node. $link = MenuLinkContent::create([ 'title' => 'Primary level node', 'menu_name' => 'main', 'bundle' => 'menu_link_content', 'parent' => '', 'link' => [['uri' => 'entity:node/' . $node->id()]], ]); $link->save(); $parent_menu_value = 'main:menu_link_content:' . $link->uuid(); // Alter the view's menu link in view page to use the menu link from the // node as parent. $this->drupalPostForm("admin/structure/views/nojs/display/test_menu_link/page_1/menu", [ 'menu[type]' => 'normal', 'menu[title]' => 'Secondary level view page', 'menu[parent]' => $parent_menu_value, ], 'Apply'); // Save view which has pending changes. $this->drupalPostForm(NULL, [], 'Save'); // Test if the node as parent menu item is selected in our views settings. $this->drupalGet('admin/structure/views/nojs/display/test_menu_link/page_1/menu'); $this->assertOptionSelected('edit-menu-parent', $parent_menu_value); $this->drupalGet(''); // Test if the primary menu item (node) is visible, and the secondary menu // item (view) is hidden. $this->assertText('Primary level node'); $this->assertNoText('Secondary level view page'); // Go to the node page and ensure that both the first and second level items // are visible. $this->drupalGet($node->urlInfo()); $this->assertText('Primary level node'); $this->assertText('Secondary level view page'); } }
gpl-2.0
Yonnick/userinfuser
static/lib/development-bundle/ui/jquery.ui.resizable.js
26336
/* * jQuery UI Resizable 1.8.5 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Resizables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function( $, undefined ) { $.widget("ui.resizable", $.ui.mouse, { widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, zIndex: 1000 }, _create: function() { var self = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Opera fix for relative positioning if (/relative/.test(this.element.css('position')) && $.browser.opera) this.element.css({ position: 'relative', top: 'auto', left: 'auto' }); //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({ position: this.element.css('position'), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css('top'), left: this.element.css('left') }) ); //Overwrite the original this.element this.element = this.element.parent().data( "resizable", this.element.data('resizable') ); this.elementIsWrapper = true; //Move margins to the wrapper this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css('resize'); this.originalElement.css('resize', 'none'); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css('margin') }); // fix handlers offset this._proportionallyResize(); } this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }); if(this.handles.constructor == String) { if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; var n = this.handles.split(","); this.handles = {}; for(var i = 0; i < n.length; i++) { var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>'); // increase zIndex of sw, se, ne, nw axis //TODO : this modifies original option if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex }); //TODO : What's going on here? if ('se' == handle) { axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); }; //Insert into internal handles object and append to element this.handles[handle] = '.ui-resizable-'+handle; this.element.append(axis); } } this._renderAxis = function(target) { target = target || this.element; for(var i in this.handles) { if(this.handles[i].constructor == String) this.handles[i] = $(this.handles[i], this.element).show(); //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { var axis = $(this.handles[i], this.element), padWrapper = 0; //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... var padPos = [ 'padding', /ne|nw|n/.test(i) ? 'Top' : /se|sw|s/.test(i) ? 'Bottom' : /^e$/.test(i) ? 'Right' : 'Left' ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) continue; } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $('.ui-resizable-handle', this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!self.resizing) { if (this.className) var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); //Axis, default = se self.axis = axis && axis[1] ? axis[1] : 'se'; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .hover(function() { $(this).removeClass("ui-resizable-autohide"); self._handles.show(); }, function(){ if (!self.resizing) { $(this).addClass("ui-resizable-autohide"); self._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, destroy: function() { this._mouseDestroy(); var _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); var wrapper = this.element; wrapper.after( this.originalElement.css({ position: wrapper.css('position'), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css('top'), left: wrapper.css('left') }) ).remove(); } this.originalElement.css('resize', this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var handle = false; for (var i in this.handles) { if ($(this.handles[i])[0] == event.target) { handle = true; } } return !this.options.disabled && handle; }, _mouseStart: function(event) { var o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; // bugfix for http://dev.jquery.com/ticket/1749 if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); } //Opera fixing relative position if ($.browser.opera && (/relative/).test(el.css('position'))) el.css({ position: 'relative', top: 'auto', left: 'auto' }); this._renderProxy(); var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); var cursor = $('.ui-resizable-' + this.axis).css('cursor'); $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var el = this.helper, o = this.options, props = {}, self = this, smp = this.originalMousePosition, a = this.axis; var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; var trigger = this._change[a]; if (!trigger) return false; // Calculate the attrs that will be change var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; if (this._aspectRatio || event.shiftKey) data = this._updateRatio(data, event); data = this._respectSize(data, event); // plugins callbacks need to be called first this._propagate("resize", event); el.css({ top: this.position.top + "px", left: this.position.left + "px", width: this.size.width + "px", height: this.size.height + "px" }); if (!this._helper && this._proportionallyResizeElements.length) this._proportionallyResize(); this._updateCache(data); // calling the user callback at the end this._trigger('resize', event, this.ui()); return false; }, _mouseStop: function(event) { this.resizing = false; var o = this.options, self = this; if(this._helper) { var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, soffsetw = ista ? 0 : self.sizeDiff.width; var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; if (!o.animate) this.element.css($.extend(s, { top: top, left: left })); self.helper.height(self.size.height); self.helper.width(self.size.width); if (this._helper && !o.animate) this._proportionallyResize(); } $('body').css('cursor', 'auto'); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) this.helper.remove(); return false; }, _updateCache: function(data) { var o = this.options; this.offset = this.helper.offset(); if (isNumber(data.left)) this.position.left = data.left; if (isNumber(data.top)) this.position.top = data.top; if (isNumber(data.height)) this.size.height = data.height; if (isNumber(data.width)) this.size.width = data.width; }, _updateRatio: function(data, event) { var o = this.options, cpos = this.position, csize = this.size, a = this.axis; if (data.height) data.width = (csize.height * this.aspectRatio); else if (data.width) data.height = (csize.width / this.aspectRatio); if (a == 'sw') { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a == 'nw') { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function(data, event) { var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); if (isminw) data.width = o.minWidth; if (isminh) data.height = o.minHeight; if (ismaxw) data.width = o.maxWidth; if (ismaxh) data.height = o.maxHeight; var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw && cw) data.left = dw - o.minWidth; if (ismaxw && cw) data.left = dw - o.maxWidth; if (isminh && ch) data.top = dh - o.minHeight; if (ismaxh && ch) data.top = dh - o.maxHeight; // fixing jump error on top/left - bug #2330 var isNotwh = !data.width && !data.height; if (isNotwh && !data.left && data.top) data.top = null; else if (isNotwh && !data.top && data.left) data.left = null; return data; }, _proportionallyResize: function() { var o = this.options; if (!this._proportionallyResizeElements.length) return; var element = this.helper || this.element; for (var i=0; i < this._proportionallyResizeElements.length; i++) { var prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; this.borderDif = $.map(b, function(v, i) { var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; return border + padding; }); } if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) continue; prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); }; }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); // fix ie6 offset TODO: This seems broken var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), pxyoffset = ( ie6 ? 2 : -1 ); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() + pxyoffset, height: this.element.outerHeight() + pxyoffset, position: 'absolute', left: this.elementOffset.left - ie6offset +'px', top: this.elementOffset.top - ie6offset +'px', zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx, dy) { return { width: this.originalSize.width + dx }; }, w: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n != "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } }); $.extend($.ui.resizable, { version: "1.8.5" }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "alsoResize", { start: function (event, ui) { var self = $(this).data("resizable"), o = self.options; var _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10), position: el.css('position') // to reset Opera on stop() }); }); }; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition; var delta = { height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left']; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) style[prop] = sum || null; }); // Opera fixing relative position if ($.browser.opera && /relative/.test(el.css('position'))) { self._revertToRelativePosition = true; el.css({ position: 'absolute', top: 'auto', left: 'auto' }); } el.css(style); }); }; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function (event, ui) { var self = $(this).data("resizable"), o = self.options; var _reset = function (exp) { $(exp).each(function() { var el = $(this); // reset position for Opera - no need to verify it was changed el.css({ position: el.data("resizable-alsoresize").position }); }); }; if (self._revertToRelativePosition) { self._revertToRelativePosition = false; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp) { _reset(exp); }); }else{ _reset(o.alsoResize); } } $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "animate", { stop: function(event, ui) { var self = $(this).data("resizable"), o = self.options; var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, soffsetw = ista ? 0 : self.sizeDiff.width; var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; self.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(self.element.css('width'), 10), height: parseInt(self.element.css('height'), 10), top: parseInt(self.element.css('top'), 10), left: parseInt(self.element.css('left'), 10) }; if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); // propagating resize, and updating values for each animation step self._updateCache(data); self._propagate("resize", event); } } ); } }); $.ui.plugin.add("resizable", "containment", { start: function(event, ui) { var self = $(this).data("resizable"), o = self.options, el = self.element; var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) return; self.containerElement = $(ce); if (/document/.test(oc) || oc == document) { self.containerOffset = { left: 0, top: 0 }; self.containerPosition = { left: 0, top: 0 }; self.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else { var element = $(ce), p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); self.containerOffset = element.offset(); self.containerPosition = element.position(); self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); self.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function(event, ui) { var self = $(this).data("resizable"), o = self.options, ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; if (cp.left < (self._helper ? co.left : 0)) { self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left)); if (pRatio) self.size.height = self.size.width / o.aspectRatio; self.position.left = o.helper ? co.left : 0; } if (cp.top < (self._helper ? co.top : 0)) { self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); if (pRatio) self.size.width = self.size.height * o.aspectRatio; self.position.top = self._helper ? co.top : 0; } self.offset.left = self.parentData.left+self.position.left; self.offset.top = self.parentData.top+self.position.top; var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); var isParent = self.containerElement.get(0) == self.element.parent().get(0), isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); if(isParent && isOffsetRelative) woset -= self.parentData.left; if (woset + self.size.width >= self.parentData.width) { self.size.width = self.parentData.width - woset; if (pRatio) self.size.height = self.size.width / self.aspectRatio; } if (hoset + self.size.height >= self.parentData.height) { self.size.height = self.parentData.height - hoset; if (pRatio) self.size.width = self.size.height * self.aspectRatio; } }, stop: function(event, ui){ var self = $(this).data("resizable"), o = self.options, cp = self.position, co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); if (self._helper && !o.animate && (/static/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } }); $.ui.plugin.add("resizable", "ghost", { start: function(event, ui) { var self = $(this).data("resizable"), o = self.options, cs = self.size; self.ghost = self.originalElement.clone(); self.ghost .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass('ui-resizable-ghost') .addClass(typeof o.ghost == 'string' ? o.ghost : ''); self.ghost.appendTo(self.helper); }, resize: function(event, ui){ var self = $(this).data("resizable"), o = self.options; if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); }, stop: function(event, ui){ var self = $(this).data("resizable"), o = self.options; if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); } }); $.ui.plugin.add("resizable", "grid", { resize: function(event, ui) { var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey; o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); if (/^(se|s|e)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; } else if (/^(ne)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.left = op.left - ox; } else { self.size.width = os.width + ox; self.size.height = os.height + oy; self.position.top = op.top - oy; self.position.left = op.left - ox; } } }); var num = function(v) { return parseInt(v, 10) || 0; }; var isNumber = function(value) { return !isNaN(parseInt(value, 10)); }; })(jQuery);
gpl-3.0
srijeyanthan/hadoop_2_4_0_experimental_version
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HdfsConfiguration.java
6589
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.classification.InterfaceAudience; /** * Adds deprecated keys into the configuration. */ @InterfaceAudience.Private public class HdfsConfiguration extends Configuration { static { addDeprecatedKeys(); // adds the default resources Configuration.addDefaultResource("hdfs-default.xml"); Configuration.addDefaultResource("hdfs-site.xml"); } public HdfsConfiguration() { super(); } public HdfsConfiguration(boolean loadDefaults) { super(loadDefaults); } public HdfsConfiguration(Configuration conf) { super(conf); } /** * This method is here so that when invoked, HdfsConfiguration is class-loaded if * it hasn't already been previously loaded. Upon loading the class, the static * initializer block above will be executed to add the deprecated keys and to add * the default resources. It is safe for this method to be called multiple times * as the static initializer block will only get invoked once. * * This replaces the previously, dangerous practice of other classes calling * Configuration.addDefaultResource("hdfs-default.xml") directly without loading * HdfsConfiguration class first, thereby skipping the key deprecation */ public static void init() { } private static void addDeprecatedKeys() { Configuration.addDeprecations(new DeprecationDelta[] { new DeprecationDelta("dfs.backup.address", DFSConfigKeys.DFS_NAMENODE_BACKUP_ADDRESS_KEY), new DeprecationDelta("dfs.backup.http.address", DFSConfigKeys.DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY), new DeprecationDelta("dfs.balance.bandwidthPerSec", DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY), new DeprecationDelta("dfs.data.dir", DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY), new DeprecationDelta("dfs.http.address", DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY), new DeprecationDelta("dfs.https.address", DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY), new DeprecationDelta("dfs.max.objects", DFSConfigKeys.DFS_NAMENODE_MAX_OBJECTS_KEY), new DeprecationDelta("dfs.name.dir", DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY), new DeprecationDelta("dfs.name.dir.restore", DFSConfigKeys.DFS_NAMENODE_NAME_DIR_RESTORE_KEY), new DeprecationDelta("dfs.name.edits.dir", DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY), new DeprecationDelta("dfs.read.prefetch.size", DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY), new DeprecationDelta("dfs.safemode.extension", DFSConfigKeys.DFS_NAMENODE_SAFEMODE_EXTENSION_KEY), new DeprecationDelta("dfs.safemode.threshold.pct", DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY), new DeprecationDelta("dfs.secondary.http.address", DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY), new DeprecationDelta("dfs.socket.timeout", DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY), new DeprecationDelta("fs.checkpoint.dir", DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_DIR_KEY), new DeprecationDelta("fs.checkpoint.edits.dir", DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_EDITS_DIR_KEY), new DeprecationDelta("fs.checkpoint.period", DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_PERIOD_KEY), new DeprecationDelta("heartbeat.recheck.interval", DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY), new DeprecationDelta("dfs.https.client.keystore.resource", DFSConfigKeys.DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY), new DeprecationDelta("dfs.https.need.client.auth", DFSConfigKeys.DFS_CLIENT_HTTPS_NEED_AUTH_KEY), new DeprecationDelta("slave.host.name", DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY), new DeprecationDelta("session.id", DFSConfigKeys.DFS_METRICS_SESSION_ID_KEY), new DeprecationDelta("dfs.access.time.precision", DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY), new DeprecationDelta("dfs.replication.considerLoad", DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY), new DeprecationDelta("dfs.replication.interval", DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY), new DeprecationDelta("dfs.replication.min", DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY), new DeprecationDelta("dfs.replication.pending.timeout.sec", DFSConfigKeys.DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_KEY), new DeprecationDelta("dfs.max-repl-streams", DFSConfigKeys.DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY), new DeprecationDelta("dfs.permissions", DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY), new DeprecationDelta("dfs.permissions.supergroup", DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_KEY), new DeprecationDelta("dfs.write.packet.size", DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY), new DeprecationDelta("dfs.block.size", DFSConfigKeys.DFS_BLOCK_SIZE_KEY), new DeprecationDelta("dfs.datanode.max.xcievers", DFSConfigKeys.DFS_DATANODE_MAX_RECEIVER_THREADS_KEY), new DeprecationDelta("io.bytes.per.checksum", DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY), new DeprecationDelta("dfs.federation.nameservices", DFSConfigKeys.DFS_NAMESERVICES), new DeprecationDelta("dfs.federation.nameservice.id", DFSConfigKeys.DFS_NAMESERVICE_ID), new DeprecationDelta("dfs.client.file-block-storage-locations.timeout", DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_MS) }); } public static void main(String[] args) { init(); Configuration.dumpDeprecatedKeys(); } }
apache-2.0
esi-mineset/spark
core/src/main/scala/org/apache/spark/storage/BlockManagerMessages.scala
4783
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.storage import java.io.{Externalizable, ObjectInput, ObjectOutput} import org.apache.spark.rpc.RpcEndpointRef import org.apache.spark.util.Utils private[spark] object BlockManagerMessages { ////////////////////////////////////////////////////////////////////////////////// // Messages from the master to slaves. ////////////////////////////////////////////////////////////////////////////////// sealed trait ToBlockManagerSlave // Remove a block from the slaves that have it. This can only be used to remove // blocks that the master knows about. case class RemoveBlock(blockId: BlockId) extends ToBlockManagerSlave // Replicate blocks that were lost due to executor failure case class ReplicateBlock(blockId: BlockId, replicas: Seq[BlockManagerId], maxReplicas: Int) extends ToBlockManagerSlave // Remove all blocks belonging to a specific RDD. case class RemoveRdd(rddId: Int) extends ToBlockManagerSlave // Remove all blocks belonging to a specific shuffle. case class RemoveShuffle(shuffleId: Int) extends ToBlockManagerSlave // Remove all blocks belonging to a specific broadcast. case class RemoveBroadcast(broadcastId: Long, removeFromDriver: Boolean = true) extends ToBlockManagerSlave /** * Driver to Executor message to trigger a thread dump. */ case object TriggerThreadDump extends ToBlockManagerSlave ////////////////////////////////////////////////////////////////////////////////// // Messages from slaves to the master. ////////////////////////////////////////////////////////////////////////////////// sealed trait ToBlockManagerMaster case class RegisterBlockManager( blockManagerId: BlockManagerId, maxOnHeapMemSize: Long, maxOffHeapMemSize: Long, sender: RpcEndpointRef) extends ToBlockManagerMaster case class UpdateBlockInfo( var blockManagerId: BlockManagerId, var blockId: BlockId, var storageLevel: StorageLevel, var memSize: Long, var diskSize: Long) extends ToBlockManagerMaster with Externalizable { def this() = this(null, null, null, 0, 0) // For deserialization only override def writeExternal(out: ObjectOutput): Unit = Utils.tryOrIOException { blockManagerId.writeExternal(out) out.writeUTF(blockId.name) storageLevel.writeExternal(out) out.writeLong(memSize) out.writeLong(diskSize) } override def readExternal(in: ObjectInput): Unit = Utils.tryOrIOException { blockManagerId = BlockManagerId(in) blockId = BlockId(in.readUTF()) storageLevel = StorageLevel(in) memSize = in.readLong() diskSize = in.readLong() } } case class GetLocations(blockId: BlockId) extends ToBlockManagerMaster case class GetLocationsAndStatus(blockId: BlockId) extends ToBlockManagerMaster // The response message of `GetLocationsAndStatus` request. case class BlockLocationsAndStatus(locations: Seq[BlockManagerId], status: BlockStatus) { assert(locations.nonEmpty) } case class GetLocationsMultipleBlockIds(blockIds: Array[BlockId]) extends ToBlockManagerMaster case class GetPeers(blockManagerId: BlockManagerId) extends ToBlockManagerMaster case class GetExecutorEndpointRef(executorId: String) extends ToBlockManagerMaster case class RemoveExecutor(execId: String) extends ToBlockManagerMaster case object StopBlockManagerMaster extends ToBlockManagerMaster case object GetMemoryStatus extends ToBlockManagerMaster case object GetStorageStatus extends ToBlockManagerMaster case class GetBlockStatus(blockId: BlockId, askSlaves: Boolean = true) extends ToBlockManagerMaster case class GetMatchingBlockIds(filter: BlockId => Boolean, askSlaves: Boolean = true) extends ToBlockManagerMaster case class BlockManagerHeartbeat(blockManagerId: BlockManagerId) extends ToBlockManagerMaster case class HasCachedBlocks(executorId: String) extends ToBlockManagerMaster }
apache-2.0
him2him2/cdnjs
ajax/libs/mobx-react/3.5.0/index.js
16011
(function() { function mrFactory(mobx, React, ReactDOM) { if (!mobx) throw new Error("mobx-react requires the MobX package") if (!React) throw new Error("mobx-react requires React to be available"); /** * dev tool support */ var isDevtoolsEnabled = false; // WeakMap<Node, Object>; var componentByNodeRegistery = typeof WeakMap !== "undefined" ? new WeakMap() : undefined; var renderReporter = new EventEmitter(); function findDOMNode(component) { if (ReactDOM) return ReactDOM.findDOMNode(component); return null; } function reportRendering(component) { var node = findDOMNode(component); if (node && componentByNodeRegistery) componentByNodeRegistery.set(node, component); renderReporter.emit({ event: 'render', renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart, component: component, node: node }); } function trackComponents() { if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser."); if (!isDevtoolsEnabled) isDevtoolsEnabled = true; } function EventEmitter() { this.listeners = []; }; EventEmitter.prototype.on = function (cb) { this.listeners.push(cb); var self = this; return function() { var idx = self.listeners.indexOf(cb); if (idx !== -1) self.listeners.splice(idx, 1); }; }; EventEmitter.prototype.emit = function(data) { this.listeners.forEach(function (fn) { fn(data); }); }; /** * Utilities */ var specialReactKeys = { children: true, key: true, ref: true }; function patch(target, funcName) { var base = target[funcName]; var mixinFunc = reactiveMixin[funcName]; if (!base) { target[funcName] = mixinFunc; } else { target[funcName] = function() { base.apply(this, arguments); mixinFunc.apply(this, arguments); } } } /** * ReactiveMixin */ var reactiveMixin = { componentWillMount: function() { // Generate friendly name for debugging var name = [ this.displayName || this.name || (this.constructor && (this.constructor.displayName || this.constructor.name)) || "<component>", "#", this._reactInternalInstance && this._reactInternalInstance._rootNodeID, ".render()" ].join(""); var baseRender = this.render.bind(this); var self = this; var reaction = null; var isRenderingPending = false; function initialRender() { reaction = new mobx.Reaction(name, function() { if (!isRenderingPending) { isRenderingPending = true; if (typeof self.componentWillReact === "function") self.componentWillReact(); if (self.__$mobxMounted) React.Component.prototype.forceUpdate.call(self) } }); reactiveRender.$mobx = reaction; self.render = reactiveRender; return reactiveRender(); } function reactiveRender() { isRenderingPending = false; var rendering; reaction.track(function() { if (isDevtoolsEnabled) self.__$mobRenderStart = Date.now(); rendering = mobx.extras.allowStateChanges(false, baseRender); if (isDevtoolsEnabled) self.__$mobRenderEnd = Date.now(); }); return rendering; } this.render = initialRender; }, componentWillUnmount: function() { this.render.$mobx && this.render.$mobx.dispose(); this.__$mobxMounted = false; if (isDevtoolsEnabled) { var node = findDOMNode(this); if (node && componentByNodeRegistery) { componentByNodeRegistery.delete(node); } renderReporter.emit({ event: 'destroy', component: this, node: node }); } }, componentDidMount: function() { this.__$mobxMounted = true; if (isDevtoolsEnabled) reportRendering(this); }, componentDidUpdate: function() { if (isDevtoolsEnabled) reportRendering(this); }, shouldComponentUpdate: function(nextProps, nextState) { // TODO: if context changed, return true.., see #18 // if props or state did change, but a render was scheduled already, no additional render needs to be scheduled if (this.render.$mobx && this.render.$mobx.isScheduled() === true) return false; // update on any state changes (as is the default) if (this.state !== nextState) return true; // update if props are shallowly not equal, inspired by PureRenderMixin var keys = Object.keys(this.props); var key; if (keys.length !== Object.keys(nextProps).length) return true; for(var i = keys.length -1; i >= 0, key = keys[i]; i--) { var newValue = nextProps[key]; if (newValue !== this.props[key]) { return true; } else if (newValue && typeof newValue === "object" && !mobx.isObservable(newValue)) { /** * If the newValue is still the same object, but that object is not observable, * fallback to the default React behavior: update, because the object *might* have changed. * If you need the non default behavior, just use the React pure render mixin, as that one * will work fine with mobx as well, instead of the default implementation of * observer. */ return true; } } return false; } } /** * Observer function / decorator */ function observer(arg1, arg2) { if (typeof arg1 === "string") throw new Error("Store names should be provided as array"); if (Array.isArray(arg1)) { // component needs stores if (!arg2) { // invoked as decorator return function(componentClass) { return observer(arg1, componentClass); } } else { // TODO: deprecate this invocation style return inject.apply(null, arg1)(observer(arg2)); } } var componentClass = arg1; // Stateless function component: // If it is function but doesn't seem to be a react class constructor, // wrap it to a react class automatically if ( typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass) ) { return observer(React.createClass({ displayName: componentClass.displayName || componentClass.name, propTypes: componentClass.propTypes, contextTypes: componentClass.contextTypes, getDefaultProps: function() { return componentClass.defaultProps; }, render: function() { return componentClass.call(this, this.props, this.context); } })); } if (!componentClass) throw new Error("Please pass a valid component to 'observer'"); var target = componentClass.prototype || componentClass; [ "componentWillMount", "componentWillUnmount", "componentDidMount", "componentDidUpdate" ].forEach(function(funcName) { patch(target, funcName) }); if (!target.shouldComponentUpdate) target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate; componentClass.isMobXReactObserver = true; return componentClass; } /** * Store provider */ var Provider = React.createClass({ displayName: "Provider", render: function() { return React.Children.only(this.props.children); }, getChildContext: function () { var stores = {}; // inherit stores var baseStores = this.context.mobxStores; if (baseStores) for (var key in baseStores) { stores[key] = baseStores[key]; } // add own stores for (var key in this.props) if (!specialReactKeys[key]) stores[key] = this.props[key]; return { mobxStores: stores }; }, componentWillReceiveProps: function(nextProps) { // Maybe this warning is to aggressive? if (Object.keys(nextProps).length !== Object.keys(this.props).length) console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children"); for (var key in nextProps) if (!specialReactKeys[key] && this.props[key] !== nextProps[key]) console.warn("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children"); } }); var PropTypes = React.PropTypes; Provider.contextTypes = { mobxStores: PropTypes.object }; Provider.childContextTypes = { mobxStores: PropTypes.object.isRequired }; /** * Store Injection */ function createStoreInjector(grabStoresFn, component) { var Injector = React.createClass({ displayName: "MobXStoreInjector", render: function() { var newProps = {}; for (var key in this.props) newProps[key] = this.props[key]; newProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context); return React.createElement(component, newProps); } // TODO: should have shouldComponentUpdate? }); Injector.contextTypes = { mobxStores: PropTypes.object }; Injector.wrappedComponent = component; return Injector; } /** * higher order component that injects stores to a child. * takes either a varargs list of strings, which are stores read from the context, * or a function that manually maps the available stores from the context to props: * storesToProps(mobxStores, props, context) => newProps */ function inject(/* fn(stores, nextProps) or ...storeNames */) { var grabStoresFn; if (typeof arguments[0] === "function") { grabStoresFn = arguments[0]; } else { var storesNames = []; for (var i = 0; i < arguments.length; i++) storesNames[i] = arguments[i]; grabStoresFn = grabStoresByName(storesNames); } return function(componentClass) { return createStoreInjector(grabStoresFn, componentClass); }; } function grabStoresByName(storeNames) { return function(baseStores, nextProps) { storeNames.forEach(function(storeName) { if (storeName in nextProps) // prefer props over stores return; if (!(storeName in baseStores)) throw new Error("MobX observer: Store '" + storeName + "' is not available! Make sure it is provided by some Provider"); nextProps[storeName] = baseStores[storeName]; }); return nextProps; } } /** * PropTypes */ function observableTypeChecker (type) { return function(props, propName, componentName) { if (!mobx['isObservable' + type](props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Expected a mobx observable ' + type + '. Validation failed.' ); } }; } // oneOfType is used for simple isRequired chaining var propTypes = { observableArray: React.PropTypes.oneOfType([observableTypeChecker('Array')]), observableMap: React.PropTypes.oneOfType([observableTypeChecker('Map')]), observableObject: React.PropTypes.oneOfType([observableTypeChecker('Object')]), arrayOrObservableArray: React.PropTypes.oneOfType([ React.PropTypes.array, observableTypeChecker('Array') ]), objectOrObservableObject: React.PropTypes.oneOfType([ React.PropTypes.object, observableTypeChecker('Object') ]) }; /** * Export */ return ({ observer: observer, Provider: Provider, inject: inject, propTypes: propTypes, reactiveComponent: function() { console.warn("[mobx-react] `reactiveComponent` has been renamed to `observer` and will be removed in 1.1."); return observer.apply(null, arguments); }, renderReporter: renderReporter, componentByNodeRegistery: componentByNodeRegistery, trackComponents: trackComponents }); } /** * UMD */ if (typeof exports === 'object') { module.exports = mrFactory(require('mobx'), require('react'), require('react-dom')); } else if (typeof define === 'function' && define.amd) { define('mobx-react', ['mobx', 'react', 'react-dom'], mrFactory); } else { this.mobxReact = mrFactory(this['mobx'], this['React'], this['ReactDOM']); } })();
mit
arnaudchenyensu/vagrant-php
modules/concat/spec/spec_helper_system.rb
664
require 'rspec-system/spec_helper' require 'rspec-system-puppet/helpers' require 'rspec-system-serverspec/helpers' include Serverspec::Helper::RSpecSystem include Serverspec::Helper::DetectOS include RSpecSystemPuppet::Helpers RSpec.configure do |c| # Project root proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) # Enable colour c.tty = true c.include RSpecSystemPuppet::Helpers # This is where we 'setup' the nodes before running our tests c.before :suite do # Install puppet puppet_install # Install modules and dependencies puppet_module_install(:source => proj_root, :module_name => 'concat') end end
gpl-2.0
sushengyang/CoreNLP
src/edu/stanford/nlp/international/arabic/pipeline/UniversalPOSMapper.java
3545
package edu.stanford.nlp.international.arabic.pipeline; import java.io.*; import java.util.List; import java.util.Map; import edu.stanford.nlp.international.arabic.ArabicMorphoFeatureSpecification; import edu.stanford.nlp.international.morph.MorphoFeatureSpecification; import edu.stanford.nlp.international.morph.MorphoFeatures; import edu.stanford.nlp.international.morph.MorphoFeatureSpecification.MorphoFeatureType; import edu.stanford.nlp.util.Generics; /** * Maps LDC-provided Bies mappings to the Universal POS tag set described in * * Slav Petrov, Dipanjan Das and Ryan McDonald. "A Universal Part-of-Speech Tagset." * <p> * Includes optional support for adding morphological annotations via the setup method. * * @author Spence Green * */ public class UniversalPOSMapper extends LDCPosMapper { private final Map<String,String> universalMap; private final MorphoFeatureSpecification morphoSpec; public UniversalPOSMapper(){ super(false); //Don't add the determiner split universalMap = Generics.newHashMap(); morphoSpec = new ArabicMorphoFeatureSpecification(); } /** * First map to the LDC short tags. Then map to the Universal POS. Then add * morphological annotations. */ @Override public String map(String posTag, String terminal) { String rawTag = posTag.trim(); String shortTag = tagsToEscape.contains(rawTag) ? rawTag : tagMap.get(rawTag); if( shortTag == null ) { System.err.printf("%s: No LDC shortened tag for %s%n", this.getClass().getName(), rawTag); return rawTag; } String universalTag = universalMap.get(shortTag); if( ! universalMap.containsKey(shortTag)) { System.err.printf("%s: No universal tag for LDC tag %s%n", this.getClass().getName(),shortTag); universalTag = shortTag; } MorphoFeatures feats = new MorphoFeatures(morphoSpec.strToFeatures(rawTag)); String functionalTag = feats.getTag(universalTag); return functionalTag; } @Override public void setup(File path, String... options) { //Setup the Bies tag mapping super.setup(path, new String[0]); for(String opt : options) { String[] optToks = opt.split(":"); if(optToks[0].equals("UniversalMap") && optToks.length == 2) { loadUniversalMap(optToks[1]); } else { //Maybe it's a morphological feature //Both of these calls will throw exceptions if the feature is illegal/invalid MorphoFeatureType feat = MorphoFeatureType.valueOf(optToks[0]); List<String> featVals = morphoSpec.getValues(feat); morphoSpec.activate(feat); } } } private void loadUniversalMap(String path) { LineNumberReader reader = null; try { reader = new LineNumberReader(new FileReader(path)); for(String line; (line = reader.readLine()) != null;) { if(line.trim().equals("")) continue; String[] toks = line.trim().split("\\s+"); if(toks.length != 2) throw new RuntimeException("Invalid mapping line: " + line); universalMap.put(toks[0], toks[1]); } reader.close(); } catch (FileNotFoundException e) { System.err.printf("%s: File not found %s%n", this.getClass().getName(),path); } catch (IOException e) { int lineId = (reader == null) ? -1 : reader.getLineNumber(); System.err.printf("%s: Error at line %d%n", this.getClass().getName(),lineId); e.printStackTrace(); } } }
gpl-2.0
jriegel/FreeCAD
src/Mod/Assembly/App/ProductRef.cpp
2516
/*************************************************************************** * Copyright (c) 2012 Juergen Riegel <FreeCAD@juergen-riegel.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRep_Builder.hxx> # include <TopoDS_Compound.hxx> #include <boost/exception/get_error_info.hpp> #endif #include <Base/Placement.h> #include <Base/Console.h> #include <App/Part.h> #include "ProductRef.h" #include "ConstraintGroup.h" #include "ProductRefPy.h" using namespace Assembly; namespace Assembly { PROPERTY_SOURCE(Assembly::ProductRef, Assembly::Item) ProductRef::ProductRef() { ADD_PROPERTY(Item,(0)); } short ProductRef::mustExecute() const { return 0; } App::DocumentObjectExecReturn* ProductRef::execute(void) { return App::DocumentObject::StdReturn; } PyObject* ProductRef::getPyObject(void) { if(PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new ProductRefPy(this),true); } return Py::new_reference_to(PythonObject); } } //assembly
lgpl-2.1
unreal666/youtube-dl
youtube_dl/extractor/qqmusic.py
13646
# coding: utf-8 from __future__ import unicode_literals import random import re import time from .common import InfoExtractor from ..utils import ( clean_html, ExtractorError, strip_jsonp, unescapeHTML, ) class QQMusicIE(InfoExtractor): IE_NAME = 'qqmusic' IE_DESC = 'QQ音乐' _VALID_URL = r'https?://y\.qq\.com/n/yqq/song/(?P<id>[0-9A-Za-z]+)\.html' _TESTS = [{ 'url': 'https://y.qq.com/n/yqq/song/004295Et37taLD.html', 'md5': '5f1e6cea39e182857da7ffc5ef5e6bb8', 'info_dict': { 'id': '004295Et37taLD', 'ext': 'mp3', 'title': '可惜没如果', 'release_date': '20141227', 'creator': '林俊杰', 'description': 'md5:d85afb3051952ecc50a1ee8a286d1eac', 'thumbnail': r're:^https?://.*\.jpg$', } }, { 'note': 'There is no mp3-320 version of this song.', 'url': 'https://y.qq.com/n/yqq/song/004MsGEo3DdNxV.html', 'md5': 'fa3926f0c585cda0af8fa4f796482e3e', 'info_dict': { 'id': '004MsGEo3DdNxV', 'ext': 'mp3', 'title': '如果', 'release_date': '20050626', 'creator': '李季美', 'description': 'md5:46857d5ed62bc4ba84607a805dccf437', 'thumbnail': r're:^https?://.*\.jpg$', } }, { 'note': 'lyrics not in .lrc format', 'url': 'https://y.qq.com/n/yqq/song/001JyApY11tIp6.html', 'info_dict': { 'id': '001JyApY11tIp6', 'ext': 'mp3', 'title': 'Shadows Over Transylvania', 'release_date': '19970225', 'creator': 'Dark Funeral', 'description': 'md5:c9b20210587cbcd6836a1c597bab4525', 'thumbnail': r're:^https?://.*\.jpg$', }, 'params': { 'skip_download': True, }, }] _FORMATS = { 'mp3-320': {'prefix': 'M800', 'ext': 'mp3', 'preference': 40, 'abr': 320}, 'mp3-128': {'prefix': 'M500', 'ext': 'mp3', 'preference': 30, 'abr': 128}, 'm4a': {'prefix': 'C200', 'ext': 'm4a', 'preference': 10} } # Reference: m_r_GetRUin() in top_player.js # http://imgcache.gtimg.cn/music/portal_v3/y/top_player.js @staticmethod def m_r_get_ruin(): curMs = int(time.time() * 1000) % 1000 return int(round(random.random() * 2147483647) * curMs % 1E10) def _real_extract(self, url): mid = self._match_id(url) detail_info_page = self._download_webpage( 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_yqq_song_detail_info.fcg?songmid=%s&play=0' % mid, mid, note='Download song detail info', errnote='Unable to get song detail info', encoding='gbk') song_name = self._html_search_regex( r"songname:\s*'([^']+)'", detail_info_page, 'song name') publish_time = self._html_search_regex( r'发行时间:(\d{4}-\d{2}-\d{2})', detail_info_page, 'publish time', default=None) if publish_time: publish_time = publish_time.replace('-', '') singer = self._html_search_regex( r"singer:\s*'([^']+)", detail_info_page, 'singer', default=None) lrc_content = self._html_search_regex( r'<div class="content" id="lrc_content"[^<>]*>([^<>]+)</div>', detail_info_page, 'LRC lyrics', default=None) if lrc_content: lrc_content = lrc_content.replace('\\n', '\n') thumbnail_url = None albummid = self._search_regex( [r'albummid:\'([0-9a-zA-Z]+)\'', r'"albummid":"([0-9a-zA-Z]+)"'], detail_info_page, 'album mid', default=None) if albummid: thumbnail_url = 'http://i.gtimg.cn/music/photo/mid_album_500/%s/%s/%s.jpg' \ % (albummid[-2:-1], albummid[-1], albummid) guid = self.m_r_get_ruin() vkey = self._download_json( 'http://base.music.qq.com/fcgi-bin/fcg_musicexpress.fcg?json=3&guid=%s' % guid, mid, note='Retrieve vkey', errnote='Unable to get vkey', transform_source=strip_jsonp)['key'] formats = [] for format_id, details in self._FORMATS.items(): formats.append({ 'url': 'http://cc.stream.qqmusic.qq.com/%s%s.%s?vkey=%s&guid=%s&fromtag=0' % (details['prefix'], mid, details['ext'], vkey, guid), 'format': format_id, 'format_id': format_id, 'preference': details['preference'], 'abr': details.get('abr'), }) self._check_formats(formats, mid) self._sort_formats(formats) actual_lrc_lyrics = ''.join( line + '\n' for line in re.findall( r'(?m)^(\[[0-9]{2}:[0-9]{2}(?:\.[0-9]{2,})?\][^\n]*|\[[^\]]*\])', lrc_content)) info_dict = { 'id': mid, 'formats': formats, 'title': song_name, 'release_date': publish_time, 'creator': singer, 'description': lrc_content, 'thumbnail': thumbnail_url } if actual_lrc_lyrics: info_dict['subtitles'] = { 'origin': [{ 'ext': 'lrc', 'data': actual_lrc_lyrics, }] } return info_dict class QQPlaylistBaseIE(InfoExtractor): @staticmethod def qq_static_url(category, mid): return 'http://y.qq.com/y/static/%s/%s/%s/%s.html' % (category, mid[-2], mid[-1], mid) def get_singer_all_songs(self, singmid, num): return self._download_webpage( r'https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg', singmid, query={ 'format': 'json', 'inCharset': 'utf8', 'outCharset': 'utf-8', 'platform': 'yqq', 'needNewCode': 0, 'singermid': singmid, 'order': 'listen', 'begin': 0, 'num': num, 'songstatus': 1, }) def get_entries_from_page(self, singmid): entries = [] default_num = 1 json_text = self.get_singer_all_songs(singmid, default_num) json_obj_all_songs = self._parse_json(json_text, singmid) if json_obj_all_songs['code'] == 0: total = json_obj_all_songs['data']['total'] json_text = self.get_singer_all_songs(singmid, total) json_obj_all_songs = self._parse_json(json_text, singmid) for item in json_obj_all_songs['data']['list']: if item['musicData'].get('songmid') is not None: songmid = item['musicData']['songmid'] entries.append(self.url_result( r'https://y.qq.com/n/yqq/song/%s.html' % songmid, 'QQMusic', songmid)) return entries class QQMusicSingerIE(QQPlaylistBaseIE): IE_NAME = 'qqmusic:singer' IE_DESC = 'QQ音乐 - 歌手' _VALID_URL = r'https?://y\.qq\.com/n/yqq/singer/(?P<id>[0-9A-Za-z]+)\.html' _TEST = { 'url': 'https://y.qq.com/n/yqq/singer/001BLpXF2DyJe2.html', 'info_dict': { 'id': '001BLpXF2DyJe2', 'title': '林俊杰', 'description': 'md5:870ec08f7d8547c29c93010899103751', }, 'playlist_mincount': 12, } def _real_extract(self, url): mid = self._match_id(url) entries = self.get_entries_from_page(mid) singer_page = self._download_webpage(url, mid, 'Download singer page') singer_name = self._html_search_regex( r"singername\s*:\s*'(.*?)'", singer_page, 'singer name', default=None) singer_desc = None if mid: singer_desc_page = self._download_xml( 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_singer_desc.fcg', mid, 'Donwload singer description XML', query={'utf8': 1, 'outCharset': 'utf-8', 'format': 'xml', 'singermid': mid}, headers={'Referer': 'https://y.qq.com/n/yqq/singer/'}) singer_desc = singer_desc_page.find('./data/info/desc').text return self.playlist_result(entries, mid, singer_name, singer_desc) class QQMusicAlbumIE(QQPlaylistBaseIE): IE_NAME = 'qqmusic:album' IE_DESC = 'QQ音乐 - 专辑' _VALID_URL = r'https?://y\.qq\.com/n/yqq/album/(?P<id>[0-9A-Za-z]+)\.html' _TESTS = [{ 'url': 'https://y.qq.com/n/yqq/album/000gXCTb2AhRR1.html', 'info_dict': { 'id': '000gXCTb2AhRR1', 'title': '我们都是这样长大的', 'description': 'md5:179c5dce203a5931970d306aa9607ea6', }, 'playlist_count': 4, }, { 'url': 'https://y.qq.com/n/yqq/album/002Y5a3b3AlCu3.html', 'info_dict': { 'id': '002Y5a3b3AlCu3', 'title': '그리고...', 'description': 'md5:a48823755615508a95080e81b51ba729', }, 'playlist_count': 8, }] def _real_extract(self, url): mid = self._match_id(url) album = self._download_json( 'http://i.y.qq.com/v8/fcg-bin/fcg_v8_album_info_cp.fcg?albummid=%s&format=json' % mid, mid, 'Download album page')['data'] entries = [ self.url_result( 'https://y.qq.com/n/yqq/song/' + song['songmid'] + '.html', 'QQMusic', song['songmid'] ) for song in album['list'] ] album_name = album.get('name') album_detail = album.get('desc') if album_detail is not None: album_detail = album_detail.strip() return self.playlist_result(entries, mid, album_name, album_detail) class QQMusicToplistIE(QQPlaylistBaseIE): IE_NAME = 'qqmusic:toplist' IE_DESC = 'QQ音乐 - 排行榜' _VALID_URL = r'https?://y\.qq\.com/n/yqq/toplist/(?P<id>[0-9]+)\.html' _TESTS = [{ 'url': 'https://y.qq.com/n/yqq/toplist/123.html', 'info_dict': { 'id': '123', 'title': '美国iTunes榜', 'description': 'md5:89db2335fdbb10678dee2d43fe9aba08', }, 'playlist_count': 100, }, { 'url': 'https://y.qq.com/n/yqq/toplist/3.html', 'info_dict': { 'id': '3', 'title': '巅峰榜·欧美', 'description': 'md5:5a600d42c01696b26b71f8c4d43407da', }, 'playlist_count': 100, }, { 'url': 'https://y.qq.com/n/yqq/toplist/106.html', 'info_dict': { 'id': '106', 'title': '韩国Mnet榜', 'description': 'md5:cb84b325215e1d21708c615cac82a6e7', }, 'playlist_count': 50, }] def _real_extract(self, url): list_id = self._match_id(url) toplist_json = self._download_json( 'http://i.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg', list_id, note='Download toplist page', query={'type': 'toplist', 'topid': list_id, 'format': 'json'}) entries = [self.url_result( 'https://y.qq.com/n/yqq/song/' + song['data']['songmid'] + '.html', 'QQMusic', song['data']['songmid']) for song in toplist_json['songlist']] topinfo = toplist_json.get('topinfo', {}) list_name = topinfo.get('ListName') list_description = topinfo.get('info') return self.playlist_result(entries, list_id, list_name, list_description) class QQMusicPlaylistIE(QQPlaylistBaseIE): IE_NAME = 'qqmusic:playlist' IE_DESC = 'QQ音乐 - 歌单' _VALID_URL = r'https?://y\.qq\.com/n/yqq/playlist/(?P<id>[0-9]+)\.html' _TESTS = [{ 'url': 'http://y.qq.com/n/yqq/playlist/3462654915.html', 'info_dict': { 'id': '3462654915', 'title': '韩国5月新歌精选下旬', 'description': 'md5:d2c9d758a96b9888cf4fe82f603121d4', }, 'playlist_count': 40, 'skip': 'playlist gone', }, { 'url': 'https://y.qq.com/n/yqq/playlist/1374105607.html', 'info_dict': { 'id': '1374105607', 'title': '易入人心的华语民谣', 'description': '民谣的歌曲易于传唱、、歌词朗朗伤口、旋律简单温馨。属于那种才入耳孔。却上心头的感觉。没有太多的复杂情绪。简单而直接地表达乐者的情绪,就是这样的简单才易入人心。', }, 'playlist_count': 20, }] def _real_extract(self, url): list_id = self._match_id(url) list_json = self._download_json( 'http://i.y.qq.com/qzone-music/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg', list_id, 'Download list page', query={'type': 1, 'json': 1, 'utf8': 1, 'onlysong': 0, 'disstid': list_id}, transform_source=strip_jsonp) if not len(list_json.get('cdlist', [])): if list_json.get('code'): raise ExtractorError( 'QQ Music said: error %d in fetching playlist info' % list_json['code'], expected=True) raise ExtractorError('Unable to get playlist info') cdlist = list_json['cdlist'][0] entries = [self.url_result( 'https://y.qq.com/n/yqq/song/' + song['songmid'] + '.html', 'QQMusic', song['songmid']) for song in cdlist['songlist']] list_name = cdlist.get('dissname') list_description = clean_html(unescapeHTML(cdlist.get('desc'))) return self.playlist_result(entries, list_id, list_name, list_description)
unlicense
bboyfeiyu/AndEngine
src/org/andengine/opengl/util/criteria/GLExtensionsGLCriteria.java
1631
package org.andengine.opengl.util.criteria; import org.andengine.opengl.util.GLState; import org.andengine.util.adt.data.operator.StringOperator; /** * (c) Zynga 2011 * * @author Nicolas Gramlich <ngramlich@zynga.com> * @since 21:02:01 - 10.10.2011 */ public class GLExtensionsGLCriteria extends StringGLCriteria { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public GLExtensionsGLCriteria(final StringOperator pStringOperator, final String pGLExtensions) { super(pStringOperator, pGLExtensions); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected String getActualCriteria(final GLState pGLState) { return pGLState.getExtensions(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
apache-2.0
samphilipd/rails
activesupport/test/autoloading_fixtures/should_not_be_required.rb
26
ShouldNotBeAutoloaded = 0
mit